Files
dtf-system/web/kanban.js
Cauê Faleiros 6f294e168b
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m37s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m10s
feat: the Kanban's new screens, from the board to the phone (redesign, steps 2 to 8)
- Board: product switch and a filters panel with counts, cards that say
  the next step and the most urgent mark, Imprimindo in one lane per
  machine with its free places, Finalizado as short cards.
- Order panel: the stage and codes on top, "Próximo passo" with its
  button, Pedido / Arquivos / Histórico tabs; going back, contact,
  rework and cancelling in a menu; every form in a dialog.
- Cotações, Pagamentos, Integrações, Números (a calendar for the
  period) and Usuários (who is on the system now, what each profile
  does, the machines) in the design's panels; the sign-in page.
- Phone: sections at the bottom, one stage at a time, the order and
  the dialogs over the whole screen.
- API: each session records when it was last used (at most once a
  minute), for "Ativo agora"; the board says who is on each machine.
- .dockerignore leaves the local test files out of the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:58:05 -03:00

2902 lines
197 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'};
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'};
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'};
const LATE_HOURS=4;
// 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'};
// 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(),integrations:()=>may('manage')||may('print'),users:()=>may('users')};
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',
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),
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});
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;throw error;}return d;
}
function download(uid){return async()=>{
const result=await api('/uploads/'+uid+'/download');
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';
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, e o recibo de cada retirada em Recibos.',
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.'),
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])].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);
}
// 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':'')).join(',');
if(!force&&sig===FOLDER.lastSig)return;
FOLDER.busy=true;
try{
if(stages)await makeStageFolders();
const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[];
const {files,states,receipts=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
const wanted=new Map(files.map(f=>[f.order+':'+f.item,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(rec.order+':'+rec.item);
const replaced=(state==='rec'||state==='tra')&&(!now||now.upload_id!==uid);
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();}
}
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;}
}
FOLDER.lastSig=sig;FOLDER.error='';
FOLDER.status='';
if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.');
if(printed)say(printed+' recibo(s) de retirada salvos em '+RECEIPTS_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));
}
}
function manifest(production){
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 no filme']]){
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;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();
}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',integrations:'Integrações',users:'Usuários'};
function showTab(name){
tab=name;
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';
for(const id of ['board','quotes','payments','stats','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
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:'';
$('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();
// Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
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==='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=>['rec','tra','imp','rev'].includes(order.state)&&Date.now()-new Date(order.updated_at)>LATE_HOURS*3600000;
// "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é 30 cm, do trecho de traço mais fino, um pedaço de cada arte diferente; 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;
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']};
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'),
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,
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:[['parados','Parados há mais de '+LATE_HOURS+' h','Parados'],
['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);
$('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';
function renderBoard(){
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);
// A queue: the order paid first is on top, the newest at the bottom, however
// the list was put together (older finished ones, one opened from the search).
const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>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);
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');};
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');clearDrop();}};
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain'));
if(!order)return;
try{
if(order.state!==state)await move(order,state);
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 a free place. Machines with
// nothing printing share one line, except the session's own, which keeps its
// lane so the operator sees the place waiting.
function printingLanes(orders){
const cap=board.printing_cap||2, mine=myMachine()?.id;
const filtered=Object.values(boardFilter).some(Boolean);
const out=[], free=[];
const list=(board.machines||[]).filter(m=>m.active||m.states?.imp||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.
const n=filtered?here.length:Math.max(m.states?.imp||0,here.length);
if(filtered&&!here.length)continue;
if(!filtered&&!n&&m.id!==mine){free.push(m.name);continue;}
const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));
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),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':'');
out.push(lane,...here.map(o=>card(o)));
if(!filtered)for(let i=n;i<cap;i++){const slot=node('div',undefined,'freeslot');slot.append(node('i',undefined,'freemark'),'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)));}
if(free.length){const line=node('div',undefined,'freeslot');line.append(node('i',undefined,'freemark'),'Livres: '+free.join(' · '));out.push(line);}
return out;
}
// 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'));
const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)).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'];
if(order.state==='rev')return ['Conferir a folha','act'];
if(order.state==='imp')return 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';
if(live&&stalled(order))out.push(['bad','Parado '+hoursSince(order.updated_at)+' h','Sem mudar de etapa desde '+when(order.updated_at)]);
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(live&&proofPending(order))out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']);
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&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
c.onclick=()=>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('button',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':''));
c.type='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');
row.append(node('span','#'+order.number,'num'),originTag(order),node('span',shortAgo(order.updated_at),'age'+(stalled(order)&&!order.cancelled_at?' late':'')));
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)));
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);
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('button',undefined,'mini'+(order.id===openOrder?' open':''));c.type='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);
if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;}
else if(order.picked_up_at)text='Retirado';
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);
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)=>a.created_at<b.created_at?-1:1);
const oldest=shown[0];const params=new URLSearchParams({limit:'50'});
if(oldest){params.set('before_created_at',oldest.created_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=''){
await api('/orders/'+order.id+'/move',{state,version:order.version,reason});
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();}});}
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;
}
// ---- Order panel ---------------------------------------------------------
// The panel's tab stays while the same order is open.
let panelTab='order';
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');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]+'), 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(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
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);
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));
// A re-render keeps where the body was scrolled.
const scrolled=panel.querySelector('.dbody')?.scrollTop||0;
panel.replaceChildren(head,body);body.scrollTop=scrolled;
api('/orders/'+order.id+'/files').then(rows=>{if(token!==openToken)return;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)historyView(order,rows,views.history);}).catch(e=>say(e.message,true));
}
// The order's own menu: the rare things, some of them destructive.
function moreMenu(order){
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&&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});});
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);}
if(canClear)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.
function approveParts(order,main=true){
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
const files=node('div',undefined,'files');
if(all)ready.forEach((r,i)=>files.append(fileRow(r.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source],downloadFile(r.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')=>{const b=button(label||'Mover para '+board.states[to],()=>move(order,to),className);b.dataset.move=to;return b;};
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)||!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.');
if(st==='rec'||st==='cor'){
if(!finalDone(order)&&trans.includes('tra')){
const lead=st==='rec'||fixed, a=approveParts(order,lead);
if(st==='rec')title='Aprovar o arquivo final';
if(lead){if(a.files)body.push(a.files);note(a.text);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'){
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{
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';
// ---- 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 FINAL_SOURCE={correction:'correção do cliente',generated:'PDF gerado',original:'original'};
const FINAL_TITLE={correction:'Correção do cliente',generated:'PDF gerado pelo sistema',original:'Original do cliente'};
// Per item, a file that can be approved as it is, or null: the customer's
// correction, or else the generated PDF (or the original that already is 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?null:{upload_id:fix.upload_id,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';
return {upload_id:made.upload_id,name:made.name,source:original?'original':'generated',label:(original?'O original (':'PDF gerado (')+made.name+')'};
});
}
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(', ');
await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note});
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)+', '+PRODUCT[item.mode]:PRODUCT[item.mode];
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);
const drop=dropField(input,{hint:'PNG, PDF ou TIFF, 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.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({item_index:index,upload_id:generated});continue;}
for(const file of input.files){
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});
}
}
await api('/orders/'+order.id+'/final-files',{version:order.version,files:refs,note:note.value});
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';
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)+', '+PRODUCT[item.mode]:PRODUCT[item.mode],'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);
return {ids:kept.length?kept:ready[index]?[ready[index].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 arquivo: suba a arte tratada 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});
}
await api('/orders/'+order.id+'/final-files',{version:order.version,files:refs,note:TREAT_NOTE});
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();
})();
}
// 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));
if(order.reworks?.length)view.append(reworkSection(order));
return view;
}
function orderFacts(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');
where.append(node('span','Entrega','lbl'),node('b',dest?dest.recipient:'Retirada em Franca'),
node('span',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:'PDF 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 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',PRODUCT[item.mode]));
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);
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 aceito pelo cliente: '+residueNote(item)+'.','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(row.status==='manual'||row.status==='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',row.status==='failed'?'Falhou ao gerar. ':'Preparar à mão. '),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+'.'));
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')links.append(dl_('PDF',row.upload_id));
item.uploads.forEach((uid,i)=>links.append(dl_(item.uploads.length>1?'Original '+(i+1):'Arquivo original',uid)));
if(spec?.placements){const m=button('Manifesto',()=>manifest(spec),'btn');m.prepend(svgIcon(IC.file,'i m'));links.append(m);}
if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed')){
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=[];
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){
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 tratamento',
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));
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]+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
order.created_at,paidOutside(order)?order.payment.note:''));
view.replaceChildren(list);
}
// ---- Machines and users ----------------------------------------------------
// "Em qual máquina você está?" (Dropstar's third round, item 12): after signing
// in, required for the operator, and for Gestão and the administrators with
// "Não estou em máquina". Per session: one person on two computers runs two
// machines. Someone else already on the machine is a warning, not a refusal.
let askingMachine=false;
function askMachine(again=false){
if(!ME?.machine_question||askingMachine||(ME.machine_answered&&!again))return;
askingMachine=true;
const required=ME.machine_question==='required', current=myMachine();
let m=null;
const choose=async(id,confirm=false)=>{
try{await api('/me/machine',{machine_id:id,confirm});m.close();await load(true);}
catch(e){
if(e.status===409&&!confirm&&await ask('Outra pessoa está nesta máquina',e.message,'Continuar mesmo assim'))return choose(id,true);
say(e.message,true);}};
// Each machine with what it is printing, and who is on it now.
const list=node('div',undefined,'mchoices');
for(const machine of (board.machines||[]).filter(x=>x.active)){
const mine=current?.id===machine.id;
const b=node('button',undefined,'mchoice'+(mine?' on':''));b.type='button';b.setAttribute('aria-pressed',String(mine));
const head=node('span',undefined,'mhead');head.append(node('b',machine.name));
if(mine){const tick=node('span',undefined,'tick');tick.append(svgIcon(IC.check,'i s'));head.append(tick);}
b.append(head,node('span',machine.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','sub'));
const here=board.orders.filter(o=>o.state==='imp'&&!o.cancelled_at&&o.machine?.id===machine.id)
.sort((x,y)=>(x.printing==='imprimindo'?0:1)-(y.printing==='imprimindo'?0:1));
for(let i=0;i<Math.max(board.printing_cap||2,here.length);i++){
const o=here[i],job=node('span',undefined,'job');
if(o)job.append(node('i',undefined,o.printing==='ripando'?'ripmark':'runmark'),node('span','#'+o.number,'code'),node('em',o.printing==='ripando'?'ripando':'imprimindo'));
else job.append(node('i',undefined,'freemark'),node('span','livre','free'));
b.append(job);
}
if(machine.operators){const others=machine.operators.filter(op=>op.name!==(ME.name||ME.email));
b.append(node('span',others.length?others.map(op=>op.name).join(', ')+(others.length>1?' estão nela':' está nela'):'Ninguém mais nela','who'));}
b.onclick=()=>choose(machine.id);list.append(b);
}
if(!list.children.length)list.append(node('p','Nenhuma máquina ativa. Peça ao Administrador para cadastrar em Usuários, Máquinas.','empty'));
const foot=[];
if(!required)foot.push(button('Não estou em máquina',()=>choose(null),'btn ghost'));
if(required&&!ME.machine_answered)foot.push(button('Sair',()=>$('logout').click(),'btn ghost'));
if(current&&ME.machine_answered)foot.push(button('Continuar na '+current.name,async()=>m.close(),'btn pri right'));
m=modal('Em qual máquina você está?',{text:'O que você puxar para Imprimindo vai para ela, e o histórico grava a máquina com o seu nome.',
body:[list],foot,width:620,locked:required&&!ME.machine_answered,onclose:()=>{askingMachine=false;}});
}
// The machine beside the account button: green, and a click changes it.
function paintMyMachine(){
const asked=!!ME?.machine_question, mine=myMachine();
for(const id of ['my-machine','rail-machine','account-machine'])$(id).hidden=!asked;
if(!asked)return;
const name=mine?mine.name:'Sem máquina';
const chip=$('my-machine');chip.replaceChildren(node('i'),node('span','Máquina '),node('b',name));
chip.classList.toggle('on',!!mine);
chip.title=mine?'Você está na '+mine.name+'. Clique para trocar.':'Você não está em máquina. Clique para escolher.';
const rail=$('rail-machine');rail.querySelector('b').textContent=mine?mine.name:'Nenhuma';rail.classList.toggle('on',!!mine);rail.title=chip.title;
$('account-machine').querySelector('.lbl').textContent=mine?mine.name:'';
}
for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true);
$('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);};
// The order's machine: chosen, or the first that prints its product.
function machineCard(order){
const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl'));
const current=order.machine;
// The operator's orders go to the machine that pulls them (item 12).
if(!may('print')||ME?.role==='operador'||!board.machines?.length){
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'),
node('span',current?.chosen?'Escolhida para este pedido':current?'Escolhida automaticamente':'Nenhuma máquina imprime este produto'));
return box;
}
const select=node('select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Automática'+(current&&!current.chosen?' ('+current.name+')':''));auto.value='';select.append(auto);
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
const o=node('option',m.name+', '+machineLoad(m));o.value=m.id;select.append(o);
}
select.value=current?.chosen?current.id:'';
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'Máquina automática pelo produto.');await load();}
catch(e){say(e.message,true);}};
box.append(node('b',current?current.name:'Nenhuma'),
node('span',current?.chosen?'Escolhida para este pedido':current?'Escolhida automaticamente quando o pedido chegou':'Nenhuma máquina imprime este produto'),select);
return box;
}
// "120,00 m de 300,00 m" or "120,00 m em aberto".
function machineLoad(m){
return m.limit_metres?metres(m.open_metres)+' de '+metres(m.limit_metres):metres(m.open_metres)+' em aberto';
}
// Chips that switch on and off (what a machine prints): .values() is what is on.
function pills(options,selected){
const box=node('div',undefined,'fopts'),on=new Set(selected);
for(const [value,label] of options){
const b=node('button',label,'fopt'+(on.has(value)?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on.has(value)));
b.onclick=()=>{if(on.has(value))on.delete(value);else on.add(value);b.classList.toggle('on',on.has(value));b.setAttribute('aria-pressed',String(on.has(value)));};
box.append(b);
}
box.values=()=>options.map(([v])=>v).filter(v=>on.has(v));return box;
}
// A dialog field that is a group (chips, a list) rather than one input.
function group(label,...content){const g=node('div',undefined,'fld');g.append(node('span',label),...content);return g;}
// A list to choose from, drawn by us: each choice with a line on what it means.
function choice(options,value,{label,disabled=false}={}){
const wrap=node('div',undefined,'sel');let current=value;
const btn=node('button',undefined,'selbtn');btn.type='button';btn.disabled=disabled;
btn.setAttribute('aria-haspopup','listbox');btn.setAttribute('aria-expanded','false');if(label)btn.setAttribute('aria-label',label);
const text=node('span');btn.append(text,svgIcon(IC.down,'i m'));
const list=node('div',undefined,'pop sellist');list.setAttribute('role','listbox');list.hidden=true;
const hint=node('small');
const close=()=>{list.hidden=true;btn.classList.remove('open');btn.setAttribute('aria-expanded','false');};
const paint=()=>{const o=options.find(x=>x.value===current)||options[0];text.textContent=o.label;hint.textContent=o.hint||'';
for(const b of list.children){const on=b.dataset.value===current;b.setAttribute('aria-selected',String(on));b.querySelector('.ck').replaceChildren(...(on?[svgIcon(IC.check,'i m')]:[]));}};
for(const o of options){
const b=node('button',undefined,'selopt');b.type='button';b.setAttribute('role','option');b.dataset.value=o.value;
const words=node('span');words.append(node('b',o.label),...(o.hint?[node('small',o.hint)]:[]));
b.append(node('span',undefined,'ck'),words);
b.onclick=()=>{current=o.value;paint();close();btn.focus();};list.append(b);
}
btn.onclick=e=>{e.stopPropagation();if(!list.hidden)return close();list.hidden=false;btn.classList.add('open');btn.setAttribute('aria-expanded','true');
list.querySelector('[aria-selected=true]')?.focus();
setTimeout(()=>document.addEventListener('click',close,{once:true}));};
list.onkeydown=e=>{const items=[...list.children],i=items.indexOf(document.activeElement);
if(e.key==='ArrowDown'){e.preventDefault();items[Math.min(items.length-1,i+1)].focus();}
if(e.key==='ArrowUp'){e.preventDefault();items[Math.max(0,i-1)].focus();}};
wrap.append(btn,list);paint();
wrap.value=()=>current;wrap.hint=hint;wrap.close=close;wrap.isOpen=()=>!list.hidden;
return wrap;
}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
// What each profile is for, in a line (app/core/auth.py).
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa e libera para Finalizado.',
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.'};
// Who is on the system: used it in the last 15 minutes, signed in before,
// never, or switched off.
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
const presence=u=>!u.active?'off':u.seen_at&&Date.now()-new Date(u.seen_at)<15*60e3?'on':u.last_login_at?'away':'never';
const initialsOf=text=>String(text||'').trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()||'·';
function avatar(u,className='ava'){
const a=node('span',initialsOf(u.name||u.email),className),p=node('i',undefined,'pres '+presence(u));
p.title=PRESENCE[presence(u)];a.append(p);return a;
}
// "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py).
const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro'];
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYYNNN'],['Pedir correção','YYYNNNN'],['Puxar da fila e imprimir','YNNYNNN'],
['Liberar para Finalizado','YNNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'],
['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNY'],['Cancelar pedido','YYNNNNY'],
['Abrir retrabalho','NYNNNNN'],['Autorizar retrabalho','YNNNNNN'],['Usuários e máquinas','YNNNNNN']];
let usersData=null;
async function loadUsers(){
usersData=await api('/users');
renderUsers();
}
function renderUsers(){
const {users,machines}=usersData;
const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
$('users-count').textContent=String(users.length);
$('users-list').replaceChildren(...users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const who=node('td'),line=node('span',undefined,'who'),words=node('span');
words.append(node('b',u.name||u.email),node('span',u.email,'sub'));line.append(avatar(u),words);who.append(line);
const machine=node('td');
if(u.machines.length){const m=node('span',undefined,'mcell');m.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));machine.append(m);}
else machine.append(node('span','Sem máquina','muted'));
const open=node('td',undefined,'r');
if(editable){open.append(iconButton(IC.right,'Editar '+(u.name||u.email),()=>userForm(u),'btn sq ghost'));tr.classList.add('click');tr.onclick=()=>userForm(u);}
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':', desativado')),machine,
node('td',u.last_login_at?ago(u.last_login_at):'nunca entrou','muted'),open);
return tr;
}));
const head=node('tr');head.append(node('th',''));for(const r of ROLE_COLUMNS)head.append(node('th',ROLE_NAMES[r]));
for(const th of head.children)th.scope='col';head.firstChild.append(node('span','Ação','vh'));
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const [label,cells] of ROLE_MATRIX){const tr=node('tr');tr.append(node('td',label));
[...cells].forEach(k=>{const td=node('td'),i=node('i',undefined,k==='Y'?'can':k==='V'?'can view':'can no');
td.title=k==='Y'?'Faz':k==='V'?'Só consulta':'Não';td.append(i,node('span',td.title,'vh'));tr.append(td);});tbody.append(tr);}
$('roles-matrix').replaceChildren(thead,tbody);
$('machines-count').textContent=String(machines.length);
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
:[emptyState(IC.printer,'Nenhuma máquina cadastrada','Cadastre as máquinas para os pedidos irem para elas.')]));
}
// A machine: its metres open against its limit, its orders by stage, and who is on it.
const STAGE_FILL={rec:'var(--tx3)',tra:'var(--ln3)',imp:'var(--ink)',cor:'var(--bad)',rev:'var(--tx2)'};
function machineTile(m){
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
const head=node('div',undefined,'row');
head.append(node('h3',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','lbl'));
if(!m.active)head.append(badge('Desativada',''));
head.append(button('Editar',()=>machineForm(m),'btn ghost right'));
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
const load=node('div',undefined,'row base');
load.append(node('b',metres(m.open_metres),over?'bad':''),node('span','em aberto, '+(m.limit_metres?'limite de '+metres(m.limit_metres)+(over?', acima do limite':''):'sem limite'),'lbl'));
const stages=Object.keys(STAGE_FILL).filter(s=>m.states[s]);
const total=stages.reduce((t,s)=>t+m.states[s],0);
tile.append(head,load);
if(total){
const stack=node('div',undefined,'stack'),list=node('ul');
for(const s of stages){const seg=node('i');seg.style.width=(100*m.states[s]/total)+'%';seg.style.background=STAGE_FILL[s];stack.append(seg);
const li=node('li'),dot=node('i');dot.style.background=STAGE_FILL[s];li.append(dot,board?.states?.[s]||s,node('b',String(m.states[s])));list.append(li);}
tile.append(stack,list);
}else tile.append(node('span','Nenhum pedido em aberto','lbl'));
const people=node('div',undefined,'row people');people.append(svgIcon(IC.user,'i s'),
m.operators?.length?m.operators.map(o=>o.name+(o.since?' desde '+new Date(o.since).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'')).join(', ')+(m.operators.length>1?' estão nela':' está nela'):'Ninguém nela agora');
tile.append(people);
return tile;
}
function userForm(u){
const editing=!!u;
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';name.placeholder='Nome e sobrenome';
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';email.placeholder='nome@dropstar.com.br';
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro'];
const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador',
{label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email});
const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint);
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter a atual':'8 caracteres ou mais';
const active=node('input');active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const row=node('div',undefined,'frow');row.append(field('Nome',name),field('E-mail',email));
const left=[];
if(editing&&u.email!==ME.email){
const remove=node('button','Excluir usuário','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir '+(u.name||u.email)+'?','A pessoa não entra mais no sistema. Os pedidos continuam com o nome dela no histórico. Para só bloquear o acesso, desmarque Ativo.','Excluir usuário',{tone:'red'}))return;
try{await api('/users/'+u.id+'/delete',{});m.close();say('Usuário excluído.');await loadUsers();}catch(e){say(e.message,true);}};
left.push(remove);
}
const m=formDialog(editing?u.name||u.email:'Novo usuário',{width:560,left,lead:editing?avatar(u,'bigava'):null,
text:editing?PRESENCE[presence(u)].split(':')[0]+', último acesso '+(u.last_login_at?when(u.last_login_at):'nunca'):'A pessoa entra com o e-mail e esta senha, e troca a senha em Minha conta.',
fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),checkbox('Ativo: pode entrar no sistema',active)],
label:editing?'Salvar':'Criar usuário',onsave:async()=>{
const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
}});
}
function machineForm(m){
const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';name.placeholder='Ex.: Têxtil 2';
const products=pills([['textil','Têxtil'],['uv','UV']],m?.products||[]);
const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal';
limit.placeholder='Sem limite';limit.value=m?.limit_metres??'';
const active=node('input');active.checked=m?m.active:true;
const left=[];
if(m){
const remove=node('button','Excluir máquina','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir a máquina '+m.name+'?','Os pedidos dela vão para outra máquina do produto.','Excluir máquina',{tone:'red'}))return;
try{await api('/machines/'+m.id+'/delete',{});d.close();say('Máquina excluída.');await loadUsers();await load();}catch(e){say(e.message,true);}};
left.push(remove);
}
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
fields:[field('Nome',name),group('Imprime',products),
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
checkbox('Ativa: recebe pedidos',active)],
onsave:async()=>{
if(!products.values().length)throw new Error('Marque o que a máquina imprime.');
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(),
limit_metres:limit.value?Number(limit.value):null});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
}});
}
// Minha conta: who is signed in, and the password, which only the person changes.
function accountForm(){
const current=node('input');current.type='password';current.required=true;current.autocomplete='current-password';
const next=node('input');next.type='password';next.required=true;next.minLength=8;next.autocomplete='new-password';
const again=node('input');again.type='password';again.required=true;again.minLength=8;again.autocomplete='new-password';
const dl=node('dl',undefined,'dl');
for(const [k,v] of [['E-mail',ME.email],['Perfil',ROLE_NAMES[ME.role]||ME.role],...(ME.machine_question?[['Máquina agora',myMachine()?.name||'Nenhuma']]:[])]){
const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);}
const sect=node('div',undefined,'sect');
const row=node('div',undefined,'frow');row.append(field('Nova senha',next,'8 caracteres ou mais'),field('Repita a nova senha',again));
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'),
text:ROLE_NAMES[ME.role]+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect],
note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave:async()=>{
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
}});
}
$('my-password').onclick=()=>{$('account-menu').hidden=true;accountForm();};
// Dark or light, per browser (web/theme.js): the rail's button and the account
// menu name the one a click gives.
const ICON_SUN='M6.75 10a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M10 2v1.75 M10 16.25V18 M2 10h1.75 M16.25 10H18 M4.35 4.35l1.24 1.24 M14.41 14.41l1.24 1.24 M4.35 15.65l1.24-1.24 M14.41 5.59l1.24-1.24';
const ICON_MOON='M16.25 12.25A6.75 6.75 0 0 1 7.75 3.75a6.75 6.75 0 1 0 8.5 8.5z';
function paintThemeToggle(){
const light=kanbanTheme.get()==='light', label=light?'Mudar para o modo escuro':'Mudar para o modo claro';
for(const id of ['theme-rail','theme-toggle'])$(id).querySelector('path').setAttribute('d',light?ICON_MOON:ICON_SUN);
$('theme-rail').setAttribute('aria-label',label);$('theme-rail').title=label;
$('theme-toggle').querySelector('span').textContent=light?'Modo escuro':'Modo claro';
}
$('theme-toggle').onclick=()=>{$('account-menu').hidden=true;kanbanTheme.toggle();paintThemeToggle();};
$('theme-rail').onclick=()=>{kanbanTheme.toggle();paintThemeToggle();};
paintThemeToggle();
$('account').onclick=e=>{e.stopPropagation();const m=$('account-menu');m.hidden=!m.hidden;
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;},{once:true});};
$('filter-btn').onclick=e=>{e.stopPropagation();if($('filter-pop').hidden)openFilters();else closeFilters();};
$('filter-pop').onclick=e=>e.stopPropagation();
$('filter-pop').onkeydown=e=>{if(e.key==='Escape'){e.stopPropagation();closeFilters();$('filter-btn').focus();}};
document.addEventListener('click',()=>{if(!$('filter-pop').hidden)closeFilters();});
$('new-user').onclick=()=>userForm(null);
$('new-machine').onclick=()=>machineForm(null);
// ---- Numbers -------------------------------------------------------------
// The period: the last 7, 30 or 90 days, or two dates picked on the calendar.
let statsDays=30, statsRange=null, statsData=null;
function duration(hours){
if(hours===null||hours===undefined)return '—';
if(hours<1)return Math.max(1,Math.round(hours*60))+' min';
if(hours<48){const h=Math.floor(hours),m=Math.round((hours-h)*60);return m&&h<10?h+' h '+String(m).padStart(2,'0'):Math.round(hours)+' h';}
return Math.round(hours/24)+' dias';
}
const dayLabel=iso=>new Date(iso+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit',year:'numeric'});
const shortDay=iso=>new Date(iso+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
const isoDay=d=>d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0');
// Brasília's today, whatever the computer's clock zone.
const todayIso=()=>new Date(Date.now()-3*3600e3).toISOString().slice(0,10);
function statsPeriod(){
const seg=$('stats-period');
seg.replaceChildren(...[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
const on=!statsRange&&days===statsDays;
const b=node('button',label,on?'on':'');b.type='button';b.setAttribute('aria-pressed',String(on));
b.onclick=()=>{statsDays=days;statsRange=null;loadStats().catch(e=>say(e.message,true));};return b;}));
const wrap=$('stats-range');
const open=node('button',undefined,'btn'+(statsRange?' on':''));open.type='button';open.setAttribute('aria-haspopup','dialog');
open.append(svgIcon(IC.calendar,'i m'),statsRange?shortDay(statsRange.start)+' a '+shortDay(statsRange.end):'Escolher datas');
open.onclick=e=>{e.stopPropagation();const pop=wrap.querySelector('.pop');if(pop){pop.remove();return;}wrap.append(calendar());};
wrap.replaceChildren(open);
}
// The calendar: presets on the left, a month where a click starts the
// period and the next one ends it.
function calendar(){
const pop=node('div',undefined,'pop calpop');pop.setAttribute('role','dialog');pop.setAttribute('aria-label','Escolher o período');
pop.onclick=e=>e.stopPropagation();
const today=todayIso();
let pick=statsRange?{...statsRange}:null, month=new Date((statsRange?.end||today)+'T12:00:00');month.setDate(1);
const presets=node('div',undefined,'presets'),grid=node('div',undefined,'dgrid'),title=node('b');
const label=node('span','','lbl');
const apply=node('button','Aplicar','btn pri');apply.type='button';
const cancel=node('button','Cancelar','btn ghost right');cancel.type='button';cancel.onclick=()=>pop.remove();
apply.onclick=()=>{if(!pick?.end)return;statsRange=pick;pop.remove();loadStats().catch(e=>say(e.message,true));};
const back=n=>{const d=new Date(today+'T12:00:00');d.setDate(d.getDate()-n);return isoDay(d);};
const first=new Date(today+'T12:00:00');first.setDate(1);
const prevEnd=new Date(first);prevEnd.setDate(0);const prevStart=new Date(prevEnd);prevStart.setDate(1);
for(const [text,range] of [['Hoje',[today,today]],['Últimos 7 dias',[back(6),today]],['Últimos 30 dias',[back(29),today]],
['Este mês',[isoDay(first),today]],['Mês passado',[isoDay(prevStart),isoDay(prevEnd)]],['Últimos 90 dias',[back(89),today]]]){
const b=node('button',text,'preset');b.type='button';b.dataset.range=range.join('|');
b.onclick=()=>{pick={start:range[0],end:range[1]};month=new Date(range[1]+'T12:00:00');month.setDate(1);paint();};presets.append(b);
}
const prev=iconButton(IC.left,'Mês anterior',()=>{month.setMonth(month.getMonth()-1);paint();},'btn sq ghost');
const next=iconButton(IC.right,'Próximo mês',()=>{month.setMonth(month.getMonth()+1);paint();},'btn sq ghost');
const head=node('div',undefined,'mhd');head.append(title,prev,next);
function paint(){
title.textContent=month.toLocaleDateString('pt-BR',{month:'long',year:'numeric'}).replace(/^./,c=>c.toUpperCase());
next.disabled=isoDay(month)>=today.slice(0,8)+'01';
for(const b of presets.children){const [a,z]=b.dataset.range.split('|');b.classList.toggle('on',!!pick&&pick.start===a&&pick.end===z);}
const days=[...['D','S','T','Q','Q','S','S'].map(w=>node('span',w,'dow'))];
const start=new Date(month);start.setDate(1-start.getDay());
for(let i=0;i<42;i++){
const d=new Date(start);d.setDate(start.getDate()+i);const iso=isoDay(d);
if(i>=35&&d.getMonth()!==month.getMonth())break;
const end=pick?.end||pick?.start;
const cls=['day'];if(d.getMonth()!==month.getMonth())cls.push('mute');if(iso>today)cls.push('future');if(iso===today)cls.push('today');
if(pick&&iso===pick.start)cls.push('s');if(pick&&iso===end)cls.push('e');if(pick&&iso>pick.start&&iso<end)cls.push('in');
const b=node('button',undefined,cls.join(' '));b.type='button';b.append(node('span',String(d.getDate())));
b.setAttribute('aria-label',dayLabel(iso));b.disabled=iso>today;
b.onclick=()=>{if(!pick||pick.end)pick={start:iso,end:null};else if(iso<pick.start)pick={start:iso,end:pick.start};else pick.end=iso;paint();};
days.push(b);
}
grid.replaceChildren(...days);
label.textContent=pick?dayLabel(pick.start)+(pick.end?' a '+dayLabel(pick.end):', escolha o fim'):'Escolha o início';
apply.disabled=!pick?.end;
}
const monthBox=node('div',undefined,'month');monthBox.append(head,grid);
const body=node('div',undefined,'cal');body.append(presets,monthBox);
const foot=node('div',undefined,'popfoot');foot.append(label,cancel,apply);
pop.append(body,foot);paint();
document.addEventListener('click',()=>pop.remove(),{once:true});
return pop;
}
async function loadStats(){
const data=await api('/stats?'+(statsRange?'start='+statsRange.start+'&end='+statsRange.end:'days='+statsDays));
statsData=data;statsPeriod();
$('stats-note').textContent='Pedidos pagos de '+dayLabel(data.start)+' a '+dayLabel(data.end)+', sem testes e cancelados';
const hk=(label,value,unit,note)=>{const k=node('div',undefined,'hk');const b=node('b',value);if(unit)b.append(node('small',unit));
k.append(node('span',label),b,...(note?[node('em',note)]:[]));return k;};
const mk=(label,value,unit)=>{const k=node('div',undefined,'mk');const b=node('b',value);if(unit)b.append(node('small',unit));k.append(node('span',label),b);return k;};
const pct=n=>data.orders?Math.round(100*n/data.orders)+'%':'';
const [reais,centavos]=money(data.cents).split(',');
const hero=node('div',undefined,'hero');
hero.append(hk('Metros vendidos',metres(data.metres).replace(' m',''),'m',plural(data.orders,'pedido pago','pedidos pagos')),
hk('Recebido, com frete',reais,','+centavos,data.orders?'ticket médio de '+money(Math.round(data.cents/data.orders)):''),
hk('Do pagamento ao Finalizado',duration(data.lead.median_hours),'',data.lead.orders?'mediana de '+plural(data.lead.orders,'pedido','pedidos')+', sem o tempo em Aguardando contato':'nenhum finalizado no período'));
const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%';
const minis=node('div',undefined,'minis');
minis.append(mk('Pedidos pagos',String(data.orders)),
mk('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'),
mk('Com correção',String(data.corrected),pct(data.corrected)),
mk('Artes tratadas',String(data.treated.orders),pct(data.treated.orders)),
mk('Retrabalho da casa',share(rw.house.percent),'meta '+share(rw.house.goal_percent)),
mk('Aguardando contato',String(board.orders.filter(waitingContact).length),'agora'));
$('stats-kpis').replaceChildren(hero,minis);
statsChart($('stats-chart'),data.daily);
// Por máquina: what each printed, how fast, and what it has now.
const cap=board.printing_cap||2;
const machineRows=data.machines.map(m=>{
const tr=node('tr');if(!m.active)tr.classList.add('off');
const name=node('td');name.append(node('b',m.name+(m.active?'':', desativada')),
node('span',(m.orders?plural(m.orders,'pedido','pedidos'):'nada')+(m.last_finished?', último '+when(m.last_finished):''),'sub'));
const now=!m.id?'—':m.now.imp?(m.now.imp>=cap?'cheia':m.now.imp+' imprimindo')+(m.now.tra?', '+m.now.tra+' na fila':''):m.now.tra?m.now.tra+' na fila':'livre';
tr.append(name,node('td',m.orders?metres(m.metres):'—','r'),
node('td',m.metres_per_hour!=null?String(m.metres_per_hour).replace('.',',')+' m':'—','r'),node('td',now,'muted'));
return tr;});
$('stats-machines').replaceChildren(...(machineRows.length?machineRows:[emptyRow('Nenhuma máquina cadastrada.',4)]));
// Each way in apart (D-21): its orders, metres, money and time to Finalizado.
$('stats-origins').replaceChildren(...data.origins.map(o=>{const tr=node('tr');
tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'),
node('td',o.finished?duration(o.median_hours):'—','r'));
if(!o.orders)tr.classList.add('off');return tr;}));
// Who prepared the finals of the period's orders, for the designer's productivity.
const most=Math.max(1,...data.treated.by.map(t=>t.orders));
$('stats-treated').replaceChildren(...(data.treated.by.length?data.treated.by.map(t=>{
const row=node('div',undefined,'byrow'),track=node('span',undefined,'track'),fill=node('i');fill.style.width=(100*t.orders/most)+'%';track.append(fill);
row.append(node('span',t.who),track,node('b',String(t.orders)));return row;}):[node('p','Nenhuma arte tratada no período.','empty')]));
// Rework (D-02 to D-04): authorized metres redone over the film printed, against the goal.
const scale=Math.max(rw.goal_percent*2,...rw.causes.map(r=>r.percent||0))*1.15||1;
const meter=(value,goal)=>{const m=node('span',undefined,'meter'),track=node('span',undefined,'track'),fill=node('span',undefined,'fill'+(goal!=null&&value>goal?' warn':''));
fill.style.width=Math.min(100,100*(value||0)/scale)+'%';track.append(fill);
if(goal!=null){const g=node('span',undefined,'goal');g.style.left=Math.min(100,100*goal/scale)+'%';track.append(g);}
m.append(track,node('span',share(value),'mv'));return m;};
const reworkRows=rw.causes.map(r=>{const tr=node('tr'),outside=r.cause===REWORK_OUTSIDE;
const cause=node('td');cause.append(REWORK_CAUSES[r.cause]);if(outside)cause.append(node('span','fora da meta','sub'));
const cell=node('td');cell.append(meter(r.percent,outside?null:rw.goal_percent));
tr.append(cause,node('td',metres(r.metres),'r'),cell);if(!r.metres)tr.classList.add('off');return tr;});
const house=node('tr',undefined,'total');const hc=node('td');hc.append(meter(rw.house.percent,rw.house.goal_percent));
house.append(node('td','Total da casa'),node('td',metres(rw.house.metres),'r'),hc);
$('stats-rework').replaceChildren(...reworkRows,house);
$('stats-rework-film').textContent='Sobre '+metres(rw.film_metres)+' impressos. Meta de '+share(rw.goal_percent)+' por causa e '+share(rw.house.goal_percent)+' no total.';
const pending=$('stats-rework-pending-pill');pending.hidden=!rw.pending.length;
pending.replaceChildren(node('span',undefined,'dot'),plural(rw.pending.length,'aguardando autorização','aguardando autorização'));
const printers=rw.by_printer.map(p=>{const tr=node('tr');tr.append(node('td',p.who),node('td',metres(p.metres),'r'));return tr;});
$('stats-rework-printers').replaceChildren(...(printers.length?printers:[emptyRow('Nenhum retrabalho da casa autorizado no período.',2)]));
$('stats-rework-pending').replaceChildren(...(rw.pending.length?rw.pending.map(p=>{const li=node('li');
const open=node('button','#'+p.number,'linkbtn');open.type='button';open.onclick=()=>openPanel(p.order_id);
li.append(open,' '+REWORK_CAUSES[p.cause]+', '+metres(p.metres)+', aberto por '+p.opened_by+' em '+when(p.opened_at));return li;}):[node('li','Nenhum.','empty')]));
$('stats-stages').replaceChildren(...['rec','tra','imp','cor','rev'].map(state=>{
const tr=node('tr'),name=node('td'),line=node('span',undefined,'stagecell');
line.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')),board.states[state]);name.append(line);
const st=data.stages[state], now=data.waiting[state];
// Orders; when some came back to the stage, how many times it was entered.
const passed=st?plural(st.orders,'pedido','pedidos')+(st.passages>st.orders?', '+st.passages+' passagens':''):'nenhum';
name.append(node('span',passed,'sub'));
tr.append(name,node('td',st?duration(st.median_hours):'—','r strong'),
node('td',now?plural(now.orders,'pedido','pedidos')+', o mais antigo há '+duration(now.oldest_hours):'nenhum','muted'));
return tr;}));
}
const emptyRow=(text,span)=>{const tr=node('tr');const td=node('td',text,'empty');td.colSpan=span;tr.append(td);return tr;};
// Metres per day: one series of columns from one baseline, the period's
// average as a dashed line, today in full; the same numbers as a table below.
function statsChart(box,daily){
const max=Math.max(...daily.map(d=>d.metres),0);
const step=max<=0?1:(()=>{const raw=max/3, p=10**Math.floor(Math.log10(raw)), f=raw/p;return (f<=1?1:f<=2?2:f<=5?5:10)*p;})();
const ceiling=step*Math.max(1,Math.ceil(max/step));
const avg=daily.length?daily.reduce((t,d)=>t+d.metres,0)/daily.length:0;
const today=todayIso();
const chart=node('div',undefined,'chart'),yaxis=node('div',undefined,'yaxis'),plot=node('div',undefined,'plot');
yaxis.setAttribute('aria-hidden','true');
for(let v=0;v<=ceiling+1e-9;v+=step){const at=100*v/ceiling+'%';
const t=node('span',v.toLocaleString('pt-BR'));t.style.bottom=at;yaxis.append(t);
if(v>0){const g=node('span',undefined,'gl');g.style.bottom=at;plot.append(g);}}
if(avg>0){const a=node('span',undefined,'avg');a.style.bottom=100*avg/ceiling+'%';plot.append(a);}
const bars=node('div',undefined,'bars'),axis=node('div',undefined,'axis');axis.setAttribute('aria-hidden','true');
bars.style.gridTemplateColumns=axis.style.gridTemplateColumns='repeat('+daily.length+',minmax(0,1fr))';
const every=Math.ceil(daily.length/10);
daily.forEach((d,i)=>{
const b=node('span',undefined,'bar'+(d.day===today?' now':''));b.style.height=(d.metres>0?Math.max(1,100*d.metres/ceiling):0)+'%';
b.style.animationDelay=Math.min(i*12,400)+'ms';
b.dataset.tip=shortDay(d.day)+': '+metres(d.metres)+', '+plural(d.orders,'pedido','pedidos');
if(i<3)b.classList.add('tip-r');else if(i>daily.length-4)b.classList.add('tip-l');
bars.append(b);axis.append(node('span',(daily.length-1-i)%every===0?shortDay(d.day):''));
});
plot.append(bars,axis);
plot.setAttribute('role','img');plot.setAttribute('aria-label','Metros vendidos por dia, '+daily.length+' dias, média de '+metres(avg));
chart.append(yaxis,plot);
$('stats-legend').replaceChildren(...[['lg-avg','média de '+metres(avg)],['lg-now','hoje']].map(([c,t])=>{const s=node('span');s.append(node('i',undefined,c),t);return s;}));
const table=node('details',undefined,'charttable');table.append(node('summary','Ver em tabela'));
const t=node('table',undefined,'table');const head=node('tr');head.append(node('th','Dia'),node('th','Pedidos','r'),node('th','Metros','r'));
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const d of [...daily].reverse()){const tr=node('tr');tr.append(node('td',dayLabel(d.day)),node('td',String(d.orders),'r'),node('td',metres(d.metres),'r'));tbody.append(tr);}
t.append(thead,tbody);table.append(t);
box.replaceChildren(chart,table);
}
// ---- Quotes --------------------------------------------------------------
function quoteMetres(q){return (q.approved||q.draft).items.reduce((s,i)=>s+Number(i.billed_metres||i.metres),0);}
let quoteRows=[], quoteTotal=0, quotePage=1, quoteSize=0, currentQuote=null, quoteLoading=0, quoteFitting=0;
// Cotações never scrolls: a page holds as many quotes as the list's height fits.
// Before the first page, a guess from the height; after it, measured rows.
function guessQuoteSize(){return Math.max(3,Math.floor(($('quote-list').clientHeight||600)/88));}
function fitQuotes(){
const list=$('quote-list'), rows=[...list.querySelectorAll('.qrow')];
if($('tab-quotes').hidden||!rows.length||quoteFitting>3)return;
const room=list.clientHeight, gap=4;
const fits=rows.filter(r=>r.offsetTop-list.offsetTop+r.offsetHeight<=room).length;
const tallest=Math.max(...rows.map(r=>r.offsetHeight));
let size=quoteSize;
if(fits<rows.length)size=Math.max(1,fits);
else if(quoteTotal>(quotePage-1)*quoteSize+rows.length||rows.length<quoteSize){
const used=rows.at(-1).offsetTop-list.offsetTop+rows.at(-1).offsetHeight;
size=rows.length+Math.max(0,Math.floor((room-used)/(tallest+gap)));
}
if(size===quoteSize)return;
const first=(quotePage-1)*quoteSize;quoteSize=size;quotePage=Math.floor(first/size)+1;quoteFitting++;
loadQuotes().catch(e=>say(e.message,true));
}
let quoteResize=null;
addEventListener('resize',()=>{clearTimeout(quoteResize);quoteResize=setTimeout(()=>{quoteFitting=0;fitQuotes();},200);});
async function loadQuotes(){
const token=++quoteLoading;
if(!quoteSize)quoteSize=guessQuoteSize();
const params=new URLSearchParams({kind:quoteKind,limit:String(quoteSize),offset:String((quotePage-1)*quoteSize)});
for(const [key,value] of [['q',quoteQuery],['product',quoteProduct],['layout',quoteLayout],['flag',quoteFlag]])if(value)params.set(key,value);
const page=absorb(await api('/quotes?'+params));
if(token!==quoteLoading)return;
quoteRows=page.quotes;quoteTotal=page.total;
if(quotePage>1&&!quoteRows.length&&quoteTotal){quotePage=Math.ceil(quoteTotal/quoteSize);return loadQuotes();}
renderQuotes();
}
// What a quote needs looked at, in a word: shown on its row.
function quoteWarning(q){
const items=q.draft.items;
if(items.some(i=>!LAYOUT_VERSIONS.includes(i.production?.version)))return ['bad','Montagem antiga: peça uma nova cotação'];
if(!q.approved&&q.review_reason)return ['warn',q.review_reason];
if(items.some(i=>i.quality_status==='warning'))return ['warn','Ressalva de resolução aceita'];
return null;
}
function renderQuotes(){
const kinds=[['pending','A revisar',board.pending_total],['approved','Aguardando pagamento',board.approved_total]];
$('quote-filters').replaceChildren(...kinds.map(([key,label,count])=>{
const b=node('button',label,quoteKind===key?'on':'');b.type='button';b.setAttribute('aria-pressed',String(quoteKind===key));
b.append(node('span',String(count??0),'n'));
b.onclick=()=>{quoteKind=key;quotePage=1;quoteFitting=0;currentQuote=null;loadQuotes().catch(e=>say(e.message,true));};return b;}));
// Product, layout and warning: each toggles; the two of a pair exclude each other.
const toggles=[['product','textil','Têxtil'],['product','uv','UV'],['layout','folha','Folha montada'],
['layout','avulsa','Artes avulsas'],['flag','ressalva','Com ressalva']];
const value={product:quoteProduct,layout:quoteLayout,flag:quoteFlag};
$('quote-chips').replaceChildren(...toggles.map(([group,key,label])=>{
const b=node('button',label,'tg'+(value[group]===key?' on':''));b.type='button';b.setAttribute('aria-pressed',String(value[group]===key));
b.onclick=()=>{const next=value[group]===key?'':key;
if(group==='product')quoteProduct=next;else if(group==='layout')quoteLayout=next;else quoteFlag=next;
quotePage=1;quoteFitting=0;loadQuotes().catch(e=>say(e.message,true));};return b;}));
if(!currentQuote||(!quoteRows.some(q=>q.id===currentQuote.id)&&currentQuote.status==='pending_review'))currentQuote=quoteRows[0]||null;
else currentQuote=quoteRows.find(q=>q.id===currentQuote.id)||currentQuote;
const list=quoteRows.map(q=>{
const b=node('button',undefined,'qrow'+(q.id===currentQuote?.id?' on':''));b.type='button';b.dataset.quotePick=q.id;
b.setAttribute('aria-current',String(q.id===currentQuote?.id));
const items=q.draft.items, who=buyer(q.draft);
const main=node('span',undefined,'qmain');
const first=node('span',undefined,'qline');
const name=node('b',who.title);name.title=who.mail||who.title;
// A quote from the last ten minutes carries a dot: someone just ordered.
if(Date.now()-new Date(q.created_at)<600000){const dot=node('span',undefined,'newdot');dot.title='Chegou agora';name.prepend(dot);}
first.append(name,node('span',q.approved?money(q.approved.total_cents):metres(quoteMetres(q)),'qm'));
const second=node('span',undefined,'qline sub');
const what=node('span');what.append(gradePill(lowestGrade(items)),' '+productLine(items)+', '+(q.draft.destination?q.draft.destination.city+'/'+q.draft.destination.state:'Retirada'));
second.append(what,node('span',shortAgo(q.created_at)));
main.append(first,second);
const warn=quoteWarning(q);
if(warn){const w=node('span',undefined,'qwarn'+(warn[0]==='bad'?' bad':''));w.append(svgIcon(IC.alert,'i s'),node('span',warn[1]));main.append(w);}
const pay=paymentBadge(q.payment);
// Approved by the Site is the rule; only a person's review is worth a word.
if(pay||q.approved&&!q.auto_approved){const line=node('span',undefined,'qpay');
if(pay)line.append(pay);if(q.approved&&!q.auto_approved)line.append(badge('Revisada pela equipe',''));main.append(line);}
b.append(artBox(items,'qthumb'),main);b.onclick=()=>{currentQuote=q;renderQuotes();};return b;
});
const filtered=quoteQuery||quoteProduct||quoteLayout||quoteFlag;
if(!list.length)list.push(node('p',filtered?'Nenhuma cotação com esses filtros.':
quoteKind==='pending'?'Nenhuma cotação para revisar.':'Nenhuma cotação aprovada aguardando pagamento.','empty pad'));
$('quote-list').replaceChildren(...list);
$('quote-pager').replaceChildren(...(quoteTotal?[pager({page:quotePage,size:quoteSize,total:quoteTotal,noun:'cotações',compact:true,fixedSize:true,
onPage:n=>{quotePage=n;quoteFitting=0;loadQuotes().catch(e=>say(e.message,true));}})]:[]));
requestAnimationFrame(fitQuotes);
$('reviews').replaceChildren(...(currentQuote?review(currentQuote):[emptyState(IC.file,'Selecione uma cotação','A revisão dela abre aqui.')]));
}
// A page or a pane with nothing to show: a mark, a line, and what to do.
function emptyState(d,title,text){
const box=node('div',undefined,'emptystate'),ico=node('span',undefined,'dropico');ico.append(svgIcon(d));
box.append(ico,node('b',title),...(text?[node('span',text)]:[]));return box;
}
const QUOTE_STATUS={pending_review:['A revisar','warn'],approved:['Aprovada, aguardando pagamento','ok'],expired:['Expirada','bad'],paid:['Paga','ok']};
function review(quote){
const head=node('div',undefined,'rhead');head.dataset.quote=quote.id;
const words=node('div',undefined,'rwords');
const who=buyer(quote.draft), c=quote.draft.customer;
const title=node('div',undefined,'rtitle');
const h=node('h2',who.title);h.title=who.legal||who.title;
const [label,tone]=QUOTE_STATUS[quote.status]||[quote.status,''];
const status=badge(label,tone);status.prepend(node('span',undefined,'dot'));
title.append(h,status);
const pay=paymentBadge(quote.payment);if(pay)title.append(pay);
const meta=node('div',undefined,'rmeta');
if(who.mail)meta.append(node('span',who.mail));
const doc=node('span');doc.append(docKind(c.cnpj)+' '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar '+docKind(c.cnpj)));meta.append(doc);
const dest=quote.draft.destination,where=node('span');where.append(svgIcon(dest?IC.truck:IC.pin,'i s'),dest?'Entrega em '+dest.city+'/'+dest.state:'Retirada em Franca');meta.append(where);
meta.append(node('span','Recebida '+ago(quote.created_at)),node('span','#'+quote.id.slice(0,8),'code'));
words.append(title,meta);head.append(words);
if(quote.approved){const total=node('div',undefined,'qbig');total.append(node('span','Total','lbl'),node('b',money(quote.approved.total_cents)));head.append(total);}
const zap=whatsappLink(c.zap);
if(zap){const a=node('a','WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=c.zap;a.prepend(svgIcon(IC.chat,'i m'));head.append(a);}
const body=node('div',undefined,'rbody');
const foot=node('div',undefined,'rfoot');
if(quote.status==='pending_review'&&quote.draft.items.some(item=>!LAYOUT_VERSIONS.includes(item.production?.version))){
body.append(callout(IC.alert,'Montagem antiga.','Solicite uma nova cotação ao cliente.','bad'));
return [head,body];
}
const count=quote.draft.items.length;
if(quote.status!=='pending_review'){
if(quote.status==='expired')body.append(callout(IC.alert,'Cotação expirada.','O cliente precisa solicitar outra.','bad'));
quote.draft.items.forEach((item,index)=>body.append(quoteItem(item,null,quote.approved?.items?.[index],index,count)));
if(quote.approved){
const sums=node('div',undefined,'qsums');const fr=quote.approved.freight||{};
const itemsTotal=quote.approved.items.reduce((t,i)=>t+i.total_cents,0);
sums.append(node('span','Itens'),node('b',money(itemsTotal)),
node('span',fr.service==='pickup'||!fr.total_cents?'Retirada':'Frete Jadlog'+(fr.weight_kg?', '+freightWeight(fr):'')),
node('b',fr.total_cents?money(fr.total_cents):'grátis'),node('span','Total'),node('b',money(quote.approved.total_cents)));
body.append(sums);
}
if(quote.status==='approved'&&may('enter'))body.append(registerForm(quote));
if(quote.status==='approved'&&may('manage')){
foot.append(discardButton(quote));
// Tries the whole production flow without a payment.
const test=button('Criar pedido de teste',async()=>{
if(!await ask('Criar um pedido de teste?','Ele entra em Arte recebida sem cobrar nada e não vai para o Tiny.','Criar pedido de teste'))return;
const order=await api('/quotes/'+quote.id+'/test-order',{});
say('Pedido de teste #'+order.number+' criado em Arte recebida.');await load();
},'btn right');
foot.append(test);
return [head,body,foot];
}
return [head,body];
}
if(!may('manage')){
quote.draft.items.forEach((item,index)=>body.append(quoteItem(item,null,null,index,count)));
return [head,body];
}
const form=node('form',undefined,'rform');
const edits=quote.draft.items.map((item,index)=>{const fields={};body.append(quoteItem(item,fields,null,index,count));
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});
const check=node('input');check.required=true;
const submit=node('button','Aprovar cotação','btn pri lg');
foot.append(checkbox('Arquivos, metragem e nota conferidos',check),discardButton(quote),submit);
form.append(body,foot);
form.onsubmit=async e=>{e.preventDefault();submit.disabled=true;
try{const approved=await api('/quotes/'+quote.id+'/approve',{items:edits.map(fn=>fn())});
// Keep showing the quote just approved while its list refreshes.
currentQuote={...quote,approved,status:'approved'};say('Cotação aprovada.');await load();}
catch(error){say(error.message,true);submit.disabled=false;}};
return [head,form];
}
function callout(d,title,text,tone=''){
const box=node('div',undefined,'callout'+(tone?' '+tone:'')),ico=node('span',undefined,'cico');ico.append(svgIcon(d,'i m'));
const p=node('p');p.append(node('b',title+' '),text||'');box.append(ico,p);return box;
}
// An order paid outside the site (Dropstar's rule D-35): the team builds the
// cart on the Site, as a customer would, and registers it here. Origin and
// payment start unchosen: a default would become the answer to everything.
const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente'};
function registerForm(quote){
const form=node('form',undefined,'register');
const group=(name,label,options)=>{
const g=node('div',undefined,'fgroup2');g.setAttribute('role','radiogroup');g.setAttribute('aria-label',label);
const set=node('div',undefined,'fopts');
for(const [value,text] of Object.entries(options)){
const l=node('label',undefined,'fopt'),r=node('input');
r.type='radio';r.name=name+'-'+quote.id;r.value=value;r.required=true;r.className='vh';l.append(r,text);set.append(l);}
g.append(node('span',label,'lbl'),set);return g;};
const note=node('input');note.type='text';note.maxLength=300;note.placeholder='Observação (opcional)';note.setAttribute('aria-label','Observação');note.className='inp';
const submit=node('button','Registrar pedido','btn pri');
const row=node('div',undefined,'decide');row.append(note,submit);
const head=node('div');head.append(node('h4','Pago fora do site?'),node('p','Registre o pedido: ele entra em Arte recebida como os outros.','nnote'));
form.append(head,group('origin','Origem',ORIGINS),group('method','Como foi pago',PAID_OUTSIDE),row);
form.onsubmit=async e=>{e.preventDefault();
const pick=name=>form.querySelector('input[name="'+name+'-'+quote.id+'"]:checked')?.value;
submit.disabled=true;
try{const order=await api('/quotes/'+quote.id+'/register',{origin:pick('origin'),method:pick('method'),note:note.value});
currentQuote=null;say('Pedido #'+order.number+' registrado em Arte recebida.');await load();}
catch(error){say(error.message,true);submit.disabled=false;}};
return form;
}
const paidOutside=order=>order.payment?.provider==='manual';
// An unpaid quote leaves the list and can no longer be paid.
function discardButton(quote){
return button('Descartar cotação',async()=>{
if(!await ask('Descartar esta cotação?','Ela sai do Kanban e o cliente não consegue mais pagá-la.','Descartar cotação',{tone:'red'}))return;
await api('/quotes/'+quote.id+'/discard',{});currentQuote=null;say('Cotação descartada.');await load();
},'btn quiet right');
}
function quoteItem(item,fields,priced,index=0,count=1){
const box=node('section',undefined,'ritem');box.setAttribute('aria-label','Item '+(index+1));
const tall=node('div',undefined,'tall');tall.tabIndex=0;tall.setAttribute('aria-label','Montagem da folha. Role para ver tudo.');
tall.append(itemPreview(item));
const info=node('div',undefined,'iinfo');
const spec=item.production;
info.append(node('span',count>1?'Item '+(index+1)+' de '+count:'Item','lbl'),node('h3',PRODUCT[item.mode]));
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('Peças',spec?String(spec.placements.length):null);
pair('Arquivos',spec?String(spec.sources.length):null);
const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g);
pair('Metros cobrados',priced?metres(priced.billed_metres):null);
pair('Valor do metro',priced?money(priced.unit_cents)+manualExtra(priced):null);
pair('Valor',priced?money(priced.total_cents):null);
info.append(dl);
const notes=node('div',undefined,'inotes');
notes.append(item.quality_status==='ok'?itemNote('Qualidade conferida','ok'):item.quality_status==='warning'?
itemNote(item.quality_acknowledged?'Ressalva de resolução aceita pelo cliente':'Ressalva de resolução não aceita','warn'):itemNote('Qualidade não conferida'));
if(item.residue_accepted)notes.append(itemNote('Resíduo aceito pelo cliente: '+residueNote(item)+'.','warn'));
info.append(notes);
if(fields){
const grid=node('div',undefined,'inputs');
fields.metres=node('input');Object.assign(fields.metres,{type:'number',min:'0.001',max:'12000',step:'any',value:item.metres,required:true});
fields.grade=node('input');Object.assign(fields.grade,{type:'number',min:'0',max:'100',step:'1',value:item.grade,required:true});
const m=field('Metros conferidos',fields.metres,'O cliente pediu '+metres(item.metres));
const low=Number(item.grade)<60;
const gr=field('Nota conferida',fields.grade,low?'Nota baixa: confira a resolução':'A nota que o Site deu');
if(low)gr.classList.add('warn');
grid.append(m,gr);info.append(grid);
}
const links=node('div',undefined,'links');
item.uploads.forEach((uid,i)=>links.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Arquivo original',download(uid),'btn')));
if(spec?.placements){const b=button('Manifesto',()=>manifest(spec),'btn');b.prepend(svgIcon(IC.file,'i m'));links.append(b);}
info.append(links);box.append(tall,info);return box;
}
// A finished sheet someone opens by hand pays this per metre on top (app/core/pricing.py).
const manualExtra=item=>item?.manual_extra_cents?' (com '+money(item.manual_extra_cents)+' de arquivo manual)':'';
// ---- Payments and integrations ------------------------------------------
const tinyResult=new URLSearchParams(location.search).get('tiny');
const tinyNotice=tinyResult?(tinyResult==='connected'?' · Tiny conectado.':' · Não foi possível conectar o Tiny. Tente de novo.'):'';
if(tinyResult)history.replaceState(null,'',location.pathname);
function tinyHeader(){
const t=board.tiny||{};const el=$('tiny');
if(!t.configured){el.textContent='';return;}
el.textContent=!t.connected?'Tiny não conectado':t.problem?'Tiny: verificar conexão':'';
el.style.setProperty('--dot','var(--warn)');
}
const TINY_PROBLEMS={refused:'O Tiny recusou a renovação da conexão. Conecte de novo.',
expired:'A conexão com o Tiny expirou. Conecte de novo.',
'renewal-failing':'A última renovação falhou; o sistema tenta de novo sozinho.',
expiring:'A conexão expira em breve e não está sendo renovada.'};
function tinyDetail(t){
if(!t.connected_by)return 'Conecte com uma conta do Tiny.';
const parts=[t.connected_by+' · conectado em '+when(t.connected_at),'renovado em '+when(t.renewed_at),
t.offline?'sem expiração diária':t.expires_at?'válido até '+when(t.expires_at):'',
'envio de pedidos '+(t.orders_enabled?'ativo':'desativado')].filter(Boolean);
const problem=TINY_PROBLEMS[t.problem];
return (problem?problem+(t.failed_at&&t.problem!=='expired'?' (falha em '+when(t.failed_at)+')':'')+' · ':'')+parts.join(' · ');
}
// One row of Integrações: its mark, name and state, one line of summary and
// the main button. Anything longer (how-tos, dates, numbers, secondary
// buttons) opens under "Detalhes", so every row keeps the same height. Which
// rows are open survives the page's automatic refresh.
const OPEN_INTEG=new Set();
const INTEG_ICONS={'Pastas dos pedidos':IC.folder,'Tiny':IC.box,'Mercado Pago':IC.card,'Frete':IC.truck,'E-mail':IC.mail,'Backup do banco':IC.database};
const TONE_PILL={ok:'ok',warn:'warn',off:''};
function statePill(text,tone){const p=badge(text,TONE_PILL[tone]??tone);p.prepend(node('span',undefined,'dot'));return p;}
function integration({name,state,tone,summary,actions=[],details=[],extra=[]}){
const row=node('div',undefined,'integ');row.dataset.integ=name;
const main=node('div',undefined,'irow');
const ico=node('span',undefined,'iico');ico.append(svgIcon(INTEG_ICONS[name]||IC.link));
const title=node('span',undefined,'iname');title.append(node('b',name),statePill(state,tone));
const text=node('p',summary);text.title=summary;
const buttons=node('span',undefined,'iact');buttons.append(...actions);
main.append(ico,title,text,buttons);row.append(main);
if(!details.length&&!extra.length)return row;
const panel=node('div',undefined,'idetails');panel.id='integ-'+name.replace(/\W+/g,'-').toLowerCase();
const list=node('dl');
for(const part of details){
if(Array.isArray(part)){const d=node('div');d.append(node('dt',part[0]),node('dd',part[1]));list.append(d);continue;}
if(list.children.length){panel.append(list.cloneNode(true));list.replaceChildren();}
panel.append(part);
}
if(list.children.length)panel.append(list);
if(extra.length){const b=node('div',undefined,'nact');b.append(...extra);panel.append(b);}
const open=OPEN_INTEG.has(name);panel.hidden=!open;
const toggle=node('button','Detalhes','btn ghost integ-more');toggle.type='button';
toggle.append(svgIcon(IC.down,'i s'));toggle.setAttribute('aria-expanded',String(open));toggle.setAttribute('aria-controls',panel.id);
toggle.onclick=()=>{const now=panel.hidden;panel.hidden=!now;toggle.setAttribute('aria-expanded',String(now));
if(now)OPEN_INTEG.add(name);else OPEN_INTEG.delete(name);};
buttons.append(toggle);row.append(panel);return row;
}
// The page bar under every list: page size, range, first/previous/page/next/last.
const PAGE_SIZES=[10,20,50,100];
function pager({page,size,total,noun,onPage,onSize,compact=false,fixedSize=false}){
const pages=Math.max(1,Math.ceil(total/size));
const bar=node('div',undefined,'pager'+(compact?' compact':''));
const sizeLabel=node('label',undefined,'pager-size');
const select=node('select');select.setAttribute('aria-label','Itens por página');
for(const n of PAGE_SIZES){const o=node('option',String(n));o.value=String(n);o.selected=n===size;select.append(o);}
select.onchange=()=>onSize(Number(select.value));
sizeLabel.append('Mostrar',select,'por página');
const nav=node('div',undefined,'pager-nav');
const from=total?(page-1)*size+1:0, to=Math.min(total,page*size);
const go=(d,aria,target,disabled)=>{const b=iconButton(d,aria,()=>onPage(target),'btn sq ghost pg');b.disabled=disabled;return b;};
const pageLabel=node('label',undefined,'pager-page');
const input=node('input');input.type='number';input.min='1';input.max=String(pages);input.value=String(page);input.setAttribute('aria-label','Página');
input.onchange=()=>onPage(Math.min(pages,Math.max(1,Math.round(Number(input.value))||1)));
pageLabel.append(compact?'':'Página',input,'de '+pages);
nav.append(go(IC.first,'Primeira página',1,page<=1),go(IC.left,'Página anterior',page-1,page<=1),pageLabel,
go(IC.right,'Próxima página',page+1,page>=pages),go(IC.last,'Última página',pages,page>=pages));
bar.append(...(fixedSize?[]:[sizeLabel]),node('span',(compact?'':'Mostrando ')+from+' a '+to+' de '+total+(compact?'':' '+noun),'pager-range'),nav);
return bar;
}
function moreButton(container,has,fn){
if(!has)return;
const b=button('Carregar mais',fn,'btn ghost');b.style.alignSelf='flex-start';b.style.marginTop='8px';container.append(b);
}
// Payments needing a person: paged, open or resolved (history).
let issueState='open', issueRows=[], issueTotal=0, issuePage=1, issueSize=20, issueLoading=0;
async function loadIssues(){
const token=++issueLoading;
const page=await api('/payment-events?'+new URLSearchParams({state:issueState,limit:String(issueSize),offset:String((issuePage-1)*issueSize)}));
if(token!==issueLoading)return;
issueRows=page.issues;issueTotal=page.total;
if(issuePage>1&&!issueRows.length&&issueTotal){issuePage=Math.ceil(issueTotal/issueSize);return loadIssues();}
renderIssues();
}
function renderIssues(){
const seg=node('div',undefined,'seg');seg.setAttribute('role','group');seg.setAttribute('aria-label','Situação');
for(const [key,label] of [['open','Abertos'],['resolved','Resolvidos'],['all','Todos']]){
const b=node('button',label,issueState===key?'on':'');b.type='button';b.setAttribute('aria-pressed',String(issueState===key));
if(key==='open')b.append(node('span',String(board.payment_issues_total||0),'n'));
b.onclick=()=>{issueState=key;issuePage=1;loadIssues().catch(e=>say(e.message,true));};seg.append(b);
}
const tools=node('div',undefined,'pagetools');tools.append(seg,node('span','Pagamentos que o sistema não conseguiu ligar a um pedido sozinho.','lbl'));
if(!issueRows.length){
$('payments').replaceChildren(tools,emptyState(IC.check,issueState==='resolved'?'Nenhum pagamento resolvido':'Nenhum pagamento pendente',
issueState==='open'?'Quando um pagamento precisar de alguém, ele aparece aqui.':''));
return;
}
const table=node('table',undefined,'table');
const head=node('tr');for(const [t,c] of [['Quando'],['O que aconteceu'],['Referência'],['Valor pago','r'],['']]){const th=node('th',t,c);th.scope='col';head.append(th);}
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const issue of issueRows){
const tr=node('tr');
const refused=issue.outcome.startsWith('refused');
const kind=issue.resolved_at?statePill('Resolvido','ok'):statePill(refused?'Recusado':'Atenção',refused?'bad':'warn');
const what=node('td');what.append(kind,node('span',outcomeText(issue.outcome),'sub'));
if(issue.resolved_at)what.append(node('span','Por '+issue.resolved_by+' em '+when(issue.resolved_at)+': '+issue.resolution,'sub'));
const ref=node('td');ref.append(node('span',issue.reference?'Cotação '+String(issue.reference).slice(0,8):'Sem cotação','code'),node('span',issue.provider+', evento '+issue.event_id,'sub'));
const act=node('td',undefined,'r');
if(!issue.resolved_at){
if(may('manage'))act.append(button('Registrar resolução',async()=>resolveDialog(issue),'btn'));
else act.append(node('span','Aguarda a Gestão','lbl'));
}
tr.append(node('td',when(issue.received_at),'nowrap muted'),what,ref,node('td',issue.amount_cents==null?'Sem valor':money(issue.amount_cents),'r nowrap strong'),act);
tbody.append(tr);
}
table.append(thead,tbody);
const panel=node('div',undefined,'panel clip');
panel.append(table,pager({page:issuePage,size:issueSize,total:issueTotal,noun:'pagamentos',
onPage:n=>{issuePage=n;loadIssues().catch(e=>say(e.message,true));},
onSize:n=>{issueSize=n;issuePage=1;loadIssues().catch(e=>say(e.message,true));}}));
$('payments').replaceChildren(tools,panel);
}
function resolveDialog(issue){
const note=node('textarea');note.placeholder='Ex.: estornado no Mercado Pago, cliente avisado';note.setAttribute('aria-label','Resolução');
note.required=true;note.minLength=3;note.maxLength=1000;
formDialog('Registrar a resolução',{width:540,
text:(issue.amount_cents==null?'Pagamento sem valor informado':'Pagamento de '+money(issue.amount_cents))+': '+outcomeText(issue.outcome)+'.',
fields:[field('O que foi feito',note,'Fica no histórico do pagamento.')],label:'Registrar resolução',
onsave:async()=>{await api('/payment-events/'+issue.id+'/resolve',{note:note.value});say('Resolução registrada.');await load();}});
}
// The integration send log: filtered and paged on the server.
let eventFilter={status:'',event:'',order:''}, eventRows=[], eventTotal=0, eventPage=1, eventSize=20, eventLoading=0, eventTimer=null;
async function loadEvents(){
const token=++eventLoading;
const params=new URLSearchParams({limit:String(eventSize),offset:String((eventPage-1)*eventSize)});
for(const [key,value] of Object.entries(eventFilter))if(value)params.set(key,value);
const page=await api('/events?'+params);
if(token!==eventLoading)return;
eventRows=page.events;eventTotal=page.total;
if(eventPage>1&&!eventRows.length&&eventTotal){eventPage=Math.ceil(eventTotal/eventSize);return loadEvents();}
renderEvents();
}
function eventFilters(){
const bar=$('event-filters');if(bar.dataset.ready)return;bar.dataset.ready='1';
const seg=node('div',undefined,'seg');seg.setAttribute('role','group');seg.setAttribute('aria-label','Situação do envio');
const paint=()=>{for(const b of seg.children){const on=b.dataset.value===eventFilter.status;b.classList.toggle('on',on);b.setAttribute('aria-pressed',String(on));}};
for(const [value,text] of [['','Todos'],['delivered','Enviados'],['queued','Na fila'],['failing','Com erro']]){
const b=node('button',text);b.type='button';b.dataset.value=value;
b.onclick=()=>{eventFilter.status=value;paint();eventPage=1;loadEvents().catch(e=>say(e.message,true));};seg.append(b);
}
paint();
const s=node('select',undefined,'inp sm');s.setAttribute('aria-label','Evento');
for(const [value,text] of [['','Todos os eventos'],...Object.entries(EVENTS)]){const o=node('option',text);o.value=value;s.append(o);}
s.onchange=()=>{eventFilter.event=s.value;eventPage=1;loadEvents().catch(e=>say(e.message,true));};
const input=node('input',undefined,'inp sm num');input.type='number';input.min='1';input.placeholder='Pedido nº';input.setAttribute('inputmode','numeric');input.setAttribute('aria-label','Pedido');
input.oninput=()=>{clearTimeout(eventTimer);eventTimer=setTimeout(()=>{eventFilter.order=input.value.trim();eventPage=1;loadEvents().catch(e=>say(e.message,true));},350);};
bar.append(seg,s,input);
}
function eventResult(e){
const receipt=e.receipt||{};
if(e.delivered_at){
const situacao=receipt.situacao?' · '+receipt.situacao:'';
if(receipt.status==='created')return ['Criado no Tiny nº '+receipt.tiny_number+situacao,'good'];
if(receipt.status==='already-created')return ['Já existia no Tiny nº '+receipt.tiny_number+' (reenvio)'+situacao,'good'];
if(receipt.status==='status-updated')return ['Tiny nº '+receipt.tiny_number+situacao,'good'];
if(receipt.status==='status-unchanged')return ['Tiny nº '+receipt.tiny_number+' já estava'+situacao.replace(' · ',' em '),''];
if(receipt.status==='not-applicable')return ['Não se aplica ao Tiny',''];
return ['Registrado, sem envio',''];
}
if(e.last_error)return ['Nova tentativa · '+e.last_error+' (tentativa '+e.attempts+')','retry'];
return ['Na fila',''];
}
function renderEvents(){
const rows=eventRows.map(e=>{
const tr=node('tr');const [result,cls]=eventResult(e);
const cell=node('td');const pill=statePill(result,cls==='good'?'ok':cls==='retry'?'warn':'');pill.title=result;cell.append(pill);
tr.append(node('td',when(e.delivered_at||e.available_at),'nowrap muted'),node('td','#'+e.payload.number,'code'),
node('td',EVENTS[e.payload.event]||e.payload.event),cell);
return tr;
});
if(!rows.length){const tr=node('tr');const td=node('td','Nenhum envio encontrado.','empty');td.colSpan=4;tr.append(td);rows.push(tr);}
$('events').replaceChildren(...rows);
$('events-more').replaceChildren(pager({page:eventPage,size:eventSize,total:eventTotal,noun:'envios',
onPage:n=>{eventPage=n;loadEvents().catch(e=>say(e.message,true));},
onSize:n=>{eventSize=n;eventPage=1;loadEvents().catch(e=>say(e.message,true));}}));
}
// Integrações: the print room's folder for whoever produces, what is on and off
// for the managers, and the buttons, details and the Tiny log for the superadmin.
const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();};
// A row with only its name, state and summary, for whoever may not change it.
const integRow=o=>may('integrations')?integration(o):integration({name:o.name,state:o.state,tone:o.tone,summary:o.summary});
let mpCheck=null;
function renderIntegrations(){
const t=board.tiny||{};const rows=may('print')?[folderCard()]:[];
$('event-log').hidden=!may('integrations');
if(!may('manage')){$('integrations').replaceChildren(...rows);return;}
const act=(text,fn)=>button(text,fn,'btn');
const ghost=(text,fn)=>button(text,fn,'btn ghost');
if(!t.configured)rows.push(integRow({name:'Tiny',state:'Não configurado',tone:'off',summary:'Credenciais ausentes no servidor.'}));
else{
const connect=(text,cls)=>button(text,async()=>{const r=await api('/tiny/connect',{});location.href=r.url;},cls);
const test=act('Testar conexão',async()=>{const r=await api('/tiny/test',{});
say(r.ok?'Conexão com o Tiny ok: pedidos, contatos, os 4 produtos e a retirada conferidos.':'Tiny: '+Object.entries(r.results).filter(([,v])=>v!=='ok').map(([k,v])=>k+': '+v).join(' · '),!r.ok);});
const problem=TINY_PROBLEMS[t.problem];
rows.push(integRow({name:'Tiny',state:!t.connected?'Não conectado':t.problem?'Verificar':'Conectado',tone:t.connected&&!t.problem?'ok':'warn',
summary:problem||(t.connected_by?t.connected_by+' · envio de pedidos '+(t.orders_enabled?'ativo':'desativado'):'Conecte com uma conta do Tiny.'),
actions:t.connected?[test]:[connect('Conectar Tiny','btn')],
details:t.connected_by?[['Conta',t.connected_by],['Conectado em',when(t.connected_at)],['Renovado em',when(t.renewed_at)],
['Validade',t.offline?'Sem expiração diária':t.expires_at?'Até '+when(t.expires_at):'—'],
['Envio de pedidos',t.orders_enabled?'Ativo':'Desativado'],
...(t.failed_at&&t.problem!=='expired'?[['Última falha',when(t.failed_at)]]:[])]:[],
extra:t.connected?[connect('Reconectar','btn ghost')]:[]}));
}
const mp=board.providers?.payment==='mercadopago';
rows.push(integRow({name:'Mercado Pago',state:mp?'Ativo':'Não configurado',tone:mp?'ok':'off',
summary:mp?'PIX e cartão ativos.':'Aguardando credenciais.',
actions:mp?[ghost('Verificar conta',async()=>{mpCheck=await api('/mercadopago/check',{});OPEN_INTEG.add('Mercado Pago');renderIntegrations();})]:[],
details:mp&&mpCheck?mercadoPagoCheck(mpCheck):[]}));
const fr=board.providers?.freight||{};
const kg=v=>String(v).replace('.',',')+' kg';
const carriers=Object.values(fr.services||{});
const list=names=>names.length>1?names.slice(0,-1).join(', ')+' e '+names.at(-1):names[0];
rows.push(carriers.length
? integRow({name:'Frete',state:fr.box_cm?'Ativo':'Verificar',tone:fr.box_cm?'ok':'warn',
summary:fr.box_cm?list([...carriers,'retirada em Franca'])+' · prazo + '+fr.production_days+' dia(s) de produção.'
:'Caixa não configurada: as transportadoras podem cobrar mais que a cotação.',
details:[['Opções',list(carriers)],['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
...(fr.box_cm?[['Caixa',fr.box_cm.map(n=>String(n).replace('.',',')).join(' × ')+' cm'],
['Cubagem Jadlog',String(fr.cubage_kg_m3).replace('.',',')+' kg/m³ = '+kg(fr.cubed_kg)+' cubados'],
...(fr.metres_per_box?[['Por caixa','Até '+String(fr.metres_per_box).replace('.',',')+' m']]:[])]:[]),
// Each carrier charges the larger of the real and the cubed weight.
node('p','No carrinho o cliente vê todas as opções, da mais barata para a mais cara, com o prazo. Cada transportadora cobra o maior entre o peso real e o cubado.')]})
: integRow({name:'Frete',state:'Não configurado',tone:'off',summary:'Somente retirada.'}));
rows.push(mailRow(board.providers?.mail||{}));
const bk=board.providers?.backup||{};
const ontem=bk.last_ok&&Date.now()-new Date(bk.last_ok)<26*3600e3;
const tam=bk.bytes?(bk.bytes<1048576?Math.max(1,Math.round(bk.bytes/1024))+' KB':(bk.bytes/1048576).toFixed(1).replace('.',',')+' MB'):'';
const never=!bk.last_ok&&!bk.failed;
const now=may('integrations')&&!never?[button(bk.requested?'Pedido…':'Fazer backup agora',async()=>{
try{await api('/backup/run',{});say('Backup pedido: começa em até 1 minuto. Atualize para ver o resultado.');await load();}
catch(e){say(e.message,true);}},'btn')]:[];
if(bk.requested&&now[0])now[0].disabled=true;
rows.push(integRow({name:'Backup do banco',state:never?'Não configurado':ontem&&!bk.failed?'Em dia':'Verificar',
tone:never?'off':ontem&&!bk.failed?'ok':'warn',actions:now,
summary:bk.requested?'Backup pedido · começa em até 1 minuto.':
bk.failed?'A última tentativa falhou ('+when(bk.failed_at)+').':bk.last_ok?'Último em '+when(bk.last_ok)+(tam?' · '+tam:''):'Nenhum backup feito ainda.',
details:[...(bk.last_ok?[['Último backup',when(bk.last_ok)+(tam?' · '+tam:'')]]:[]),...(bk.failed?[['Erro',bk.failed]]:[]),
node('p','Cópia diária, criptografada, fora do servidor.')]}));
$('integrations').replaceChildren(...rows);
eventFilters();
}
// E-mail: the customers' messages (app/mail.py).
function mailRow(m){
const name='E-mail';
if(m.adapter!=='smtp'&&m.adapter!=='log')return integRow({name,state:'Não configurado',tone:'off',
summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'});
const local=m.adapter==='log';
return integRow({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'E-mails dos clientes: confirmação de pedido, recuperação de senha e códigos de confirmação.',
actions:[button('Enviar teste',async()=>{const r=await api('/mail/test',{});
say(local?'Teste registrado. Neste ambiente os e-mails ficam só no registro do servidor.':'Teste enviado para '+r.to+'. Confira a caixa de entrada (e o spam).');})],
details:[...(local?[node('p','Ambiente local: os e-mails não saem do servidor, ficam no registro do worker.')]:[]),
['Remetente',m.from||'—'],...(m.host?[['Servidor',m.host]]:[]),
['Último envio',m.last_sent?when(m.last_sent):'Nenhum ainda'],['Na fila',String(m.pending||0)],
...(m.error?[['Último erro',when(m.error.at)+' · '+m.error.error]]:[])]});
}
function mercadoPagoCheck(r){
const w=r.webhooks||{};
return [['Credencial',r.token==='test'?'De teste':'De produção'],
['Conta',r.account.error||r.account.nickname+' ('+r.account.id+')'+(r.account.test_user?' · usuário de teste':'')],
['Cartão de teste',Array.isArray(r.bin)?(r.bin.length?r.bin.map(o=>o.method+' '+o.type+' · '+o.issuer+' · até '+Math.max(...o.installments)+'x').join('; '):'Não reconhecido'):r.bin.error],
['Avisos em 24 h',w.accepted_24h+' aceitos, '+w.refused_24h+' recusados pela assinatura'],
['Último aviso',w.last?when(w.last.received_at)+' ('+w.last.status+')':'Nenhum recebido ainda']];
}
// ---- Wiring --------------------------------------------------------------
for(const b of document.querySelectorAll('[data-tab]'))b.onclick=()=>showTab(b.dataset.tab);
$('quote-q').oninput=e=>{clearTimeout(quoteTimer);quoteTimer=setTimeout(()=>{
quoteQuery=e.target.value.trim();quotePage=1;loadQuotes().catch(err=>say(err.message,true));},300);};
// ---- Search: orders (any stage) and unpaid quotes ---------------------------
// On a phone the search is behind a button, and opens over the top bar.
$('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();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(' + ')+' · '+(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;$('quote-q').value=quoteQuery;
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())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;});
restoreFolder().finally(()=>load());