feat: the pickup receipt in Recibos/ and "Retirado" on the card (Dropstar's third round, item 14)
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s

A pickup order reaching Finalizado has its receipt due: a PDF for the
80 mm roll with the order number large at the top, the customer and
CPF/CNPJ, each product and its metres, the amount and how it was paid,
the date issued, and the "Retirado em" and "Assinatura" lines
(app/receipt.py). The Kanban's folder saves it in Recibos/, where the
counter's print queue sends it to the Bematech. One computer claims each
receipt on the server before writing it, so it is never printed twice,
and gives it back if it could not save it. Orders sent by carrier have
none.

"Retirado" on a pickup in Finalizado records when and who handed it
over, with an optional photo of the signed receipt (kept 30 days). Anyone
but the seller may mark it (new "deliver" capability); the order panel
also opens the receipt to print it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-29 18:39:17 -03:00
parent a5417d200e
commit d962865944
8 changed files with 378 additions and 14 deletions

View File

@@ -28,16 +28,18 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
def final_status(uid: UUID, user=Depends(operator)):
return upload_status(uid,session_id=operator_identity(user))
# The parts of an upload its operator started: a final (produce) or the
# photo of a signed pickup receipt (deliver, which includes produce).
@router.post('/api/operator/uploads/{uid}/parts/{number}')
def final_part(uid: UUID, number: int, user=Depends(can('produce'))):
def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
return part_url(uid,number,session_id=operator_identity(user))
@router.post('/api/operator/uploads/{uid}/complete')
def final_complete(uid: UUID, user=Depends(can('produce'))):
def final_complete(uid: UUID, user=Depends(can('deliver'))):
return complete_upload(uid,session_id=operator_identity(user))
@router.delete('/api/operator/uploads/{uid}')
def final_cancel(uid: UUID, user=Depends(can('produce'))):
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
return cancel_upload(uid,session_id=operator_identity(user))
@router.get('/api/operator/orders/{oid}/files')

View File

@@ -15,12 +15,13 @@ from pydantic import Field
from ..core import db
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import file_prefix, queue as queue_print_files
from .. import cnpj, machines, mail, payments, proof, quote_review
from .. import cnpj, machines, mail, payments, proof, quote_review, receipt
from .. import tiny
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, storage, upload_row)
from .uploads import begin_upload
from ..scanning import require_clean
router = APIRouter()
@@ -694,6 +695,105 @@ def proof_ok(uid: UUID, user=Depends(can('print'))):
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."""
@@ -775,7 +875,11 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
(uid,row['state'],body.state,user,body.reason,back))
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
# 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=NULL,
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
WHERE id=%s RETURNING *''', (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'}
@@ -1244,8 +1348,14 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print')))
files = named_files(rows)
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
(body.held,)).fetchall() if body.held else []
# The pickup receipts no computer saved yet (item 14), due since the
# folders were chosen: one that was off catches up, like the files.
due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL
AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s)
ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else []
return {'files': files,
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}}
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held},
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due]}
@router.get('/api/operator/uploads/{uid}/download')

View File

@@ -137,6 +137,10 @@ CAPABILITIES = {
'authorize': {'superadmin', 'admin'},
'users': {'superadmin', 'admin'},
'integrations': {'superadmin'},
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
# but the seller, who only views (D-30). It includes everyone who produces,
# so an operator upload (artwork.py) takes it for its parts.
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of

137
app/receipt.py Normal file
View File

@@ -0,0 +1,137 @@
"""The pickup receipt (Dropstar's third round, item 14, 2026-10-29).
A PDF for the counter's 80 mm thermal roll: the order number large at the
top, the customer and their CPF or CNPJ, each product and its metres, the
amount and how it was paid, when it was issued, and blank lines for the
date of pickup and the signature. Only for orders picked up in Franca: one
sent by a carrier has none. The Kanban's folder saves it in Recibos/, and the
counter's print queue sends it to the Bematech.
"""
import io
import unicodedata
from datetime import datetime
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
from .printjobs import LOCAL, file_prefix
MM = 72 / 25.4
WIDTH = 80 * MM
MARGIN = 4 * MM
ROOM = WIDTH - 2 * MARGIN
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
# Helvetica's widths for what the tables in printfile.py leave out.
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
def code(order):
"""DTF-123: the order as the Kanban, the files and Tiny name it."""
return file_prefix(order['number'], 0).rsplit('-item-', 1)[0]
def is_pickup(snapshot):
return ((snapshot or {}).get('freight') or {}).get('service') == 'pickup'
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
def document(value):
digits = ''.join(ch for ch in str(value or '') if ch.isdigit())
if len(digits) == 14:
return 'CNPJ', f'{digits[:2]}.{digits[2:5]}.{digits[5:8]}/{digits[8:12]}-{digits[12:]}'
if len(digits) == 11:
return 'CPF', f'{digits[:3]}.{digits[3:6]}.{digits[6:9]}-{digits[9:]}'
return 'CPF/CNPJ', str(value or '')
def width(text, bold=False):
"""The width of `text` in Helvetica at size 1: an accented letter is as
wide as its letter."""
table = _HELVETICA_BOLD if bold else _HELVETICA
total = 0
for ch in text:
base = unicodedata.normalize('NFD', ch)[0]
total += table.get(ch) or table.get(base) or EXTRA.get(ch) or 600
return total / 1000
def wrap(text, size, bold=False):
"""The text in lines that fit the roll, broken between words."""
lines, line = [], ''
for word in str(text).split():
attempt = f'{line} {word}' if line else word
if line and width(attempt, bold) * size > ROOM:
lines.append(line)
line = word
else:
line = attempt
return lines + [line] if line else lines or ['']
def literal(text):
raw = text.encode('cp1252', 'replace')
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
def lines(order, paid_with, issued):
"""What the receipt says, top to bottom: (text, size, bold, space before)."""
snapshot = order['snapshot']
customer = snapshot.get('customer') or {}
kind, number = document(customer.get('cnpj'))
name = code(order)
# The number as large as the roll takes, up to 34 pt.
big = min(34, int(ROOM / width(name, True)))
out = [('DROPSTAR · Recibo de retirada', 9, True, 0), (name, big, True, 4)]
if paid_with == 'teste':
out.append(('PEDIDO DE TESTE', 10, True, 2))
out.append(('Cliente', 7.5, False, 10))
out += [(part, 10, True, 1) for part in wrap(customer.get('name') or customer.get('mail') or '', 10, True)]
out += [(kind, 7.5, False, 6), (number, 10, False, 1)]
out.append(('Produto', 7.5, False, 10))
for item in snapshot.get('items') or []:
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)]
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
('Retirado em ____/____/________', 10, False, 22),
('Assinatura ______________________', 10, False, 26)]
return out
def render(order, paid_with, issued=None):
"""The receipt's PDF bytes, 80 mm wide and as long as what it says."""
rows = lines(order, paid_with, issued or datetime.now(LOCAL))
height = MARGIN * 2 + sum(size * 1.2 + space for _, size, _, space in rows)
y = height - MARGIN
commands = [b'0 g\n']
for text, size, bold, space in rows:
y -= space + size
commands.append(b'BT /%s %s Tf %s %s Td %s Tj ET\n' % (b'F1' if bold else b'F2', serialize(size),
serialize(MARGIN), serialize(y), literal(text)))
y -= size * 0.2
out = io.BytesIO()
pdf = PdfWriter(out)
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
pages = pdf.alloc()
fonts = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
'Encoding': Name('WinAnsiEncoding')} for key, font in FONTS.items()}
box = [0, 0, WIDTH, height]
page = pdf.obj({'Type': Name('Page'), 'Parent': pages, 'MediaBox': box, 'Resources': {'Font': fonts},
'Contents': content})
pdf.obj({'Type': Name('Pages'), 'Kids': [page], 'Count': 1}, pages)
root = pdf.obj({'Type': Name('Catalog'), 'Pages': pages})
info = pdf.obj({'Title': f'Recibo {code(order)}',
'Producer': 'DTF System'})
pdf.finish(root, info)
return out.getvalue()
def file_name(order):
"""Recibo-DTF-123.pdf"""
return f'Recibo-{code(order)}.pdf'

View File

@@ -401,3 +401,16 @@ CREATE TABLE IF NOT EXISTS dtf_local.reworks (
authorized boolean, decided_by text, decided_at timestamptz, decline_reason text
);
CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id);
-- The pickup receipt (Dropstar's third round, item 14, 2026-10-29): due when
-- an order to be picked up reaches Finalizado; one computer's folder claims
-- it and saves the PDF in Recibos/, where the counter's print queue sends it
-- to the Bematech. Claimed once, so it is never printed twice.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_due_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text;
-- "Retirado": when, who handed it over and, optionally, a photo of the
-- signed receipt. Finalizado means ready; this means delivered.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL;