Files
dtf-system/web/kanban-order.js
Cauê Faleiros ee772a43ff refactor: the production board and the order panel in files of their own
Plan 007e (Critical Corrections 7, last step; layout Phase D step 1):
web/kanban-board.js holds the board and the phone screens, and
web/kanban-order.js the order panel, its dialogs, the final files and
Abrir e conferir, moved verbatim from kanban.js (now 952 lines). The
browser test also walks the phone board. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 09:46:36 -03:00

1117 lines
72 KiB
JavaScript
Raw 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 order panel, its dialogs, the final files and Abrir e
conferir (fronts 2/7). Loaded after kanban.js, which defines $, api, node,
button, svgIcon, IC, badge, money, when, ago, metres, plural, say, may,
mayMove, mayAct, myMachine, board, ME, MODALS, load, render, dialog, modal,
formDialog, field, checkbox, dropField, iconButton, gradePill, itemPreview,
productName, sheetSize, buyer, cnpj, docKind, copyButton, freightWeight,
whatsappLink, download, downloadButton, FOLDER, STAGE_FOLDERS, FLOW, kv,
orderCode, fileCode, stateName, manifest, contractionRecord and cm. */
// ---- Order panel ---------------------------------------------------------
// The panel's tab stays while the same order is open.
let panelTab='order';
// A dialog sits over the order's panel when it is open, and over the page
// when it is not: opened from a card's face or the board, inside the closed
// drawer it would be invisible.
const dialogHost=()=>$('drawer').hidden?document.body:$('drawer');
function openPanel(id){if(id!==openOrder)panelTab='order';openOrder=id;const order=board.orders.find(o=>o.id===id);$('drawer').hidden=false;renderPanel(order);renderBoard();}
function closePanel(){
for(const m of [...MODALS])if(m.host===$('drawer'))m.close();
openOrder=null;$('drawer').hidden=true;$('panel').replaceChildren();if(board)renderBoard();
}
$('scrim').onclick=closePanel;
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&openOrder)closePanel();});
function layoutPreview(production){
const ns='http://www.w3.org/2000/svg', w=Number(production.film_width_cm), h=Math.max(1,Number(production.height_cm));
const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img');
svg.setAttribute('aria-label','Montagem: '+production.placements.length+' peças em '+w+' × '+h+' cm');
const film=document.createElementNS(ns,'rect');film.setAttribute('width',w);film.setAttribute('height',h);film.setAttribute('fill','#0F1113');svg.append(film);
const colors=['#2BB6D9','#E0508F','#E9C23A','#6FD19C','#FF8B2B','#A78BFA'];
for(const p of production.placements){const r=document.createElementNS(ns,'rect');
r.setAttribute('x',p.x_cm);r.setAttribute('y',p.y_cm);r.setAttribute('width',p.width_cm);r.setAttribute('height',p.length_cm);
r.setAttribute('fill',colors[p.source_index%colors.length]);r.setAttribute('fill-opacity','.55');svg.append(r);}
return svg;
}
function renderPanel(order){
const token=++openToken, panel=$('panel');
panel.dataset.order=order.id;$('drawer').dataset.order=order.id;
panel.setAttribute('aria-label','Pedido #'+order.number);
const s=order.snapshot, who=buyer(s);
// The head: who, where the order is, and what it is called.
const top=node('div',undefined,'dtop');
const name=node('span',who.title,'dname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;
const stage=node('span',undefined,'stage'+(order.cancelled_at?' bad':''));
stage.append(svgIcon(order.cancelled_at?IC.ban:GLYPH[order.state]||GLYPH.rec,'sg'+(order.state==='cor'||order.cancelled_at?' cor':'')),
order.cancelled_at?'Cancelado':stateName(order.state));
const tools=node('span',undefined,'dtools');
const more=moreMenu(order);if(more)tools.append(more);
tools.append(iconButton(IC.close,'Fechar',closePanel));
top.append(node('span','#'+order.number,'dnum'),name,stage,tools);
// What was paid and when, where it came from, and the codes: DTF-23 is the
// room's, in the file names, the footer and Tiny; the customer knows the other.
const sub=node('div',undefined,'dsub');
const paid=node('span');
// A proof card is no sale (app/proof.py): it says whose proof it is.
if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at));
else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at):
paidOutside(order)?' pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at));
const code=node('span',undefined,'chip');
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
sub.append(paid,node('span','Entrou pelo '+(ORIGINS[order.origin]||order.origin)),code,theirs);
if(s.coupon && !order.proof_parent)
sub.append(badge('Cupom '+s.coupon.code,'','Desconto de '+money(s.coupon.discount_cents)));
if(s.grade_flags?.aviso!=null && !order.proof_parent)
sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn',
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir'));
if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
if(s.items.some(i=>i.mode==='premium'))sub.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas');
const at=FLOW.indexOf(order.state);
for(const [i,state] of FLOW.entries()){const li=node('li',board.states[state]);
if(at>=0&&i<at)li.classList.add('done');if(i===at)li.classList.add('now');steps.append(li);}
if(order.state==='cor')steps.classList.add('paused');
const head=node('div',undefined,'dhead');head.append(top,sub,steps);
// The phone's head: back, the order and where it is, its menu.
const mhead=node('div',undefined,'mhead phone'),mt=node('span',undefined,'t');
mt.append(node('b','#'+order.number+' '+who.title),node('span',(order.cancelled_at?'Cancelado':stateName(order.state))+', '+money(s.total_cents)+(isTest(order)?' de teste':' pago')));
const phoneMore=moreMenu(order,'mic');
mhead.append(iconButton(IC.left,'Voltar',closePanel,'mic'),mt,...(phoneMore?[phoneMore]:[]));
const body=node('div',undefined,'dbody');
if(order.cancelled_at)body.append(cancelledNotice(order));
if(waitingContact(order))body.append(contactNotice(order,may('produce')));
const next=nextBox(order);if(next)body.append(next);
// Pedido, Arquivos and Histórico: one at a time.
const views={order:orderView(order),files:node('div',undefined,'tview'),history:node('div',undefined,'tview')};
views.files.append(node('p','Carregando…','lbl'));views.history.append(node('p','Carregando…','lbl'));
const tabs=node('div',undefined,'tabs');tabs.setAttribute('role','tablist');
for(const [key,label] of [['order','Pedido'],['files','Arquivos'],['history','Histórico']]){
const b=node('button',label);b.type='button';b.setAttribute('role','tab');b.dataset.ptab=key;
if(key==='files')b.append(node('span','','n'));
b.onclick=()=>{panelTab=key;paintTabs();};tabs.append(b);
}
const paintTabs=()=>{for(const b of tabs.children){const on=b.dataset.ptab===panelTab;b.classList.toggle('on',on);b.setAttribute('aria-selected',String(on));}
for(const [key,view] of Object.entries(views))view.hidden=key!==panelTab;};
paintTabs();
body.append(tabs,...Object.values(views));
// On the phone the order is one page; its files and history open as sheets.
let fileRows=null,historyRows=null;
const mbtns=node('div',undefined,'mbtns phone');
const zap=whatsappLink(s.customer.zap);
if(zap){const a=node('a','WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i m'));mbtns.append(a);}
const sheetOf=(title,fill)=>()=>{const box=node('div',undefined,'sbody pad');fill(box);
const m=sheet([sheetHead(title,()=>m.close()),box],{label:title});};
const files=node('button','Arquivos','btn');files.type='button';files.onclick=sheetOf('Arquivos',box=>fileRows?filesView(order,fileRows,box):box.append(node('p','Carregando…','lbl')));
const hist=node('button','Histórico','btn');hist.type='button';hist.onclick=sheetOf('Histórico',box=>historyRows?historyView(order,historyRows,box):box.append(node('p','Carregando…','lbl')));
mbtns.append(files,hist);body.append(mbtns);
// A re-render keeps where the body was scrolled.
const scrolled=panel.querySelector('.dbody')?.scrollTop||0;
panel.replaceChildren(mhead,head,body);body.scrollTop=scrolled;
api('/orders/'+order.id+'/files').then(rows=>{if(token!==openToken)return;fileRows=rows;filesView(order,rows,views.files);
tabs.querySelector('[data-ptab=files] .n').textContent=rows.length?String(rows.length):'';}).catch(e=>say(e.message,true));
api('/orders/'+order.id+'/history').then(rows=>{if(token===openToken){historyRows=rows;historyView(order,rows,views.history);}}).catch(e=>say(e.message,true));
}
// A phone sheet's title line with its close button.
function sheetHead(title,close){const h=node('div',undefined,'shead');h.append(node('b',title),iconButton(IC.close,'Fechar',close,'mic right'));return h;}
// The order's own menu: the rare things, some of them destructive.
function moreMenu(order,buttonClass='btn sq ghost'){
const items=[];
const item=(d,text,fn,className='menuitem')=>{const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem');
b.append(svgIcon(d,'i m'),text);b.onclick=async e=>{e.stopPropagation();menu.hidden=true;try{await fn();}catch(err){say(err.message,true);}};items.push(b);return b;};
const menu=node('div',undefined,'menu dmenu');menu.hidden=true;menu.setAttribute('role','menu');
if(!order.cancelled_at){
// Undo a mistaken move: one stage back, internal reason, no customer message.
const previous=board.back?.[order.state];
if(previous&&!waitingProof(order)&&mayMove(order.state,previous)&&mayAct(order))item(IC.back,'Voltar para '+board.states[previous],()=>backDialog(order,previous)).dataset.back=previous;
if(order.state!=='fin'&&!waitingContact(order)&&may('produce'))
item(IC.phone,'Aguardando contato',()=>contactDialog(order)).dataset.contact='';
if(!isTest(order)&&may('rework'))item(IC.rework,'Abrir retrabalho',()=>reworkForm(order));
if(isTest(order)&&may('manage'))item(IC.ban,'Excluir pedido de teste',async()=>{
if(!await ask('Excluir o pedido de teste #'+order.number+'?','Ele some do Kanban, com o histórico.','Excluir pedido',{tone:'red',host:$('drawer')}))return;
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();},'menuitem bad');
else if(!isTest(order)&&may('cancel'))item(IC.ban,'Cancelar pedido',()=>cancelDialog(order),'menuitem bad');
}
if(!items.length)return null;
// The destructive one apart, under a line.
const last=items.at(-1);if(last.classList.contains('bad')&&items.length>1)items.splice(-1,0,node('div',undefined,'menusep'));
menu.append(...items);
const b=iconButton(IC.more,'Mais ações',()=>{menu.hidden=!menu.hidden;b.setAttribute('aria-expanded',String(!menu.hidden));
if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;b.setAttribute('aria-expanded','false');},{once:true});},buttonClass);
b.setAttribute('aria-haspopup','menu');b.setAttribute('aria-expanded','false');
const wrap=node('span',undefined,'morewrap');wrap.append(b,menu);return wrap;
}
function cancelledNotice(order){
const box=node('div',undefined,'callout bad'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.ban,'i m'));
const p=node('p');p.append(node('b','Pedido cancelado. '),order.cancel_reason,node('small','Por '+order.cancelled_by+' em '+when(order.cancelled_at)));
box.append(ico,p);
if(may('manage'))box.append(button('Excluir pedido',async()=>{
if(!await ask('Excluir o pedido #'+order.number+' de vez?','Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.','Excluir pedido',{tone:'red',host:$('drawer')}))return;
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load();
},'btn quiet'));
return box;
}
function contactNotice(order,canClear){
const box=node('div',undefined,'callout'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.phone,'i m'));
const p=node('p');p.append(node('b','Aguardando contato. '),order.contact_note,node('small',contactWho(order)));
box.append(ico,p);
const zap=whatsappLink(order.snapshot.customer.zap);
if(zap){const a=node('a','Abrir conversa','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i s'));box.append(a);}
// A proof order closes its contact wait with Prova OK, the only button
// (item 0.1). Other orders still need a way to record that contact is done.
if(canClear&&!needsProof(order))box.append(button('Contato feito',async()=>{
await api('/orders/'+order.id+'/contact',{waiting:false});say('Contato registrado: a marca saiu do pedido #'+order.number+'.');await load();},'btn'));
return box;
}
// In correction, the customer has to be told: a message ready to send on
// WhatsApp with the reason and where to send the new file.
function correctionMessage(order){
const reason=order.correction_reason||'', link=board.site_origin+'/conta/pedidos?order='+order.id;
return 'Olá! Aqui é da Dropstar. O seu pedido '+orderCode(order.id)+' precisa de um ajuste na arte antes da impressão'+
(reason?': '+reason:'.')+'\n\nEnvie o arquivo corrigido por aqui: '+link;
}
function correctionActions(order,main){
const message=correctionMessage(order), zap=whatsappLink(order.snapshot.customer.zap), out=[];
if(zap){const a=node('a','Avisar no WhatsApp','btn lg'+(main?' pri':''));a.href=zap+'?text='+encodeURIComponent(message);
a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i m'));out.push(a);}
out.push(button('Copiar mensagem',async()=>{await navigator.clipboard.writeText(message);say('Mensagem copiada.');},'btn lg'+(main&&!zap?' pri':'')));
return out;
}
// A file the step is about: its kind, its name and what to do with it.
function fileRow(name,label,...actions){
const row=node('div',undefined,'file');
const ext=(String(name).split('.').pop()||'').slice(0,4).toUpperCase();
const text=node('span',undefined,'ftext');text.append(node('b',name),node('span',label));
row.append(node('span',ext,'fico'),text,...actions);return row;
}
const downloadFile=uid=>downloadButton('Baixar',download(uid),'btn');
// The approved final is the way to the queue (Arte conferida): approving it,
// with the files that would be printed, or sending one.
// The contraction class of an item (item 9): the one chosen, else the one the
// browser measured. The FlexiPRINT applies it by the C1, C2 or C3 folder.
const CLASS_NOTE={C1:'traço até 4 px',C2:'traço de 5 a 19 px',C3:'traço de 20 px ou mais'};
// A mixed sheet (item 16) where the customer chose to protect the solid areas starts at C3.
const measuredClass=item=>item.stroke_choice==='client_c3'?'C3':item.stroke_class||null;
const contractionOf=(order,index)=>order.contraction?.[index]?.class||measuredClass(order.snapshot.items[index]);
function contractionControl(order,index){
const item=order.snapshot.items[index], now=contractionOf(order,index), chosen=order.contraction?.[index];
const measured=(item.stroke_class?'medido '+item.stroke_class+', '+item.stroke_px+' px':'sem medida do navegador')+
(item.stroke_choice==='client_c3'?'; o cliente escolheu proteger as áreas chapadas (C3)':'');
const editable=may('produce')&&!order.cancelled_at&&['rec','tra','cor'].includes(order.state);
if(!editable){const t=node('span',now?now+' ('+(chosen?'escolhida':measured)+')':'Sem classe');return t;}
const select=node('select',undefined,'inp sm');select.setAttribute('aria-label','Contração do item '+(index+1));
for(const [value,text] of [['','Escolha'],['C1','C1, '+CLASS_NOTE.C1],['C2','C2, '+CLASS_NOTE.C2],['C3','C3, '+CLASS_NOTE.C3]]){
const o=node('option',text);o.value=value;select.append(o);}
select.value=now||'';
select.onchange=async()=>{try{
await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value||null});
say('Contração do item '+(index+1)+': '+(select.value||'a medida do navegador')+'.');await load();}
catch(e){say(e.message,true);}};
const box=node('span',undefined,'contr');box.append(select,node('small',chosen?'escolhida por '+chosen.by+'; '+measured:measured,'sub'));
return box;
}
// The approve step's "Está OK?": each item's class, prefilled, to confirm or change.
function contractionList(order){
const box=node('div',undefined,'contrlist');
order.snapshot.items.forEach((item,index)=>{
const row=node('div',undefined,'contrrow');
row.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+', contração':'Contração','lbl'),contractionControl(order,index));
box.append(row);});
return box;
}
function approveParts(order,main=true){
if(designerPaid(order)){
const label=order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino';
const approve=button('Enviar arte do '+label,()=>treatDialog(order),'btn lg'+(main?' pri':''));
approve.dataset.treat='';
return {text:label+' pago: o designer precisa enviar o PNG do '+label+' de cada item antes da fila.',
files:null,approve,extra:[]};
}
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
const files=node('div',undefined,'files');
if(all)ready.forEach((r,i)=>r.files.forEach((f,k)=>files.append(fileRow(f.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source]+
(r.files.length>1?', parte '+(k+1)+' de '+r.files.length:''),downloadFile(f.upload_id)))));
const text=all?'Baixe e confira. É este arquivo que vai para a impressão.':ready.some(Boolean)
?'Alguns itens já têm arquivo pronto; envie o arquivo preparado dos outros.'
:'Nenhum arquivo pronto para aprovar como está: envie o arquivo preparado para a impressão.';
const upload=()=>finalDialog(order,all?ready.map(()=>null):ready);
const approve=button(all?'Aprovar arquivo final':'Enviar arquivo final',all?()=>approveReady(order,ready):async()=>upload(),'btn lg'+(main?' pri':''));
approve.dataset.approve='';
const extra=[];
// In Arte recebida the art may need work first (Dropstar, 2026-10-29).
if(order.state==='rec'&&may('produce')){const t=button('Tratar a arte',async()=>treatDialog(order),'btn lg');t.dataset.treat='';extra.push(t);}
if(all)extra.push(button('Enviar outro arquivo',async()=>upload(),'btn lg'));
return {text,files:all?files:null,approve,extra};
}
// "Próximo passo": what the order needs now, said once, with its button.
// Going back, the contact mark, rework and cancelling are in the menu above.
function nextBox(order){
if(order.cancelled_at)return null;
const st=order.state, trans=board.transitions[st]||[];
let title='';const body=[],main=[],more=[];
const note=text=>body.push(node('p',text,'nnote'));
const can=to=>mayMove(st,to)&&mayAct(order);
const moveBtn=(to,label,className='btn pri lg')=>{
// 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');
note(manual?'O Prumo não abriu o original. Prepare o PNG completo deste pedido; a prova será gerada automaticamente a partir dele.'
:'O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.');
if(manual&&may('produce'))main.push(button('Preparar arquivo para a prova',()=>finalDialog(order,readyFinals(order)),'btn pri lg'));
return composeNext(title,body,main,more);
}
// A proof card in Revisão waits for its answer (Dropstar, 2026-11-03).
if(order.proof_parent&&st==='rev'){
title='Responder a prova';
note('Prova do pedido #'+order.proof_parent.number+'. Com a prova impressa conferida'+(order.snapshot.proof?' e o aceite do cliente':'')+', responda aqui.');
if(may('proof')){main.push(button('Prova OK',()=>proofAnswer(order,'ok'),'btn pri lg'));
more.push(button('Prova reprovada',()=>proofReject(order),'btn quiet lg'));}
else note('Quem responde é o Vendedor, a Gestão ou o Administrador.');
return composeNext(title,body,main,more);
}
const readOnly=!may('produce')&&!ME?.moves?.length;
const fixed=(order.corrections||[]).length>0;
if(st==='cor'){
title=fixed?'Conferir a correção do cliente':'Esperando o arquivo novo';
if(order.correction_reason){const p=node('p',undefined,'nnote');p.append(node('b','Motivo: '),order.correction_reason);body.push(p);}
if(!whatsappLink(order.snapshot.customer.zap))note('Sem WhatsApp no pedido: envie a mensagem para '+order.snapshot.customer.mail+'.');
(fixed?more:main).push(...correctionActions(order,!fixed));
}
if(readOnly){
if(!title)title=st==='fin'?'Pedido concluído':'Com a produção';
note('Somente consulta: seu perfil não move pedidos.');
return composeNext(title,body,main,more);
}
const fixBtn=()=>{if(!trans.includes('cor')||!can('cor'))return;
const b=node('button','Pedir correção','btn quiet lg');b.type='button';b.dataset.move='cor';b.onclick=()=>correctionDialog(order);more.push(b);};
const proofBtn=(className='btn lg')=>{if(!proofPending(order)||order.proof_card||!may('print'))return null;
const b=button('Prova OK',()=>proofOk(order),className);b.dataset.proof='';b.title='A prova foi impressa e conferida';return b;};
const cannot=()=>note(!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.'
:st==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.');
// The proof was rejected: its reason, and a new proof card when the art is fixed.
if(st==='rec'&&proofRejected(order)){
const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p);
if(may('produce'))more.push(button('Nova prova',async()=>{await api('/orders/'+order.id+'/proof-card',{});await load();say('Nova prova criada.');},'btn lg'));
}
if(st==='rec'&&order.proof_parent){
title=finalDone(order)?'Conferir a prova':'Gerando a prova';
const manual=(order.print_files||[]).some(r=>r.status==='manual');
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual
?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.'
:'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg'));
if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg'));
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
more.push(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn lg'));
return composeNext(title,body,main,more);
}
if(st==='rec'||st==='cor'){
if(st==='rec'&&designerPaid(order)&&!treatmentDone(order)&&finalDone(order)){
title='Enviar a arte do '+(order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino');
note((order.snapshot.redesign?'O Ajuste Fino Redesenho foi pago.':'O Ajuste Fino foi pago.')+
' Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
return composeNext(title,body,main,more);
}
if(!finalDone(order)&&trans.includes('tra')){
if(st==='rec')title='Aprovar o arquivo final';
// The designer approves every file (D-16); the others see it waiting.
if(!may('produce')){note('O Designer confere e aprova o arquivo final.');body.push(contractionList(order));}
else{
const lead=st==='rec'||fixed, a=approveParts(order,lead);
// Item 7: open the file, then say whether it is OK.
if(st==='rec'){a.approve.classList.remove('pri');main.push(checkButton(order,'btn pri lg'));}
if(lead){if(a.files)body.push(a.files);note(a.text);body.push(contractionList(order));main.push(a.approve,...a.extra);}
else more.push(a.approve,...a.extra);
}
}else if(st==='rec'){
title='Mandar para a fila';
note('O arquivo final está aprovado. Na fila, o operador puxa para a máquina.');
if(can('tra'))main.push(moveBtn('tra'));else cannot();
// Approved already, the art can still be treated while in Arte recebida.
if(may('produce')){const t=button('Tratar a arte',async()=>treatDialog(order),'btn lg');t.dataset.treat='';more.push(t);}
}
if(st==='cor')for(const to of trans){
if(to==='tra'&&!finalDone(order))continue;
if(can(to))(to==='tra'&&finalDone(order)?main:more).push(moveBtn(to,null,to==='tra'&&finalDone(order)?'btn pri lg':'btn lg'));
}
if(st==='rec')fixBtn();
}else if(st==='tra'&&waitingProof(order)){
title='Aguardando prova';
note('O pedido entra na fila com Prova OK no card da prova #'+order.proof_card.number+'.');
fixBtn();
}else if(st==='tra'){
title='Puxar para a máquina';
note(order.machine?'Vai para a '+order.machine.name+'. O arquivo final já está aprovado.':'O arquivo final já está aprovado.');
if(can('imp'))main.push(moveBtn('imp'));else cannot();
const p=proofBtn();if(p)more.push(p);
fixBtn();
}else if(st==='imp'){
title=order.printing==='ripando'?'Ripando enquanto o anterior roda':'Terminou de imprimir?';
note('A folha segue para o Revisor conferir.');
if(can('rev'))main.push(moveBtn('rev'));else cannot();
const p=proofBtn();if(p)more.push(p);
fixBtn();
}else if(st==='rev'){
if(proofPending(order)){
// Finalizado waits for the proof: printing it and checking it is the next step.
title='Conferir a prova';
note((order.snapshot.proof?'O cliente pediu uma prova: imprima, mande a foto pelo WhatsApp e, com o aceite dele, marque Prova OK.'
:'Pedido acima de 10 m: imprima a prova, confira e marque Prova OK antes de rodar o resto.')+' '+PROOF_RULE);
const p=proofBtn('btn pri lg');if(p)main.push(p);
}else{
// Above 1 m the photo is required to finish (app/reviews.py): the main
// button takes it instead of releasing the order.
const hasPhoto=(order.reviews||[]).some(review=>review.kind==='photo');
if(!order.proof_parent&&orderMetres(order)>1&&!hasPhoto){
title='Tire a foto da revisão';
note('Pedido acima de 1 m: tire a foto da revisão antes de finalizar.');
if(may('inspect'))main.push(button('Revisar',()=>reviewDialog(order),'btn pri lg'));else cannot();
}else{
title='Conferir a folha impressa';
note('Confira cores, recorte e a folha inteira contra o arquivo.');
if(can('fin'))main.push(moveBtn('fin','Liberar para Finalizado'));else cannot();
}
}
fixBtn();
}else if(st==='fin'){
const dest=order.snapshot.destination;
if(isPickup(order)){
// Pickup (item 14): the receipt, and "Retirado", with the signed receipt's photo.
const paper=button('Recibo',()=>window.open('/api/operator/orders/'+order.id+'/receipt','_blank','noopener'),'btn lg');
paper.title='Abrir o recibo de retirada para imprimir de novo';paper.prepend(svgIcon(IC.file,'i m'));
if(order.picked_up_at){
title='Retirado';note('Em '+when(order.picked_up_at)+', entregue por '+order.picked_up_by+'.');
if(order.picked_up_photo){const b=downloadButton('Foto do recibo',download(order.picked_up_photo),'btn lg');more.push(b);}
more.push(paper);
}else{
title='Entregar ao cliente';note('O cliente retira na fábrica. O recibo vai junto, para a assinatura.');
if(may('deliver')){const b=node('button','Marcar retirado','btn pri lg');b.type='button';b.dataset.pickedUp='';b.onclick=()=>pickupDialog(order);main.push(b);}
more.push(paper);
}
}else{
title='Pedido concluído';
note(dest?'Vai para entrega em '+dest.city+'/'+dest.state+'.':'Pedido concluído.');
}
}
return composeNext(title,body,main,more);
}
function composeNext(title,body,main,more){
const box=node('section',undefined,'nextbox');box.setAttribute('aria-label','Próximo passo');
const head=node('div');head.append(node('span','Próximo passo','lbl'),node('h3',title));
box.append(head,...body);
if(main.length||more.length){const acts=node('div',undefined,'nact');acts.append(...main,...more);box.append(acts);}
return box;
}
// ---- The order's dialogs: each a form.reason, so its field is the order's.
function correctionDialog(order){
const text=node('textarea');text.placeholder='Ex.: o logo da manga veio em 72 DPI';text.maxLength=1000;text.required=true;
text.setAttribute('aria-label','Motivo da correção');
formDialog('Pedir correção do pedido #'+order.number,{host:$('drawer'),className:'reason',width:540,
text:'O pedido vai para Correção. Depois, a mensagem para o cliente fica pronta para mandar no WhatsApp.',
fields:[field('Motivo',text,'O cliente vê este motivo na mensagem.')],label:'Enviar para correção',tone:'red',
onsave:async()=>{await move(order,'cor',text.value.trim());}});
}
function backDialog(order,previous){
const why=node('input');why.placeholder='Motivo';why.setAttribute('aria-label','Motivo do retorno');why.required=true;why.maxLength=1000;
formDialog('Voltar para '+board.states[previous]+'?',{host:$('drawer'),className:'reason',width:500,
text:'Para desfazer um movimento feito por engano. O cliente não é avisado e os arquivos aprovados continuam.',
fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Voltar para '+board.states[previous],
onsave:async()=>{await move(order,previous,why.value.trim());}});
}
function contactDialog(order){
const what=node('input');what.placeholder='Ex.: confirmar se a arte vai na frente ou nas costas';what.setAttribute('aria-label','O que precisa ser combinado');
what.required=true;what.minLength=3;what.maxLength=500;
formDialog('Aguardando contato',{host:$('drawer'),className:'reason',width:540,
text:'O card fica marcado até alguém registrar o contato feito.',
fields:[field('O que precisa ser combinado com o cliente',what)],label:'Marcar aguardando contato',
onsave:async()=>{await api('/orders/'+order.id+'/contact',{waiting:true,note:what.value.trim()});say('Pedido #'+order.number+' aguardando contato.');await load();}});
}
function cancelDialog(order){
const why=node('textarea');why.placeholder='Ex.: cliente desistiu, vai refazer a arte';why.setAttribute('aria-label','Motivo do cancelamento');
why.required=true;why.minLength=3;why.maxLength=1000;
formDialog('Cancelar o pedido #'+order.number+'?',{host:$('drawer'),className:'reason',width:520,
text:'O pedido sai do quadro e fica em Cancelados, com o pagamento e o histórico. O valor fica como crédito do cliente, no controle financeiro, e o pedido no Tiny se cancela lá.',
fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Cancelar pedido',tone:'red',
onsave:async()=>{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}});
}
function pickupDialog(order){
const photo=node('input');photo.accept='image/*';photo.setAttribute('aria-label','Foto do recibo assinado');
formDialog('Marcar o pedido #'+order.number+' como retirado',{host:$('drawer'),width:540,
text:'Quem retirou assina o recibo. A foto dele fica no pedido.',
fields:[dropField(photo,{title:'Foto do recibo assinado',hint:'Opcional. JPG, PNG ou HEIC.'})],label:'Confirmar retirada',
onsave:async()=>{
const uid=photo.files[0]?await dtfUpload(photo.files[0],{api,startPath:'/orders/'+order.id+'/pickup-uploads',
scope:'operator:pickup:'+order.id,progress:text=>say(text)}):null;
await api('/orders/'+order.id+'/picked-up',{photo:uid});
await load();say('Pedido #'+order.number+' marcado como retirado.');
}});
}
// Pickup or delivery, from the freight the customer chose.
const isPickup=order=>order.snapshot.freight?.service==='pickup';
// An internal order stays in house, and a sale can travel with the customer's
// clothing order (Fase 2, front 7a.3): the card and the panel say so instead
// of "Retirada".
const specialDelivery=s=>s.kind==='interno'?'Interno':s.with_order?'Junto com o pedido de roupa nº '+s.with_order:null;
// ---- Final files: the file each item is printed from, approved by an operator.
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index));
const designerPaid=order=>!!(order.snapshot.treatment||order.snapshot.redesign);
const FINAL_SOURCE={correction:'correção do cliente',generated:'arquivo gerado',original:'original'};
const FINAL_TITLE={correction:'Correção do cliente',generated:'Gerado pelo sistema',original:'Original do cliente'};
// What the system generated for an item: one PNG, or the parts of a film
// over 15 m (item 13). An item generated before parts has just its file.
const generatedFiles=row=>row.parts?.length?row.parts:[{upload_id:row.upload_id,name:row.name}];
// Per item, the files that can be approved as they are, or null: the
// customer's correction, or else what the system generated (or the original
// that already was one). After a correction, a generated file reproduces
// artwork nobody wants printed.
function readyFinals(order){
const fixes=order.corrections||[];
return order.snapshot.items.map((item,index)=>{
const fix=fixes.find(f=>f.item_index===index);
if(fix)return fix.expired||!fix.name.toLowerCase().endsWith('.png')?null:{files:[{upload_id:fix.upload_id,name:fix.name}],name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'};
const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready');
if(!made)return null;
const original=made.detail?.source==='original', files=generatedFiles(made);
const names=files.length>1?files.length+' partes, '+files[0].name+' a '+files[files.length-1].name:files[0].name;
return {files,name:files[0].name,source:original?'original':'generated',label:(original?'O original (':'Gerado pelo sistema (')+names+')'};
});
}
// Sends final-files from a dialog that may have been opened before another
// screen approved the same files (DTF-WEB-7). A stale version gets 409 "O
// pedido mudou"; when the approval is already there, or the order left Arte
// recebida/Correção, reload and say so; true tells the caller to stop, and a
// form dialog then closes itself. Anything else is still an error, and the
// version is never resent blindly.
async function saveFinalFiles(order, files, note){
try{
await api('/orders/'+order.id+'/final-files',{version:order.version,files,note});
return false;
}catch(error){
if(error.status!==409||!String(error.message).startsWith('O pedido mudou'))throw error;
await load();
const fresh=(board.orders||[]).find(row=>row.id===order.id);
if(fresh&&(finalDone(fresh)||!['rec','cor'].includes(fresh.state))){
say('O arquivo final já estava aprovado.');
return true;
}
throw error;
}
}
async function approveReady(order,ready){
const many=ready.length>1;
if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+
ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return;
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
if(await saveFinalFiles(order,
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return;
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
}
// The file the operator prepared, per item; a ready file comes ticked.
function finalDialog(order,ready,{replace=false}={}){
const fields=[];
const inputs=order.snapshot.items.map((item,index)=>{
const slot=node('div',undefined,'fslot');
const label=order.snapshot.items.length>1?'Item '+(index+1)+', '+productName(item):productName(item);
slot.append(node('span',label,'lbl'));
const input=node('input');input.multiple=true;input.required=true;input.dataset.finalItem=index;
input.setAttribute('aria-label','Arquivo final, '+label);
input.accept='.png,image/png';
const drop=dropField(input,{hint:'PNG transparente a 300 DPI, do tamanho da impressão.'});
const file=ready[index];
if(file){
const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true;
use.onchange=()=>{drop.hidden=use.checked;input.required=!use.checked;};
slot.append(checkbox('Usar: '+file.label,use));input.generated=()=>use.checked?file.files.map(f=>f.upload_id):null;
}
slot.append(drop);fields.push(slot);return input;
});
const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;note.setAttribute('aria-label','Nota da revisão');
const check=node('input');check.required=true;check.dataset.confirm='';
fields.push(field('Nota',note,'Ex.: ajustei a margem e o recorte. Fica no histórico.'),checkbox('Arquivos conferidos',check));
formDialog(replace?'Trocar o arquivo final':'Enviar o arquivo final',{host:$('drawer'),width:580,className:'finalform',
text:'Pedido #'+order.number+'. O arquivo novo passa a ser o que vai para a impressão.',note:'O anterior fica em Arquivos.',
fields,label:'Aprovar arquivo final',onsave:async()=>{
const refs=[];
for(const [index,input] of inputs.entries()){
const generated=input.generated?.();
if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;}
for(const file of input.files){
if(!file.name.toLowerCase().endsWith('.png'))throw Error('O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.');
const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)});
refs.push({item_index:index,upload_id:uid});
}
}
if(await saveFinalFiles(order,refs,note.value))return;
await load();say('Arquivo final aprovado.');
}});
}
// "Tratar a arte" (Dropstar, 2026-10-29): where each item's file is in the
// orders folder, to open it, treat it and save it over with the same name;
// then the treated file sent here becomes the item's final, "Arte tratada".
// The browser only knows the folder's name, so each computer is told once
// where the folder is, to copy the whole path.
const TREAT_NOTE='Arte tratada';
const FOLDER_PATH_KEY='folder-path';
// ---- Abrir e conferir (item 7) ----------------------------------------------
// The print file full screen, in pieces (web/kanban-viewer.js); closed in
// Arte recebida, it asks whether the art is OK.
function checkButton(order,className='btn'){
const b=button('Abrir e conferir',()=>openCheck(order),className);b.prepend(svgIcon(IC.eye||IC.file,'i m'));return b;
}
function cardOpenAction(order){
const action=button('Abrir arquivo',()=>openCheck(order),'card-open');
action.prepend(svgIcon(IC.eye||IC.file,'i s'));
// In Revisão the Revisor also has the photo/video on the card's face, beside
// the file. The click is stopped by button(), as on "Abrir arquivo".
if(order.state==='rev'&&!order.cancelled_at&&may('inspect')){
const review=button('Revisar',()=>reviewDialog(order),'card-open');
review.prepend(svgIcon(IC.camera,'i s'));
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,
// taken here with the computer's or the phone's camera, or a file already
// recorded. The server names it DTF-<n>-revisao-<seq> and keeps it 180 days.
const REVIEW_VIDEO_MAX=30;
const reviewClock=s=>Math.floor(s/60)+':'+String(s%60).padStart(2,'0');
function reviewDialog(order){
const host=dialogHost();
const video=node('video');video.className='reviewcam';video.muted=true;video.playsInline=true;video.autoplay=true;
video.setAttribute('aria-label','Pré-visualização da câmera');
const timer=node('span','0:00 / 0:30','reviewtime');timer.setAttribute('aria-live','polite');
const controls=node('div',undefined,'reviewcontrols');
const photoBtn=node('button','Tirar foto','btn pri');photoBtn.type='button';photoBtn.setAttribute('aria-label','Tirar foto');photoBtn.setAttribute('autofocus','');
const videoBtn=node('button','Gravar vídeo','btn');videoBtn.type='button';videoBtn.setAttribute('aria-label','Gravar vídeo');
const input=node('input');input.type='file';input.className='vh';
input.accept='image/jpeg,image/png,image/webp,video/mp4,video/webm,video/quicktime';
const fileLabel=node('label',undefined,'btn');fileLabel.tabIndex=0;
fileLabel.append(svgIcon(IC.upload,'i m'),'Enviar arquivo',input);
const preview=node('div',undefined,'reviewpreview');preview.hidden=true;
const status=node('p','','reviewmsg');status.setAttribute('role','status');status.setAttribute('aria-live','polite');
const save=node('button','Salvar revisão','btn pri');save.type='button';save.disabled=true;
const cancel=node('button','Cancelar','btn ghost right');cancel.type='button';
controls.append(photoBtn,videoBtn,fileLabel);
let stream=null,recorder=null,recordTimer=null,chunks=[],ready=null,objectUrl=null,closed=false,recording=false,recordStart=0;
const fail=text=>{status.textContent=text;status.classList.add('bad');};
const clear=()=>{status.textContent='';status.classList.remove('bad');};
const endStream=()=>{
if(recordTimer){clearInterval(recordTimer);recordTimer=null;}
if(stream){stream.getTracks().forEach(track=>track.stop());stream=null;}
};
const cleanup=()=>{
closed=true;
if(recorder&&recorder.state!=='inactive'){try{recorder.stop();}catch(_){}}
endStream();
if(objectUrl){URL.revokeObjectURL(objectUrl);objectUrl=null;}
};
function showReady(file,kind){
ready={file,kind};
endStream();
video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true;
if(objectUrl)URL.revokeObjectURL(objectUrl);
objectUrl=URL.createObjectURL(file);
preview.replaceChildren();
if(kind==='video'){
const shot=node('video');shot.controls=true;shot.playsInline=true;shot.src=objectUrl;
shot.setAttribute('aria-label','Pré-visualização do vídeo gravado');preview.append(shot);
}else{
const shot=node('img');shot.src=objectUrl;shot.alt='Pré-visualização da foto';preview.append(shot);
}
preview.hidden=false;save.disabled=false;clear();save.focus();
}
function checkDuration(file){
return new Promise((resolve,reject)=>{
const probe=document.createElement('video');probe.preload='metadata';
const url=URL.createObjectURL(file);
probe.onloadedmetadata=()=>{
const seconds=probe.duration;URL.revokeObjectURL(url);
if(Number.isFinite(seconds)&&seconds>REVIEW_VIDEO_MAX+0.2)
reject(new Error('O vídeo tem mais de 30 segundos. Grave um de até 30 s ou envie outro menor.'));
else resolve();
};
probe.onerror=()=>{URL.revokeObjectURL(url);resolve();};
probe.src=url;
});
}
function stopRecording(){if(recorder&&recorder.state!=='inactive')recorder.stop();}
photoBtn.onclick=()=>{
clear();
const width=video.videoWidth,height=video.videoHeight;
if(!width||!height){fail('A câmera ainda não está pronta. Espere um instante.');return;}
const canvas=document.createElement('canvas');canvas.width=width;canvas.height=height;
canvas.getContext('2d').drawImage(video,0,0,width,height);
canvas.toBlob(blob=>{
if(!blob){fail('Não foi possível tirar a foto.');return;}
showReady(new File([blob],'revisao.jpg',{type:'image/jpeg'}),'photo');
},'image/jpeg',0.9);
};
videoBtn.onclick=()=>{
clear();
if(recording){stopRecording();return;}
if(!stream){fail('A câmera não está disponível. Envie um arquivo.');return;}
const options=['video/mp4','video/webm;codecs=vp9','video/webm'];
const mime=(window.MediaRecorder&&options.find(type=>MediaRecorder.isTypeSupported(type)))||'';
try{recorder=new MediaRecorder(stream,mime?{mimeType:mime}:undefined);}
catch(_){fail('Este navegador não grava vídeo. Envie um arquivo.');return;}
const type=recorder.mimeType||mime||'video/webm';
chunks=[];recording=true;recordStart=Date.now();
recorder.ondataavailable=event=>{if(event.data&&event.data.size)chunks.push(event.data);};
recorder.onstop=()=>{
recording=false;videoBtn.textContent='Gravar vídeo';
if(recordTimer){clearInterval(recordTimer);recordTimer=null;}
if(closed)return;
const blob=new Blob(chunks,{type});chunks=[];
if(!blob.size){fail('Não foi possível gravar o vídeo.');return;}
showReady(new File([blob],'revisao.'+(type.includes('mp4')?'mp4':'webm'),{type}),'video');
};
recorder.start();videoBtn.textContent='Parar';
const paint=()=>{
const elapsed=Math.min(REVIEW_VIDEO_MAX,Math.floor((Date.now()-recordStart)/1000));
timer.textContent=reviewClock(elapsed)+' / '+reviewClock(REVIEW_VIDEO_MAX);
if(elapsed>=REVIEW_VIDEO_MAX)stopRecording();
};
paint();recordTimer=setInterval(paint,250);
};
input.onchange=async()=>{
const file=input.files[0];if(!file)return;
clear();
const name=file.name.toLowerCase();
const isVideo=file.type.startsWith('video/')||/\.(mp4|webm|mov)$/.test(name);
const isPhoto=file.type.startsWith('image/')||/\.(jpe?g|png|webp)$/.test(name);
if(!isVideo&&!isPhoto){input.value='';fail('Escolha uma foto JPG, PNG ou WebP, ou um vídeo MP4, WebM ou MOV.');return;}
if(isVideo){
try{await checkDuration(file);}catch(error){input.value='';fail(error.message);return;}
if(closed)return;
showReady(file,'video');
}else showReady(file,'photo');
};
fileLabel.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();input.click();}};
cancel.onclick=()=>m.close();
save.onclick=async()=>{
if(!ready)return;
save.disabled=true;clear();status.textContent='Enviando '+ready.file.name+'…';
try{
const uid=await dtfUpload(ready.file,{api,startPath:'/orders/'+order.id+'/reviews/uploads',
scope:'operator:review:'+order.id,progress:text=>{if(!closed)status.textContent=text;}});
if(closed)return;
await api('/orders/'+order.id+'/reviews',{upload_id:uid});
m.close();
say('Revisão salva no pedido #'+order.number+'.');
await load();
}catch(error){
if(closed)return;
fail(error.message);save.disabled=false;
}
};
const m=modal('Revisão do #'+order.number,{host,width:640,
text:'Tire uma foto ou grave um vídeo de até 30 s da folha impressa, ou envie um arquivo.',
body:[video,controls,timer,preview],foot:[status,cancel,save],onclose:cleanup});
(async()=>{
try{
if(!navigator.mediaDevices?.getUserMedia)throw new Error('sem câmera');
stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'environment',
width:{ideal:1920},height:{ideal:1080}},audio:false});
if(closed){endStream();return;}
video.srcObject=stream;
await video.play().catch(()=>{});
photoBtn.focus();
}catch(_){
endStream();video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true;
fail('Câmera indisponível neste computador. Envie um arquivo.');
fileLabel.focus();
}
})();
}
async function openCheck(order){
const {files}=await api('/orders/'+order.id+'/view');
if(!files.length){say('Ainda não há arquivo para abrir.',true);return;}
openViewer(files,{title:'#'+order.number,onClose:()=>{
const now=board.orders.find(o=>o.id===order.id)||order;
if(now.state==='rec'&&!now.cancelled_at&&!waitingProof(now)&&may('produce')&&mayMove('rec','tra')){
if(openOrder!==order.id)openPanel(order.id);
isOk(now);
}}});
}
// "Está OK?" (Dropstar, 2026-10-29): the class of each item, prefilled with
// the measure, and the art either goes on to Arte conferida, its final
// approved and its class kept, or is treated (item 8).
function isOk(order){
// Ajuste Fino or Redesenho paid: only the treated PNG goes to the queue, so
// nothing is approved here; the designer goes to "Tratar a arte" (DTF-WEB-A).
if(designerPaid(order)&&!treatmentDone(order)){
const service=order.snapshot.redesign?'O Ajuste Fino Redesenho':'O Ajuste Fino';
const m=formDialog('Falta a arte tratada',{host:$('drawer'),label:'Tratar a arte',
text:service+' foi pago. Envie o PNG ajustado de cada item antes de colocar o pedido na fila.',
onsave:async()=>{m.close();treatDialog(order);return false;}});
return;
}
const items=order.snapshot.items, ready=readyFinals(order);
const selects=items.map((item,index)=>{
const select=node('select');select.required=true;
const none=node('option','Escolha');none.value='';none.disabled=true;select.append(none);
for(const c of ['C1','C2','C3']){const o=node('option',c+', '+CLASS_NOTE[c]);o.value=c;select.append(o);}
select.value=contractionOf(order,index)||'';return select;});
const fields=selects.map((select,index)=>{const item=items[index];
return field(items.length>1?'Item '+(index+1)+', contração':'Contração',select,
item.stroke_class?'O site mediu '+item.stroke_class+', traço de '+item.stroke_px+' px':'O site não mediu esta arte');});
const missing=!finalDone(order)&&!ready.every(Boolean);
const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn');
const m=formDialog('Está OK?',{host:$('drawer'),fields,left:[treat],label:'Mover para Arte conferida',
text:missing?'Falta o arquivo final de um item: trate a arte e envie o arquivo preparado.'
:'A arte chegou boa? Confira a contração e mova para Arte conferida.',
onsave:async()=>{
if(missing)throw new Error('Falta o arquivo final de um item.');
for(const [index,select] of selects.entries())
if(select.value!==contractionOf(order,index))
await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value});
if(!finalDone(order)&&await saveFinalFiles(order,
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),
'Conferido em Abrir e conferir'))return;
await load();
await move(board.orders.find(o=>o.id===order.id)||order,'tra');
say('Pedido #'+order.number+' em Arte conferida.');
}});
if(missing)m.box.querySelector('button.pri')?.setAttribute('disabled','');
}
function treatDialog(order){
const base=node('input');base.placeholder='Ex.: D:\\'+(FOLDER.handle?.name||'Pedidos');
const names={};
const rows=order.snapshot.items.map((item,index)=>{
const slot=node('div',undefined,'fslot');
const path=node('code','Procurando o arquivo…','treatpath');
const copy=node('button','Copiar','btn');copy.type='button';copy.disabled=true;
const line=node('div',undefined,'treatline');line.append(path,copy);
const input=node('input');input.dataset.treatItem=index;
input.setAttribute('aria-label','Arte tratada do item '+(index+1));
slot.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+', '+productName(item):productName(item),'lbl'),line,
dropField(input,{title:'Arte tratada',hint:'O arquivo salvo depois de tratar.'}));
return {path,copy,input};
});
// Windows paths unless the folder was written the other way.
const where=name=>{const b=base.value.trim().replace(/[\\/]+$/,''),sep=b.includes('/')&&!b.includes('\\')?'/':'\\';
return (b?b+sep:'')+STAGE_FOLDERS[order.state]+sep+name;};
const paint=()=>rows.forEach((row,index)=>{
const name=names[index+1];
row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.';
row.copy.disabled=!name;
row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(name));
say(base.value.trim()?'Caminho copiado.':'Caminho copiado a partir da pasta dos pedidos: informe onde ela fica neste computador para copiar o caminho inteiro.');}
catch(_){say('Não foi possível copiar.',true);}};
});
base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();};
formDialog('Tratar a arte',{host:$('drawer'),width:620,className:'finalform',
text:'Copie o caminho e abra o arquivo. Trate e salve por cima, com o mesmo nome. Depois suba aqui o arquivo tratado.',
fields:[...rows.map(r=>r.input.closest('.fslot')),field('Pasta dos pedidos neste computador',base)],label:'Subir arte tratada',
onsave:async()=>{
// Each item keeps its approved final, or else the file ready to approve,
// unless a treated one is sent for it.
const ready=readyFinals(order);
const plan=rows.map((row,index)=>{
const file=row.input.files[0];
if(file)return {file};
const kept=(order.finals||[]).filter(f=>f.item_index===index).map(f=>f.upload_id);
const treated=order.treated?.items?.includes(index);
return {ids:designerPaid(order)&&!treated?[]:
kept.length?kept:ready[index]?ready[index].files.map(f=>f.upload_id):[]};
});
if(!plan.some(p=>p.file))throw new Error('Escolha o arquivo tratado.');
const empty=plan.findIndex(p=>!p.file&&!p.ids.length);
if(empty>=0)throw new Error('O item '+(empty+1)+' ainda não tem arte tratada: envie o PNG dele também.');
const refs=[];
for(const [index,p] of plan.entries()){
if(!p.file){refs.push(...p.ids.map(upload_id=>({item_index:index,upload_id})));continue;}
const uid=await dtfUpload(p.file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)});
refs.push({item_index:index,upload_id:uid});
}
if(await saveFinalFiles(order,refs,TREAT_NOTE))return;
await load();
say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.');
}});
// Filled once open: the names the automatic folders give the files.
(async()=>{
base.value=await kv.get(FOLDER_PATH_KEY).catch(()=>'')||'';
try{for(const f of (await api('/orders/'+order.id+'/folder-files')).files)names[f.item]=names[f.item]||f.name;}
catch(error){say(error.message,true);}
paint();
})();
}
// The reviews recorded on the order: what was checked, when and by whom. A
// photo opens in the viewer; a video cannot, so it opens in a new tab. In
// Revisão a reviewer may remove one.
function reviewSection(order){
if(!order.reviews?.length)return null;
const box=node('section',undefined,'reviewsec');box.setAttribute('aria-label','Revisões');
const info=node('div',undefined,'iinfo');
info.append(node('span','Revisões','lbl'),node('h3',plural(order.reviews.length,'revisão','revisões')));
const list=node('div',undefined,'reviewlist');
for(const review of order.reviews){
const row=node('div',undefined,'reviewrow');
const open=node('button',undefined,'reviewopen');open.type='button';
open.append(node('span','Revisão · '+(review.kind==='video'?'vídeo':'foto')+' · '+
when(review.created_at)+' · '+review.created_by));
open.onclick=async()=>{
try{
const view=await api('/orders/'+order.id+'/reviews/'+review.id+'/view');
if(review.kind==='photo'&&window.openViewer)openViewer([{name:view.name,picture:view.url}],{title:'Revisão #'+order.number});
else{const link=node('a');link.href=view.url;link.target='_blank';link.rel='noopener noreferrer';link.click();}
}catch(error){say(error.message,true);}
};
row.append(open);
if(order.state==='rev'&&may('inspect')){
const remove=node('button','Remover','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Remover esta revisão?','Ela some do pedido e o arquivo deixa de ficar guardado.','Remover revisão',{tone:'red',host:$('drawer')}))return;
await api('/orders/'+order.id+'/reviews/'+review.id+'/remove',{});
say('Revisão removida do pedido #'+order.number+'.');await load();
};
row.append(remove);
}
list.append(row);
}
info.append(list);box.append(info);
return box;
}
// Pedido: the items, then who, where and on which machine, then any rework.
function orderView(order){
const view=node('div',undefined,'tview');
const s=order.snapshot;
s.items.forEach((item,index)=>view.append(itemCard(order,item,index)));
view.append(orderFacts(order));
const reviews=reviewSection(order);if(reviews)view.append(reviews);
if(order.reworks?.length)view.append(reworkSection(order));
return view;
}
// On the phone: one row per fact, the label on the left.
function phoneFacts(order){
const s=order.snapshot, dest=s.destination, who=buyer(s);
const box=node('div',undefined,'mblock mfacts');
const row=(k,v)=>{if(!v)return;const r=node('div',undefined,'mfact');r.append(node('span',k),node('b',v));box.append(r);};
row('Cliente',who.title);row('E-mail',s.customer.mail);row(docKind(s.customer.cnpj),cnpj(s.customer.cnpj));
row('Entrega',specialDelivery(s)||(dest?dest.city+'/'+dest.state:'Retirada em Franca'));
row('Máquina',order.machine?.name||'Nenhuma');row('Código','DTF-'+order.number+', cliente '+orderCode(order.id));
// Choosing the machine stays where it is allowed.
if(may('print')&&ME?.role!=='operador'&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);}
return box;
}
function orderFacts(order){
if(PHONE.matches)return phoneFacts(order);
const s=order.snapshot, dest=s.destination, who=buyer(s);
const grid=node('div',undefined,'facts3');
const client=node('div',undefined,'fact');
const doc=node('span',undefined,'factline');doc.append(docKind(s.customer.cnpj)+' '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar '+docKind(s.customer.cnpj)));
const title=node('b',who.title);title.title=who.legal||who.title;
client.append(node('span','Cliente','lbl'),title,...(who.mail?[node('span',who.mail)]:[]),doc);
const zap=whatsappLink(s.customer.zap);
if(zap){const a=node('a','Abrir conversa','btn lnk');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(svgIcon(IC.chat,'i s'));client.append(a);}
const where=node('div',undefined,'fact'),special=specialDelivery(s);
where.append(node('span','Entrega','lbl'),node('b',special||(dest?dest.recipient:'Retirada em Franca')),
node('span',special?(special==='Interno'?'Fica na fábrica':'Sem frete próprio'):
dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+', '+dest.district+', '+dest.city+'/'+dest.state+', CEP '+dest.postal_code:'O cliente retira na fábrica'));
if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+', '+money(s.freight.total_cents)+(s.freight.weight_kg?', '+freightWeight(s.freight):''),'faint'));
grid.append(client,where);
if(order.machine||board.machines?.length)grid.append(machineCard(order));
return grid;
}
const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'Arquivo gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'};
// A line on an item: what is fine (ok), to look at (warn) or wrong (bad).
function itemNote(text,tone=''){
const line=node('div',undefined,'inote'+(tone?' '+tone:''));
line.append(svgIcon(tone==='ok'?IC.check:tone?IC.alert:IC.info,'i s'),node('span',text));return line;
}
function itemCard(order,item,index){
const row=(order.print_files||[]).find(r=>r.item_index===index), spec=item.production;
const printStatus=row?.timed_out?'failed':row?.status;
const box=node('section',undefined,'item');box.setAttribute('aria-label','Item '+(index+1));
const info=node('div',undefined,'iinfo');
const count=order.snapshot.items.length;
info.append(node('span',count>1?'Item '+(index+1)+' de '+count:'Item','lbl'),node('h3',productName(item)));
const dl=node('dl',undefined,'dl');
const pair=(k,v)=>{if(v===null||v===undefined||v==='')return;const d=node('div');const dd=node('dd');dd.append(v);d.append(node('dt',k),dd);dl.append(d);};
pair('Folha',sheetSize(spec));pair('Metros cobrados',metres(item.billed_metres));
pair('Peças',spec?String(spec.placements.length):null);
pair('Valor do metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null);
const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g);
pair('Menor resolução',row?.status==='ready'&&row.detail?.min_dpi?row.detail.min_dpi+' DPI':null);
pair('Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null);
pair('Contração',contractionControl(order,index));
info.append(dl);
const notes=node('div',undefined,'inotes');
if(item.quality_status==='warning')notes.append(itemNote('O cliente aceitou a ressalva de resolução.','warn'));
if(item.residue_accepted)notes.append(itemNote('Resíduo: '+item.residue_accepted+' pontos, aceito pelo cliente'+
(item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn'));
if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+
(item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.'
:'o cliente foi avisado e quis imprimir assim mesmo (C1).')+
(item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn'));
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
// After a customer correction, that file is the artwork: the generated
// print file, or the reason it could not be made, no longer applies.
const fix=(order.corrections||[]).find(f=>f.item_index===index);
if(fix)notes.append(itemNote('Correção do cliente recebida: '+fix.name,'ok'));
else if(!row)notes.append(itemNote('Arquivo de impressão ainda não gerado.'));
else if(printStatus==='manual'||printStatus==='failed'){
const call=node('div',undefined,'callout warn'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.alert,'i m'));
const p=node('p');p.append(node('b',printStatus==='failed'?'Falhou ao gerar'+(row.finished_at||row.timeout_at?' às '+when(row.finished_at||row.timeout_at):'')+'. ':'Preparar à mão. '),
row.timed_out?'Tempo limite excedido. Gere de novo.':row.detail?.reason||'Monte a folha a partir do original.');
call.append(ico,p);notes.append(call);
}else{
const original=row.status==='ready'&&row.detail?.source==='original';
notes.append(itemNote((original?'O original é o arquivo de impressão':PRINT_TEXT[row.status])+
(row.status==='ready'&&row.name&&!original?': '+row.name:'')+(row.status==='ready'&&row.detail?.vector_sources&&!original?', PDF vetorial':''),row.status==='ready'?'ok':''));
}
if(['rec','tra','cor'].includes(order.state)){
const done=(order.final_items||[]).includes(index);
notes.append(itemNote(done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn'));
}
if(order.treated?.items.includes(index))notes.append(itemNote('Arte tratada: '+TREATED_NOTE.charAt(0).toLowerCase()+TREATED_NOTE.slice(1)+' Aprovado por '+order.treated.by+'.'));
// O que o Prumo fez (front 6): the actions that happened, before the
// designer opens the file. Multi-item orders show each item's own lines.
const multi=order.snapshot.items.length>1, prefix=multi?'Item '+(index+1)+': ':'';
const prumoLines=(order.prumo||[]).filter(line=>!multi||line.startsWith(prefix)||line.startsWith('Prova do'))
.map(line=>line.startsWith(prefix)?line.slice(prefix.length):line);
if(prumoLines.length){
const block=node('details',undefined,'prumo');block.append(node('summary','O que o Prumo fez'));
prumoLines.forEach(line=>block.append(node('p',line)));
notes.append(block);
}
if(notes.children.length)info.append(notes);
const links=node('div',undefined,'links');
const dl_=(text,uid)=>{const b=downloadButton(text,download(uid),'btn');return b;};
if(fix&&!fix.expired)links.append(dl_('Correção',fix.upload_id));
else if(row?.status==='ready'&&row.detail?.source!=='original'){
const made=generatedFiles(row);
made.forEach((f,k)=>links.append(dl_(made.length>1?'Parte '+(k+1)+' de '+made.length:/\.pdf$/i.test(f.name)?'PDF':'PNG',f.upload_id)));
}
const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')'));
item.uploads.forEach((uid,i)=>originals.append(downloadButton('Original '+(i+1),download(uid,order.id),'btn')));
links.append(originals);
if(row?.status==='ready')links.prepend(checkButton(order));
if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&!waitingProof(order)&&(!row||row.status==='manual'||row.status==='failed'||row.timed_out)){
const again=button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn');again.prepend(svgIcon(IC.refresh,'i m'));links.append(again);}
info.append(links);
box.append(itemPreview(item),info);return box;
}
// Arquivos: every final, current or replaced, and the way to send a new one.
function filesView(order,revisions,view){
const out=[];
const layouts=node('div',undefined,'links');
order.snapshot.items.forEach((item,index)=>{
if(item.production?.placements){
const b=button('Manifesto · item '+(index+1),()=>manifest(item.production,contractionRecord(item,order.contraction?.[index])),'btn');
b.prepend(svgIcon(IC.file,'i m'));layouts.append(b);
}
});
if(layouts.children.length)out.push(layouts);
if(revisions.length){
const panel=node('div',undefined,'tpanel');
const table=node('table',undefined,'table');
const head=node('tr');head.append(node('th','Arquivo'),node('th','Item'),node('th','Situação'),node('th',''));
for(const th of head.children)th.scope='col';
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const file of revisions){
const tr=node('tr');
const name=node('td');name.append(node('span',file.name,'code'),node('span',(file.kind==='final'?'Final':'Correção do cliente')+(file.note?', '+file.note:''),'sub'));
const state=node('td');state.append(badge(file.expired?'Expirado':file.active?'Atual':'Substituído',file.active&&!file.expired?'ok':''),node('span',when(file.created_at),'sub'));
const act=node('td',undefined,'r');if(!file.expired)act.append(downloadButton('Baixar',download(file.upload_id),'btn ghost'));
tr.append(name,node('td',String(file.item_index+1)),state,act);tbody.append(tr);
}
table.append(thead,tbody);panel.append(table);out.push(panel);
}else out.push(node('p','Nenhum arquivo final ainda.','empty'));
// Replacing an approved final, while the art is still in Arte recebida or Correção;
// in Arte conferida, the queue, the order goes back to Arte recebida first.
if(may('produce')&&['rec','cor'].includes(order.state)&&finalDone(order)&&!order.cancelled_at&&!order.proof_parent){
const open=button('Enviar nova versão',async()=>finalDialog(order,readyFinals(order).map(()=>null),{replace:true}),'btn');
open.prepend(svgIcon(IC.upload,'i m'));open.classList.add('self-start');out.push(open);
}
view.replaceChildren(...out);
}
// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause,
// which never changes after; an Administrador authorizes or declines it,
// never one they opened. Bad art the customer approved is outside the goal.
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de Ajuste Fino',
pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'};
const REWORK_OUTSIDE='arte_cliente';
function reworkForm(order){
const cause=node('select');cause.required=true;
const none=node('option','Escolha a causa');none.value='';cause.append(none);
for(const [value,text] of Object.entries(REWORK_CAUSES)){const o=node('option',text+(value===REWORK_OUTSIDE?' (fora da meta)':''));o.value=value;cause.append(o);}
const size=node('input');size.type='number';size.required=true;size.min='0.01';size.max='1000';size.step='0.01';
size.value=order.snapshot.items.reduce((t,i)=>t+Number(i.metres??i.billed_metres),0).toFixed(2);
const note=node('textarea');note.maxLength=1000;note.placeholder='O que aconteceu (opcional)';
formDialog('Abrir retrabalho no pedido #'+order.number,{host:$('drawer'),width:540,
text:'A causa não muda depois de aberta. O retrabalho conta na meta quando um administrador autoriza.',
fields:[field('Causa',cause),field('Metros refeitos',unit(size,'metros')),field('Observação',note)],label:'Abrir retrabalho',
onsave:async()=>{
await api('/orders/'+order.id+'/reworks',{cause:cause.value,metres:size.value,note:note.value});
say('Retrabalho aberto no pedido #'+order.number+'. Aguarda a autorização de um administrador.');await load();
}});
}
// An input with its unit inside it, on the right.
function unit(input,text){const u=node('span',undefined,'unit');u.append(input,node('span',text));return u;}
function reworkSection(order){
const section=node('section',undefined,'tsection');section.append(node('h4','Retrabalho'));
for(const r of order.reworks){
const box=node('div',undefined,'rework');
box.append(node('b',REWORK_CAUSES[r.cause]+(r.cause===REWORK_OUTSIDE?', fora da meta':'')+', '+metres(r.metres)),
node('span','Aberto por '+r.opened_name+' em '+when(r.opened_at)+(r.printed_name?', impresso por '+r.printed_name:''),'sub'));
if(r.note)box.append(node('span',r.note,'sub'));
if(r.decided_at)box.append(badge((r.authorized?'Autorizado por ':'Não autorizado por ')+r.decided_name+' em '+when(r.decided_at),r.authorized?'ok':'bad',r.decline_reason||''));
else if(may('authorize')&&r.opened_by!==ME.email){
const why=node('input');why.placeholder='Motivo, se não autorizar';why.setAttribute('aria-label','Motivo, se não autorizar');why.maxLength=1000;
const decide=authorized=>async()=>{
await api('/reworks/'+r.id+'/decision',{authorized,reason:why.value});
say(authorized?'Retrabalho autorizado.':'Retrabalho não autorizado.');await load();};
const row=node('div',undefined,'decide');
row.append(button('Autorizar',decide(true),'btn pri'),why,button('Não autorizar',decide(false),'btn ghost'));
box.append(row);
}else box.append(badge('Aguardando a autorização de um administrador','warn'));
section.append(box);
}
return section;
}
// Histórico: the newest first, the order's arrival last.
function historyView(order,rows,view){
const list=node('ol',undefined,'hist');
const entry=(title,who,at,reason)=>{
const li=node('li'),text=node('span');
text.append(node('b',title),node('span',who+(reason?': '+reason:''),'sub'));
const time=node('time',when(at));time.dateTime=at;
li.append(node('i'),text,time);return li;
};
for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason));
for(const item of order.snapshot.items){
if(item.residue_accepted_at)list.append(entry('Resíduo aceito','cliente',item.residue_accepted_at,
item.residue_accepted+' pontos'));
if(item.stroke_choice_at)list.append(entry('Traço fino aceito','cliente',item.stroke_choice_at,
item.stroke_choice==='client_c3'?'proteger chapado (C3)':'imprimir assim (C1)'));
}
list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
order.created_at,paidOutside(order)?order.payment.note:''));
view.replaceChildren(list);
}