Files
dtf-system/app/proof.py
Cauê Faleiros b027bb5013
Some checks failed
Build and deploy / Validate source (push) Successful in 16s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
fix: Prova OK approves every part of a film, and "Gerar de novo" names the new files with a version (#114, #128, #130)
The proof's approval took the print file's first upload as the final, so the
other parts of a film in parts never reached Arte conferida or the hot folder
and were downloaded by hand. It now approves every part, and adds the missing
ones to a first part already approved. A one-off migration completes the
open orders still before Imprimindo. Generated again, the files are named
DTF-130-v2-item-1-p2.png, as Marcus asked, so the FlexiPRINT queue and the
Hoson list never take them for the first ones.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 12:25:23 -03:00

157 lines
8.1 KiB
Python

"""The print proof (Dropstar, 2026-10-21).
An order above 10 m prints a proof before the rest, checked by the print room
without stopping the order. Dropstar's current rule: up to 15 cm, from
the part with the thinnest lines, a piece of each different artwork, at most
three proofs per order, never billed. On an order above 10 m the customer
may also ask for a proof at checkout (below 10 m there is none, Dropstar
2026-10-28): that order waits for them, marked "Aguardando contato", until
they approve the photo sent by WhatsApp. Either way the room
marks "Prova OK" once the proof is checked, and without it the order does not
reach Finalizado.
"""
from decimal import Decimal
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.')
def billed_metres(snapshot):
return sum((Decimal(str(item.get('billed_metres') or 0)) for item in snapshot.get('items') or []), Decimal(0))
def needs_proof(snapshot):
"""Whether the order prints a proof first: asked for, or above 10 m."""
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
# ---- The proof card (Dropstar's third round, 2026-10-30 and 2026-11-03) -----
#
# An order with a proof becomes a parent and a child. The child, the card
# "Prova", is an order of its own (orders.parent_id) with a pre-built proof
# sheet of up to 15 cm per contraction class, and follows the normal flow up
# to Revisão. The parent waits outside the queue, "Aguardando prova". On the
# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and
# the parent enters the queue; or Prova reprovada, with its reason, and the
# parent goes back to Arte recebida and the child closes. The child is no
# sale: it is not in Tiny, Números, the customer's account or their e-mails.
PROOF_SHEET_CM = Decimal('15')
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
MAX_PROOFS = 3
PROVIDER = 'prova'
def proof_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}')
def create_child(c, parent):
"""The parent's proof card, in Arte recebida, its proof sheets queued to be
generated. Returns it, or None when the order needs no proof."""
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
return None
from .printjobs import queue
# A class has one proof. When several items share it, use the one with the
# finest measured line; no metre or product value is sold on this card.
classes = {}
for index, item in enumerate(parent['snapshot']['items']):
kind = item.get('stroke_class') or 'C3'
width = item.get('stroke_px') or 10000
if kind not in classes or width < classes[kind][0]:
classes[kind] = (width, index, item)
selected = [classes[kind] for kind in ('C1', 'C2', 'C3') if kind in classes][:MAX_PROOFS]
proof_items = [{**item, 'billed_metres': '0', 'total_cents': 0, 'unit_cents': 0,
'proof_parent_item_index': index} for _, index, item in selected]
freight = {**parent['snapshot'].get('freight', {}), 'total_cents': 0}
snapshot = {**parent['snapshot'], 'items': proof_items, 'total_cents': 0,
'freight': freight, 'proof_of': parent['number']}
child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone()
queue(c, child['id'], len(snapshot['items']))
return child
def open_child(c, parent_id):
"""The parent's proof card still waiting for its answer, if any."""
return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone()
def waiting(c, order):
"""Whether the order waits for its proof: it has a proof card without an OK."""
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
def manual_source_needed(c, order):
"""A proof child cannot decode an original; prepare the full parent PNG first."""
if order.get('parent_id') or order['state'] != 'rec':
return False
child = open_child(c, order['id'])
return bool(child and c.execute('''SELECT 1 FROM dtf_local.print_files
WHERE order_id=%s AND status='manual' LIMIT 1''', (child['id'],)).fetchone())
def require_unlocked(c, order):
"""A parent cannot enter production or have its final changed before the proof answer."""
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
ORDER BY p.item_index''', (parent['id'],)).fetchall()
for row in generated:
# Every part of a film in parts, not only its first: the others
# never reached the folders (#114, #128, #130).
parts = [r['upload_id'] for r in c.execute('''SELECT upload_id FROM dtf_local.print_parts
WHERE order_id=%s AND item_index=%s ORDER BY part''', (parent['id'], row['item_index'])).fetchall()]
parts = parts or [row['upload_id']]
active = {r['upload_id'] for r in c.execute('''SELECT upload_id FROM dtf_local.order_files
WHERE order_id=%s AND item_index=%s AND kind='final' AND active''',
(parent['id'], row['item_index'])).fetchall()}
# A final someone prepared or approved stays as it is.
if active and not active <= set(parts):
continue
for upload_id in parts:
if upload_id not in active:
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'], 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