fix: the print file is written over twice as fast, and a file finished after Prova OK queues its order (#81)
Some checks failed
Build and deploy / Validate source (push) Successful in 1m41s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled

#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) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-25 09:40:13 -03:00
parent a1fad7698a
commit 449b45b520
8 changed files with 111 additions and 69 deletions

View File

@@ -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})'

View File

@@ -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'],))

14
app/finals.py Normal file
View File

@@ -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')"""

View File

@@ -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

View File

@@ -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:

View File

@@ -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

View File

@@ -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