Files
dtf-system/web/kanban.js
Cauê Faleiros 9ae865619e fix: Abrir e conferir sends a paid Ajuste Fino order to Tratar a arte
DTF-WEB-A: closing the viewer on an order with Ajuste Fino or Redesenho
paid approved the original as the final and then tried the move, which
the server refused (the queue needs the treated PNG). The dialog now says
the treated art is missing and opens Tratar a arte, approving nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 14:24:51 -03:00

2662 lines
170 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: production board, quote review, payments and integrations.
Everything is built with textContent; nothing from an order or a customer is
ever parsed as HTML. The previous screen is in git tag ui-v1. */
const $ = id=>document.getElementById(id);
// Remove credentials saved by older local builds. Only HttpOnly sessions now.
sessionStorage.removeItem('dtf-operator');
// Dropstar's flow (2026-10-23): Arte conferida is the print queue and Revisão
// checks the printed sheet. 'fil' (Fila de impressão) is only in older history.
const FLOW=['rec','tra','imp','rev','fin'];
const FORMER_STATES={fil:'Fila de impressão'};
const stateName=s=>board.states[s]||FORMER_STATES[s]||s;
const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas',premium:'DTF Têxtil Premium · folha montada'};
// Loose art the Site split by stroke (item 17): each sheet is an item of its own.
const productName=item=>PRODUCT[item.mode]+(item.split?' · folha '+item.split.part+' de '+item.split.of+
', '+(item.stroke_class==='C3'?'chapado':'traço fino'):'');
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa',premium:'Premium'};
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'};
// Payment outcomes are recorded by the API in English; operators read Portuguese.
function outcomeText(outcome){
const rules=[
[/^refused: paid (\S+) but quote total is (\d+)/,m=>'valor pago ('+(m[1]==='None'?'não informado':money(Number(m[1])))+') diferente do total da cotação ('+money(Number(m[2]))+')'],
[/^refused: quote expired/,()=>'a cotação venceu antes do pagamento'],
[/^refused: quote not found/,()=>'cotação não encontrada'],
[/^refused: quote was discarded/,()=>'a cotação tinha sido descartada no Kanban'],
[/^refused: reference is not a quote id/,()=>'a referência do pagamento não é uma cotação'],
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'],
[/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]],
];
for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
return outcome;
}
let board=null;
let tab='board', openOrder=null, openToken=0;
const boardFilter={product:'',machine:'',delivery:'',origin:'',status:''};
// Layout versions the server takes (app/core/models.py PRODUCTION_VERSIONS).
const LAYOUT_VERSIONS=[2,3];
let quoteKind='pending', pickedQuote=null;
let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=null;
// Uploads that have an artwork picture (the customer's browser made it). Every
// list the API returns says which, so only pictures that exist are asked for.
// The signed-in operator and what their profile allows (app/core/auth.py).
let ME=null;
const may=cap=>!!ME?.can?.includes(cap);
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor',financeiro:'Financeiro',expedicao:'Expedição'};
// Which moves this profile makes, and which columns' order it sets: the
// server's own list (app/core/auth.py MOVES), never worked out here.
const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to);
const mayReorder=state=>!!ME?.reorder?.includes(state);
// The session's machine (item 12). An operator pulls any card from the queue,
// which becomes their machine's, and moves only their machine's cards; the
// others show, without drag or buttons.
const myMachine=()=>ME?.machine||null;
const isMine=order=>!!myMachine()&&order.machine?.id===myMachine().id;
const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order);
// Which tabs each capability opens.
// Vendedor and Financeiro consult Cotações and Números without acting there.
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')||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');
}
const THUMBS=new Set();
// Company names by CNPJ, from the public registry (app/cnpj.py).
const NAMES=new Map();
const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id));
for(const [cnpj,name] of Object.entries(r?.names||{}))NAMES.set(cnpj,name);return r;};
let olderFinished=[], finishedMore=null;
const money=cents=>(cents/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
const metres=value=>Number(value).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+' m';
const when=value=>new Date(value).toLocaleString('pt-BR',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});
function ago(value){
const minutes=Math.max(0,Math.round((Date.now()-new Date(value))/60000));
if(minutes<60)return 'há '+minutes+' min';
const hours=Math.round(minutes/60);
return hours<48?'há '+hours+' h':'há '+Math.round(hours/24)+' dias';
}
// The customer's WhatsApp opens the conversation, for messages the system does
// not send (a correction, a question about the artwork).
function whatsappLink(zap){
const digits=String(zap||'').replace(/\D/g,'');
if(digits.length<10)return null;
return 'https://wa.me/'+(digits.length<=11?'55':'')+digits;
}
function node(tag,text,className){const e=document.createElement(tag);if(text!==undefined&&text!==null)e.textContent=text;if(className)e.className=className;return e;}
function button(text,fn,className='btn'){
const b=node('button',text,className);b.type='button';
b.onclick=async event=>{event.stopPropagation();b.disabled=true;try{await fn();}catch(e){say(e.message,true);}finally{b.disabled=false;}};
return b;
}
// Messages are notifications, not state: they clear themselves. Errors stay
// longer so they can be read; a caller can hold one for as long as it needs.
let sayTimer=null;
function say(text,error=false,ms){
clearTimeout(sayTimer);
for(const id of ['status','login-status']){$(id).textContent=text||'';$(id).classList.toggle('error',!!error);}
if(text)sayTimer=setTimeout(()=>say(''),ms??(error?8000:4000));
}
// The redesign's icons (the design canvas of 2026-10-30): one 20 px grid,
// square ends, drawn by svgIcon with the classes i (20), i m (16), i s (14).
const C=(x,y,r)=>'M'+(x-r)+' '+y+'a'+r+' '+r+' 0 1 0 '+(2*r)+' 0a'+r+' '+r+' 0 1 0 '+(-2*r)+' 0';
const IC={
search:C(8.75,8.75,5.75)+' M13 13l4.25 4.25',
filter:'M3 5h14 M5.5 10h9 M8 15h4',
download:'M10 3v9.5 M6 8.75l4 4 4-4 M3.75 16.75h12.5',
upload:'M10 13V3.5 M6 7.25l4-4 4 4 M3.75 16.75h12.5',
close:'M5 5l10 10 M15 5L5 15',
copy:'M7 7h9.25v9.25H7z M4 13V3.75h9',
phone:'M6.75 3h-3v1.5A12.25 12.25 0 0 0 15.5 16.25H17v-3l-3.25-1-1.5 1.5a8 8 0 0 1-4.25-4.25l1.5-1.5z',
chat:'M3.25 16.75l1-3.25a6.75 6.75 0 1 1 2.5 2.5z',
truck:'M2.75 5h9.5v8.5h-9.5z M12.25 8h3l2 2.75v2.75h-5 '+C(5.75,15.25,1.5)+' '+C(14.5,15.25,1.5),
pin:'M10 17.5s-5.25-4.75-5.25-9a5.25 5.25 0 0 1 10.5 0c0 4.25-5.25 9-5.25 9z '+C(10,8.5,1.75),
check:'M4 10.5l3.75 3.75L16 6',
alert:C(10,10,7.25)+' M10 6v5 M10 13.25v1',
info:C(10,10,7.25)+' M10 9v4.5 M10 6.25v.75',
arrow:'M4 10h11 M11 5.5l4.5 4.5-4.5 4.5',
left:'M12 5.5L7.5 10l4.5 4.5',
right:'M8 5.5l4.5 4.5L8 14.5',
first:'M10 5.5L5.5 10l4.5 4.5 M15 5.5L10.5 10l4.5 4.5',
last:'M5 5.5l4.5 4.5L5 14.5 M10 5.5l4.5 4.5L10 14.5',
down:'M5.5 8l4.5 4.5L14.5 8',
plus:'M10 4v12 M4 10h12',
more:C(5,10,.9)+' '+C(10,10,.9)+' '+C(15,10,.9),
folder:'M2.75 5h5l1.5 1.75h8v9.5H2.75z',
mail:'M2.75 4.75h14.5v10.5H2.75z M2.75 5l7.25 6 7.25-6',
box:'M3 6.5L10 3l7 3.5v7L10 17l-7-3.5z M3 6.5l7 3.5 7-3.5 M10 10v7',
file:'M5 2.75h6.5L15 6.25v11H5z M11.5 2.75v3.5H15 M7.5 10.5h5 M7.5 13.5h5',
calendar:'M3 4.75h14v12H3z M3 8.25h14 M7 3v3 M13 3v3',
card:'M2.75 5h14.5v10H2.75z M2.75 8.25h14.5',
bag:'M4 7h12l-1 10.25H5z M7.25 7V5.5a2.75 2.75 0 0 1 5.5 0V7',
key:C(6.5,13.5,3.25)+' M8.8 11.2L16 4 M13.5 6.5l2 2',
database:'M3.75 5c0-1.25 2.8-2.25 6.25-2.25s6.25 1 6.25 2.25-2.8 2.25-6.25 2.25S3.75 6.25 3.75 5z M3.75 5v10c0 1.25 2.8 2.25 6.25 2.25s6.25-1 6.25-2.25V5 M3.75 10c0 1.25 2.8 2.25 6.25 2.25s6.25-1 6.25-2.25',
refresh:'M16.25 10a6.25 6.25 0 1 1-1.83-4.42 M16.5 3.25V6.5h-3.25',
rework:'M15.5 7.5A6 6 0 0 0 4.25 9 M4.5 12.5A6 6 0 0 0 15.75 11 M15.75 3.75V7.5H12 M4.25 16.25V12.5H8',
back:'M8 5L4 9l4 4 M4 9h8a4 4 0 0 1 0 8h-2',
ban:C(10,10,7.25)+' M5 15L15 5',
logout:'M8 3.25H3.75v13.5H8 M12 6.5l3.5 3.5-3.5 3.5 M15.5 10H7.5',
printer:'M5.75 7.5V3h8.5v4.5 M5.75 14H3V7.5h14V14h-2.75 M5.75 11.25h8.5v5.75h-8.5z',
eye:'M2.5 10s2.75-5.25 7.5-5.25S17.5 10 17.5 10s-2.75 5.25-7.5 5.25S2.5 10 2.5 10z '+C(10,10,2.25),
camera:'M2.75 6.5h3.25l1.25-2.5h5.5l1.25 2.5h3.25v9.5H2.75z '+C(10,11.25,2.75),
edit:'M12.5 4l3.5 3.5L7.5 16H4v-3.5z M10.5 6l3.5 3.5',
user:C(10,6.25,3.25)+' M3.75 17c.6-3.2 3.1-5 6.25-5s5.65 1.8 6.25 5',
link:'M8.5 6.5H6a3.25 3.25 0 0 0 0 6.5h2.5 M11.5 6.5H14a3.25 3.25 0 0 1 0 6.5h-2.5 M7 9.75h6',
};
function svgIcon(d,className='i'){
const ns='http://www.w3.org/2000/svg',svg=document.createElementNS(ns,'svg'),path=document.createElementNS(ns,'path');
svg.setAttribute('class',className);svg.setAttribute('viewBox','0 0 20 20');svg.setAttribute('aria-hidden','true');
path.setAttribute('d',d);svg.append(path);return svg;
}
// ---- Badges: one system on every screen (canvas "Kanban DTF — redesign", v2) --
// The grade pill is coloured in bands (90/75/60/40), those of the old price
// ladder; the grade no longer sets the price (2026-10-23). The bands are the same
// for all four products; product, status and warnings are pills with text.
const GRADE_BANDS=[[90,'g90'],[75,'g75'],[60,'g60'],[40,'g40'],[0,'g0']];
function gradePill(grade){
const n=grade===null||grade===undefined||grade===''?NaN:Number(grade);
const ok=Number.isFinite(n);
const b=node('span',ok?String(n):'—','grade '+(ok?GRADE_BANDS.find(([min])=>n>=min)[1]:'gnone'));
b.title=ok?'Nota da arte: '+n:'Sem nota: conferência manual';return b;
}
const lowestGrade=items=>{const g=items.map(i=>Number(i.grade)).filter(Number.isFinite);return g.length?Math.min(...g):null;};
function badge(text,tone='',title=''){const b=node('span',text,'pill '+tone);if(title)b.title=title;return b;}
const cm=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:1});
// The machine sheet shows metres with one decimal even when it is a round number.
const m1=v=>Number(v).toLocaleString('pt-BR',{minimumFractionDigits:1,maximumFractionDigits:1});
const plural=(n,one,many)=>n+' '+(n===1?one:many);
// The customer's CPF or CNPJ, formatted, and which of the two it is.
function cnpj(value){const d=String(value||'').replace(/\D/g,'');return d.length===14?d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'):d.length===11?d.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/,'$1.$2.$3-$4'):String(value||'');}
const docKind=value=>String(value||'').replace(/\D/g,'').length===11?'CPF':'CNPJ';
function copyButton(text,label){
const b=node('button',undefined,'copy');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(svgIcon(IC.copy,'i s'));
b.onclick=async e=>{e.stopPropagation();try{await navigator.clipboard.writeText(text);say('Copiado.');}catch(_){say('Não foi possível copiar.',true);}};
return b;
}
// Facts as a grid of small labelled boxes; empty values are left out.
function facts(pairs){
const dl=node('dl',undefined,'factgrid');
for(const [k,v] of pairs){if(v===null||v===undefined||v==='')continue;const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);}
return dl;
}
// Who is buying: a name when the order has one (the customer's, or whoever
// receives the delivery), else the e-mail. With a name, the e-mail is the
// second line, still searchable.
function buyer(content){
const c=content.customer||{}, company=NAMES.get(String(c.cnpj||'').replace(/\D/g,''));
// The trade name people know the shop by, else its razão social.
const name=(c.name||company?.trade||company?.legal||content.destination?.recipient||'').trim();
return {title:name||c.mail, mail:name?c.mail:'', legal:company?.legal||''};
}
// The quote's latest payment attempt as a badge; none means nobody tried yet.
function paymentBadge(p){
if(!p)return null;
const hour=v=>new Date(v).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'});
const tried=' · tentativa '+when(p.created_at);
if(p.method==='pix'){
if(p.status==='approved')return badge('✓ PIX pago','ok');
const live=p.status==='pending'&&p.expires_at&&new Date(p.expires_at)>Date.now();
return live?badge('PIX gerado · expira '+hour(p.expires_at),'info','O cliente gerou o código'+tried)
:badge('! PIX expirou sem pagamento','warn','O código venceu e o cliente ainda pode gerar outro'+tried);
}
if(p.status==='approved')return badge('✓ Cartão aprovado','ok');
if(p.status==='rejected')return badge('! Cartão recusado','bad',(p.message||'Recusado')+(p.status_detail?' ('+p.status_detail+')':'')+tried);
if(p.status==='pending')return badge(p.status_detail==='pending_challenge'?'Cartão aguardando o banco':'Cartão em análise','info',tried.slice(3));
return badge('Pagamento '+p.status,'',tried.slice(3));
}
// What the customer calls the order (the id's first 8 characters, as the
// server's order_code); the # number is the operators'.
const orderCode=id=>String(id).replace(/-/g,'').slice(0,8).toUpperCase();
// The order's files start with this (app/printjobs.py): pasted into the folder's
// search it finds them, and the dash keeps DTF-23 from finding DTF-230.
const fileCode=order=>'DTF-'+order.number+'-';
const sheetSize=p=>p?cm(p.film_width_cm)+' × '+cm(p.height_cm)+' cm':null;
const hoursSince=v=>Math.floor((Date.now()-new Date(v))/3600000);
// The freight's weight: what the package weighs and, when Jadlog charges the
// box's size instead (the cubed weight), what it is charged as.
function freightWeight(fr){
const kg=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:2})+' kg';
if(!fr?.weight_kg)return '';
if(fr.real_kg&&Number(fr.real_kg)<Number(fr.weight_kg))return kg(fr.real_kg)+' · cobrado como '+kg(fr.weight_kg)+' pela caixa';
return kg(fr.weight_kg);
}
// A download button: the arrow, then its label.
function downloadButton(text,fn,className){const b=button(text,fn,className);b.prepend(svgIcon(IC.download,'i m'));return b;}
async function api(path,body){
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
const d=await r.json();
if(!r.ok){
const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');
error.status=r.status;
window.dtfObservability?.apiError?.(path,r.status,error.message,d.detail);
throw error;
}
return d;
}
function download(uid,orderId){return async()=>{
const result=await api('/uploads/'+uid+'/download'+(orderId?'?order_id='+encodeURIComponent(orderId):''));
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
};}
// ---- Automatic folder ------------------------------------------------------
// The orders' files, kept by this browser in Dropstar's folders
// (2026-10-26) inside the one chosen, while the Kanban is open. It is switched
// on in Integrações, on a computer of the factory that reaches the server's
// folder: the folder belongs to that browser, not to the account. Chrome and
// Edge write into the folder chosen, remembered, with one click to release it
// after the browser restarts. Brave has the same API behind a flag that is off
// by default; the card says how to turn it on. Firefox cannot write into a
// chosen folder: there each file entering the queue is downloaded, and
// Firefox's own download folder is set to FlexiPRINT's.
const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1);
r.onupgradeneeded=()=>r.result.createObjectStore('kv');r.onsuccess=()=>ok(r.result);r.onerror=()=>fail(r.error);}));
const run=async(mode,fn)=>{const db=await open();return new Promise((ok,fail)=>{const t=db.transaction('kv',mode);const req=fn(t.objectStore('kv'));
t.oncomplete=()=>ok(req?.result);t.onerror=()=>fail(t.error);});};
return {get:k=>run('readonly',s=>s.get(k)),set:(k,v)=>run('readwrite',s=>s.put(v,k)),del:k=>run('readwrite',s=>s.delete(k))};})();
const BRAVE_FLAG='brave://flags/#file-system-access-api';
// Where an order's file is, by its stage: it arrives in Arte recebida, moves
// to Arte conferida (the queue) with the card and stays there while it
// prints, goes to Revisão with the card, then to Finalizado, kept 30 days.
// Correção, a cancellation or a deletion takes it out; a replaced final is
// swapped. Numbered as Dropstar set them (2026-10-30), so a folder listing
// shows the flow's order; 3. Imprimindo is where the machines' hot folders go.
const STAGE_FOLDERS={rec:'1. Arte recebida',tra:'2. Arte conferida',imp:'2. Arte conferida',rev:'4. Revisão',fin:'5. Finalizado'};
const PRINTING_FOLDER='3. Imprimindo';
// The names before 2026-10-30: their files move to the new ones, and the old
// folder goes once it is empty.
const OLD_FOLDERS=['3. Finalizado'];
const KEEP_FINISHED_DAYS=30;
// The pickup receipts (item 14): the counter's print queue watches this one.
const RECEIPTS_FOLDER='Recibos';
// The review photos and videos (front 2), written once and never removed.
const REVIEWS_FOLDER='Revisões';
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null,
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
// When the folders were chosen: every order paid since then ends up in them,
// even one that went through while this computer was off (Dropstar's rules,
// 2026-10-26). Folders chosen before this existed count from their first round.
async function folderSince(reset=false){
let since=reset?null:await kv.get('folder-since').catch(()=>null);
if(!since){since=new Date().toISOString();await kv.set('folder-since',since).catch(()=>{});}
return FOLDER.since=since;
}
// Switched on: a chosen folder released, or automatic downloads.
const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
// The three folders started their own record: files saved by the single
// folder of before 2026-10-26 are left where they are.
const savedKey=()=>FOLDER.mode==='folder'?'stages:'+FOLDER.handle.name:'saved:downloads';
// What this folder received, by upload: its order, item, name, the folder it
// is in and, in Finalizado, since when. Older versions kept only the upload ids.
const savedMap=list=>new Map((list||[]).map(e=>typeof e==='string'?[e,{place:'done'}]:e));
const loadSaved=async()=>savedMap(await kv.get(savedKey()).catch(()=>null));
const keepSaved=()=>kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{});
async function restoreFolder(){
if(FOLDER.mode==='downloads'){
try{FOLDER.downloads=localStorage.getItem('dtf-auto-downloads')==='1';}catch{}
if(FOLDER.downloads)FOLDER.saved=await loadSaved();
return;
}
if(FOLDER.mode!=='folder')return;
try{FOLDER.handle=await kv.get('folder')||null;
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
FOLDER.saved=await loadSaved();await folderSince();
if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos nas pastas, abra Integrações e clique em “Liberar pasta”.',false,10000),2500);}}
catch{FOLDER.handle=null;}
}
// The folder's row in Integrações, redrawn whenever its state changes. The
// row says what is happening; the how-to and the secondary buttons are under
// "Detalhes".
function folderCard(){
const name='Pastas dos pedidos', h=FOLDER.handle;
const act=(text,fn)=>button(text,fn,'btn');
const ghost=(text,fn)=>button(text,fn,'btn ghost');
const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;};
let row;
if(FOLDER.mode==='none'){
if(FOLDER.brave){
const first=node('li','Copie este endereço: ');first.append(node('code',BRAVE_FLAG,'flag'));
row=integration({name,state:'Desligada no Brave',tone:'warn',summary:'O Brave bloqueia o acesso a pastas. Dá para liberar em 1 minuto.',
actions:[act('Copiar endereço',async()=>{await navigator.clipboard.writeText(BRAVE_FLAG);say('Endereço copiado: cole na barra do Brave.');})],
details:[steps(first,'Cole na barra do Brave e mude “File System Access API” para “Enabled”.','Reinicie o Brave e volte aqui.'),
node('p','Ou abra o Kanban no Chrome ou no Edge, que já vêm com isso ligado.')]});
}else row=integration({name,state:'Não funciona aqui',tone:'off',summary:'Abra o Kanban no Chrome ou no Edge para salvar numa pasta.'});
}else if(FOLDER.mode==='downloads'){
const how=[steps('No Firefox, abra Configurações → Geral → Arquivos e aplicativos.',
'Em “Salvar arquivos em”, escolha a pasta que o FlexiPRINT lê.','Desmarque “Sempre perguntar onde salvar arquivos”.'),
node('p','Use um perfil do Firefox só para o Kanban: os outros downloads também vão para essa pasta.')];
row=FOLDER.downloads
? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(),
details:how,extra:[ghost('Desligar',()=>setDownloads(false))]})
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as pastas do fluxo pedem o Chrome ou o Edge.',
actions:[act('Ligar',()=>setDownloads(true))],details:how});
}else if(!h){
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos nas pastas do fluxo, de 1. Arte recebida a 5. Finalizado, o recibo de cada retirada em Recibos e as fotos da revisão em Revisões.',
actions:[act('Escolher pasta',chooseFolder)],
details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as pastas do fluxo e move o arquivo conforme o card anda. '+
'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]});
}else if(!FOLDER.granted){
row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.',
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
}else{
row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em '+STAGE_FOLDERS.rec+', passa para '+STAGE_FOLDERS.tra+' quando o card vai para lá '+
'e fica lá enquanto imprime, vai para '+STAGE_FOLDERS.rev+' com o card e para '+STAGE_FOLDERS.fin+' quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'),
node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada. As fotos da revisão vão para '+REVIEWS_FOLDER+' e não saem de lá.'),
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+
'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')],
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
}
row.id='folder-card';return row;
}
function folderCount(){
const n=FOLDER.saved.size;
return (n?n+(n>1?' arquivos salvos':' arquivo salvo'):'nenhum arquivo salvo ainda')+
(FOLDER.last?', o último às '+FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'');
}
// The folder's row and the tab's warning sign, which shows the folder needs a click.
function paintFolder(){
$('folder-card')?.replaceWith(folderCard());
const attention=may('print')&&(FOLDER.mode==='folder'&&!!FOLDER.handle&&!FOLDER.granted||folderActive()&&!!FOLDER.error);
$('badge-integrations').textContent=attention?'!':'';
}
async function chooseFolder(){
let handle;
try{handle=await window.showDirectoryPicker({id:'dtf-fila',mode:'readwrite'});}
catch(e){if(e.name==='AbortError')return;throw e;}
FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null;
FOLDER.saved=await loadSaved();
await kv.set('folder',handle).catch(()=>{});
await folderSince(true);
await makeStageFolders();
paintFolder();say('Pastas '+[...new Set(Object.values(STAGE_FOLDERS))].join(', ')+' criadas dentro de “'+handle.name+'”.');syncFolder(true);
}
async function releaseFolder(){
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
FOLDER.lastSig=null;FOLDER.error='';if(FOLDER.granted)await makeStageFolders();paintFolder();if(FOLDER.granted)syncFolder(true);
}
async function forgetFolder(){
FOLDER.handle=null;FOLDER.granted=false;FOLDER.error='';FOLDER.status='';
await kv.del('folder').catch(()=>{});paintFolder();say('Pasta automática desligada.');
}
async function setDownloads(on){
FOLDER.downloads=on;FOLDER.lastSig=null;FOLDER.error='';FOLDER.status='';
try{localStorage.setItem('dtf-auto-downloads',on?'1':'0');}catch{}
if(on)FOLDER.saved=await loadSaved();
paintFolder();say(on?'Download automático ligado.':'Download automático desligado.');
if(on)syncFolder();
}
// A whole file in a folder: written under another name and renamed at the
// end, so the FlexiPRINT never sees half of it. `source` is a download's body
// or a file.
async function writeWhole(dir,name,source){
const temp=await dir.getFileHandle(name+'.baixando',{create:true});
const out=await temp.createWritable();
try{if(source instanceof Blob){await out.write(source);await out.close();}else await source.pipeTo(out);}
catch(e){await out.abort().catch(()=>{});await dir.removeEntry(temp.name).catch(()=>{});throw e;}
await dir.removeEntry(name).catch(()=>{});
// A browser that cannot rename a file outside its own storage copies it.
try{await temp.move(name);}
catch{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable();
await whole.write(await temp.getFile());await whole.close();await dir.removeEntry(temp.name);}
}
const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true});
// The flow's folders exist from the moment the main one is chosen, empty or not.
const makeStageFolders=()=>Promise.all([...new Set([...Object.values(STAGE_FOLDERS),PRINTING_FOLDER,RECEIPTS_FOLDER,REVIEWS_FOLDER])].map(stageDir));
// Remove a saved file from its folder; one already gone (someone took it) is fine.
async function removeSaved(rec){
const dir=await stageDir(rec.folder);
await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;});
}
// To another of the flow's folders. False when the file is no longer where it was.
async function moveSaved(rec,to){
const from=await stageDir(rec.folder), dest=await stageDir(to);let file;
try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;}
await dest.removeEntry(rec.name).catch(()=>{});
try{await file.move(dest);}
catch{await writeWhole(dest,rec.name,await file.getFile());await from.removeEntry(rec.name);}
return true;
}
// One file from storage, whole, into a folder.
async function fetchInto(dir,file){
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
await writeWhole(dir,file.name,r.body);
}
// The machines' hot folders (item 10): 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/.
// The server says what this computer writes now (claimed for it alone, two
// parts at most per machine); a written part gone from its folder was taken
// by FlexiPRINT, and is never written again; a withdrawn one, from a card that
// left Imprimindo, is deleted if Flexi has not taken it. Returns how many
// parts it wrote.
async function syncHot(){
const hot=await api('/queue/hot',{});
if(!hot.write.length&&!hot.watch.length&&!hot.withdraw.length)return 0;
const root=await stageDir(hot.folder);
const dirOf=async path=>{let dir=root;for(const part of path.split('/'))dir=await dir.getDirectoryHandle(part,{create:true});return dir;};
const missing=e=>e.name==='NotFoundError';
for(const p of hot.withdraw){
await (await dirOf(p.folder)).removeEntry(p.name).catch(e=>{if(!missing(e))throw e;});
await api('/queue/hot/'+p.id,{state:'gone'});
}
for(const p of hot.watch){
try{await (await dirOf(p.folder)).getFileHandle(p.name);}
catch(e){if(!missing(e))throw e;await api('/queue/hot/'+p.id,{state:'consumed'});}
}
let written=0;
for(const p of hot.write){
FOLDER.status='Gravando na hot folder '+p.folder+': '+p.name;paintFolder();
try{await fetchInto(await dirOf(p.folder),p);}
catch(e){await api('/queue/hot/'+p.id,{state:'released'}).catch(()=>{});throw e;}
await api('/queue/hot/'+p.id,{state:'written'});written++;
}
return written;
}
// Bring the folders in line with the board: remove the files of orders that
// were cancelled, deleted, sent back for correction or given another file,
// and those kept their days in Finalizado; move each file to its stage's
// folder; download what arrived in Arte recebida or Arte conferida. A file
// someone took out is downloaded again only when its order moves on. After a
// board load it asks only when something it follows changed; the folder's
// own timer always asks, since another computer may have moved the order.
async function syncFolder(force=false){
if(!folderActive()||FOLDER.busy||!board||!may('print'))return;
const stages=FOLDER.mode==='folder';
const follows=stages?['rec','tra','imp','rev','fin','cor']:['tra'];
const sig=board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at)
.map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')+':'+(o.reviews?.length||0)).join(',');
if(!force&&sig===FOLDER.lastSig)return;
FOLDER.busy=true;
try{
if(stages)await makeStageFolders();
const held=stages?[...new Set([...FOLDER.saved.values()].filter(r=>!r.review).map(r=>r.order).filter(Boolean))].slice(-1000):[];
const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
// By file: an item over 15 m is several parts (item 13), each its own file.
const wanted=new Map(files.map(f=>[f.upload_id,f]));
const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
let removed=0, moved=0, saved=0;
const record=async(uid,file,folder)=>{
FOLDER.saved.set(uid,{order:file.order,item:file.item,name:file.name,folder,
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
FOLDER.last=new Date();await keepSaved();};
if(stages)for(const [uid,rec] of [...FOLDER.saved]){
if(!rec.order||!rec.folder)continue;
const state=states[rec.order], target=STAGE_FOLDERS[state];
const now=wanted.get(uid);
const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order);
const kept=rec.folder===STAGE_FOLDERS.fin&&Date.now()-(rec.at||0)>KEEP_FINISHED_DAYS*86400000;
if(!target||replaced||kept){await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();continue;}
if(rec.folder===target)continue;
if(await moveSaved(rec,target)){await record(uid,{...rec},target);moved++;continue;}
// Not where it was: downloaded again into its new folder while storage has it.
if(now&&now.upload_id===uid){await fetchInto(await stageDir(target),now);await record(uid,now,target);moved++;}
else{FOLDER.saved.delete(uid);await keepSaved();}
}
const hot=stages?await syncHot():0;
if(stages)for(const old of OLD_FOLDERS)
if(![...FOLDER.saved.values()].some(r=>r.folder===old))await FOLDER.handle.removeEntry(old).catch(()=>{});
// New files, each into its stage's folder: the server sends those in Arte
// recebida and Arte conferida, and the orders paid since the folders were
// chosen in any stage, so what passed while this computer was off comes in
// too. An order already printing when the folders were chosen is the room's.
const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id)&&(stages?!!STAGE_FOLDERS[f.state]:f.state==='tra'));
for(const [i,file] of pending.entries()){
FOLDER.status=(stages?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
say(FOLDER.status,false,60000);
if(stages){
await fetchInto(await stageDir(STAGE_FOLDERS[file.state]),file);
await record(file.upload_id,file,STAGE_FOLDERS[file.state]);
}else{
// Firefox writes it as .part and renames it when whole.
const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click();
await new Promise(r=>setTimeout(r,900));
FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name});
FOLDER.last=new Date();await keepSaved();
}
saved++;
}
// Each pickup receipt saved once, by the computer that takes it, so the
// counter's queue never prints one twice; one this computer could not
// save goes back for another to take. Written whole, then named .pdf.
let printed=0;
for(const r of receipts){
try{await api('/orders/'+r.order+'/receipt/claim',{});}catch(e){if(e.status===409)continue;throw e;}
try{
const res=await fetch('/api/operator/orders/'+r.order+'/receipt');
if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').');
await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res.body);printed++;
}catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;}
}
// The review photos and videos, once each, into Revisões/. They are never
// removed from there: the folder is the room's evidence of the check.
let reviewSaved=0;
if(stages)for(const review of reviews){
const key='review:'+review.upload_id;
if(FOLDER.saved.has(key))continue;
FOLDER.status='Salvando revisão: '+review.name;paintFolder();
const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view');
const res=await fetch(view.url,{referrerPolicy:'no-referrer'});
if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').');
await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res.body);
FOLDER.saved.set(key,{order:review.order,name:review.name,review:true});
FOLDER.last=new Date();await keepSaved();reviewSaved++;
}
FOLDER.lastSig=sig;FOLDER.error='';
FOLDER.status='';
if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.');
if(hot)say('Gravados '+hot+' arquivo(s) na hot folder da máquina.');
if(printed)say(printed+' recibo(s) de retirada salvos em '+RECEIPTS_FOLDER+'.');
if(reviewSaved)say(reviewSaved+' foto(s)/vídeo(s) de revisão salvos em '+REVIEWS_FOLDER+'.');
if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.');
if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.');
}catch(e){
if(e.name==='NotAllowedError')FOLDER.granted=false;
else if(e.name==='NotFoundError')FOLDER.error='A pasta “'+FOLDER.handle?.name+'” não foi encontrada. Ela foi apagada ou a rede caiu? Escolha a pasta de novo.';
else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.';
FOLDER.status='';say('Pastas automáticas: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true);
}finally{FOLDER.busy=false;paintFolder();}
}
setInterval(()=>syncFolder(true),30000);
async function downloadQueue(){
const {files}=await api('/queue/finals');
if(!files.length){say('Nenhum arquivo final aprovado na fila.');return;}
say('Baixando '+files.length+(files.length>1?' arquivos':' arquivo')+' da fila… Se o navegador perguntar, permita vários downloads.',false,8000);
// One at a time: browsers drop clicks that come too close together.
for(const file of files){
const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click();
await new Promise(r=>setTimeout(r,700));
}
}
// What the manifest says about contraction: the class to print with, what the
// Site measured, the customer's choice on a mixed sheet and who changed it.
function contractionRecord(item,chosen){
if(!item.stroke_class&&!chosen)return null;
return {class:chosen?.class||measuredClass(item),measured_class:item.stroke_class||null,measured_px:item.stroke_px||null,
customer_choice:item.stroke_choice||null,chosen_by:chosen?.by||null};
}
function manifest(production,contraction=null){
if(contraction)production={...production,contraction};
const url=URL.createObjectURL(new Blob([JSON.stringify(production,null,2)],{type:'application/json'}));
const link=node('a');link.href=url;link.download='dtf-layout-'+production.sources[0].upload_id.slice(0,8)+'.json';
link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
// ---- Artwork pictures -------------------------------------------------------
// The picture of one upload, or null when the browser could not make one (a
// CDR, a PSD, an order from before pictures existed).
function artPicture(uid,alt=''){
if(!uid||!THUMBS.has(String(uid)))return null;
const img=node('img');img.src='/api/operator/uploads/'+uid+'/thumbnail';img.alt=alt;img.loading='lazy';img.decoding='async';
// Only a picture still on screen gives up: one dropped by a re-render mid-load is not missing.
img.onerror=()=>{if(!img.isConnected)return;THUMBS.delete(String(uid));img.remove();};
return img;
}
// A small box with the first picture of these items; without one, the layout
// drawing, as before pictures existed.
function artBox(items,className){
const box=node('div',undefined,'art '+className);
const uid=items.flatMap(i=>i.uploads||[]).find(u=>THUMBS.has(String(u)));
const pic=artPicture(uid);
if(pic){box.append(pic);return box;}
const item=items.find(i=>i.production?.placements);
if(item){box.classList.add('layout');box.append(layoutPreview(item.production));}
else{box.classList.add('none');box.append(node('span','sem prévia','noart'));}
return box;
}
// An item's artwork (each file's picture) and its layout on the film, as two views.
function itemPreview(item){
const wrap=node('div',undefined,'preview');
const pics=(item.uploads||[]).map((uid,i)=>artPicture(uid,'Arte '+(i+1))).filter(Boolean);
const layout=item.production?.placements?layoutPreview(item.production):null;
if(!pics.length){if(layout)wrap.append(layout);return wrap;}
wrap.classList.add('with-art');
const art=node('div',undefined,'view art');art.append(...pics);
if(!layout){wrap.append(art);return wrap;}
const film=node('div',undefined,'view layout');film.append(layout);film.hidden=true;
const tabs=node('div',undefined,'ptabs');
const pick=(show)=>{art.hidden=show!=='art';film.hidden=show!=='film';
for(const b of tabs.children)b.setAttribute('aria-pressed',String(b.dataset.view===show));};
for(const [view,label] of [['art','Arte'],['film','Montagem']]){
const b=node('button',label);b.type='button';b.dataset.view=view;b.setAttribute('aria-pressed',String(view==='art'));
b.onclick=e=>{e.stopPropagation();pick(view);};tabs.append(b);}
wrap.append(tabs,art,film);return wrap;
}
// ---- Loading and tabs ------------------------------------------------------
// What the last load saw, so the next one can tell what is new.
let seenOrders=null, seenPending=null, unseen=0;
async function load(quiet=false){
try{
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
board=absorb(loaded);ME=me;
window.dtfEnvironment=me.sentry_environment||me.environment;
window.dtfRelease=me.sentry_release||undefined;
window.dtfObservability?.start?.(me.sentry_dsn_web,'kanban');
applyRole();paintMyMachine();
noticeNew(quiet);
const known=new Set(board.orders.map(o=>o.id));
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
if(finishedMore===null)finishedMore=board.finished_total>board.finished_shown;
$('login').hidden=true;$('app').hidden=false;
$('sync-at').textContent='Atualizado às '+new Date().toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'});
if(!quiet&&tinyNotice)say(tinyNotice.replace(/^ · /,''),false,6000);
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.
if(e.status===401){say('');return;}
say(e.message,true);
}
}
// The page's name in the top bar; Produção also says what is open.
const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',site:'Site',integrations:'Integrações',users:'Usuários',montar:'Montar folha'};
function showTab(name){
tab=name;$('tab-quotes').classList.remove('reviewing');
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
$('page-title').textContent=PAGE_TITLES[name];$('board-summary').hidden=name!=='board';$('filter-open').hidden=name!=='board';
$('more-nav').classList.toggle('on',['integrations','users'].includes(name));
for(const id of ['board','quotes','payments','stats','site','integrations','users','montar'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
}
function render(){
$('who').textContent=ME?(ME.name||ME.email):'';
$('who-role').textContent=ME?(ROLE_NAMES[ME.role]||ME.role)+', '+ME.email:'';
$('who-initials').textContent=ME?initialsOf(ME.name||ME.email):'';
$('initials').textContent=ME?initialsOf(ME.name||ME.email):'·';
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
tinyHeader();renderBoard();renderIntegrations();
$('badge-more').textContent=$('badge-integrations').textContent;
// Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador};
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
}
// ---- Production board ----------------------------------------------------
function printState(order){
if(order.state==='imp'||order.state==='rev')return {text:'Final aprovado',tone:'ok'};
if(order.state==='fin')return {text:'Concluído',tone:'ok'};
if(order.state==='cor')return {text:'Aguardando o cliente',tone:''};
if(finalDone(order))return {text:'Final aprovado',tone:'ok'};
if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'};
const rows=order.print_files||[], items=order.snapshot.items.length;
const ready=rows.filter(r=>r.status==='ready').length;
if(rows.some(r=>r.status==='failed'||r.timed_out))return {text:'Falhou ao gerar',tone:'warn'};
if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''};
if(ready===items)return {text:'Falta aprovar o final',tone:'warn'};
if(rows.some(r=>r.status==='manual'||r.status==='failed'))
return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'};
return {text:'Sem arquivo gerado',tone:'warn'};
}
const stalled=order=>!!order.late;
// "Aguardando contato": a word with the customer is needed before printing.
// A mark on the card, not a stage; a finished order no longer needs it.
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
// The room marks "Prova OK" once it is checked; without it, no Finalizado.
const PROOF_ABOVE_METRES=10;
const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.';
const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES;
const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent;
// The proof card (app/proof.py): the order's own card waits outside the queue
// for its answer; an order from before the cards has none.
const waitingProof=order=>!!order.proof_card&&!order.proof_card.proof_result&&!order.proof_ok_at;
const proofRejected=order=>order.proof_card?.proof_result==='rejected'&&!order.proof_ok_at;
async function proofAnswer(order,result,reason=''){
await api('/orders/'+order.id+'/proof-answer',{result,reason});await load();
say(result==='ok'?'Prova OK: o pedido #'+order.proof_parent.number+' entra na fila.':'Prova reprovada: o pedido #'+order.proof_parent.number+' voltou para Arte recebida.');
}
function proofReject(order){
const reason=node('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=3;
formDialog('Prova reprovada',{host:$('drawer'),label:'Reprovar a prova',tone:'red',
text:'O pedido #'+order.proof_parent.number+' volta para Arte recebida com o motivo, e este card de prova encerra.',
fields:[field('Motivo',reason)],onsave:async()=>{await proofAnswer(order,'rejected',reason.value);}});
}
const TREATED_NOTE='O arquivo final foi preparado pela equipe, não é a arte que o cliente mandou.';
// Mirrored by the customer (UV only, web/site-pdf.js): the room checks it before printing.
const mirroredItem=item=>!!item.production?.sources?.some(source=>source.mirrored);
const MIRROR_NOTE='O cliente espelhou a arte: confira antes de imprimir';
// Residue dots under 2 mm the customer accepted printing (Dropstar, 2026-10-29).
const residueNote=item=>{const many=item.residue_accepted>1;
return item.residue_accepted+(many?' pontos menores':' ponto menor')+' que 2 mm, que '+(many?'podem':'pode')+' se perder no recorte';};
const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imprimir com '+residueNote(item));
// Two places per machine in Imprimindo (app/machines.py): the first to come
// in is printing, the next is being ripped meanwhile.
const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'],
ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']};
// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30):
// "parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last from
// the hot folder while the one before it prints.
function partsStep(order){
const hot=order.hot;if(!hot||hot.parts<2)return null;
const n=hot.parts, t=hot.taken;
if(!t)return ['Parte 1/'+n+' na hot folder','wait'];
if(t===1)return ['Parte 1/'+n+' ripando','rip'];
return ['Parte '+(t-1)+'/'+n+' imprimindo · '+t+'/'+n+' ripando','live'];
}
async function proofOk(order){
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
}
// Where an order came from (Dropstar's rule D-21): every card says it.
const ORIGINS={site:'Site',dropflow:'Dropflow',atendimento:'Atendimento'};
const ORIGIN_NOTE='Origem do pedido';
const originTag=order=>{const t=node('span',ORIGINS[order.origin]||order.origin,'origin');t.title=ORIGIN_NOTE;return t;};
// The board's filters: one choice per kind, and the kinds combine (Têxtil on
// máquina2, waiting for contact). An empty choice is "all".
const FILTER_TESTS={
site:o=>o.origin==='site',
dropflow:o=>o.origin==='dropflow',
atendimento:o=>o.origin==='atendimento',
textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'||i.mode==='premium'),
uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'),
entrega:o=>!!o.snapshot.destination,
retirada:o=>!o.snapshot.destination,
parados:stalled,
atrasados:stalled,
contato:waitingContact,
prova:proofPending,
manual:o=>['rec','tra'].includes(o.state)&&!finalDone(o)&&(o.print_files||[]).some(r=>
(r.status==='manual'||r.status==='failed')&&!(o.corrections||[]).some(f=>f.item_index===r.item_index)),
};
function matches(order,f=boardFilter){
// A cancelled order shows only under "Cancelados", and only there.
if(!!order.cancelled_at!==(f.status==='cancelados'))return false;
return Object.values(f).every(key=>!key||key==='cancelados'||
(key.startsWith('m:')?order.machine?.id===key.slice(2):FILTER_TESTS[key](order)));
}
// What each choice would show: orders in progress, or every cancelled one.
const filterCount=f=>board.orders.filter(o=>(f.status==='cancelados'||o.state!=='fin')&&matches(o,f)).length;
// The kinds of filter: [value, label in the panel, label on the tag]. The
// product is the segment beside the button, not in the panel.
function filterKinds(){
const kinds=[
{key:'delivery',label:'Envio',options:[['entrega','Entrega'],['retirada','Retirada']]},
{key:'origin',label:'Origem',options:Object.entries(ORIGINS)},
{key:'status',label:'Situação',options:[['atrasados','Fora do tempo aceitável','Atrasados'],
['contato','Aguardando contato'],['prova','Prova a conferir'],['manual','Preparar à mão'],['cancelados','Cancelados']]}];
// A machine, when there is more than one to tell apart.
const machines=(board.machines||[]).filter(m=>m.active||m.open_orders);
if(machines.length>1)kinds.unshift({key:'machine',label:'Máquina',options:machines.map(m=>
['m:'+m.id,m.name+(m.limit_metres&&m.open_metres>m.limit_metres?' · acima do limite':''),m.name])});
return kinds;
}
const PRODUCTS=[['','Todos'],['textil','Têxtil'],['uv','UV']];
const xIcon=()=>svgIcon(IC.close,'i s');
function openFilters(){
const pop=$('filter-pop');
const close=node('button',undefined,'btn sq ghost right');close.type='button';close.setAttribute('aria-label','Fechar filtros');
close.append(svgIcon(IC.close,'i m'));close.onclick=closeFilters;
const head=node('div',undefined,'pophead');head.append(node('b','Filtros'),close);
const groups=filterKinds().map(kind=>{
const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts');
for(const [value,text] of kind.options){
const b=node('button',text,'fopt');b.type='button';b.dataset.kind=kind.key;b.dataset.value=value;
b.append(node('span','','n'));
// A second click on the choice in use takes it off.
b.onclick=()=>{boardFilter[kind.key]=boardFilter[kind.key]===value?'':value;renderBoard();};
opts.append(b);
}
group.append(node('span',kind.label),opts);return group;
});
const clear=node('button','Limpar filtros','btn ghost');clear.type='button';clear.onclick=clearFilters;
const foot=node('div',undefined,'popfoot');foot.append(clear,node('span','','lbl right'));
pop.replaceChildren(head,...groups,foot);pop.hidden=false;$('filter-btn').setAttribute('aria-expanded','true');
filterCounts();pop.querySelector('.fopt')?.focus();
}
function closeFilters(){$('filter-pop').hidden=true;$('filter-btn').setAttribute('aria-expanded','false');}
function clearFilters(){for(const key in boardFilter)if(key!=='product')boardFilter[key]='';renderBoard();}
// Each choice says how many orders it would show with the others kept.
function filterCounts(){
const pop=$('filter-pop');
for(const b of pop.querySelectorAll('.fopt')){
b.classList.toggle('on',boardFilter[b.dataset.kind]===b.dataset.value);
b.setAttribute('aria-pressed',String(boardFilter[b.dataset.kind]===b.dataset.value));
b.querySelector('.n').textContent=String(filterCount({...boardFilter,[b.dataset.kind]:b.dataset.value}));
}
const shown=filterCount(boardFilter);
pop.querySelector('.popfoot .lbl').textContent=plural(shown,'pedido','pedidos');
}
// The product segment, the filters in use as tags beside the button, and the
// button's count.
function renderFilters(){
const kinds=filterKinds();
// A choice that is gone (a machine deleted or switched off) is dropped.
for(const key in boardFilter){if(key==='product')continue;const kind=kinds.find(k=>k.key===key);
if(boardFilter[key]&&!kind?.options.some(([value])=>value===boardFilter[key]))boardFilter[key]='';}
$('product-seg').replaceChildren(...PRODUCTS.map(([value,text])=>{
const b=node('button',text,boardFilter.product===value?'on':'');b.type='button';
b.setAttribute('aria-pressed',String(boardFilter.product===value));
b.append(node('span',String(filterCount({...boardFilter,product:value})),'n'));
b.onclick=()=>{boardFilter.product=value;renderBoard();};return b;}));
const used=kinds.filter(k=>boardFilter[k.key]);
const tags=used.map(kind=>{
const [,text,tag]=kind.options.find(([value])=>value===boardFilter[kind.key]);
const b=node('button',tag||text,'ftag');b.type='button';
b.setAttribute('aria-label','Tirar o filtro '+(tag||text));
const x=node('span',undefined,'x');x.append(xIcon());b.append(x);
b.onclick=()=>{boardFilter[kind.key]='';renderBoard();};return b;});
if(used.length>1){const all=node('button','Limpar','btn ghost');all.type='button';all.onclick=clearFilters;tags.push(all);}
$('filter-tags').replaceChildren(...tags);
$('filter-count').hidden=!used.length;$('filter-count').textContent=String(used.length);
const all=used.length+(boardFilter.product?1:0);$('filter-dot').hidden=!all;$('filter-dot').textContent=String(all);
$('filter-btn').classList.toggle('on',used.length>0);
if(!$('filter-pop').hidden)filterCounts();
}
// Each column's mark (the design canvas): what happens in that stage.
const GLYPH={
rec:'M10 3v8 M6.75 7.75L10 11l3.25-3.25 M3 12h4l1 2h4l1-2h4v4.5H3z',
tra:'M3 5h9 M3 10h9 M3 15h5 M11.5 14.25l2.25 2.25 3.75-4',
imp:'M5.75 7.5V3h8.5v4.5 M5.75 14H3V7.5h14V14h-2.75 M5.75 11.25h8.5v5.75h-8.5z',
cor:'M7.5 4.5L4 8l3.5 3.5 M4 8h8.25a3.75 3.75 0 0 1 0 7.5H9',
rev:'M2.5 10s2.75-5.25 7.5-5.25S17.5 10 17.5 10s-2.75 5.25-7.5 5.25S2.5 10 2.5 10z '+C(10,10,2.25),
fin:C(10,10,7.25)+' M6.5 10.25l2.5 2.5 4.75-5'};
const orderMetres=o=>o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0);
// On a phone the board shows one stage at a time, picked from the chips above it.
let phoneCol='rec';
// Atrasados (front 11): the cards past the stage limit, with the person
// responsible for that column, above the board.
function renderLatebar(){
const bar=$('latebar');
// The top strip is for production delays. A pickup waiting in Finalizado
// keeps its yellow/red card and is counted in Números; it does not push
// every historical finished order across the top of the board.
const late=board.orders.filter(o=>!o.cancelled_at&&!isTest(o)&&o.late&&o.state!=='fin')
.sort((a,b)=>(b.state_hours||0)-(a.state_hours||0));
if(!late.length){bar.hidden=true;bar.replaceChildren();return;}
bar.hidden=false;
const head=node('b','Atrasados ('+late.length+')');bar.replaceChildren(head);
late.slice(0,10).forEach(o=>{
const chip=node('button',undefined,'latechip'+(o.late==='bad'?' bad':''));
chip.type='button';chip.append(node('i'),node('span','#'+o.number+' · '+board.states[o.state]));
chip.title=(o.state_hours??'?')+' h nesta etapa · limite '+(o.limit_hours??'?')+
' h · responsável: '+(o.limit_by||'—');
chip.onclick=()=>openPanel(o.id);bar.append(chip);
});
if(late.length>10)bar.append(node('span','+'+(late.length-10),'lbl'));
if(may('manage'))bar.append(button('Editar tempos',()=>stageLimitsDialog(),'btn ghost'));
}
function renderBoard(){
renderLatebar();
renderFilters();
const active=board.orders.filter(o=>['rec','tra','imp'].includes(o.state)&&!o.cancelled_at);
const open=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length;
$('board-summary').textContent=plural(open,'pedido','pedidos')+', '+metres(active.reduce((s,o)=>s+orderMetres(o),0))+' em produção';
const filtered=Object.entries(boardFilter).some(([key,value])=>value&&key!=='product')||!!boardFilter.product;
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
const column=node('section',undefined,'col');column.dataset.state=state;column.setAttribute('aria-label',title);
// Working columns are queues; Finalizado shows the most recently ready order first.
const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>state==='fin'
? new Date(b.finished_at||b.updated_at)-new Date(a.finished_at||a.updated_at)||b.id.localeCompare(a.id)
: queueKey(a)-queueKey(b)||a.number-b.number);
const head=node('header',undefined,'colhead');
head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')));
const text=node('span',undefined,'coltx');text.append(node('h2',title));
if(state!=='fin')text.append(node('span',orders.length?metres(orders.reduce((s,o)=>s+orderMetres(o),0)):'vazio','colm'));
head.append(text);
// The print queue's files, all at once, to import into FlexiPRINT.
if(state==='tra'&&may('print')&&orders.length){
const all=node('button',undefined,'colbtn tip-l');all.type='button';all.setAttribute('aria-label','Baixar os arquivos da fila');
all.dataset.tip='Baixar os arquivos finais de todos os pedidos da fila, para o FlexiPRINT';all.append(svgIcon(IC.download,'i m'));
all.onclick=async()=>{all.disabled=true;try{await downloadQueue();}catch(e){say(e.message,true);}finally{all.disabled=false;}};
head.append(all);
}
// Finished orders are a recent window, not the whole history: the count is the whole.
head.append(node('span',String(state==='fin'&&!filtered?Math.max(board.finished_total||0,orders.length):orders.length),'coln'));
column.append(head);
// The phone's line over the cards: this stage's metres and the session's machine.
const sum=node('div',undefined,'msum');const total=node('span');
total.append(node('b',state==='fin'?plural(orders.length,'pedido','pedidos'):metres(orders.reduce((t,o)=>t+orderMetres(o),0))),state==='fin'?' recentes':' nesta etapa');
sum.append(total);
if(myMachine()){const m=node('span',undefined,'right mcell');m.append(node('i',undefined,'mdot'),'Máquina ',node('b',myMachine().name));sum.append(m);}
column.append(sum);
if(state==='tra'&&may('print')&&orders.length){
const dl=button('Baixar os arquivos da fila',downloadQueue,'btn mdl');dl.prepend(svgIcon(IC.download,'i m'));column.append(dl);}
if(state==='imp')column.append(...printingLanes(orders));
else if(state==='fin')column.append(...orders.map(miniCard));
else column.append(...orders.map((o,i)=>card(o,state==='tra'?queuePlace(o,orders):null)));
if(state==='fin'&&finishedMore&&!filtered){
const left=Math.max(0,(board.finished_total||0)-orders.length);
const more=node('button',left>50?'Ver mais 50 anteriores':left?'Ver os '+left+' anteriores':'Ver anteriores','moreold');more.type='button';
more.onclick=async()=>{more.disabled=true;try{await loadOlderFinished();}catch(e){say(e.message,true);more.disabled=false;}};
column.append(more);
}
// Dragging only goes forward to the next stage. Going back or asking for a
// correction needs a reason, so those happen in the order panel.
column.ondragover=e=>{
if(dragging?.state===state&&state!=='fin'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;}
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');
if(state==='imp')markLane(column,laneAt(column,e.clientY));};
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');markLane(column,null);clearDrop();}};
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain'));
const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null);
if(!order)return;
try{
if(order.state!==state)await (state==='imp'?pullTo(order,machine):move(order,state,'',machine));
else if(state!=='fin')await reorder(order,column,e.clientY);
}catch(error){say(error.message,true);}
finally{clearDrop();}};
return column;
}));
const cols=[...$('kan').children];
if(!board.states[phoneCol])phoneCol='rec';
$('col-tabs').replaceChildren(...cols.map(col=>{
const st=col.dataset.state, on=st===phoneCol;
const b=node('button',undefined,'mtab'+(on?' on':''));b.type='button';b.setAttribute('role','tab');b.setAttribute('aria-selected',String(on));
b.append(svgIcon(GLYPH[st],'sg'+(st==='cor'?' cor':'')),board.states[st],node('span',col.querySelector('.coln').textContent,'n'));
b.onclick=()=>{phoneCol=st;renderBoard();$('col-tabs').querySelector('.on')?.scrollIntoView({inline:'nearest',block:'nearest'});};
return b;}));
for(const col of cols)col.classList.toggle('pick',col.dataset.state===phoneCol);
}
// Imprimindo, one lane per machine (app/machines.py): its name and places,
// the order printing, the one ripping, then its free place. Every active
// machine has its lane, so a card dragged from the queue can be dropped on
// the machine it goes to print on.
function printingLanes(orders){
const cap=board.printing_cap||2, mine=myMachine()?.id;
const filtered=Object.values(boardFilter).some(Boolean);
const out=[];
const list=(board.machines||[]).filter(m=>m.active||orders.some(o=>o.machine?.id===m.id));
for(const m of list){
const here=orders.filter(o=>o.machine?.id===m.id)
.sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1));
// Filtered, a lane with nothing to show stays out; unfiltered, the places count every order.
if(filtered&&!here.length)continue;
const n=filtered?here.length:Math.max(m.states?.imp||0,here.length);
const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));lane.dataset.machine=m.id;
const load=n>cap?'acima do limite':n>=cap?'cheia':plural(cap-n,'vaga','vagas');
lane.append(svgIcon(IC.printer,'i s'),node('b',m.name));
// The machine's sheet opens here; an alert due shows a warning dot with its text.
const alerts=m.alerts||[];
if(alerts.length){const mark=node('i',undefined,'lanealert');mark.title=alerts.map(a=>a.text).join(' · ');
mark.setAttribute('aria-hidden','true');lane.append(mark);}
lane.append(node('span',(m.id===mine?'sua máquina · ':'')+load));
lane.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':'');
lane.tabIndex=0;lane.setAttribute('role','button');lane.setAttribute('aria-label','Ficha da '+m.name);
const openSheet=()=>openMachineSheet(m.id);
lane.onclick=openSheet;
lane.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();openSheet();}};
out.push(lane,...here.map(o=>{const c=card(o);c.dataset.machine=m.id;return c;}));
if(!filtered&&n<cap){
const slot=node('div',undefined,'freeslot');slot.dataset.machine=m.id;
slot.append(node('i',undefined,'freemark'),cap-n>1?plural(cap-n,'vaga livre','vagas livres')+' na '+m.name:'Vaga livre na '+m.name);out.push(slot);
}
}
// An order whose machine is gone or off still shows.
const loose=orders.filter(o=>!list.some(m=>m.id===o.machine?.id));
if(loose.length){const lane=node('div',undefined,'lanehead');lane.append(svgIcon(IC.printer,'i s'),node('b','Sem máquina'));out.push(lane,...loose.map(o=>card(o)));}
return out;
}
// The machine lane under the pointer in Imprimindo: the last lane head above it.
function laneAt(column,y){
let found=null;
for(const el of column.querySelectorAll('[data-machine]')){
if(el.getBoundingClientRect().top<=y)found=el.dataset.machine;
}
return found||column.querySelector('.lanehead[data-machine]')?.dataset.machine||null;
}
function markLane(column,id){
for(const l of column.querySelectorAll('.lanehead,.freeslot,.card'))l.classList.toggle('droplane',!!id&&l.dataset.machine===id);
}
// A card's place in the print queue, among the orders of its product (a
// textile machine pulls the next textile order).
const uvOrder=o=>o.snapshot.items.some(i=>i.mode.startsWith('uv'));
// An order waiting for its proof is not in the queue yet (app/proof.py).
const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)&&!waitingProof(o)).indexOf(order)+1;
// An operator's test order: no payment, no Tiny.
const isTest=order=>order.payment?.provider==='teste';
const shortAgo=value=>ago(value).replace(/^há /,'');
// What happens next with the order, said on its card, and in what tone:
// act (someone has to do it now), live (printing), rip (ripping), busy (the
// system is working) or wait (nothing to do here).
function nextStep(order,place){
if(order.cancelled_at)return ['Cancelado','wait'];
if(order.state==='cor')return ['Esperando o cliente','wait'];
// The proof card waits for its answer; its order, outside the queue, for that.
if(order.proof_parent&&order.state==='rev')return ['Responder a prova','act'];
if(order.state==='tra'&&waitingProof(order))return ['Aguardando prova','wait'];
if(order.state==='rev')return ['Conferir a folha','act'];
if(order.state==='imp')return partsStep(order)||(order.printing?PRINTING[order.printing].slice(0,2):['Na máquina','wait']);
if(order.state==='tra'){
// The operator whose machine prints this product pulls the first one.
const m=(board.machines||[]).find(x=>x.id===myMachine()?.id);
const fits=!m?.products?.length||order.snapshot.items.some(i=>m.products.includes(i.mode));
if(place===1&&m&&fits&&mayMove('tra','imp'))return ['Puxar da fila','act'];
return [place?place+'º na fila':'Na fila','wait'];
}
const p=printState(order);
if(p.text==='Gerando arquivo…')return ['Gerando o arquivo','busy'];
if(p.text==='Falta aprovar o final')return ['Aprovar o final','act'];
if(p.text==='Correção recebida')return ['Conferir correção','act'];
if(p.text==='Final aprovado')return ['Pronto para a fila','act'];
return [p.text,'act'];
}
// Everything a card has to say beyond its stage, the most urgent first; the
// card shows the first and how many more, and all of them on hover.
function cardFlags(order){
const s=order.snapshot, out=[];
if(order.cancelled_at)return [['bad','Cancelado','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason]];
const live=order.state!=='fin';
// A stalled order says so in red where its time is, not as a mark.
const redo=(order.reworks||[]).filter(r=>r.authorized!==false);
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
if(order.snapshot.treatment){
const n=Number(order.snapshot.treatment.arts)||1;
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']);
}
if(order.snapshot.redesign){
const n=Number(order.snapshot.redesign.arts)||1;
out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'),
'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 h']);
}
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
if(live&&proofPending(order)&&!order.proof_card)out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']);
// The grade rule set in the Site tab flagged this order for the designer.
if(!order.proof_parent&&s.grade_flags?.aviso!=null)
out.push(['warn','Nota '+s.grade_flags.aviso+': conferir a arte',
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir']);
if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']);
const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0);
if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]);
if(order.treated)out.push(['','Tratada',TREATED_NOTE+' Aprovado por '+order.treated.by+'.']);
if(live&&needsProof(order)&&order.proof_ok_at)out.push(['','Prova OK','Prova conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at)]);
if(isTest(order))out.push(['','Teste','Pedido de teste: sem pagamento, não vai ao Tiny']);
return out;
}
function flagNode(flags){
if(!flags.length)return null;
const [tone,text]=flags[0];
const f=node('span',text,'flag tip-l'+(tone?' '+tone:''));f.dataset.tip=flags.map(x=>x[2]).join(' · ');
if(flags.length>1)f.append(node('span',' +'+(flags.length-1),'plus'));
return f;
}
const KIND={file:'Folha',avulsa:'Avulsa',uvfile:'Folha',uv:'Avulsa'};
function productLine(items){
const modes=[...new Set(items.map(i=>i.mode))];
return SHORT[modes[0]]+(items.length>1?' ×'+items.length:'')+(modes.length>1?' +'+(modes.length-1):'');
}
// A card drags forward when this profile makes that move, or up and down
// when it sets the column's order; a card of another operator's machine does not.
function draggable(c,order){
c.draggable=!order.cancelled_at&&!waitingProof(order)&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
c.onclick=()=>openPanel(order.id);
c.onkeydown=e=>{if(e.target===c&&(e.key==='Enter'||e.key===' ')){e.preventDefault();openPanel(order.id);}};
c.ondragstart=e=>{
dragging=order;
e.dataTransfer.setData('text/plain',order.id);
const forward=board.transitions[order.state].filter(s=>s!=='cor'&&mayMove(order.state,s));
for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state));
const moves=forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou '):'';
const priority=mayReorder(order.state)?'arraste para cima ou para baixo para mudar a prioridade':'';
say(moves&&priority?moves+', ou '+priority:moves||priority,false,60000);
};
c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');};
}
function card(order,place){
const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at;
const [step,tone]=nextStep(order,place);
const c=node('div',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':''));
c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id;
const who=buyer(s);
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step);
const top=node('span',undefined,'ctop'), info=node('span',undefined,'cinfo');
const row=node('span',undefined,'crow');
const late=!!order.late&&!order.cancelled_at;
const age=node('span',shortAgo(order.state_since||order.updated_at),'age'+(late?' late tip-l'+(order.late==='bad'?' late2':''):''));
if(late)age.dataset.tip='Fora do tempo: '+(order.state_hours??'?')+' h nesta etapa · limite '+
(order.limit_hours??'?')+' h · responsável: '+(order.limit_by||'—');
row.append(node('span','#'+order.number,'num'),originTag(order),age);
const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;
const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items)));
const special=specialDelivery(s);
if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);}
if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);}
meta.append(node('b',metres(orderMetres(order)),'mtr'));
info.append(row,name,meta);
const art=artBox(s.items,'thumb');top.append(art,info);
c.append(top);
if(order.state==='cor'&&order.correction_reason){const r=node('span',undefined,'creason');r.append(node('b','Motivo'),' '+order.correction_reason);c.append(r);}
const foot=node('span',undefined,'cfoot'), next=node('span',undefined,'next'+(tone==='wait'?' wait':''));
if(tone==='live'){const f=node('i',undefined,'feed');f.append(node('i'),node('i'),node('i'));next.append(f);}
if(tone==='rip')next.append(node('i',undefined,'rip'));
if(tone==='busy'){const d=node('i',undefined,'dots');d.append(node('i'),node('i'),node('i'));next.append(d);}
next.append(node('span',step,'stx'));
foot.append(next);
const flag=flagNode(cardFlags(order));if(flag)foot.append(flag);
c.append(foot,cardOpenAction(order));
draggable(c,order);
return c;
}
// Finalizado is the end of the line: what the customer still has to do,
// nothing else. A pickup waiting more than two days is said in warning.
const PICKUP_WARN_DAYS=2;
function miniCard(order){
const c=node('div',undefined,'mini'+(order.id===openOrder?' open':''));c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id;
const who=buyer(order.snapshot);
const row=node('span',undefined,'crow');row.append(node('span','#'+order.number,'num'),node('span',metres(orderMetres(order)),'age'));
const name=node('span',who.title,'cname');name.title=who.mail||who.title;
let text,ic=IC.check,warn=false;
const days=Math.floor((Date.now()-new Date(order.updated_at))/86400000);
const special=specialDelivery(order.snapshot);
if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;}
else if(order.picked_up_at)text='Retirado';
else if(special){text=special;ic=IC.box;}
else if(order.snapshot.destination){text='Entrega, '+order.snapshot.destination.city+'/'+order.snapshot.destination.state;ic=IC.truck;}
else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;}
else{text='Aguardando retirada';ic=IC.bag;}
const done=node('span',undefined,'done'+(warn?' warn':''));done.append(svgIcon(ic,'i s'),text);
c.append(row,name,done,cardOpenAction(order));
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+text);
draggable(c,order);
return c;
}
// The column's queue: payment time, unless an operator dragged the card to
// another place (queue_key, seconds like the payment time).
const queueKey=o=>o.queue_key!=null?Number(o.queue_key):new Date(o.created_at).getTime()/1000;
let dragging=null;
// Where a card dropped at this height lands: the card it goes before, if any.
function dropTarget(column,y){
const cards=[...column.querySelectorAll('.card')].filter(c=>c.dataset.card!==dragging?.id);
return cards.find(c=>{const r=c.getBoundingClientRect();return y<r.top+r.height/2;})||null;
}
function markDrop(column,y){
clearDrop();
const target=dropTarget(column,y);
if(target)target.classList.add('drop-before');
else{const cards=[...column.querySelectorAll('.card')].filter(c=>c.dataset.card!==dragging?.id);cards.at(-1)?.classList.add('drop-after');}
}
function clearDrop(){for(const c of document.querySelectorAll('.drop-before,.drop-after'))c.classList.remove('drop-before','drop-after');}
async function reorder(order,column,y){
const target=dropTarget(column,y);
const cards=[...column.querySelectorAll('.card')].map(c=>c.dataset.card).filter(id=>id!==order.id);
const at=target?cards.indexOf(target.dataset.card):cards.length;
const after=cards[at-1]||null, before=cards[at]||null;
if(!after&&!before)return;
// Dropped where it already was: nothing to save.
const current=[...column.querySelectorAll('.card')].map(c=>c.dataset.card);
const was=current.indexOf(order.id);
if(current[was-1]===(after||undefined)&&current[was+1]===(before||undefined))return;
await api('/orders/'+order.id+'/queue',{after,before});
await load();
}
async function loadOlderFinished(){
const shown=board.orders.filter(o=>o.state==='fin').sort((a,b)=>
new Date(a.finished_at||a.updated_at)-new Date(b.finished_at||b.updated_at)||a.id.localeCompare(b.id));
const oldest=shown[0];const params=new URLSearchParams({limit:'50'});
if(oldest){params.set('before_finished_at',oldest.finished_at||oldest.updated_at);params.set('before_id',oldest.id);}
const page=absorb(await api('/orders/finished?'+params));
const known=new Set(board.orders.map(o=>o.id));
const fresh=page.orders.filter(o=>!known.has(o.id));
olderFinished.push(...fresh);board.orders.push(...fresh);finishedMore=page.has_more;renderBoard();
}
async function move(order,state,reason='',machine=null){
await api('/orders/'+order.id+'/move',{state,version:order.version,reason,...(machine?{machine_id:machine}:{})});
await load();
}
// ---- Dialogs ---------------------------------------------------------------
// One kind of dialog (the design's .modal): a title, a line on what it does,
// the fields and a foot. Over the order, it lives in #drawer, beside the panel,
// so it belongs to that order and closes with it. Escape closes the top one.
const MODALS=[];
document.addEventListener('keydown',e=>{
if(e.key!=='Escape')return;
// An open list inside a dialog closes first.
const list=document.querySelector('.sellist:not([hidden])');
if(list){e.stopImmediatePropagation();list.closest('.sel').close();list.previousSibling.focus();return;}
if(MODALS.length){e.stopImmediatePropagation();if(!MODALS.at(-1).locked)MODALS.at(-1).close();}},true);
function iconButton(d,label,fn,className='btn sq ghost'){
const b=node('button',undefined,className);b.type='button';b.setAttribute('aria-label',label);b.title=label;b.append(svgIcon(d,'i m'));
if(fn)b.onclick=e=>{e.stopPropagation();fn(e);};return b;
}
function modal(title,{text,body=[],foot=[],host=document.body,width,role='dialog',onclose,form,locked=false,lead=null}={}){
const scrim=node('div',undefined,'scrim hi');
const box=node(form?'form':'div',undefined,'modal dlg');box.setAttribute('role',role);box.setAttribute('aria-modal','true');
if(width)box.style.width=width+'px';
const h=node('h2',title);h.id='dlg'+MODALS.length+Date.now();box.setAttribute('aria-labelledby',h.id);
const head=node('div',undefined,'dlghead'),words=node('div');words.append(h);if(text)words.append(node('p',text));
// A locked dialog (a question that must be answered) has no way out but its buttons.
head.append(...(lead?[lead]:[]),words,...(locked?[]:[iconButton(IC.close,'Fechar',()=>entry.close(),'btn sq ghost right')]));
box.append(head,...body);
if(foot.length){const f=node('div',undefined,'dfoot');f.append(...foot);box.append(f);}
const entry={box,host,locked,close(){const i=MODALS.indexOf(entry);if(i<0)return;MODALS.splice(i,1);scrim.remove();box.remove();onclose?.();}};
scrim.onclick=()=>{if(!locked)entry.close();};
MODALS.push(entry);host.append(scrim,box);
(box.querySelector('[autofocus]')||box.querySelector('input:not([type=checkbox]):not([type=file]):not([hidden]),textarea,select'))?.focus();
return entry;
}
// A question with two answers, in place of the browser's confirm().
function ask(title,text,label,{tone='pri',host}={}){
return new Promise(resolve=>{
let answered=false;
const back=node('button','Voltar','btn ghost right');back.type='button';
const ok=node('button',label,'btn '+tone);ok.type='button';
const m=modal(title,{text,foot:[back,ok],host,role:'alertdialog',width:500,onclose:()=>{if(!answered)resolve(false);}});
back.onclick=()=>m.close();ok.onclick=()=>{answered=true;m.close();resolve(true);};ok.focus();
});
}
// A dialog that is a form: the fields, Cancelar and the button that saves.
// onsave throws to keep it open (the message shows); returns to close it.
function formDialog(title,{text,fields=[],label='Salvar',tone='pri',host,width,note,className,onsave,left=[],lead=null}){
const save=node('button',label,'btn '+tone);
const cancel=node('button','Cancelar','btn ghost right');cancel.type='button';
const foot=[...left,...(note?[node('span',note,'lbl')]:[]),cancel,save];
const m=modal(title,{text,body:fields,foot,host,width,form:true,lead});
const form=m.box;if(className)form.classList.add(className);
cancel.onclick=()=>m.close();
form.onsubmit=async e=>{e.preventDefault();save.disabled=true;
try{if(await onsave(form)!==false)m.close();}catch(err){say(err.message,true);}finally{save.disabled=false;}};
return m;
}
// The old name, for the dialogs of Usuários and the rework.
function dialog(title,fields,onsave){return formDialog(title,{fields,onsave:async()=>{await onsave();}});}
// Front 11: Gestão edits the acceptable time and the person responsible for
// each column. The cards read the same table on the next board refresh.
const STAGE_LABELS={rec:'Arte recebida',tra:'Arte conferida',imp:'Imprimindo',rev:'Revisão',fin:'Finalizado sem retirada'};
function stageLimitsDialog(){
api('/stage-limits').then(({limits})=>{
const current=Object.fromEntries((limits||[]).map(limit=>[limit.state,limit]));
const inputs={},fields=[];
for(const state of ['rec','tra','imp','rev','fin']){
const limit=current[state]||{hours:2,responsible:''};
const hours=node('input');hours.type='number';hours.min='0.1';hours.step='0.5';hours.value=limit.hours;
const who=node('input');who.value=limit.responsible||'';who.maxLength=80;
inputs[state]={hours,who};
fields.push(field(STAGE_LABELS[state]+' (horas)',hours,state==='fin'?'Use 72 para 3 dias.':''));
fields.push(field('Responsável por '+STAGE_LABELS[state].toLowerCase(),who));
}
formDialog('Tempos aceitáveis por etapa',{host:dialogHost(),width:640,fields,
note:'Amarelo ao passar do limite; vermelho no dobro.',
onsave:async()=>{
const limits=Object.entries(inputs).map(([state,{hours,who}])=>({
state,hours:Number(hours.value),responsible:who.value.trim()}));
await api('/stage-limits',{limits});
say('Tempos aceitáveis atualizados.');await load();
}});
}).catch(error=>say(error.message,true));
}
function field(label,input,hint){
const l=node('label',undefined,'fld');l.append(label,input);if(hint)l.append(node('small',hint));return l;
}
// A checkbox drawn as the design's box.
function checkbox(label,input){
input.type='checkbox';input.classList.add('vh');
const l=node('label',undefined,'ckb'),box=node('span',undefined,'box');box.setAttribute('aria-hidden','true');
const ns='http://www.w3.org/2000/svg',svg=document.createElementNS(ns,'svg'),p=document.createElementNS(ns,'path');
svg.setAttribute('viewBox','0 0 20 20');p.setAttribute('d','M5 10.5l3.25 3.25L15 7');svg.append(p);box.append(svg);
l.append(input,box,label);return l;
}
// A file field as a place to drop the file, or to pick it.
function dropField(input,{title='Arraste o arquivo para cá',hint=''}={}){
input.type='file';input.classList.add('vh');
const l=node('label',undefined,'drop'),ico=node('span',undefined,'dropico');ico.append(svgIcon(IC.upload));
const pick=node('span');pick.append('ou ',node('u','escolha no computador'));
const chosen=node('span','','dropfiles');
l.append(ico,node('b',title),pick,...(hint?[node('small',hint)]:[]),chosen,input);
const show=()=>{chosen.textContent=[...input.files].map(f=>f.name).join(', ');l.classList.toggle('has',input.files.length>0);};
input.addEventListener('change',show);
l.ondragover=e=>{e.preventDefault();l.classList.add('over');};
l.ondragleave=()=>l.classList.remove('over');
l.ondrop=e=>{e.preventDefault();l.classList.remove('over');if(!e.dataTransfer.files.length)return;
input.files=input.multiple?e.dataTransfer.files:(()=>{const t=new DataTransfer();t.items.add(e.dataTransfer.files[0]);return t.files;})();
input.dispatchEvent(new Event('change',{bubbles:true}));};
return l;
}
// ---- Phone (the design canvas' phone screens) -------------------------------
// Under 700 px the Kanban is the phone mockup: sections at the bottom, menus
// and filters as sheets from the bottom, the order and the quote as pages.
const PHONE=matchMedia('(max-width:700px)');
PHONE.addEventListener('change',()=>{if(board)render();});
// A sheet from the bottom: the grab, then what it holds. Escape or the scrim closes.
function sheet(parts,{label='',role='dialog',onclose}={}){
const scrim=node('div',undefined,'mscrim');
const box=node('div',undefined,'msheet');box.setAttribute('role',role);if(label)box.setAttribute('aria-label',label);
box.append(node('span',undefined,'grab'),...parts);
const entry={box,host:document.body,close(){const i=MODALS.indexOf(entry);if(i<0)return;MODALS.splice(i,1);scrim.remove();box.remove();onclose?.();}};
scrim.onclick=()=>entry.close();
MODALS.push(entry);document.body.append(scrim,box);return entry;
}
// A row of a phone sheet: an icon, the words, and maybe something on the right.
function mrow(d,text,fn,className='mrow',end=null){
const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem');
b.append(svgIcon(d),node('span',text,'mtext'),...(end?[end]:[]));
b.onclick=async()=>{try{await fn();}catch(e){say(e.message,true);}};return b;
}
// "Mais": who is signed in, the sections that do not fit the bar, the machine,
// the theme, the password and Sair.
function phoneMenu(){
let m=null;
const go=fn=>async()=>{m.close();await fn();};
const who=node('div',undefined,'who sheetwho'),words=node('span');
const ava=node('span',initialsOf(ME.name||ME.email),'ava');ava.append(node('i',undefined,'pres on'));
words.append(node('b',ME.name||ME.email),node('span',(ROLE_NAMES[ME.role]||ME.role)+(myMachine()?', na '+myMachine().name:''),'sub'));
who.append(ava,words);
const rows=[];
if(TAB_NEEDS.integrations()){const n=$('badge-integrations').textContent;
rows.push(mrow(IC.link,'Integrações',go(()=>showTab('integrations')),'mrow',n?statePill(n,'warn'):null));}
if(TAB_NEEDS.users())rows.push(mrow(IC.user,'Usuários',go(()=>showTab('users'))));
if(ME.machine_question)rows.push(mrow(IC.printer,'Trocar de máquina',go(()=>askMachine(true)),'mrow',node('span',myMachine()?.name||'','lbl')));
const light=kanbanTheme.get()==='light';
rows.push(mrow(light?ICON_MOON:ICON_SUN,light?'Mudar para o modo escuro':'Mudar para o modo claro',go(()=>{kanbanTheme.toggle();paintThemeToggle();})));
rows.push(mrow(IC.key,'Trocar a senha',go(accountForm)));
rows.push(mrow(IC.logout,'Sair',go(()=>$('logout').click()),'mrow bad'));
const body=node('div',undefined,'sbody');body.append(...rows);
m=sheet([who,body],{label:'Mais',role:'menu'});
}
// The board's filters on the phone: every kind, the product too, and how many
// orders they show.
function phoneFilters(){
const kinds=[{key:'product',label:'Produto',options:PRODUCTS.filter(([v])=>v)},...filterKinds()];
const body=node('div',undefined,'sbody');
const show=node('button','','btn pri');show.type='button';
const paint=()=>{
body.replaceChildren(...kinds.map(kind=>{
const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts');
for(const [value,text] of kind.options){
const on=boardFilter[kind.key]===value;
const b=node('button',text,'fopt'+(on?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on));
b.append(node('span',String(filterCount({...boardFilter,[kind.key]:value})),'n'));
b.onclick=()=>{boardFilter[kind.key]=on?'':value;renderBoard();paint();};opts.append(b);
}
group.append(node('span',kind.label),opts);return group;}));
show.textContent='Ver '+plural(filterCount(boardFilter),'pedido','pedidos');
};
const close=iconButton(IC.close,'Fechar',()=>m.close(),'mic right');
const head=node('div',undefined,'shead');head.append(node('b','Filtros'),close);
const clear=node('button','Limpar','btn');clear.type='button';clear.onclick=()=>{for(const k in boardFilter)boardFilter[k]='';renderBoard();paint();};
const foot=node('div',undefined,'sfoot');foot.append(clear,show);
const m=sheet([head,body,foot],{label:'Filtros'});show.onclick=()=>m.close();
paint();
}
$('more-nav').onclick=()=>phoneMenu();
$('filter-open').onclick=()=>phoneFilters();
// ---- 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);
}
// ---- Wiring --------------------------------------------------------------
for(const b of document.querySelectorAll('[data-tab]'))b.onclick=()=>showTab(b.dataset.tab);
// ---- Search: orders (any stage) and unpaid quotes ---------------------------
// On a phone the search is behind a button, and opens over the top bar.
$('search-back').onclick=()=>{$('search').value='';closeSearch();document.querySelector('.top').classList.remove('searching');$('search-open').setAttribute('aria-expanded','false');};
$('search-open').onclick=()=>{const on=document.querySelector('.top').classList.toggle('searching');
$('search-open').setAttribute('aria-expanded',String(on));if(on)$('search').focus();};
let searchTimer=null, searchToken=0, searchHits=[], searchAt=-1;
function closeSearch(){$('search-results').hidden=true;$('search').setAttribute('aria-expanded','false');searchAt=-1;}
async function runSearch(text){
const token=++searchToken;
const result=absorb(await api('/search?'+new URLSearchParams({q:text})));
if(token!==searchToken||$('search').value.trim()!==text)return;
const box=$('search-results');searchHits=[];searchAt=-1;
const parts=[];
for(const [title,rows,make] of [['Pedidos',result.orders,orderHit],['Cotações',result.quotes,quoteHit]]){
if(!rows.length)continue;
parts.push(node('div',title+' · '+rows.length,'rgroup'));
for(const row of rows){const hit=make(row);hit.el.id='hit-'+searchHits.length;searchHits.push(hit);parts.push(hit.el);}
}
if(!searchHits.length)parts.push(node('p','Nada encontrado para “'+text+'”.','rempty'));
parts.push(node('div','↑ ↓ para escolher · Enter abre · Esc fecha · busca por e-mail, CPF/CNPJ, WhatsApp ou nº do pedido','rhelp'));
box.replaceChildren(...parts);box.hidden=false;$('search').setAttribute('aria-expanded','true');
}
function hitRow(items,title,sub,meta,state,tone,open){
const el=node('button',undefined,'rhit');el.type='button';el.setAttribute('role','option');el.setAttribute('aria-selected','false');
const text=node('span',undefined,'rtext');text.append(node('b',title),node('span',sub,'sub'),node('span',meta,'rmeta'));
el.append(artBox(items,'qthumb rart'),text,badge(state,tone));
el.onmousedown=e=>e.preventDefault();
el.onclick=()=>{closeSearch();document.querySelector('.top').classList.remove('searching');open();};
return {el,open};
}
function orderHit(order){
const s=order.snapshot;
return hitRow(s.items,'#'+order.number+' · '+orderCode(order.id),buyer(s).title,
s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(specialDelivery(s)||(s.destination?'Entrega':'Retirada'))+' · pago '+when(order.created_at),
order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'bad':'',()=>{
// An older finished order is not on the board yet: it joins, like "Carregar mais".
if(!board.orders.some(o=>o.id===order.id)){olderFinished.push(order);board.orders.push(order);}
showTab('board');openPanel(order.id);});
}
function quoteHit(q){
return hitRow(q.draft.items,q.approved?money(q.approved.total_cents):'Cotação '+q.id.slice(0,8),buyer(q.draft).title,
q.draft.items.map(i=>SHORT[i.mode]).join(' + ')+' · '+metres(quoteMetres(q))+' · '+ago(q.created_at),
q.approved?'Aguardando pagamento':'A revisar',q.approved?'':'warn',()=>{
// Opens Cotações filtered to this customer, with this quote selected.
quoteKind=q.approved?'approved':'pending';quoteQuery=q.draft.customer.mail;
quoteProduct=quoteLayout=quoteFlag='';quotePage=1;currentQuote=q;showTab('quotes');});
}
$('search').oninput=e=>{
const text=e.target.value.trim();clearTimeout(searchTimer);
if(text.length<2){searchToken++;closeSearch();return;}
searchTimer=setTimeout(()=>runSearch(text).catch(err=>say(err.message,true)),250);
};
$('search').onkeydown=e=>{
if(e.key==='Escape'){e.stopPropagation();closeSearch();return;}
if($('search-results').hidden||!searchHits.length)return;
if(e.key==='ArrowDown'||e.key==='ArrowUp'){
e.preventDefault();searchAt=(searchAt+(e.key==='ArrowDown'?1:-1)+searchHits.length)%searchHits.length;
searchHits.forEach((h,i)=>h.el.setAttribute('aria-selected',String(i===searchAt)));
$('search').setAttribute('aria-activedescendant',searchHits[searchAt].el.id);searchHits[searchAt].el.scrollIntoView({block:'nearest'});
}
if(e.key==='Enter'){e.preventDefault();const hit=searchHits[Math.max(0,searchAt)];closeSearch();hit.open();}
};
$('search').onblur=()=>setTimeout(()=>{closeSearch();if(!$('search').value.trim()&&!PHONE.matches)document.querySelector('.top').classList.remove('searching');},150);
$('search').onfocus=()=>{if($('search').value.trim().length>=2&&searchHits.length){$('search-results').hidden=false;$('search').setAttribute('aria-expanded','true');}};
// "/" jumps to the search, as the field shows, unless typing somewhere else.
document.addEventListener('keydown',e=>{
if(e.key!=='/'||e.ctrlKey||e.metaKey||e.altKey)return;
const t=e.target;if(t.closest&&t.closest('input,textarea,select,[contenteditable="true"]'))return;
if($('app').hidden)return;e.preventDefault();$('search').focus();
});
$('login').onsubmit=async e=>{e.preventDefault();try{await api('/login',{email:$('email').value,password:$('password').value});await load();}catch(error){say(error.message,true);}finally{$('password').value='';}};
$('logout').onclick=async()=>{await api('/logout',{});for(const key of Object.keys(localStorage))if(key.startsWith('dtf-'))localStorage.removeItem(key);location.reload();};
$('refresh').onclick=()=>load();
// ---- Refreshing by itself --------------------------------------------------
// New orders and quotes to review since the last load: a notice, and the
// count in the tab's title until the operator looks at the tab.
function noticeNew(quiet){
const orders=new Set(board.orders.map(o=>o.id));
const fresh=seenOrders?board.orders.filter(o=>!seenOrders.has(o.id)&&o.state==='rec'&&!o.cancelled_at):[];
const reviews=seenPending===null?0:Math.max(0,board.pending_total-seenPending);
seenOrders=orders;seenPending=board.pending_total;
if(!fresh.length&&!reviews)return;
const parts=[];
if(fresh.length)parts.push(fresh.length===1?'Novo pedido #'+fresh[0].number:fresh.length+' pedidos novos');
if(reviews)parts.push(reviews===1?'1 cotação nova para revisar':reviews+' cotações novas para revisar');
say(parts.join(' · '),false,10000);
if(document.hidden||quiet){unseen+=fresh.length+reviews;document.title='('+unseen+') Kanban DTF';}
}
document.addEventListener('visibilitychange',()=>{if(!document.hidden){unseen=0;document.title='Kanban DTF';}});
addEventListener('focus',()=>{unseen=0;document.title='Kanban DTF';});
// Every N seconds, chosen beside "Atualizar" and remembered by this browser.
// Never under the operator's hands: not while typing, dragging or with an
// order open. With the Kanban's tab hidden it still looks, at most once a
// minute, so the tab's title can say a new order arrived.
let autoTimer=null, lastAuto=0;
function busy(){
const a=document.activeElement;
const typing=!!(a&&a.matches&&a.matches('input,textarea,select')&&a.id!=='refresh-every');
// An order being registered, half filled in and on screen, keeps its choices.
const registering=!$('tab-quotes').hidden&&[...document.querySelectorAll('.register')].some(f=>
f.querySelector('input:checked')||f.querySelector('input[type=text]').value);
return $('app').hidden||!!dragging||!$('drawer').hidden||typing||registering;
}
function autoRefresh(){
if(busy())return;
if(document.hidden&&Date.now()-lastAuto<60000)return;
lastAuto=Date.now();
load(true).catch(()=>{});
}
function scheduleAuto(){
clearInterval(autoTimer);
const secs=Number($('refresh-every').value);
if(secs)autoTimer=setInterval(autoRefresh,secs*1000);
}
(()=>{
let saved='30';
try{saved=localStorage.getItem('dtf-refresh-every')??'30';}catch(_){}
$('refresh-every').value=[...$('refresh-every').options].some(o=>o.value===saved)?saved:'30';
$('refresh-every').onchange=()=>{
try{localStorage.setItem('dtf-refresh-every',$('refresh-every').value);}catch(_){}
scheduleAuto();paintSync();
};
scheduleAuto();paintSync();
})();
function paintSync(){
const every=$('refresh-every'), on=every.value!=='0';
$('sync').classList.toggle('off',!on);
$('sync').title=on?'Atualiza sozinho '+every.selectedOptions[0].textContent.toLowerCase()+'. Clique para mudar.':'Não atualiza sozinho. Clique para mudar.';
$('sync-every').replaceChildren(...[...every.options].map(o=>{
const b=node('button',undefined,'menuitem');b.type='button';b.setAttribute('role','menuitemradio');
b.setAttribute('aria-checked',String(o.value===every.value));b.append(node('span',o.textContent));
if(o.value===every.value)b.append(svgIcon(IC.check,'i m'));
b.onclick=()=>{$('sync-menu').hidden=true;every.value=o.value;every.dispatchEvent(new Event('change'));};
return b;}));
}
$('sync').onclick=e=>{e.stopPropagation();const m=$('sync-menu');m.hidden=!m.hidden;$('sync').setAttribute('aria-expanded',String(!m.hidden));
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;$('sync').setAttribute('aria-expanded','false');},{once:true});};
$('refresh').addEventListener('click',()=>{$('sync-menu').hidden=true;});
// The tabs live in later files: wait for all scripts before loading.
addEventListener('DOMContentLoaded',()=>restoreFolder().finally(()=>load()));