From ee772a43ff6cb5af41a0e56d55ead65db6916d35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 16 Nov 2026 09:46:36 -0300 Subject: [PATCH] refactor: the production board and the order panel in files of their own Plan 007e (Critical Corrections 7, last step; layout Phase D step 1): web/kanban-board.js holds the board and the phone screens, and web/kanban-order.js the order panel, its dialogs, the final files and Abrir e conferir, moved verbatim from kanban.js (now 952 lines). The browser test also walks the phone board. Built by Prensa. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/browser_test.mjs | 13 + web/kanban-board.js | 607 ++++++++++++++ web/kanban-order.js | 1116 ++++++++++++++++++++++++++ web/kanban.html | 2 +- web/kanban.js | 1708 ---------------------------------------- 5 files changed, 1737 insertions(+), 1709 deletions(-) create mode 100644 web/kanban-board.js create mode 100644 web/kanban-order.js diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 8d4c99b..8944c94 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -369,6 +369,19 @@ try{ await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab'); await kanban.click('[data-tab="integrations"]'); await waitFor(()=>kanban.eval(`document.querySelector('#integrations').children.length>0`),'Integrações tab'); + // The phone board lives in its own file now: open its Mais and filters. + await kanban.call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true}); + await waitFor(()=>kanban.eval('PHONE.matches'),'phone board'); + await kanban.click('#more-nav'); + await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone menu'); + await kanban.eval('document.querySelector(".mscrim").click()'); + await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone menu closed'); + await kanban.click('#filter-open'); + await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone filters'); + await kanban.eval('document.querySelector(".mscrim").click()'); + await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone filters closed'); + await kanban.call('Emulation.setDeviceMetricsOverride',{width:1440,height:1000,deviceScaleFactor:1,mobile:false}); + await waitFor(()=>kanban.eval('!PHONE.matches'),'desktop board again'); // A guest sees the order paid in this browser; creating an account keeps it. const portal=await page(siteOrigin+'/conta/pedidos?order='+oid); await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking'); diff --git a/web/kanban-board.js b/web/kanban-board.js new file mode 100644 index 0000000..7a8ccad --- /dev/null +++ b/web/kanban-board.js @@ -0,0 +1,607 @@ +/* Kanban DTF: the production board, its filters and lanes, and the phone + board (fronts 5/11 and the design canvas' phone screens). Loaded after + kanban.js, which defines $, api, node, button, svgIcon, IC, badge, money, + when, ago, metres, plural, say, may, mayMove, mayReorder, mayAct, myMachine, + isMine, board, boardFilter, tab, load, render, download, downloadQueue, + field, formDialog, stageLimitsDialog, absorb, olderFinished, buyer, artBox, + lowestGrade, cm, SHORT and ME. */ +// ---- Production board ---------------------------------------------------- + +function printState(order){ + if(order.state==='imp'||order.state==='rev')return {text:'Final aprovado',tone:'ok'}; + if(order.state==='fin')return {text:'Concluído',tone:'ok'}; + if(order.state==='cor')return {text:'Aguardando o cliente',tone:''}; + if(finalDone(order))return {text:'Final aprovado',tone:'ok'}; + if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'}; + const rows=order.print_files||[], items=order.snapshot.items.length; + const ready=rows.filter(r=>r.status==='ready').length; + if(rows.some(r=>r.status==='failed'||r.timed_out))return {text:'Falhou ao gerar',tone:'warn'}; + if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''}; + if(ready===items)return {text:'Falta aprovar o final',tone:'warn'}; + if(rows.some(r=>r.status==='manual'||r.status==='failed')) + return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'}; + return {text:'Sem arquivo gerado',tone:'warn'}; +} +const stalled=order=>!!order.late; +// "Aguardando contato": a word with the customer is needed before printing. +// A mark on the card, not a stage; a finished order no longer needs it. +const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin'; +const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since); +// The print proof (app/proof.py): asked for at checkout, or an order above 10 m. +// The room marks "Prova OK" once it is checked; without it, no Finalizado. +const PROOF_ABOVE_METRES=10; +const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.'; +const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES; +const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent; +// The proof card (app/proof.py): the order's own card waits outside the queue +// for its answer; an order from before the cards has none. +const waitingProof=order=>!!order.proof_card&&!order.proof_card.proof_result&&!order.proof_ok_at; +const proofRejected=order=>order.proof_card?.proof_result==='rejected'&&!order.proof_ok_at; +async function proofAnswer(order,result,reason=''){ + await api('/orders/'+order.id+'/proof-answer',{result,reason});await load(); + say(result==='ok'?'Prova OK: o pedido #'+order.proof_parent.number+' entra na fila.':'Prova reprovada: o pedido #'+order.proof_parent.number+' voltou para Arte recebida.'); +} +function proofReject(order){ + const reason=node('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=3; + formDialog('Prova reprovada',{host:$('drawer'),label:'Reprovar a prova',tone:'red', + text:'O pedido #'+order.proof_parent.number+' volta para Arte recebida com o motivo, e este card de prova encerra.', + fields:[field('Motivo',reason)],onsave:async()=>{await proofAnswer(order,'rejected',reason.value);}}); +} +const TREATED_NOTE='O arquivo final foi preparado pela equipe, não é a arte que o cliente mandou.'; +// Mirrored by the customer (UV only, web/site-pdf.js): the room checks it before printing. +const mirroredItem=item=>!!item.production?.sources?.some(source=>source.mirrored); +const MIRROR_NOTE='O cliente espelhou a arte: confira antes de imprimir'; +// Residue dots under 2 mm the customer accepted printing (Dropstar, 2026-10-29). +const residueNote=item=>{const many=item.residue_accepted>1; + return item.residue_accepted+(many?' pontos menores':' ponto menor')+' que 2 mm, que '+(many?'podem':'pode')+' se perder no recorte';}; +const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imprimir com '+residueNote(item)); +// Two places per machine in Imprimindo (app/machines.py): the first to come +// in is printing, the next is being ripped meanwhile. +const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'], + ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']}; +// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30): +// "parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last from +// the hot folder while the one before it prints. +function partsStep(order){ + const hot=order.hot;if(!hot||hot.parts<2)return null; + const n=hot.parts, t=hot.taken; + if(!t)return ['Parte 1/'+n+' na hot folder','wait']; + if(t===1)return ['Parte 1/'+n+' ripando','rip']; + return ['Parte '+(t-1)+'/'+n+' imprimindo · '+t+'/'+n+' ripando','live']; +} +async function proofOk(order){ + await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load(); +} +// Where an order came from (Dropstar's rule D-21): every card says it. +const ORIGINS={site:'Site',dropflow:'Dropflow',atendimento:'Atendimento'}; +const ORIGIN_NOTE='Origem do pedido'; +const originTag=order=>{const t=node('span',ORIGINS[order.origin]||order.origin,'origin');t.title=ORIGIN_NOTE;return t;}; +// The board's filters: one choice per kind, and the kinds combine (Têxtil on +// máquina2, waiting for contact). An empty choice is "all". +const FILTER_TESTS={ + site:o=>o.origin==='site', + dropflow:o=>o.origin==='dropflow', + atendimento:o=>o.origin==='atendimento', + textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'||i.mode==='premium'), + uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'), + entrega:o=>!!o.snapshot.destination, + retirada:o=>!o.snapshot.destination, + parados:stalled, + atrasados:stalled, + contato:waitingContact, + prova:proofPending, + manual:o=>['rec','tra'].includes(o.state)&&!finalDone(o)&&(o.print_files||[]).some(r=> + (r.status==='manual'||r.status==='failed')&&!(o.corrections||[]).some(f=>f.item_index===r.item_index)), +}; +function matches(order,f=boardFilter){ + // A cancelled order shows only under "Cancelados", and only there. + if(!!order.cancelled_at!==(f.status==='cancelados'))return false; + return Object.values(f).every(key=>!key||key==='cancelados'|| + (key.startsWith('m:')?order.machine?.id===key.slice(2):FILTER_TESTS[key](order))); +} +// What each choice would show: orders in progress, or every cancelled one. +const filterCount=f=>board.orders.filter(o=>(f.status==='cancelados'||o.state!=='fin')&&matches(o,f)).length; +// The kinds of filter: [value, label in the panel, label on the tag]. The +// product is the segment beside the button, not in the panel. +function filterKinds(){ + const kinds=[ + {key:'delivery',label:'Envio',options:[['entrega','Entrega'],['retirada','Retirada']]}, + {key:'origin',label:'Origem',options:Object.entries(ORIGINS)}, + {key:'status',label:'Situação',options:[['atrasados','Fora do tempo aceitável','Atrasados'], + ['contato','Aguardando contato'],['prova','Prova a conferir'],['manual','Preparar à mão'],['cancelados','Cancelados']]}]; + // A machine, when there is more than one to tell apart. + const machines=(board.machines||[]).filter(m=>m.active||m.open_orders); + if(machines.length>1)kinds.unshift({key:'machine',label:'Máquina',options:machines.map(m=> + ['m:'+m.id,m.name+(m.limit_metres&&m.open_metres>m.limit_metres?' · acima do limite':''),m.name])}); + return kinds; +} +const PRODUCTS=[['','Todos'],['textil','Têxtil'],['uv','UV']]; +const xIcon=()=>svgIcon(IC.close,'i s'); +function openFilters(){ + const pop=$('filter-pop'); + const close=node('button',undefined,'btn sq ghost right');close.type='button';close.setAttribute('aria-label','Fechar filtros'); + close.append(svgIcon(IC.close,'i m'));close.onclick=closeFilters; + const head=node('div',undefined,'pophead');head.append(node('b','Filtros'),close); + const groups=filterKinds().map(kind=>{ + const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts'); + for(const [value,text] of kind.options){ + const b=node('button',text,'fopt');b.type='button';b.dataset.kind=kind.key;b.dataset.value=value; + b.append(node('span','','n')); + // A second click on the choice in use takes it off. + b.onclick=()=>{boardFilter[kind.key]=boardFilter[kind.key]===value?'':value;renderBoard();}; + opts.append(b); + } + group.append(node('span',kind.label),opts);return group; + }); + const clear=node('button','Limpar filtros','btn ghost');clear.type='button';clear.onclick=clearFilters; + const foot=node('div',undefined,'popfoot');foot.append(clear,node('span','','lbl right')); + pop.replaceChildren(head,...groups,foot);pop.hidden=false;$('filter-btn').setAttribute('aria-expanded','true'); + filterCounts();pop.querySelector('.fopt')?.focus(); +} +function closeFilters(){$('filter-pop').hidden=true;$('filter-btn').setAttribute('aria-expanded','false');} +function clearFilters(){for(const key in boardFilter)if(key!=='product')boardFilter[key]='';renderBoard();} +// Each choice says how many orders it would show with the others kept. +function filterCounts(){ + const pop=$('filter-pop'); + for(const b of pop.querySelectorAll('.fopt')){ + b.classList.toggle('on',boardFilter[b.dataset.kind]===b.dataset.value); + b.setAttribute('aria-pressed',String(boardFilter[b.dataset.kind]===b.dataset.value)); + b.querySelector('.n').textContent=String(filterCount({...boardFilter,[b.dataset.kind]:b.dataset.value})); + } + const shown=filterCount(boardFilter); + pop.querySelector('.popfoot .lbl').textContent=plural(shown,'pedido','pedidos'); +} +// The product segment, the filters in use as tags beside the button, and the +// button's count. +function renderFilters(){ + const kinds=filterKinds(); + // A choice that is gone (a machine deleted or switched off) is dropped. + for(const key in boardFilter){if(key==='product')continue;const kind=kinds.find(k=>k.key===key); + if(boardFilter[key]&&!kind?.options.some(([value])=>value===boardFilter[key]))boardFilter[key]='';} + $('product-seg').replaceChildren(...PRODUCTS.map(([value,text])=>{ + const b=node('button',text,boardFilter.product===value?'on':'');b.type='button'; + b.setAttribute('aria-pressed',String(boardFilter.product===value)); + b.append(node('span',String(filterCount({...boardFilter,product:value})),'n')); + b.onclick=()=>{boardFilter.product=value;renderBoard();};return b;})); + const used=kinds.filter(k=>boardFilter[k.key]); + const tags=used.map(kind=>{ + const [,text,tag]=kind.options.find(([value])=>value===boardFilter[kind.key]); + const b=node('button',tag||text,'ftag');b.type='button'; + b.setAttribute('aria-label','Tirar o filtro '+(tag||text)); + const x=node('span',undefined,'x');x.append(xIcon());b.append(x); + b.onclick=()=>{boardFilter[kind.key]='';renderBoard();};return b;}); + if(used.length>1){const all=node('button','Limpar','btn ghost');all.type='button';all.onclick=clearFilters;tags.push(all);} + $('filter-tags').replaceChildren(...tags); + $('filter-count').hidden=!used.length;$('filter-count').textContent=String(used.length); + const all=used.length+(boardFilter.product?1:0);$('filter-dot').hidden=!all;$('filter-dot').textContent=String(all); + $('filter-btn').classList.toggle('on',used.length>0); + if(!$('filter-pop').hidden)filterCounts(); +} +// Each column's mark (the design canvas): what happens in that stage. +const GLYPH={ + rec:'M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32Zm0,16V152h-28.7A15.86,15.86,0,0,0,168,156.69L148.69,176H107.31L88,156.69A15.86,15.86,0,0,0,76.69,152H48V48Zm0,160H48V168H76.69L96,187.31A15.86,15.86,0,0,0,107.31,192h41.38A15.86,15.86,0,0,0,160,187.31L179.31,168H208v40ZM90.34,125.66a8,8,0,0,1,11.32-11.32L120,132.69V72a8,8,0,0,1,16,0v60.69l18.34-18.35a8,8,0,0,1,11.32,11.32l-32,32a8,8,0,0,1-11.32,0Z', + tra:'M224,128a8,8,0,0,1-8,8H128a8,8,0,0,1,0-16h88A8,8,0,0,1,224,128ZM128,72h88a8,8,0,0,0,0-16H128a8,8,0,0,0,0,16Zm88,112H128a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16ZM82.34,42.34,56,68.69,45.66,58.34A8,8,0,0,0,34.34,69.66l16,16a8,8,0,0,0,11.32,0l32-32A8,8,0,0,0,82.34,42.34Zm0,64L56,132.69,45.66,122.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Zm0,64L56,196.69,45.66,186.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Z', + imp:'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', + cor:'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', + rev:'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', + fin:'M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z'}; +const orderMetres=o=>o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0); +// On a phone the board shows one stage at a time, picked from the chips above it. +let phoneCol='rec'; +// Atrasados (front 11): the cards past the stage limit, with the person +// responsible for that column, above the board. +function renderLatebar(){ + const bar=$('latebar'); + // The top strip is for production delays. A pickup waiting in Finalizado + // keeps its yellow/red card and is counted in Números; it does not push + // every historical finished order across the top of the board. + const late=board.orders.filter(o=>!o.cancelled_at&&!isTest(o)&&o.late&&o.state!=='fin') + .sort((a,b)=>(b.state_hours||0)-(a.state_hours||0)); + if(!late.length){bar.hidden=true;bar.replaceChildren();return;} + bar.hidden=false; + const head=node('b','Atrasados ('+late.length+')');bar.replaceChildren(head); + late.slice(0,10).forEach(o=>{ + const chip=node('button',undefined,'latechip'+(o.late==='bad'?' bad':'')); + chip.type='button';chip.append(node('i'),node('span','#'+o.number+' · '+board.states[o.state])); + chip.title=(o.state_hours??'?')+' h nesta etapa · limite '+(o.limit_hours??'?')+ + ' h · responsável: '+(o.limit_by||'—'); + chip.onclick=()=>openPanel(o.id);bar.append(chip); + }); + if(late.length>10)bar.append(node('span','+'+(late.length-10),'lbl')); + if(may('manage'))bar.append(button('Editar tempos',()=>stageLimitsDialog(),'btn ghost')); +} +function renderBoard(){ + renderLatebar(); + renderFilters(); + const active=board.orders.filter(o=>['rec','tra','imp'].includes(o.state)&&!o.cancelled_at); + const open=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length; + $('board-summary').textContent=plural(open,'pedido','pedidos')+', '+metres(active.reduce((s,o)=>s+orderMetres(o),0))+' em produção'; + const filtered=Object.entries(boardFilter).some(([key,value])=>value&&key!=='product')||!!boardFilter.product; + $('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{ + const column=node('section',undefined,'col');column.dataset.state=state;column.setAttribute('aria-label',title); + // Working columns are queues; Finalizado shows the most recently ready order first. + const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>state==='fin' + ? new Date(b.finished_at||b.updated_at)-new Date(a.finished_at||a.updated_at)||b.id.localeCompare(a.id) + : queueKey(a)-queueKey(b)||a.number-b.number); + const head=node('header',undefined,'colhead'); + head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':''))); + const text=node('span',undefined,'coltx');text.append(node('h2',title)); + if(state!=='fin')text.append(node('span',orders.length?metres(orders.reduce((s,o)=>s+orderMetres(o),0)):'vazio','colm')); + head.append(text); + // The print queue's files, all at once, to import into FlexiPRINT. + if(state==='tra'&&may('print')&&orders.length){ + const all=node('button',undefined,'colbtn tip-l');all.type='button';all.setAttribute('aria-label','Baixar os arquivos da fila'); + all.dataset.tip='Baixar os arquivos finais de todos os pedidos da fila, para o FlexiPRINT';all.append(svgIcon(IC.download,'i m')); + all.onclick=async()=>{all.disabled=true;try{await downloadQueue();}catch(e){say(e.message,true);}finally{all.disabled=false;}}; + head.append(all); + } + // Finished orders are a recent window, not the whole history: the count is the whole. + head.append(node('span',String(state==='fin'&&!filtered?Math.max(board.finished_total||0,orders.length):orders.length),'coln')); + column.append(head); + // The phone's line over the cards: this stage's metres and the session's machine. + const sum=node('div',undefined,'msum');const total=node('span'); + total.append(node('b',state==='fin'?plural(orders.length,'pedido','pedidos'):metres(orders.reduce((t,o)=>t+orderMetres(o),0))),state==='fin'?' recentes':' nesta etapa'); + sum.append(total); + if(myMachine()){const m=node('span',undefined,'right mcell');m.append(node('i',undefined,'mdot'),'Máquina ',node('b',myMachine().name));sum.append(m);} + column.append(sum); + if(state==='tra'&&may('print')&&orders.length){ + const dl=button('Baixar os arquivos da fila',downloadQueue,'btn mdl');dl.prepend(svgIcon(IC.download,'i m'));column.append(dl);} + if(state==='imp')column.append(...printingLanes(orders)); + else if(state==='fin')column.append(...orders.map(miniCard)); + else column.append(...orders.map((o,i)=>card(o,state==='tra'?queuePlace(o,orders):null))); + if(state==='fin'&&finishedMore&&!filtered){ + const left=Math.max(0,(board.finished_total||0)-orders.length); + const more=node('button',left>50?'Ver mais 50 anteriores':left?'Ver os '+left+' anteriores':'Ver anteriores','moreold');more.type='button'; + more.onclick=async()=>{more.disabled=true;try{await loadOlderFinished();}catch(e){say(e.message,true);more.disabled=false;}}; + column.append(more); + } + // Dragging only goes forward to the next stage. Going back or asking for a + // correction needs a reason, so those happen in the order panel. + column.ondragover=e=>{ + if(dragging?.state===state&&state!=='fin'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;} + if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target'); + if(state==='imp')markLane(column,laneAt(column,e.clientY));}; + column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');markLane(column,null);clearDrop();}}; + column.ondrop=async e=>{e.preventDefault();column.classList.remove('target'); + const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain')); + const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null); + if(!order)return; + try{ + if(order.state!==state)await (state==='imp'?pullTo(order,machine):move(order,state,'',machine)); + else if(state!=='fin')await reorder(order,column,e.clientY); + }catch(error){say(error.message,true);} + finally{clearDrop();}}; + return column; + })); + const cols=[...$('kan').children]; + if(!board.states[phoneCol])phoneCol='rec'; + $('col-tabs').replaceChildren(...cols.map(col=>{ + const st=col.dataset.state, on=st===phoneCol; + const b=node('button',undefined,'mtab'+(on?' on':''));b.type='button';b.setAttribute('role','tab');b.setAttribute('aria-selected',String(on)); + b.append(svgIcon(GLYPH[st],'sg'+(st==='cor'?' cor':'')),board.states[st],node('span',col.querySelector('.coln').textContent,'n')); + b.onclick=()=>{phoneCol=st;renderBoard();$('col-tabs').querySelector('.on')?.scrollIntoView({inline:'nearest',block:'nearest'});}; + return b;})); + for(const col of cols)col.classList.toggle('pick',col.dataset.state===phoneCol); +} +// Imprimindo, one lane per machine (app/machines.py): its name and places, +// the order printing, the one ripping, then its free place. Every active +// machine has its lane, so a card dragged from the queue can be dropped on +// the machine it goes to print on. +function printingLanes(orders){ + const cap=board.printing_cap||2, mine=myMachine()?.id; + const filtered=Object.values(boardFilter).some(Boolean); + const out=[]; + const list=(board.machines||[]).filter(m=>m.active||orders.some(o=>o.machine?.id===m.id)); + for(const m of list){ + const here=orders.filter(o=>o.machine?.id===m.id) + .sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1)); + // Filtered, a lane with nothing to show stays out; unfiltered, the places count every order. + if(filtered&&!here.length)continue; + const n=filtered?here.length:Math.max(m.states?.imp||0,here.length); + const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));lane.dataset.machine=m.id; + const load=n>cap?'acima do limite':n>=cap?'cheia':plural(cap-n,'vaga','vagas'); + lane.append(svgIcon(IC.printer,'i s'),node('b',m.name)); + // The machine's sheet opens here; an alert due shows a warning dot with its text. + const alerts=m.alerts||[]; + if(alerts.length){const mark=node('i',undefined,'lanealert');mark.title=alerts.map(a=>a.text).join(' · '); + mark.setAttribute('aria-hidden','true');lane.append(mark);} + lane.append(node('span',(m.id===mine?'sua máquina · ':'')+load)); + lane.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':''); + lane.tabIndex=0;lane.setAttribute('role','button');lane.setAttribute('aria-label','Ficha da '+m.name); + const openSheet=()=>openMachineSheet(m.id); + lane.onclick=openSheet; + lane.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();openSheet();}}; + out.push(lane,...here.map(o=>{const c=card(o);c.dataset.machine=m.id;return c;})); + if(!filtered&&n1?plural(cap-n,'vaga livre','vagas livres')+' na '+m.name:'Vaga livre na '+m.name);out.push(slot); + } + } + // An order whose machine is gone or off still shows. + const loose=orders.filter(o=>!list.some(m=>m.id===o.machine?.id)); + if(loose.length){const lane=node('div',undefined,'lanehead');lane.append(svgIcon(IC.printer,'i s'),node('b','Sem máquina'));out.push(lane,...loose.map(o=>card(o)));} + return out; +} +// The machine lane under the pointer in Imprimindo: the last lane head above it. +function laneAt(column,y){ + let found=null; + for(const el of column.querySelectorAll('[data-machine]')){ + if(el.getBoundingClientRect().top<=y)found=el.dataset.machine; + } + return found||column.querySelector('.lanehead[data-machine]')?.dataset.machine||null; +} +function markLane(column,id){ + for(const l of column.querySelectorAll('.lanehead,.freeslot,.card'))l.classList.toggle('droplane',!!id&&l.dataset.machine===id); +} +// A card's place in the print queue, among the orders of its product (a +// textile machine pulls the next textile order). +const uvOrder=o=>o.snapshot.items.some(i=>i.mode.startsWith('uv')); +// An order waiting for its proof is not in the queue yet (app/proof.py). +const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)&&!waitingProof(o)).indexOf(order)+1; +// An operator's test order: no payment, no Tiny. +const isTest=order=>order.payment?.provider==='teste'; +const shortAgo=value=>ago(value).replace(/^há /,''); +// What happens next with the order, said on its card, and in what tone: +// act (someone has to do it now), live (printing), rip (ripping), busy (the +// system is working) or wait (nothing to do here). +function nextStep(order,place){ + if(order.cancelled_at)return ['Cancelado','wait']; + if(order.state==='cor')return ['Esperando o cliente','wait']; + // The proof card waits for its answer; its order, outside the queue, for that. + if(order.proof_parent&&order.state==='rev')return ['Responder a prova','act']; + if(order.state==='tra'&&waitingProof(order))return ['Aguardando prova','wait']; + if(order.state==='rev')return ['Conferir a folha','act']; + if(order.state==='imp')return partsStep(order)||(order.printing?PRINTING[order.printing].slice(0,2):['Na máquina','wait']); + if(order.state==='tra'){ + // The operator whose machine prints this product pulls the first one. + const m=(board.machines||[]).find(x=>x.id===myMachine()?.id); + const fits=!m?.products?.length||order.snapshot.items.some(i=>m.products.includes(i.mode)); + if(place===1&&m&&fits&&mayMove('tra','imp'))return ['Puxar da fila','act']; + return [place?place+'º na fila':'Na fila','wait']; + } + const p=printState(order); + if(p.text==='Gerando arquivo…')return ['Gerando o arquivo','busy']; + if(p.text==='Falta aprovar o final')return ['Aprovar o final','act']; + if(p.text==='Correção recebida')return ['Conferir correção','act']; + if(p.text==='Final aprovado')return ['Pronto para a fila','act']; + return [p.text,'act']; +} +// Everything a card has to say beyond its stage, the most urgent first; the +// card shows the first and how many more, and all of them on hover. +function cardFlags(order){ + const s=order.snapshot, out=[]; + if(order.cancelled_at)return [['bad','Cancelado','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason]]; + const live=order.state!=='fin'; + // A stalled order says so in red where its time is, not as a mark. + const redo=(order.reworks||[]).filter(r=>r.authorized!==false); + if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]); + if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]); + if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]); + if(order.snapshot.treatment){ + const n=Number(order.snapshot.treatment.arts)||1; + out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'), + 'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']); + } + if(order.snapshot.redesign){ + const n=Number(order.snapshot.redesign.arts)||1; + out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'), + 'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 h']); + } + if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]); + if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]); + if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]); + if(live&&proofPending(order)&&!order.proof_card)out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']); + // The grade rule set in the Site tab flagged this order for the designer. + if(!order.proof_parent&&s.grade_flags?.aviso!=null) + out.push(['warn','Nota '+s.grade_flags.aviso+': conferir a arte', + 'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir']); + if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']); + const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0); + if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]); + if(order.treated)out.push(['','Tratada',TREATED_NOTE+' Aprovado por '+order.treated.by+'.']); + if(live&&needsProof(order)&&order.proof_ok_at)out.push(['','Prova OK','Prova conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at)]); + if(isTest(order))out.push(['','Teste','Pedido de teste: sem pagamento, não vai ao Tiny']); + return out; +} +function flagNode(flags){ + if(!flags.length)return null; + const [tone,text]=flags[0]; + const f=node('span',text,'flag tip-l'+(tone?' '+tone:''));f.dataset.tip=flags.map(x=>x[2]).join(' · '); + if(flags.length>1)f.append(node('span',' +'+(flags.length-1),'plus')); + return f; +} +const KIND={file:'Folha',avulsa:'Avulsa',uvfile:'Folha',uv:'Avulsa'}; +function productLine(items){ + const modes=[...new Set(items.map(i=>i.mode))]; + return SHORT[modes[0]]+(items.length>1?' ×'+items.length:'')+(modes.length>1?' +'+(modes.length-1):''); +} +// A card drags forward when this profile makes that move, or up and down +// when it sets the column's order; a card of another operator's machine does not. +function draggable(c,order){ + c.draggable=!order.cancelled_at&&!waitingProof(order)&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s))); + c.onclick=()=>openPanel(order.id); + c.onkeydown=e=>{if(e.target===c&&(e.key==='Enter'||e.key===' ')){e.preventDefault();openPanel(order.id);}}; + c.ondragstart=e=>{ + dragging=order; + e.dataTransfer.setData('text/plain',order.id); + const forward=board.transitions[order.state].filter(s=>s!=='cor'&&mayMove(order.state,s)); + for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state)); + const moves=forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou '):''; + const priority=mayReorder(order.state)?'arraste para cima ou para baixo para mudar a prioridade':''; + say(moves&&priority?moves+', ou '+priority:moves||priority,false,60000); + }; + c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');}; +} +function card(order,place){ + const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at; + const [step,tone]=nextStep(order,place); + const c=node('div',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':'')); + c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id; + const who=buyer(s); + c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step); + const top=node('span',undefined,'ctop'), info=node('span',undefined,'cinfo'); + const row=node('span',undefined,'crow'); + const late=!!order.late&&!order.cancelled_at; + const age=node('span',shortAgo(order.state_since||order.updated_at),'age'+(late?' late tip-l'+(order.late==='bad'?' late2':''):'')); + if(late)age.dataset.tip='Fora do tempo: '+(order.state_hours??'?')+' h nesta etapa · limite '+ + (order.limit_hours??'?')+' h · responsável: '+(order.limit_by||'—'); + row.append(node('span','#'+order.number,'num'),originTag(order),age); + const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title; + const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items))); + const special=specialDelivery(s); + if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);} + if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo')); + if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);} + meta.append(node('b',metres(orderMetres(order)),'mtr')); + info.append(row,name,meta); + const art=artBox(s.items,'thumb');top.append(art,info); + c.append(top); + if(order.state==='cor'&&order.correction_reason){const r=node('span',undefined,'creason');r.append(node('b','Motivo'),' '+order.correction_reason);c.append(r);} + const foot=node('span',undefined,'cfoot'), next=node('span',undefined,'next'+(tone==='wait'?' wait':'')); + if(tone==='live'){const f=node('i',undefined,'feed');f.append(node('i'),node('i'),node('i'));next.append(f);} + if(tone==='rip')next.append(node('i',undefined,'rip')); + if(tone==='busy'){const d=node('i',undefined,'dots');d.append(node('i'),node('i'),node('i'));next.append(d);} + next.append(node('span',step,'stx')); + foot.append(next); + const flag=flagNode(cardFlags(order));if(flag)foot.append(flag); + c.append(foot,cardOpenAction(order)); + draggable(c,order); + return c; +} +// Finalizado is the end of the line: what the customer still has to do, +// nothing else. A pickup waiting more than two days is said in warning. +const PICKUP_WARN_DAYS=2; +function miniCard(order){ + const c=node('div',undefined,'mini'+(order.id===openOrder?' open':''));c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id; + const who=buyer(order.snapshot); + const row=node('span',undefined,'crow');row.append(node('span','#'+order.number,'num'),node('span',metres(orderMetres(order)),'age')); + const name=node('span',who.title,'cname');name.title=who.mail||who.title; + let text,ic=IC.check,warn=false; + const days=Math.floor((Date.now()-new Date(order.updated_at))/86400000); + const special=specialDelivery(order.snapshot); + if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;} + else if(order.picked_up_at)text='Retirado'; + else if(special){text=special;ic=IC.box;} + else if(order.snapshot.destination){text='Entrega, '+order.snapshot.destination.city+'/'+order.snapshot.destination.state;ic=IC.truck;} + else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;} + else{text='Aguardando retirada';ic=IC.bag;} + const done=node('span',undefined,'done'+(warn?' warn':''));done.append(svgIcon(ic,'i s'),text); + c.append(row,name,done,cardOpenAction(order)); + c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+text); + draggable(c,order); + return c; +} +// The column's queue: payment time, unless an operator dragged the card to +// another place (queue_key, seconds like the payment time). +const queueKey=o=>o.queue_key!=null?Number(o.queue_key):new Date(o.created_at).getTime()/1000; +let dragging=null; +// Where a card dropped at this height lands: the card it goes before, if any. +function dropTarget(column,y){ + const cards=[...column.querySelectorAll('.card')].filter(c=>c.dataset.card!==dragging?.id); + return cards.find(c=>{const r=c.getBoundingClientRect();return yc.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)=> + new Date(a.finished_at||a.updated_at)-new Date(b.finished_at||b.updated_at)||a.id.localeCompare(b.id)); + const oldest=shown[0];const params=new URLSearchParams({limit:'50'}); + if(oldest){params.set('before_finished_at',oldest.finished_at||oldest.updated_at);params.set('before_id',oldest.id);} + const page=absorb(await api('/orders/finished?'+params)); + const known=new Set(board.orders.map(o=>o.id)); + const fresh=page.orders.filter(o=>!known.has(o.id)); + olderFinished.push(...fresh);board.orders.push(...fresh);finishedMore=page.has_more;renderBoard(); +} +async function move(order,state,reason='',machine=null){ + await api('/orders/'+order.id+'/move',{state,version:order.version,reason,...(machine?{machine_id:machine}:{})}); + await load(); +} + +// ---- Phone (the design canvas' phone screens) ------------------------------- + +// Under 700 px the Kanban is the phone mockup: sections at the bottom, menus +// and filters as sheets from the bottom, the order and the quote as pages. +const PHONE=matchMedia('(max-width:700px)'); +PHONE.addEventListener('change',()=>{if(board)render();}); +// A sheet from the bottom: the grab, then what it holds. Escape or the scrim closes. +function sheet(parts,{label='',role='dialog',onclose}={}){ + const scrim=node('div',undefined,'mscrim'); + const box=node('div',undefined,'msheet');box.setAttribute('role',role);if(label)box.setAttribute('aria-label',label); + box.append(node('span',undefined,'grab'),...parts); + const entry={box,host:document.body,close(){const i=MODALS.indexOf(entry);if(i<0)return;MODALS.splice(i,1);scrim.remove();box.remove();onclose?.();}}; + scrim.onclick=()=>entry.close(); + MODALS.push(entry);document.body.append(scrim,box);return entry; +} +// A row of a phone sheet: an icon, the words, and maybe something on the right. +function mrow(d,text,fn,className='mrow',end=null){ + const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem'); + b.append(svgIcon(d),node('span',text,'mtext'),...(end?[end]:[])); + b.onclick=async()=>{try{await fn();}catch(e){say(e.message,true);}};return b; +} +// "Mais": who is signed in, the sections that do not fit the bar, the machine, +// the theme, the password and Sair. +function phoneMenu(){ + let m=null; + const go=fn=>async()=>{m.close();await fn();}; + const who=node('div',undefined,'who sheetwho'),words=node('span'); + const ava=node('span',initialsOf(ME.name||ME.email),'ava');ava.append(node('i',undefined,'pres on')); + words.append(node('b',ME.name||ME.email),node('span',(ROLE_NAMES[ME.role]||ME.role)+(myMachine()?', na '+myMachine().name:''),'sub')); + who.append(ava,words); + const rows=[]; + if(TAB_NEEDS.integrations()){const n=$('badge-integrations').textContent; + rows.push(mrow(IC.link,'Integrações',go(()=>showTab('integrations')),'mrow',n?statePill(n,'warn'):null));} + if(TAB_NEEDS.users())rows.push(mrow(IC.user,'Usuários',go(()=>showTab('users')))); + if(ME.machine_question)rows.push(mrow(IC.printer,'Trocar de máquina',go(()=>askMachine(true)),'mrow',node('span',myMachine()?.name||'','lbl'))); + const light=kanbanTheme.get()==='light'; + rows.push(mrow(light?ICON_MOON:ICON_SUN,light?'Mudar para o modo escuro':'Mudar para o modo claro',go(()=>{kanbanTheme.toggle();paintThemeToggle();}))); + rows.push(mrow(IC.key,'Trocar a senha',go(accountForm))); + rows.push(mrow(IC.logout,'Sair',go(()=>$('logout').click()),'mrow bad')); + const body=node('div',undefined,'sbody');body.append(...rows); + m=sheet([who,body],{label:'Mais',role:'menu'}); +} +// The board's filters on the phone: every kind, the product too, and how many +// orders they show. +function phoneFilters(){ + const kinds=[{key:'product',label:'Produto',options:PRODUCTS.filter(([v])=>v)},...filterKinds()]; + const body=node('div',undefined,'sbody'); + const show=node('button','','btn pri');show.type='button'; + const paint=()=>{ + body.replaceChildren(...kinds.map(kind=>{ + const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts'); + for(const [value,text] of kind.options){ + const on=boardFilter[kind.key]===value; + const b=node('button',text,'fopt'+(on?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on)); + b.append(node('span',String(filterCount({...boardFilter,[kind.key]:value})),'n')); + b.onclick=()=>{boardFilter[kind.key]=on?'':value;renderBoard();paint();};opts.append(b); + } + group.append(node('span',kind.label),opts);return group;})); + show.textContent='Ver '+plural(filterCount(boardFilter),'pedido','pedidos'); + }; + const close=iconButton(IC.close,'Fechar',()=>m.close(),'mic right'); + const head=node('div',undefined,'shead');head.append(node('b','Filtros'),close); + const clear=node('button','Limpar','btn');clear.type='button';clear.onclick=()=>{for(const k in boardFilter)boardFilter[k]='';renderBoard();paint();}; + const foot=node('div',undefined,'sfoot');foot.append(clear,show); + const m=sheet([head,body,foot],{label:'Filtros'});show.onclick=()=>m.close(); + paint(); +} +$('more-nav').onclick=()=>phoneMenu(); +$('filter-open').onclick=()=>phoneFilters(); + diff --git a/web/kanban-order.js b/web/kanban-order.js new file mode 100644 index 0000000..d2e12b8 --- /dev/null +++ b/web/kanban-order.js @@ -0,0 +1,1116 @@ +/* Kanban DTF: the order panel, its dialogs, the final files and Abrir e + conferir (fronts 2/7). Loaded after kanban.js, which defines $, api, node, + button, svgIcon, IC, badge, money, when, ago, metres, plural, say, may, + mayMove, mayAct, myMachine, board, ME, MODALS, load, render, dialog, modal, + formDialog, field, checkbox, dropField, iconButton, gradePill, itemPreview, + productName, sheetSize, buyer, cnpj, docKind, copyButton, freightWeight, + whatsappLink, download, downloadButton, FOLDER, STAGE_FOLDERS, FLOW, kv, + orderCode, fileCode, stateName, manifest, contractionRecord and cm. */ +// ---- Order panel --------------------------------------------------------- + +// The panel's tab stays while the same order is open. +let panelTab='order'; +// A dialog sits over the order's panel when it is open, and over the page +// when it is not: opened from a card's face or the board, inside the closed +// drawer it would be invisible. +const dialogHost=()=>$('drawer').hidden?document.body:$('drawer'); +function openPanel(id){if(id!==openOrder)panelTab='order';openOrder=id;const order=board.orders.find(o=>o.id===id);$('drawer').hidden=false;renderPanel(order);renderBoard();} +function closePanel(){ + for(const m of [...MODALS])if(m.host===$('drawer'))m.close(); + openOrder=null;$('drawer').hidden=true;$('panel').replaceChildren();if(board)renderBoard(); +} +$('scrim').onclick=closePanel; +document.addEventListener('keydown',e=>{if(e.key==='Escape'&&openOrder)closePanel();}); + +function layoutPreview(production){ + const ns='http://www.w3.org/2000/svg', w=Number(production.film_width_cm), h=Math.max(1,Number(production.height_cm)); + const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img'); + svg.setAttribute('aria-label','Montagem: '+production.placements.length+' peças em '+w+' × '+h+' cm'); + const film=document.createElementNS(ns,'rect');film.setAttribute('width',w);film.setAttribute('height',h);film.setAttribute('fill','#0F1113');svg.append(film); + const colors=['#2BB6D9','#E0508F','#E9C23A','#6FD19C','#FF8B2B','#A78BFA']; + for(const p of production.placements){const r=document.createElementNS(ns,'rect'); + r.setAttribute('x',p.x_cm);r.setAttribute('y',p.y_cm);r.setAttribute('width',p.width_cm);r.setAttribute('height',p.length_cm); + r.setAttribute('fill',colors[p.source_index%colors.length]);r.setAttribute('fill-opacity','.55');svg.append(r);} + return svg; +} +function renderPanel(order){ + const token=++openToken, panel=$('panel'); + panel.dataset.order=order.id;$('drawer').dataset.order=order.id; + panel.setAttribute('aria-label','Pedido #'+order.number); + const s=order.snapshot, who=buyer(s); + // The head: who, where the order is, and what it is called. + const top=node('div',undefined,'dtop'); + const name=node('span',who.title,'dname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title; + const stage=node('span',undefined,'stage'+(order.cancelled_at?' bad':'')); + stage.append(svgIcon(order.cancelled_at?IC.ban:GLYPH[order.state]||GLYPH.rec,'sg'+(order.state==='cor'||order.cancelled_at?' cor':'')), + order.cancelled_at?'Cancelado':stateName(order.state)); + const tools=node('span',undefined,'dtools'); + const more=moreMenu(order);if(more)tools.append(more); + tools.append(iconButton(IC.close,'Fechar',closePanel)); + top.append(node('span','#'+order.number,'dnum'),name,stage,tools); + // What was paid and when, where it came from, and the codes: DTF-23 is the + // room's, in the file names, the footer and Tiny; the customer knows the other. + const sub=node('div',undefined,'dsub'); + const paid=node('span'); + // A proof card is no sale (app/proof.py): it says whose proof it is. + if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at)); + else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at): + paidOutside(order)?' pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at)); + const code=node('span',undefined,'chip'); + code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido')); + const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente'; + sub.append(paid,node('span','Entrou pelo '+(ORIGINS[order.origin]||order.origin)),code,theirs); + if(s.coupon && !order.proof_parent) + sub.append(badge('Cupom '+s.coupon.code,'','Desconto de '+money(s.coupon.discount_cents))); + if(s.grade_flags?.aviso!=null && !order.proof_parent) + sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn', + 'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir')); + if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny')); + if(s.items.some(i=>i.mode==='premium'))sub.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo')); + if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at))); + const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas'); + const at=FLOW.indexOf(order.state); + for(const [i,state] of FLOW.entries()){const li=node('li',board.states[state]); + if(at>=0&&i{panelTab=key;paintTabs();};tabs.append(b); + } + const paintTabs=()=>{for(const b of tabs.children){const on=b.dataset.ptab===panelTab;b.classList.toggle('on',on);b.setAttribute('aria-selected',String(on));} + for(const [key,view] of Object.entries(views))view.hidden=key!==panelTab;}; + paintTabs(); + body.append(tabs,...Object.values(views)); + // On the phone the order is one page; its files and history open as sheets. + let fileRows=null,historyRows=null; + const mbtns=node('div',undefined,'mbtns phone'); + const zap=whatsappLink(s.customer.zap); + if(zap){const a=node('a','WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i m'));mbtns.append(a);} + const sheetOf=(title,fill)=>()=>{const box=node('div',undefined,'sbody pad');fill(box); + const m=sheet([sheetHead(title,()=>m.close()),box],{label:title});}; + const files=node('button','Arquivos','btn');files.type='button';files.onclick=sheetOf('Arquivos',box=>fileRows?filesView(order,fileRows,box):box.append(node('p','Carregando…','lbl'))); + const hist=node('button','Histórico','btn');hist.type='button';hist.onclick=sheetOf('Histórico',box=>historyRows?historyView(order,historyRows,box):box.append(node('p','Carregando…','lbl'))); + mbtns.append(files,hist);body.append(mbtns); + // A re-render keeps where the body was scrolled. + const scrolled=panel.querySelector('.dbody')?.scrollTop||0; + panel.replaceChildren(mhead,head,body);body.scrollTop=scrolled; + + api('/orders/'+order.id+'/files').then(rows=>{if(token!==openToken)return;fileRows=rows;filesView(order,rows,views.files); + tabs.querySelector('[data-ptab=files] .n').textContent=rows.length?String(rows.length):'';}).catch(e=>say(e.message,true)); + api('/orders/'+order.id+'/history').then(rows=>{if(token===openToken){historyRows=rows;historyView(order,rows,views.history);}}).catch(e=>say(e.message,true)); +} +// A phone sheet's title line with its close button. +function sheetHead(title,close){const h=node('div',undefined,'shead');h.append(node('b',title),iconButton(IC.close,'Fechar',close,'mic right'));return h;} +// The order's own menu: the rare things, some of them destructive. +function moreMenu(order,buttonClass='btn sq ghost'){ + const items=[]; + const item=(d,text,fn,className='menuitem')=>{const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem'); + b.append(svgIcon(d,'i m'),text);b.onclick=async e=>{e.stopPropagation();menu.hidden=true;try{await fn();}catch(err){say(err.message,true);}};items.push(b);return b;}; + const menu=node('div',undefined,'menu dmenu');menu.hidden=true;menu.setAttribute('role','menu'); + if(!order.cancelled_at){ + // Undo a mistaken move: one stage back, internal reason, no customer message. + const previous=board.back?.[order.state]; + if(previous&&!waitingProof(order)&&mayMove(order.state,previous)&&mayAct(order))item(IC.back,'Voltar para '+board.states[previous],()=>backDialog(order,previous)).dataset.back=previous; + if(order.state!=='fin'&&!waitingContact(order)&&may('produce')) + item(IC.phone,'Aguardando contato',()=>contactDialog(order)).dataset.contact=''; + if(!isTest(order)&&may('rework'))item(IC.rework,'Abrir retrabalho',()=>reworkForm(order)); + if(isTest(order)&&may('manage'))item(IC.ban,'Excluir pedido de teste',async()=>{ + if(!await ask('Excluir o pedido de teste #'+order.number+'?','Ele some do Kanban, com o histórico.','Excluir pedido',{tone:'red',host:$('drawer')}))return; + await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();},'menuitem bad'); + else if(!isTest(order)&&may('cancel'))item(IC.ban,'Cancelar pedido',()=>cancelDialog(order),'menuitem bad'); + } + if(!items.length)return null; + // The destructive one apart, under a line. + const last=items.at(-1);if(last.classList.contains('bad')&&items.length>1)items.splice(-1,0,node('div',undefined,'menusep')); + menu.append(...items); + const b=iconButton(IC.more,'Mais ações',()=>{menu.hidden=!menu.hidden;b.setAttribute('aria-expanded',String(!menu.hidden)); + if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;b.setAttribute('aria-expanded','false');},{once:true});},buttonClass); + b.setAttribute('aria-haspopup','menu');b.setAttribute('aria-expanded','false'); + const wrap=node('span',undefined,'morewrap');wrap.append(b,menu);return wrap; +} +function cancelledNotice(order){ + const box=node('div',undefined,'callout bad'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.ban,'i m')); + const p=node('p');p.append(node('b','Pedido cancelado. '),order.cancel_reason,node('small','Por '+order.cancelled_by+' em '+when(order.cancelled_at))); + box.append(ico,p); + if(may('manage'))box.append(button('Excluir pedido',async()=>{ + if(!await ask('Excluir o pedido #'+order.number+' de vez?','Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.','Excluir pedido',{tone:'red',host:$('drawer')}))return; + await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load(); + },'btn quiet')); + return box; +} +function contactNotice(order,canClear){ + const box=node('div',undefined,'callout'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.phone,'i m')); + const p=node('p');p.append(node('b','Aguardando contato. '),order.contact_note,node('small',contactWho(order))); + box.append(ico,p); + const zap=whatsappLink(order.snapshot.customer.zap); + if(zap){const a=node('a','Abrir conversa','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i s'));box.append(a);} + // A proof order closes its contact wait with Prova OK, the only button + // (item 0.1). Other orders still need a way to record that contact is done. + if(canClear&&!needsProof(order))box.append(button('Contato feito',async()=>{ + await api('/orders/'+order.id+'/contact',{waiting:false});say('Contato registrado: a marca saiu do pedido #'+order.number+'.');await load();},'btn')); + return box; +} +// In correction, the customer has to be told: a message ready to send on +// WhatsApp with the reason and where to send the new file. +function correctionMessage(order){ + const reason=order.correction_reason||'', link=board.site_origin+'/conta/pedidos?order='+order.id; + return 'Olá! Aqui é da Dropstar. O seu pedido '+orderCode(order.id)+' precisa de um ajuste na arte antes da impressão'+ + (reason?': '+reason:'.')+'\n\nEnvie o arquivo corrigido por aqui: '+link; +} +function correctionActions(order,main){ + const message=correctionMessage(order), zap=whatsappLink(order.snapshot.customer.zap), out=[]; + if(zap){const a=node('a','Avisar no WhatsApp','btn lg'+(main?' pri':''));a.href=zap+'?text='+encodeURIComponent(message); + a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i m'));out.push(a);} + out.push(button('Copiar mensagem',async()=>{await navigator.clipboard.writeText(message);say('Mensagem copiada.');},'btn lg'+(main&&!zap?' pri':''))); + return out; +} +// A file the step is about: its kind, its name and what to do with it. +function fileRow(name,label,...actions){ + const row=node('div',undefined,'file'); + const ext=(String(name).split('.').pop()||'').slice(0,4).toUpperCase(); + const text=node('span',undefined,'ftext');text.append(node('b',name),node('span',label)); + row.append(node('span',ext,'fico'),text,...actions);return row; +} +const downloadFile=uid=>downloadButton('Baixar',download(uid),'btn'); +// The approved final is the way to the queue (Arte conferida): approving it, +// with the files that would be printed, or sending one. +// The contraction class of an item (item 9): the one chosen, else the one the +// browser measured. The FlexiPRINT applies it by the C1, C2 or C3 folder. +const CLASS_NOTE={C1:'traço até 4 px',C2:'traço de 5 a 19 px',C3:'traço de 20 px ou mais'}; +// A mixed sheet (item 16) where the customer chose to protect the solid areas starts at C3. +const measuredClass=item=>item.stroke_choice==='client_c3'?'C3':item.stroke_class||null; +const contractionOf=(order,index)=>order.contraction?.[index]?.class||measuredClass(order.snapshot.items[index]); +function contractionControl(order,index){ + const item=order.snapshot.items[index], now=contractionOf(order,index), chosen=order.contraction?.[index]; + const measured=(item.stroke_class?'medido '+item.stroke_class+', '+item.stroke_px+' px':'sem medida do navegador')+ + (item.stroke_choice==='client_c3'?'; o cliente escolheu proteger as áreas chapadas (C3)':''); + const editable=may('produce')&&!order.cancelled_at&&['rec','tra','cor'].includes(order.state); + if(!editable){const t=node('span',now?now+' ('+(chosen?'escolhida':measured)+')':'Sem classe');return t;} + const select=node('select',undefined,'inp sm');select.setAttribute('aria-label','Contração do item '+(index+1)); + for(const [value,text] of [['','Escolha'],['C1','C1, '+CLASS_NOTE.C1],['C2','C2, '+CLASS_NOTE.C2],['C3','C3, '+CLASS_NOTE.C3]]){ + const o=node('option',text);o.value=value;select.append(o);} + select.value=now||''; + select.onchange=async()=>{try{ + await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value||null}); + say('Contração do item '+(index+1)+': '+(select.value||'a medida do navegador')+'.');await load();} + catch(e){say(e.message,true);}}; + const box=node('span',undefined,'contr');box.append(select,node('small',chosen?'escolhida por '+chosen.by+'; '+measured:measured,'sub')); + return box; +} +// The approve step's "Está OK?": each item's class, prefilled, to confirm or change. +function contractionList(order){ + const box=node('div',undefined,'contrlist'); + order.snapshot.items.forEach((item,index)=>{ + const row=node('div',undefined,'contrrow'); + row.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+', contração':'Contração','lbl'),contractionControl(order,index)); + box.append(row);}); + return box; +} +function approveParts(order,main=true){ + if(designerPaid(order)){ + const label=order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino'; + const approve=button('Enviar arte do '+label,()=>treatDialog(order),'btn lg'+(main?' pri':'')); + approve.dataset.treat=''; + return {text:label+' pago: o designer precisa enviar o PNG do '+label+' de cada item antes da fila.', + files:null,approve,extra:[]}; + } + const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1; + const files=node('div',undefined,'files'); + if(all)ready.forEach((r,i)=>r.files.forEach((f,k)=>files.append(fileRow(f.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source]+ + (r.files.length>1?', parte '+(k+1)+' de '+r.files.length:''),downloadFile(f.upload_id))))); + const text=all?'Baixe e confira. É este arquivo que vai para a impressão.':ready.some(Boolean) + ?'Alguns itens já têm arquivo pronto; envie o arquivo preparado dos outros.' + :'Nenhum arquivo pronto para aprovar como está: envie o arquivo preparado para a impressão.'; + const upload=()=>finalDialog(order,all?ready.map(()=>null):ready); + const approve=button(all?'Aprovar arquivo final':'Enviar arquivo final',all?()=>approveReady(order,ready):async()=>upload(),'btn lg'+(main?' pri':'')); + approve.dataset.approve=''; + const extra=[]; + // In Arte recebida the art may need work first (Dropstar, 2026-10-29). + if(order.state==='rec'&&may('produce')){const t=button('Tratar a arte',async()=>treatDialog(order),'btn lg');t.dataset.treat='';extra.push(t);} + if(all)extra.push(button('Enviar outro arquivo',async()=>upload(),'btn lg')); + return {text,files:all?files:null,approve,extra}; +} +// "Próximo passo": what the order needs now, said once, with its button. +// Going back, the contact mark, rework and cancelling are in the menu above. +function nextBox(order){ + if(order.cancelled_at)return null; + const st=order.state, trans=board.transitions[st]||[]; + let title='';const body=[],main=[],more=[]; + const note=text=>body.push(node('p',text,'nnote')); + const can=to=>mayMove(st,to)&&mayAct(order); + const moveBtn=(to,label,className='btn pri lg')=>{ + // Pulling to a machine goes through the sheet's alerts first (front 1a). + const fn=to==='imp'?()=>pullTo(order,order.machine?.id||myMachine()?.id||null):()=>move(order,to); + const b=button(label||'Mover para '+board.states[to],fn,className);b.dataset.move=to;return b;}; + // The 10x15 label at Finalizado: added here so a view-only Expedição sees it + // too (the read-only branch below skips the stage blocks). + if(st==='fin'&&typeof labelReprintButton==='function'){ + const reprint=labelReprintButton(order); + if(reprint)more.push(reprint); + } + if(waitingProof(order)){ + title='Aguardando prova do #'+order.proof_card.number; + const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual'); + note(manual?'O Prumo não abriu o original. Prepare o PNG completo deste pedido; a prova será gerada automaticamente a partir dele.' + :'O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.'); + if(manual&&may('produce'))main.push(button('Preparar arquivo para a prova',()=>finalDialog(order,readyFinals(order)),'btn pri lg')); + return composeNext(title,body,main,more); + } + // A proof card in Revisão waits for its answer (Dropstar, 2026-11-03). + if(order.proof_parent&&st==='rev'){ + title='Responder a prova'; + note('Prova do pedido #'+order.proof_parent.number+'. Com a prova impressa conferida'+(order.snapshot.proof?' e o aceite do cliente':'')+', responda aqui.'); + if(may('proof')){main.push(button('Prova OK',()=>proofAnswer(order,'ok'),'btn pri lg')); + more.push(button('Prova reprovada',()=>proofReject(order),'btn quiet lg'));} + else note('Quem responde é o Vendedor, a Gestão ou o Administrador.'); + return composeNext(title,body,main,more); + } + const readOnly=!may('produce')&&!ME?.moves?.length; + const fixed=(order.corrections||[]).length>0; + if(st==='cor'){ + title=fixed?'Conferir a correção do cliente':'Esperando o arquivo novo'; + if(order.correction_reason){const p=node('p',undefined,'nnote');p.append(node('b','Motivo: '),order.correction_reason);body.push(p);} + if(!whatsappLink(order.snapshot.customer.zap))note('Sem WhatsApp no pedido: envie a mensagem para '+order.snapshot.customer.mail+'.'); + (fixed?more:main).push(...correctionActions(order,!fixed)); + } + if(readOnly){ + if(!title)title=st==='fin'?'Pedido concluído':'Com a produção'; + note('Somente consulta: seu perfil não move pedidos.'); + return composeNext(title,body,main,more); + } + const fixBtn=()=>{if(!trans.includes('cor')||!can('cor'))return; + const b=node('button','Pedir correção','btn quiet lg');b.type='button';b.dataset.move='cor';b.onclick=()=>correctionDialog(order);more.push(b);}; + const proofBtn=(className='btn lg')=>{if(!proofPending(order)||order.proof_card||!may('print'))return null; + const b=button('Prova OK',()=>proofOk(order),className);b.dataset.proof='';b.title='A prova foi impressa e conferida';return b;}; + const cannot=()=>note(!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.' + :st==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.'); + // The proof was rejected: its reason, and a new proof card when the art is fixed. + if(st==='rec'&&proofRejected(order)){ + const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p); + if(may('produce'))more.push(button('Nova prova',async()=>{await api('/orders/'+order.id+'/proof-card',{});await load();say('Nova prova criada.');},'btn lg')); + } + if(st==='rec'&&order.proof_parent){ + title=finalDone(order)?'Conferir a prova':'Gerando a prova'; + const manual=(order.print_files||[]).some(r=>r.status==='manual'); + note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual + ?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.' + :'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.'); + if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg')); + if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg')); + if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce')) + more.push(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn lg')); + return composeNext(title,body,main,more); + } + if(st==='rec'||st==='cor'){ + if(st==='rec'&&designerPaid(order)&&!treatmentDone(order)&&finalDone(order)){ + title='Enviar a arte do '+(order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino'); + note((order.snapshot.redesign?'O Ajuste Fino Redesenho foi pago.':'O Ajuste Fino foi pago.')+ + ' Envie o PNG ajustado de cada item antes de colocar o pedido na fila.'); + if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg')); + return composeNext(title,body,main,more); + } + if(!finalDone(order)&&trans.includes('tra')){ + if(st==='rec')title='Aprovar o arquivo final'; + // The designer approves every file (D-16); the others see it waiting. + if(!may('produce')){note('O Designer confere e aprova o arquivo final.');body.push(contractionList(order));} + else{ + const lead=st==='rec'||fixed, a=approveParts(order,lead); + // Item 7: open the file, then say whether it is OK. + if(st==='rec'){a.approve.classList.remove('pri');main.push(checkButton(order,'btn pri lg'));} + if(lead){if(a.files)body.push(a.files);note(a.text);body.push(contractionList(order));main.push(a.approve,...a.extra);} + else more.push(a.approve,...a.extra); + } + }else if(st==='rec'){ + title='Mandar para a fila'; + note('O arquivo final está aprovado. Na fila, o operador puxa para a máquina.'); + if(can('tra'))main.push(moveBtn('tra'));else cannot(); + // Approved already, the art can still be treated while in Arte recebida. + if(may('produce')){const t=button('Tratar a arte',async()=>treatDialog(order),'btn lg');t.dataset.treat='';more.push(t);} + } + if(st==='cor')for(const to of trans){ + if(to==='tra'&&!finalDone(order))continue; + if(can(to))(to==='tra'&&finalDone(order)?main:more).push(moveBtn(to,null,to==='tra'&&finalDone(order)?'btn pri lg':'btn lg')); + } + if(st==='rec')fixBtn(); + }else if(st==='tra'&&waitingProof(order)){ + title='Aguardando prova'; + note('O pedido entra na fila com Prova OK no card da prova #'+order.proof_card.number+'.'); + fixBtn(); + }else if(st==='tra'){ + title='Puxar para a máquina'; + note(order.machine?'Vai para a '+order.machine.name+'. O arquivo final já está aprovado.':'O arquivo final já está aprovado.'); + if(can('imp'))main.push(moveBtn('imp'));else cannot(); + const p=proofBtn();if(p)more.push(p); + fixBtn(); + }else if(st==='imp'){ + title=order.printing==='ripando'?'Ripando enquanto o anterior roda':'Terminou de imprimir?'; + note('A folha segue para o Revisor conferir.'); + if(can('rev'))main.push(moveBtn('rev'));else cannot(); + const p=proofBtn();if(p)more.push(p); + fixBtn(); + }else if(st==='rev'){ + if(proofPending(order)){ + // Finalizado waits for the proof: printing it and checking it is the next step. + title='Conferir a prova'; + note((order.snapshot.proof?'O cliente pediu uma prova: imprima, mande a foto pelo WhatsApp e, com o aceite dele, marque Prova OK.' + :'Pedido acima de 10 m: imprima a prova, confira e marque Prova OK antes de rodar o resto.')+' '+PROOF_RULE); + const p=proofBtn('btn pri lg');if(p)main.push(p); + }else{ + // Above 1 m the photo is required to finish (app/reviews.py): the main + // button takes it instead of releasing the order. + const hasPhoto=(order.reviews||[]).some(review=>review.kind==='photo'); + if(!order.proof_parent&&orderMetres(order)>1&&!hasPhoto){ + title='Tire a foto da revisão'; + note('Pedido acima de 1 m: tire a foto da revisão antes de finalizar.'); + if(may('inspect'))main.push(button('Revisar',()=>reviewDialog(order),'btn pri lg'));else cannot(); + }else{ + title='Conferir a folha impressa'; + note('Confira cores, recorte e a folha inteira contra o arquivo.'); + if(can('fin'))main.push(moveBtn('fin','Liberar para Finalizado'));else cannot(); + } + } + fixBtn(); + }else if(st==='fin'){ + const dest=order.snapshot.destination; + if(isPickup(order)){ + // Pickup (item 14): the receipt, and "Retirado", with the signed receipt's photo. + const paper=button('Recibo',()=>window.open('/api/operator/orders/'+order.id+'/receipt','_blank','noopener'),'btn lg'); + paper.title='Abrir o recibo de retirada para imprimir de novo';paper.prepend(svgIcon(IC.file,'i m')); + if(order.picked_up_at){ + title='Retirado';note('Em '+when(order.picked_up_at)+', entregue por '+order.picked_up_by+'.'); + if(order.picked_up_photo){const b=downloadButton('Foto do recibo',download(order.picked_up_photo),'btn lg');more.push(b);} + more.push(paper); + }else{ + title='Entregar ao cliente';note('O cliente retira na fábrica. O recibo vai junto, para a assinatura.'); + if(may('deliver')){const b=node('button','Marcar retirado','btn pri lg');b.type='button';b.dataset.pickedUp='';b.onclick=()=>pickupDialog(order);main.push(b);} + more.push(paper); + } + }else{ + title='Pedido concluído'; + note(dest?'Vai para entrega em '+dest.city+'/'+dest.state+'.':'Pedido concluído.'); + } + } + return composeNext(title,body,main,more); +} +function composeNext(title,body,main,more){ + const box=node('section',undefined,'nextbox');box.setAttribute('aria-label','Próximo passo'); + const head=node('div');head.append(node('span','Próximo passo','lbl'),node('h3',title)); + box.append(head,...body); + if(main.length||more.length){const acts=node('div',undefined,'nact');acts.append(...main,...more);box.append(acts);} + return box; +} +// ---- The order's dialogs: each a form.reason, so its field is the order's. +function correctionDialog(order){ + const text=node('textarea');text.placeholder='Ex.: o logo da manga veio em 72 DPI';text.maxLength=1000;text.required=true; + text.setAttribute('aria-label','Motivo da correção'); + formDialog('Pedir correção do pedido #'+order.number,{host:$('drawer'),className:'reason',width:540, + text:'O pedido vai para Correção. Depois, a mensagem para o cliente fica pronta para mandar no WhatsApp.', + fields:[field('Motivo',text,'O cliente vê este motivo na mensagem.')],label:'Enviar para correção',tone:'red', + onsave:async()=>{await move(order,'cor',text.value.trim());}}); +} +function backDialog(order,previous){ + const why=node('input');why.placeholder='Motivo';why.setAttribute('aria-label','Motivo do retorno');why.required=true;why.maxLength=1000; + formDialog('Voltar para '+board.states[previous]+'?',{host:$('drawer'),className:'reason',width:500, + text:'Para desfazer um movimento feito por engano. O cliente não é avisado e os arquivos aprovados continuam.', + fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Voltar para '+board.states[previous], + onsave:async()=>{await move(order,previous,why.value.trim());}}); +} +function contactDialog(order){ + const what=node('input');what.placeholder='Ex.: confirmar se a arte vai na frente ou nas costas';what.setAttribute('aria-label','O que precisa ser combinado'); + what.required=true;what.minLength=3;what.maxLength=500; + formDialog('Aguardando contato',{host:$('drawer'),className:'reason',width:540, + text:'O card fica marcado até alguém registrar o contato feito.', + fields:[field('O que precisa ser combinado com o cliente',what)],label:'Marcar aguardando contato', + onsave:async()=>{await api('/orders/'+order.id+'/contact',{waiting:true,note:what.value.trim()});say('Pedido #'+order.number+' aguardando contato.');await load();}}); +} +function cancelDialog(order){ + const why=node('textarea');why.placeholder='Ex.: cliente desistiu, vai refazer a arte';why.setAttribute('aria-label','Motivo do cancelamento'); + why.required=true;why.minLength=3;why.maxLength=1000; + formDialog('Cancelar o pedido #'+order.number+'?',{host:$('drawer'),className:'reason',width:520, + text:'O pedido sai do quadro e fica em Cancelados, com o pagamento e o histórico. O valor fica como crédito do cliente, no controle financeiro, e o pedido no Tiny se cancela lá.', + fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Cancelar pedido',tone:'red', + onsave:async()=>{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}}); +} +function pickupDialog(order){ + const photo=node('input');photo.accept='image/*';photo.setAttribute('aria-label','Foto do recibo assinado'); + formDialog('Marcar o pedido #'+order.number+' como retirado',{host:$('drawer'),width:540, + text:'Quem retirou assina o recibo. A foto dele fica no pedido.', + fields:[dropField(photo,{title:'Foto do recibo assinado',hint:'Opcional. JPG, PNG ou HEIC.'})],label:'Confirmar retirada', + onsave:async()=>{ + const uid=photo.files[0]?await dtfUpload(photo.files[0],{api,startPath:'/orders/'+order.id+'/pickup-uploads', + scope:'operator:pickup:'+order.id,progress:text=>say(text)}):null; + await api('/orders/'+order.id+'/picked-up',{photo:uid}); + await load();say('Pedido #'+order.number+' marcado como retirado.'); + }}); +} +// Pickup or delivery, from the freight the customer chose. +const isPickup=order=>order.snapshot.freight?.service==='pickup'; +// An internal order stays in house, and a sale can travel with the customer's +// clothing order (Fase 2, front 7a.3): the card and the panel say so instead +// of "Retirada". +const specialDelivery=s=>s.kind==='interno'?'Interno':s.with_order?'Junto com o pedido de roupa nº '+s.with_order:null; +// ---- Final files: the file each item is printed from, approved by an operator. +const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index)); +const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index)); +const designerPaid=order=>!!(order.snapshot.treatment||order.snapshot.redesign); +const FINAL_SOURCE={correction:'correção do cliente',generated:'arquivo gerado',original:'original'}; +const FINAL_TITLE={correction:'Correção do cliente',generated:'Gerado pelo sistema',original:'Original do cliente'}; +// What the system generated for an item: one PNG, or the parts of a film +// over 15 m (item 13). An item generated before parts has just its file. +const generatedFiles=row=>row.parts?.length?row.parts:[{upload_id:row.upload_id,name:row.name}]; +// Per item, the files that can be approved as they are, or null: the +// customer's correction, or else what the system generated (or the original +// that already was one). After a correction, a generated file reproduces +// artwork nobody wants printed. +function readyFinals(order){ + const fixes=order.corrections||[]; + return order.snapshot.items.map((item,index)=>{ + const fix=fixes.find(f=>f.item_index===index); + if(fix)return fix.expired||!fix.name.toLowerCase().endsWith('.png')?null:{files:[{upload_id:fix.upload_id,name:fix.name}],name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'}; + const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready'); + if(!made)return null; + const original=made.detail?.source==='original', files=generatedFiles(made); + const names=files.length>1?files.length+' partes, '+files[0].name+' a '+files[files.length-1].name:files[0].name; + return {files,name:files[0].name,source:original?'original':'generated',label:(original?'O original (':'Gerado pelo sistema (')+names+')'}; + }); +} +// Sends final-files from a dialog that may have been opened before another +// screen approved the same files (DTF-WEB-7). A stale version gets 409 "O +// pedido mudou"; when the approval is already there, or the order left Arte +// recebida/Correção, reload and say so; true tells the caller to stop, and a +// form dialog then closes itself. Anything else is still an error, and the +// version is never resent blindly. +async function saveFinalFiles(order, files, note){ + try{ + await api('/orders/'+order.id+'/final-files',{version:order.version,files,note}); + return false; + }catch(error){ + if(error.status!==409||!String(error.message).startsWith('O pedido mudou'))throw error; + await load(); + const fresh=(board.orders||[]).find(row=>row.id===order.id); + if(fresh&&(finalDone(fresh)||!['rec','cor'].includes(fresh.state))){ + say('O arquivo final já estava aprovado.'); + return true; + } + throw error; + } +} +async function approveReady(order,ready){ + const many=ready.length>1; + if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+ + ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return; + const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', '); + if(await saveFinalFiles(order, + ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return; + await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.'); +} +// The file the operator prepared, per item; a ready file comes ticked. +function finalDialog(order,ready,{replace=false}={}){ + const fields=[]; + const inputs=order.snapshot.items.map((item,index)=>{ + const slot=node('div',undefined,'fslot'); + const label=order.snapshot.items.length>1?'Item '+(index+1)+', '+productName(item):productName(item); + slot.append(node('span',label,'lbl')); + const input=node('input');input.multiple=true;input.required=true;input.dataset.finalItem=index; + input.setAttribute('aria-label','Arquivo final, '+label); + input.accept='.png,image/png'; + const drop=dropField(input,{hint:'PNG transparente a 300 DPI, do tamanho da impressão.'}); + const file=ready[index]; + if(file){ + const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true; + use.onchange=()=>{drop.hidden=use.checked;input.required=!use.checked;}; + slot.append(checkbox('Usar: '+file.label,use));input.generated=()=>use.checked?file.files.map(f=>f.upload_id):null; + } + slot.append(drop);fields.push(slot);return input; + }); + const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;note.setAttribute('aria-label','Nota da revisão'); + const check=node('input');check.required=true;check.dataset.confirm=''; + fields.push(field('Nota',note,'Ex.: ajustei a margem e o recorte. Fica no histórico.'),checkbox('Arquivos conferidos',check)); + formDialog(replace?'Trocar o arquivo final':'Enviar o arquivo final',{host:$('drawer'),width:580,className:'finalform', + text:'Pedido #'+order.number+'. O arquivo novo passa a ser o que vai para a impressão.',note:'O anterior fica em Arquivos.', + fields,label:'Aprovar arquivo final',onsave:async()=>{ + const refs=[]; + for(const [index,input] of inputs.entries()){ + const generated=input.generated?.(); + if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;} + for(const file of input.files){ + if(!file.name.toLowerCase().endsWith('.png'))throw Error('O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'); + const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)}); + refs.push({item_index:index,upload_id:uid}); + } + } + if(await saveFinalFiles(order,refs,note.value))return; + await load();say('Arquivo final aprovado.'); + }}); +} +// "Tratar a arte" (Dropstar, 2026-10-29): where each item's file is in the +// orders folder, to open it, treat it and save it over with the same name; +// then the treated file sent here becomes the item's final, "Arte tratada". +// The browser only knows the folder's name, so each computer is told once +// where the folder is, to copy the whole path. +const TREAT_NOTE='Arte tratada'; +const FOLDER_PATH_KEY='folder-path'; +// ---- Abrir e conferir (item 7) ---------------------------------------------- + +// The print file full screen, in pieces (web/kanban-viewer.js); closed in +// Arte recebida, it asks whether the art is OK. +function checkButton(order,className='btn'){ + const b=button('Abrir e conferir',()=>openCheck(order),className);b.prepend(svgIcon(IC.eye||IC.file,'i m'));return b; +} +function cardOpenAction(order){ + const action=button('Abrir arquivo',()=>openCheck(order),'card-open'); + action.prepend(svgIcon(IC.eye||IC.file,'i s')); + // In Revisão the Revisor also has the photo/video on the card's face, beside + // the file. The click is stopped by button(), as on "Abrir arquivo". + if(order.state==='rev'&&!order.cancelled_at&&may('inspect')){ + const review=button('Revisar',()=>reviewDialog(order),'card-open'); + review.prepend(svgIcon(IC.camera,'i s')); + const row=node('span',undefined,'card-open-row');row.append(action,review); + return row; + } + if(order.state==='fin'&&typeof labelReprintButton==='function'){ + const reprint=labelReprintButton(order,'card-open'); + if(reprint){const row=node('span',undefined,'card-open-row');row.append(action,reprint);return row;} + } + return action; +} +// "Revisar" (Fase 2, front 2): the sheet's photo or a video of up to 30 s, +// taken here with the computer's or the phone's camera, or a file already +// recorded. The server names it DTF--revisao- and keeps it 180 days. +const REVIEW_VIDEO_MAX=30; +const reviewClock=s=>Math.floor(s/60)+':'+String(s%60).padStart(2,'0'); +function reviewDialog(order){ + const host=dialogHost(); + const video=node('video');video.className='reviewcam';video.muted=true;video.playsInline=true;video.autoplay=true; + video.setAttribute('aria-label','Pré-visualização da câmera'); + const timer=node('span','0:00 / 0:30','reviewtime');timer.setAttribute('aria-live','polite'); + const controls=node('div',undefined,'reviewcontrols'); + const photoBtn=node('button','Tirar foto','btn pri');photoBtn.type='button';photoBtn.setAttribute('aria-label','Tirar foto');photoBtn.setAttribute('autofocus',''); + const videoBtn=node('button','Gravar vídeo','btn');videoBtn.type='button';videoBtn.setAttribute('aria-label','Gravar vídeo'); + const input=node('input');input.type='file';input.className='vh'; + input.accept='image/jpeg,image/png,image/webp,video/mp4,video/webm,video/quicktime'; + const fileLabel=node('label',undefined,'btn');fileLabel.tabIndex=0; + fileLabel.append(svgIcon(IC.upload,'i m'),'Enviar arquivo',input); + const preview=node('div',undefined,'reviewpreview');preview.hidden=true; + const status=node('p','','reviewmsg');status.setAttribute('role','status');status.setAttribute('aria-live','polite'); + const save=node('button','Salvar revisão','btn pri');save.type='button';save.disabled=true; + const cancel=node('button','Cancelar','btn ghost right');cancel.type='button'; + controls.append(photoBtn,videoBtn,fileLabel); + let stream=null,recorder=null,recordTimer=null,chunks=[],ready=null,objectUrl=null,closed=false,recording=false,recordStart=0; + const fail=text=>{status.textContent=text;status.classList.add('bad');}; + const clear=()=>{status.textContent='';status.classList.remove('bad');}; + const endStream=()=>{ + if(recordTimer){clearInterval(recordTimer);recordTimer=null;} + if(stream){stream.getTracks().forEach(track=>track.stop());stream=null;} + }; + const cleanup=()=>{ + closed=true; + if(recorder&&recorder.state!=='inactive'){try{recorder.stop();}catch(_){}} + endStream(); + if(objectUrl){URL.revokeObjectURL(objectUrl);objectUrl=null;} + }; + function showReady(file,kind){ + ready={file,kind}; + endStream(); + video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true; + if(objectUrl)URL.revokeObjectURL(objectUrl); + objectUrl=URL.createObjectURL(file); + preview.replaceChildren(); + if(kind==='video'){ + const shot=node('video');shot.controls=true;shot.playsInline=true;shot.src=objectUrl; + shot.setAttribute('aria-label','Pré-visualização do vídeo gravado');preview.append(shot); + }else{ + const shot=node('img');shot.src=objectUrl;shot.alt='Pré-visualização da foto';preview.append(shot); + } + preview.hidden=false;save.disabled=false;clear();save.focus(); + } + function checkDuration(file){ + return new Promise((resolve,reject)=>{ + const probe=document.createElement('video');probe.preload='metadata'; + const url=URL.createObjectURL(file); + probe.onloadedmetadata=()=>{ + const seconds=probe.duration;URL.revokeObjectURL(url); + if(Number.isFinite(seconds)&&seconds>REVIEW_VIDEO_MAX+0.2) + reject(new Error('O vídeo tem mais de 30 segundos. Grave um de até 30 s ou envie outro menor.')); + else resolve(); + }; + probe.onerror=()=>{URL.revokeObjectURL(url);resolve();}; + probe.src=url; + }); + } + function stopRecording(){if(recorder&&recorder.state!=='inactive')recorder.stop();} + photoBtn.onclick=()=>{ + clear(); + const width=video.videoWidth,height=video.videoHeight; + if(!width||!height){fail('A câmera ainda não está pronta. Espere um instante.');return;} + const canvas=document.createElement('canvas');canvas.width=width;canvas.height=height; + canvas.getContext('2d').drawImage(video,0,0,width,height); + canvas.toBlob(blob=>{ + if(!blob){fail('Não foi possível tirar a foto.');return;} + showReady(new File([blob],'revisao.jpg',{type:'image/jpeg'}),'photo'); + },'image/jpeg',0.9); + }; + videoBtn.onclick=()=>{ + clear(); + if(recording){stopRecording();return;} + if(!stream){fail('A câmera não está disponível. Envie um arquivo.');return;} + const options=['video/mp4','video/webm;codecs=vp9','video/webm']; + const mime=(window.MediaRecorder&&options.find(type=>MediaRecorder.isTypeSupported(type)))||''; + try{recorder=new MediaRecorder(stream,mime?{mimeType:mime}:undefined);} + catch(_){fail('Este navegador não grava vídeo. Envie um arquivo.');return;} + const type=recorder.mimeType||mime||'video/webm'; + chunks=[];recording=true;recordStart=Date.now(); + recorder.ondataavailable=event=>{if(event.data&&event.data.size)chunks.push(event.data);}; + recorder.onstop=()=>{ + recording=false;videoBtn.textContent='Gravar vídeo'; + if(recordTimer){clearInterval(recordTimer);recordTimer=null;} + if(closed)return; + const blob=new Blob(chunks,{type});chunks=[]; + if(!blob.size){fail('Não foi possível gravar o vídeo.');return;} + showReady(new File([blob],'revisao.'+(type.includes('mp4')?'mp4':'webm'),{type}),'video'); + }; + recorder.start();videoBtn.textContent='Parar'; + const paint=()=>{ + const elapsed=Math.min(REVIEW_VIDEO_MAX,Math.floor((Date.now()-recordStart)/1000)); + timer.textContent=reviewClock(elapsed)+' / '+reviewClock(REVIEW_VIDEO_MAX); + if(elapsed>=REVIEW_VIDEO_MAX)stopRecording(); + }; + paint();recordTimer=setInterval(paint,250); + }; + input.onchange=async()=>{ + const file=input.files[0];if(!file)return; + clear(); + const name=file.name.toLowerCase(); + const isVideo=file.type.startsWith('video/')||/\.(mp4|webm|mov)$/.test(name); + const isPhoto=file.type.startsWith('image/')||/\.(jpe?g|png|webp)$/.test(name); + if(!isVideo&&!isPhoto){input.value='';fail('Escolha uma foto JPG, PNG ou WebP, ou um vídeo MP4, WebM ou MOV.');return;} + if(isVideo){ + try{await checkDuration(file);}catch(error){input.value='';fail(error.message);return;} + if(closed)return; + showReady(file,'video'); + }else showReady(file,'photo'); + }; + fileLabel.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();input.click();}}; + cancel.onclick=()=>m.close(); + save.onclick=async()=>{ + if(!ready)return; + save.disabled=true;clear();status.textContent='Enviando '+ready.file.name+'…'; + try{ + const uid=await dtfUpload(ready.file,{api,startPath:'/orders/'+order.id+'/reviews/uploads', + scope:'operator:review:'+order.id,progress:text=>{if(!closed)status.textContent=text;}}); + if(closed)return; + await api('/orders/'+order.id+'/reviews',{upload_id:uid}); + m.close(); + say('Revisão salva no pedido #'+order.number+'.'); + await load(); + }catch(error){ + if(closed)return; + fail(error.message);save.disabled=false; + } + }; + const m=modal('Revisão do #'+order.number,{host,width:640, + text:'Tire uma foto ou grave um vídeo de até 30 s da folha impressa, ou envie um arquivo.', + body:[video,controls,timer,preview],foot:[status,cancel,save],onclose:cleanup}); + (async()=>{ + try{ + if(!navigator.mediaDevices?.getUserMedia)throw new Error('sem câmera'); + stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'environment', + width:{ideal:1920},height:{ideal:1080}},audio:false}); + if(closed){endStream();return;} + video.srcObject=stream; + await video.play().catch(()=>{}); + photoBtn.focus(); + }catch(_){ + endStream();video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true; + fail('Câmera indisponível neste computador. Envie um arquivo.'); + fileLabel.focus(); + } + })(); +} +async function openCheck(order){ + const {files}=await api('/orders/'+order.id+'/view'); + if(!files.length){say('Ainda não há arquivo para abrir.',true);return;} + openViewer(files,{title:'#'+order.number,onClose:()=>{ + const now=board.orders.find(o=>o.id===order.id)||order; + if(now.state==='rec'&&!now.cancelled_at&&!waitingProof(now)&&may('produce')&&mayMove('rec','tra')){ + if(openOrder!==order.id)openPanel(order.id); + isOk(now); + }}}); +} +// "Está OK?" (Dropstar, 2026-10-29): the class of each item, prefilled with +// the measure, and the art either goes on to Arte conferida, its final +// approved and its class kept, or is treated (item 8). +function isOk(order){ + // Ajuste Fino or Redesenho paid: only the treated PNG goes to the queue, so + // nothing is approved here; the designer goes to "Tratar a arte" (DTF-WEB-A). + if(designerPaid(order)&&!treatmentDone(order)){ + const service=order.snapshot.redesign?'O Ajuste Fino Redesenho':'O Ajuste Fino'; + const m=formDialog('Falta a arte tratada',{host:$('drawer'),label:'Tratar a arte', + text:service+' foi pago. Envie o PNG ajustado de cada item antes de colocar o pedido na fila.', + onsave:async()=>{m.close();treatDialog(order);return false;}}); + return; + } + const items=order.snapshot.items, ready=readyFinals(order); + const selects=items.map((item,index)=>{ + const select=node('select');select.required=true; + const none=node('option','Escolha');none.value='';none.disabled=true;select.append(none); + for(const c of ['C1','C2','C3']){const o=node('option',c+', '+CLASS_NOTE[c]);o.value=c;select.append(o);} + select.value=contractionOf(order,index)||'';return select;}); + const fields=selects.map((select,index)=>{const item=items[index]; + return field(items.length>1?'Item '+(index+1)+', contração':'Contração',select, + item.stroke_class?'O site mediu '+item.stroke_class+', traço de '+item.stroke_px+' px':'O site não mediu esta arte');}); + const missing=!finalDone(order)&&!ready.every(Boolean); + const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn'); + const m=formDialog('Está OK?',{host:$('drawer'),fields,left:[treat],label:'Mover para Arte conferida', + text:missing?'Falta o arquivo final de um item: trate a arte e envie o arquivo preparado.' + :'A arte chegou boa? Confira a contração e mova para Arte conferida.', + onsave:async()=>{ + if(missing)throw new Error('Falta o arquivo final de um item.'); + for(const [index,select] of selects.entries()) + if(select.value!==contractionOf(order,index)) + await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value}); + if(!finalDone(order)&&await saveFinalFiles(order, + ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))), + 'Conferido em Abrir e conferir'))return; + await load(); + await move(board.orders.find(o=>o.id===order.id)||order,'tra'); + say('Pedido #'+order.number+' em Arte conferida.'); + }}); + if(missing)m.box.querySelector('button.pri')?.setAttribute('disabled',''); +} +function treatDialog(order){ + const base=node('input');base.placeholder='Ex.: D:\\'+(FOLDER.handle?.name||'Pedidos'); + const names={}; + const rows=order.snapshot.items.map((item,index)=>{ + const slot=node('div',undefined,'fslot'); + const path=node('code','Procurando o arquivo…','treatpath'); + const copy=node('button','Copiar','btn');copy.type='button';copy.disabled=true; + const line=node('div',undefined,'treatline');line.append(path,copy); + const input=node('input');input.dataset.treatItem=index; + input.setAttribute('aria-label','Arte tratada do item '+(index+1)); + slot.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+', '+productName(item):productName(item),'lbl'),line, + dropField(input,{title:'Arte tratada',hint:'O arquivo salvo depois de tratar.'})); + return {path,copy,input}; + }); + // Windows paths unless the folder was written the other way. + const where=name=>{const b=base.value.trim().replace(/[\\/]+$/,''),sep=b.includes('/')&&!b.includes('\\')?'/':'\\'; + return (b?b+sep:'')+STAGE_FOLDERS[order.state]+sep+name;}; + const paint=()=>rows.forEach((row,index)=>{ + const name=names[index+1]; + row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.'; + row.copy.disabled=!name; + row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(name)); + say(base.value.trim()?'Caminho copiado.':'Caminho copiado a partir da pasta dos pedidos: informe onde ela fica neste computador para copiar o caminho inteiro.');} + catch(_){say('Não foi possível copiar.',true);}}; + }); + base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();}; + formDialog('Tratar a arte',{host:$('drawer'),width:620,className:'finalform', + text:'Copie o caminho e abra o arquivo. Trate e salve por cima, com o mesmo nome. Depois suba aqui o arquivo tratado.', + fields:[...rows.map(r=>r.input.closest('.fslot')),field('Pasta dos pedidos neste computador',base)],label:'Subir arte tratada', + onsave:async()=>{ + // Each item keeps its approved final, or else the file ready to approve, + // unless a treated one is sent for it. + const ready=readyFinals(order); + const plan=rows.map((row,index)=>{ + const file=row.input.files[0]; + if(file)return {file}; + const kept=(order.finals||[]).filter(f=>f.item_index===index).map(f=>f.upload_id); + const treated=order.treated?.items?.includes(index); + return {ids:designerPaid(order)&&!treated?[]: + kept.length?kept:ready[index]?ready[index].files.map(f=>f.upload_id):[]}; + }); + if(!plan.some(p=>p.file))throw new Error('Escolha o arquivo tratado.'); + const empty=plan.findIndex(p=>!p.file&&!p.ids.length); + if(empty>=0)throw new Error('O item '+(empty+1)+' ainda não tem arte tratada: envie o PNG dele também.'); + const refs=[]; + for(const [index,p] of plan.entries()){ + if(!p.file){refs.push(...p.ids.map(upload_id=>({item_index:index,upload_id})));continue;} + const uid=await dtfUpload(p.file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)}); + refs.push({item_index:index,upload_id:uid}); + } + if(await saveFinalFiles(order,refs,TREAT_NOTE))return; + await load(); + say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.'); + }}); + // Filled once open: the names the automatic folders give the files. + (async()=>{ + base.value=await kv.get(FOLDER_PATH_KEY).catch(()=>'')||''; + try{for(const f of (await api('/orders/'+order.id+'/folder-files')).files)names[f.item]=names[f.item]||f.name;} + catch(error){say(error.message,true);} + paint(); + })(); +} +// The reviews recorded on the order: what was checked, when and by whom. A +// photo opens in the viewer; a video cannot, so it opens in a new tab. In +// Revisão a reviewer may remove one. +function reviewSection(order){ + if(!order.reviews?.length)return null; + const box=node('section',undefined,'reviewsec');box.setAttribute('aria-label','Revisões'); + const info=node('div',undefined,'iinfo'); + info.append(node('span','Revisões','lbl'),node('h3',plural(order.reviews.length,'revisão','revisões'))); + const list=node('div',undefined,'reviewlist'); + for(const review of order.reviews){ + const row=node('div',undefined,'reviewrow'); + const open=node('button',undefined,'reviewopen');open.type='button'; + open.append(node('span','Revisão · '+(review.kind==='video'?'vídeo':'foto')+' · '+ + when(review.created_at)+' · '+review.created_by)); + open.onclick=async()=>{ + try{ + const view=await api('/orders/'+order.id+'/reviews/'+review.id+'/view'); + if(review.kind==='photo'&&window.openViewer)openViewer([{name:view.name,picture:view.url}],{title:'Revisão #'+order.number}); + else{const link=node('a');link.href=view.url;link.target='_blank';link.rel='noopener noreferrer';link.click();} + }catch(error){say(error.message,true);} + }; + row.append(open); + if(order.state==='rev'&&may('inspect')){ + const remove=node('button','Remover','btn quiet');remove.type='button'; + remove.onclick=async()=>{ + if(!await ask('Remover esta revisão?','Ela some do pedido e o arquivo deixa de ficar guardado.','Remover revisão',{tone:'red',host:$('drawer')}))return; + await api('/orders/'+order.id+'/reviews/'+review.id+'/remove',{}); + say('Revisão removida do pedido #'+order.number+'.');await load(); + }; + row.append(remove); + } + list.append(row); + } + info.append(list);box.append(info); + return box; +} +// Pedido: the items, then who, where and on which machine, then any rework. +function orderView(order){ + const view=node('div',undefined,'tview'); + const s=order.snapshot; + s.items.forEach((item,index)=>view.append(itemCard(order,item,index))); + view.append(orderFacts(order)); + const reviews=reviewSection(order);if(reviews)view.append(reviews); + if(order.reworks?.length)view.append(reworkSection(order)); + return view; +} +// On the phone: one row per fact, the label on the left. +function phoneFacts(order){ + const s=order.snapshot, dest=s.destination, who=buyer(s); + const box=node('div',undefined,'mblock mfacts'); + const row=(k,v)=>{if(!v)return;const r=node('div',undefined,'mfact');r.append(node('span',k),node('b',v));box.append(r);}; + row('Cliente',who.title);row('E-mail',s.customer.mail);row(docKind(s.customer.cnpj),cnpj(s.customer.cnpj)); + row('Entrega',specialDelivery(s)||(dest?dest.city+'/'+dest.state:'Retirada em Franca')); + row('Máquina',order.machine?.name||'Nenhuma');row('Código','DTF-'+order.number+', cliente '+orderCode(order.id)); + // Choosing the machine stays where it is allowed. + if(may('print')&&ME?.role!=='operador'&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);} + return box; +} +function orderFacts(order){ + if(PHONE.matches)return phoneFacts(order); + const s=order.snapshot, dest=s.destination, who=buyer(s); + const grid=node('div',undefined,'facts3'); + const client=node('div',undefined,'fact'); + const doc=node('span',undefined,'factline');doc.append(docKind(s.customer.cnpj)+' '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar '+docKind(s.customer.cnpj))); + const title=node('b',who.title);title.title=who.legal||who.title; + client.append(node('span','Cliente','lbl'),title,...(who.mail?[node('span',who.mail)]:[]),doc); + const zap=whatsappLink(s.customer.zap); + if(zap){const a=node('a','Abrir conversa','btn lnk');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(svgIcon(IC.chat,'i s'));client.append(a);} + const where=node('div',undefined,'fact'),special=specialDelivery(s); + where.append(node('span','Entrega','lbl'),node('b',special||(dest?dest.recipient:'Retirada em Franca')), + node('span',special?(special==='Interno'?'Fica na fábrica':'Sem frete próprio'): + dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+', '+dest.district+', '+dest.city+'/'+dest.state+', CEP '+dest.postal_code:'O cliente retira na fábrica')); + if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+', '+money(s.freight.total_cents)+(s.freight.weight_kg?', '+freightWeight(s.freight):''),'faint')); + grid.append(client,where); + if(order.machine||board.machines?.length)grid.append(machineCard(order)); + return grid; +} +const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'Arquivo gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'}; +// A line on an item: what is fine (ok), to look at (warn) or wrong (bad). +function itemNote(text,tone=''){ + const line=node('div',undefined,'inote'+(tone?' '+tone:'')); + line.append(svgIcon(tone==='ok'?IC.check:tone?IC.alert:IC.info,'i s'),node('span',text));return line; +} +function itemCard(order,item,index){ + const row=(order.print_files||[]).find(r=>r.item_index===index), spec=item.production; + const printStatus=row?.timed_out?'failed':row?.status; + const box=node('section',undefined,'item');box.setAttribute('aria-label','Item '+(index+1)); + const info=node('div',undefined,'iinfo'); + const count=order.snapshot.items.length; + info.append(node('span',count>1?'Item '+(index+1)+' de '+count:'Item','lbl'),node('h3',productName(item))); + const dl=node('dl',undefined,'dl'); + const pair=(k,v)=>{if(v===null||v===undefined||v==='')return;const d=node('div');const dd=node('dd');dd.append(v);d.append(node('dt',k),dd);dl.append(d);}; + pair('Folha',sheetSize(spec));pair('Metros cobrados',metres(item.billed_metres)); + pair('Peças',spec?String(spec.placements.length):null); + pair('Valor do metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null); + const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g); + pair('Menor resolução',row?.status==='ready'&&row.detail?.min_dpi?row.detail.min_dpi+' DPI':null); + pair('Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null); + pair('Contração',contractionControl(order,index)); + info.append(dl); + const notes=node('div',undefined,'inotes'); + if(item.quality_status==='warning')notes.append(itemNote('O cliente aceitou a ressalva de resolução.','warn')); + if(item.residue_accepted)notes.append(itemNote('Resíduo: '+item.residue_accepted+' pontos, aceito pelo cliente'+ + (item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn')); + if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+ + (item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.' + :'o cliente foi avisado e quis imprimir assim mesmo (C1).')+ + (item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn')); + if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad')); + // After a customer correction, that file is the artwork: the generated + // print file, or the reason it could not be made, no longer applies. + const fix=(order.corrections||[]).find(f=>f.item_index===index); + if(fix)notes.append(itemNote('Correção do cliente recebida: '+fix.name,'ok')); + else if(!row)notes.append(itemNote('Arquivo de impressão ainda não gerado.')); + else if(printStatus==='manual'||printStatus==='failed'){ + const call=node('div',undefined,'callout warn'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.alert,'i m')); + const p=node('p');p.append(node('b',printStatus==='failed'?'Falhou ao gerar'+(row.finished_at||row.timeout_at?' às '+when(row.finished_at||row.timeout_at):'')+'. ':'Preparar à mão. '), + row.timed_out?'Tempo limite excedido. Gere de novo.':row.detail?.reason||'Monte a folha a partir do original.'); + call.append(ico,p);notes.append(call); + }else{ + const original=row.status==='ready'&&row.detail?.source==='original'; + notes.append(itemNote((original?'O original é o arquivo de impressão':PRINT_TEXT[row.status])+ + (row.status==='ready'&&row.name&&!original?': '+row.name:'')+(row.status==='ready'&&row.detail?.vector_sources&&!original?', PDF vetorial':''),row.status==='ready'?'ok':'')); + } + if(['rec','tra','cor'].includes(order.state)){ + const done=(order.final_items||[]).includes(index); + notes.append(itemNote(done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn')); + } + if(order.treated?.items.includes(index))notes.append(itemNote('Arte tratada: '+TREATED_NOTE.charAt(0).toLowerCase()+TREATED_NOTE.slice(1)+' Aprovado por '+order.treated.by+'.')); + // O que o Prumo fez (front 6): the actions that happened, before the + // designer opens the file. Multi-item orders show each item's own lines. + const multi=order.snapshot.items.length>1, prefix=multi?'Item '+(index+1)+': ':''; + const prumoLines=(order.prumo||[]).filter(line=>!multi||line.startsWith(prefix)||line.startsWith('Prova do')) + .map(line=>line.startsWith(prefix)?line.slice(prefix.length):line); + if(prumoLines.length){ + const block=node('details',undefined,'prumo');block.append(node('summary','O que o Prumo fez')); + prumoLines.forEach(line=>block.append(node('p',line))); + notes.append(block); + } + if(notes.children.length)info.append(notes); + const links=node('div',undefined,'links'); + const dl_=(text,uid)=>{const b=downloadButton(text,download(uid),'btn');return b;}; + if(fix&&!fix.expired)links.append(dl_('Correção',fix.upload_id)); + else if(row?.status==='ready'&&row.detail?.source!=='original'){ + const made=generatedFiles(row); + made.forEach((f,k)=>links.append(dl_(made.length>1?'Parte '+(k+1)+' de '+made.length:/\.pdf$/i.test(f.name)?'PDF':'PNG',f.upload_id))); + } + const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')')); + item.uploads.forEach((uid,i)=>originals.append(downloadButton('Original '+(i+1),download(uid,order.id),'btn'))); + links.append(originals); + if(row?.status==='ready')links.prepend(checkButton(order)); + if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&!waitingProof(order)&&(!row||row.status==='manual'||row.status==='failed'||row.timed_out)){ + const again=button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn');again.prepend(svgIcon(IC.refresh,'i m'));links.append(again);} + info.append(links); + box.append(itemPreview(item),info);return box; +} +// Arquivos: every final, current or replaced, and the way to send a new one. +function filesView(order,revisions,view){ + const out=[]; + const layouts=node('div',undefined,'links'); + order.snapshot.items.forEach((item,index)=>{ + if(item.production?.placements){ + const b=button('Manifesto · item '+(index+1),()=>manifest(item.production,contractionRecord(item,order.contraction?.[index])),'btn'); + b.prepend(svgIcon(IC.file,'i m'));layouts.append(b); + } + }); + if(layouts.children.length)out.push(layouts); + if(revisions.length){ + const panel=node('div',undefined,'tpanel'); + const table=node('table',undefined,'table'); + const head=node('tr');head.append(node('th','Arquivo'),node('th','Item'),node('th','Situação'),node('th','')); + for(const th of head.children)th.scope='col'; + const thead=node('thead');thead.append(head);const tbody=node('tbody'); + for(const file of revisions){ + const tr=node('tr'); + const name=node('td');name.append(node('span',file.name,'code'),node('span',(file.kind==='final'?'Final':'Correção do cliente')+(file.note?', '+file.note:''),'sub')); + const state=node('td');state.append(badge(file.expired?'Expirado':file.active?'Atual':'Substituído',file.active&&!file.expired?'ok':''),node('span',when(file.created_at),'sub')); + const act=node('td',undefined,'r');if(!file.expired)act.append(downloadButton('Baixar',download(file.upload_id),'btn ghost')); + tr.append(name,node('td',String(file.item_index+1)),state,act);tbody.append(tr); + } + table.append(thead,tbody);panel.append(table);out.push(panel); + }else out.push(node('p','Nenhum arquivo final ainda.','empty')); + // Replacing an approved final, while the art is still in Arte recebida or Correção; + // in Arte conferida, the queue, the order goes back to Arte recebida first. + if(may('produce')&&['rec','cor'].includes(order.state)&&finalDone(order)&&!order.cancelled_at&&!order.proof_parent){ + const open=button('Enviar nova versão',async()=>finalDialog(order,readyFinals(order).map(()=>null),{replace:true}),'btn'); + open.prepend(svgIcon(IC.upload,'i m'));open.classList.add('self-start');out.push(open); + } + view.replaceChildren(...out); +} +// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause, +// which never changes after; an Administrador authorizes or declines it, +// never one they opened. Bad art the customer approved is outside the goal. +const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de Ajuste Fino', + pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'}; +const REWORK_OUTSIDE='arte_cliente'; +function reworkForm(order){ + const cause=node('select');cause.required=true; + const none=node('option','Escolha a causa');none.value='';cause.append(none); + for(const [value,text] of Object.entries(REWORK_CAUSES)){const o=node('option',text+(value===REWORK_OUTSIDE?' (fora da meta)':''));o.value=value;cause.append(o);} + const size=node('input');size.type='number';size.required=true;size.min='0.01';size.max='1000';size.step='0.01'; + size.value=order.snapshot.items.reduce((t,i)=>t+Number(i.metres??i.billed_metres),0).toFixed(2); + const note=node('textarea');note.maxLength=1000;note.placeholder='O que aconteceu (opcional)'; + formDialog('Abrir retrabalho no pedido #'+order.number,{host:$('drawer'),width:540, + text:'A causa não muda depois de aberta. O retrabalho conta na meta quando um administrador autoriza.', + fields:[field('Causa',cause),field('Metros refeitos',unit(size,'metros')),field('Observação',note)],label:'Abrir retrabalho', + onsave:async()=>{ + await api('/orders/'+order.id+'/reworks',{cause:cause.value,metres:size.value,note:note.value}); + say('Retrabalho aberto no pedido #'+order.number+'. Aguarda a autorização de um administrador.');await load(); + }}); +} +// An input with its unit inside it, on the right. +function unit(input,text){const u=node('span',undefined,'unit');u.append(input,node('span',text));return u;} +function reworkSection(order){ + const section=node('section',undefined,'tsection');section.append(node('h4','Retrabalho')); + for(const r of order.reworks){ + const box=node('div',undefined,'rework'); + box.append(node('b',REWORK_CAUSES[r.cause]+(r.cause===REWORK_OUTSIDE?', fora da meta':'')+', '+metres(r.metres)), + node('span','Aberto por '+r.opened_name+' em '+when(r.opened_at)+(r.printed_name?', impresso por '+r.printed_name:''),'sub')); + if(r.note)box.append(node('span',r.note,'sub')); + if(r.decided_at)box.append(badge((r.authorized?'Autorizado por ':'Não autorizado por ')+r.decided_name+' em '+when(r.decided_at),r.authorized?'ok':'bad',r.decline_reason||'')); + else if(may('authorize')&&r.opened_by!==ME.email){ + const why=node('input');why.placeholder='Motivo, se não autorizar';why.setAttribute('aria-label','Motivo, se não autorizar');why.maxLength=1000; + const decide=authorized=>async()=>{ + await api('/reworks/'+r.id+'/decision',{authorized,reason:why.value}); + say(authorized?'Retrabalho autorizado.':'Retrabalho não autorizado.');await load();}; + const row=node('div',undefined,'decide'); + row.append(button('Autorizar',decide(true),'btn pri'),why,button('Não autorizar',decide(false),'btn ghost')); + box.append(row); + }else box.append(badge('Aguardando a autorização de um administrador','warn')); + section.append(box); + } + return section; +} +// Histórico: the newest first, the order's arrival last. +function historyView(order,rows,view){ + const list=node('ol',undefined,'hist'); + const entry=(title,who,at,reason)=>{ + const li=node('li'),text=node('span'); + text.append(node('b',title),node('span',who+(reason?': '+reason:''),'sub')); + const time=node('time',when(at));time.dateTime=at; + li.append(node('i'),text,time);return li; + }; + for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state), + r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason)); + for(const item of order.snapshot.items){ + if(item.residue_accepted_at)list.append(entry('Resíduo aceito','cliente',item.residue_accepted_at, + item.residue_accepted+' pontos')); + if(item.stroke_choice_at)list.append(entry('Traço fino aceito','cliente',item.stroke_choice_at, + item.stroke_choice==='client_c3'?'proteger chapado (C3)':'imprimir assim (C1)')); + } + list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento': + paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site', + order.created_at,paidOutside(order)?order.payment.note:'')); + view.replaceChildren(list); +} + + diff --git a/web/kanban.html b/web/kanban.html index 5308ad6..348298f 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -307,4 +307,4 @@
- + diff --git a/web/kanban.js b/web/kanban.js index e8a4a5b..d82ff59 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -691,536 +691,6 @@ function render(){ if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();} } -// ---- Production board ---------------------------------------------------- - -function printState(order){ - if(order.state==='imp'||order.state==='rev')return {text:'Final aprovado',tone:'ok'}; - if(order.state==='fin')return {text:'Concluído',tone:'ok'}; - if(order.state==='cor')return {text:'Aguardando o cliente',tone:''}; - if(finalDone(order))return {text:'Final aprovado',tone:'ok'}; - if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'}; - const rows=order.print_files||[], items=order.snapshot.items.length; - const ready=rows.filter(r=>r.status==='ready').length; - if(rows.some(r=>r.status==='failed'||r.timed_out))return {text:'Falhou ao gerar',tone:'warn'}; - if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''}; - if(ready===items)return {text:'Falta aprovar o final',tone:'warn'}; - if(rows.some(r=>r.status==='manual'||r.status==='failed')) - return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'}; - return {text:'Sem arquivo gerado',tone:'warn'}; -} -const stalled=order=>!!order.late; -// "Aguardando contato": a word with the customer is needed before printing. -// A mark on the card, not a stage; a finished order no longer needs it. -const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin'; -const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since); -// The print proof (app/proof.py): asked for at checkout, or an order above 10 m. -// The room marks "Prova OK" once it is checked; without it, no Finalizado. -const PROOF_ABOVE_METRES=10; -const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.'; -const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES; -const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent; -// The proof card (app/proof.py): the order's own card waits outside the queue -// for its answer; an order from before the cards has none. -const waitingProof=order=>!!order.proof_card&&!order.proof_card.proof_result&&!order.proof_ok_at; -const proofRejected=order=>order.proof_card?.proof_result==='rejected'&&!order.proof_ok_at; -async function proofAnswer(order,result,reason=''){ - await api('/orders/'+order.id+'/proof-answer',{result,reason});await load(); - say(result==='ok'?'Prova OK: o pedido #'+order.proof_parent.number+' entra na fila.':'Prova reprovada: o pedido #'+order.proof_parent.number+' voltou para Arte recebida.'); -} -function proofReject(order){ - const reason=node('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=3; - formDialog('Prova reprovada',{host:$('drawer'),label:'Reprovar a prova',tone:'red', - text:'O pedido #'+order.proof_parent.number+' volta para Arte recebida com o motivo, e este card de prova encerra.', - fields:[field('Motivo',reason)],onsave:async()=>{await proofAnswer(order,'rejected',reason.value);}}); -} -const TREATED_NOTE='O arquivo final foi preparado pela equipe, não é a arte que o cliente mandou.'; -// Mirrored by the customer (UV only, web/site-pdf.js): the room checks it before printing. -const mirroredItem=item=>!!item.production?.sources?.some(source=>source.mirrored); -const MIRROR_NOTE='O cliente espelhou a arte: confira antes de imprimir'; -// Residue dots under 2 mm the customer accepted printing (Dropstar, 2026-10-29). -const residueNote=item=>{const many=item.residue_accepted>1; - return item.residue_accepted+(many?' pontos menores':' ponto menor')+' que 2 mm, que '+(many?'podem':'pode')+' se perder no recorte';}; -const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imprimir com '+residueNote(item)); -// Two places per machine in Imprimindo (app/machines.py): the first to come -// in is printing, the next is being ripped meanwhile. -const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'], - ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']}; -// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30): -// "parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last from -// the hot folder while the one before it prints. -function partsStep(order){ - const hot=order.hot;if(!hot||hot.parts<2)return null; - const n=hot.parts, t=hot.taken; - if(!t)return ['Parte 1/'+n+' na hot folder','wait']; - if(t===1)return ['Parte 1/'+n+' ripando','rip']; - return ['Parte '+(t-1)+'/'+n+' imprimindo · '+t+'/'+n+' ripando','live']; -} -async function proofOk(order){ - await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load(); -} -// Where an order came from (Dropstar's rule D-21): every card says it. -const ORIGINS={site:'Site',dropflow:'Dropflow',atendimento:'Atendimento'}; -const ORIGIN_NOTE='Origem do pedido'; -const originTag=order=>{const t=node('span',ORIGINS[order.origin]||order.origin,'origin');t.title=ORIGIN_NOTE;return t;}; -// The board's filters: one choice per kind, and the kinds combine (Têxtil on -// máquina2, waiting for contact). An empty choice is "all". -const FILTER_TESTS={ - site:o=>o.origin==='site', - dropflow:o=>o.origin==='dropflow', - atendimento:o=>o.origin==='atendimento', - textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'||i.mode==='premium'), - uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'), - entrega:o=>!!o.snapshot.destination, - retirada:o=>!o.snapshot.destination, - parados:stalled, - atrasados:stalled, - contato:waitingContact, - prova:proofPending, - manual:o=>['rec','tra'].includes(o.state)&&!finalDone(o)&&(o.print_files||[]).some(r=> - (r.status==='manual'||r.status==='failed')&&!(o.corrections||[]).some(f=>f.item_index===r.item_index)), -}; -function matches(order,f=boardFilter){ - // A cancelled order shows only under "Cancelados", and only there. - if(!!order.cancelled_at!==(f.status==='cancelados'))return false; - return Object.values(f).every(key=>!key||key==='cancelados'|| - (key.startsWith('m:')?order.machine?.id===key.slice(2):FILTER_TESTS[key](order))); -} -// What each choice would show: orders in progress, or every cancelled one. -const filterCount=f=>board.orders.filter(o=>(f.status==='cancelados'||o.state!=='fin')&&matches(o,f)).length; -// The kinds of filter: [value, label in the panel, label on the tag]. The -// product is the segment beside the button, not in the panel. -function filterKinds(){ - const kinds=[ - {key:'delivery',label:'Envio',options:[['entrega','Entrega'],['retirada','Retirada']]}, - {key:'origin',label:'Origem',options:Object.entries(ORIGINS)}, - {key:'status',label:'Situação',options:[['atrasados','Fora do tempo aceitável','Atrasados'], - ['contato','Aguardando contato'],['prova','Prova a conferir'],['manual','Preparar à mão'],['cancelados','Cancelados']]}]; - // A machine, when there is more than one to tell apart. - const machines=(board.machines||[]).filter(m=>m.active||m.open_orders); - if(machines.length>1)kinds.unshift({key:'machine',label:'Máquina',options:machines.map(m=> - ['m:'+m.id,m.name+(m.limit_metres&&m.open_metres>m.limit_metres?' · acima do limite':''),m.name])}); - return kinds; -} -const PRODUCTS=[['','Todos'],['textil','Têxtil'],['uv','UV']]; -const xIcon=()=>svgIcon(IC.close,'i s'); -function openFilters(){ - const pop=$('filter-pop'); - const close=node('button',undefined,'btn sq ghost right');close.type='button';close.setAttribute('aria-label','Fechar filtros'); - close.append(svgIcon(IC.close,'i m'));close.onclick=closeFilters; - const head=node('div',undefined,'pophead');head.append(node('b','Filtros'),close); - const groups=filterKinds().map(kind=>{ - const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts'); - for(const [value,text] of kind.options){ - const b=node('button',text,'fopt');b.type='button';b.dataset.kind=kind.key;b.dataset.value=value; - b.append(node('span','','n')); - // A second click on the choice in use takes it off. - b.onclick=()=>{boardFilter[kind.key]=boardFilter[kind.key]===value?'':value;renderBoard();}; - opts.append(b); - } - group.append(node('span',kind.label),opts);return group; - }); - const clear=node('button','Limpar filtros','btn ghost');clear.type='button';clear.onclick=clearFilters; - const foot=node('div',undefined,'popfoot');foot.append(clear,node('span','','lbl right')); - pop.replaceChildren(head,...groups,foot);pop.hidden=false;$('filter-btn').setAttribute('aria-expanded','true'); - filterCounts();pop.querySelector('.fopt')?.focus(); -} -function closeFilters(){$('filter-pop').hidden=true;$('filter-btn').setAttribute('aria-expanded','false');} -function clearFilters(){for(const key in boardFilter)if(key!=='product')boardFilter[key]='';renderBoard();} -// Each choice says how many orders it would show with the others kept. -function filterCounts(){ - const pop=$('filter-pop'); - for(const b of pop.querySelectorAll('.fopt')){ - b.classList.toggle('on',boardFilter[b.dataset.kind]===b.dataset.value); - b.setAttribute('aria-pressed',String(boardFilter[b.dataset.kind]===b.dataset.value)); - b.querySelector('.n').textContent=String(filterCount({...boardFilter,[b.dataset.kind]:b.dataset.value})); - } - const shown=filterCount(boardFilter); - pop.querySelector('.popfoot .lbl').textContent=plural(shown,'pedido','pedidos'); -} -// The product segment, the filters in use as tags beside the button, and the -// button's count. -function renderFilters(){ - const kinds=filterKinds(); - // A choice that is gone (a machine deleted or switched off) is dropped. - for(const key in boardFilter){if(key==='product')continue;const kind=kinds.find(k=>k.key===key); - if(boardFilter[key]&&!kind?.options.some(([value])=>value===boardFilter[key]))boardFilter[key]='';} - $('product-seg').replaceChildren(...PRODUCTS.map(([value,text])=>{ - const b=node('button',text,boardFilter.product===value?'on':'');b.type='button'; - b.setAttribute('aria-pressed',String(boardFilter.product===value)); - b.append(node('span',String(filterCount({...boardFilter,product:value})),'n')); - b.onclick=()=>{boardFilter.product=value;renderBoard();};return b;})); - const used=kinds.filter(k=>boardFilter[k.key]); - const tags=used.map(kind=>{ - const [,text,tag]=kind.options.find(([value])=>value===boardFilter[kind.key]); - const b=node('button',tag||text,'ftag');b.type='button'; - b.setAttribute('aria-label','Tirar o filtro '+(tag||text)); - const x=node('span',undefined,'x');x.append(xIcon());b.append(x); - b.onclick=()=>{boardFilter[kind.key]='';renderBoard();};return b;}); - if(used.length>1){const all=node('button','Limpar','btn ghost');all.type='button';all.onclick=clearFilters;tags.push(all);} - $('filter-tags').replaceChildren(...tags); - $('filter-count').hidden=!used.length;$('filter-count').textContent=String(used.length); - const all=used.length+(boardFilter.product?1:0);$('filter-dot').hidden=!all;$('filter-dot').textContent=String(all); - $('filter-btn').classList.toggle('on',used.length>0); - if(!$('filter-pop').hidden)filterCounts(); -} -// Each column's mark (the design canvas): what happens in that stage. -const GLYPH={ - rec:'M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32Zm0,16V152h-28.7A15.86,15.86,0,0,0,168,156.69L148.69,176H107.31L88,156.69A15.86,15.86,0,0,0,76.69,152H48V48Zm0,160H48V168H76.69L96,187.31A15.86,15.86,0,0,0,107.31,192h41.38A15.86,15.86,0,0,0,160,187.31L179.31,168H208v40ZM90.34,125.66a8,8,0,0,1,11.32-11.32L120,132.69V72a8,8,0,0,1,16,0v60.69l18.34-18.35a8,8,0,0,1,11.32,11.32l-32,32a8,8,0,0,1-11.32,0Z', - tra:'M224,128a8,8,0,0,1-8,8H128a8,8,0,0,1,0-16h88A8,8,0,0,1,224,128ZM128,72h88a8,8,0,0,0,0-16H128a8,8,0,0,0,0,16Zm88,112H128a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16ZM82.34,42.34,56,68.69,45.66,58.34A8,8,0,0,0,34.34,69.66l16,16a8,8,0,0,0,11.32,0l32-32A8,8,0,0,0,82.34,42.34Zm0,64L56,132.69,45.66,122.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Zm0,64L56,196.69,45.66,186.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Z', - imp:'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', - cor:'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', - rev:'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', - fin:'M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z'}; -const orderMetres=o=>o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0); -// On a phone the board shows one stage at a time, picked from the chips above it. -let phoneCol='rec'; -// Atrasados (front 11): the cards past the stage limit, with the person -// responsible for that column, above the board. -function renderLatebar(){ - const bar=$('latebar'); - // The top strip is for production delays. A pickup waiting in Finalizado - // keeps its yellow/red card and is counted in Números; it does not push - // every historical finished order across the top of the board. - const late=board.orders.filter(o=>!o.cancelled_at&&!isTest(o)&&o.late&&o.state!=='fin') - .sort((a,b)=>(b.state_hours||0)-(a.state_hours||0)); - if(!late.length){bar.hidden=true;bar.replaceChildren();return;} - bar.hidden=false; - const head=node('b','Atrasados ('+late.length+')');bar.replaceChildren(head); - late.slice(0,10).forEach(o=>{ - const chip=node('button',undefined,'latechip'+(o.late==='bad'?' bad':'')); - chip.type='button';chip.append(node('i'),node('span','#'+o.number+' · '+board.states[o.state])); - chip.title=(o.state_hours??'?')+' h nesta etapa · limite '+(o.limit_hours??'?')+ - ' h · responsável: '+(o.limit_by||'—'); - chip.onclick=()=>openPanel(o.id);bar.append(chip); - }); - if(late.length>10)bar.append(node('span','+'+(late.length-10),'lbl')); - if(may('manage'))bar.append(button('Editar tempos',()=>stageLimitsDialog(),'btn ghost')); -} -function renderBoard(){ - renderLatebar(); - renderFilters(); - const active=board.orders.filter(o=>['rec','tra','imp'].includes(o.state)&&!o.cancelled_at); - const open=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length; - $('board-summary').textContent=plural(open,'pedido','pedidos')+', '+metres(active.reduce((s,o)=>s+orderMetres(o),0))+' em produção'; - const filtered=Object.entries(boardFilter).some(([key,value])=>value&&key!=='product')||!!boardFilter.product; - $('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{ - const column=node('section',undefined,'col');column.dataset.state=state;column.setAttribute('aria-label',title); - // Working columns are queues; Finalizado shows the most recently ready order first. - const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>state==='fin' - ? new Date(b.finished_at||b.updated_at)-new Date(a.finished_at||a.updated_at)||b.id.localeCompare(a.id) - : queueKey(a)-queueKey(b)||a.number-b.number); - const head=node('header',undefined,'colhead'); - head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':''))); - const text=node('span',undefined,'coltx');text.append(node('h2',title)); - if(state!=='fin')text.append(node('span',orders.length?metres(orders.reduce((s,o)=>s+orderMetres(o),0)):'vazio','colm')); - head.append(text); - // The print queue's files, all at once, to import into FlexiPRINT. - if(state==='tra'&&may('print')&&orders.length){ - const all=node('button',undefined,'colbtn tip-l');all.type='button';all.setAttribute('aria-label','Baixar os arquivos da fila'); - all.dataset.tip='Baixar os arquivos finais de todos os pedidos da fila, para o FlexiPRINT';all.append(svgIcon(IC.download,'i m')); - all.onclick=async()=>{all.disabled=true;try{await downloadQueue();}catch(e){say(e.message,true);}finally{all.disabled=false;}}; - head.append(all); - } - // Finished orders are a recent window, not the whole history: the count is the whole. - head.append(node('span',String(state==='fin'&&!filtered?Math.max(board.finished_total||0,orders.length):orders.length),'coln')); - column.append(head); - // The phone's line over the cards: this stage's metres and the session's machine. - const sum=node('div',undefined,'msum');const total=node('span'); - total.append(node('b',state==='fin'?plural(orders.length,'pedido','pedidos'):metres(orders.reduce((t,o)=>t+orderMetres(o),0))),state==='fin'?' recentes':' nesta etapa'); - sum.append(total); - if(myMachine()){const m=node('span',undefined,'right mcell');m.append(node('i',undefined,'mdot'),'Máquina ',node('b',myMachine().name));sum.append(m);} - column.append(sum); - if(state==='tra'&&may('print')&&orders.length){ - const dl=button('Baixar os arquivos da fila',downloadQueue,'btn mdl');dl.prepend(svgIcon(IC.download,'i m'));column.append(dl);} - if(state==='imp')column.append(...printingLanes(orders)); - else if(state==='fin')column.append(...orders.map(miniCard)); - else column.append(...orders.map((o,i)=>card(o,state==='tra'?queuePlace(o,orders):null))); - if(state==='fin'&&finishedMore&&!filtered){ - const left=Math.max(0,(board.finished_total||0)-orders.length); - const more=node('button',left>50?'Ver mais 50 anteriores':left?'Ver os '+left+' anteriores':'Ver anteriores','moreold');more.type='button'; - more.onclick=async()=>{more.disabled=true;try{await loadOlderFinished();}catch(e){say(e.message,true);more.disabled=false;}}; - column.append(more); - } - // Dragging only goes forward to the next stage. Going back or asking for a - // correction needs a reason, so those happen in the order panel. - column.ondragover=e=>{ - if(dragging?.state===state&&state!=='fin'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;} - if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target'); - if(state==='imp')markLane(column,laneAt(column,e.clientY));}; - column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');markLane(column,null);clearDrop();}}; - column.ondrop=async e=>{e.preventDefault();column.classList.remove('target'); - const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain')); - const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null); - if(!order)return; - try{ - if(order.state!==state)await (state==='imp'?pullTo(order,machine):move(order,state,'',machine)); - else if(state!=='fin')await reorder(order,column,e.clientY); - }catch(error){say(error.message,true);} - finally{clearDrop();}}; - return column; - })); - const cols=[...$('kan').children]; - if(!board.states[phoneCol])phoneCol='rec'; - $('col-tabs').replaceChildren(...cols.map(col=>{ - const st=col.dataset.state, on=st===phoneCol; - const b=node('button',undefined,'mtab'+(on?' on':''));b.type='button';b.setAttribute('role','tab');b.setAttribute('aria-selected',String(on)); - b.append(svgIcon(GLYPH[st],'sg'+(st==='cor'?' cor':'')),board.states[st],node('span',col.querySelector('.coln').textContent,'n')); - b.onclick=()=>{phoneCol=st;renderBoard();$('col-tabs').querySelector('.on')?.scrollIntoView({inline:'nearest',block:'nearest'});}; - return b;})); - for(const col of cols)col.classList.toggle('pick',col.dataset.state===phoneCol); -} -// Imprimindo, one lane per machine (app/machines.py): its name and places, -// the order printing, the one ripping, then its free place. Every active -// machine has its lane, so a card dragged from the queue can be dropped on -// the machine it goes to print on. -function printingLanes(orders){ - const cap=board.printing_cap||2, mine=myMachine()?.id; - const filtered=Object.values(boardFilter).some(Boolean); - const out=[]; - const list=(board.machines||[]).filter(m=>m.active||orders.some(o=>o.machine?.id===m.id)); - for(const m of list){ - const here=orders.filter(o=>o.machine?.id===m.id) - .sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1)); - // Filtered, a lane with nothing to show stays out; unfiltered, the places count every order. - if(filtered&&!here.length)continue; - const n=filtered?here.length:Math.max(m.states?.imp||0,here.length); - const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));lane.dataset.machine=m.id; - const load=n>cap?'acima do limite':n>=cap?'cheia':plural(cap-n,'vaga','vagas'); - lane.append(svgIcon(IC.printer,'i s'),node('b',m.name)); - // The machine's sheet opens here; an alert due shows a warning dot with its text. - const alerts=m.alerts||[]; - if(alerts.length){const mark=node('i',undefined,'lanealert');mark.title=alerts.map(a=>a.text).join(' · '); - mark.setAttribute('aria-hidden','true');lane.append(mark);} - lane.append(node('span',(m.id===mine?'sua máquina · ':'')+load)); - lane.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':''); - lane.tabIndex=0;lane.setAttribute('role','button');lane.setAttribute('aria-label','Ficha da '+m.name); - const openSheet=()=>openMachineSheet(m.id); - lane.onclick=openSheet; - lane.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();openSheet();}}; - out.push(lane,...here.map(o=>{const c=card(o);c.dataset.machine=m.id;return c;})); - if(!filtered&&n1?plural(cap-n,'vaga livre','vagas livres')+' na '+m.name:'Vaga livre na '+m.name);out.push(slot); - } - } - // An order whose machine is gone or off still shows. - const loose=orders.filter(o=>!list.some(m=>m.id===o.machine?.id)); - if(loose.length){const lane=node('div',undefined,'lanehead');lane.append(svgIcon(IC.printer,'i s'),node('b','Sem máquina'));out.push(lane,...loose.map(o=>card(o)));} - return out; -} -// The machine lane under the pointer in Imprimindo: the last lane head above it. -function laneAt(column,y){ - let found=null; - for(const el of column.querySelectorAll('[data-machine]')){ - if(el.getBoundingClientRect().top<=y)found=el.dataset.machine; - } - return found||column.querySelector('.lanehead[data-machine]')?.dataset.machine||null; -} -function markLane(column,id){ - for(const l of column.querySelectorAll('.lanehead,.freeslot,.card'))l.classList.toggle('droplane',!!id&&l.dataset.machine===id); -} -// A card's place in the print queue, among the orders of its product (a -// textile machine pulls the next textile order). -const uvOrder=o=>o.snapshot.items.some(i=>i.mode.startsWith('uv')); -// An order waiting for its proof is not in the queue yet (app/proof.py). -const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)&&!waitingProof(o)).indexOf(order)+1; -// An operator's test order: no payment, no Tiny. -const isTest=order=>order.payment?.provider==='teste'; -const shortAgo=value=>ago(value).replace(/^há /,''); -// What happens next with the order, said on its card, and in what tone: -// act (someone has to do it now), live (printing), rip (ripping), busy (the -// system is working) or wait (nothing to do here). -function nextStep(order,place){ - if(order.cancelled_at)return ['Cancelado','wait']; - if(order.state==='cor')return ['Esperando o cliente','wait']; - // The proof card waits for its answer; its order, outside the queue, for that. - if(order.proof_parent&&order.state==='rev')return ['Responder a prova','act']; - if(order.state==='tra'&&waitingProof(order))return ['Aguardando prova','wait']; - if(order.state==='rev')return ['Conferir a folha','act']; - if(order.state==='imp')return partsStep(order)||(order.printing?PRINTING[order.printing].slice(0,2):['Na máquina','wait']); - if(order.state==='tra'){ - // The operator whose machine prints this product pulls the first one. - const m=(board.machines||[]).find(x=>x.id===myMachine()?.id); - const fits=!m?.products?.length||order.snapshot.items.some(i=>m.products.includes(i.mode)); - if(place===1&&m&&fits&&mayMove('tra','imp'))return ['Puxar da fila','act']; - return [place?place+'º na fila':'Na fila','wait']; - } - const p=printState(order); - if(p.text==='Gerando arquivo…')return ['Gerando o arquivo','busy']; - if(p.text==='Falta aprovar o final')return ['Aprovar o final','act']; - if(p.text==='Correção recebida')return ['Conferir correção','act']; - if(p.text==='Final aprovado')return ['Pronto para a fila','act']; - return [p.text,'act']; -} -// Everything a card has to say beyond its stage, the most urgent first; the -// card shows the first and how many more, and all of them on hover. -function cardFlags(order){ - const s=order.snapshot, out=[]; - if(order.cancelled_at)return [['bad','Cancelado','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason]]; - const live=order.state!=='fin'; - // A stalled order says so in red where its time is, not as a mark. - const redo=(order.reworks||[]).filter(r=>r.authorized!==false); - if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]); - if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]); - if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]); - if(order.snapshot.treatment){ - const n=Number(order.snapshot.treatment.arts)||1; - out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'), - 'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']); - } - if(order.snapshot.redesign){ - const n=Number(order.snapshot.redesign.arts)||1; - out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'), - 'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 h']); - } - if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]); - if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]); - if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]); - if(live&&proofPending(order)&&!order.proof_card)out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']); - // The grade rule set in the Site tab flagged this order for the designer. - if(!order.proof_parent&&s.grade_flags?.aviso!=null) - out.push(['warn','Nota '+s.grade_flags.aviso+': conferir a arte', - 'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir']); - if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']); - const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0); - if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]); - if(order.treated)out.push(['','Tratada',TREATED_NOTE+' Aprovado por '+order.treated.by+'.']); - if(live&&needsProof(order)&&order.proof_ok_at)out.push(['','Prova OK','Prova conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at)]); - if(isTest(order))out.push(['','Teste','Pedido de teste: sem pagamento, não vai ao Tiny']); - return out; -} -function flagNode(flags){ - if(!flags.length)return null; - const [tone,text]=flags[0]; - const f=node('span',text,'flag tip-l'+(tone?' '+tone:''));f.dataset.tip=flags.map(x=>x[2]).join(' · '); - if(flags.length>1)f.append(node('span',' +'+(flags.length-1),'plus')); - return f; -} -const KIND={file:'Folha',avulsa:'Avulsa',uvfile:'Folha',uv:'Avulsa'}; -function productLine(items){ - const modes=[...new Set(items.map(i=>i.mode))]; - return SHORT[modes[0]]+(items.length>1?' ×'+items.length:'')+(modes.length>1?' +'+(modes.length-1):''); -} -// A card drags forward when this profile makes that move, or up and down -// when it sets the column's order; a card of another operator's machine does not. -function draggable(c,order){ - c.draggable=!order.cancelled_at&&!waitingProof(order)&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s))); - c.onclick=()=>openPanel(order.id); - c.onkeydown=e=>{if(e.target===c&&(e.key==='Enter'||e.key===' ')){e.preventDefault();openPanel(order.id);}}; - c.ondragstart=e=>{ - dragging=order; - e.dataTransfer.setData('text/plain',order.id); - const forward=board.transitions[order.state].filter(s=>s!=='cor'&&mayMove(order.state,s)); - for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state)); - const moves=forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou '):''; - const priority=mayReorder(order.state)?'arraste para cima ou para baixo para mudar a prioridade':''; - say(moves&&priority?moves+', ou '+priority:moves||priority,false,60000); - }; - c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');}; -} -function card(order,place){ - const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at; - const [step,tone]=nextStep(order,place); - const c=node('div',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':'')); - c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id; - const who=buyer(s); - c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step); - const top=node('span',undefined,'ctop'), info=node('span',undefined,'cinfo'); - const row=node('span',undefined,'crow'); - const late=!!order.late&&!order.cancelled_at; - const age=node('span',shortAgo(order.state_since||order.updated_at),'age'+(late?' late tip-l'+(order.late==='bad'?' late2':''):'')); - if(late)age.dataset.tip='Fora do tempo: '+(order.state_hours??'?')+' h nesta etapa · limite '+ - (order.limit_hours??'?')+' h · responsável: '+(order.limit_by||'—'); - row.append(node('span','#'+order.number,'num'),originTag(order),age); - const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title; - const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items))); - const special=specialDelivery(s); - if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);} - if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo')); - if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);} - meta.append(node('b',metres(orderMetres(order)),'mtr')); - info.append(row,name,meta); - const art=artBox(s.items,'thumb');top.append(art,info); - c.append(top); - if(order.state==='cor'&&order.correction_reason){const r=node('span',undefined,'creason');r.append(node('b','Motivo'),' '+order.correction_reason);c.append(r);} - const foot=node('span',undefined,'cfoot'), next=node('span',undefined,'next'+(tone==='wait'?' wait':'')); - if(tone==='live'){const f=node('i',undefined,'feed');f.append(node('i'),node('i'),node('i'));next.append(f);} - if(tone==='rip')next.append(node('i',undefined,'rip')); - if(tone==='busy'){const d=node('i',undefined,'dots');d.append(node('i'),node('i'),node('i'));next.append(d);} - next.append(node('span',step,'stx')); - foot.append(next); - const flag=flagNode(cardFlags(order));if(flag)foot.append(flag); - c.append(foot,cardOpenAction(order)); - draggable(c,order); - return c; -} -// Finalizado is the end of the line: what the customer still has to do, -// nothing else. A pickup waiting more than two days is said in warning. -const PICKUP_WARN_DAYS=2; -function miniCard(order){ - const c=node('div',undefined,'mini'+(order.id===openOrder?' open':''));c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id; - const who=buyer(order.snapshot); - const row=node('span',undefined,'crow');row.append(node('span','#'+order.number,'num'),node('span',metres(orderMetres(order)),'age')); - const name=node('span',who.title,'cname');name.title=who.mail||who.title; - let text,ic=IC.check,warn=false; - const days=Math.floor((Date.now()-new Date(order.updated_at))/86400000); - const special=specialDelivery(order.snapshot); - if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;} - else if(order.picked_up_at)text='Retirado'; - else if(special){text=special;ic=IC.box;} - else if(order.snapshot.destination){text='Entrega, '+order.snapshot.destination.city+'/'+order.snapshot.destination.state;ic=IC.truck;} - else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;} - else{text='Aguardando retirada';ic=IC.bag;} - const done=node('span',undefined,'done'+(warn?' warn':''));done.append(svgIcon(ic,'i s'),text); - c.append(row,name,done,cardOpenAction(order)); - c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+text); - draggable(c,order); - return c; -} -// The column's queue: payment time, unless an operator dragged the card to -// another place (queue_key, seconds like the payment time). -const queueKey=o=>o.queue_key!=null?Number(o.queue_key):new Date(o.created_at).getTime()/1000; -let dragging=null; -// Where a card dropped at this height lands: the card it goes before, if any. -function dropTarget(column,y){ - const cards=[...column.querySelectorAll('.card')].filter(c=>c.dataset.card!==dragging?.id); - return cards.find(c=>{const r=c.getBoundingClientRect();return yc.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)=> - new Date(a.finished_at||a.updated_at)-new Date(b.finished_at||b.updated_at)||a.id.localeCompare(b.id)); - const oldest=shown[0];const params=new URLSearchParams({limit:'50'}); - if(oldest){params.set('before_finished_at',oldest.finished_at||oldest.updated_at);params.set('before_id',oldest.id);} - const page=absorb(await api('/orders/finished?'+params)); - const known=new Set(board.orders.map(o=>o.id)); - const fresh=page.orders.filter(o=>!known.has(o.id)); - olderFinished.push(...fresh);board.orders.push(...fresh);finishedMore=page.has_more;renderBoard(); -} -async function move(order,state,reason='',machine=null){ - await api('/orders/'+order.id+'/move',{state,version:order.version,reason,...(machine?{machine_id:machine}:{})}); - await load(); -} - // ---- Dialogs --------------------------------------------------------------- // One kind of dialog (the design's .modal): a title, a line on what it does, @@ -1331,1184 +801,6 @@ function dropField(input,{title='Arraste o arquivo para cá',hint=''}={}){ return l; } -// ---- Phone (the design canvas' phone screens) ------------------------------- - -// Under 700 px the Kanban is the phone mockup: sections at the bottom, menus -// and filters as sheets from the bottom, the order and the quote as pages. -const PHONE=matchMedia('(max-width:700px)'); -PHONE.addEventListener('change',()=>{if(board)render();}); -// A sheet from the bottom: the grab, then what it holds. Escape or the scrim closes. -function sheet(parts,{label='',role='dialog',onclose}={}){ - const scrim=node('div',undefined,'mscrim'); - const box=node('div',undefined,'msheet');box.setAttribute('role',role);if(label)box.setAttribute('aria-label',label); - box.append(node('span',undefined,'grab'),...parts); - const entry={box,host:document.body,close(){const i=MODALS.indexOf(entry);if(i<0)return;MODALS.splice(i,1);scrim.remove();box.remove();onclose?.();}}; - scrim.onclick=()=>entry.close(); - MODALS.push(entry);document.body.append(scrim,box);return entry; -} -// A row of a phone sheet: an icon, the words, and maybe something on the right. -function mrow(d,text,fn,className='mrow',end=null){ - const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem'); - b.append(svgIcon(d),node('span',text,'mtext'),...(end?[end]:[])); - b.onclick=async()=>{try{await fn();}catch(e){say(e.message,true);}};return b; -} -// "Mais": who is signed in, the sections that do not fit the bar, the machine, -// the theme, the password and Sair. -function phoneMenu(){ - let m=null; - const go=fn=>async()=>{m.close();await fn();}; - const who=node('div',undefined,'who sheetwho'),words=node('span'); - const ava=node('span',initialsOf(ME.name||ME.email),'ava');ava.append(node('i',undefined,'pres on')); - words.append(node('b',ME.name||ME.email),node('span',(ROLE_NAMES[ME.role]||ME.role)+(myMachine()?', na '+myMachine().name:''),'sub')); - who.append(ava,words); - const rows=[]; - if(TAB_NEEDS.integrations()){const n=$('badge-integrations').textContent; - rows.push(mrow(IC.link,'Integrações',go(()=>showTab('integrations')),'mrow',n?statePill(n,'warn'):null));} - if(TAB_NEEDS.users())rows.push(mrow(IC.user,'Usuários',go(()=>showTab('users')))); - if(ME.machine_question)rows.push(mrow(IC.printer,'Trocar de máquina',go(()=>askMachine(true)),'mrow',node('span',myMachine()?.name||'','lbl'))); - const light=kanbanTheme.get()==='light'; - rows.push(mrow(light?ICON_MOON:ICON_SUN,light?'Mudar para o modo escuro':'Mudar para o modo claro',go(()=>{kanbanTheme.toggle();paintThemeToggle();}))); - rows.push(mrow(IC.key,'Trocar a senha',go(accountForm))); - rows.push(mrow(IC.logout,'Sair',go(()=>$('logout').click()),'mrow bad')); - const body=node('div',undefined,'sbody');body.append(...rows); - m=sheet([who,body],{label:'Mais',role:'menu'}); -} -// The board's filters on the phone: every kind, the product too, and how many -// orders they show. -function phoneFilters(){ - const kinds=[{key:'product',label:'Produto',options:PRODUCTS.filter(([v])=>v)},...filterKinds()]; - const body=node('div',undefined,'sbody'); - const show=node('button','','btn pri');show.type='button'; - const paint=()=>{ - body.replaceChildren(...kinds.map(kind=>{ - const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts'); - for(const [value,text] of kind.options){ - const on=boardFilter[kind.key]===value; - const b=node('button',text,'fopt'+(on?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on)); - b.append(node('span',String(filterCount({...boardFilter,[kind.key]:value})),'n')); - b.onclick=()=>{boardFilter[kind.key]=on?'':value;renderBoard();paint();};opts.append(b); - } - group.append(node('span',kind.label),opts);return group;})); - show.textContent='Ver '+plural(filterCount(boardFilter),'pedido','pedidos'); - }; - const close=iconButton(IC.close,'Fechar',()=>m.close(),'mic right'); - const head=node('div',undefined,'shead');head.append(node('b','Filtros'),close); - const clear=node('button','Limpar','btn');clear.type='button';clear.onclick=()=>{for(const k in boardFilter)boardFilter[k]='';renderBoard();paint();}; - const foot=node('div',undefined,'sfoot');foot.append(clear,show); - const m=sheet([head,body,foot],{label:'Filtros'});show.onclick=()=>m.close(); - paint(); -} -$('more-nav').onclick=()=>phoneMenu(); -$('filter-open').onclick=()=>phoneFilters(); - -// ---- Order panel --------------------------------------------------------- - -// The panel's tab stays while the same order is open. -let panelTab='order'; -// A dialog sits over the order's panel when it is open, and over the page -// when it is not: opened from a card's face or the board, inside the closed -// drawer it would be invisible. -const dialogHost=()=>$('drawer').hidden?document.body:$('drawer'); -function openPanel(id){if(id!==openOrder)panelTab='order';openOrder=id;const order=board.orders.find(o=>o.id===id);$('drawer').hidden=false;renderPanel(order);renderBoard();} -function closePanel(){ - for(const m of [...MODALS])if(m.host===$('drawer'))m.close(); - openOrder=null;$('drawer').hidden=true;$('panel').replaceChildren();if(board)renderBoard(); -} -$('scrim').onclick=closePanel; -document.addEventListener('keydown',e=>{if(e.key==='Escape'&&openOrder)closePanel();}); - -function layoutPreview(production){ - const ns='http://www.w3.org/2000/svg', w=Number(production.film_width_cm), h=Math.max(1,Number(production.height_cm)); - const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img'); - svg.setAttribute('aria-label','Montagem: '+production.placements.length+' peças em '+w+' × '+h+' cm'); - const film=document.createElementNS(ns,'rect');film.setAttribute('width',w);film.setAttribute('height',h);film.setAttribute('fill','#0F1113');svg.append(film); - const colors=['#2BB6D9','#E0508F','#E9C23A','#6FD19C','#FF8B2B','#A78BFA']; - for(const p of production.placements){const r=document.createElementNS(ns,'rect'); - r.setAttribute('x',p.x_cm);r.setAttribute('y',p.y_cm);r.setAttribute('width',p.width_cm);r.setAttribute('height',p.length_cm); - r.setAttribute('fill',colors[p.source_index%colors.length]);r.setAttribute('fill-opacity','.55');svg.append(r);} - return svg; -} -function renderPanel(order){ - const token=++openToken, panel=$('panel'); - panel.dataset.order=order.id;$('drawer').dataset.order=order.id; - panel.setAttribute('aria-label','Pedido #'+order.number); - const s=order.snapshot, who=buyer(s); - // The head: who, where the order is, and what it is called. - const top=node('div',undefined,'dtop'); - const name=node('span',who.title,'dname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title; - const stage=node('span',undefined,'stage'+(order.cancelled_at?' bad':'')); - stage.append(svgIcon(order.cancelled_at?IC.ban:GLYPH[order.state]||GLYPH.rec,'sg'+(order.state==='cor'||order.cancelled_at?' cor':'')), - order.cancelled_at?'Cancelado':stateName(order.state)); - const tools=node('span',undefined,'dtools'); - const more=moreMenu(order);if(more)tools.append(more); - tools.append(iconButton(IC.close,'Fechar',closePanel)); - top.append(node('span','#'+order.number,'dnum'),name,stage,tools); - // What was paid and when, where it came from, and the codes: DTF-23 is the - // room's, in the file names, the footer and Tiny; the customer knows the other. - const sub=node('div',undefined,'dsub'); - const paid=node('span'); - // A proof card is no sale (app/proof.py): it says whose proof it is. - if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at)); - else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at): - paidOutside(order)?' pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at)); - const code=node('span',undefined,'chip'); - code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido')); - const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente'; - sub.append(paid,node('span','Entrou pelo '+(ORIGINS[order.origin]||order.origin)),code,theirs); - if(s.coupon && !order.proof_parent) - sub.append(badge('Cupom '+s.coupon.code,'','Desconto de '+money(s.coupon.discount_cents))); - if(s.grade_flags?.aviso!=null && !order.proof_parent) - sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn', - 'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir')); - if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny')); - if(s.items.some(i=>i.mode==='premium'))sub.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo')); - if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at))); - const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas'); - const at=FLOW.indexOf(order.state); - for(const [i,state] of FLOW.entries()){const li=node('li',board.states[state]); - if(at>=0&&i{panelTab=key;paintTabs();};tabs.append(b); - } - const paintTabs=()=>{for(const b of tabs.children){const on=b.dataset.ptab===panelTab;b.classList.toggle('on',on);b.setAttribute('aria-selected',String(on));} - for(const [key,view] of Object.entries(views))view.hidden=key!==panelTab;}; - paintTabs(); - body.append(tabs,...Object.values(views)); - // On the phone the order is one page; its files and history open as sheets. - let fileRows=null,historyRows=null; - const mbtns=node('div',undefined,'mbtns phone'); - const zap=whatsappLink(s.customer.zap); - if(zap){const a=node('a','WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i m'));mbtns.append(a);} - const sheetOf=(title,fill)=>()=>{const box=node('div',undefined,'sbody pad');fill(box); - const m=sheet([sheetHead(title,()=>m.close()),box],{label:title});}; - const files=node('button','Arquivos','btn');files.type='button';files.onclick=sheetOf('Arquivos',box=>fileRows?filesView(order,fileRows,box):box.append(node('p','Carregando…','lbl'))); - const hist=node('button','Histórico','btn');hist.type='button';hist.onclick=sheetOf('Histórico',box=>historyRows?historyView(order,historyRows,box):box.append(node('p','Carregando…','lbl'))); - mbtns.append(files,hist);body.append(mbtns); - // A re-render keeps where the body was scrolled. - const scrolled=panel.querySelector('.dbody')?.scrollTop||0; - panel.replaceChildren(mhead,head,body);body.scrollTop=scrolled; - - api('/orders/'+order.id+'/files').then(rows=>{if(token!==openToken)return;fileRows=rows;filesView(order,rows,views.files); - tabs.querySelector('[data-ptab=files] .n').textContent=rows.length?String(rows.length):'';}).catch(e=>say(e.message,true)); - api('/orders/'+order.id+'/history').then(rows=>{if(token===openToken){historyRows=rows;historyView(order,rows,views.history);}}).catch(e=>say(e.message,true)); -} -// A phone sheet's title line with its close button. -function sheetHead(title,close){const h=node('div',undefined,'shead');h.append(node('b',title),iconButton(IC.close,'Fechar',close,'mic right'));return h;} -// The order's own menu: the rare things, some of them destructive. -function moreMenu(order,buttonClass='btn sq ghost'){ - const items=[]; - const item=(d,text,fn,className='menuitem')=>{const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem'); - b.append(svgIcon(d,'i m'),text);b.onclick=async e=>{e.stopPropagation();menu.hidden=true;try{await fn();}catch(err){say(err.message,true);}};items.push(b);return b;}; - const menu=node('div',undefined,'menu dmenu');menu.hidden=true;menu.setAttribute('role','menu'); - if(!order.cancelled_at){ - // Undo a mistaken move: one stage back, internal reason, no customer message. - const previous=board.back?.[order.state]; - if(previous&&!waitingProof(order)&&mayMove(order.state,previous)&&mayAct(order))item(IC.back,'Voltar para '+board.states[previous],()=>backDialog(order,previous)).dataset.back=previous; - if(order.state!=='fin'&&!waitingContact(order)&&may('produce')) - item(IC.phone,'Aguardando contato',()=>contactDialog(order)).dataset.contact=''; - if(!isTest(order)&&may('rework'))item(IC.rework,'Abrir retrabalho',()=>reworkForm(order)); - if(isTest(order)&&may('manage'))item(IC.ban,'Excluir pedido de teste',async()=>{ - if(!await ask('Excluir o pedido de teste #'+order.number+'?','Ele some do Kanban, com o histórico.','Excluir pedido',{tone:'red',host:$('drawer')}))return; - await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();},'menuitem bad'); - else if(!isTest(order)&&may('cancel'))item(IC.ban,'Cancelar pedido',()=>cancelDialog(order),'menuitem bad'); - } - if(!items.length)return null; - // The destructive one apart, under a line. - const last=items.at(-1);if(last.classList.contains('bad')&&items.length>1)items.splice(-1,0,node('div',undefined,'menusep')); - menu.append(...items); - const b=iconButton(IC.more,'Mais ações',()=>{menu.hidden=!menu.hidden;b.setAttribute('aria-expanded',String(!menu.hidden)); - if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;b.setAttribute('aria-expanded','false');},{once:true});},buttonClass); - b.setAttribute('aria-haspopup','menu');b.setAttribute('aria-expanded','false'); - const wrap=node('span',undefined,'morewrap');wrap.append(b,menu);return wrap; -} -function cancelledNotice(order){ - const box=node('div',undefined,'callout bad'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.ban,'i m')); - const p=node('p');p.append(node('b','Pedido cancelado. '),order.cancel_reason,node('small','Por '+order.cancelled_by+' em '+when(order.cancelled_at))); - box.append(ico,p); - if(may('manage'))box.append(button('Excluir pedido',async()=>{ - if(!await ask('Excluir o pedido #'+order.number+' de vez?','Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.','Excluir pedido',{tone:'red',host:$('drawer')}))return; - await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load(); - },'btn quiet')); - return box; -} -function contactNotice(order,canClear){ - const box=node('div',undefined,'callout'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.phone,'i m')); - const p=node('p');p.append(node('b','Aguardando contato. '),order.contact_note,node('small',contactWho(order))); - box.append(ico,p); - const zap=whatsappLink(order.snapshot.customer.zap); - if(zap){const a=node('a','Abrir conversa','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i s'));box.append(a);} - // A proof order closes its contact wait with Prova OK, the only button - // (item 0.1). Other orders still need a way to record that contact is done. - if(canClear&&!needsProof(order))box.append(button('Contato feito',async()=>{ - await api('/orders/'+order.id+'/contact',{waiting:false});say('Contato registrado: a marca saiu do pedido #'+order.number+'.');await load();},'btn')); - return box; -} -// In correction, the customer has to be told: a message ready to send on -// WhatsApp with the reason and where to send the new file. -function correctionMessage(order){ - const reason=order.correction_reason||'', link=board.site_origin+'/conta/pedidos?order='+order.id; - return 'Olá! Aqui é da Dropstar. O seu pedido '+orderCode(order.id)+' precisa de um ajuste na arte antes da impressão'+ - (reason?': '+reason:'.')+'\n\nEnvie o arquivo corrigido por aqui: '+link; -} -function correctionActions(order,main){ - const message=correctionMessage(order), zap=whatsappLink(order.snapshot.customer.zap), out=[]; - if(zap){const a=node('a','Avisar no WhatsApp','btn lg'+(main?' pri':''));a.href=zap+'?text='+encodeURIComponent(message); - a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i m'));out.push(a);} - out.push(button('Copiar mensagem',async()=>{await navigator.clipboard.writeText(message);say('Mensagem copiada.');},'btn lg'+(main&&!zap?' pri':''))); - return out; -} -// A file the step is about: its kind, its name and what to do with it. -function fileRow(name,label,...actions){ - const row=node('div',undefined,'file'); - const ext=(String(name).split('.').pop()||'').slice(0,4).toUpperCase(); - const text=node('span',undefined,'ftext');text.append(node('b',name),node('span',label)); - row.append(node('span',ext,'fico'),text,...actions);return row; -} -const downloadFile=uid=>downloadButton('Baixar',download(uid),'btn'); -// The approved final is the way to the queue (Arte conferida): approving it, -// with the files that would be printed, or sending one. -// The contraction class of an item (item 9): the one chosen, else the one the -// browser measured. The FlexiPRINT applies it by the C1, C2 or C3 folder. -const CLASS_NOTE={C1:'traço até 4 px',C2:'traço de 5 a 19 px',C3:'traço de 20 px ou mais'}; -// A mixed sheet (item 16) where the customer chose to protect the solid areas starts at C3. -const measuredClass=item=>item.stroke_choice==='client_c3'?'C3':item.stroke_class||null; -const contractionOf=(order,index)=>order.contraction?.[index]?.class||measuredClass(order.snapshot.items[index]); -function contractionControl(order,index){ - const item=order.snapshot.items[index], now=contractionOf(order,index), chosen=order.contraction?.[index]; - const measured=(item.stroke_class?'medido '+item.stroke_class+', '+item.stroke_px+' px':'sem medida do navegador')+ - (item.stroke_choice==='client_c3'?'; o cliente escolheu proteger as áreas chapadas (C3)':''); - const editable=may('produce')&&!order.cancelled_at&&['rec','tra','cor'].includes(order.state); - if(!editable){const t=node('span',now?now+' ('+(chosen?'escolhida':measured)+')':'Sem classe');return t;} - const select=node('select',undefined,'inp sm');select.setAttribute('aria-label','Contração do item '+(index+1)); - for(const [value,text] of [['','Escolha'],['C1','C1, '+CLASS_NOTE.C1],['C2','C2, '+CLASS_NOTE.C2],['C3','C3, '+CLASS_NOTE.C3]]){ - const o=node('option',text);o.value=value;select.append(o);} - select.value=now||''; - select.onchange=async()=>{try{ - await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value||null}); - say('Contração do item '+(index+1)+': '+(select.value||'a medida do navegador')+'.');await load();} - catch(e){say(e.message,true);}}; - const box=node('span',undefined,'contr');box.append(select,node('small',chosen?'escolhida por '+chosen.by+'; '+measured:measured,'sub')); - return box; -} -// The approve step's "Está OK?": each item's class, prefilled, to confirm or change. -function contractionList(order){ - const box=node('div',undefined,'contrlist'); - order.snapshot.items.forEach((item,index)=>{ - const row=node('div',undefined,'contrrow'); - row.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+', contração':'Contração','lbl'),contractionControl(order,index)); - box.append(row);}); - return box; -} -function approveParts(order,main=true){ - if(designerPaid(order)){ - const label=order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino'; - const approve=button('Enviar arte do '+label,()=>treatDialog(order),'btn lg'+(main?' pri':'')); - approve.dataset.treat=''; - return {text:label+' pago: o designer precisa enviar o PNG do '+label+' de cada item antes da fila.', - files:null,approve,extra:[]}; - } - const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1; - const files=node('div',undefined,'files'); - if(all)ready.forEach((r,i)=>r.files.forEach((f,k)=>files.append(fileRow(f.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source]+ - (r.files.length>1?', parte '+(k+1)+' de '+r.files.length:''),downloadFile(f.upload_id))))); - const text=all?'Baixe e confira. É este arquivo que vai para a impressão.':ready.some(Boolean) - ?'Alguns itens já têm arquivo pronto; envie o arquivo preparado dos outros.' - :'Nenhum arquivo pronto para aprovar como está: envie o arquivo preparado para a impressão.'; - const upload=()=>finalDialog(order,all?ready.map(()=>null):ready); - const approve=button(all?'Aprovar arquivo final':'Enviar arquivo final',all?()=>approveReady(order,ready):async()=>upload(),'btn lg'+(main?' pri':'')); - approve.dataset.approve=''; - const extra=[]; - // In Arte recebida the art may need work first (Dropstar, 2026-10-29). - if(order.state==='rec'&&may('produce')){const t=button('Tratar a arte',async()=>treatDialog(order),'btn lg');t.dataset.treat='';extra.push(t);} - if(all)extra.push(button('Enviar outro arquivo',async()=>upload(),'btn lg')); - return {text,files:all?files:null,approve,extra}; -} -// "Próximo passo": what the order needs now, said once, with its button. -// Going back, the contact mark, rework and cancelling are in the menu above. -function nextBox(order){ - if(order.cancelled_at)return null; - const st=order.state, trans=board.transitions[st]||[]; - let title='';const body=[],main=[],more=[]; - const note=text=>body.push(node('p',text,'nnote')); - const can=to=>mayMove(st,to)&&mayAct(order); - const moveBtn=(to,label,className='btn pri lg')=>{ - // Pulling to a machine goes through the sheet's alerts first (front 1a). - const fn=to==='imp'?()=>pullTo(order,order.machine?.id||myMachine()?.id||null):()=>move(order,to); - const b=button(label||'Mover para '+board.states[to],fn,className);b.dataset.move=to;return b;}; - // The 10x15 label at Finalizado: added here so a view-only Expedição sees it - // too (the read-only branch below skips the stage blocks). - if(st==='fin'&&typeof labelReprintButton==='function'){ - const reprint=labelReprintButton(order); - if(reprint)more.push(reprint); - } - if(waitingProof(order)){ - title='Aguardando prova do #'+order.proof_card.number; - const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual'); - note(manual?'O Prumo não abriu o original. Prepare o PNG completo deste pedido; a prova será gerada automaticamente a partir dele.' - :'O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.'); - if(manual&&may('produce'))main.push(button('Preparar arquivo para a prova',()=>finalDialog(order,readyFinals(order)),'btn pri lg')); - return composeNext(title,body,main,more); - } - // A proof card in Revisão waits for its answer (Dropstar, 2026-11-03). - if(order.proof_parent&&st==='rev'){ - title='Responder a prova'; - note('Prova do pedido #'+order.proof_parent.number+'. Com a prova impressa conferida'+(order.snapshot.proof?' e o aceite do cliente':'')+', responda aqui.'); - if(may('proof')){main.push(button('Prova OK',()=>proofAnswer(order,'ok'),'btn pri lg')); - more.push(button('Prova reprovada',()=>proofReject(order),'btn quiet lg'));} - else note('Quem responde é o Vendedor, a Gestão ou o Administrador.'); - return composeNext(title,body,main,more); - } - const readOnly=!may('produce')&&!ME?.moves?.length; - const fixed=(order.corrections||[]).length>0; - if(st==='cor'){ - title=fixed?'Conferir a correção do cliente':'Esperando o arquivo novo'; - if(order.correction_reason){const p=node('p',undefined,'nnote');p.append(node('b','Motivo: '),order.correction_reason);body.push(p);} - if(!whatsappLink(order.snapshot.customer.zap))note('Sem WhatsApp no pedido: envie a mensagem para '+order.snapshot.customer.mail+'.'); - (fixed?more:main).push(...correctionActions(order,!fixed)); - } - if(readOnly){ - if(!title)title=st==='fin'?'Pedido concluído':'Com a produção'; - note('Somente consulta: seu perfil não move pedidos.'); - return composeNext(title,body,main,more); - } - const fixBtn=()=>{if(!trans.includes('cor')||!can('cor'))return; - const b=node('button','Pedir correção','btn quiet lg');b.type='button';b.dataset.move='cor';b.onclick=()=>correctionDialog(order);more.push(b);}; - const proofBtn=(className='btn lg')=>{if(!proofPending(order)||order.proof_card||!may('print'))return null; - const b=button('Prova OK',()=>proofOk(order),className);b.dataset.proof='';b.title='A prova foi impressa e conferida';return b;}; - const cannot=()=>note(!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.' - :st==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.'); - // The proof was rejected: its reason, and a new proof card when the art is fixed. - if(st==='rec'&&proofRejected(order)){ - const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p); - if(may('produce'))more.push(button('Nova prova',async()=>{await api('/orders/'+order.id+'/proof-card',{});await load();say('Nova prova criada.');},'btn lg')); - } - if(st==='rec'&&order.proof_parent){ - title=finalDone(order)?'Conferir a prova':'Gerando a prova'; - const manual=(order.print_files||[]).some(r=>r.status==='manual'); - note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual - ?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.' - :'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.'); - if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg')); - if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg')); - if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce')) - more.push(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn lg')); - return composeNext(title,body,main,more); - } - if(st==='rec'||st==='cor'){ - if(st==='rec'&&designerPaid(order)&&!treatmentDone(order)&&finalDone(order)){ - title='Enviar a arte do '+(order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino'); - note((order.snapshot.redesign?'O Ajuste Fino Redesenho foi pago.':'O Ajuste Fino foi pago.')+ - ' Envie o PNG ajustado de cada item antes de colocar o pedido na fila.'); - if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg')); - return composeNext(title,body,main,more); - } - if(!finalDone(order)&&trans.includes('tra')){ - if(st==='rec')title='Aprovar o arquivo final'; - // The designer approves every file (D-16); the others see it waiting. - if(!may('produce')){note('O Designer confere e aprova o arquivo final.');body.push(contractionList(order));} - else{ - const lead=st==='rec'||fixed, a=approveParts(order,lead); - // Item 7: open the file, then say whether it is OK. - if(st==='rec'){a.approve.classList.remove('pri');main.push(checkButton(order,'btn pri lg'));} - if(lead){if(a.files)body.push(a.files);note(a.text);body.push(contractionList(order));main.push(a.approve,...a.extra);} - else more.push(a.approve,...a.extra); - } - }else if(st==='rec'){ - title='Mandar para a fila'; - note('O arquivo final está aprovado. Na fila, o operador puxa para a máquina.'); - if(can('tra'))main.push(moveBtn('tra'));else cannot(); - // Approved already, the art can still be treated while in Arte recebida. - if(may('produce')){const t=button('Tratar a arte',async()=>treatDialog(order),'btn lg');t.dataset.treat='';more.push(t);} - } - if(st==='cor')for(const to of trans){ - if(to==='tra'&&!finalDone(order))continue; - if(can(to))(to==='tra'&&finalDone(order)?main:more).push(moveBtn(to,null,to==='tra'&&finalDone(order)?'btn pri lg':'btn lg')); - } - if(st==='rec')fixBtn(); - }else if(st==='tra'&&waitingProof(order)){ - title='Aguardando prova'; - note('O pedido entra na fila com Prova OK no card da prova #'+order.proof_card.number+'.'); - fixBtn(); - }else if(st==='tra'){ - title='Puxar para a máquina'; - note(order.machine?'Vai para a '+order.machine.name+'. O arquivo final já está aprovado.':'O arquivo final já está aprovado.'); - if(can('imp'))main.push(moveBtn('imp'));else cannot(); - const p=proofBtn();if(p)more.push(p); - fixBtn(); - }else if(st==='imp'){ - title=order.printing==='ripando'?'Ripando enquanto o anterior roda':'Terminou de imprimir?'; - note('A folha segue para o Revisor conferir.'); - if(can('rev'))main.push(moveBtn('rev'));else cannot(); - const p=proofBtn();if(p)more.push(p); - fixBtn(); - }else if(st==='rev'){ - if(proofPending(order)){ - // Finalizado waits for the proof: printing it and checking it is the next step. - title='Conferir a prova'; - note((order.snapshot.proof?'O cliente pediu uma prova: imprima, mande a foto pelo WhatsApp e, com o aceite dele, marque Prova OK.' - :'Pedido acima de 10 m: imprima a prova, confira e marque Prova OK antes de rodar o resto.')+' '+PROOF_RULE); - const p=proofBtn('btn pri lg');if(p)main.push(p); - }else{ - // Above 1 m the photo is required to finish (app/reviews.py): the main - // button takes it instead of releasing the order. - const hasPhoto=(order.reviews||[]).some(review=>review.kind==='photo'); - if(!order.proof_parent&&orderMetres(order)>1&&!hasPhoto){ - title='Tire a foto da revisão'; - note('Pedido acima de 1 m: tire a foto da revisão antes de finalizar.'); - if(may('inspect'))main.push(button('Revisar',()=>reviewDialog(order),'btn pri lg'));else cannot(); - }else{ - title='Conferir a folha impressa'; - note('Confira cores, recorte e a folha inteira contra o arquivo.'); - if(can('fin'))main.push(moveBtn('fin','Liberar para Finalizado'));else cannot(); - } - } - fixBtn(); - }else if(st==='fin'){ - const dest=order.snapshot.destination; - if(isPickup(order)){ - // Pickup (item 14): the receipt, and "Retirado", with the signed receipt's photo. - const paper=button('Recibo',()=>window.open('/api/operator/orders/'+order.id+'/receipt','_blank','noopener'),'btn lg'); - paper.title='Abrir o recibo de retirada para imprimir de novo';paper.prepend(svgIcon(IC.file,'i m')); - if(order.picked_up_at){ - title='Retirado';note('Em '+when(order.picked_up_at)+', entregue por '+order.picked_up_by+'.'); - if(order.picked_up_photo){const b=downloadButton('Foto do recibo',download(order.picked_up_photo),'btn lg');more.push(b);} - more.push(paper); - }else{ - title='Entregar ao cliente';note('O cliente retira na fábrica. O recibo vai junto, para a assinatura.'); - if(may('deliver')){const b=node('button','Marcar retirado','btn pri lg');b.type='button';b.dataset.pickedUp='';b.onclick=()=>pickupDialog(order);main.push(b);} - more.push(paper); - } - }else{ - title='Pedido concluído'; - note(dest?'Vai para entrega em '+dest.city+'/'+dest.state+'.':'Pedido concluído.'); - } - } - return composeNext(title,body,main,more); -} -function composeNext(title,body,main,more){ - const box=node('section',undefined,'nextbox');box.setAttribute('aria-label','Próximo passo'); - const head=node('div');head.append(node('span','Próximo passo','lbl'),node('h3',title)); - box.append(head,...body); - if(main.length||more.length){const acts=node('div',undefined,'nact');acts.append(...main,...more);box.append(acts);} - return box; -} -// ---- The order's dialogs: each a form.reason, so its field is the order's. -function correctionDialog(order){ - const text=node('textarea');text.placeholder='Ex.: o logo da manga veio em 72 DPI';text.maxLength=1000;text.required=true; - text.setAttribute('aria-label','Motivo da correção'); - formDialog('Pedir correção do pedido #'+order.number,{host:$('drawer'),className:'reason',width:540, - text:'O pedido vai para Correção. Depois, a mensagem para o cliente fica pronta para mandar no WhatsApp.', - fields:[field('Motivo',text,'O cliente vê este motivo na mensagem.')],label:'Enviar para correção',tone:'red', - onsave:async()=>{await move(order,'cor',text.value.trim());}}); -} -function backDialog(order,previous){ - const why=node('input');why.placeholder='Motivo';why.setAttribute('aria-label','Motivo do retorno');why.required=true;why.maxLength=1000; - formDialog('Voltar para '+board.states[previous]+'?',{host:$('drawer'),className:'reason',width:500, - text:'Para desfazer um movimento feito por engano. O cliente não é avisado e os arquivos aprovados continuam.', - fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Voltar para '+board.states[previous], - onsave:async()=>{await move(order,previous,why.value.trim());}}); -} -function contactDialog(order){ - const what=node('input');what.placeholder='Ex.: confirmar se a arte vai na frente ou nas costas';what.setAttribute('aria-label','O que precisa ser combinado'); - what.required=true;what.minLength=3;what.maxLength=500; - formDialog('Aguardando contato',{host:$('drawer'),className:'reason',width:540, - text:'O card fica marcado até alguém registrar o contato feito.', - fields:[field('O que precisa ser combinado com o cliente',what)],label:'Marcar aguardando contato', - onsave:async()=>{await api('/orders/'+order.id+'/contact',{waiting:true,note:what.value.trim()});say('Pedido #'+order.number+' aguardando contato.');await load();}}); -} -function cancelDialog(order){ - const why=node('textarea');why.placeholder='Ex.: cliente desistiu, vai refazer a arte';why.setAttribute('aria-label','Motivo do cancelamento'); - why.required=true;why.minLength=3;why.maxLength=1000; - formDialog('Cancelar o pedido #'+order.number+'?',{host:$('drawer'),className:'reason',width:520, - text:'O pedido sai do quadro e fica em Cancelados, com o pagamento e o histórico. O valor fica como crédito do cliente, no controle financeiro, e o pedido no Tiny se cancela lá.', - fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Cancelar pedido',tone:'red', - onsave:async()=>{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}}); -} -function pickupDialog(order){ - const photo=node('input');photo.accept='image/*';photo.setAttribute('aria-label','Foto do recibo assinado'); - formDialog('Marcar o pedido #'+order.number+' como retirado',{host:$('drawer'),width:540, - text:'Quem retirou assina o recibo. A foto dele fica no pedido.', - fields:[dropField(photo,{title:'Foto do recibo assinado',hint:'Opcional. JPG, PNG ou HEIC.'})],label:'Confirmar retirada', - onsave:async()=>{ - const uid=photo.files[0]?await dtfUpload(photo.files[0],{api,startPath:'/orders/'+order.id+'/pickup-uploads', - scope:'operator:pickup:'+order.id,progress:text=>say(text)}):null; - await api('/orders/'+order.id+'/picked-up',{photo:uid}); - await load();say('Pedido #'+order.number+' marcado como retirado.'); - }}); -} -// Pickup or delivery, from the freight the customer chose. -const isPickup=order=>order.snapshot.freight?.service==='pickup'; -// An internal order stays in house, and a sale can travel with the customer's -// clothing order (Fase 2, front 7a.3): the card and the panel say so instead -// of "Retirada". -const specialDelivery=s=>s.kind==='interno'?'Interno':s.with_order?'Junto com o pedido de roupa nº '+s.with_order:null; -// ---- Final files: the file each item is printed from, approved by an operator. -const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index)); -const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index)); -const designerPaid=order=>!!(order.snapshot.treatment||order.snapshot.redesign); -const FINAL_SOURCE={correction:'correção do cliente',generated:'arquivo gerado',original:'original'}; -const FINAL_TITLE={correction:'Correção do cliente',generated:'Gerado pelo sistema',original:'Original do cliente'}; -// What the system generated for an item: one PNG, or the parts of a film -// over 15 m (item 13). An item generated before parts has just its file. -const generatedFiles=row=>row.parts?.length?row.parts:[{upload_id:row.upload_id,name:row.name}]; -// Per item, the files that can be approved as they are, or null: the -// customer's correction, or else what the system generated (or the original -// that already was one). After a correction, a generated file reproduces -// artwork nobody wants printed. -function readyFinals(order){ - const fixes=order.corrections||[]; - return order.snapshot.items.map((item,index)=>{ - const fix=fixes.find(f=>f.item_index===index); - if(fix)return fix.expired||!fix.name.toLowerCase().endsWith('.png')?null:{files:[{upload_id:fix.upload_id,name:fix.name}],name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'}; - const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready'); - if(!made)return null; - const original=made.detail?.source==='original', files=generatedFiles(made); - const names=files.length>1?files.length+' partes, '+files[0].name+' a '+files[files.length-1].name:files[0].name; - return {files,name:files[0].name,source:original?'original':'generated',label:(original?'O original (':'Gerado pelo sistema (')+names+')'}; - }); -} -// Sends final-files from a dialog that may have been opened before another -// screen approved the same files (DTF-WEB-7). A stale version gets 409 "O -// pedido mudou"; when the approval is already there, or the order left Arte -// recebida/Correção, reload and say so; true tells the caller to stop, and a -// form dialog then closes itself. Anything else is still an error, and the -// version is never resent blindly. -async function saveFinalFiles(order, files, note){ - try{ - await api('/orders/'+order.id+'/final-files',{version:order.version,files,note}); - return false; - }catch(error){ - if(error.status!==409||!String(error.message).startsWith('O pedido mudou'))throw error; - await load(); - const fresh=(board.orders||[]).find(row=>row.id===order.id); - if(fresh&&(finalDone(fresh)||!['rec','cor'].includes(fresh.state))){ - say('O arquivo final já estava aprovado.'); - return true; - } - throw error; - } -} -async function approveReady(order,ready){ - const many=ready.length>1; - if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+ - ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return; - const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', '); - if(await saveFinalFiles(order, - ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return; - await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.'); -} -// The file the operator prepared, per item; a ready file comes ticked. -function finalDialog(order,ready,{replace=false}={}){ - const fields=[]; - const inputs=order.snapshot.items.map((item,index)=>{ - const slot=node('div',undefined,'fslot'); - const label=order.snapshot.items.length>1?'Item '+(index+1)+', '+productName(item):productName(item); - slot.append(node('span',label,'lbl')); - const input=node('input');input.multiple=true;input.required=true;input.dataset.finalItem=index; - input.setAttribute('aria-label','Arquivo final, '+label); - input.accept='.png,image/png'; - const drop=dropField(input,{hint:'PNG transparente a 300 DPI, do tamanho da impressão.'}); - const file=ready[index]; - if(file){ - const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true; - use.onchange=()=>{drop.hidden=use.checked;input.required=!use.checked;}; - slot.append(checkbox('Usar: '+file.label,use));input.generated=()=>use.checked?file.files.map(f=>f.upload_id):null; - } - slot.append(drop);fields.push(slot);return input; - }); - const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;note.setAttribute('aria-label','Nota da revisão'); - const check=node('input');check.required=true;check.dataset.confirm=''; - fields.push(field('Nota',note,'Ex.: ajustei a margem e o recorte. Fica no histórico.'),checkbox('Arquivos conferidos',check)); - formDialog(replace?'Trocar o arquivo final':'Enviar o arquivo final',{host:$('drawer'),width:580,className:'finalform', - text:'Pedido #'+order.number+'. O arquivo novo passa a ser o que vai para a impressão.',note:'O anterior fica em Arquivos.', - fields,label:'Aprovar arquivo final',onsave:async()=>{ - const refs=[]; - for(const [index,input] of inputs.entries()){ - const generated=input.generated?.(); - if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;} - for(const file of input.files){ - if(!file.name.toLowerCase().endsWith('.png'))throw Error('O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'); - const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)}); - refs.push({item_index:index,upload_id:uid}); - } - } - if(await saveFinalFiles(order,refs,note.value))return; - await load();say('Arquivo final aprovado.'); - }}); -} -// "Tratar a arte" (Dropstar, 2026-10-29): where each item's file is in the -// orders folder, to open it, treat it and save it over with the same name; -// then the treated file sent here becomes the item's final, "Arte tratada". -// The browser only knows the folder's name, so each computer is told once -// where the folder is, to copy the whole path. -const TREAT_NOTE='Arte tratada'; -const FOLDER_PATH_KEY='folder-path'; -// ---- Abrir e conferir (item 7) ---------------------------------------------- - -// The print file full screen, in pieces (web/kanban-viewer.js); closed in -// Arte recebida, it asks whether the art is OK. -function checkButton(order,className='btn'){ - const b=button('Abrir e conferir',()=>openCheck(order),className);b.prepend(svgIcon(IC.eye||IC.file,'i m'));return b; -} -function cardOpenAction(order){ - const action=button('Abrir arquivo',()=>openCheck(order),'card-open'); - action.prepend(svgIcon(IC.eye||IC.file,'i s')); - // In Revisão the Revisor also has the photo/video on the card's face, beside - // the file. The click is stopped by button(), as on "Abrir arquivo". - if(order.state==='rev'&&!order.cancelled_at&&may('inspect')){ - const review=button('Revisar',()=>reviewDialog(order),'card-open'); - review.prepend(svgIcon(IC.camera,'i s')); - const row=node('span',undefined,'card-open-row');row.append(action,review); - return row; - } - if(order.state==='fin'&&typeof labelReprintButton==='function'){ - const reprint=labelReprintButton(order,'card-open'); - if(reprint){const row=node('span',undefined,'card-open-row');row.append(action,reprint);return row;} - } - return action; -} -// "Revisar" (Fase 2, front 2): the sheet's photo or a video of up to 30 s, -// taken here with the computer's or the phone's camera, or a file already -// recorded. The server names it DTF--revisao- and keeps it 180 days. -const REVIEW_VIDEO_MAX=30; -const reviewClock=s=>Math.floor(s/60)+':'+String(s%60).padStart(2,'0'); -function reviewDialog(order){ - const host=dialogHost(); - const video=node('video');video.className='reviewcam';video.muted=true;video.playsInline=true;video.autoplay=true; - video.setAttribute('aria-label','Pré-visualização da câmera'); - const timer=node('span','0:00 / 0:30','reviewtime');timer.setAttribute('aria-live','polite'); - const controls=node('div',undefined,'reviewcontrols'); - const photoBtn=node('button','Tirar foto','btn pri');photoBtn.type='button';photoBtn.setAttribute('aria-label','Tirar foto');photoBtn.setAttribute('autofocus',''); - const videoBtn=node('button','Gravar vídeo','btn');videoBtn.type='button';videoBtn.setAttribute('aria-label','Gravar vídeo'); - const input=node('input');input.type='file';input.className='vh'; - input.accept='image/jpeg,image/png,image/webp,video/mp4,video/webm,video/quicktime'; - const fileLabel=node('label',undefined,'btn');fileLabel.tabIndex=0; - fileLabel.append(svgIcon(IC.upload,'i m'),'Enviar arquivo',input); - const preview=node('div',undefined,'reviewpreview');preview.hidden=true; - const status=node('p','','reviewmsg');status.setAttribute('role','status');status.setAttribute('aria-live','polite'); - const save=node('button','Salvar revisão','btn pri');save.type='button';save.disabled=true; - const cancel=node('button','Cancelar','btn ghost right');cancel.type='button'; - controls.append(photoBtn,videoBtn,fileLabel); - let stream=null,recorder=null,recordTimer=null,chunks=[],ready=null,objectUrl=null,closed=false,recording=false,recordStart=0; - const fail=text=>{status.textContent=text;status.classList.add('bad');}; - const clear=()=>{status.textContent='';status.classList.remove('bad');}; - const endStream=()=>{ - if(recordTimer){clearInterval(recordTimer);recordTimer=null;} - if(stream){stream.getTracks().forEach(track=>track.stop());stream=null;} - }; - const cleanup=()=>{ - closed=true; - if(recorder&&recorder.state!=='inactive'){try{recorder.stop();}catch(_){}} - endStream(); - if(objectUrl){URL.revokeObjectURL(objectUrl);objectUrl=null;} - }; - function showReady(file,kind){ - ready={file,kind}; - endStream(); - video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true; - if(objectUrl)URL.revokeObjectURL(objectUrl); - objectUrl=URL.createObjectURL(file); - preview.replaceChildren(); - if(kind==='video'){ - const shot=node('video');shot.controls=true;shot.playsInline=true;shot.src=objectUrl; - shot.setAttribute('aria-label','Pré-visualização do vídeo gravado');preview.append(shot); - }else{ - const shot=node('img');shot.src=objectUrl;shot.alt='Pré-visualização da foto';preview.append(shot); - } - preview.hidden=false;save.disabled=false;clear();save.focus(); - } - function checkDuration(file){ - return new Promise((resolve,reject)=>{ - const probe=document.createElement('video');probe.preload='metadata'; - const url=URL.createObjectURL(file); - probe.onloadedmetadata=()=>{ - const seconds=probe.duration;URL.revokeObjectURL(url); - if(Number.isFinite(seconds)&&seconds>REVIEW_VIDEO_MAX+0.2) - reject(new Error('O vídeo tem mais de 30 segundos. Grave um de até 30 s ou envie outro menor.')); - else resolve(); - }; - probe.onerror=()=>{URL.revokeObjectURL(url);resolve();}; - probe.src=url; - }); - } - function stopRecording(){if(recorder&&recorder.state!=='inactive')recorder.stop();} - photoBtn.onclick=()=>{ - clear(); - const width=video.videoWidth,height=video.videoHeight; - if(!width||!height){fail('A câmera ainda não está pronta. Espere um instante.');return;} - const canvas=document.createElement('canvas');canvas.width=width;canvas.height=height; - canvas.getContext('2d').drawImage(video,0,0,width,height); - canvas.toBlob(blob=>{ - if(!blob){fail('Não foi possível tirar a foto.');return;} - showReady(new File([blob],'revisao.jpg',{type:'image/jpeg'}),'photo'); - },'image/jpeg',0.9); - }; - videoBtn.onclick=()=>{ - clear(); - if(recording){stopRecording();return;} - if(!stream){fail('A câmera não está disponível. Envie um arquivo.');return;} - const options=['video/mp4','video/webm;codecs=vp9','video/webm']; - const mime=(window.MediaRecorder&&options.find(type=>MediaRecorder.isTypeSupported(type)))||''; - try{recorder=new MediaRecorder(stream,mime?{mimeType:mime}:undefined);} - catch(_){fail('Este navegador não grava vídeo. Envie um arquivo.');return;} - const type=recorder.mimeType||mime||'video/webm'; - chunks=[];recording=true;recordStart=Date.now(); - recorder.ondataavailable=event=>{if(event.data&&event.data.size)chunks.push(event.data);}; - recorder.onstop=()=>{ - recording=false;videoBtn.textContent='Gravar vídeo'; - if(recordTimer){clearInterval(recordTimer);recordTimer=null;} - if(closed)return; - const blob=new Blob(chunks,{type});chunks=[]; - if(!blob.size){fail('Não foi possível gravar o vídeo.');return;} - showReady(new File([blob],'revisao.'+(type.includes('mp4')?'mp4':'webm'),{type}),'video'); - }; - recorder.start();videoBtn.textContent='Parar'; - const paint=()=>{ - const elapsed=Math.min(REVIEW_VIDEO_MAX,Math.floor((Date.now()-recordStart)/1000)); - timer.textContent=reviewClock(elapsed)+' / '+reviewClock(REVIEW_VIDEO_MAX); - if(elapsed>=REVIEW_VIDEO_MAX)stopRecording(); - }; - paint();recordTimer=setInterval(paint,250); - }; - input.onchange=async()=>{ - const file=input.files[0];if(!file)return; - clear(); - const name=file.name.toLowerCase(); - const isVideo=file.type.startsWith('video/')||/\.(mp4|webm|mov)$/.test(name); - const isPhoto=file.type.startsWith('image/')||/\.(jpe?g|png|webp)$/.test(name); - if(!isVideo&&!isPhoto){input.value='';fail('Escolha uma foto JPG, PNG ou WebP, ou um vídeo MP4, WebM ou MOV.');return;} - if(isVideo){ - try{await checkDuration(file);}catch(error){input.value='';fail(error.message);return;} - if(closed)return; - showReady(file,'video'); - }else showReady(file,'photo'); - }; - fileLabel.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();input.click();}}; - cancel.onclick=()=>m.close(); - save.onclick=async()=>{ - if(!ready)return; - save.disabled=true;clear();status.textContent='Enviando '+ready.file.name+'…'; - try{ - const uid=await dtfUpload(ready.file,{api,startPath:'/orders/'+order.id+'/reviews/uploads', - scope:'operator:review:'+order.id,progress:text=>{if(!closed)status.textContent=text;}}); - if(closed)return; - await api('/orders/'+order.id+'/reviews',{upload_id:uid}); - m.close(); - say('Revisão salva no pedido #'+order.number+'.'); - await load(); - }catch(error){ - if(closed)return; - fail(error.message);save.disabled=false; - } - }; - const m=modal('Revisão do #'+order.number,{host,width:640, - text:'Tire uma foto ou grave um vídeo de até 30 s da folha impressa, ou envie um arquivo.', - body:[video,controls,timer,preview],foot:[status,cancel,save],onclose:cleanup}); - (async()=>{ - try{ - if(!navigator.mediaDevices?.getUserMedia)throw new Error('sem câmera'); - stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'environment', - width:{ideal:1920},height:{ideal:1080}},audio:false}); - if(closed){endStream();return;} - video.srcObject=stream; - await video.play().catch(()=>{}); - photoBtn.focus(); - }catch(_){ - endStream();video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true; - fail('Câmera indisponível neste computador. Envie um arquivo.'); - fileLabel.focus(); - } - })(); -} -async function openCheck(order){ - const {files}=await api('/orders/'+order.id+'/view'); - if(!files.length){say('Ainda não há arquivo para abrir.',true);return;} - openViewer(files,{title:'#'+order.number,onClose:()=>{ - const now=board.orders.find(o=>o.id===order.id)||order; - if(now.state==='rec'&&!now.cancelled_at&&!waitingProof(now)&&may('produce')&&mayMove('rec','tra')){ - if(openOrder!==order.id)openPanel(order.id); - isOk(now); - }}}); -} -// "Está OK?" (Dropstar, 2026-10-29): the class of each item, prefilled with -// the measure, and the art either goes on to Arte conferida, its final -// approved and its class kept, or is treated (item 8). -function isOk(order){ - // Ajuste Fino or Redesenho paid: only the treated PNG goes to the queue, so - // nothing is approved here; the designer goes to "Tratar a arte" (DTF-WEB-A). - if(designerPaid(order)&&!treatmentDone(order)){ - const service=order.snapshot.redesign?'O Ajuste Fino Redesenho':'O Ajuste Fino'; - const m=formDialog('Falta a arte tratada',{host:$('drawer'),label:'Tratar a arte', - text:service+' foi pago. Envie o PNG ajustado de cada item antes de colocar o pedido na fila.', - onsave:async()=>{m.close();treatDialog(order);return false;}}); - return; - } - const items=order.snapshot.items, ready=readyFinals(order); - const selects=items.map((item,index)=>{ - const select=node('select');select.required=true; - const none=node('option','Escolha');none.value='';none.disabled=true;select.append(none); - for(const c of ['C1','C2','C3']){const o=node('option',c+', '+CLASS_NOTE[c]);o.value=c;select.append(o);} - select.value=contractionOf(order,index)||'';return select;}); - const fields=selects.map((select,index)=>{const item=items[index]; - return field(items.length>1?'Item '+(index+1)+', contração':'Contração',select, - item.stroke_class?'O site mediu '+item.stroke_class+', traço de '+item.stroke_px+' px':'O site não mediu esta arte');}); - const missing=!finalDone(order)&&!ready.every(Boolean); - const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn'); - const m=formDialog('Está OK?',{host:$('drawer'),fields,left:[treat],label:'Mover para Arte conferida', - text:missing?'Falta o arquivo final de um item: trate a arte e envie o arquivo preparado.' - :'A arte chegou boa? Confira a contração e mova para Arte conferida.', - onsave:async()=>{ - if(missing)throw new Error('Falta o arquivo final de um item.'); - for(const [index,select] of selects.entries()) - if(select.value!==contractionOf(order,index)) - await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value}); - if(!finalDone(order)&&await saveFinalFiles(order, - ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))), - 'Conferido em Abrir e conferir'))return; - await load(); - await move(board.orders.find(o=>o.id===order.id)||order,'tra'); - say('Pedido #'+order.number+' em Arte conferida.'); - }}); - if(missing)m.box.querySelector('button.pri')?.setAttribute('disabled',''); -} -function treatDialog(order){ - const base=node('input');base.placeholder='Ex.: D:\\'+(FOLDER.handle?.name||'Pedidos'); - const names={}; - const rows=order.snapshot.items.map((item,index)=>{ - const slot=node('div',undefined,'fslot'); - const path=node('code','Procurando o arquivo…','treatpath'); - const copy=node('button','Copiar','btn');copy.type='button';copy.disabled=true; - const line=node('div',undefined,'treatline');line.append(path,copy); - const input=node('input');input.dataset.treatItem=index; - input.setAttribute('aria-label','Arte tratada do item '+(index+1)); - slot.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+', '+productName(item):productName(item),'lbl'),line, - dropField(input,{title:'Arte tratada',hint:'O arquivo salvo depois de tratar.'})); - return {path,copy,input}; - }); - // Windows paths unless the folder was written the other way. - const where=name=>{const b=base.value.trim().replace(/[\\/]+$/,''),sep=b.includes('/')&&!b.includes('\\')?'/':'\\'; - return (b?b+sep:'')+STAGE_FOLDERS[order.state]+sep+name;}; - const paint=()=>rows.forEach((row,index)=>{ - const name=names[index+1]; - row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.'; - row.copy.disabled=!name; - row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(name)); - say(base.value.trim()?'Caminho copiado.':'Caminho copiado a partir da pasta dos pedidos: informe onde ela fica neste computador para copiar o caminho inteiro.');} - catch(_){say('Não foi possível copiar.',true);}}; - }); - base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();}; - formDialog('Tratar a arte',{host:$('drawer'),width:620,className:'finalform', - text:'Copie o caminho e abra o arquivo. Trate e salve por cima, com o mesmo nome. Depois suba aqui o arquivo tratado.', - fields:[...rows.map(r=>r.input.closest('.fslot')),field('Pasta dos pedidos neste computador',base)],label:'Subir arte tratada', - onsave:async()=>{ - // Each item keeps its approved final, or else the file ready to approve, - // unless a treated one is sent for it. - const ready=readyFinals(order); - const plan=rows.map((row,index)=>{ - const file=row.input.files[0]; - if(file)return {file}; - const kept=(order.finals||[]).filter(f=>f.item_index===index).map(f=>f.upload_id); - const treated=order.treated?.items?.includes(index); - return {ids:designerPaid(order)&&!treated?[]: - kept.length?kept:ready[index]?ready[index].files.map(f=>f.upload_id):[]}; - }); - if(!plan.some(p=>p.file))throw new Error('Escolha o arquivo tratado.'); - const empty=plan.findIndex(p=>!p.file&&!p.ids.length); - if(empty>=0)throw new Error('O item '+(empty+1)+' ainda não tem arte tratada: envie o PNG dele também.'); - const refs=[]; - for(const [index,p] of plan.entries()){ - if(!p.file){refs.push(...p.ids.map(upload_id=>({item_index:index,upload_id})));continue;} - const uid=await dtfUpload(p.file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)}); - refs.push({item_index:index,upload_id:uid}); - } - if(await saveFinalFiles(order,refs,TREAT_NOTE))return; - await load(); - say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.'); - }}); - // Filled once open: the names the automatic folders give the files. - (async()=>{ - base.value=await kv.get(FOLDER_PATH_KEY).catch(()=>'')||''; - try{for(const f of (await api('/orders/'+order.id+'/folder-files')).files)names[f.item]=names[f.item]||f.name;} - catch(error){say(error.message,true);} - paint(); - })(); -} -// The reviews recorded on the order: what was checked, when and by whom. A -// photo opens in the viewer; a video cannot, so it opens in a new tab. In -// Revisão a reviewer may remove one. -function reviewSection(order){ - if(!order.reviews?.length)return null; - const box=node('section',undefined,'reviewsec');box.setAttribute('aria-label','Revisões'); - const info=node('div',undefined,'iinfo'); - info.append(node('span','Revisões','lbl'),node('h3',plural(order.reviews.length,'revisão','revisões'))); - const list=node('div',undefined,'reviewlist'); - for(const review of order.reviews){ - const row=node('div',undefined,'reviewrow'); - const open=node('button',undefined,'reviewopen');open.type='button'; - open.append(node('span','Revisão · '+(review.kind==='video'?'vídeo':'foto')+' · '+ - when(review.created_at)+' · '+review.created_by)); - open.onclick=async()=>{ - try{ - const view=await api('/orders/'+order.id+'/reviews/'+review.id+'/view'); - if(review.kind==='photo'&&window.openViewer)openViewer([{name:view.name,picture:view.url}],{title:'Revisão #'+order.number}); - else{const link=node('a');link.href=view.url;link.target='_blank';link.rel='noopener noreferrer';link.click();} - }catch(error){say(error.message,true);} - }; - row.append(open); - if(order.state==='rev'&&may('inspect')){ - const remove=node('button','Remover','btn quiet');remove.type='button'; - remove.onclick=async()=>{ - if(!await ask('Remover esta revisão?','Ela some do pedido e o arquivo deixa de ficar guardado.','Remover revisão',{tone:'red',host:$('drawer')}))return; - await api('/orders/'+order.id+'/reviews/'+review.id+'/remove',{}); - say('Revisão removida do pedido #'+order.number+'.');await load(); - }; - row.append(remove); - } - list.append(row); - } - info.append(list);box.append(info); - return box; -} -// Pedido: the items, then who, where and on which machine, then any rework. -function orderView(order){ - const view=node('div',undefined,'tview'); - const s=order.snapshot; - s.items.forEach((item,index)=>view.append(itemCard(order,item,index))); - view.append(orderFacts(order)); - const reviews=reviewSection(order);if(reviews)view.append(reviews); - if(order.reworks?.length)view.append(reworkSection(order)); - return view; -} -// On the phone: one row per fact, the label on the left. -function phoneFacts(order){ - const s=order.snapshot, dest=s.destination, who=buyer(s); - const box=node('div',undefined,'mblock mfacts'); - const row=(k,v)=>{if(!v)return;const r=node('div',undefined,'mfact');r.append(node('span',k),node('b',v));box.append(r);}; - row('Cliente',who.title);row('E-mail',s.customer.mail);row(docKind(s.customer.cnpj),cnpj(s.customer.cnpj)); - row('Entrega',specialDelivery(s)||(dest?dest.city+'/'+dest.state:'Retirada em Franca')); - row('Máquina',order.machine?.name||'Nenhuma');row('Código','DTF-'+order.number+', cliente '+orderCode(order.id)); - // Choosing the machine stays where it is allowed. - if(may('print')&&ME?.role!=='operador'&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);} - return box; -} -function orderFacts(order){ - if(PHONE.matches)return phoneFacts(order); - const s=order.snapshot, dest=s.destination, who=buyer(s); - const grid=node('div',undefined,'facts3'); - const client=node('div',undefined,'fact'); - const doc=node('span',undefined,'factline');doc.append(docKind(s.customer.cnpj)+' '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar '+docKind(s.customer.cnpj))); - const title=node('b',who.title);title.title=who.legal||who.title; - client.append(node('span','Cliente','lbl'),title,...(who.mail?[node('span',who.mail)]:[]),doc); - const zap=whatsappLink(s.customer.zap); - if(zap){const a=node('a','Abrir conversa','btn lnk');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(svgIcon(IC.chat,'i s'));client.append(a);} - const where=node('div',undefined,'fact'),special=specialDelivery(s); - where.append(node('span','Entrega','lbl'),node('b',special||(dest?dest.recipient:'Retirada em Franca')), - node('span',special?(special==='Interno'?'Fica na fábrica':'Sem frete próprio'): - dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+', '+dest.district+', '+dest.city+'/'+dest.state+', CEP '+dest.postal_code:'O cliente retira na fábrica')); - if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+', '+money(s.freight.total_cents)+(s.freight.weight_kg?', '+freightWeight(s.freight):''),'faint')); - grid.append(client,where); - if(order.machine||board.machines?.length)grid.append(machineCard(order)); - return grid; -} -const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'Arquivo gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'}; -// A line on an item: what is fine (ok), to look at (warn) or wrong (bad). -function itemNote(text,tone=''){ - const line=node('div',undefined,'inote'+(tone?' '+tone:'')); - line.append(svgIcon(tone==='ok'?IC.check:tone?IC.alert:IC.info,'i s'),node('span',text));return line; -} -function itemCard(order,item,index){ - const row=(order.print_files||[]).find(r=>r.item_index===index), spec=item.production; - const printStatus=row?.timed_out?'failed':row?.status; - const box=node('section',undefined,'item');box.setAttribute('aria-label','Item '+(index+1)); - const info=node('div',undefined,'iinfo'); - const count=order.snapshot.items.length; - info.append(node('span',count>1?'Item '+(index+1)+' de '+count:'Item','lbl'),node('h3',productName(item))); - const dl=node('dl',undefined,'dl'); - const pair=(k,v)=>{if(v===null||v===undefined||v==='')return;const d=node('div');const dd=node('dd');dd.append(v);d.append(node('dt',k),dd);dl.append(d);}; - pair('Folha',sheetSize(spec));pair('Metros cobrados',metres(item.billed_metres)); - pair('Peças',spec?String(spec.placements.length):null); - pair('Valor do metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null); - const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g); - pair('Menor resolução',row?.status==='ready'&&row.detail?.min_dpi?row.detail.min_dpi+' DPI':null); - pair('Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null); - pair('Contração',contractionControl(order,index)); - info.append(dl); - const notes=node('div',undefined,'inotes'); - if(item.quality_status==='warning')notes.append(itemNote('O cliente aceitou a ressalva de resolução.','warn')); - if(item.residue_accepted)notes.append(itemNote('Resíduo: '+item.residue_accepted+' pontos, aceito pelo cliente'+ - (item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn')); - if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+ - (item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.' - :'o cliente foi avisado e quis imprimir assim mesmo (C1).')+ - (item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn')); - if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad')); - // After a customer correction, that file is the artwork: the generated - // print file, or the reason it could not be made, no longer applies. - const fix=(order.corrections||[]).find(f=>f.item_index===index); - if(fix)notes.append(itemNote('Correção do cliente recebida: '+fix.name,'ok')); - else if(!row)notes.append(itemNote('Arquivo de impressão ainda não gerado.')); - else if(printStatus==='manual'||printStatus==='failed'){ - const call=node('div',undefined,'callout warn'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.alert,'i m')); - const p=node('p');p.append(node('b',printStatus==='failed'?'Falhou ao gerar'+(row.finished_at||row.timeout_at?' às '+when(row.finished_at||row.timeout_at):'')+'. ':'Preparar à mão. '), - row.timed_out?'Tempo limite excedido. Gere de novo.':row.detail?.reason||'Monte a folha a partir do original.'); - call.append(ico,p);notes.append(call); - }else{ - const original=row.status==='ready'&&row.detail?.source==='original'; - notes.append(itemNote((original?'O original é o arquivo de impressão':PRINT_TEXT[row.status])+ - (row.status==='ready'&&row.name&&!original?': '+row.name:'')+(row.status==='ready'&&row.detail?.vector_sources&&!original?', PDF vetorial':''),row.status==='ready'?'ok':'')); - } - if(['rec','tra','cor'].includes(order.state)){ - const done=(order.final_items||[]).includes(index); - notes.append(itemNote(done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn')); - } - if(order.treated?.items.includes(index))notes.append(itemNote('Arte tratada: '+TREATED_NOTE.charAt(0).toLowerCase()+TREATED_NOTE.slice(1)+' Aprovado por '+order.treated.by+'.')); - // O que o Prumo fez (front 6): the actions that happened, before the - // designer opens the file. Multi-item orders show each item's own lines. - const multi=order.snapshot.items.length>1, prefix=multi?'Item '+(index+1)+': ':''; - const prumoLines=(order.prumo||[]).filter(line=>!multi||line.startsWith(prefix)||line.startsWith('Prova do')) - .map(line=>line.startsWith(prefix)?line.slice(prefix.length):line); - if(prumoLines.length){ - const block=node('details',undefined,'prumo');block.append(node('summary','O que o Prumo fez')); - prumoLines.forEach(line=>block.append(node('p',line))); - notes.append(block); - } - if(notes.children.length)info.append(notes); - const links=node('div',undefined,'links'); - const dl_=(text,uid)=>{const b=downloadButton(text,download(uid),'btn');return b;}; - if(fix&&!fix.expired)links.append(dl_('Correção',fix.upload_id)); - else if(row?.status==='ready'&&row.detail?.source!=='original'){ - const made=generatedFiles(row); - made.forEach((f,k)=>links.append(dl_(made.length>1?'Parte '+(k+1)+' de '+made.length:/\.pdf$/i.test(f.name)?'PDF':'PNG',f.upload_id))); - } - const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')')); - item.uploads.forEach((uid,i)=>originals.append(downloadButton('Original '+(i+1),download(uid,order.id),'btn'))); - links.append(originals); - if(row?.status==='ready')links.prepend(checkButton(order)); - if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&!waitingProof(order)&&(!row||row.status==='manual'||row.status==='failed'||row.timed_out)){ - const again=button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn');again.prepend(svgIcon(IC.refresh,'i m'));links.append(again);} - info.append(links); - box.append(itemPreview(item),info);return box; -} -// Arquivos: every final, current or replaced, and the way to send a new one. -function filesView(order,revisions,view){ - const out=[]; - const layouts=node('div',undefined,'links'); - order.snapshot.items.forEach((item,index)=>{ - if(item.production?.placements){ - const b=button('Manifesto · item '+(index+1),()=>manifest(item.production,contractionRecord(item,order.contraction?.[index])),'btn'); - b.prepend(svgIcon(IC.file,'i m'));layouts.append(b); - } - }); - if(layouts.children.length)out.push(layouts); - if(revisions.length){ - const panel=node('div',undefined,'tpanel'); - const table=node('table',undefined,'table'); - const head=node('tr');head.append(node('th','Arquivo'),node('th','Item'),node('th','Situação'),node('th','')); - for(const th of head.children)th.scope='col'; - const thead=node('thead');thead.append(head);const tbody=node('tbody'); - for(const file of revisions){ - const tr=node('tr'); - const name=node('td');name.append(node('span',file.name,'code'),node('span',(file.kind==='final'?'Final':'Correção do cliente')+(file.note?', '+file.note:''),'sub')); - const state=node('td');state.append(badge(file.expired?'Expirado':file.active?'Atual':'Substituído',file.active&&!file.expired?'ok':''),node('span',when(file.created_at),'sub')); - const act=node('td',undefined,'r');if(!file.expired)act.append(downloadButton('Baixar',download(file.upload_id),'btn ghost')); - tr.append(name,node('td',String(file.item_index+1)),state,act);tbody.append(tr); - } - table.append(thead,tbody);panel.append(table);out.push(panel); - }else out.push(node('p','Nenhum arquivo final ainda.','empty')); - // Replacing an approved final, while the art is still in Arte recebida or Correção; - // in Arte conferida, the queue, the order goes back to Arte recebida first. - if(may('produce')&&['rec','cor'].includes(order.state)&&finalDone(order)&&!order.cancelled_at&&!order.proof_parent){ - const open=button('Enviar nova versão',async()=>finalDialog(order,readyFinals(order).map(()=>null),{replace:true}),'btn'); - open.prepend(svgIcon(IC.upload,'i m'));open.classList.add('self-start');out.push(open); - } - view.replaceChildren(...out); -} -// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause, -// which never changes after; an Administrador authorizes or declines it, -// never one they opened. Bad art the customer approved is outside the goal. -const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de Ajuste Fino', - pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'}; -const REWORK_OUTSIDE='arte_cliente'; -function reworkForm(order){ - const cause=node('select');cause.required=true; - const none=node('option','Escolha a causa');none.value='';cause.append(none); - for(const [value,text] of Object.entries(REWORK_CAUSES)){const o=node('option',text+(value===REWORK_OUTSIDE?' (fora da meta)':''));o.value=value;cause.append(o);} - const size=node('input');size.type='number';size.required=true;size.min='0.01';size.max='1000';size.step='0.01'; - size.value=order.snapshot.items.reduce((t,i)=>t+Number(i.metres??i.billed_metres),0).toFixed(2); - const note=node('textarea');note.maxLength=1000;note.placeholder='O que aconteceu (opcional)'; - formDialog('Abrir retrabalho no pedido #'+order.number,{host:$('drawer'),width:540, - text:'A causa não muda depois de aberta. O retrabalho conta na meta quando um administrador autoriza.', - fields:[field('Causa',cause),field('Metros refeitos',unit(size,'metros')),field('Observação',note)],label:'Abrir retrabalho', - onsave:async()=>{ - await api('/orders/'+order.id+'/reworks',{cause:cause.value,metres:size.value,note:note.value}); - say('Retrabalho aberto no pedido #'+order.number+'. Aguarda a autorização de um administrador.');await load(); - }}); -} -// An input with its unit inside it, on the right. -function unit(input,text){const u=node('span',undefined,'unit');u.append(input,node('span',text));return u;} -function reworkSection(order){ - const section=node('section',undefined,'tsection');section.append(node('h4','Retrabalho')); - for(const r of order.reworks){ - const box=node('div',undefined,'rework'); - box.append(node('b',REWORK_CAUSES[r.cause]+(r.cause===REWORK_OUTSIDE?', fora da meta':'')+', '+metres(r.metres)), - node('span','Aberto por '+r.opened_name+' em '+when(r.opened_at)+(r.printed_name?', impresso por '+r.printed_name:''),'sub')); - if(r.note)box.append(node('span',r.note,'sub')); - if(r.decided_at)box.append(badge((r.authorized?'Autorizado por ':'Não autorizado por ')+r.decided_name+' em '+when(r.decided_at),r.authorized?'ok':'bad',r.decline_reason||'')); - else if(may('authorize')&&r.opened_by!==ME.email){ - const why=node('input');why.placeholder='Motivo, se não autorizar';why.setAttribute('aria-label','Motivo, se não autorizar');why.maxLength=1000; - const decide=authorized=>async()=>{ - await api('/reworks/'+r.id+'/decision',{authorized,reason:why.value}); - say(authorized?'Retrabalho autorizado.':'Retrabalho não autorizado.');await load();}; - const row=node('div',undefined,'decide'); - row.append(button('Autorizar',decide(true),'btn pri'),why,button('Não autorizar',decide(false),'btn ghost')); - box.append(row); - }else box.append(badge('Aguardando a autorização de um administrador','warn')); - section.append(box); - } - return section; -} -// Histórico: the newest first, the order's arrival last. -function historyView(order,rows,view){ - const list=node('ol',undefined,'hist'); - const entry=(title,who,at,reason)=>{ - const li=node('li'),text=node('span'); - text.append(node('b',title),node('span',who+(reason?': '+reason:''),'sub')); - const time=node('time',when(at));time.dateTime=at; - li.append(node('i'),text,time);return li; - }; - for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state), - r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason)); - for(const item of order.snapshot.items){ - if(item.residue_accepted_at)list.append(entry('Resíduo aceito','cliente',item.residue_accepted_at, - item.residue_accepted+' pontos')); - if(item.stroke_choice_at)list.append(entry('Traço fino aceito','cliente',item.stroke_choice_at, - item.stroke_choice==='client_c3'?'proteger chapado (C3)':'imprimir assim (C1)')); - } - list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento': - paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site', - order.created_at,paidOutside(order)?order.payment.note:'')); - view.replaceChildren(list); -} - - // ---- Wiring -------------------------------------------------------------- for(const b of document.querySelectorAll('[data-tab]'))b.onclick=()=>showTab(b.dataset.tab);