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:
Cauê Faleiros
2026-11-11 11:32:27 -03:00
parent e6197d6e40
commit 223bd61798
16 changed files with 593 additions and 12 deletions

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

@@ -241,4 +241,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.
@@ -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');