diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 4991f95..7c24b5b 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -27,6 +27,7 @@ jobs: tests.test_coupons \ tests.test_grade_rules \ tests.test_migrate \ + tests.test_label \ tests.test_secrets -v sh -n infra/lock_dependencies.sh @@ -84,7 +85,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 \ @@ -97,7 +98,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: | diff --git a/app/api/operator/__init__.py b/app/api/operator/__init__.py index 4fa08be..63e41fd 100644 --- a/app/api/operator/__init__.py +++ b/app/api/operator/__init__.py @@ -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) diff --git a/app/api/operator/labels.py b/app/api/operator/labels.py new file mode 100644 index 0000000..99c1fb2 --- /dev/null +++ b/app/api/operator/labels.py @@ -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} diff --git a/app/core/auth.py b/app/core/auth.py index de0a1ec..de30000 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -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 diff --git a/app/label.py b/app/label.py new file mode 100644 index 0000000..ea547b5 --- /dev/null +++ b/app/label.py @@ -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- 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""" + + + +Etiqueta {code} + + + +
+
{code}
+
{customer}
+
DTF · {sheets} · {metres} m
+
{delivery}
+
Finalizado em {finished}
Revisor: {revisor}
+
{qr_svg(fields['qr'])}
+
+ + +""" diff --git a/app/migrations/202611111530_label-prints.sql b/app/migrations/202611111530_label-prints.sql new file mode 100644 index 0000000..c12dcd9 --- /dev/null +++ b/app/migrations/202611111530_label-prints.sql @@ -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'; diff --git a/infra/requirements.lock b/infra/requirements.lock index a89136e..17d121c 100644 --- a/infra/requirements.lock +++ b/infra/requirements.lock @@ -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 diff --git a/infra/requirements.txt b/infra/requirements.txt index a528694..8bf92be 100644 --- a/infra/requirements.txt +++ b/infra/requirements.txt @@ -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 diff --git a/tests/label_test.py b/tests/label_test.py new file mode 100644 index 0000000..aeb2615 --- /dev/null +++ b/tests/label_test.py @@ -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 'Loja', 'mail': 'x@example.test'}), + None, FINISHED, None) + page = label_html(fields) + self.assertIn('<b>Loja</b>', page) + self.assertNotIn('Loja', page) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_moves.py b/tests/test_moves.py index f2cc637..af5e729 100644 --- a/tests/test_moves.py +++ b/tests/test_moves.py @@ -55,6 +55,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']) diff --git a/tests/users_test.py b/tests/users_test.py index dfc6ed2..a949ac1 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -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' diff --git a/web/kanban-label.js b/web/kanban-label.js new file mode 100644 index 0000000..08a5ebb --- /dev/null +++ b/web/kanban-label.js @@ -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())]] : []) + ] + }); +} diff --git a/web/kanban.html b/web/kanban.html index e0897f1..041e61d 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -241,4 +241,4 @@
- + diff --git a/web/kanban.js b/web/kanban.js index 92e51ba..900dea8 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -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. @@ -1626,6 +1627,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'); @@ -1919,6 +1926,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, @@ -2565,9 +2576,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'}; @@ -2582,7 +2593,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'); @@ -3316,7 +3328,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=[]}){ @@ -3565,6 +3577,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');