Merge front 10: the 10x15 label at Finalizado
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 5m35s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m7s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-11 11:48:40 -03:00
16 changed files with 593 additions and 12 deletions

View File

@@ -28,6 +28,7 @@ jobs:
tests.test_grade_rules \
tests.test_hotfolder \
tests.test_migrate \
tests.test_label \
tests.test_secrets -v
sh -n infra/lock_dependencies.sh
@@ -85,7 +86,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \
@@ -98,7 +99,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_worker_drain -v
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_worker_drain -v
- name: Runtime and retention regressions
run: |

View File

@@ -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)

View 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}

View File

@@ -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
View 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>
"""

View 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';

View File

@@ -616,6 +616,10 @@ s3transfer==0.13.1 \
--hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \
--hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf
# via boto3
segno==1.6.6 \
--hash=sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7 \
--hash=sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3
# via -r infra/requirements.txt
six==1.17.0 \
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81

View File

@@ -8,3 +8,4 @@ httpx==0.28.1
pillow==13.0.0
pikepdf==10.13.0.post1
pypdfium2==5.14.0
segno==1.6.6

99
tests/label_test.py Normal file
View File

@@ -0,0 +1,99 @@
"""The 10x15 thermal label at Finalizado (Fase 2, front 10).
Run inside the API container: python -m tests.label_test
"""
from urllib.error import HTTPError
from urllib.request import Request
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import BASE, Client, with_host
from tests.users_test import PASSWORD, order_fixture
def label_page(client, order_id, expected=200):
"""GET the label as the browser does; returns the HTML (or the error body)."""
request = Request(BASE + '/api/operator/orders/' + order_id + '/label', headers=with_host())
try:
with client.opener.open(request, timeout=30) as response:
assert response.status == expected, (response.status, expected)
assert response.headers.get_content_type() == 'text/html', response.headers
return response.read().decode()
except HTTPError as error:
if error.code != expected:
raise AssertionError((error.code, expected, error.read().decode())) from error
return error.read().decode()
def user(superadmin, tag, role, name):
email = f'etiqueta-{tag}-{role}@example.test'
superadmin.call('/operator/users',
{'name': name, 'email': email, 'role': role, 'password': PASSWORD}, operator=True)
client = Client()
client.call('/session')
client.call('/operator/login', {'email': email, 'password': PASSWORD})
return client
def run():
su = Client()
su.call('/session')
su.call('/operator/me', operator=True) # the default superadmin
tag = uuid4().hex[:6]
revisor_email = f'etiqueta-{tag}-revisor@example.test'
revisor = user(su, tag, 'revisor', 'Revisor Etiqueta')
designer = user(su, tag, 'designer', 'Designer Etiqueta')
expedicao = user(su, tag, 'expedicao', 'Expedição Etiqueta')
owner = uuid4()
with db.connect() as c:
_, order_id = order_fixture(c, owner, 'file', metres='2.5')
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['snapshot']
snapshot['customer']['name'] = 'Cliente Etiqueta'
snapshot['destination'] = {'recipient': 'Loja Etiqueta', 'street': 'Rua A', 'number': '10',
'complement': '', 'district': 'Centro', 'city': 'Franca',
'state': 'SP', 'postal_code': '14400000'}
snapshot['freight'] = {'service': 'jadlog', 'description': 'Jadlog .Package', 'total_cents': 1500}
c.execute("UPDATE dtf_local.orders SET snapshot=%s, state='fin' WHERE id=%s",
(Jsonb(snapshot), order_id))
c.execute("INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) "
"VALUES(%s,'rev','fin',%s,'')", (order_id, revisor_email))
number = c.execute('SELECT number FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['number']
oid = str(order_id)
# The first computer claims the automatic print; the second does not.
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': True}
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': False}
# A reprint always prints, on any computer.
assert su.call(f'/operator/orders/{oid}/label/reprint', {}, operator=True) == {'print': True}
# The page is the server's HTML: customer, what the order is, delivery, QR.
page = label_page(revisor, oid)
assert 'Cliente Etiqueta' in page, page
assert 'DTF · 1 folha · 2,50 m' in page, page
assert 'Envio · Jadlog .Package' in page, page
assert 'Revisor Etiqueta' in page, page
assert '<svg' in page, page
# No Tiny receipt: the order's own DTF number, also in the QR.
assert f'DTF-{number}' in page, page
# With the Tiny sale receipt, its number takes the big type and the QR.
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.outbox(event_key,provider,payload,receipt,delivered_at)
VALUES(%s,'tiny',%s,%s,now())''', (f'{oid}:paid:tiny', Jsonb({}),
Jsonb({'tiny_number': '98765'})))
page = label_page(revisor, oid)
assert '98765' in page, page
assert f'DTF-{number}' not in page, page
# Only the label profiles print it: the designer may not, Expedição may.
label_page(designer, oid, expected=403)
label_page(expedicao, oid)
print('PASS: the label page, one automatic print, reprint, Tiny number, designer refused '
'and Expedição allowed')
if __name__ == '__main__':
run()

View File

@@ -93,7 +93,7 @@ def run():
manager = signed_in(emails['gestao'])
designer = signed_in(emails['designer'])
me = shipping.call('/operator/me')
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'label', 'view'], me
read = shipping.call('/operator/stamp-sizes')['sizes']
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
# The designer does not assemble: no reading the table.

80
tests/test_label.py Normal file
View File

@@ -0,0 +1,80 @@
"""The 10x15 label's fields and page (Fase 2, front 10), without a database."""
import importlib.util
import unittest
from datetime import datetime, timezone
from app.label import label_fields, label_html
HAS_SEGNO = importlib.util.find_spec('segno') is not None
def order(**snapshot):
content = {'customer': {'name': 'Cliente Etiqueta', 'mail': 'cliente@example.test'},
'items': [{'billed_metres': '1.5'}, {'billed_metres': '1'}],
'destination': {'recipient': 'Loja Etiqueta'},
'freight': {'service': 'jadlog', 'description': 'Jadlog .Package'}}
content.update(snapshot)
return {'number': 42, 'snapshot': content}
FINISHED = datetime(2026, 11, 11, 17, 32, tzinfo=timezone.utc)
class LabelFieldsTest(unittest.TestCase):
def test_the_order_number_falls_back_to_dtf_when_tiny_did_not_answer(self):
fields = label_fields(order(), None, FINISHED, 'Revisor Etiqueta')
self.assertEqual(fields['code'], 'DTF-42')
self.assertEqual(fields['qr'], 'DTF-42')
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
self.assertEqual(fields['code'], '98765')
self.assertEqual(fields['qr'], '98765')
def test_customer_sheets_and_billed_metres(self):
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
self.assertEqual(fields['customer'], 'Cliente Etiqueta')
self.assertEqual(fields['sheets'], 2)
self.assertEqual(fields['metres'], '2,50')
self.assertEqual(fields['finished_at'], '11/11/2026 14:32')
self.assertEqual(fields['revisor'], 'Revisor Etiqueta')
def test_pickup_shipping_interno_and_junto_com_a_roupa(self):
pickup = order(destination=None, freight={'service': 'pickup'})
self.assertEqual(label_fields(pickup, None, FINISHED, None)['delivery'], 'Retirada')
self.assertEqual(label_fields(order(), None, FINISHED, None)['delivery'],
'Envio · Jadlog .Package')
self.assertEqual(label_fields(order(kind='interno'), None, FINISHED, None)['delivery'], 'Interno')
self.assertEqual(label_fields(order(with_order='4321'), None, FINISHED, None)['delivery'],
'Junto com pedido de roupa nº 4321')
# The internal customer's name is the one on the label.
self.assertEqual(label_fields(order(kind='interno', destination=None), None, FINISHED, None)['customer'],
'Cliente Etiqueta')
class LabelHtmlTest(unittest.TestCase):
@unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image')
def test_the_page_is_sized_for_the_10x15_label(self):
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
page = label_html(fields)
self.assertIn('@page { size: 100mm 150mm; margin: 0 }', page)
self.assertIn('98765', page)
self.assertIn('Cliente Etiqueta', page)
self.assertIn('DTF · 2 folhas · 2,50 m', page)
self.assertIn('Envio · Jadlog .Package', page)
self.assertIn('Finalizado em 11/11/2026 14:32', page)
self.assertIn('Revisor: Revisor Etiqueta', page)
self.assertIn('<svg', page)
# The viewBox lets the CSS print the QR at 30 mm; a fixed pixel width
# would leave the modules tiny.
self.assertIn('viewBox=', page)
@unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image')
def test_the_customer_name_is_escaped(self):
fields = label_fields(order(customer={'name': '<b>Loja</b>', 'mail': 'x@example.test'}),
None, FINISHED, None)
page = label_html(fields)
self.assertIn('&lt;b&gt;Loja&lt;/b&gt;', page)
self.assertNotIn('<b>Loja</b>', page)
if __name__ == '__main__':
unittest.main()

View File

@@ -56,6 +56,15 @@ class MovesTest(unittest.TestCase):
self.assertEqual(CAPABILITIES['assemble'],
{'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'})
def test_the_label_is_printed_by_these_profiles(self):
# Marcus, 2026-11-10: the Revisor who releases the card, Expedição and
# Gestão; the designer, the operator and the seller do not print it.
self.assertEqual(CAPABILITIES['label'],
{'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'})
for role in ROLES:
self.assertEqual(role in CAPABILITIES['label'],
role in ('superadmin', 'admin', 'gestao', 'revisor', 'expedicao'), role)
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp'])
self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor'])

View File

@@ -203,7 +203,7 @@ def run():
'password': PASSWORD})
reviewer = signed_in(emails['revisor'])
me = reviewer.call('/operator/me')
assert me['can'] == ['deliver', 'inspect', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
assert me['can'] == ['deliver', 'inspect', 'label', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
'reason': ''})['state'] == 'fin'

147
web/kanban-label.js Normal file
View File

@@ -0,0 +1,147 @@
/* Kanban DTF — the 10x15 cm label at Finalizado (Fase 2, front 10).
Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a Zebra
ZD220 label by itself. The server renders the page (app/label.py), so this
file only decides which computer prints it: the first to claim it prints it
once, and whoever may see labels can reprint. The browser opts in here, in
Integrações, and only orders that reach Finalizado after that moment are
printed automatically, never the whole history. */
const LABEL_SINCE = 'label-print-since';
const LABEL_ASKED = new Set(); // claimed from this browser in this session
const LABEL_BUSY = new Set(); // a claim in flight, so two loads do not repeat it
function labelSince() {
try {
const value = localStorage.getItem(LABEL_SINCE);
const date = value ? new Date(value) : null;
return date && !Number.isNaN(date.getTime()) ? date : null;
} catch (error) {
return null;
}
}
function labelSetSince(on) {
try {
if (on) localStorage.setItem(LABEL_SINCE, new Date().toISOString());
else localStorage.removeItem(LABEL_SINCE);
} catch (error) {
// A browser that cannot store it simply never prints automatically.
}
}
function labelEnabled() {
return !!labelSince();
}
// The label page is rendered by the server; this prints what it returns.
async function labelPrint(orderId) {
const response = await fetch('/api/operator/orders/' + encodeURIComponent(orderId) + '/label',
{credentials: 'same-origin', cache: 'no-store'});
if (!response.ok) throw new Error('Não foi possível abrir a etiqueta (' + response.status + ').');
const page = await response.text();
await new Promise((resolve, reject) => {
const frame = document.createElement('iframe');
frame.setAttribute('aria-hidden', 'true');
frame.tabIndex = -1;
frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:100mm;height:150mm;border:0';
let closed = false;
const done = () => {
if (closed) return;
closed = true;
frame.remove();
resolve();
};
frame.addEventListener('load', () => {
try {
const view = frame.contentWindow;
view.addEventListener('afterprint', done, {once: true});
// A browser that never fires afterprint still releases the frame.
setTimeout(done, 120000);
view.focus();
view.print();
} catch (error) {
done();
reject(error);
}
}, {once: true});
// The gateway adds X-Frame-Options: DENY and frame-ancestors 'none' to
// /api responses, so the label URL cannot be framed directly. The page is
// still the server's: it is fetched and written into a srcdoc iframe,
// which is not a framed navigation and inherits this page's policy.
frame.srcdoc = page;
document.body.append(frame);
});
}
function labelReprintButton(order, className = 'btn lg') {
if (!may('label') || order.state !== 'fin' || order.cancelled_at) return null;
const print = button('Reimprimir etiqueta', async () => {
try {
await api('/orders/' + order.id + '/label/reprint', {});
await labelPrint(order.id);
say('Etiqueta do pedido #' + order.number + ' enviada para a impressora.');
} catch (error) {
say(error.message, true);
}
}, className);
print.prepend(svgIcon(IC.printer, 'i m'));
return print;
}
// After every board load: claim the labels of the orders that reached
// Finalizado after this browser opted in. Only one computer gets print:true.
async function labelAfterLoad() {
if (!may('label') || !labelEnabled() || !board) return;
const since = labelSince();
for (const order of board.orders) {
if (order.state !== 'fin' || order.cancelled_at || !order.finished_at) continue;
if (new Date(order.finished_at) <= since) continue;
if (LABEL_ASKED.has(order.id) || LABEL_BUSY.has(order.id)) continue;
LABEL_BUSY.add(order.id);
try {
const answer = await api('/orders/' + order.id + '/label/claim', {});
LABEL_ASKED.add(order.id);
if (answer.print) {
try {
await labelPrint(order.id);
} catch (error) {
say('Etiqueta do pedido #' + order.number + ': ' + error.message, true);
}
}
} catch (error) {
// The claim did not answer: not marked, so the next board load retries it.
} finally {
LABEL_BUSY.delete(order.id);
}
}
}
// The Integrações row: the switch that makes this browser the label printer.
function labelIntegrationRow() {
if (!may('label')) return null;
const on = labelEnabled();
const input = node('input');
const toggle = checkbox('Esta tela imprime as etiquetas', input);
input.checked = on;
input.onchange = () => {
labelSetSince(input.checked);
say(input.checked
? 'Etiqueta ligada: os pedidos que chegarem em Finalizado daqui em diante serão impressos.'
: 'Etiqueta desligada nesta tela.');
renderIntegrations();
};
const since = labelSince();
return integration({
name: 'Etiqueta 10×15', state: on ? 'Ligada' : 'Desligada', tone: on ? 'ok' : 'off',
summary: on ? 'Esta tela imprime as etiquetas de pedidos que chegam em Finalizado.'
: 'Esta tela não imprime etiquetas.',
actions: [toggle],
details: [
node('p', 'A etiqueta é impressa uma vez, no primeiro computador que a pegar; os outros não a imprimem de novo. ' +
'O Revisor e a Expedição também podem reimprimir pelo card do pedido em Finalizado.'),
node('p', 'Para imprimir sem a janela de confirmação, abra o Chrome com --kiosk-printing e deixe a Zebra ZD220 como impressora padrão.'),
...(since ? [['Ligada desde', when(since.toISOString())]] : [])
]
});
}

View File

@@ -276,4 +276,4 @@
<div class="scrim" id="scrim"></div>
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
</div>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-label.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>

View File

@@ -60,7 +60,7 @@ const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order);
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'),
stats:()=>may('manage')||consults(),site:()=>may('manage'),
integrations:()=>may('manage')||may('print'),users:()=>may('users'),montar:()=>may('assemble')};
integrations:()=>may('manage')||may('print')||may('label'),users:()=>may('users'),montar:()=>may('assemble')};
function applyRole(){
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
@@ -647,6 +647,7 @@ async function load(quiet=false){
render();
askMachine();
syncFolder();
if(typeof labelAfterLoad==='function')labelAfterLoad();
}catch(e){
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
// Not being signed in yet is the normal start, not an error.
@@ -1632,6 +1633,12 @@ function nextBox(order){
// Pulling to a machine goes through the sheet's alerts first (front 1a).
const fn=to==='imp'?()=>pullTo(order,order.machine?.id||myMachine()?.id||null):()=>move(order,to);
const b=button(label||'Mover para '+board.states[to],fn,className);b.dataset.move=to;return b;};
// The 10x15 label at Finalizado: added here so a view-only Expedição sees it
// too (the read-only branch below skips the stage blocks).
if(st==='fin'&&typeof labelReprintButton==='function'){
const reprint=labelReprintButton(order);
if(reprint)more.push(reprint);
}
if(waitingProof(order)){
title='Aguardando prova do #'+order.proof_card.number;
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
@@ -1929,6 +1936,10 @@ function cardOpenAction(order){
const row=node('span',undefined,'card-open-row');row.append(action,review);
return row;
}
if(order.state==='fin'&&typeof labelReprintButton==='function'){
const reprint=labelReprintButton(order,'card-open');
if(reprint){const row=node('span',undefined,'card-open-row');row.append(action,reprint);return row;}
}
return action;
}
// "Revisar" (Fase 2, front 2): the sheet's photo or a video of up to 30 s,
@@ -2576,9 +2587,9 @@ const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
// What each profile is for, in a line (app/core/auth.py).
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa e libera para Finalizado.',
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa, libera para Finalizado e reimprime a etiqueta.',
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.',
expedicao:'Monta folhas no Kanban; só consulta o resto.'};
expedicao:'Monta folhas no Kanban e imprime a etiqueta; só consulta o resto.'};
// Who is on the system: used it in the last 15 minutes, signed in before,
// never, or switched off.
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
@@ -2593,7 +2604,8 @@ const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor',
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'],
['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'],
['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'],
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY']];
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY'],
['Imprimir a etiqueta 10×15','YYNNYNNY']];
let usersData=null;
async function loadUsers(){
usersData=await api('/users');
@@ -3331,7 +3343,7 @@ function tinyDetail(t){
// buttons) opens under "Detalhes", so every row keeps the same height. Which
// rows are open survives the page's automatic refresh.
const OPEN_INTEG=new Set();
const INTEG_ICONS={'Pastas dos pedidos':IC.folder,'Tiny':IC.box,'Mercado Pago':IC.card,'Frete':IC.truck,'E-mail':IC.mail,'Backup do banco':IC.database};
const INTEG_ICONS={'Pastas dos pedidos':IC.folder,'Etiqueta 10×15':IC.printer,'Tiny':IC.box,'Mercado Pago':IC.card,'Frete':IC.truck,'E-mail':IC.mail,'Backup do banco':IC.database};
const TONE_PILL={ok:'ok',warn:'warn',off:''};
function statePill(text,tone){const p=badge(text,TONE_PILL[tone]??tone);p.prepend(node('span',undefined,'dot'));return p;}
function integration({name,state,tone,summary,actions=[],details=[],extra=[]}){
@@ -3580,6 +3592,8 @@ const integRow=o=>may('integrations')?integration(o):integration({name:o.name,st
let mpCheck=null;
function renderIntegrations(){
const t=board.tiny||{};const rows=may('print')?[folderCard()]:[];
const labelRow=typeof labelIntegrationRow==='function'?labelIntegrationRow():null;
if(labelRow)rows.push(labelRow);
$('event-log').hidden=!may('integrations');
if(!may('manage')){$('integrations').replaceChildren(...rows);return;}
const act=(text,fn)=>button(text,fn,'btn');