"""The 10x15 thermal label at Finalizado (Fase 2, front 10; Marcus, 2026-11-10). The label page is rendered by the server; one computer prints it automatically (the first claim), and the Expedição profile or the Revisor may reprint it. """ from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Response from ... import label from ...core import db from ...core.auth import audit, can router = APIRouter() def _order(c, uid, columns='number,state,cancelled_at'): order = c.execute(f'SELECT {columns} FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() if not order: raise HTTPException(404, 'Pedido não encontrado.') return order def _tiny_number(c, uid): """The Tiny order number from the sale event's receipt, or None.""" row = c.execute("SELECT receipt->>'tiny_number' AS tiny_number FROM dtf_local.outbox WHERE event_key=%s", (f'{uid}:paid:tiny',)).fetchone() return row['tiny_number'] if row else None def _finished(c, uid): """When the card reached Finalizado and who released it, from the movements.""" row = c.execute('''SELECT m.created_at, COALESCE(NULLIF((SELECT o.name FROM dtf_local.operators o WHERE o.email=m.operator), ''), m.operator) AS revisor FROM dtf_local.movements m WHERE m.order_id=%s AND m.to_state='fin' AND NOT m.back ORDER BY m.created_at DESC, m.id DESC LIMIT 1''', (uid,)).fetchone() return (row['created_at'], row['revisor']) if row else (None, None) @router.get('/api/operator/orders/{uid}/label') def order_label(uid: UUID, user=Depends(can('label'))): """The printable label page (text/html), sized 100 x 150 mm.""" with db.connect() as c: order = _order(c, uid, 'number,state,cancelled_at,updated_at,snapshot') if order['cancelled_at'] or order['state'] != 'fin': raise HTTPException(409, 'A etiqueta é impressa em Finalizado.') tiny = _tiny_number(c, uid) finished, revisor = _finished(c, uid) fields = label.label_fields(order, tiny, finished or order['updated_at'], revisor) return Response(label.label_html(fields), media_type='text/html; charset=utf-8', headers={'Cache-Control': 'no-store'}) @router.post('/api/operator/orders/{uid}/label/claim') def claim_label(uid: UUID, user=Depends(can('label'))): """The first computer to ask prints the label; the unique partial index on the 'auto' row decides, so two computers at once cannot both print it.""" with db.connect() as c: order = _order(c, uid) if order['cancelled_at'] or order['state'] != 'fin': return {'print': False} row = c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by) VALUES(%s,'auto',%s) ON CONFLICT DO NOTHING RETURNING id''', (uid, user)).fetchone() if row: audit('label_printed', order=order['number'], reason='auto', operator=user) return {'print': bool(row)} @router.post('/api/operator/orders/{uid}/label/reprint') def reprint_label(uid: UUID, user=Depends(can('label'))): """A new label for an order in Finalizado, from any computer.""" with db.connect() as c: order = _order(c, uid) if order['cancelled_at'] or order['state'] != 'fin': raise HTTPException(409, 'A etiqueta é reimpressa em Finalizado.') c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by) VALUES(%s,'reprint',%s)''', (uid, user)) audit('label_printed', order=order['number'], reason='reprint', operator=user) return {'print': True}