From 449b45b520ec76340d9980d8f113dc2469f29a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 25 Nov 2026 09:40:13 -0300 Subject: [PATCH] fix: the print file is written over twice as fast, and a file finished after Prova OK queues its order (#81) #81's 91,5 m took 6 hours to generate. The PNG writer ran Pillow's row filters and then deflate at level 6; no filter at level 1 gives the same size in under half the time, for the file and the viewer's strips alike (1 m: 34 s -> 13 s). Its Prova OK came while the file was still being generated, so the order stayed in Arte recebida. The approval now also runs when the file finishes. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/api/operator/common.py | 15 +------------- app/api/operator/orders.py | 32 +++--------------------------- app/finals.py | 14 +++++++++++++ app/printjobs.py | 6 ++++++ app/printpng.py | 31 ++++++----------------------- app/printtiles.py | 7 ++++++- app/proof.py | 40 ++++++++++++++++++++++++++++++++++++++ tests/print_file_test.py | 35 +++++++++++++++++++++++++++++++++ 8 files changed, 111 insertions(+), 69 deletions(-) create mode 100644 app/finals.py diff --git a/app/api/operator/common.py b/app/api/operator/common.py index 4fa00f5..eb1708f 100644 --- a/app/api/operator/common.py +++ b/app/api/operator/common.py @@ -5,6 +5,7 @@ from fastapi import APIRouter, HTTPException from ... import cnpj from ...core import db +from ...finals import FINAL_OK, TREATED # noqa: F401 (the board, files and stats use them) router = APIRouter() @@ -40,20 +41,6 @@ def company_names(c, *groups): for rows in groups for row in rows]) -# An item's final counts while its file is still there and scanned clean: the -# same rule that lets an order into the print queue. -FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'""" -# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the -# customer's own artwork. It is neither the file the system generated from -# their art, nor one of their originals, nor a correction they sent. `f` is -# the final in dtf_local.order_files, `o` its order. -TREATED = """f.kind='final' - AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id) - AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text) - AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id - AND k.kind='correction')""" - - def person(column): """SQL: the team member's name for the e-mail in `column`, or the e-mail.""" return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})' diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index 2baade0..1307403 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -205,35 +205,9 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))): c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label)) if body.result == 'ok': - # A prova aprovada é a conferência do pai: os arquivos completos - # que o Prumo gerou entram como finais, e o pai segue para a fila. - # Itens que ainda dependem de preparo manual continuam em Arte - # recebida, com o botão de final disponível. - if parent['state'] == 'rec' and not needs_designer(parent['snapshot']): - generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p - WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f - WHERE f.order_id=p.order_id AND f.item_index=p.item_index - AND f.kind='final' AND f.active) - ORDER BY p.item_index''', (parent['id'],)).fetchall() - for row in generated: - c.execute('''INSERT INTO dtf_local.order_files - (id,order_id,upload_id,item_index,kind,note,created_by) - VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''', - (uuid4(), parent['id'], row['upload_id'], row['item_index'], - f'Aprovado pela prova do #{card["number"]}')) - treatment_clause = f'AND {TREATED}' if needs_designer(parent['snapshot']) else '' - ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f - JOIN dtf_local.orders o ON o.id=f.order_id - JOIN dtf_local.uploads u ON u.id=f.upload_id - WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} - {treatment_clause} LIMIT 1''', (parent['id'], i)).fetchone() - for i in range(len(parent['snapshot']['items']))) - c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(), - state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id'])) - if ready: - c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) - VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user)) + c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, + updated_at=now() WHERE id=%s''', (user, parent['id'])) + proof.approve_parent(c, parent, user) elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']: # Back to Arte recebida with the reason; its final is approved again. c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],)) diff --git a/app/finals.py b/app/finals.py new file mode 100644 index 0000000..0bfa4c6 --- /dev/null +++ b/app/finals.py @@ -0,0 +1,14 @@ +"""Which of an order's finals count: shared by the board, the proof and the worker.""" + +# An item's final counts while its file is still there and scanned clean: the +# same rule that lets an order into the print queue. +FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'""" +# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the +# customer's own artwork. It is neither the file the system generated from +# their art, nor one of their originals, nor a correction they sent. `f` is +# the final in dtf_local.order_files, `o` its order. +TREATED = """f.kind='final' + AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id) + AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text) + AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id + AND k.kind='correction')""" diff --git a/app/printjobs.py b/app/printjobs.py index 2d1d9c6..af1f57f 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -39,6 +39,7 @@ from .core.auth import audit from .core.db import connect from .printfile import Unsupported from .printpng import part_cuts, render +from . import proof from .proof import PROOF_SHEET_CM from .tiny import purchase_order @@ -297,6 +298,11 @@ def render_one(storage): (id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''', (uuid4(), job['order_id'], stored[0][0], job['item_index'])) + elif not job['parent_id']: + # A Prova OK given while this file was still being generated. + order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (job['order_id'],)).fetchone() + if order['proof_ok_at']: + proof.approve_parent(c, order, 'Prumo') audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored)) return True diff --git a/app/printpng.py b/app/printpng.py index 0818e3c..1d86360 100644 --- a/app/printpng.py +++ b/app/printpng.py @@ -68,8 +68,9 @@ class PngWriter: def __init__(self, fp, width, height): self.fp, self.width, self.height = fp, width, height self.rows = 0 - self.previous = None # the last row written, as an image - self.z = zlib.compressobj(6) + # Level 1 and no row filter: the same size as Pillow's filters at + # level 6, in under half the time. #81's 91,5 m took 6 hours (2026-11-25). + self.z = zlib.compressobj(1) self.pending = [] fp.write(b'\x89PNG\r\n\x1a\n') _chunk(fp, b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0)) @@ -83,18 +84,9 @@ class PngWriter: rows = image.height if self.rows + rows > self.height: raise ValueError('more rows than the file has') - # The previous row on top, so each row's filter refers to the real row - # above it; that first filtered row is dropped. - lead = 1 if self.previous is not None else 0 - framed = Image.new('RGBA', (self.width, rows + lead)) - if lead: - framed.paste(self.previous, (0, 0)) - framed.paste(image, (0, lead)) - encoded = io.BytesIO() - framed.save(encoded, 'PNG', compress_level=0) - filtered = zlib.decompress(_idat(encoded.getvalue())) - self._write(filtered[lead * (1 + 4 * self.width):]) - self.previous = image.crop((0, rows - 1, self.width, rows)) + raw, stride = image.tobytes(), 4 * self.width + # Each row behind its filter byte, 0 (none). + self._write(b''.join(b'\x00' + raw[i * stride:(i + 1) * stride] for i in range(rows))) self.rows += rows def _write(self, data): @@ -117,17 +109,6 @@ class PngWriter: _chunk(self.fp, b'IEND', b'') -def _idat(png): - """The concatenated IDAT data of an in-memory PNG.""" - data, at = [], 8 - while at < len(png): - size, kind = struct.unpack('>I4s', png[at:at + 8]) - if kind == b'IDAT': - data.append(png[at + 8:at + 8 + size]) - at += 12 + size - return b''.join(data) - - # ---- Reading ---------------------------------------------------------------- class PngRows: diff --git a/app/printtiles.py b/app/printtiles.py index 508c67e..699c134 100644 --- a/app/printtiles.py +++ b/app/printtiles.py @@ -78,8 +78,13 @@ class Pyramid: self._feed(level + 1, small) def _strip(self, level, image): + # The print file's own writer, the fast one (imported here: printpng + # imports this module). + from .printpng import PngWriter out = io.BytesIO() - image.save(out, 'PNG', compress_level=1) + writer = PngWriter(out, image.width, image.height) + writer.band(image) + writer.close() self.emit(level, self.count[level], out.getvalue()) self.count[level] += 1 diff --git a/app/proof.py b/app/proof.py index d3bb6be..e6ceff5 100644 --- a/app/proof.py +++ b/app/proof.py @@ -16,6 +16,9 @@ from uuid import NAMESPACE_URL, uuid4, uuid5 from psycopg.types.json import Jsonb from fastapi import HTTPException +from .cart_pricing import needs_designer +from .finals import FINAL_OK, TREATED + PROOF_ABOVE_METRES = Decimal('10') CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp ' 'e espere o aceite.') @@ -103,3 +106,40 @@ def require_unlocked(c, order): if waiting(c, order): child = open_child(c, order['id']) raise HTTPException(409, f'Aguardando prova do #{child["number"]}: responda no card da prova.') + + +def approve_parent(c, parent, operator): + """Prova OK is the parent's check: the full files the Prumo generated + become its finals, and with every item's final the parent enters the + queue. Items that still need a manual final stay in Arte recebida. Runs at + the answer, and again when a file finishes after it: #81's 91,5 m was + still being generated at its Prova OK and stayed behind (2026-11-24). + Returns whether the parent entered the queue.""" + card = c.execute('''SELECT number FROM dtf_local.orders WHERE parent_id=%s AND proof_result='ok' + AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent['id'],)).fetchone() + if parent['state'] != 'rec' or parent['cancelled_at'] or not card: + return False + designer = needs_designer(parent['snapshot']) + if not designer: + generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p + WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f + WHERE f.order_id=p.order_id AND f.item_index=p.item_index AND f.kind='final' AND f.active) + ORDER BY p.item_index''', (parent['id'],)).fetchall() + for row in generated: + c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) + VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''', + (uuid4(), parent['id'], row['upload_id'], row['item_index'], + f'Aprovado pela prova do #{card["number"]}')) + treatment_clause = f'AND {TREATED}' if designer else '' + ready = all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f + JOIN dtf_local.orders o ON o.id=f.order_id + JOIN dtf_local.uploads u ON u.id=f.upload_id + WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} {treatment_clause} LIMIT 1''', + (parent['id'], i)).fetchone() for i in range(len(parent['snapshot']['items']))) + if ready: + c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now() + WHERE id=%s''', (parent['id'],)) + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], operator)) + return ready diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 62cb148..dd3b4a8 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -396,6 +396,41 @@ def run(): assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it') + # Prova OK while the parent's file is still being generated (#81, 91,5 m, + # 2026-11-24): the parent waits in Arte recebida and enters the queue on + # its own once the file is ready. + readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-LATE.png') + parent = paid_order(client, loose_item(readable, copies=1)) + with db.connect() as c: + c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s", + (parent['id'],)) + card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True) + wait_print(client, parent['id'], 'ready') + wait_print(client, card['id'], 'ready') + with db.connect() as c: + # The parent's file back to "being generated", held by a claim no worker owns. + c.execute('''UPDATE dtf_local.print_files SET status='rendering', upload_id=NULL, finished_at=NULL, + claimed_at=now(), deadline_at=now()+interval '1 hour', claim_token=%s WHERE order_id=%s''', + (str(uuid4()), parent['id'])) + c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],)) + client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True) + mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id']) + assert mine['state'] == 'rec' and mine['proof_ok_at'] and not mine['final_items'], mine + with db.connect() as c: + c.execute("UPDATE dtf_local.print_files SET status='pending', claim_token=NULL WHERE order_id=%s", + (parent['id'],)) + wait_print(client, parent['id'], 'ready') + deadline = time.monotonic() + 30 + while (mine := next(o for o in client.call('/operator/board', operator=True)['orders'] + if o['id'] == parent['id']))['state'] != 'tra' and time.monotonic() < deadline: + time.sleep(1) + assert mine['state'] == 'tra' and mine['final_items'] == [0], mine + with db.connect() as c: + moved = c.execute('''SELECT operator,reason FROM dtf_local.movements + WHERE order_id=%s AND to_state='tra' ORDER BY id DESC LIMIT 1''', (parent['id'],)).fetchone() + assert (moved['operator'], moved['reason']) == ('Prumo', 'Prova OK'), moved + print('PASS: a file finished after Prova OK becomes the final and queues the order') + # A CDR cannot be decoded by the worker. The designer prepares the full # parent PNG, then the worker automatically cuts the child's proof from it. manual_source = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='MANUAL-PROOF.cdr')