/* Kanban DTF: production board, quote review, payments and integrations. Everything is built with textContent; nothing from an order or a customer is ever parsed as HTML. The previous screen is in git tag ui-v1. */ const $ = id=>document.getElementById(id); // Remove credentials saved by older local builds. Only HttpOnly sessions now. sessionStorage.removeItem('dtf-operator'); // Dropstar's flow (2026-10-23): Arte conferida is the print queue and Revisão // checks the printed sheet. 'fil' (Fila de impressão) is only in older history. const FLOW=['rec','tra','imp','rev','fin']; const FORMER_STATES={fil:'Fila de impressão'}; const stateName=s=>board.states[s]||FORMER_STATES[s]||s; const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas',premium:'DTF Têxtil Premium · folha montada'}; // Loose art the Site split by stroke (item 17): each sheet is an item of its own. const productName=item=>PRODUCT[item.mode]+(item.split?' · folha '+item.split.part+' de '+item.split.of+ ', '+(item.stroke_class==='C3'?'chapado':'traço fino'):''); const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa',premium:'Premium'}; const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'}; // Payment outcomes are recorded by the API in English; operators read Portuguese. function outcomeText(outcome){ const rules=[ [/^refused: paid (\S+) but quote total is (\d+)/,m=>'valor pago ('+(m[1]==='None'?'não informado':money(Number(m[1])))+') diferente do total da cotação ('+money(Number(m[2]))+')'], [/^refused: quote expired/,()=>'a cotação venceu antes do pagamento'], [/^refused: quote not found/,()=>'cotação não encontrada'], [/^refused: quote was discarded/,()=>'a cotação tinha sido descartada no Kanban'], [/^refused: reference is not a quote id/,()=>'a referência do pagamento não é uma cotação'], [/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'], [/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'], [/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]], // The customer paid the same cart twice (a PIX and a card): one is refunded. [/^attention: second payment (\S+) for order (\d+)/,m=>'segundo pagamento ('+m[1]+') do pedido #'+m[2]+': o cliente pagou duas vezes, estorne um no Mercado Pago'], ]; for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);} return outcome; } let board=null; let tab='board', openOrder=null, openToken=0; const boardFilter={product:'',machine:'',delivery:'',origin:'',status:''}; // Layout versions the server takes (app/core/models.py PRODUCTION_VERSIONS). const LAYOUT_VERSIONS=[2,3]; let quoteKind='pending', pickedQuote=null; let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=null; // Uploads that have an artwork picture (the customer's browser made it). Every // list the API returns says which, so only pictures that exist are asked for. // The signed-in operator and what their profile allows (app/core/auth.py). let ME=null; const may=cap=>!!ME?.can?.includes(cap); const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor',financeiro:'Financeiro',expedicao:'Expedição'}; // Which moves this profile makes, and which columns' order it sets: the // server's own list (app/core/auth.py MOVES), never worked out here. const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to); const mayReorder=state=>!!ME?.reorder?.includes(state); // The session's machine (item 12). An operator pulls any card from the queue, // which becomes their machine's, and moves only their machine's cards; the // others show, without drag or buttons. const myMachine=()=>ME?.machine||null; const isMine=order=>!!myMachine()&&order.machine?.id===myMachine().id; // Every profile of the user, the main one first (Marcus, 2026-11-26): what // they may do is the sum of them. const myRoles=()=>ME?.roles?.length?ME.roles:ME?[ME.role]:[]; const hasRole=r=>myRoles().includes(r); const rolesLabel=roles=>roles.map(r=>ROLE_NAMES[r]||r).join(' / '); // The moves only the Operador profile allows this user: they keep to the // session's machine. An operator who is also Revisor releases any sheet. const machineBound=(a,b)=>(ME?.machine_moves||[]).some(([c,d])=>c===a&&d===b); // Printing comes to this user only through Operador: no choosing the machine by hand. const printOnlyAsOperator=()=>hasRole('operador')&&!myRoles().some(r=>['superadmin','admin','gestao'].includes(r)); const mayAct=order=>!hasRole('operador')||order.state==='tra'||isMine(order)|| (ME?.moves||[]).some(([a,b])=>a===order.state&&!machineBound(a,b)); // Which tabs each capability opens. // Vendedor and Financeiro consult Cotações and Números without acting there. const consults=()=>myRoles().some(r=>['vendedor','financeiro'].includes(r)); const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'), stats:()=>may('manage')||consults(),site:()=>may('manage'), integrations:()=>may('manage')||may('print')||may('label'),users:()=>may('users'),montar:()=>may('assemble')}; function applyRole(){ for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();} if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board'); } const THUMBS=new Set(); // Company names by CNPJ, from the public registry (app/cnpj.py). const NAMES=new Map(); const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id)); for(const [cnpj,name] of Object.entries(r?.names||{}))NAMES.set(cnpj,name);return r;}; let olderFinished=[], finishedMore=null; const money=cents=>(cents/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'}); const metres=value=>Number(value).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+' m'; const when=value=>new Date(value).toLocaleString('pt-BR',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'}); function ago(value){ const minutes=Math.max(0,Math.round((Date.now()-new Date(value))/60000)); if(minutes<60)return 'há '+minutes+' min'; const hours=Math.round(minutes/60); return hours<48?'há '+hours+' h':'há '+Math.round(hours/24)+' dias'; } // The customer's WhatsApp opens the conversation, for messages the system does // not send (a correction, a question about the artwork). function whatsappLink(zap){ const digits=String(zap||'').replace(/\D/g,''); if(digits.length<10)return null; return 'https://wa.me/'+(digits.length<=11?'55':'')+digits; } function node(tag,text,className){const e=document.createElement(tag);if(text!==undefined&&text!==null)e.textContent=text;if(className)e.className=className;return e;} function button(text,fn,className='btn'){ const b=node('button',text,className);b.type='button'; b.onclick=async event=>{event.stopPropagation();b.disabled=true;try{await fn();}catch(e){say(e.message,true);}finally{b.disabled=false;}}; return b; } // Messages are notifications, not state: they clear themselves. Errors stay // longer so they can be read; a caller can hold one for as long as it needs. let sayTimer=null; function say(text,error=false,ms){ clearTimeout(sayTimer); if(error&&text)window.dtfObservability?.uiError?.(text,'kanban'); for(const id of ['status','login-status']){$(id).textContent=text||'';$(id).classList.toggle('error',!!error);} if(text)sayTimer=setTimeout(()=>say(''),ms??(error?8000:4000)); } // Phosphor icons (regular, MIT): a 256 px viewBox filled with the text // colour. svgIcon keeps the same classes: i (20), i m (16), i s (14). const IC={ search:'M229.66,218.34l-50.07-50.06a88.11,88.11,0,1,0-11.31,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z', filter:'M200,136a8,8,0,0,1-8,8H64a8,8,0,0,1,0-16H192A8,8,0,0,1,200,136Zm32-56H24a8,8,0,0,0,0,16H232a8,8,0,0,0,0-16Zm-80,96H104a8,8,0,0,0,0,16h48a8,8,0,0,0,0-16Z', download:'M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z', upload:'M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0ZM93.66,77.66,120,51.31V144a8,8,0,0,0,16,0V51.31l26.34,26.35a8,8,0,0,0,11.32-11.32l-40-40a8,8,0,0,0-11.32,0l-40,40A8,8,0,0,0,93.66,77.66Z', close:'M205.66,194.34a8,8,0,0,1-11.32,11.32L128,139.31,61.66,205.66a8,8,0,0,1-11.32-11.32L116.69,128,50.34,61.66A8,8,0,0,1,61.66,50.34L128,116.69l66.34-66.35a8,8,0,0,1,11.32,11.32L139.31,128Z', copy:'M216,32H88a8,8,0,0,0-8,8V80H40a8,8,0,0,0-8,8V216a8,8,0,0,0,8,8H168a8,8,0,0,0,8-8V176h40a8,8,0,0,0,8-8V40A8,8,0,0,0,216,32ZM160,208H48V96H160Zm48-48H176V88a8,8,0,0,0-8-8H96V48H208Z', phone:'M222.37,158.46l-47.11-21.11-.13-.06a16,16,0,0,0-15.17,1.4,8.12,8.12,0,0,0-.75.56L134.87,160c-15.42-7.49-31.34-23.29-38.83-38.51l20.78-24.71c.2-.25.39-.5.57-.77a16,16,0,0,0,1.32-15.06l0-.12L97.54,33.64a16,16,0,0,0-16.62-9.52A56.26,56.26,0,0,0,32,80c0,79.4,64.6,144,144,144a56.26,56.26,0,0,0,55.88-48.92A16,16,0,0,0,222.37,158.46ZM176,208A128.14,128.14,0,0,1,48,80,40.2,40.2,0,0,1,82.87,40a.61.61,0,0,0,0,.12l21,47L83.2,111.86a6.13,6.13,0,0,0-.57.77,16,16,0,0,0-1,15.7c9.06,18.53,27.73,37.06,46.46,46.11a16,16,0,0,0,15.75-1.14,8.44,8.44,0,0,0,.74-.56L168.89,152l47,21.05h0s.08,0,.11,0A40.21,40.21,0,0,1,176,208Z', chat:'M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm0,192a87.87,87.87,0,0,1-44.06-11.81,8,8,0,0,0-6.54-.67L40,216,52.47,178.6a8,8,0,0,0-.66-6.54A88,88,0,1,1,128,216Z', truck:'M255.42,117l-14-35A15.93,15.93,0,0,0,226.58,72H192V64a8,8,0,0,0-8-8H32A16,16,0,0,0,16,72V184a16,16,0,0,0,16,16H49a32,32,0,0,0,62,0h50a32,32,0,0,0,62,0h17a16,16,0,0,0,16-16V120A7.94,7.94,0,0,0,255.42,117ZM192,88h34.58l9.6,24H192ZM32,72H176v64H32ZM80,208a16,16,0,1,1,16-16A16,16,0,0,1,80,208Zm81-24H111a32,32,0,0,0-62,0H32V152H176v12.31A32.11,32.11,0,0,0,161,184Zm31,24a16,16,0,1,1,16-16A16,16,0,0,1,192,208Zm48-24H223a32.06,32.06,0,0,0-31-24V128h48Z', pin:'M128,64a40,40,0,1,0,40,40A40,40,0,0,0,128,64Zm0,64a24,24,0,1,1,24-24A24,24,0,0,1,128,128Zm0-112a88.1,88.1,0,0,0-88,88c0,31.4,14.51,64.68,42,96.25a254.19,254.19,0,0,0,41.45,38.3,8,8,0,0,0,9.18,0A254.19,254.19,0,0,0,174,200.25c27.45-31.57,42-64.85,42-96.25A88.1,88.1,0,0,0,128,16Zm0,206c-16.53-13-72-60.75-72-118a72,72,0,0,1,144,0C200,161.23,144.53,209,128,222Z', check:'M229.66,77.66l-128,128a8,8,0,0,1-11.32,0l-56-56a8,8,0,0,1,11.32-11.32L96,188.69,218.34,66.34a8,8,0,0,1,11.32,11.32Z', alert:'M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z', info:'M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm16-40a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176ZM112,84a12,12,0,1,1,12,12A12,12,0,0,1,112,84Z', arrow:'M221.66,133.66l-72,72a8,8,0,0,1-11.32-11.32L196.69,136H40a8,8,0,0,1,0-16H196.69L138.34,61.66a8,8,0,0,1,11.32-11.32l72,72A8,8,0,0,1,221.66,133.66Z', left:'M165.66,202.34a8,8,0,0,1-11.32,11.32l-80-80a8,8,0,0,1,0-11.32l80-80a8,8,0,0,1,11.32,11.32L91.31,128Z', right:'M181.66,133.66l-80,80a8,8,0,0,1-11.32-11.32L164.69,128,90.34,53.66a8,8,0,0,1,11.32-11.32l80,80A8,8,0,0,1,181.66,133.66Z', first:'M205.66,202.34a8,8,0,0,1-11.32,11.32l-80-80a8,8,0,0,1,0-11.32l80-80a8,8,0,0,1,11.32,11.32L131.31,128ZM51.31,128l74.35-74.34a8,8,0,0,0-11.32-11.32l-80,80a8,8,0,0,0,0,11.32l80,80a8,8,0,0,0,11.32-11.32Z', last:'M141.66,133.66l-80,80a8,8,0,0,1-11.32-11.32L124.69,128,50.34,53.66A8,8,0,0,1,61.66,42.34l80,80A8,8,0,0,1,141.66,133.66Zm80-11.32-80-80a8,8,0,0,0-11.32,11.32L204.69,128l-74.35,74.34a8,8,0,0,0,11.32,11.32l80-80A8,8,0,0,0,221.66,122.34Z', down:'M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,53.66,90.34L128,164.69l74.34-74.35a8,8,0,0,1,11.32,11.32Z', plus:'M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z', more:'M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z', folder:'M216,72H131.31L104,44.69A15.86,15.86,0,0,0,92.69,40H40A16,16,0,0,0,24,56V200.62A15.4,15.4,0,0,0,39.38,216H216.89A15.13,15.13,0,0,0,232,200.89V88A16,16,0,0,0,216,72ZM40,56H92.69l16,16H40ZM216,200H40V88H216Z', mail:'M224,48H32a8,8,0,0,0-8,8V192a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V56A8,8,0,0,0,224,48ZM203.43,64,128,133.15,52.57,64ZM216,192H40V74.19l82.59,75.71a8,8,0,0,0,10.82,0L216,74.19V192Z', box:'M223.68,66.15,135.68,18a15.88,15.88,0,0,0-15.36,0l-88,48.17a16,16,0,0,0-8.32,14v95.64a16,16,0,0,0,8.32,14l88,48.17a15.88,15.88,0,0,0,15.36,0l88-48.17a16,16,0,0,0,8.32-14V80.18A16,16,0,0,0,223.68,66.15ZM128,32l80.34,44-29.77,16.3-80.35-44ZM128,120,47.66,76l33.9-18.56,80.34,44ZM40,90l80,43.78v85.79L40,175.82Zm176,85.78h0l-80,43.79V133.82l32-17.51V152a8,8,0,0,0,16,0V107.55L216,90v85.77Z', file:'M213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40V216a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V88A8,8,0,0,0,213.66,82.34ZM160,51.31,188.69,80H160ZM200,216H56V40h88V88a8,8,0,0,0,8,8h48V216Zm-32-80a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,136Zm0,32a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,168Z', calendar:'M208,32H184V24a8,8,0,0,0-16,0v8H88V24a8,8,0,0,0-16,0v8H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32ZM72,48v8a8,8,0,0,0,16,0V48h80v8a8,8,0,0,0,16,0V48h24V80H48V48ZM208,208H48V96H208V208Z', card:'M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48Zm0,16V88H32V64Zm0,128H32V104H224v88Zm-16-24a8,8,0,0,1-8,8H168a8,8,0,0,1,0-16h32A8,8,0,0,1,208,168Zm-64,0a8,8,0,0,1-8,8H120a8,8,0,0,1,0-16h16A8,8,0,0,1,144,168Z', bag:'M216,40H40A16,16,0,0,0,24,56V200a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V56A16,16,0,0,0,216,40Zm0,160H40V56H216V200ZM176,88a48,48,0,0,1-96,0,8,8,0,0,1,16,0,32,32,0,0,0,64,0,8,8,0,0,1,16,0Z', key:'M216.57,39.43A80,80,0,0,0,83.91,120.78L28.69,176A15.86,15.86,0,0,0,24,187.31V216a16,16,0,0,0,16,16H72a8,8,0,0,0,8-8V208H96a8,8,0,0,0,8-8V184h16a8,8,0,0,0,5.66-2.34l9.56-9.57A79.73,79.73,0,0,0,160,176h.1A80,80,0,0,0,216.57,39.43ZM224,98.1c-1.09,34.09-29.75,61.86-63.89,61.9H160a63.7,63.7,0,0,1-23.65-4.51,8,8,0,0,0-8.84,1.68L116.69,168H96a8,8,0,0,0-8,8v16H72a8,8,0,0,0-8,8v16H40V187.31l58.83-58.82a8,8,0,0,0,1.68-8.84A63.72,63.72,0,0,1,96,95.92c0-34.14,27.81-62.8,61.9-63.89A64,64,0,0,1,224,98.1ZM192,76a12,12,0,1,1-12-12A12,12,0,0,1,192,76Z', database:'M128,24C74.17,24,32,48.6,32,80v96c0,31.4,42.17,56,96,56s96-24.6,96-56V80C224,48.6,181.83,24,128,24Zm80,104c0,9.62-7.88,19.43-21.61,26.92C170.93,163.35,150.19,168,128,168s-42.93-4.65-58.39-13.08C55.88,147.43,48,137.62,48,128V111.36c17.06,15,46.23,24.64,80,24.64s62.94-9.68,80-24.64ZM69.61,53.08C85.07,44.65,105.81,40,128,40s42.93,4.65,58.39,13.08C200.12,60.57,208,70.38,208,80s-7.88,19.43-21.61,26.92C170.93,115.35,150.19,120,128,120s-42.93-4.65-58.39-13.08C55.88,99.43,48,89.62,48,80S55.88,60.57,69.61,53.08ZM186.39,202.92C170.93,211.35,150.19,216,128,216s-42.93-4.65-58.39-13.08C55.88,195.43,48,185.62,48,176V159.36c17.06,15,46.23,24.64,80,24.64s62.94-9.68,80-24.64V176C208,185.62,200.12,195.43,186.39,202.92Z', refresh:'M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z', rework:'M224,48V96a8,8,0,0,1-8,8H168a8,8,0,0,1,0-16h28.69L182.06,73.37a79.56,79.56,0,0,0-56.13-23.43h-.45A79.52,79.52,0,0,0,69.59,72.71,8,8,0,0,1,58.41,61.27a96,96,0,0,1,135,.79L208,76.69V48a8,8,0,0,1,16,0ZM186.41,183.29a80,80,0,0,1-112.47-.66L59.31,168H88a8,8,0,0,0,0-16H40a8,8,0,0,0-8,8v48a8,8,0,0,0,16,0V179.31l14.63,14.63A95.43,95.43,0,0,0,130,222.06h.53a95.36,95.36,0,0,0,67.07-27.33,8,8,0,0,0-11.18-11.44Z', back:'M232,144a64.07,64.07,0,0,1-64,64H80a8,8,0,0,1,0-16h88a48,48,0,0,0,0-96H51.31l34.35,34.34a8,8,0,0,1-11.32,11.32l-48-48a8,8,0,0,1,0-11.32l48-48A8,8,0,0,1,85.66,45.66L51.31,80H168A64.07,64.07,0,0,1,232,144Z', ban:'M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm88,104a87.56,87.56,0,0,1-20.41,56.28L71.72,60.4A88,88,0,0,1,216,128ZM40,128A87.56,87.56,0,0,1,60.41,71.72L184.28,195.6A88,88,0,0,1,40,128Z', logout:'M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40a8,8,0,0,0-11.32,11.32L204.69,120H112a8,8,0,0,0,0,16h92.69l-26.35,26.34a8,8,0,0,0,11.32,11.32l40-40A8,8,0,0,0,229.66,122.34Z', printer:'M214.67,72H200V40a8,8,0,0,0-8-8H64a8,8,0,0,0-8,8V72H41.33C27.36,72,16,82.77,16,96v80a8,8,0,0,0,8,8H56v32a8,8,0,0,0,8,8H192a8,8,0,0,0,8-8V184h32a8,8,0,0,0,8-8V96C240,82.77,228.64,72,214.67,72ZM72,48H184V72H72ZM184,208H72V160H184Zm40-40H200V152a8,8,0,0,0-8-8H64a8,8,0,0,0-8,8v16H32V96c0-4.41,4.19-8,9.33-8H214.67c5.14,0,9.33,3.59,9.33,8Zm-24-52a12,12,0,1,1-12-12A12,12,0,0,1,200,116Z', eye:'M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z', camera:'M208,56H180.28L166.65,35.56A8,8,0,0,0,160,32H96a8,8,0,0,0-6.65,3.56L75.71,56H48A24,24,0,0,0,24,80V192a24,24,0,0,0,24,24H208a24,24,0,0,0,24-24V80A24,24,0,0,0,208,56Zm8,136a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V80a8,8,0,0,1,8-8H80a8,8,0,0,0,6.66-3.56L100.28,48h55.43l13.63,20.44A8,8,0,0,0,176,72h32a8,8,0,0,1,8,8ZM128,88a44,44,0,1,0,44,44A44.05,44.05,0,0,0,128,88Zm0,72a28,28,0,1,1,28-28A28,28,0,0,1,128,160Z', edit:'M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z', user:'M230.92,212c-15.23-26.33-38.7-45.21-66.09-54.16a72,72,0,1,0-73.66,0C63.78,166.78,40.31,185.66,25.08,212a8,8,0,1,0,13.85,8c18.84-32.56,52.14-52,89.07-52s70.23,19.44,89.07,52a8,8,0,1,0,13.85-8ZM72,96a56,56,0,1,1,56,56A56.06,56.06,0,0,1,72,96Z', link:'M240,88.23a54.43,54.43,0,0,1-16,37L189.25,160a54.27,54.27,0,0,1-38.63,16h-.05A54.63,54.63,0,0,1,96,119.84a8,8,0,0,1,16,.45A38.62,38.62,0,0,0,150.58,160h0a38.39,38.39,0,0,0,27.31-11.31l34.75-34.75a38.63,38.63,0,0,0-54.63-54.63l-11,11A8,8,0,0,1,135.7,59l11-11A54.65,54.65,0,0,1,224,48,54.86,54.86,0,0,1,240,88.23ZM109,185.66l-11,11A38.41,38.41,0,0,1,70.6,208h0a38.63,38.63,0,0,1-27.29-65.94L78,107.31A38.63,38.63,0,0,1,144,135.71a8,8,0,0,0,16,.45A54.86,54.86,0,0,0,144,96a54.65,54.65,0,0,0-77.27,0L32,130.75A54.62,54.62,0,0,0,70.56,224h0a54.28,54.28,0,0,0,38.64-16l11-11A8,8,0,0,0,109,185.66Z', }; function svgIcon(d,className='i'){ const ns='http://www.w3.org/2000/svg',svg=document.createElementNS(ns,'svg'),path=document.createElementNS(ns,'path'); svg.setAttribute('class',className);svg.setAttribute('viewBox','0 0 256 256');svg.setAttribute('aria-hidden','true'); path.setAttribute('fill','currentColor');path.setAttribute('d',d);svg.append(path);return svg; } // ---- Badges: one system on every screen (canvas "Kanban DTF — redesign", v2) -- // The grade pill is coloured in bands (90/75/60/40), those of the old price // ladder; the grade no longer sets the price (2026-10-23). The bands are the same // for all four products; product, status and warnings are pills with text. const GRADE_BANDS=[[90,'g90'],[75,'g75'],[60,'g60'],[40,'g40'],[0,'g0']]; function gradePill(grade){ const n=grade===null||grade===undefined||grade===''?NaN:Number(grade); const ok=Number.isFinite(n); const b=node('span',ok?String(n):'—','grade '+(ok?GRADE_BANDS.find(([min])=>n>=min)[1]:'gnone')); b.title=ok?'Nota da arte: '+n:'Sem nota: conferência manual';return b; } const lowestGrade=items=>{const g=items.map(i=>Number(i.grade)).filter(Number.isFinite);return g.length?Math.min(...g):null;}; function badge(text,tone='',title=''){const b=node('span',text,'pill '+tone);if(title)b.title=title;return b;} const cm=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:1}); // The machine sheet shows metres with one decimal even when it is a round number. const m1=v=>Number(v).toLocaleString('pt-BR',{minimumFractionDigits:1,maximumFractionDigits:1}); const plural=(n,one,many)=>n+' '+(n===1?one:many); // The customer's CPF or CNPJ, formatted, and which of the two it is. function cnpj(value){const d=String(value||'').replace(/\D/g,'');return d.length===14?d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'):d.length===11?d.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/,'$1.$2.$3-$4'):String(value||'');} const docKind=value=>String(value||'').replace(/\D/g,'').length===11?'CPF':'CNPJ'; function copyButton(text,label){ const b=node('button',undefined,'copy');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(svgIcon(IC.copy,'i s')); b.onclick=async e=>{e.stopPropagation();try{await navigator.clipboard.writeText(text);say('Copiado.');}catch(_){say('Não foi possível copiar.',true);}}; return b; } // Facts as a grid of small labelled boxes; empty values are left out. function facts(pairs){ const dl=node('dl',undefined,'factgrid'); for(const [k,v] of pairs){if(v===null||v===undefined||v==='')continue;const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);} return dl; } // Who is buying: a name when the order has one (the customer's, or whoever // receives the delivery), else the e-mail. With a name, the e-mail is the // second line, still searchable. function buyer(content){ const c=content.customer||{}, company=NAMES.get(String(c.cnpj||'').replace(/\D/g,'')); // The trade name people know the shop by, else its razão social. const name=(c.name||company?.trade||company?.legal||content.destination?.recipient||'').trim(); return {title:name||c.mail, mail:name?c.mail:'', legal:company?.legal||''}; } // The quote's latest payment attempt as a badge; none means nobody tried yet. function paymentBadge(p){ if(!p)return null; const hour=v=>new Date(v).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}); const tried=' · tentativa '+when(p.created_at); if(p.method==='pix'){ if(p.status==='approved')return badge('✓ PIX pago','ok'); const live=p.status==='pending'&&p.expires_at&&new Date(p.expires_at)>Date.now(); return live?badge('PIX gerado · expira '+hour(p.expires_at),'info','O cliente gerou o código'+tried) :badge('! PIX expirou sem pagamento','warn','O código venceu e o cliente ainda pode gerar outro'+tried); } if(p.status==='approved')return badge('✓ Cartão aprovado','ok'); if(p.status==='rejected')return badge('! Cartão recusado','bad',(p.message||'Recusado')+(p.status_detail?' ('+p.status_detail+')':'')+tried); if(p.status==='pending')return badge(p.status_detail==='pending_challenge'?'Cartão aguardando o banco':'Cartão em análise','info',tried.slice(3)); return badge('Pagamento '+p.status,'',tried.slice(3)); } // What the customer calls the order (the id's first 8 characters, as the // server's order_code); the # number is the operators'. const orderCode=id=>String(id).replace(/-/g,'').slice(0,8).toUpperCase(); // The order's files start with this (app/printjobs.py): pasted into the folder's // search it finds them, and the dash keeps DTF-23 from finding DTF-230. const fileCode=order=>'DTF-'+order.number+'-'; const sheetSize=p=>p?cm(p.film_width_cm)+' × '+cm(p.height_cm)+' cm':null; const hoursSince=v=>Math.floor((Date.now()-new Date(v))/3600000); // The freight's weight: what the package weighs and, when Jadlog charges the // box's size instead (the cubed weight), what it is charged as. function freightWeight(fr){ const kg=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:2})+' kg'; if(!fr?.weight_kg)return ''; if(fr.real_kg&&Number(fr.real_kg)e&&e.msg):null; const field=first?.loc?.filter(part=>typeof part==='string'&&part!=='body').join('.'); const error=new Error(typeof d.detail==='string'?d.detail: 'Confira os campos ('+r.status+')'+(first?': '+(field?field+', ':'')+first.msg:'.')); error.status=r.status; // A status the caller expects and answers itself is not reported. if(!(options.expected||[]).includes(r.status))window.dtfObservability?.apiError?.(path,r.status,error.message,d.detail); throw error; } return d; } function download(uid,orderId){return async()=>{ const result=await api('/uploads/'+uid+'/download'+(orderId?'?order_id='+encodeURIComponent(orderId):'')); const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click(); };} // ---- Automatic folder ------------------------------------------------------ // The orders' files, kept by this browser in Dropstar's folders // (2026-10-26) inside the one chosen, while the Kanban is open. It is switched // on in Integrações, on a computer of the factory that reaches the server's // folder: the folder belongs to that browser, not to the account. Chrome and // Edge write into the folder chosen, remembered, with one click to release it // after the browser restarts. Brave has the same API behind a flag that is off // by default; the card says how to turn it on. Firefox cannot write into a // chosen folder: there each file entering the queue is downloaded, and // Firefox's own download folder is set to FlexiPRINT's. const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1); r.onupgradeneeded=()=>r.result.createObjectStore('kv');r.onsuccess=()=>ok(r.result);r.onerror=()=>fail(r.error);})); const run=async(mode,fn)=>{const db=await open();return new Promise((ok,fail)=>{const t=db.transaction('kv',mode);const req=fn(t.objectStore('kv')); t.oncomplete=()=>ok(req?.result);t.onerror=()=>fail(t.error);});}; return {get:k=>run('readonly',s=>s.get(k)),set:(k,v)=>run('readwrite',s=>s.put(v,k)),del:k=>run('readwrite',s=>s.delete(k))};})(); const BRAVE_FLAG='brave://flags/#file-system-access-api'; // Where an order's file is, by its stage: it arrives in Arte recebida, moves // to Arte conferida (the queue) with the card and stays there while it // prints, goes to Revisão with the card, then to Finalizado, kept 30 days. // Correção, a cancellation or a deletion takes it out; a replaced final is // swapped. Numbered as Dropstar set them (2026-10-30), so a folder listing // shows the flow's order; 3. Imprimindo is where the machines' hot folders go. const STAGE_FOLDERS={rec:'1. Arte recebida',tra:'2. Arte conferida',imp:'2. Arte conferida',rev:'4. Revisão',fin:'5. Finalizado'}; const PRINTING_FOLDER='3. Imprimindo'; // The names before 2026-10-30: their files move to the new ones, and the old // folder goes once it is empty. const OLD_FOLDERS=['3. Finalizado']; const KEEP_FINISHED_DAYS=30; // The pickup receipts (item 14): the counter's print queue watches this one. const RECEIPTS_FOLDER='Recibos'; // The review photos and videos (front 2), written once and never removed. const REVIEWS_FOLDER='Revisões'; const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null, saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null, // Passes in a row each file was held open by another program (DTF-WEB-M), // or could not be downloaded for the network (DTF-WEB-V). locked:new Map(),unreachable:new Map(), // Since when the main folder does not answer (DTF-WEB-P), and whether that was reported. awaySince:0,awayReported:false, // Whether this page load cleared the old version's leftovers (order #30). swept:false}; const LOCKED_REPORT_PASSES=10; const FOLDER_AWAY_REPORT_MS=5*60000; // When the folders were chosen: every order paid since then ends up in them, // even one that went through while this computer was off (Dropstar's rules, // 2026-10-26). Folders chosen before this existed count from their first round. async function folderSince(reset=false){ let since=reset?null:await kv.get('folder-since').catch(()=>null); if(!since){since=new Date().toISOString();await kv.set('folder-since',since).catch(()=>{});} return FOLDER.since=since; } // Switched on: a chosen folder released, or automatic downloads. const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads; // The three folders started their own record: files saved by the single // folder of before 2026-10-26 are left where they are. const savedKey=()=>FOLDER.mode==='folder'?'stages:'+FOLDER.handle.name:'saved:downloads'; // What this folder received, by upload: its order, item, name, the folder it // is in and, in Finalizado, since when. Older versions kept only the upload ids. const savedMap=list=>new Map((list||[]).map(e=>typeof e==='string'?[e,{place:'done'}]:e)); const loadSaved=async()=>savedMap(await kv.get(savedKey()).catch(()=>null)); const keepSaved=()=>kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{}); async function restoreFolder(){ if(FOLDER.mode==='downloads'){ try{FOLDER.downloads=localStorage.getItem('dtf-auto-downloads')==='1';}catch{} if(FOLDER.downloads)FOLDER.saved=await loadSaved(); return; } if(FOLDER.mode!=='folder')return; try{FOLDER.handle=await kv.get('folder')||null; if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted'; FOLDER.saved=await loadSaved();await folderSince(); if(!FOLDER.granted)armFolderRelease();}} catch{FOLDER.handle=null;} } // After a reload the browser forgets the folder's permission and only gives // it back on a click. Nobody at the machines opens Integrações (Marcus, // 2026-11-16), so the first click or key anywhere in the signed-in Kanban asks // for it; Chrome may then offer to allow it on every visit. function armFolderRelease(){ const ask=event=>{ if(!FOLDER.handle||FOLDER.granted){stop();return;} if($('app').hidden||event.key==='Escape')return; stop(); releaseFolder().catch(()=>{}).finally(()=>{if(FOLDER.handle&&!FOLDER.granted)armFolderRelease();}); }; const stop=()=>{removeEventListener('pointerup',ask,true);removeEventListener('keydown',ask,true);}; addEventListener('pointerup',ask,true);addEventListener('keydown',ask,true); } // The folder's row in Integrações, redrawn whenever its state changes. The // row says what is happening; the how-to and the secondary buttons are under // "Detalhes". function folderCard(){ const name='Pastas dos pedidos', h=FOLDER.handle; const act=(text,fn)=>button(text,fn,'btn'); const ghost=(text,fn)=>button(text,fn,'btn ghost'); const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;}; let row; if(FOLDER.mode==='none'){ if(FOLDER.brave){ const first=node('li','Copie este endereço: ');first.append(node('code',BRAVE_FLAG,'flag')); row=integration({name,state:'Desligada no Brave',tone:'warn',summary:'O Brave bloqueia o acesso a pastas. Dá para liberar em 1 minuto.', actions:[act('Copiar endereço',async()=>{await navigator.clipboard.writeText(BRAVE_FLAG);say('Endereço copiado: cole na barra do Brave.');})], details:[steps(first,'Cole na barra do Brave e mude “File System Access API” para “Enabled”.','Reinicie o Brave e volte aqui.'), node('p','Ou abra o Kanban no Chrome ou no Edge, que já vêm com isso ligado.')]}); }else row=integration({name,state:'Não funciona aqui',tone:'off',summary:'Abra o Kanban no Chrome ou no Edge para salvar numa pasta.'}); }else if(FOLDER.mode==='downloads'){ const how=[steps('No Firefox, abra Configurações → Geral → Arquivos e aplicativos.', 'Em “Salvar arquivos em”, escolha a pasta que o FlexiPRINT lê.','Desmarque “Sempre perguntar onde salvar arquivos”.'), node('p','Use um perfil do Firefox só para o Kanban: os outros downloads também vão para essa pasta.')]; row=FOLDER.downloads ? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok', summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(), details:how,extra:[ghost('Desligar',()=>setDownloads(false))]}) : integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as pastas do fluxo pedem o Chrome ou o Edge.', actions:[act('Ligar',()=>setDownloads(true))],details:how}); }else if(!h){ row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos nas pastas do fluxo, de 1. Arte recebida a 5. Finalizado, o recibo de cada retirada em Recibos e as fotos da revisão em Revisões.', actions:[act('Escolher pasta',chooseFolder)], details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as pastas do fluxo e move o arquivo conforme o card anda. '+ 'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]}); }else if(!FOLDER.granted){ row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.', actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]}); }else{ row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok', summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(), details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)], ['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'], node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em '+STAGE_FOLDERS.rec+', passa para '+STAGE_FOLDERS.tra+' quando o card vai para lá '+ 'e fica lá enquanto imprime, vai para '+STAGE_FOLDERS.rev+' com o card e para '+STAGE_FOLDERS.fin+' quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'), node('p','A pasta '+WORK_FOLDER+' é a de trabalho do Kanban: cada arquivo é gravado nela e só entra na pasta da etapa ou na hot folder completo, com o nome final. Não coloque nada nela.'), node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada. As fotos da revisão vão para '+REVIEWS_FOLDER+' e não saem de lá.'), node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+ 'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+ 'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')], extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]}); } row.id='folder-card';return row; } function folderCount(){ const n=FOLDER.saved.size; return (n?n+(n>1?' arquivos salvos':' arquivo salvo'):'nenhum arquivo salvo ainda')+ (FOLDER.last?', o último às '+FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):''); } // The folder's row and the tab's warning sign, which shows the folder needs a click. function paintFolder(){ $('folder-card')?.replaceWith(folderCard()); const attention=may('print')&&(FOLDER.mode==='folder'&&!!FOLDER.handle&&!FOLDER.granted||folderActive()&&!!FOLDER.error); $('badge-integrations').textContent=attention?'!':''; } async function chooseFolder(){ // Safari and the phones have no folder picker (Sentry DTF-WEB-16). if(!('showDirectoryPicker' in window)){say('Este navegador não grava em pastas. Use o Chrome ou o Edge no computador da fábrica.');return;} 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.swept=false; FOLDER.saved=await loadSaved(); await kv.set('folder',handle).catch(()=>{}); await folderSince(true); await makeStageFolders(); paintFolder();say('Pastas '+[...new Set(Object.values(STAGE_FOLDERS))].join(', ')+' criadas dentro de “'+handle.name+'”.');syncFolder(true); } // One request at a time: the first click on "Liberar pasta" is also the click // armFolderRelease waits for. let folderReleasing=null; function releaseFolder(){ return folderReleasing||=(async()=>{ try{FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';} finally{folderReleasing=null;} // The pass creates the flow's folders and says what failed, if anything. FOLDER.lastSig=null;FOLDER.error='';paintFolder();if(FOLDER.granted)syncFolder(true); })(); } async function forgetFolder(){ FOLDER.handle=null;FOLDER.granted=false;FOLDER.error='';FOLDER.status=''; await kv.del('folder').catch(()=>{});paintFolder();say('Pasta automática desligada.'); } async function setDownloads(on){ FOLDER.downloads=on;FOLDER.lastSig=null;FOLDER.error='';FOLDER.status=''; try{localStorage.setItem('dtf-auto-downloads',on?'1':'0');}catch{} if(on)FOLDER.saved=await loadSaved(); paintFolder();say(on?'Download automático ligado.':'Download automático desligado.'); if(on)syncFolder(); } // Where a file is written before it goes to its folder (Marcus, 2026-11-17, // order #30). Chrome writes a working copy (.crswap) beside the file it // writes; in a hot folder the FlexiPRINT took each one as it appeared, the // write failed and every try left one behind. Nothing watches this folder; // the whole file then moves to its own folder under its final name, a // rename on the same share. What stays here an hour is a try that never finished. const WORK_FOLDER='_tmp'; const WORK_KEEP_MS=3600000; // A file that arrived empty or short: deleted, reported, tried again. class IncompleteFile extends Error{constructor(message){super(message);this.name='IncompleteFile';}} const fileSize=bytes=>bytes<1048576?Math.round(bytes/1024)+' KB':(bytes/1048576).toLocaleString('pt-BR',{maximumFractionDigits:1})+' MB'; // A whole file in a folder: written in WORK_FOLDER, its size checked, then // moved in, so no program ever sees half of it. `source` is a download's // response or a file. In a folder a program watches (`watched`: the hot // folders, and Recibos for the counter's printer) nothing else is ever written: a move that fails is tried again on // the next pass. Elsewhere a browser that cannot move the file copies it. async function writeWhole(dir,name,source,watched=false){ const blob=source instanceof Blob; // A compressed response's length is not the file's: then only "not empty". const expected=blob?source.size:source.headers.get('content-encoding')?0:Number(source.headers.get('content-length'))||0; // Its own name, so two computers writing the same file never meet. const work=await stageDir(WORK_FOLDER); const temp=await work.getFileHandle(Math.random().toString(36).slice(2,10)+'-'+name,{create:true}); try{ const out=await temp.createWritable(); try{if(blob){await out.write(source);await out.close();}else await source.body.pipeTo(out);} catch(e){ await out.abort().catch(()=>{}); // A download the network cut halfway waits for the next pass, as one // that never started (Sentry DTF-WEB-17). if(!blob&&e instanceof TypeError)e.unreachable=true; throw e; } const size=(await temp.getFile()).size; if(!size||expected&&size!==expected) throw new IncompleteFile('O arquivo '+name+' chegou incompleto ('+fileSize(size)+(expected?' de '+fileSize(expected):'')+') e foi descartado.'); await dir.removeEntry(name).catch(e=>{if(e.name!=='NotFoundError')throw e;}); try{await temp.move(dir,name);} catch(e){ if(watched)throw e; window.dtfObservability?.uiError?.('Pastas automáticas: o navegador não moveu '+name+' ('+e.name+') e copiou o arquivo.','kanban'); let out; try{out=await (await dir.getFileHandle(name,{create:true})).createWritable();await out.write(await temp.getFile());await out.close();} catch(error){await out?.abort().catch(()=>{});await dir.removeEntry(name).catch(()=>{});throw error;} } }finally{await work.removeEntry(temp.name).catch(()=>{});} } // The tries that never finished in WORK_FOLDER, and what the Kanban of // before 2026-11-17 left in the flow's folders: its .baixando files and // Chrome's .crswap copies (order #30). The leftovers once per page load, the // work folder on every pass. A file still held open waits for the next time. const LEFTOVER=/\.(baixando|crswap)$/; async function clearWork(){ const work=await stageDir(WORK_FOLDER); for await(const [name,entry] of work.entries()){ if(entry.kind!=='file')continue; const old=await entry.getFile().then(f=>Date.now()-f.lastModified>WORK_KEEP_MS,()=>true); if(old)await work.removeEntry(name).catch(()=>{}); } } async function sweepLeftovers(dir,depth){ for await(const [name,entry] of dir.entries()){ if(entry.kind==='directory'){if(depth>0)await sweepLeftovers(entry,depth-1);} else if(LEFTOVER.test(name))await dir.removeEntry(name).catch(()=>{}); } } // A file another program holds open (FlexiPRINT reading it, an editor): the // browser refuses to write, move or delete it. One that program changed while // the browser wrote or copied it (the hot folder's watcher, Sentry DTF-WEB-S) // is the same case. The pass goes on without it and the next one, 30 s later, // tries again. // A file that arrived incomplete waits for the next pass too, reported. const LOCKED=new Set(['NoModificationAllowedError','InvalidModificationError','NotReadableError','InvalidStateError']); function fileStep(locked,incomplete,unreachable){ return async(name,fn)=>{try{await fn();return true;} catch(e){ if(e.name==='IncompleteFile'){incomplete.push(e.message);return false;} if(e.unreachable){unreachable.push(name);return false;} if(!LOCKED.has(e.name))throw e;locked.push(name);return false;}}; } const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true}); // The flow's folders exist from the moment the main one is chosen, empty or not. const FLOW_FOLDERS=[...new Set([...Object.values(STAGE_FOLDERS),PRINTING_FOLDER,RECEIPTS_FOLDER,REVIEWS_FOLDER])]; const makeStageFolders=()=>Promise.all(FLOW_FOLDERS.map(stageDir)); // Whether the main folder answers at all. A folder on the network can be away // for a while: the server's share not up yet when the computer starts, the // network down (Sentry DTF-WEB-P). async function folderReachable(){ try{for await(const _ of FOLDER.handle.keys())break;return true;}catch{return false;} } // Remove a saved file from its folder; one already gone (someone took it) is fine. async function removeSaved(rec){ const dir=await stageDir(rec.folder); await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;}); } // To another of the flow's folders. False when the file is no longer where it was. async function moveSaved(rec,to){ const from=await stageDir(rec.folder), dest=await stageDir(to);let file; try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;} await dest.removeEntry(rec.name).catch(()=>{}); try{await file.move(dest);} catch{await writeWhole(dest,rec.name,await file.getFile());await from.removeEntry(rec.name);} return true; } // One file from storage, whole, into a folder. // A download that never reached storage or the server (the network dropped // for a moment, Sentry DTF-WEB-V) is marked unreachable: the file waits for // the next pass, like one held open, and is reported only if it keeps failing. async function fetchFile(url,options){ try{return await fetch(url,options);}catch(e){e.unreachable=true;throw e;} } async function fetchInto(dir,file,watched=false){ const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'}); if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').'); await writeWhole(dir,file.name,r,watched); } // The machines' hot folders (item 10): 3. Imprimindo///. // The server says what this computer writes now (claimed for it alone, two // parts at most per machine); a written part gone from its folder was taken // by FlexiPRINT, and is never written again; a withdrawn one, from a card that // left Imprimindo, is deleted if Flexi has not taken it. Returns how many // parts it wrote. async function syncHot(step){ const hot=await api('/queue/hot',{}); if(!hot.write.length&&!hot.watch.length&&!hot.withdraw.length)return 0; const root=await stageDir(hot.folder); const dirOf=async path=>{let dir=root;for(const part of path.split('/'))dir=await dir.getDirectoryHandle(part,{create:true});return dir;}; const missing=e=>e.name==='NotFoundError'; for(const p of hot.withdraw)await step(p.name,async()=>{ await (await dirOf(p.folder)).removeEntry(p.name).catch(e=>{if(!missing(e))throw e;}); await api('/queue/hot/'+p.id,{state:'gone'}); }); for(const p of hot.watch){ try{await (await dirOf(p.folder)).getFileHandle(p.name);} catch(e){if(!missing(e))throw e;await api('/queue/hot/'+p.id,{state:'consumed'});} } let written=0; for(const p of hot.write){ FOLDER.status='Gravando na hot folder '+p.folder+': '+p.name;paintFolder(); const ok=await step(p.name,async()=>{ try{await fetchInto(await dirOf(p.folder),p,true);} catch(e){await api('/queue/hot/'+p.id,{state:'released'}).catch(()=>{});throw e;} }); if(ok){await api('/queue/hot/'+p.id,{state:'written'});written++;} } return written; } // Bring the folders in line with the board: remove the files of orders that // were cancelled, deleted, sent back for correction or given another file, // and those kept their days in Finalizado; move each file to its stage's // folder; download what arrived in Arte recebida or Arte conferida. A file // someone took out is downloaded again only when its order moves on. After a // board load it asks only when something it follows changed; the folder's // own timer always asks, since another computer may have moved the order. async function syncFolder(force=false){ if(!folderActive()||FOLDER.busy||!board||!may('print')||$('app').hidden)return; // One tab per computer writes the folders: two tabs writing the same file // lock each other out. The other tabs skip the pass. if(navigator.locks&&!force?.held)return navigator.locks.request('dtf-folders',{ifAvailable:true}, lock=>lock?syncFolder({held:true,force:force===true}):undefined); if(force?.held)force=force.force; const stages=FOLDER.mode==='folder'; const follows=stages?['rec','tra','imp','rev','fin','cor']:['tra']; const sig=board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at) .map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')+':'+(o.reviews?.length||0)).join(','); if(!force&&sig===FOLDER.lastSig)return; FOLDER.busy=true; try{ if(stages)await makeStageFolders(); const held=stages?[...new Set([...FOLDER.saved.values()].filter(r=>!r.review).map(r=>r.order).filter(Boolean))].slice(-1000):[]; const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null}); // By file: an item longer than a part (10 m) is several parts (item 13), each its own file. const wanted=new Map(files.map(f=>[f.upload_id,f])); const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; let removed=0, moved=0, saved=0; const locked=[], incomplete=[], unreachable=[], step=fileStep(locked,incomplete,unreachable); if(stages){ await clearWork(); if(!FOLDER.swept){for(const name of FLOW_FOLDERS)await sweepLeftovers(await stageDir(name),2);FOLDER.swept=true;} } const record=async(uid,file,folder)=>{ FOLDER.saved.set(uid,{order:file.order,item:file.item,name:file.name,folder, ...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})}); FOLDER.last=new Date();await keepSaved();}; if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{ if(!rec.order||!rec.folder)return; const state=states[rec.order], target=STAGE_FOLDERS[state]; const now=wanted.get(uid); const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order); const kept=rec.folder===STAGE_FOLDERS.fin&&Date.now()-(rec.at||0)>KEEP_FINISHED_DAYS*86400000; if(!target||replaced||kept){await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();return;} if(rec.folder===target)return; if(await moveSaved(rec,target)){await record(uid,{...rec},target);moved++;return;} // Not where it was: downloaded again into its new folder while storage has it. if(now&&now.upload_id===uid){await fetchInto(await stageDir(target),now);await record(uid,now,target);moved++;} else{FOLDER.saved.delete(uid);await keepSaved();} }); const hot=stages?await syncHot(step):0; if(stages)for(const old of OLD_FOLDERS) if(![...FOLDER.saved.values()].some(r=>r.folder===old))await FOLDER.handle.removeEntry(old).catch(()=>{}); // New files, each into its stage's folder: the server sends those in Arte // recebida and Arte conferida, and the orders paid since the folders were // chosen in any stage, so what passed while this computer was off comes in // too. An order already printing when the folders were chosen is the room's. const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id)&&(stages?!!STAGE_FOLDERS[f.state]:f.state==='tra')); for(const [i,file] of pending.entries()){ FOLDER.status=(stages?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); say(FOLDER.status,false,60000); if(stages){ if(!await step(file.name,async()=>{ await fetchInto(await stageDir(STAGE_FOLDERS[file.state]),file); await record(file.upload_id,file,STAGE_FOLDERS[file.state]); }))continue; }else{ // Firefox writes it as .part and renames it when whole. const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click(); await new Promise(r=>setTimeout(r,900)); FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name}); FOLDER.last=new Date();await keepSaved(); } saved++; } // Each pickup receipt saved once, by the computer that takes it, so the // counter's queue never prints one twice; one this computer could not // save goes back for another to take. Written whole, then named .pdf. let printed=0; for(const r of receipts){ // Another computer took it first: expected, not reported (Sentry DTF-WEB-1N). try{await api('/orders/'+r.order+'/receipt/claim',{},{expected:[409]});}catch(e){if(e.status===409)continue;throw e;} await step(r.name,async()=>{try{ const res=await fetchFile('/api/operator/orders/'+r.order+'/receipt'); if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').'); await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res,true);printed++; }catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;}}); } // The review photos and videos, once each, into Revisões/. They are never // removed from there: the folder is the room's evidence of the check. let reviewSaved=0; if(stages)for(const review of reviews){ const key='review:'+review.upload_id; if(FOLDER.saved.has(key))continue; FOLDER.status='Salvando revisão: '+review.name;paintFolder(); if(!await step(review.name,async()=>{ const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view'); const res=await fetchFile(view.url,{referrerPolicy:'no-referrer'}); if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').'); await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res); }))continue; FOLDER.saved.set(key,{order:review.order,name:review.name,review:true}); FOLDER.last=new Date();await keepSaved();reviewSaved++; } FOLDER.lastSig=sig;FOLDER.error='';FOLDER.awaySince=0;FOLDER.awayReported=false; FOLDER.status=''; if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.'); if(hot)say('Gravados '+hot+' arquivo(s) na hot folder da máquina.'); if(printed)say(printed+' recibo(s) de retirada salvos em '+RECEIPTS_FOLDER+'.'); if(reviewSaved)say(reviewSaved+' foto(s)/vídeo(s) de revisão salvos em '+REVIEWS_FOLDER+'.'); if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.'); if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.'); // What another program held open waits for the next pass; the rest is done. // Expected while the FlexiPRINT reads a file: a warning the first time, and // an error (which reaches Sentry) only when the same file is still held // after LOCKED_REPORT_PASSES passes (Sentry DTF-WEB-M). // Not downloaded for the network: a warning, and an error (so in Sentry) // only when the same file still fails after LOCKED_REPORT_PASSES passes. for(const name of [...FOLDER.unreachable.keys()])if(!unreachable.includes(name))FOLDER.unreachable.delete(name); for(const name of unreachable)FOLDER.unreachable.set(name,(FOLDER.unreachable.get(name)||0)+1); if(unreachable.length){ FOLDER.lastSig=null; const stuck=unreachable.filter(name=>FOLDER.unreachable.get(name)===LOCKED_REPORT_PASSES); FOLDER.error='Não foi possível baixar '+unreachable[0]+(unreachable.length>1?' e mais '+(unreachable.length-1):'')+ ' agora (a rede oscilou). Os outros foram gravados; o Kanban tenta de novo em 30 s.'; if(stuck.length)say('Pastas automáticas: '+stuck.join(', ')+' não baixa há '+Math.round(LOCKED_REPORT_PASSES*30/60)+ ' minutos. Confira a internet deste computador.',true); else if(unreachable.some(name=>FOLDER.unreachable.get(name)===1))say('Pastas automáticas: '+FOLDER.error); } for(const name of [...FOLDER.locked.keys()])if(!locked.includes(name))FOLDER.locked.delete(name); for(const name of locked)FOLDER.locked.set(name,(FOLDER.locked.get(name)||0)+1); if(locked.length){ FOLDER.lastSig=null; FOLDER.error='O arquivo '+locked[0]+(locked.length>1?' e mais '+(locked.length-1):'')+ ' está aberto ou foi mexido por outro programa (o FlexiPRINT, por exemplo). Os outros foram gravados; o Kanban tenta este de novo em 30 s.'; const stuck=locked.filter(name=>FOLDER.locked.get(name)===LOCKED_REPORT_PASSES); if(stuck.length)say('Pastas automáticas: o arquivo '+stuck.join(', ')+' segue aberto em outro programa há '+ Math.round(LOCKED_REPORT_PASSES*30/60)+' minutos. Feche-o no programa que o usa.',true); else if(locked.some(name=>FOLDER.locked.get(name)===1))say('Pastas automáticas: '+FOLDER.error); } // Empty or short: an error every time, since a file must arrive whole. if(incomplete.length){ FOLDER.lastSig=null; FOLDER.error=incomplete.join(' ')+' O Kanban tenta de novo em 30 s.'; say('Pastas automáticas: '+FOLDER.error,true); } }catch(e){ // The session ended (8 h) or the server is restarting: load() already shows // the sign-in, and the folders resume after it (Sentry DTF-WEB-N). // No network: load() says so, and reports it if it lasts (Sentry DTF-WEB-Q). if(e.status===401||e.status===503||e.offline){FOLDER.status='';return;} // The main folder away: a warning while it may come back by itself, an // error (which reaches Sentry) after FOLDER_AWAY_REPORT_MS. const name=FOLDER.handle?.name; if(e.name==='NotFoundError'&&stages&&!await folderReachable()){ const first=!FOLDER.awaySince;FOLDER.awaySince||=Date.now(); FOLDER.status='';FOLDER.lastSig=null; FOLDER.error='A pasta “'+name+'” não responde: a rede ou o servidor caiu, ou ela foi apagada. O Kanban tenta de novo a cada 30 s; se ela mudou de lugar, escolha a pasta de novo.'; if(!FOLDER.awayReported&&Date.now()-FOLDER.awaySince>=FOLDER_AWAY_REPORT_MS){ FOLDER.awayReported=true; say('Pastas automáticas: a pasta “'+name+'” não responde há '+Math.round(FOLDER_AWAY_REPORT_MS/60000)+ ' minutos. Confira a rede e o servidor, ou escolha a pasta de novo em Integrações.',true); }else if(first)say('Pastas automáticas: '+FOLDER.error); return; } FOLDER.awaySince=0;FOLDER.awayReported=false; if(e.name==='NotAllowedError')FOLDER.granted=false; else if(e.name==='NotFoundError')FOLDER.error='Um arquivo ou pasta dentro de “'+name+'” sumiu durante a passagem (alguém tirou ou renomeou?). O Kanban tenta de novo sozinho.'; else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.'; FOLDER.status='';say('Pastas automáticas: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true); }finally{FOLDER.busy=false;paintFolder();} } setInterval(()=>syncFolder(true),30000); async function downloadQueue(){ const {files}=await api('/queue/finals'); if(!files.length){say('Nenhum arquivo final aprovado na fila.');return;} say('Baixando '+files.length+(files.length>1?' arquivos':' arquivo')+' da fila… Se o navegador perguntar, permita vários downloads.',false,8000); // One at a time: browsers drop clicks that come too close together. for(const file of files){ const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click(); await new Promise(r=>setTimeout(r,700)); } } // What the manifest says about contraction: the class to print with, what the // Site measured, the customer's choice on a mixed sheet and who changed it. function contractionRecord(item,chosen){ if(!item.stroke_class&&!chosen)return null; return {class:chosen?.class||measuredClass(item),measured_class:item.stroke_class||null,measured_px:item.stroke_px||null, customer_choice:item.stroke_choice||null,chosen_by:chosen?.by||null}; } function manifest(production,contraction=null){ if(contraction)production={...production,contraction}; const url=URL.createObjectURL(new Blob([JSON.stringify(production,null,2)],{type:'application/json'})); const link=node('a');link.href=url;link.download='dtf-layout-'+production.sources[0].upload_id.slice(0,8)+'.json'; link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); } // ---- Artwork pictures ------------------------------------------------------- // The picture of one upload, or null when the browser could not make one (a // CDR, a PSD, an order from before pictures existed). function artPicture(uid,alt=''){ if(!uid||!THUMBS.has(String(uid)))return null; const img=node('img');img.src='/api/operator/uploads/'+uid+'/thumbnail';img.alt=alt;img.loading='lazy';img.decoding='async'; // Only a picture still on screen gives up: one dropped by a re-render mid-load is not missing. img.onerror=()=>{if(!img.isConnected)return;THUMBS.delete(String(uid));img.remove();}; return img; } // A small box with the first picture of these items; without one, the layout // drawing, as before pictures existed. function artBox(items,className){ const box=node('div',undefined,'art '+className); const uid=items.flatMap(i=>i.uploads||[]).find(u=>THUMBS.has(String(u))); const pic=artPicture(uid); if(pic){box.append(pic);return box;} const item=items.find(i=>i.production?.placements); if(item){box.classList.add('layout');box.append(layoutPreview(item.production));} else{box.classList.add('none');box.append(node('span','sem prévia','noart'));} return box; } // An item's artwork (each file's picture) and its layout on the film, as two views. function itemPreview(item){ const wrap=node('div',undefined,'preview'); const pics=(item.uploads||[]).map((uid,i)=>artPicture(uid,'Arte '+(i+1))).filter(Boolean); const layout=item.production?.placements?layoutPreview(item.production):null; if(!pics.length){if(layout)wrap.append(layout);return wrap;} wrap.classList.add('with-art'); const art=node('div',undefined,'view art');art.append(...pics); if(!layout){wrap.append(art);return wrap;} const film=node('div',undefined,'view layout');film.append(layout);film.hidden=true; const tabs=node('div',undefined,'ptabs'); const pick=(show)=>{art.hidden=show!=='art';film.hidden=show!=='film'; for(const b of tabs.children)b.setAttribute('aria-pressed',String(b.dataset.view===show));}; for(const [view,label] of [['art','Arte'],['film','Montagem']]){ const b=node('button',label);b.type='button';b.dataset.view=view;b.setAttribute('aria-pressed',String(view==='art')); b.onclick=e=>{e.stopPropagation();pick(view);};tabs.append(b);} wrap.append(tabs,art,film);return wrap; } // ---- Loading and tabs ------------------------------------------------------ // What the last load saw, so the next one can tell what is new. let seenOrders=null, seenPending=null, unseen=0; // A network that drops for a moment (the computer waking up, the Wi-Fi) is // not a bug: the next refresh tries again. Red, and so in Sentry, only when // the server stays out of reach for OFFLINE_REPORT_MS (Sentry DTF-WEB-Q). const OFFLINE_REPORT_MS=3*60000; let offlineSince=0, offlineReported=false; async function load(quiet=false){ try{ const [loaded,me]=await Promise.all([api('/board'),api('/me')]); board=absorb(loaded);ME=me;offlineSince=0;offlineReported=false; window.dtfEnvironment=me.sentry_environment||me.environment; window.dtfRelease=me.sentry_release||undefined; window.dtfObservability?.start?.(me.sentry_dsn_web,'kanban'); applyRole();paintMyMachine(); noticeNew(quiet); const known=new Set(board.orders.map(o=>o.id)); board.orders.push(...olderFinished.filter(o=>!known.has(o.id))); if(finishedMore===null)finishedMore=board.finished_total>board.finished_shown; $('login').hidden=true;$('app').hidden=false; $('sync-at').textContent='Atualizado às '+new Date().toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}); if(!quiet&&tinyNotice)say(tinyNotice.replace(/^ · /,''),false,6000); render(); askMachine(); syncFolder(); if(typeof labelAfterLoad==='function')labelAfterLoad(); }catch(e){ if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;} // Not being signed in yet is the normal start, not an error. if(e.status===401){say('');return;} if(e.offline){ offlineSince||=Date.now(); if(!offlineReported&&Date.now()-offlineSince>=OFFLINE_REPORT_MS){ offlineReported=true; say('Sem conexão com o servidor há '+Math.round(OFFLINE_REPORT_MS/60000)+' minutos. Confira a internet deste computador.',true); }else say('Sem conexão com o servidor. O Kanban tenta de novo sozinho.',false,8000); return; } say(e.message,true); } } // The page's name in the top bar; Produção also says what is open. // On the phone the bottom bar holds four tabs; these live in its Mais sheet. const MORE_TABS=['montar','site','integrations','users']; const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',site:'Site',integrations:'Integrações',users:'Usuários',montar:'Montar folha'}; function showTab(name){ tab=name;$('tab-quotes').classList.remove('reviewing'); for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name)); $('page-title').textContent=PAGE_TITLES[name];$('board-summary').hidden=name!=='board';$('filter-open').hidden=name!=='board'; $('more-nav').classList.toggle('on',MORE_TABS.includes(name)); for(const id of ['board','quotes','payments','stats','site','integrations','users','montar'])$('tab-'+id).hidden=name!==id; const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador}; if(board&&lists[name])lists[name]().catch(e=>say(e.message,true)); } function render(){ $('who').textContent=ME?(ME.name||ME.email):''; $('who-role').textContent=ME?rolesLabel(myRoles())+', '+ME.email:''; $('who-initials').textContent=ME?initialsOf(ME.name||ME.email):''; $('initials').textContent=ME?initialsOf(ME.name||ME.email):'·'; $('badge-quotes').textContent=board.pending_total?String(board.pending_total):''; $('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):''; tinyHeader();renderBoard();renderIntegrations(); $('badge-more').textContent=$('badge-integrations').textContent; // Lists live on their own pages of the API; refresh the one being looked at. const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador}; if(lists[tab])lists[tab]().catch(e=>say(e.message,true)); if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();} } // ---- Dialogs --------------------------------------------------------------- // One kind of dialog (the design's .modal): a title, a line on what it does, // the fields and a foot. Over the order, it lives in #drawer, beside the panel, // so it belongs to that order and closes with it. Escape closes the top one. const MODALS=[]; document.addEventListener('keydown',e=>{ if(e.key!=='Escape')return; // An open list inside a dialog closes first. const list=document.querySelector('.sellist:not([hidden])'); if(list){e.stopImmediatePropagation();list.closest('.sel').close();list.previousSibling.focus();return;} if(MODALS.length){e.stopImmediatePropagation();if(!MODALS.at(-1).locked)MODALS.at(-1).close();}},true); function iconButton(d,label,fn,className='btn sq ghost'){ const b=node('button',undefined,className);b.type='button';b.setAttribute('aria-label',label);b.title=label;b.append(svgIcon(d,'i m')); if(fn)b.onclick=e=>{e.stopPropagation();fn(e);};return b; } function modal(title,{text,body=[],foot=[],host=document.body,width,role='dialog',onclose,form,locked=false,lead=null}={}){ const scrim=node('div',undefined,'scrim hi'); const box=node(form?'form':'div',undefined,'modal dlg');box.setAttribute('role',role);box.setAttribute('aria-modal','true'); if(width)box.style.width=width+'px'; const h=node('h2',title);h.id='dlg'+MODALS.length+Date.now();box.setAttribute('aria-labelledby',h.id); const head=node('div',undefined,'dlghead'),words=node('div');words.append(h);if(text)words.append(node('p',text)); // A locked dialog (a question that must be answered) has no way out but its buttons. head.append(...(lead?[lead]:[]),words,...(locked?[]:[iconButton(IC.close,'Fechar',()=>entry.close(),'btn sq ghost right')])); box.append(head,...body); if(foot.length){const f=node('div',undefined,'dfoot');f.append(...foot);box.append(f);} const entry={box,host,locked,close(){const i=MODALS.indexOf(entry);if(i<0)return;MODALS.splice(i,1);scrim.remove();box.remove();onclose?.();}}; scrim.onclick=()=>{if(!locked)entry.close();}; MODALS.push(entry);host.append(scrim,box); (box.querySelector('[autofocus]')||box.querySelector('input:not([type=checkbox]):not([type=file]):not([hidden]),textarea,select'))?.focus(); return entry; } // A question with two answers, in place of the browser's confirm(). function ask(title,text,label,{tone='pri',host}={}){ return new Promise(resolve=>{ let answered=false; const back=node('button','Voltar','btn ghost right');back.type='button'; const ok=node('button',label,'btn '+tone);ok.type='button'; const m=modal(title,{text,foot:[back,ok],host,role:'alertdialog',width:500,onclose:()=>{if(!answered)resolve(false);}}); back.onclick=()=>m.close();ok.onclick=()=>{answered=true;m.close();resolve(true);};ok.focus(); }); } // A dialog that is a form: the fields, Cancelar and the button that saves. // onsave throws to keep it open (the message shows); returns to close it. function formDialog(title,{text,fields=[],label='Salvar',tone='pri',host,width,note,className,onsave,left=[],lead=null}){ const save=node('button',label,'btn '+tone); const cancel=node('button','Cancelar','btn ghost right');cancel.type='button'; const foot=[...left,...(note?[node('span',note,'lbl')]:[]),cancel,save]; const m=modal(title,{text,body:fields,foot,host,width,form:true,lead}); const form=m.box;if(className)form.classList.add(className); cancel.onclick=()=>m.close(); form.onsubmit=async e=>{e.preventDefault();save.disabled=true; // A plain Error without an API status is the form's own check ("O código // precisa ter de 3 a 30 letras"): guidance, not a failure, so it stays out // of Sentry (DTF-WEB-Z). The API's refusals (apiError already reports // them) and broken code (TypeError and the like) stay red. try{if(await onsave(form)!==false)m.close();} catch(err){say(err.message,!(err?.constructor===Error&&err.status===undefined));} finally{save.disabled=false;}}; return m; } // The old name, for the dialogs of Usuários and the rework. function dialog(title,fields,onsave){return formDialog(title,{fields,onsave:async()=>{await onsave();}});} // Front 11: Gestão edits the acceptable time and the person responsible for // each column. The cards read the same table on the next board refresh. const STAGE_LABELS={rec:'Arte recebida',tra:'Arte conferida',imp:'Imprimindo',rev:'Revisão',fin:'Finalizado sem retirada'}; function stageLimitsDialog(){ api('/stage-limits').then(({limits})=>{ const current=Object.fromEntries((limits||[]).map(limit=>[limit.state,limit])); const inputs={}; const table=node('table',undefined,'dtable stageLimits'); const thead=node('thead'),headRow=node('tr'); for(const title of ['Etapa','Aceitável','Responde pela etapa'])headRow.append(node('th',title)); thead.append(headRow); const tbody=node('tbody'); for(const state of ['rec','tra','imp','rev','fin']){ const limit=current[state]||{hours:2,responsible:''}; const tr=node('tr'); const stage=node('td'); const name=node('span',undefined,'limitStage'); name.append(svgIcon(GLYPH[state],'i m'),node('b',STAGE_LABELS[state])); stage.append(name); const hoursCell=node('td'); const hoursBox=node('span',undefined,'inp limitHours'); const hours=node('input');hours.type='number';hours.min='0.1';hours.step='0.5';hours.value=limit.hours; hours.className='limitInp';hours.setAttribute('aria-label','Horas aceitáveis em '+STAGE_LABELS[state]); hoursBox.append(hours,node('span','h','pre')); hoursCell.append(hoursBox); if(state==='fin')hoursCell.append(node('span','3 dias','limitHint')); const whoCell=node('td'); const whoBox=node('span',undefined,'inp limitWho'); const who=node('input');who.value=limit.responsible||'';who.maxLength=80; who.className='limitInp';who.setAttribute('aria-label','Quem responde por '+STAGE_LABELS[state]); whoBox.append(who); whoCell.append(whoBox); inputs[state]={hours,who}; tr.append(stage,hoursCell,whoCell);tbody.append(tr); } table.append(thead,tbody); formDialog('Tempo aceitável de cada etapa',{host:dialogHost(),width:680,className:'limitsDialog', text:'Passou disso, o horário do card fica vermelho.',fields:[table],label:'Salvar tempos', onsave:async()=>{ const limits=Object.entries(inputs).map(([state,{hours,who}])=>({ state,hours:Number(hours.value),responsible:who.value.trim()})); await api('/stage-limits',{limits}); say('Tempos aceitáveis atualizados.');await load(); }}); }).catch(error=>say(error.message,true)); } function field(label,input,hint){ const l=node('label',undefined,'fld');l.append(label,input);if(hint)l.append(hint instanceof Node?hint:node('small',hint));return l; } // A checkbox drawn as the design's box. function checkbox(label,input){ input.type='checkbox';input.classList.add('vh'); const l=node('label',undefined,'ckb'),box=node('span',undefined,'box');box.setAttribute('aria-hidden','true'); const ns='http://www.w3.org/2000/svg',svg=document.createElementNS(ns,'svg'),p=document.createElementNS(ns,'path'); svg.setAttribute('viewBox','0 0 20 20');p.setAttribute('d','M5 10.5l3.25 3.25L15 7');svg.append(p);box.append(svg); l.append(input,box,label);return l; } // A file field as a place to drop the file, or to pick it. function dropField(input,{title='Arraste o arquivo para cá',hint=''}={}){ input.type='file';input.classList.add('vh'); const l=node('label',undefined,'drop'),ico=node('span',undefined,'dropico');ico.append(svgIcon(IC.upload)); const pick=node('span');pick.append('ou ',node('u','escolha no computador')); const chosen=node('span','','dropfiles'); l.append(ico,node('b',title),pick,...(hint?[node('small',hint)]:[]),chosen,input); const show=()=>{chosen.textContent=[...input.files].map(f=>f.name).join(', ');l.classList.toggle('has',input.files.length>0);}; input.addEventListener('change',show); l.ondragover=e=>{e.preventDefault();l.classList.add('over');}; l.ondragleave=()=>l.classList.remove('over'); l.ondrop=e=>{e.preventDefault();l.classList.remove('over');if(!e.dataTransfer.files.length)return; input.files=input.multiple?e.dataTransfer.files:(()=>{const t=new DataTransfer();t.items.add(e.dataTransfer.files[0]);return t.files;})(); input.dispatchEvent(new Event('change',{bubbles:true}));}; return l; } // ---- Wiring -------------------------------------------------------------- for(const b of document.querySelectorAll('[data-tab]'))b.onclick=()=>showTab(b.dataset.tab); // ---- Search: orders (any stage) and unpaid quotes --------------------------- // On a phone the search is behind a button, and opens over the top bar. $('search-back').onclick=()=>{$('search').value='';closeSearch();document.querySelector('.top').classList.remove('searching');$('search-open').setAttribute('aria-expanded','false');}; $('search-open').onclick=()=>{const on=document.querySelector('.top').classList.toggle('searching'); $('search-open').setAttribute('aria-expanded',String(on));if(on)$('search').focus();}; let searchTimer=null, searchToken=0, searchHits=[], searchAt=-1; function closeSearch(){$('search-results').hidden=true;$('search').setAttribute('aria-expanded','false');searchAt=-1;} async function runSearch(text){ const token=++searchToken; const result=absorb(await api('/search?'+new URLSearchParams({q:text}))); if(token!==searchToken||$('search').value.trim()!==text)return; const box=$('search-results');searchHits=[];searchAt=-1; const parts=[]; for(const [title,rows,make] of [['Pedidos',result.orders,orderHit],['Cotações',result.quotes,quoteHit]]){ if(!rows.length)continue; parts.push(node('div',title+' · '+rows.length,'rgroup')); for(const row of rows){const hit=make(row);hit.el.id='hit-'+searchHits.length;searchHits.push(hit);parts.push(hit.el);} } if(!searchHits.length)parts.push(node('p','Nada encontrado para “'+text+'”.','rempty')); parts.push(node('div','↑ ↓ para escolher · Enter abre · Esc fecha · busca por e-mail, CPF/CNPJ, WhatsApp ou nº do pedido','rhelp')); box.replaceChildren(...parts);box.hidden=false;$('search').setAttribute('aria-expanded','true'); } function hitRow(items,title,sub,meta,state,tone,open){ const el=node('button',undefined,'rhit');el.type='button';el.setAttribute('role','option');el.setAttribute('aria-selected','false'); const text=node('span',undefined,'rtext');text.append(node('b',title),node('span',sub,'sub'),node('span',meta,'rmeta')); el.append(artBox(items,'qthumb rart'),text,badge(state,tone)); el.onmousedown=e=>e.preventDefault(); el.onclick=()=>{closeSearch();document.querySelector('.top').classList.remove('searching');open();}; return {el,open}; } function orderHit(order){ const s=order.snapshot; return hitRow(s.items,'#'+order.number+' · '+orderCode(order.id),buyer(s).title, s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(specialDelivery(s)||(s.destination?'Entrega':'Retirada'))+' · pago '+when(order.created_at), order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'bad':'',()=>{ // An older finished order is not on the board yet: it joins, like "Carregar mais". if(!board.orders.some(o=>o.id===order.id)){olderFinished.push(order);board.orders.push(order);} showTab('board');openPanel(order.id);}); } function quoteHit(q){ return hitRow(q.draft.items,q.approved?money(q.approved.total_cents):'Cotação '+q.id.slice(0,8),buyer(q.draft).title, q.draft.items.map(i=>SHORT[i.mode]).join(' + ')+' · '+metres(quoteMetres(q))+' · '+ago(q.created_at), q.approved?'Aguardando pagamento':'A revisar',q.approved?'':'warn',()=>{ // Opens Cotações filtered to this customer, with this quote selected. quoteKind=q.approved?'approved':'pending';quoteQuery=q.draft.customer.mail; quoteProduct=quoteLayout=quoteFlag='';quotePage=1;currentQuote=q;showTab('quotes');}); } $('search').oninput=e=>{ const text=e.target.value.trim();clearTimeout(searchTimer); if(text.length<2){searchToken++;closeSearch();return;} searchTimer=setTimeout(()=>runSearch(text).catch(err=>say(err.message,true)),250); }; $('search').onkeydown=e=>{ if(e.key==='Escape'){e.stopPropagation();closeSearch();return;} if($('search-results').hidden||!searchHits.length)return; if(e.key==='ArrowDown'||e.key==='ArrowUp'){ e.preventDefault();searchAt=(searchAt+(e.key==='ArrowDown'?1:-1)+searchHits.length)%searchHits.length; searchHits.forEach((h,i)=>h.el.setAttribute('aria-selected',String(i===searchAt))); $('search').setAttribute('aria-activedescendant',searchHits[searchAt].el.id);searchHits[searchAt].el.scrollIntoView({block:'nearest'}); } if(e.key==='Enter'){e.preventDefault();const hit=searchHits[Math.max(0,searchAt)];closeSearch();hit.open();} }; $('search').onblur=()=>setTimeout(()=>{closeSearch();if(!$('search').value.trim()&&!PHONE.matches)document.querySelector('.top').classList.remove('searching');},150); $('search').onfocus=()=>{if($('search').value.trim().length>=2&&searchHits.length){$('search-results').hidden=false;$('search').setAttribute('aria-expanded','true');}}; // "/" jumps to the search, as the field shows, unless typing somewhere else. document.addEventListener('keydown',e=>{ if(e.key!=='/'||e.ctrlKey||e.metaKey||e.altKey)return; const t=e.target;if(t.closest&&t.closest('input,textarea,select,[contenteditable="true"]'))return; if($('app').hidden)return;e.preventDefault();$('search').focus(); }); $('login').onsubmit=async e=>{e.preventDefault();try{await api('/login',{email:$('email').value,password:$('password').value});await load();}catch(error){say(error.message,true);}finally{$('password').value='';}}; $('logout').onclick=async()=>{await api('/logout',{});for(const key of Object.keys(localStorage))if(key.startsWith('dtf-'))localStorage.removeItem(key);location.reload();}; $('refresh').onclick=()=>load(); // ---- Refreshing by itself -------------------------------------------------- // New orders and quotes to review since the last load: a notice, and the // count in the tab's title until the operator looks at the tab. function noticeNew(quiet){ const orders=new Set(board.orders.map(o=>o.id)); const fresh=seenOrders?board.orders.filter(o=>!seenOrders.has(o.id)&&o.state==='rec'&&!o.cancelled_at):[]; const reviews=seenPending===null?0:Math.max(0,board.pending_total-seenPending); seenOrders=orders;seenPending=board.pending_total; if(!fresh.length&&!reviews)return; const parts=[]; if(fresh.length)parts.push(fresh.length===1?'Novo pedido #'+fresh[0].number:fresh.length+' pedidos novos'); if(reviews)parts.push(reviews===1?'1 cotação nova para revisar':reviews+' cotações novas para revisar'); say(parts.join(' · '),false,10000); if(document.hidden||quiet){unseen+=fresh.length+reviews;document.title='('+unseen+') Kanban DTF';} } document.addEventListener('visibilitychange',()=>{if(!document.hidden){unseen=0;document.title='Kanban DTF';}}); addEventListener('focus',()=>{unseen=0;document.title='Kanban DTF';}); // Every N seconds, chosen beside "Atualizar" and remembered by this browser. // Never under the operator's hands: not while typing, dragging or with an // order open. With the Kanban's tab hidden it still looks, at most once a // minute, so the tab's title can say a new order arrived. let autoTimer=null, lastAuto=0; function busy(){ const a=document.activeElement; const typing=!!(a&&a.matches&&a.matches('input,textarea,select')&&a.id!=='refresh-every'); // An order being registered, half filled in and on screen, keeps its choices. const registering=!$('tab-quotes').hidden&&[...document.querySelectorAll('.register')].some(f=> f.querySelector('input:checked')||f.querySelector('input[type=text]').value); return $('app').hidden||!!dragging||!$('drawer').hidden||typing||registering; } function autoRefresh(){ if(busy())return; if(document.hidden&&Date.now()-lastAuto<60000)return; lastAuto=Date.now(); load(true).catch(()=>{}); } function scheduleAuto(){ clearInterval(autoTimer); const secs=Number($('refresh-every').value); if(secs)autoTimer=setInterval(autoRefresh,secs*1000); } (()=>{ let saved='30'; try{saved=localStorage.getItem('dtf-refresh-every')??'30';}catch(_){} $('refresh-every').value=[...$('refresh-every').options].some(o=>o.value===saved)?saved:'30'; $('refresh-every').onchange=()=>{ try{localStorage.setItem('dtf-refresh-every',$('refresh-every').value);}catch(_){} scheduleAuto();paintSync(); }; scheduleAuto();paintSync(); })(); function paintSync(){ const every=$('refresh-every'), on=every.value!=='0'; $('sync').classList.toggle('off',!on); $('sync').title=on?'Atualiza sozinho '+every.selectedOptions[0].textContent.toLowerCase()+'. Clique para mudar.':'Não atualiza sozinho. Clique para mudar.'; $('sync-every').replaceChildren(...[...every.options].map(o=>{ const b=node('button',undefined,'menuitem');b.type='button';b.setAttribute('role','menuitemradio'); b.setAttribute('aria-checked',String(o.value===every.value));b.append(node('span',o.textContent)); if(o.value===every.value)b.append(svgIcon(IC.check,'i m')); b.onclick=()=>{$('sync-menu').hidden=true;every.value=o.value;every.dispatchEvent(new Event('change'));}; return b;})); } $('sync').onclick=e=>{e.stopPropagation();const m=$('sync-menu');m.hidden=!m.hidden;$('sync').setAttribute('aria-expanded',String(!m.hidden)); if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;$('sync').setAttribute('aria-expanded','false');},{once:true});}; $('refresh').addEventListener('click',()=>{$('sync-menu').hidden=true;}); // The tabs live in later files: wait for all scripts before loading. addEventListener('DOMContentLoaded',()=>restoreFolder().finally(()=>load()));