feat: the proof card, a child order the seller answers (Dropstar, 30/10 and 03/11)
Some checks failed
Build and deploy / Validate source (push) Successful in 1m8s
Build and deploy / Integration suite on a real stack (push) Failing after 3m14s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Secret scan and release gate (push) Successful in 9s

An order with a proof (asked for at checkout, or above 10 m) gets a child
card "Prova": an order of its own (orders.parent_id), no sale, with the
film's first 30 cm as DTF-N-item-1-prova.png ("Prova do pedido DTF-N" in its
footer), which follows the flow up to Revisão like any card, hot folder
included. The order waits outside the queue, "Aguardando prova": it is not
pulled to Imprimindo, nor counted in the queue's places.

In Revisão the card is answered by the Vendedor, Gestão or the
Administrador (capability "proof"): Prova OK records who and when and puts
the order in Arte conferida when its finals are approved; Prova reprovada,
with its reason, sends the order back to Arte recebida, its final to be
approved again, and offers "Nova prova". Either way the card closes and
leaves the board. An order from before the cards keeps the old Prova OK.

The card is kept out of Tiny, e-mails, Números, the search, Finalizado and
the customer's account. Deleting an order takes its cards and their rows:
movements, order files and print files now cascade with their order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-03 20:39:52 -03:00
parent 8b7d9f0bdb
commit 5520081184
11 changed files with 311 additions and 27 deletions

View File

@@ -111,9 +111,10 @@ def board(user=Depends(operator)):
# card they can act on. Finished orders are terminal and only accumulate,
# so the board carries a recent window of them and reports the true total.
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s",
(BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n']
# A proof card that got its answer is done with (app/proof.py).
finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
@@ -238,8 +239,19 @@ def with_print_files(c, orders):
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
# Where a printing order's files are in its machine's hot folder (item 10).
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
# Each parent's latest proof card, and each card's parent (app/proof.py).
children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state,
proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
for order in orders:
order['hot'] = hot.get(order['id'])
child = children.get(order['id'])
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
parent = parents.get(order.get('parent_id'))
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
approved = [row for row in finals if row['order_id'] == order['id']]
@@ -271,7 +283,7 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N
"""Older finished orders, newest first, beyond the board's recent window."""
paged = cursor_pair(before_created_at, before_id)
with db.connect() as c:
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin'
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY created_at DESC,id DESC LIMIT %s''',
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
@@ -436,7 +448,8 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
params.append(code + '%')
quote_match, quote_params = customer_match('q.draft', q)
with db.connect() as c:
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql}
# Real orders: a proof card is found through its order (app/proof.py).
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL
ORDER BY created_at DESC LIMIT 8''', params).fetchall()
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
@@ -603,8 +616,10 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''',
(uid, uid, uid)).fetchall()}
candidates = produced - originals if test else produced | originals
# Its proof cards (app/proof.py) go with it.
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,))
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
if not test:
@@ -744,10 +759,78 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
return {'ok': True}
class ProofAnswer(StrictModel):
result: Literal['ok', 'rejected']
reason: str = Field(default='', max_length=500)
@router.post('/api/operator/orders/{uid}/proof-answer')
def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
"""The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK
puts its order in the queue; Prova reprovada, with its reason, sends the
order back to Arte recebida. Either way the card closes."""
reason = ' '.join(body.reason.split())
if body.result == 'rejected' and len(reason) < 3:
raise HTTPException(422, 'Diga por que a prova foi reprovada.')
with db.connect() as c:
card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not card or not card.get('parent_id'):
raise HTTPException(404, 'Card de prova não encontrado.')
if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev':
raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.')
parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone()
c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s,
proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''',
(body.result, user, reason or None, uid))
label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason
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':
# The order enters the queue: Arte conferida, if its finals are approved.
ready = parent['state'] == 'rec' and all(c.execute('''SELECT 1 FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active AND item_index=%s 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))
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'],))
c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL,
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,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/proof-card')
def new_proof_card(uid: UUID, user=Depends(can('produce'))):
"""A new proof card for an order whose proof was rejected, or that has
none yet (an order from before the cards)."""
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row or row.get('parent_id'):
raise HTTPException(404, 'Pedido não encontrado.')
if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid):
raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.')
child = proof.create_child(c, row)
if not child:
raise HTTPException(409, 'Este pedido não leva prova.')
machines.route(c)
audit('order_proof_card', order=row['number'], operator=user)
return {'ok': True, 'id': child['id'], 'number': child['number']}
@router.post('/api/operator/orders/{uid}/proof')
def proof_ok(uid: UUID, user=Depends(can('print'))):
"""The print room checked the proof: the order may reach Finalizado."""
"""An order from before the proof cards: the print room checked the
proof, and the order may reach Finalizado."""
with db.connect() as c:
if proof.open_child(c, uid):
raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.')
row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1
WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone()
if not row:
@@ -968,7 +1051,13 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
# Two at most per machine in Imprimindo (app/machines.py).
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
# A proof card ends with its answer, not in Finalizado; its order waits
# for that answer outside the queue (app/proof.py).
if row.get('parent_id') and body.state == 'fin':
raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.')
if body.state == 'imp' and proof.waiting(c, row):
raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.')
if body.state == 'fin' and not row.get('parent_id') and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
if body.state == 'cor':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
@@ -1124,7 +1213,8 @@ def thumbnail(uid: UUID, user=Depends(operator)):
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})
# Real work only: an operator's test order and a cancelled one are not production.
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'"
# A proof card (app/proof.py) is no sale either.
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL"
# Where orders come from (D-21), in the order Números lists them.
ORIGINS = ('site', 'dropflow', 'atendimento')
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"