Some checks failed
Dropstar's items 15 and 16 (2026-10-21). - an order above 10 m prints 20 cm of proof first; the room checks it and marks "Prova OK", without stopping the order, and without that mark the order cannot reach Finalizado - at checkout, "Quero aprovar uma prova antes de imprimir", for any length: the paid order arrives marked "Aguardando contato" with what to do, and waits for the customer's word on the photo sent by WhatsApp - the card shows Prova / Prova OK, the panel gives the next step, and "Prova a conferir" is a board filter; the designer cannot mark it - the proof is not billed, as Dropstar leans; rounds and which part of the sheet wait for their answer Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2005 lines
134 KiB
JavaScript
2005 lines
134 KiB
JavaScript
/* 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');
|
||
|
||
const STAGE_COLORS={rec:'var(--rec)',tra:'var(--tra)',fil:'var(--fil)',imp:'var(--imp)',cor:'var(--cor)',fin:'var(--fin)'};
|
||
const FLOW=['rec','tra','fil','imp','fin'];
|
||
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:'',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',vendedor:'Vendedor'};
|
||
// The designer moves cards only among the artwork stages; the queue onwards is the print room's (app/core/auth.py).
|
||
const DESIGNER_STATES=['rec','tra','cor'];
|
||
const mayMove=(from,to)=>may('produce')&&(ME?.role!=='designer'||DESIGNER_STATES.includes(from)&&DESIGNER_STATES.includes(to));
|
||
// Which tabs each capability opens.
|
||
const TAB_NEEDS={quotes:o=>may('manage')||ME?.role==='vendedor',payments:()=>may('manage'),
|
||
stats:()=>may('manage')||ME?.role==='vendedor',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));
|
||
}
|
||
function icon(path){
|
||
const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');
|
||
svg.setAttribute('width','14');svg.setAttribute('height','14');svg.setAttribute('viewBox','0 0 24 24');
|
||
svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','2.2');svg.setAttribute('aria-hidden','true');
|
||
for(const d of path){const p=document.createElementNS(ns,d.startsWith('circle')?'circle':'path');
|
||
if(d.startsWith('circle')){const [cx,cy,r]=d.split(' ').slice(1);p.setAttribute('cx',cx);p.setAttribute('cy',cy);p.setAttribute('r',r);}else p.setAttribute('d',d);svg.append(p);}
|
||
return svg;
|
||
}
|
||
const ICON_OK=['M5 12l4 4 10-10'], ICON_WARN=['M12 8v5M12 17h.01','circle 12 12 9'];
|
||
// Lucide shapes (ISC licence), in the same stroke as the two above.
|
||
const ICON_TRUCK=['M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2','M15 18H9',
|
||
'M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14','circle 17 18 2','circle 7 18 2'];
|
||
const ICON_PIN=['M20 10c0 4.99-5.54 10.19-7.4 11.8a1 1 0 0 1-1.2 0C9.54 20.19 4 14.99 4 10a8 8 0 0 1 16 0','circle 12 10 3'];
|
||
const ICON_PRINTER=['M6 9V2h12v7','M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2','M6 14h12v8H6z'];
|
||
const ICON_DOWNLOAD=['M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4','m7 10 5 5 5-5','M12 15V3'];
|
||
const ICON_CHAT=['M7.9 20A9 9 0 1 0 4 16.1L2 22Z'];
|
||
const ICON_COPY=['M9 9h12v12H9z','M5 15V5a2 2 0 0 1 2-2h10'];
|
||
|
||
// ---- Badges: one system on every screen (canvas "Kanban DTF — redesign", v2) --
|
||
// The grade pill is coloured by the price ladder's bands (90/75/60/40), 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;};
|
||
const PRODUCT_BADGE={file:'Têxtil · Folha',avulsa:'Têxtil · Avulsa',uvfile:'UV · Folha',uv:'UV · Avulsa'};
|
||
function productBadge(items){
|
||
const counts=new Map();for(const i of items)counts.set(i.mode,(counts.get(i.mode)||0)+1);
|
||
const [mode,n]=[...counts][0]||['file',0];
|
||
return node('span',PRODUCT_BADGE[mode]+(n>1?' ×'+n:'')+(counts.size>1?' +'+(counts.size-1):''),'pbadge'+(mode.startsWith('uv')?' uv':''));
|
||
}
|
||
function badge(text,tone='',title=''){const b=node('span',text,'pill '+tone);if(title)b.title=title;return b;}
|
||
function place(dest,prefix=''){
|
||
const s=node('span',undefined,'place');s.append(icon(dest?ICON_TRUCK:ICON_PIN),dest?prefix+dest.city+'/'+dest.state:'Retirada em Franca');return s;
|
||
}
|
||
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(icon(ICON_COPY));
|
||
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||''};
|
||
}
|
||
function buyerBlock(content,className){
|
||
const who=buyer(content);
|
||
const box=node('div',undefined,'buyer '+(className||''));
|
||
const title=node('b',who.title);title.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;box.append(title);
|
||
if(who.mail)box.append(node('span',who.mail,'buyer-mail'));
|
||
return box;
|
||
}
|
||
// 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();
|
||
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(icon(ICON_DOWNLOAD));b.classList.add('with-icon');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 print queue's files, saved by this browser as orders enter Fila de
|
||
// impressão, while the Kanban is open. It is switched on in Integrações, on
|
||
// the print room's computer: the folder belongs to that browser, not to the
|
||
// account. Chrome and Edge write into a folder the operator chose
|
||
// (FlexiPRINT's, or the internal server's share), 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 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';
|
||
// `when`: download as soon as the order arrives in Arte recebida ('rec', the
|
||
// default), into a "Recebidos" folder inside the chosen one; the file moves up
|
||
// when the order enters the queue; or only at the queue ('fil'). Only a chosen folder can do that: Firefox
|
||
// downloads cannot be moved or removed afterwards.
|
||
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
|
||
brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'rec',
|
||
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
|
||
const RECEIVED='Recebidos';
|
||
// Switched on: a chosen folder released, or automatic downloads.
|
||
const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
|
||
const early=()=>FOLDER.mode==='folder'&&FOLDER.when==='rec';
|
||
const savedKey=()=>FOLDER.mode==='folder'?'saved:'+FOLDER.handle.name:'saved:downloads';
|
||
// What this folder received, by upload: its order, item, name and where it is
|
||
// ('early' in Recebidos, 'queue' in the folder, 'done' once printing). 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.when=await kv.get('folder-when')==='fil'?'fil':'rec';
|
||
FOLDER.handle=await kv.get('folder')||null;
|
||
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
|
||
FOLDER.saved=await loadSaved();
|
||
if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos da fila na pasta, 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='Pasta da Fila de impressão', h=FOLDER.handle;
|
||
const act=(text,fn)=>button(text,fn,'btn small');
|
||
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
|
||
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:'Baixa sozinho, no Firefox, os arquivos que entram na fila.',
|
||
actions:[act('Ligar',()=>setDownloads(true))],details:how});
|
||
}else if(!h){
|
||
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho, numa pasta, os arquivos que entram na fila.',
|
||
actions:[act('Escolher pasta',chooseFolder)],
|
||
details:[node('p','Escolha a pasta que o FlexiPRINT lê, ou a pasta da rede do servidor. Os arquivos levam o número do pedido no nome. '+
|
||
'Funciona neste computador, com o Kanban aberto.')]});
|
||
}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{
|
||
const when=node('select',undefined,'machine-select');when.setAttribute('aria-label','Quando baixar');
|
||
for(const [value,text] of [['rec','Baixar em Arte recebida'],['fil','Baixar na Fila de impressão']]){
|
||
const o=node('option',text);o.value=value;o.selected=FOLDER.when===value;when.append(o);}
|
||
when.onchange=()=>setWhen(when.value);
|
||
row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
||
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),actions:[when],
|
||
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',FOLDER.when==='rec'
|
||
?'Em Arte recebida: o arquivo do pedido é baixado em “'+h.name+'/'+RECEIVED+'” assim que o pedido chega, e passa para “'+h.name+'” quando entra na Fila de impressão.'
|
||
:'Na Fila de impressão: o arquivo é baixado em “'+h.name+'” quando o pedido entra na Fila de impressão.'),
|
||
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai. '+
|
||
'Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')],
|
||
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(()=>{});
|
||
paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder();
|
||
}
|
||
async function releaseFolder(){
|
||
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
|
||
FOLDER.lastSig=null;FOLDER.error='';paintFolder();if(FOLDER.granted)syncFolder();
|
||
}
|
||
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();
|
||
}
|
||
async function setWhen(when){
|
||
FOLDER.when=when;FOLDER.lastSig=null;
|
||
await kv.set('folder-when',when).catch(()=>{});
|
||
paintFolder();say(when==='rec'?'Os arquivos vão ser baixados assim que o pedido chegar, em “'+RECEIVED+'”.':'Os arquivos vão ser baixados quando o pedido entrar na Fila.');
|
||
syncFolder(true);
|
||
}
|
||
|
||
// 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 received=()=>FOLDER.handle.getDirectoryHandle(RECEIVED,{create:true});
|
||
// Remove a saved file from where it is; one already gone (the FlexiPRINT
|
||
// took it) is fine.
|
||
async function removeSaved(rec){
|
||
const dir=rec.place==='early'?await received():FOLDER.handle;
|
||
await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;});
|
||
}
|
||
// From Recebidos up to the folder, when the order enters the queue. False when
|
||
// the file is no longer there, so it is downloaded again.
|
||
async function moveToQueue(rec){
|
||
const from=await received();let file;
|
||
try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;}
|
||
await FOLDER.handle.removeEntry(rec.name).catch(()=>{});
|
||
try{await file.move(FOLDER.handle);}
|
||
catch{await writeWhole(FOLDER.handle,rec.name,await file.getFile());await from.removeEntry(rec.name);}
|
||
return true;
|
||
}
|
||
|
||
// Bring the folder in line with the board: remove the files of orders that
|
||
// were cancelled, deleted, sent back for correction or given another file;
|
||
// move up what entered the queue; download what is missing. A file the
|
||
// FlexiPRINT moved away after importing is not downloaded again. 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 follows=early()?['rec','tra','cor','fil']:['fil'];
|
||
const sig=FOLDER.when+'|'+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{
|
||
const tidy=FOLDER.mode==='folder';
|
||
const held=tidy?[...new Set([...FOLDER.saved.values()].filter(r=>r.order&&r.place!=='done').map(r=>r.order))]:[];
|
||
const {files,states}=await api('/queue/folder',{early:early(),held});
|
||
const wanted=new Map(files.map(f=>[f.order+':'+f.item,f]));
|
||
const where=FOLDER.mode==='folder'?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
|
||
let removed=0;
|
||
if(tidy)for(const [uid,rec] of [...FOLDER.saved]){
|
||
if(!rec.order||rec.place==='done')continue;
|
||
const state=states[rec.order];
|
||
if(state==='imp'||state==='fin'){rec.place='done';continue;}
|
||
const now=wanted.get(rec.order+':'+rec.item);
|
||
const expected=state==='fil'||early()&&(state==='rec'||state==='tra');
|
||
if(state&&state!=='cancelled'&&state!=='cor'&&!(expected&&(!now||now.upload_id!==uid)))continue;
|
||
await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();
|
||
}
|
||
const pending=files.filter(f=>{const r=FOLDER.saved.get(f.upload_id);return !r||r.place==='early'&&f.state==='fil';});
|
||
for(const [i,file] of pending.entries()){
|
||
const rec=FOLDER.saved.get(file.upload_id);
|
||
const up=!!rec&&await moveToQueue(rec);
|
||
if(!up){
|
||
FOLDER.status=(FOLDER.mode==='folder'?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
|
||
say(FOLDER.status,false,60000);
|
||
if(FOLDER.mode==='downloads'){
|
||
// 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));
|
||
}else{
|
||
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(file.state==='fil'?FOLDER.handle:await received(),file.name,r.body);
|
||
}
|
||
}
|
||
FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name,
|
||
place:file.state==='fil'||FOLDER.mode!=='folder'?'queue':'early'});
|
||
FOLDER.last=new Date();await keepSaved();
|
||
}
|
||
FOLDER.lastSig=sig;FOLDER.error='';
|
||
FOLDER.status='';
|
||
if(pending.length)say((FOLDER.mode==='folder'?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where+'.');
|
||
if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos ou trocados saíram da pasta.');
|
||
}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('Pasta automática: '+(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();
|
||
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;
|
||
if(!quiet)say('Atualizado às '+new Date().toLocaleTimeString('pt-BR')+tinyNotice,false,tinyNotice?6000:2500);
|
||
render();
|
||
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);
|
||
}
|
||
}
|
||
function showTab(name){
|
||
tab=name;
|
||
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
|
||
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?((ME.name||ME.email).trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()):'·';
|
||
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
|
||
$('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==='fil'||order.state==='imp')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','fil','imp'].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 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;
|
||
async function proofOk(order){
|
||
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
|
||
}
|
||
// 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={
|
||
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 list, label on the tag].
|
||
function filterKinds(){
|
||
const kinds=[
|
||
{key:'product',label:'Produto',all:'Todos',options:[['textil','Têxtil'],['uv','UV']]},
|
||
{key:'delivery',label:'Envio',all:'Entrega e retirada',options:[['entrega','Entrega'],['retirada','Retirada']]},
|
||
{key:'status',label:'Situação',all:'Todos',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.splice(1,0,{key:'machine',label:'Máquina',all:'Todas',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;
|
||
}
|
||
function openFilters(){
|
||
const pop=$('filter-pop'),head=node('div',undefined,'filterpop-head');
|
||
const close=node('button',undefined,'close');close.type='button';close.setAttribute('aria-label','Fechar filtros');
|
||
close.append(icon(['M6 6l12 12M18 6L6 18']));close.onclick=closeFilters;
|
||
head.append(node('b','Filtros'),close);
|
||
const grid=node('div',undefined,'filtergrid');
|
||
for(const kind of filterKinds()){
|
||
const field=node('label',undefined,'field'),select=node('select');select.dataset.kind=kind.key;
|
||
for(const [value,text] of [['',kind.all],...kind.options]){const o=node('option',text);o.value=value;o.dataset.text=text;select.append(o);}
|
||
select.value=boardFilter[kind.key];
|
||
select.onchange=()=>{boardFilter[kind.key]=select.value;renderBoard();filterCounts();};
|
||
field.append(node('span',kind.label),select);grid.append(field);
|
||
}
|
||
const clear=node('button','Limpar filtros','linkbtn');clear.type='button';clear.onclick=clearFilters;
|
||
const foot=node('div',undefined,'filterpop-foot');foot.append(clear);
|
||
pop.replaceChildren(head,grid,foot);pop.hidden=false;$('filter-btn').setAttribute('aria-expanded','true');
|
||
filterCounts();grid.querySelector('select').focus();
|
||
}
|
||
function closeFilters(){$('filter-pop').hidden=true;$('filter-btn').setAttribute('aria-expanded','false');}
|
||
function clearFilters(){for(const key in boardFilter)boardFilter[key]='';renderBoard();}
|
||
// Each choice in the lists says how many orders it would show with the others kept.
|
||
function filterCounts(){
|
||
for(const select of $('filter-pop').querySelectorAll('select'))for(const o of select.options)
|
||
o.textContent=o.dataset.text+' ('+filterCount({...boardFilter,[select.dataset.kind]:o.value})+')';
|
||
}
|
||
// The filters in use, beside the button: each one taken off with a click.
|
||
function renderFilters(){
|
||
const kinds=filterKinds();
|
||
// A choice that is gone (a machine deleted or switched off) is dropped.
|
||
for(const key in boardFilter){const kind=kinds.find(k=>k.key===key);
|
||
if(boardFilter[key]&&!kind?.options.some(([value])=>value===boardFilter[key]))boardFilter[key]='';}
|
||
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,'filtertag');b.type='button';b.title='Tirar este filtro';
|
||
b.setAttribute('aria-label','Tirar o filtro '+(tag||text));b.append(icon(['M6 6l12 12M18 6L6 18']));
|
||
b.onclick=()=>{boardFilter[kind.key]='';renderBoard();};return b;});
|
||
if(used.length>1){const all=node('button','Limpar','linkbtn');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);
|
||
// Open, the lists follow: the choices, and the counts unless one is in use.
|
||
const pop=$('filter-pop');
|
||
if(!pop.hidden){
|
||
for(const select of pop.querySelectorAll('select'))select.value=boardFilter[select.dataset.kind];
|
||
if(!(pop.contains(document.activeElement)&&document.activeElement.tagName==='SELECT'))filterCounts();
|
||
}
|
||
}
|
||
function renderBoard(){
|
||
renderFilters();
|
||
const active=board.orders.filter(o=>['rec','tra','fil','imp'].includes(o.state));
|
||
const queued=active.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
|
||
$('board-summary').textContent=metres(queued)+' em produção';
|
||
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
|
||
const column=node('section',undefined,'col');column.dataset.state=state;column.style.setProperty('--c',STAGE_COLORS[state]);
|
||
// 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 total=orders.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
|
||
const head=node('div',undefined,'col-head');const line=node('div');
|
||
const swatch=node('span',undefined,'swatch');swatch.style.setProperty('--c',STAGE_COLORS[state]);
|
||
// Finished orders are a recent window, not the whole history: say so.
|
||
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
|
||
line.append(swatch,node('h2',title),node('span',count,'n'));
|
||
// The print queue's tools need the room: there it says only the metres.
|
||
const tools=state==='fil'&&may('print');
|
||
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+(tools?'':' no total'):'vazio'));
|
||
// The print queue's files, all at once, to import into FlexiPRINT.
|
||
if(tools){
|
||
const tools=node('div',undefined,'coltools');
|
||
if(orders.length){const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';tools.append(all);}
|
||
sub.append(tools);
|
||
}
|
||
head.append(line,sub);
|
||
column.append(head);
|
||
for(const order of orders)column.append(card(order));
|
||
if(state==='fin'&&finishedMore&&!Object.values(boardFilter).some(Boolean))moreButton(column,true,loadOlderFinished);
|
||
// 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'&&mayMove(state,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;
|
||
}));
|
||
}
|
||
// An operator's test order: no payment, no Tiny.
|
||
const isTest=order=>order.payment?.provider==='teste';
|
||
function card(order){
|
||
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at&&mayMove(order.state,order.state);
|
||
if(order.id===openOrder)c.classList.add('open');
|
||
const s=order.snapshot;
|
||
const top=node('div',undefined,'row');
|
||
top.append(node('span','#'+order.number,'num'),...(isTest(order)?[node('span','TESTE','tag-teste')]:[]),node('span',ago(order.updated_at),'age'));
|
||
const meta=node('div',undefined,'meta');
|
||
meta.append(gradePill(lowestGrade(s.items)),productBadge(s.items),
|
||
node('b',metres(s.items.reduce((t,i)=>t+Number(i.billed_metres),0)),'mtr'));
|
||
// What needs attention, as badges; a finished order needs none.
|
||
const flags=node('div',undefined,'flags');
|
||
if(order.cancelled_at)flags.append(badge('Cancelado','bad','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason));
|
||
else if(order.state!=='fin'){
|
||
const p=printState(order);
|
||
flags.append(badge((p.tone==='ok'?'✓ ':p.tone==='warn'?'! ':'')+p.text,p.tone));
|
||
if(s.items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva','warn','O cliente aceitou a ressalva de resolução'));
|
||
if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
|
||
if(waitingContact(order))flags.append(badge('☎ Aguardando contato','warn',order.contact_note+' · '+contactWho(order)));
|
||
if(needsProof(order))flags.append(order.proof_ok_at
|
||
? badge('✓ Prova OK','ok','Conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at))
|
||
: badge('Prova','warn',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: 20 cm de prova antes do resto'));
|
||
}
|
||
c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination));
|
||
if(order.machine&&order.state!=='fin'){const m=node('div',undefined,'place machine');m.append(icon(ICON_PRINTER),order.machine.name);c.append(m);}
|
||
if(flags.children.length)c.append(flags);
|
||
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));
|
||
say((forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou ')+', ou ':'')+'arraste para cima ou para baixo para mudar a prioridade',false,60000);
|
||
};
|
||
c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');};
|
||
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)&¤t[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();
|
||
}
|
||
|
||
// ---- Order panel ---------------------------------------------------------
|
||
|
||
function openPanel(id){openOrder=id;const order=board.orders.find(o=>o.id===id);$('drawer').hidden=false;renderPanel(order);renderBoard();}
|
||
function closePanel(){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;
|
||
const color=STAGE_COLORS[order.state];
|
||
const head=node('div',undefined,'panel-head');
|
||
const row=node('div',undefined,'row');
|
||
const stage=node('span',board.states[order.state],'stage');stage.style.setProperty('--c',color);
|
||
const close=node('button',undefined,'close');close.type='button';close.setAttribute('aria-label','Fechar');close.append(icon(['M6 6l12 12M18 6L6 18']));close.onclick=closePanel;
|
||
const test=isTest(order)?node('span','TESTE','tag-teste'):null;
|
||
if(test)test.title='Pedido de teste: sem pagamento, não vai ao Tiny';
|
||
const code=node('span',undefined,'ocode');code.append('Pedido '+orderCode(order.id),copyButton(orderCode(order.id),'Copiar código do pedido'));
|
||
code.title='O código que o cliente vê';
|
||
row.append(node('span','#'+order.number,'num'),stage,...(test?[test]:[]),code,close);
|
||
// What was paid and when, and whether it is stuck: the first things asked of an order.
|
||
const paid=node('div',undefined,'paidline');
|
||
paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at):' pago em '+when(order.created_at));
|
||
if(order.cancelled_at)paid.append(badge('Cancelado','bad'));
|
||
else if(stalled(order))paid.append(badge('⏱ Parado há '+hoursSince(order.updated_at)+' h','bad'));
|
||
const steps=node('ol',undefined,'steps');steps.setAttribute('aria-label','Etapas');
|
||
const at=FLOW.indexOf(order.state);
|
||
for(const [i,s] of FLOW.entries()){const li=node('li',board.states[s]);li.style.setProperty('--c',STAGE_COLORS[s]);
|
||
if(at>=0&&i<at)li.classList.add('done');if(i===at)li.classList.add('now');steps.append(li);}
|
||
head.append(row,paid,steps,moves(order));
|
||
|
||
const body=node('div',undefined,'panel-body');
|
||
const s=order.snapshot, dest=s.destination;
|
||
const facts=node('section',undefined,'facts');
|
||
const who=node('div',undefined,'fcard');
|
||
const doc=node('span',undefined,'line');doc.append(docKind(s.customer.cnpj)+' '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar '+docKind(s.customer.cnpj)));
|
||
who.append(node('p','Cliente','eyebrow'),buyerBlock(s),doc);
|
||
const zap=whatsappLink(s.customer.zap);
|
||
if(zap){const a=node('a','Abrir conversa','zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(icon(ICON_CHAT));who.append(a);}
|
||
const where=node('div',undefined,'fcard');
|
||
const placeLine=node('b');placeLine.append(icon(dest?ICON_TRUCK:ICON_PIN),dest?dest.recipient:'Retirada em Franca');
|
||
where.append(node('p','Entrega','eyebrow'),placeLine,
|
||
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'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'));
|
||
facts.append(who,where);
|
||
if(order.machine||board.machines?.length)facts.append(machineCard(order));
|
||
const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow'));
|
||
const itemsList=node('div');itemsList.style.display='flex';itemsList.style.flexDirection='column';itemsList.style.gap='10px';
|
||
s.items.forEach((item,index)=>itemsList.append(itemCard(order,item,index)));
|
||
items.append(itemsList);
|
||
const finals=node('section',undefined,'finals');finals.append(node('p','Arquivos finais','eyebrow'),node('p','Carregando…','faint'));
|
||
const history=node('section');history.append(node('p','Histórico','eyebrow'),node('p','Carregando…','faint'));
|
||
body.append(facts,items,finals,history);
|
||
panel.replaceChildren(head,body);
|
||
|
||
api('/orders/'+order.id+'/files').then(rows=>{if(token===openToken)finalsSection(order,rows,finals);}).catch(e=>say(e.message,true));
|
||
api('/orders/'+order.id+'/history').then(rows=>{if(token===openToken)historySection(order,rows,history);}).catch(e=>say(e.message,true));
|
||
}
|
||
function moves(order){
|
||
const box=node('div',undefined,'panel-actions');
|
||
if(!may('produce')){
|
||
// Sellers read the order; a correction's notice is theirs to send too.
|
||
if(order.state==='cor'&&!order.cancelled_at)box.append(correctionNotice(order));
|
||
if(waitingContact(order))box.append(contactNotice(order,false));
|
||
box.append(node('p',order.cancelled_at?'Pedido cancelado.':'Somente consulta: seu perfil não move pedidos.','muted'));
|
||
return box;
|
||
}
|
||
if(order.cancelled_at){
|
||
const note=node('div',undefined,'callout bad');
|
||
note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason));
|
||
const remove=button('Excluir pedido',async()=>{
|
||
if(!window.confirm('Excluir o pedido #'+order.number+' de vez? Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.'))return;
|
||
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load();
|
||
},'btn danger');remove.style.alignSelf='flex-start';
|
||
box.append(note,...(may('manage')?[remove]:[]));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.
|
||
const waiting=order.state==='cor'?correctionNotice(order):null;
|
||
const row=node('div',undefined,'moves');
|
||
// One form open at a time under the buttons.
|
||
const forms=[];
|
||
let sync=()=>{};
|
||
const toggle=form=>{const show=form.hidden;for(const f of forms)f.hidden=true;form.hidden=!show;sync();
|
||
if(show)form.querySelector('textarea,input:not([type=checkbox]):not([hidden])')?.focus();};
|
||
const reason=node('form',undefined,'reason');reason.hidden=true;forms.push(reason);
|
||
let step=null;
|
||
for(const next of board.transitions[order.state]){
|
||
if(next==='cor'){
|
||
if(!mayMove(order.state,next))continue;
|
||
const b=node('button','Pedir correção','btn danger');b.type='button';b.dataset.move='cor';
|
||
b.onclick=()=>toggle(reason);row.append(b);
|
||
}else if(next==='fil'&&!finalDone(order)){
|
||
// The queue needs an approved final: approving it is the next step,
|
||
// shown first, with the file that would be printed.
|
||
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
||
const upload=finalForm(order,all?ready.map(()=>null):ready);forms.unshift(upload);
|
||
const text=node('div');text.append(node('b','Próximo passo: aprovar o arquivo final'));
|
||
if(all){
|
||
text.append(node('span','Baixe e confira. É este arquivo que vai para a impressão.'));
|
||
const files=node('div',undefined,'readyfiles');
|
||
ready.forEach((r,i)=>{const line=node('div',undefined,'readyfile');
|
||
line.append(node('span',(many?'Item '+(i+1)+' · ':'')+FINAL_TITLE[r.source],'faint'),node('b',r.name),
|
||
downloadButton('Baixar',download(r.upload_id),'btn ghost small'));files.append(line);});
|
||
text.append(files);
|
||
}else text.append(node('span',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 actions=node('div',undefined,'stepactions');
|
||
const b=button(all?'Aprovar arquivo final':'Enviar arquivo final',all?()=>approveReady(order,ready):async()=>toggle(upload),'btn primary');
|
||
b.dataset.approve='';actions.append(b);
|
||
if(all){const other=node('button','Enviar outro arquivo','btn ghost');other.type='button';other.onclick=()=>toggle(upload);actions.append(other);}
|
||
// The upload form opens inside the step, in place of its buttons.
|
||
const cancel=node('button','Cancelar','linkbtn');cancel.type='button';cancel.onclick=()=>toggle(upload);
|
||
upload.append(cancel);sync=()=>{actions.hidden=!upload.hidden;};
|
||
text.append(actions,upload);
|
||
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
|
||
}else if(next==='fin'&&proofPending(order)){
|
||
// Finalizado waits for the proof: printing it and checking it is the next step.
|
||
const text=node('div');text.append(node('b','Próximo passo: conferir a prova'),
|
||
node('span',order.snapshot.proof
|
||
?'O cliente pediu uma prova: mande a foto pelo WhatsApp e, com o aceite dele, marque Prova OK.'
|
||
:'Pedido acima de 10 m: imprima 20 cm, confira e marque Prova OK antes de rodar o resto.'));
|
||
if(may('print')){const actions=node('div',undefined,'stepactions');
|
||
const b=button('Prova OK',()=>proofOk(order),'btn primary');b.dataset.proof='';actions.append(b);text.append(actions);}
|
||
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
|
||
}else if(mayMove(order.state,next)){
|
||
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
|
||
}
|
||
}
|
||
if(!row.children.length)row.append(node('span',order.state==='fin'?'Pedido concluído.':'Daqui em diante, com a produção.','muted'));
|
||
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
||
const previous=mayMove(order.state,board.back?.[order.state])?board.back?.[order.state]:null;
|
||
const sub=node('div',undefined,'subactions');
|
||
const backForm=node('form',undefined,'reason');backForm.hidden=true;forms.push(backForm);
|
||
if(previous){
|
||
const b=node('button','← Voltar para '+board.states[previous],'linkbtn');b.type='button';b.dataset.back=previous;
|
||
b.onclick=()=>toggle(backForm);sub.append(b);
|
||
const why=node('input');why.placeholder='Motivo';why.setAttribute('aria-label','Motivo do retorno');why.required=true;why.maxLength=1000;
|
||
const go=node('button','Voltar para '+board.states[previous],'btn');
|
||
backForm.append(why,go);
|
||
backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}};
|
||
}
|
||
// The proof may be checked before Imprimindo, while the order waits in the queue.
|
||
if(order.state==='fil'&&proofPending(order)&&may('print')){
|
||
const b=button('✓ Prova OK',()=>proofOk(order),'linkbtn');b.title='A prova foi impressa e conferida';sub.append(b);
|
||
}
|
||
// Waiting for a word with the customer: shown on top with "Contato feito";
|
||
// otherwise marked from here, with what has to be agreed.
|
||
const contactForm=node('form',undefined,'reason');contactForm.hidden=true;forms.push(contactForm);
|
||
if(order.state!=='fin'&&!waitingContact(order)){
|
||
const b=node('button','☎ Aguardando contato','linkbtn');b.type='button';b.dataset.contact='';
|
||
b.title='Marcar que é preciso falar com o cliente antes de imprimir';b.onclick=()=>toggle(contactForm);sub.append(b);
|
||
const what=node('input');what.placeholder='O que precisa ser combinado com o cliente';what.setAttribute('aria-label','O que precisa ser combinado');
|
||
what.required=true;what.minLength=3;what.maxLength=500;
|
||
const go=node('button','Marcar aguardando contato','btn');
|
||
contactForm.append(what,go);
|
||
contactForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;
|
||
try{await api('/orders/'+order.id+'/contact',{waiting:true,note:what.value.trim()});say('Pedido #'+order.number+' aguardando contato.');await load();}
|
||
catch(error){say(error.message,true);go.disabled=false;}};
|
||
}
|
||
// Rare and destructive: behind a menu. A test order is deleted; a paid one
|
||
// is cancelled, with a reason, and kept.
|
||
const cancelForm=node('form',undefined,'reason');cancelForm.hidden=true;forms.push(cancelForm);
|
||
const menu=node('div',undefined,'menu');menu.hidden=true;menu.setAttribute('role','menu');
|
||
if(isTest(order)){
|
||
menu.append(button('Excluir pedido de teste',async()=>{
|
||
menu.hidden=true;
|
||
if(!window.confirm('Excluir o pedido de teste #'+order.number+'? Ele some do Kanban, com o histórico.'))return;
|
||
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();
|
||
},'menuitem bad'));
|
||
}else{
|
||
const b=node('button','Cancelar pedido','menuitem bad');b.type='button';
|
||
b.onclick=()=>{menu.hidden=true;toggle(cancelForm);};menu.append(b);
|
||
const why=node('input');why.placeholder='Motivo do cancelamento';why.setAttribute('aria-label','Motivo do cancelamento');why.required=true;why.minLength=3;why.maxLength=1000;
|
||
const go=node('button','Cancelar pedido #'+order.number,'btn danger');
|
||
cancelForm.append(node('span','O pedido sai do quadro e fica em "Cancelados", com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago, e o pedido no Tiny se cancela lá.','muted'),why,go);
|
||
cancelForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;
|
||
try{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}
|
||
catch(error){say(error.message,true);go.disabled=false;}};
|
||
}
|
||
const more=node('button','⋯','btn ghost more');more.type='button';more.title='Mais ações';more.setAttribute('aria-label','Mais ações');
|
||
more.setAttribute('aria-haspopup','menu');
|
||
more.onclick=e=>{e.stopPropagation();menu.hidden=!menu.hidden;
|
||
if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;},{once:true});};
|
||
const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);if(may('manage'))row.append(wrap);
|
||
const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true;
|
||
const sendFix=node('button','Enviar para correção','btn danger');
|
||
reason.append(text,sendFix);
|
||
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
|
||
const contactNow=waitingContact(order)?contactNotice(order,true):null;
|
||
box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
||
}
|
||
function contactNotice(order,canClear){
|
||
const box=node('div',undefined,'callout contact');
|
||
box.append(node('b','☎ Aguardando contato com o cliente'),node('span',order.contact_note),node('span',contactWho(order),'faint'));
|
||
const actions=node('div',undefined,'buttons');
|
||
const zap=whatsappLink(order.snapshot.customer.zap);
|
||
if(zap){const a=node('a','Abrir conversa','zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));actions.append(a);}
|
||
if(canClear)actions.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 small'));
|
||
if(actions.children.length)box.append(actions);
|
||
return box;
|
||
}
|
||
function correctionNotice(order){
|
||
const s=order.snapshot, reason=order.correction_reason||'';
|
||
const link=board.site_origin+'/conta/pedidos?order='+order.id;
|
||
const message='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;
|
||
const text=node('div');
|
||
text.append(node('b','Aguardando a correção do cliente'),node('span',reason?'Motivo: '+reason:'O motivo está no histórico.'));
|
||
const actions=node('div',undefined,'stepactions');
|
||
const zap=whatsappLink(s.customer.zap);
|
||
if(zap){
|
||
const a=node('a','Avisar no WhatsApp','zapbtn big');a.href=zap+'?text='+encodeURIComponent(message);
|
||
a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));actions.append(a);
|
||
}
|
||
const copy=button('Copiar mensagem',async()=>{await navigator.clipboard.writeText(message);say('Mensagem copiada.');},'btn ghost');
|
||
actions.append(copy);
|
||
text.append(actions);
|
||
if(!zap)text.append(node('span','Sem WhatsApp no pedido: envie a mensagem para '+s.customer.mail+'.'));
|
||
const box=node('div',undefined,'nextstep lead');box.append(node('span','!','nextmark'),text);return box;
|
||
}
|
||
// ---- 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',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(!window.confirm('Conferiu o arquivo? Ele vai ser o arquivo de impressão.\n\n'+
|
||
ready.map((r,i)=>(many?'Item '+(i+1)+': ':'')+r.label).join('\n')))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,'fil')?'Arquivo final aprovado. Agora é só mover para a fila.':'Arquivo final aprovado. A produção coloca na fila.');
|
||
}
|
||
// The form for a file the operator prepared, or to pick per item; ready
|
||
// files come ticked.
|
||
function finalForm(order,ready){
|
||
const form=node('form',undefined,'finalform');form.hidden=true;
|
||
const inputs=order.snapshot.items.map((item,index)=>{
|
||
const slot=node('label',undefined,'slot');slot.append('Item '+(index+1)+' · '+PRODUCT[item.mode]);
|
||
const input=node('input');input.type='file';input.multiple=true;input.required=true;input.dataset.finalItem=index;
|
||
const file=ready[index];
|
||
if(file){
|
||
const use=node('input');use.type='checkbox';use.checked=true;use.dataset.useGenerated=index;input.required=false;input.hidden=true;
|
||
use.onchange=()=>{input.hidden=use.checked;input.required=!use.checked;};
|
||
const choice=node('label',undefined,'check');choice.append(use,'Usar: '+file.label);
|
||
slot.append(choice);input.generated=()=>use.checked?file.upload_id:null;
|
||
}
|
||
slot.append(input);form.append(slot);return input;
|
||
});
|
||
const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;
|
||
const check=node('input');check.type='checkbox';check.required=true;check.dataset.confirm='';
|
||
const checked=node('label',undefined,'check');checked.append(check,'Arquivos conferidos');
|
||
const submit=node('button','Aprovar arquivo final','btn primary');
|
||
form.append(note,checked,submit);
|
||
form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;try{
|
||
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.');
|
||
}catch(error){say(error.message,true);submit.disabled=false;}};
|
||
return form;
|
||
}
|
||
const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'PDF gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'};
|
||
function itemCard(order,item,index){
|
||
const row=(order.print_files||[]).find(r=>r.item_index===index);
|
||
const box=node('div',undefined,'item');
|
||
if(row&&(row.status==='manual'||row.status==='failed')&&!(order.corrections||[]).some(f=>f.item_index===index))box.classList.add('attention');
|
||
const preview=itemPreview(item);
|
||
const body=node('div',undefined,'body');
|
||
const spec=item.production;
|
||
const title=node('div',undefined,'title');title.append(node('b',PRODUCT[item.mode]),gradePill(item.grade),node('span',metres(item.billed_metres),'mono'));
|
||
body.append(title,facts([['Folha',sheetSize(spec)],['Peças',spec?String(spec.placements.length):null],
|
||
['Metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null],['Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null]]));
|
||
if(item.quality_status==='warning')body.append(badge('! Ressalva de resolução aceita','warn'));
|
||
// 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){
|
||
const file=node('div',undefined,'file');
|
||
file.append(icon(ICON_OK),node('span','Correção do cliente recebida · '+fix.name,'ok'));body.append(file);
|
||
}
|
||
// The print file: a line when it is fine, a callout when someone must act.
|
||
else if(!row)body.append(node('div','Arquivo de impressão ainda não gerado','line'));
|
||
else if(row.status==='manual'||row.status==='failed'){
|
||
const call=node('div',undefined,'callout');
|
||
call.append(node('b',row.status==='failed'?'! Falhou ao gerar':'! Preparar à mão'),
|
||
node('span',row.detail?.reason||'Monte a folha a partir do original.'));
|
||
body.append(call);
|
||
}else{
|
||
const original=row.status==='ready'&&row.detail?.source==='original';
|
||
const tone=row.status==='ready'?'ok':'muted';
|
||
const file=node('div',undefined,'file');
|
||
file.append(tone==='ok'?icon(ICON_OK):'',node('span',(original?'O original é o arquivo de impressão':PRINT_TEXT[row.status])+
|
||
(row.status==='ready'&&row.name&&!original?' · '+row.name:''),tone));
|
||
body.append(file);
|
||
if(row.status==='ready'&&row.detail&&!original){
|
||
const extra=[row.detail.min_dpi?'menor resolução '+row.detail.min_dpi+' DPI':'',row.detail.vector_sources?'PDF vetorial':''].filter(Boolean).join(' · ');
|
||
if(extra)body.append(node('div',extra,'line'));
|
||
}
|
||
}
|
||
if(['rec','tra','cor'].includes(order.state)){
|
||
const done=(order.final_items||[]).includes(index), status=node('div',undefined,'file');
|
||
status.append(icon(done?ICON_OK:ICON_WARN),node('span',done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn'));
|
||
body.append(status);
|
||
}
|
||
const buttons=node('div',undefined,'buttons');
|
||
if(fix&&!fix.expired)buttons.append(downloadButton('Correção',download(fix.upload_id)));
|
||
else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
|
||
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
|
||
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
|
||
if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
|
||
buttons.append(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn ghost'));
|
||
body.append(buttons);
|
||
box.append(preview,body);return box;
|
||
}
|
||
function finalsSection(order,revisions,section){
|
||
section.replaceChildren(node('p','Arquivos finais','eyebrow'));
|
||
for(const file of revisions){
|
||
const rev=node('div',undefined,'rev');
|
||
rev.append(node('b',(file.kind==='final'?'Final':'Correção do cliente')+' · item '+(file.item_index+1)+' · '+file.name),
|
||
node('span',(file.expired?'expirado':file.active?'atual':'substituído')+' · '+when(file.created_at)+' · '+file.note,'faint'));
|
||
if(!file.expired){const b=downloadButton('Baixar',download(file.upload_id),'btn ghost');b.style.alignSelf='flex-start';rev.append(b);}
|
||
section.append(rev);
|
||
}
|
||
if(!revisions.length)section.append(node('p','Nenhum arquivo final ainda.','faint'));
|
||
// Approving is the button at the top; this is for replacing an approved
|
||
// final, or sending one before the art is marked as handled.
|
||
// Before approval in Arte conferida, the step at the top is the way in.
|
||
if(!may('produce')||!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
|
||
const form=finalForm(order,readyFinals(order).map(()=>null));
|
||
const open=node('button',finalDone(order)?'Enviar nova versão':'Enviar arquivo final','btn ghost');open.type='button';
|
||
open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();};
|
||
section.append(open,form);
|
||
}
|
||
function historySection(order,rows,section){
|
||
const list=node('ol',undefined,'timeline');
|
||
const entry=(color,title,who,at,reason)=>{
|
||
const li=node('li');li.style.setProperty('--c',color);
|
||
const text=node('div');text.append(node('b',title),node('span',' · '+who,'faint'));
|
||
if(reason)text.append(node('span',' · '+reason,'muted'));
|
||
li.append(text,node('small',when(at)));return li;
|
||
};
|
||
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+board.states[r.to_state]:board.states[r.to_state],r.operator,r.created_at,r.reason));
|
||
list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':'Site',order.created_at,''));
|
||
section.replaceChildren(node('p','Histórico','eyebrow'),list);
|
||
}
|
||
|
||
// ---- Machines and users ----------------------------------------------------
|
||
|
||
// The order's machine: chosen, or the first that prints its product.
|
||
function machineCard(order){
|
||
const box=node('div',undefined,'fcard');box.append(node('p','Máquina','eyebrow'));
|
||
const current=order.machine;
|
||
if(!may('print')||!board.machines?.length){
|
||
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'));return box;
|
||
}
|
||
const select=node('select',undefined,'machine-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(select,node('span',current?.chosen?'Escolhida para este pedido.':current?'Escolhida automaticamente quando o pedido chegou.':'Nenhuma máquina imprime este produto.','faint'));
|
||
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';
|
||
}
|
||
// Checkboxes drawn as chips; .values() is what is ticked.
|
||
function pills(options,selected){
|
||
const box=node('div',undefined,'pills');
|
||
const inputs=options.map(([value,label])=>{const c=node('input');c.type='checkbox';c.value=value;c.checked=selected.includes(value);
|
||
const pill=node('label',undefined,'pill');pill.append(c,node('span',label));box.append(pill);return c;});
|
||
box.values=()=>inputs.filter(c=>c.checked).map(c=>c.value);
|
||
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,'mfield');g.append(node('span',label),...content);return g;}
|
||
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
|
||
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||'—';
|
||
const rows=users.map(u=>{
|
||
const tr=node('tr');if(!u.active)tr.classList.add('off');
|
||
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email,'faint block'));
|
||
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—'));
|
||
const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint');
|
||
const actions=node('td',undefined,'actions');
|
||
const editable=u.role!=='superadmin'||ME.role==='superadmin';
|
||
if(editable)actions.append(button('Editar',()=>userForm(u),'btn ghost small'));
|
||
if(editable&&u.email!==ME.email)actions.append(button('Excluir',async()=>{
|
||
if(!window.confirm('Excluir o usuário '+(u.name||u.email)+'? Ele perde o acesso na hora. O histórico dos pedidos continua com o e-mail dele.'))return;
|
||
await api('/users/'+u.id+'/delete',{});say('Usuário excluído.');await loadUsers();},'btn ghost small danger-text'));
|
||
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':' · desativado')),machinesTd,seen,actions);return tr;
|
||
});
|
||
$('users-list').replaceChildren(...rows);
|
||
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
|
||
:[node('p','Nenhuma máquina cadastrada.','faint')]));
|
||
}
|
||
const OPEN_STAGES=['rec','tra','fil','imp','cor'];
|
||
function machineTile(m){
|
||
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
|
||
const head=node('div',undefined,'mtile-head');
|
||
const state=node('span',m.active?'Ativa':'Desativada','integ-state');state.style.setProperty('--c',m.active?'var(--ok)':'var(--faint)');
|
||
head.append(node('b',m.name),state);
|
||
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
|
||
const full=!over&&!!m.limit_metres&&m.open_metres>=m.limit_metres;
|
||
const bar=node('div',undefined,'mbar'+(over?' over':full?' full':''));const fill=node('span');
|
||
fill.style.width=(m.limit_metres?Math.min(100,m.open_metres/m.limit_metres*100):0)+'%';bar.append(fill);
|
||
const used=node('div',undefined,'mload'+(over?' over':''));
|
||
used.append(node('span',machineLoad(m)),node('span',over?'acima do limite':full?'no limite':m.limit_metres?'':'sem limite'));
|
||
const stages=OPEN_STAGES.filter(s=>m.states[s]).map(s=>(board?.states?.[s]||s)+' '+m.states[s]).join(' · ');
|
||
const actions=node('div',undefined,'mtile-actions');
|
||
actions.append(button('Editar',()=>machineForm(m),'btn ghost small'),button('Excluir',async()=>{
|
||
if(!window.confirm('Excluir a máquina '+m.name+'? Os pedidos dela vão para outra máquina do produto.'))return;
|
||
await api('/machines/'+m.id+'/delete',{});say('Máquina excluída.');await loadUsers();await load();},'btn ghost small danger-text'));
|
||
tile.append(head,node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','meta'),
|
||
...(m.active||m.open_orders?[bar,used]:[]),
|
||
node('span',stages||'Nenhum pedido em aberto','meta'),
|
||
node('span',m.operators.length?'Operadores: '+m.operators.map(o=>o.name).join(', '):'Nenhum operador ligado','meta'),actions);
|
||
return tile;
|
||
}
|
||
// One dialog for creating and editing, for users and machines alike.
|
||
function dialog(title,fields,onsave){
|
||
const back=node('div',undefined,'modal');const form=node('form',undefined,'modal-box');
|
||
form.append(node('h2',title),...fields);
|
||
const row=node('div',undefined,'modal-actions');
|
||
const cancel=node('button','Cancelar','btn ghost');cancel.type='button';cancel.onclick=()=>back.remove();
|
||
const save=node('button','Salvar','btn primary');row.append(cancel,save);form.append(row);
|
||
form.onsubmit=async e=>{e.preventDefault();save.disabled=true;try{await onsave();back.remove();}catch(err){say(err.message,true);save.disabled=false;}};
|
||
back.onclick=e=>{if(e.target===back)back.remove();};
|
||
back.append(form);document.body.append(back);form.querySelector('input,select')?.focus();
|
||
}
|
||
function field(label,input){const l=node('label',undefined,'mfield');l.append(label,input);return l;}
|
||
function userForm(u){
|
||
const editing=!!u;
|
||
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';
|
||
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';
|
||
const role=node('select');
|
||
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','vendedor'];
|
||
for(const r of roles){const o=node('option',ROLE_NAMES[r]);o.value=r;role.append(o);}
|
||
role.value=u?.role||'operador';role.disabled=u?.role==='superadmin'||u?.email===ME.email;
|
||
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':'8 caracteres ou mais';
|
||
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
|
||
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
|
||
const picks=pills(usersData.machines.map(m=>[m.id,m.name]),u?.machines||[]);
|
||
const machinesField=group('Máquinas',picks);
|
||
const syncMachines=()=>{machinesField.hidden=role.value!=='operador'||!usersData.machines.length;};role.onchange=syncMachines;syncMachines();
|
||
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
|
||
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
|
||
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
|
||
machines:role.value==='operador'?picks.values():[],
|
||
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||'';
|
||
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 unit=node('div',undefined,'unit');unit.append(limit,node('span','metros em aberto','faint'));
|
||
const operators=usersData.users.filter(u=>u.role==='operador');
|
||
const crew=pills(operators.map(u=>[u.id,u.name||u.email]),(m?.operators||[]).map(o=>o.id));
|
||
const active=node('input');active.type='checkbox';active.checked=m?m.active:true;
|
||
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativa (recebe pedidos)');
|
||
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),group('Imprime',products),field('Limite',unit),
|
||
group('Operadores',operators.length?crew:node('span','Nenhum operador cadastrado.','faint')),activeLabel],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,operators:crew.values()});
|
||
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
|
||
});
|
||
}
|
||
function passwordForm(){
|
||
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';
|
||
dialog('Minha senha',[field('Senha atual',current),field('Nova senha (8 caracteres ou mais)',next),field('Repita a nova senha',again)],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;passwordForm();};
|
||
$('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 the person picks.
|
||
let statsDays=30, statsRange=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)return (hours<10?hours.toFixed(1):Math.round(hours).toString()).replace('.',',')+' 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'});
|
||
function statsPeriod(){
|
||
const box=$('stats-period');
|
||
const chips=[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
|
||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(!statsRange&&days===statsDays));
|
||
b.onclick=()=>{statsDays=days;statsRange=null;loadStats().catch(e=>say(e.message,true));};return b;});
|
||
const from=node('input');from.type='date';from.setAttribute('aria-label','De');
|
||
const to=node('input');to.type='date';to.setAttribute('aria-label','Até');
|
||
const today=new Date(Date.now()-3*3600e3).toISOString().slice(0,10);
|
||
from.max=to.max=today;
|
||
if(statsRange){from.value=statsRange.start;to.value=statsRange.end;}
|
||
const apply=button('Ver',()=>{
|
||
if(!from.value||!to.value)return say('Escolha a data inicial e a final.',true);
|
||
if(from.value>to.value)return say('A data inicial é depois da final.',true);
|
||
statsRange={start:from.value,end:to.value};loadStats().catch(e=>say(e.message,true));},'btn small');
|
||
const range=node('div',undefined,'daterange');range.append(from,node('span','até','faint'),to,apply);
|
||
box.replaceChildren(...chips,range);
|
||
}
|
||
async function loadStats(){
|
||
const data=await api('/stats?'+(statsRange?'start='+statsRange.start+'&end='+statsRange.end:'days='+statsDays));
|
||
statsPeriod();
|
||
$('stats-note').textContent='Pedidos pagos de '+dayLabel(data.start)+' a '+dayLabel(data.end)+'. Pedidos de teste e cancelados ficam de fora.';
|
||
const kpi=(label,value,note)=>{const k=node('div',undefined,'kpi');k.append(node('span',label),node('b',value));if(note)k.append(node('small',note));return k;};
|
||
const pct=data.orders?Math.round(100*data.corrected/data.orders):0;
|
||
$('stats-kpis').replaceChildren(
|
||
kpi('Pedidos pagos',String(data.orders)),
|
||
kpi('Metros vendidos',metres(data.metres)),
|
||
kpi('Recebido',money(data.cents),'com frete'),
|
||
kpi('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'),
|
||
kpi('Pedidos com correção',String(data.corrected),data.orders?pct+'% dos pedidos':null),
|
||
kpi('Do pagamento ao Finalizado',duration(data.lead.median_hours),data.lead.orders?'mediana de '+data.lead.orders+' pedidos':'nenhum finalizado'));
|
||
statsChart($('stats-chart'),data.daily);
|
||
const machineRows=data.machines.map(m=>{
|
||
const tr=node('tr');if(!m.active)tr.classList.add('off');
|
||
const now=[m.now.imp?m.now.imp+' imprimindo':'',m.now.fil?m.now.fil+' na fila':''].filter(Boolean).join(' · ');
|
||
tr.append(node('td',m.name+(m.active?'':' · desativada')),
|
||
node('td',m.orders?metres(m.metres)+' · '+m.orders+(m.orders>1?' pedidos':' pedido'):'nada'),
|
||
node('td',m.metres_per_hour!=null?String(m.metres_per_hour).replace('.',',')+' m/h':'—'),
|
||
node('td',m.last_finished?when(m.last_finished):'nunca','faint'),
|
||
node('td',m.id?now||'nada na fila':'—'));
|
||
return tr;});
|
||
if(!machineRows.length){const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada.','faint');td.colSpan=5;tr.append(td);machineRows.push(tr);}
|
||
$('stats-machines').replaceChildren(...machineRows);
|
||
const rows=['rec','tra','fil','imp','cor'].map(state=>{
|
||
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
|
||
name.append(sw,board.states[state]);
|
||
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?String(st.orders)+(st.passages>st.orders?' · '+st.passages+' passagens':''):'0';
|
||
tr.append(name,node('td',st?duration(st.median_hours):'—'),node('td',passed),
|
||
node('td',now?now.orders+(now.orders>1?' pedidos':' pedido')+' · o mais antigo há '+duration(now.oldest_hours):'nenhum'));
|
||
return tr;});
|
||
$('stats-stages').replaceChildren(...rows);
|
||
}
|
||
// Metres per day: one series, columns from one baseline, a tooltip per day
|
||
// and the same numbers as a table under the chart.
|
||
function statsChart(box,daily){
|
||
const ns='http://www.w3.org/2000/svg', w=Math.max(320,box.clientWidth||800), h=220, left=44, bottom=26, top=10;
|
||
const max=Math.max(...daily.map(d=>d.metres),0);
|
||
const step=max<=0?1:(()=>{const raw=max/4, 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 svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img');
|
||
svg.setAttribute('aria-label','Metros vendidos por dia, '+daily.length+' dias');
|
||
const el=(tag,attrs)=>{const e=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attrs))e.setAttribute(k,v);return e;};
|
||
const y=v=>top+(h-top-bottom)*(1-v/ceiling);
|
||
for(let v=0;v<=ceiling+1e-9;v+=step){
|
||
svg.append(el('line',{x1:left,x2:w,y1:y(v),y2:y(v),class:'grid'}));
|
||
const t=el('text',{x:left-8,y:y(v)+4,class:'tick','text-anchor':'end'});t.textContent=v.toLocaleString('pt-BR');svg.append(t);
|
||
}
|
||
const band=(w-left)/daily.length, bar=Math.min(24,Math.max(2,band-2));
|
||
const tip=node('div',undefined,'tip');tip.hidden=true;
|
||
const label=d=>new Date(d.day+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
|
||
const every=Math.ceil(daily.length/8);
|
||
daily.forEach((d,i)=>{
|
||
const x=left+band*i+(band-bar)/2, top_=y(d.metres), base=y(0), r=Math.min(4,bar/2,base-top_);
|
||
if(d.metres>0)svg.append(el('path',{class:'bar',d:`M${x},${base}V${top_+r}Q${x},${top_} ${x+r},${top_}H${x+bar-r}Q${x+bar},${top_} ${x+bar},${top_+r}V${base}Z`}));
|
||
if((daily.length-1-i)%every===0){const t=el('text',{x:x+bar/2,y:h-8,class:'tick','text-anchor':'middle'});t.textContent=label(d);svg.append(t);}
|
||
const hit=el('rect',{x:left+band*i,y:top,width:band,height:h-top-bottom,class:'hit'});
|
||
hit.onmouseenter=()=>{tip.hidden=false;tip.textContent=label(d)+' · '+d.orders+(d.orders===1?' pedido':' pedidos')+' · '+metres(d.metres);
|
||
tip.style.left=(100*(x+bar/2)/w)+'%';tip.style.top=(100*Math.min(top_,base-4)/h)+'%';};
|
||
hit.onmouseleave=()=>{tip.hidden=true;};
|
||
svg.append(hit);
|
||
});
|
||
const table=node('details',undefined,'charttable');table.append(node('summary','Ver em tabela'));
|
||
const t=node('table',undefined,'log');const head=node('tr');head.append(node('th','Dia'),node('th','Pedidos'),node('th','Metros'));t.append(head);
|
||
for(const d of [...daily].reverse()){const tr=node('tr');tr.append(node('td',label(d)),node('td',String(d.orders)),node('td',metres(d.metres)));t.append(tr);}
|
||
table.append(t);
|
||
box.replaceChildren(svg,tip,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)/96));}
|
||
function fitQuotes(){
|
||
const list=$('quote-list'), rows=[...list.querySelectorAll('.qitem')];
|
||
if($('tab-quotes').hidden||!rows.length||quoteFitting>3)return;
|
||
const room=list.clientHeight, gap=8;
|
||
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&"eTotal){quotePage=Math.ceil(quoteTotal/quoteSize);return loadQuotes();}
|
||
renderQuotes();
|
||
}
|
||
function renderQuotes(){
|
||
const kinds=[['pending','A revisar',board.pending_total],['approved','Aprovadas, aguardando pagamento',board.approved_total]];
|
||
$('quote-filters').replaceChildren(...kinds.map(([key,label,count])=>{
|
||
const b=node('button',label+' · '+count,'chip');b.type='button';b.setAttribute('aria-pressed',String(quoteKind===key));
|
||
b.onclick=()=>{quoteKind=key;quotePage=1;quoteFitting=0;currentQuote=null;loadQuotes().catch(e=>say(e.message,true));};return b;}));
|
||
// Product, layout and warning: each chip 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,'chip');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)&¤tQuote.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,'qitem');b.type='button';b.dataset.quotePick=q.id;b.setAttribute('aria-current',String(q.id===currentQuote?.id));
|
||
const items=q.draft.items;
|
||
const head=node('div',undefined,'qhead');
|
||
// 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';head.append(dot);}
|
||
head.append(buyerBlock(q.draft,'qmail'),node('b',q.approved?money(q.approved.total_cents):'a revisar','qtotal'+(q.approved?'':' muted')));
|
||
const meta=node('div',undefined,'meta');
|
||
meta.append(gradePill(lowestGrade(items)),productBadge(items),node('b',metres(quoteMetres(q)),'mtr'),
|
||
place(q.draft.destination),node('span',ago(q.created_at),'age'));
|
||
const flags=node('div',undefined,'flags');
|
||
if(items.some(i=>!LAYOUT_VERSIONS.includes(i.production?.version)))flags.append(badge('Montagem antiga','bad','Peça uma nova cotação ao cliente'));
|
||
else if(items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva aceita','warn','O cliente aceitou a ressalva de resolução'));
|
||
if(!q.approved&&q.review_reason)flags.append(badge('! '+q.review_reason,'warn','Revisão manual: '+q.review_reason));
|
||
// Approved by the Site is the rule; only a person's review is worth a line.
|
||
if(q.approved&&!q.auto_approved)flags.append(badge('Revisada pela equipe',''));
|
||
const pay=paymentBadge(q.payment);if(pay)flags.append(pay);
|
||
const main=node('div',undefined,'qmain');main.append(head,meta);if(flags.children.length)main.append(flags);
|
||
b.append(artBox(items,'qart'),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.','faint'));
|
||
$('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):node('p','Selecione uma cotação.','note'));
|
||
}
|
||
function review(quote){
|
||
const card=node('article',undefined,'review');card.style.display='contents';card.dataset.quote=quote.id;
|
||
const head=node('div',undefined,'head');const title=node('div',undefined,'qtitle');
|
||
const status={pending_review:['● A revisar','accent'],approved:['● Aprovada · aguardando pagamento','ok'],
|
||
expired:['Expirada','bad'],paid:['● Paga','info']}[quote.status]||[quote.status,''];
|
||
const name=node('div',undefined,'qname');name.append(buyerBlock(quote.draft),badge(...status));
|
||
const pay=paymentBadge(quote.payment);if(pay)name.append(pay);
|
||
const sub=node('div',undefined,'qsub');const c=quote.draft.customer;
|
||
const doc=node('span');doc.append(docKind(c.cnpj)+' '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar '+docKind(c.cnpj)));sub.append(doc);
|
||
const zap=whatsappLink(c.zap);
|
||
if(zap){const a=node('a',c.zap,'zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));sub.append(a);}
|
||
sub.append(place(quote.draft.destination,'Entrega em '),node('span','#'+quote.id.slice(0,8)+' · '+ago(quote.created_at),'faint'));
|
||
title.append(name,sub);head.append(title);
|
||
if(quote.approved){const total=node('div',undefined,'qbig');total.append(node('span','Total'),node('b',money(quote.approved.total_cents)));head.append(total);}
|
||
const content=node('div',undefined,'content');
|
||
const foot=node('div',undefined,'foot');
|
||
if(quote.status==='pending_review'&"e.draft.items.some(item=>!LAYOUT_VERSIONS.includes(item.production?.version))){
|
||
content.append(node('p','Montagem antiga. Solicite uma nova cotação ao cliente.','muted'));
|
||
card.append(head,content);return card;
|
||
}
|
||
if(quote.status!=='pending_review'){
|
||
if(quote.status==='expired')content.append(node('p','Cotação expirada. O cliente precisa solicitar outra.','muted'));
|
||
quote.draft.items.forEach((item,index)=>content.append(quoteItem(item,null,quote.approved?.items?.[index])));
|
||
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'));
|
||
content.append(sums);
|
||
}
|
||
card.append(head,content);
|
||
if(quote.status==='approved'&&may('manage')){
|
||
foot.append(discardButton(quote));
|
||
// Tries the whole production flow without a payment.
|
||
foot.append(button('Criar pedido de teste',async()=>{
|
||
if(!window.confirm('Criar um pedido de TESTE para esta cotação? Não cobra nada e não vai para o Tiny.'))return;
|
||
const order=await api('/quotes/'+quote.id+'/test-order',{});
|
||
say('Pedido de teste #'+order.number+' criado em Arte recebida.');await load();
|
||
},'btn ghost'));
|
||
card.append(foot);
|
||
}
|
||
return card;
|
||
}
|
||
if(!may('manage')){
|
||
quote.draft.items.forEach(item=>content.append(quoteItem(item,null)));
|
||
card.append(head,content);return card;
|
||
}
|
||
const form=node('form');form.style.display='contents';
|
||
const edits=quote.draft.items.map(item=>{const fields={};content.append(quoteItem(item,fields));
|
||
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});
|
||
foot.append(discardButton(quote));
|
||
const check=node('input');check.type='checkbox';check.required=true;
|
||
// Not "confirm": that name in this function hid window.confirm from the
|
||
// test-order button above, which then failed before asking anything.
|
||
const checked=node('label',undefined,'check');checked.append(check,'Arquivos, metragem e nota conferidos');
|
||
const submit=node('button','Aprovar cotação','btn primary');
|
||
foot.append(checked,submit);
|
||
form.append(content,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;}};
|
||
card.append(head,form);return card;
|
||
}
|
||
// An unpaid quote leaves the list and can no longer be paid.
|
||
function discardButton(quote){
|
||
return button('Descartar cotação',async()=>{
|
||
if(!window.confirm('Descartar esta cotação? Ela sai do Kanban e o cliente não consegue mais pagá-la.'))return;
|
||
await api('/quotes/'+quote.id+'/discard',{});currentQuote=null;say('Cotação descartada.');await load();
|
||
},'btn ghost discard');
|
||
}
|
||
function quoteItem(item,fields,priced){
|
||
const box=node('div',undefined,'item');
|
||
const preview=itemPreview(item);
|
||
if(!preview.classList.contains('with-art'))preview.style.width='160px';
|
||
const body=node('div',undefined,'body');
|
||
const spec=item.production;
|
||
const title=node('div',undefined,'title');
|
||
title.append(node('b',PRODUCT[item.mode]),gradePill(item.grade),...(priced?[node('span',money(priced.total_cents),'mono')]:[]));
|
||
body.append(title,facts([['Folha',sheetSize(spec)],['Cobrado',priced?metres(priced.billed_metres):null],
|
||
['Metro',priced?money(priced.unit_cents)+manualExtra(priced):null],['Peças',spec?String(spec.placements.length):null],
|
||
['Arquivos',spec?String(spec.sources.length):null]]));
|
||
const chips=node('div',undefined,'flags');
|
||
chips.append(item.quality_status==='ok'?badge('✓ Qualidade conferida','ok'):item.quality_status==='warning'?
|
||
badge(item.quality_acknowledged?'! Ressalva aceita pelo cliente':'! Ressalva não aceita','warn'):badge('Qualidade não conferida',''));
|
||
body.append(chips);
|
||
if(fields){
|
||
const grid=node('div',undefined,'fields');
|
||
const asked=node('label','Metros do cliente');const a=node('input');a.value=item.metres;a.readOnly=true;asked.append(a);
|
||
const m=node('label','Metros conferidos');fields.metres=node('input');Object.assign(fields.metres,{type:'number',min:'0.001',max:'12000',step:'any',value:item.metres,required:true});m.append(fields.metres);
|
||
const g=node('label','Nota conferida');fields.grade=node('input');Object.assign(fields.grade,{type:'number',min:'0',max:'100',step:'1',value:item.grade,required:true});g.append(fields.grade);
|
||
grid.append(asked,m,g);body.append(grid);
|
||
}
|
||
const buttons=node('div',undefined,'buttons');
|
||
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
|
||
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
|
||
body.append(buttons);box.append(preview,body);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;}
|
||
const trouble=!t.connected||t.problem;
|
||
el.textContent=!t.connected?'Tiny não conectado':t.problem?'Tiny: verificar conexão':'Tiny conectado';
|
||
el.style.setProperty('--dot',trouble?'var(--warn)':'var(--fin)');
|
||
}
|
||
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: name, 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 TONES={ok:'var(--ok)',warn:'var(--warn)',off:'var(--faint)'};
|
||
function integration({name,state,tone,summary,actions=[],details=[],extra=[]}){
|
||
const row=node('div',undefined,'integ');row.dataset.integ=name;
|
||
const main=node('div',undefined,'integ-main');main.style.setProperty('--c',TONES[tone]);
|
||
const title=node('div',undefined,'integ-name');title.append(node('span',undefined,'dot'),node('b',name));
|
||
const text=node('span',summary,'integ-summary');text.title=summary;
|
||
const buttons=node('div',undefined,'integ-actions');buttons.append(...actions);
|
||
// "Detalhes" has a column of its own, so the main buttons line up.
|
||
const more=node('div',undefined,'integ-toggle');
|
||
main.append(title,node('span',state,'integ-state'),text,buttons,more);row.append(main);
|
||
if(!details.length&&!extra.length)return row;
|
||
const panel=node('div',undefined,'integ-details');panel.id='integ-'+name.replace(/\W+/g,'-').toLowerCase();
|
||
const list=node('dl');
|
||
for(const part of details){
|
||
if(Array.isArray(part)){list.append(node('dt',part[0]),node('dd',part[1]));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,'buttons');b.append(...extra);panel.append(b);}
|
||
const open=OPEN_INTEG.has(name);panel.hidden=!open;
|
||
const toggle=node('button','Detalhes','btn ghost small integ-more');toggle.type='button';
|
||
toggle.append(icon(['M6 9l6 6 6-6']));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);};
|
||
more.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=(label,aria,target,disabled)=>{const b=node('button',label,'pg');b.type='button';b.setAttribute('aria-label',aria);b.disabled=disabled;b.onclick=()=>onPage(target);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('«','Primeira página',1,page<=1),go('‹','Página anterior',page-1,page<=1),pageLabel,
|
||
go('›','Próxima página',page+1,page>=pages),go('»','Ú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 chips(container,options,current,pick){
|
||
container.replaceChildren(...options.map(([key,label])=>{
|
||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(current===key));
|
||
b.onclick=()=>pick(key);return b;}));
|
||
}
|
||
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 filters=node('div',undefined,'chips');filters.style.marginBottom='12px';
|
||
chips(filters,[['open','Abertos'],['resolved','Resolvidos'],['all','Todos']],issueState,key=>{issueState=key;issuePage=1;loadIssues().catch(e=>say(e.message,true));});
|
||
const list=node('div');
|
||
if(!issueRows.length)list.append(node('p',issueState==='resolved'?'Nenhum pagamento resolvido.':'Nenhum pagamento pendente.','faint'));
|
||
for(const issue of issueRows){
|
||
const box=node('div',undefined,'issue');
|
||
if(issue.resolved_at)box.classList.add('done');
|
||
box.append(issue.resolved_at?icon(ICON_OK):icon(ICON_WARN));box.firstChild.style.color=issue.resolved_at?'var(--ok)':'var(--warn)';
|
||
const text=node('div',undefined,'text');
|
||
text.append(node('b',(issue.amount_cents==null?'Pagamento sem valor informado':'Pagamento de '+money(issue.amount_cents))+': '+outcomeText(issue.outcome)),
|
||
node('span',issue.provider+' · evento '+issue.event_id+' · cotação '+(issue.reference||'—')+' · '+when(issue.received_at)));
|
||
if(issue.resolved_at){
|
||
text.append(node('span','Resolvido por '+issue.resolved_by+' em '+when(issue.resolved_at)+': '+issue.resolution));
|
||
box.append(text);
|
||
}else{
|
||
const form=node('form');const note=node('input');note.placeholder='Resolução';note.setAttribute('aria-label','Resolução');note.required=true;note.minLength=3;note.maxLength=1000;
|
||
const save=node('button','Registrar resolução','btn warn');form.append(note,save);
|
||
form.onsubmit=async e=>{e.preventDefault();save.disabled=true;
|
||
try{await api('/payment-events/'+issue.id+'/resolve',{note:note.value});say('Resolução registrada.');await load();}
|
||
catch(error){say(error.message,true);save.disabled=false;}};
|
||
box.append(text,form);
|
||
}
|
||
list.append(box);
|
||
}
|
||
const bar=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(filters,list,bar);
|
||
}
|
||
|
||
// 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 select=(label,key,options)=>{
|
||
const field=node('label',undefined,'field');field.append(label);
|
||
const s=node('select');for(const [value,text] of options){const o=node('option',text);o.value=value;s.append(o);}
|
||
s.onchange=()=>{eventFilter[key]=s.value;eventPage=1;loadEvents().catch(e=>say(e.message,true));};
|
||
field.append(s);return field;
|
||
};
|
||
const order=node('label',undefined,'field');order.append('Pedido');
|
||
const input=node('input');input.type='number';input.min='1';input.placeholder='Nº';input.setAttribute('inputmode','numeric');
|
||
input.oninput=()=>{clearTimeout(eventTimer);eventTimer=setTimeout(()=>{eventFilter.order=input.value.trim();eventPage=1;loadEvents().catch(e=>say(e.message,true));},350);};
|
||
order.append(input);
|
||
bar.append(
|
||
select('Situação','status',[['','Todas'],['delivered','Enviados'],['queued','Na fila'],['failing','Com erro']]),
|
||
select('Evento','event',[['','Todos'],...Object.entries(EVENTS)]),
|
||
order);
|
||
}
|
||
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);
|
||
tr.append(node('td',when(e.delivered_at||e.available_at),'muted'),node('td','#'+e.payload.number,'mono'),
|
||
node('td',EVENTS[e.payload.event]||e.payload.event),node('td',result,cls));
|
||
return tr;
|
||
});
|
||
if(!rows.length){const tr=node('tr');const td=node('td','Nenhum envio encontrado.','faint');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 small');
|
||
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
|
||
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 small')],
|
||
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 small')]:[]}));
|
||
}
|
||
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 small')]:[];
|
||
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 ---------------------------
|
||
|
||
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,badge,color,open){
|
||
const el=node('button',undefined,'rhit');el.type='button';el.setAttribute('role','option');el.setAttribute('aria-selected','false');
|
||
const text=node('div',undefined,'rtext');const line=node('div');line.append(node('b',title),node('span',sub));
|
||
text.append(line,node('span',meta,'rmeta'));
|
||
const tag=node('span',badge,'rbadge');if(color)tag.style.setProperty('--c',color);
|
||
el.append(artBox(items,'rart'),text,tag);
|
||
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?'var(--bad)':STAGE_COLORS[order.state],()=>{
|
||
// 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?'':'var(--accent)',()=>{
|
||
// 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,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');
|
||
return $('app').hidden||!!dragging||!$('drawer').hidden||typing;
|
||
}
|
||
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();$('refresh-every').blur();
|
||
};
|
||
scheduleAuto();
|
||
})();
|
||
restoreFolder().finally(()=>load());
|