feat: the 10x15 label at Finalizado (Marcus 10/11, point 10)
When an order reaches Finalizado, the Kanban on the computer that opted in (Integrações > Etiqueta 10x15) prints a 10x15 label rendered by the server: the Tiny order number in large type (DTF-<n> when there is none), customer, DTF · N folhas · X m, the delivery line, date and time, the Revisor and a QR with the number. One automatic print per order (label_prints, claimed once); Revisor, Expedição, Gestão and the administrators can reprint. Chrome with --kiosk-printing prints without the dialog. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,7 @@ includes and the names other modules imported from the old single file.
|
||||
"""
|
||||
from fastapi import APIRouter
|
||||
|
||||
from . import board, common, files, integrations, orders, quotes, rework, session, stats
|
||||
from . import board, common, files, integrations, labels, orders, quotes, rework, session, stats
|
||||
from .integrations import tiny_callback
|
||||
from .stats import speed_figures
|
||||
|
||||
@@ -13,5 +13,5 @@ router = APIRouter()
|
||||
# The order the routes first appeared in the old file. Static paths that could
|
||||
# meet a parameterised one stay ahead of it: /orders/finished before any
|
||||
# /orders/{uid} GET.
|
||||
for module in (common, session, integrations, board, quotes, rework, orders, stats, files):
|
||||
for module in (common, session, integrations, board, quotes, rework, orders, labels, stats, files):
|
||||
router.include_router(module.router)
|
||||
|
||||
81
app/api/operator/labels.py
Normal file
81
app/api/operator/labels.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""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}
|
||||
@@ -164,6 +164,10 @@ CAPABILITIES = {
|
||||
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
|
||||
# who gets this one action although otherwise view-only (D-30).
|
||||
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
|
||||
# The 10x15 thermal label at Finalizado (Marcus, 2026-11-10, front 10): the
|
||||
# Revisor who releases the card, the Expedição profile that ships it, and
|
||||
# Gestão, which may stand in for either.
|
||||
'label': {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'},
|
||||
}
|
||||
|
||||
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
||||
|
||||
129
app/label.py
Normal file
129
app/label.py
Normal file
@@ -0,0 +1,129 @@
|
||||
"""The 10x15 cm thermal label printed at Finalizado (Fase 2, front 10).
|
||||
|
||||
Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a label on
|
||||
the Zebra ZD220: the Tiny order number, the customer, what the order is, pickup
|
||||
or shipping, when it was released and by which Revisor, and a QR with the Tiny
|
||||
order number only. The server renders the page so its content lives in one
|
||||
place. The QR is an inline SVG from segno; nothing is loaded from outside.
|
||||
|
||||
`label_fields` is pure, for the tests; `label_html` only adds the markup and the
|
||||
QR. Without a Tiny receipt the order keeps its own DTF-<number> as the number
|
||||
and in the QR (an Interno order never reaches Tiny).
|
||||
"""
|
||||
import html
|
||||
from datetime import timezone
|
||||
from decimal import Decimal
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
|
||||
SERVICE_NAMES = {'pac': 'Correios PAC', 'sedex': 'Correios SEDEX', 'jadlog': 'Jadlog'}
|
||||
|
||||
|
||||
def _escape(value):
|
||||
return html.escape(str(value if value is not None else ''), quote=True)
|
||||
|
||||
|
||||
def _metres(items):
|
||||
"""The order's billed metres with a comma and two decimals, as the card shows."""
|
||||
total = sum((Decimal(str(item.get('billed_metres') or item.get('metres') or 0))
|
||||
for item in items), Decimal(0))
|
||||
return f'{total:.2f}'.replace('.', ',')
|
||||
|
||||
|
||||
def _sheets(count):
|
||||
return f'{count} folha' if count == 1 else f'{count} folhas'
|
||||
|
||||
|
||||
def _delivery(snapshot):
|
||||
"""Retirada, Envio with the carrier the card shows, junto com a roupa, or Interno."""
|
||||
if snapshot.get('with_order'):
|
||||
return f"Junto com pedido de roupa nº {snapshot['with_order']}"
|
||||
if snapshot.get('kind') == 'interno':
|
||||
return 'Interno'
|
||||
if snapshot.get('destination'):
|
||||
freight = snapshot.get('freight') or {}
|
||||
service = freight.get('service')
|
||||
return 'Envio · ' + (freight.get('description') or SERVICE_NAMES.get(service) or service or 'Frete')
|
||||
return 'Retirada'
|
||||
|
||||
|
||||
def _customer(snapshot):
|
||||
customer = snapshot.get('customer') or {}
|
||||
destination = snapshot.get('destination') or {}
|
||||
return customer.get('name') or destination.get('recipient') or customer.get('mail') or '—'
|
||||
|
||||
|
||||
def _finished_at(value):
|
||||
if value is None:
|
||||
return ''
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')
|
||||
|
||||
|
||||
def label_fields(order, tiny_number, finished_at, revisor):
|
||||
"""What the label says, from one order and its Tiny sale receipt."""
|
||||
snapshot = order.get('snapshot') or {}
|
||||
items = snapshot.get('items') or []
|
||||
code = str(tiny_number) if tiny_number else f"DTF-{order['number']}"
|
||||
return {'code': code, 'customer': _customer(snapshot), 'sheets': len(items),
|
||||
'metres': _metres(items), 'delivery': _delivery(snapshot),
|
||||
'finished_at': _finished_at(finished_at), 'revisor': revisor or '—',
|
||||
'qr': code}
|
||||
|
||||
|
||||
def qr_svg(text):
|
||||
"""The QR as an inline SVG, dark on the label's white; segno is pure Python.
|
||||
|
||||
`omitsize` keeps a viewBox and drops the fixed width/height, so the CSS can
|
||||
print it at the label's 30 mm without the modules staying pixel-sized.
|
||||
"""
|
||||
import segno
|
||||
return segno.make_qr(text, error='m').svg_inline(border=1, omitsize=True)
|
||||
|
||||
|
||||
def label_html(fields):
|
||||
"""The printable page: 100 x 150 mm, black on white, no external resources."""
|
||||
code = _escape(fields['code'])
|
||||
# The number is as large as its length allows on the 88 mm of usable width.
|
||||
code_size = 22 if len(str(fields['code'])) <= 7 else 18 if len(str(fields['code'])) <= 9 else 15
|
||||
customer = _escape(fields['customer'])
|
||||
sheets = _escape(_sheets(int(fields['sheets'])))
|
||||
metres = _escape(fields['metres'])
|
||||
delivery = _escape(fields['delivery'])
|
||||
finished = _escape(fields['finished_at'])
|
||||
revisor = _escape(fields['revisor'])
|
||||
return f"""<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Etiqueta {code}</title>
|
||||
<style>
|
||||
@page {{ size: 100mm 150mm; margin: 0 }}
|
||||
* {{ box-sizing: border-box }}
|
||||
html, body {{ margin: 0; padding: 0; background: #fff; color: #000 }}
|
||||
body {{ font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif }}
|
||||
.label {{ width: 100mm; height: 150mm; padding: 6mm 6mm 5mm; display: flex;
|
||||
flex-direction: column; gap: 2mm; overflow: hidden }}
|
||||
.code {{ font-size: {code_size}mm; line-height: .95; font-weight: 800; letter-spacing: -.02em;
|
||||
white-space: nowrap; overflow: hidden }}
|
||||
.customer {{ font-size: 6mm; line-height: 1.15; font-weight: 700 }}
|
||||
.line {{ font-size: 4.6mm; line-height: 1.2 }}
|
||||
.foot {{ font-size: 3.6mm; line-height: 1.35; margin-top: 2mm }}
|
||||
.qr {{ margin-top: auto; display: flex; justify-content: center }}
|
||||
.qr svg {{ width: 30mm; height: 30mm; display: block }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="label">
|
||||
<div class="code">{code}</div>
|
||||
<div class="customer">{customer}</div>
|
||||
<div class="line">DTF · {sheets} · {metres} m</div>
|
||||
<div class="line">{delivery}</div>
|
||||
<div class="foot"><div>Finalizado em {finished}</div><div>Revisor: {revisor}</div></div>
|
||||
<div class="qr">{qr_svg(fields['qr'])}</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
12
app/migrations/202611111530_label-prints.sql
Normal file
12
app/migrations/202611111530_label-prints.sql
Normal file
@@ -0,0 +1,12 @@
|
||||
-- Front 10: the 10x15 cm label at Finalizado (Marcus, 2026-11-10). One 'auto'
|
||||
-- print per order, decided by the unique partial index, so two computers
|
||||
-- asking at once cannot both print it; a reprint is always another row.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.label_prints (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||
reason text NOT NULL CHECK (reason IN ('auto','reprint')),
|
||||
printed_by text NOT NULL,
|
||||
printed_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS label_prints_one_auto
|
||||
ON dtf_local.label_prints(order_id) WHERE reason='auto';
|
||||
Reference in New Issue
Block a user