Files
dtf-system/web/kanban-label.js
Cauê Faleiros 223bd61798 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>
2026-11-11 11:32:27 -03:00

148 lines
5.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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())]] : [])
]
});
}