Files
dtf-system/app/api/operator/orders.py
Cauê Faleiros f5df5b96e4 refactor: app/api/operator.py split by area into a package
A pure move: the 48 Kanban routes, their code and comments are unchanged,
grouped in session, board, quotes, orders, rework, integrations, stats
and files, with shared helpers in common. The fast CI check now compiles
the package's files too (app/**/*.py does not reach a third level without
globstar).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:11:19 -03:00

588 lines
36 KiB
Python

"""Order actions: cancel and delete, machine, contraction, contact, proof,
receipt and pickup, queue place, move, print-file regeneration."""
from datetime import datetime, timezone
from typing import Literal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import Field
from psycopg.types.json import Jsonb
from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews
from ...core import db
from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator
from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart
from ...payments import release_files
from ...printjobs import queue as queue_print_files
from ...runtime import BACK, STATES, TRANSITIONS, enqueue, operator_identity, upload_row
from ...scanning import require_clean
from ..uploads import begin_upload
from .common import FINAL_OK, TREATED
router = APIRouter()
@router.post('/api/operator/orders/{uid}/delete')
def delete_order(uid: UUID, user=Depends(can('manage'))):
"""Deletes a test order, or a paid order already cancelled, with its
history and files' records. A paid order in progress must be cancelled
first, with its reason. A test order's quote is unpaid again; a cancelled
one's is discarded, so it neither returns to Cotações nor can be paid twice.
The payment itself stays recorded, and the audit log keeps who deleted what."""
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
test = payments.is_test(row)
if not test and not row.get('cancelled_at'):
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
# Its files leave storage too: the finals, corrections and generated PDFs,
# and the customer's originals unless the quote can still be paid (a test
# order's). The worker deletes them within a minute.
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL
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=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:
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
(user, row['quote_id']))
freed = release_files(c, candidates)
audit('order_deleted', order=row['number'], test=test, operator=user,
reason=row.get('cancel_reason') or '', files_released=freed)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
"""A paid order leaves the board but keeps its payment and history. Nothing
is refunded here (that is done at the provider); Tiny is told, so the
order is cancelled there too while it was not invoiced (app/tiny.py)."""
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING *''',
(user, body.note, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
hotfolder.stop(c, uid)
if payments.in_tiny(row):
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()
enqueue(c, f'{uid}:cancelled:tiny', 'tiny',
{'order_id': str(uid), 'number': row['number'], 'event': 'cancelled', 'reason': body.note,
'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')})
audit('order_cancelled', order=row['number'], operator=user)
return {'ok': True}
class MachineChoice(StrictModel):
machine_id: UUID | None = None
@router.post('/api/operator/orders/{uid}/machine')
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
"""Exceptional manual choice before printing; the operator's pull is final."""
if request.state.operator['role'] == 'operador':
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
with db.connect() as c:
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not current:
raise HTTPException(404, 'Pedido não encontrado.')
proof.require_unlocked(c, current)
if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'):
raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.')
if body.machine_id:
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
if machines.product_family(current) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders
WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']:
raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.')
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
if current['parent_id']:
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
(body.machine_id, body.machine_id is not None, current['parent_id']))
elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'):
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
(body.machine_id, body.machine_id is not None, linked['id']))
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/contraction')
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's
measure comes prefilled, and whoever prepares the art may change it until
the order prints. Both stay: the measure in the snapshot, the choice here."""
with db.connect() as c:
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
(uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
proof.require_unlocked(c, row)
if body.item_index >= len(row['snapshot']['items']):
raise HTTPException(422, 'Item não encontrado no pedido.')
# Printing, the class still changes while the item's files wait to go
# into the hot folder: the class is its folder (item 10).
written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s
AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone()
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written:
raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.')
chosen = dict(row['contraction'] or {})
key = str(body.item_index)
if body.value is None:
chosen.pop(key, None)
else:
chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()}
c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid))
audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user)
return {'ok': True, 'contraction': chosen}
class ContactWait(StrictModel):
waiting: bool
note: str = Field(default='', max_length=500)
@router.post('/api/operator/orders/{uid}/contact')
def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
"""Mark an order as waiting for a word with the customer, with what has to
be agreed, or clear the mark once that is done. The stage does not change
and the customer is not told."""
note = ' '.join(body.note.split())
if body.waiting and len(note) < 3:
raise HTTPException(422, 'Escreva o que precisa ser combinado com o cliente.')
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET contact_since=CASE WHEN %s THEN now() END,
contact_by=CASE WHEN %s THEN %s END, contact_note=CASE WHEN %s THEN %s END
WHERE id=%s AND cancelled_at IS NULL RETURNING number''',
(body.waiting, body.waiting, user, body.waiting, note, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
# The wait's history, for the time figures that leave it out (D-38).
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', (uid,))
if body.waiting:
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (uid,))
audit('order_contact_waiting' if body.waiting else 'order_contact_done', order=row['number'], operator=user)
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':
# 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 parent['snapshot'].get('treatment'):
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 parent['snapshot'].get('treatment') 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))
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,
machine_id=NULL,machine_chosen=false,
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))
# The proof answer is the contact with the customer: the old
# "Aguardando contato" mark has done its job either way (0.1).
c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL
WHERE id=%s''', (parent['id'],))
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL',
(parent['id'],))
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.')
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'))):
"""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:
raise HTTPException(404, 'Pedido não encontrado.')
audit('order_proof_ok', order=row['number'], operator=user)
return {'ok': True, 'version': row['version']}
def paid_with(c, order):
"""How the order was paid, for its receipt: pix, card, cash, credit, or
'teste' for an operator's test order."""
paid = order.get('payment') or {}
if paid.get('provider') == 'teste':
return 'teste'
if paid.get('provider') == payments.MANUAL_PROVIDER:
return paid.get('method')
row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone()
return row and row['method']
@router.get('/api/operator/orders/{uid}/receipt')
def pickup_receipt(uid: UUID, user=Depends(operator)):
"""The pickup receipt's PDF (item 14), for the folder to save or someone
to print again."""
with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if not receipt.is_pickup(order['snapshot']):
raise HTTPException(409, 'Só pedido de retirada tem recibo.')
body = receipt.render(order, paid_with(c, order))
return Response(body, media_type='application/pdf',
headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'})
@router.post('/api/operator/orders/{uid}/receipt/claim')
def claim_receipt(uid: UUID, user=Depends(can('print'))):
"""One computer's folder takes the receipt to save: once, so the counter's
queue never prints it twice."""
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s
WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL
RETURNING number''', (user, uid)).fetchone()
if not row:
raise HTTPException(409, 'Este recibo já foi salvo.')
audit('pickup_receipt_saved', order=row['number'], operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/receipt/release')
def release_receipt(uid: UUID, user=Depends(can('print'))):
"""The folder could not save the receipt it took: another computer may."""
with db.connect() as c:
c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL
WHERE id=%s AND receipt_saved_by=%s''', (uid, user))
return {'ok': True}
def pickup_order(c, uid, lock=False):
"""An order in Finalizado to be picked up, or why it cannot be marked."""
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']):
raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.')
if order['picked_up_at']:
raise HTTPException(409, 'Este pedido já foi marcado como retirado.')
return order
@router.post('/api/operator/orders/{uid}/pickup-uploads')
def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))):
"""The photo of the signed receipt, sent before marking the order."""
with db.connect() as c:
pickup_order(c, uid)
return begin_upload(body, session_id=operator_identity(user))
class PickedUp(StrictModel):
photo: UUID | None = None
PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif')
@router.post('/api/operator/orders/{uid}/picked-up')
def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))):
""""Retirado": when and who handed the order over, and the photo of the
signed receipt when there is one (item 14). Finalizado means ready; this
closes the cycle. The photo is kept 30 days, as the order's files are."""
with db.connect() as c:
order = pickup_order(c, uid, lock=True)
if body.photo:
photo = upload_row(c, body.photo, operator_identity(user), lock=True)
if not photo['complete']:
raise HTTPException(409, 'Espere a foto terminar de enviar.')
if not photo['name'].lower().endswith(PHOTO_TYPES):
raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).')
require_clean(photo)
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,))
row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s
WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone()
audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo))
return {'ok': True, 'picked_up_at': row['picked_up_at']}
class QueuePlace(StrictModel):
"""Where a dragged card lands: between two orders of its column, either
of them absent at the top or the bottom."""
after: UUID | None = None
before: UUID | None = None
QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))'
@router.post('/api/operator/orders/{uid}/queue')
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(operator)):
"""An order's place in its column: by default its payment time; dragged,
halfway between the orders it was dropped between. It neither changes the
order's stage nor counts as activity (the stalled clock keeps running)."""
if not body.after and not body.before:
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
with db.connect() as c:
row = c.execute('SELECT id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if not may_reorder(request.state.operator['role'], row['state']):
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
mine = request.state.operator['machine']
if (request.state.operator['role'] == 'operador' and row['state'] != 'tra'
and (not mine or str(row['machine_id'] or '') != mine['id'])):
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
keys = {}
for side in ('after', 'before'):
other = getattr(body, side)
if other:
near = c.execute(f'SELECT state, {QUEUE_KEY} AS key FROM dtf_local.orders WHERE id=%s', (other,)).fetchone()
if not near or near['state'] != row['state']:
raise HTTPException(409, 'Os pedidos mudaram de etapa. Clique em Atualizar.')
keys[side] = float(near['key'])
if 'after' in keys and 'before' in keys:
key = (keys['after'] + keys['before']) / 2
elif 'after' in keys:
key = keys['after'] + 60
else:
key = keys['before'] - 60
c.execute('UPDATE dtf_local.orders SET queue_key=%s WHERE id=%s', (key, uid))
audit('order_queue_moved', order=str(uid), operator=user)
return {'ok': True, 'queue_key': key}
@router.post('/api/operator/orders/{uid}/move')
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
if request.state.operator['role'] not in MOVERS:
raise HTTPException(403, 'Seu perfil não permite esta ação.')
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
if body.version != row['version']:
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
if row.get('cancelled_at'):
raise HTTPException(409, 'Pedido cancelado.')
proof.require_unlocked(c, row)
if body.state == row['state']:
return row
back = BACK.get(row['state']) == body.state
if body.state not in TRANSITIONS[row['state']] and not back:
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
if not may_move(request.state.operator['role'], row['state'], body.state, back):
raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back
else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.")
if body.state == 'cor' and not body.reason.strip():
raise HTTPException(422, 'Informe o motivo da correção.')
if back and not body.reason.strip():
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
# The machine of this session takes a card when it is pulled. A proof
# and its parent must keep the same physical machine.
account = request.state.operator
session_machine = account['machine']
pulling = row['state'] == 'tra' and body.state == 'imp'
if account['role'] == 'operador':
if not session_machine:
raise HTTPException(409, 'Escolha a máquina em que você está.')
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
if pulling:
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
if not chosen:
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
if account['role'] == 'operador' and str(chosen) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
if not target or not target['active']:
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
if machines.product_family(row) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
# The machine's sheet speaks between one file and the next, never in
# the middle: a blocking alert stops this card here (app/machine_log.py).
blocking = [alert for alert in machine_log.alerts(c, chosen) if alert['blocking']]
if blocking:
raise HTTPException(409, 'Antes do próximo arquivo: ' + blocking[0]['text'])
linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s
AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
if linked and linked['machine_id'] and chosen != linked['machine_id']:
raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.')
row['machine_id'] = chosen
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid))
if row['parent_id']:
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
(chosen, row['parent_id']))
# Arte conferida is the queue: what enters it has its final files approved.
if body.state in ('tra','imp'):
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
if row['snapshot'].get('treatment') and not row['parent_id']:
treated = c.execute(f'''SELECT DISTINCT f.item_index 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 {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.')
# 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.')
# 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.')
# Above 1 m the review photo is the evidence the sheet was checked; a
# proof card is no sale and skips this (app/reviews.py).
if (body.state == 'fin' and not back and not row.get('parent_id')
and reviews.required(row['snapshot']) and not reviews.has_photo(c, uid)):
raise HTTPException(409, 'Pedido acima de 1 m: tire a foto da revisão 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,))
# Who moved it, and on which machine: the one it goes to print on, or
# else the mover's.
machine_name = (session_machine or {}).get('name')
if body.state == 'imp' and row['machine_id']:
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
(row['machine_id'],)).fetchone() or {}).get('name')
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
# Pulled to Imprimindo, its files go to its machine's hot folder; out
# of it, what Flexi did not take leaves (item 10).
if row['state'] == 'imp':
hotfolder.stop(c, uid)
if body.state == 'imp':
hotfolder.start(c, uid)
# A pickup reaching Finalizado has its receipt due (item 14), once.
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(),
queue_key=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END,
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone()
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
if body.state in events and not back and payments.in_tiny(row):
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction
# is a new request, so it keeps one message per movement.
once = body.state in ('tra','fin')
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
'customer_path': f'/portal.html?order={uid}'}
# Tiny needs the order (customer, pickup or delivery) and, once the
# sale reached it, its id, to set the situação without a search.
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()
tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny'
enqueue(c, key, 'tiny', tiny)
return changed
@router.post('/api/operator/orders/{uid}/print-files')
def regenerate(uid: UUID, user=Depends(can('produce'))):
"""Queue generation again for items that failed or went to manual preparation,
and for orders paid before the generator existed."""
with db.connect() as c:
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if row['state'] not in ('rec','tra'):
raise HTTPException(409, 'Print files are generated only before the order is queued')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
raise HTTPException(409, 'A customer correction replaced the original artwork; prepare the final file by hand')
if row['parent_id']:
manual = c.execute("SELECT item_index FROM dtf_local.print_files WHERE order_id=%s AND status='manual'",
(uid,)).fetchall()
for stuck in manual:
original_index = row['snapshot']['items'][stuck['item_index']]['proof_parent_item_index']
prepared = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE order_id=%s
AND item_index=%s AND kind='final' AND active LIMIT 1''',
(row['parent_id'], original_index)).fetchone()
if not prepared:
raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.')
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
audit('print_file_requeued', order=str(uid), operator=user)
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()