diff --git a/app/printfile.py b/app/printfile.py index d098d16..4a3357b 100644 --- a/app/printfile.py +++ b/app/printfile.py @@ -396,10 +396,32 @@ def check_layout(item, sizes, vector=()): return lowest -def render(item, files, out, title): +# The footer (Dropstar, 2026-10-21): a 1,5 cm band after the last piece with one +# line of black text on no background, saying which order, item, date and length +# the sheet is, so a sheet cut off or dropped in the room is still known. The band +# is outside the billed length: the page grows by it and never covers artwork. +FOOTER_CM = Decimal('1.5') +FOOTER_PT = 18 +FOOTER_FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'} + + +def footer_commands(text): + """The footer's line, its first part (the brand) in bold, 0,5 cm from the left.""" + brand, _, rest = text.partition(' · ') + def literal(value): + raw = value.encode('cp1252', 'replace') + return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')' + x = 0.5 * PT_PER_CM + y = (float(FOOTER_CM) * PT_PER_CM - FOOTER_PT * 0.7) / 2 + return (b'q 0 g BT /F1 %d Tf %s %s Td %s Tj /F2 %d Tf %s Tj ET Q\n' + % (FOOTER_PT, serialize(x), serialize(y), literal(brand), FOOTER_PT, literal(' · ' + rest if rest else ''))) + + +def render(item, files, out, title, footer=None): """Write the PDF for one approved order item. - `files` maps each source index to (local path, original name). Returns the + `files` maps each source index to (local path, original name). With + `footer`, the page gets the footer band and that line in it. Returns the evidence the Kanban shows: page size, what was billed, and the lowest DPI. Raster sources are written by the streaming writer above. PDF sources are @@ -418,12 +440,13 @@ def render(item, files, out, title): lowest_dpi = check_layout(item, [source.size for source in sources], vector) width_pt = float(production['film_width_cm']) * PT_PER_CM - height_pt = float(production['height_cm']) * PT_PER_CM + page_cm = Decimal(str(production['height_cm'])) + (FOOTER_CM if footer else 0) + height_pt = float(page_cm) * PT_PER_CM unit = max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT)) first = tempfile.TemporaryFile() if vector else out try: - write_rasters(production, sources, first, title, width_pt, height_pt, unit) + write_rasters(production, sources, first, title, width_pt, height_pt, unit, footer) if vector: first.seek(0) add_vector_pages(production, sources, first, out, height_pt) @@ -435,6 +458,8 @@ def render(item, files, out, title): source.close() return {'film_width_cm': str(production['film_width_cm']), 'height_cm': str(production['height_cm']), + 'page_height_cm': str(page_cm), + 'footer': footer, 'billed_metres': str(item['billed_metres']), 'placements': len(production['placements']), 'sources': len(sources), @@ -443,7 +468,7 @@ def render(item, files, out, title): 'user_unit': unit} -def write_rasters(production, sources, out, title, width_pt, height_pt, unit): +def write_rasters(production, sources, out, title, width_pt, height_pt, unit, footer=None): pdf = PdfWriter(out) images = {index: source.embed(pdf) for index, source in enumerate(sources) if isinstance(source, SourceImage)} @@ -456,12 +481,16 @@ def write_rasters(production, sources, out, title, width_pt, height_pt, unit): matrix = placement_matrix(placement, height_pt) commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) + b' cm /Im%d Do Q\n' % placement['source_index']) + resources = {'XObject': {f'Im{index}': ref for index, ref in images.items()}} + if footer: + commands.append(footer_commands(footer)) + resources['Font'] = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font), + 'Encoding': Name('WinAnsiEncoding')} for key, font in FOOTER_FONTS.items()} content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands)) pages = pdf.alloc() page_box = [0, 0, width_pt / unit, height_pt / unit] page = {'Type': Name('Page'), 'Parent': pages, 'MediaBox': page_box, 'TrimBox': page_box, - 'Resources': {'XObject': {f'Im{index}': ref for index, ref in images.items()}}, - 'Contents': content} + 'Resources': resources, 'Contents': content} if unit > 1: page['UserUnit'] = unit page_ref = pdf.obj(page) diff --git a/app/printjobs.py b/app/printjobs.py index 09e1fb3..856fd29 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -21,6 +21,8 @@ import os import tempfile import time from datetime import timedelta +from decimal import Decimal +from zoneinfo import ZoneInfo from uuid import NAMESPACE_URL, UUID, uuid4, uuid5 from psycopg.types.json import Jsonb @@ -28,6 +30,9 @@ from psycopg.types.json import Jsonb from .core.auth import audit from .core.db import connect from .printfile import Unsupported, render +from .tiny import purchase_order + +LOCAL = ZoneInfo('America/Sao_Paulo') CLAIM_TIMEOUT = timedelta(minutes=15) MAX_ATTEMPTS = 3 @@ -55,7 +60,7 @@ def queue(c, order_id, items, only_missing=False): def claim(c): - return c.execute('''SELECT p.*, o.snapshot, o.number FROM dtf_local.print_files p + return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s) ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone() @@ -137,6 +142,17 @@ def whole_sheet(item, uploads): return row +def footer(job, item): + """The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 · + 21/10/2026 · 0,90 m. The order is named by its Kanban number, which Tiny + keeps as the purchase order; the length is the one billed.""" + count = len(job['snapshot']['items']) + day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y') + billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',') + return ' · '.join(('DROPSTAR', f'Pedido {purchase_order(job["number"])}', + f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m')) + + def produce(storage, job, item, uploads): """Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence).""" for upload_id in item['uploads']: @@ -156,7 +172,8 @@ def produce(storage, job, item, uploads): handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf') try: with os.fdopen(handle, 'wb') as out: - detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}') + detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}', + footer=footer(job, item)) except BaseException: os.unlink(output) raise diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 176a7be..566aa99 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -353,7 +353,11 @@ shape packing is used only when it saves 1 cm or more. A ready sheet with a residue (ink under 2 mm on both sides, measured in pixels from the ink map in web/site-sheet.js) or without transparency (under 1,5 % of transparent pixels; every JPG) cannot be paid for; the preview circles each dot. PDFs -over 150 MB and CDR/AI/PSD/TIFF are not checked. Waiting on +over 150 MB and CDR/AI/PSD/TIFF are not checked. The generated print PDF ends +in a 1,5 cm footer band below the layout, outside the billed length: "DROPSTAR +· Pedido DTF- · Item 1/2 · date · billed metres" in black +Helvetica (the logo waits for Dropstar's file). An original used whole as its +own print file (over 300 MB) has no footer. Waiting on Dropstar: the Tiny category/seller/tag conflict, residue and opaque background blocking, the print-file footer, the packing margins, the DTF terms, the manual-file value, the proof print, and mirroring. diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 75f458f..329a206 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -87,8 +87,10 @@ def run(): pdf = response.read() assert pdf.startswith(b'%PDF-') and pdf.rstrip().endswith(b'%%EOF') width, height = map(float, re.search(rb'/MediaBox \[0 0 ([\d.]+) ([\d.]+)\]', pdf).groups()) - assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 10 * PT_PER_CM) < 0.01, (width, height) - print('PASS: paid order generated a 57 x 10 cm print file with both copies') + # The layout's 10 cm and the 1,5 cm footer band, outside the billed length. + assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 11.5 * PT_PER_CM) < 0.01, (width, height) + assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail'] + print('PASS: paid order generated a 57 x 10 cm print file with both copies and its footer') # The automatic folder, downloading on arrival, gets the generated file # before anyone approves it; at the queue only, it does not. diff --git a/tests/test_printfile.py b/tests/test_printfile.py index 1e7b2e9..e4a460e 100644 --- a/tests/test_printfile.py +++ b/tests/test_printfile.py @@ -87,6 +87,30 @@ class PrintFileTests(unittest.TestCase): streams = re.findall(rb'/Filter /FlateDecode/Length \d+ 0 R>>\nstream\n(.*?)\nendstream', pdf, re.S) return zlib.decompress(streams[-1]) + def test_footer_band_is_added_below_the_layout(self): + # Dropstar, 2026-10-21: 1,5 cm after the last piece, black text, no fill. + path = self.save(quadrants(), 'a.png') + spec = item([placement(0, 0, 20, 10)], [source(20, 10)], 10) + out = io.BytesIO() + line = 'DROPSTAR · Pedido DTF-7 · Item 1/2 · 21/10/2026 · 1,00 m' + detail = render(spec, {0: (path, 'a.png')}, out, 'test', footer=line) + pdf = out.getvalue() + height = float(re.search(rb'/MediaBox \[0 0 [\d.]+ ([\d.]+)\]', pdf).group(1)) + self.assertAlmostEqual(height, 11.5 * PT_PER_CM, places=2) + self.assertEqual((detail['height_cm'], detail['page_height_cm'], detail['footer']), ('10', '11.5', line)) + content = self.content(pdf) + self.assertIn(b'/F1 18 Tf', content) + self.assertIn(b'(DROPSTAR) Tj', content) + self.assertIn(' · Pedido DTF-7 · Item 1/2 · 21/10/2026 · 1,00 m'.encode('cp1252'), content) + self.assertNotIn(b' re f', content) # no filled background + self.assertIn(b'/BaseFont /Helvetica-Bold', pdf) + # The artwork keeps its place from the top: the band is below it. + matrix = re.search(rb'q ([\d. -]+) cm /Im0 Do Q', content).group(1).split() + self.assertAlmostEqual(float(matrix[5]), 1.5 * PT_PER_CM, places=2) + # Without a footer, the page is the layout. + plain = io.BytesIO() + self.assertEqual(render(spec, {0: (path, 'a.png')}, plain, 'test')['page_height_cm'], '10') + def test_jpeg_bytes_are_embedded_unchanged(self): path = self.save(quadrants(), 'a.jpg', quality=90) pdf, _ = self.render(item([placement(0, 0, 20, 10)], [source(20, 10)], 10), [path])