diff --git a/app/api/operator.py b/app/api/operator.py index 70beb39..be5f51e 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -945,29 +945,32 @@ def named_files(rows): return files -def print_ready(c, request, states): +def print_ready(c, request, states, only=None): """The file to print for each item of the orders in these stages, in queue order: the approved final, or before approval the generated print file - (unless the customer has sent a correction since). An operator who works - on some machines gets only those machines' orders.""" + (unless the customer has sent a correction since). `only` narrows it to + these orders. An operator who works on some machines gets only those + machines' orders.""" + ids = None if only is None else list(only) rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position FROM dtf_local.orders o JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id - WHERE o.state=ANY(%s) AND o.cancelled_at IS NULL AND {FINAL_OK} + WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND o.cancelled_at IS NULL AND {FINAL_OK} UNION ALL SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) FROM dtf_local.orders o JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.uploads u ON u.id=p.upload_id - WHERE o.state=ANY(%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' + WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean' AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final' AND f.active AND f.item_index=p.item_index) AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction') - ORDER BY position,order_id,item_index''', (list(states), list(states))).fetchall() + ORDER BY position,order_id,item_index''', (list(states), ids, ids, list(states), ids, ids)).fetchall() staged = assign_machines(c, c.execute('''SELECT * FROM dtf_local.orders - WHERE state=ANY(%s) AND cancelled_at IS NULL''', (list(states),)).fetchall()) + WHERE state=ANY(%s) AND (%s::uuid[] IS NULL OR id=ANY(%s)) AND cancelled_at IS NULL''', + (list(states), ids, ids)).fetchall()) mine = {o['id'] for o in visible(request, staged)} return [row for row in rows if row['order_id'] in mine] @@ -992,13 +995,19 @@ class FolderSync(StrictModel): @router.post('/api/operator/queue/folder') def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))): - """What the Kanban's automatic folder should hold. Early, it also gets the - files of orders just received (to a "Recebidos" folder), so a large sheet is - already on the computer when the order reaches the queue. `states` answers - for the orders the folder already holds files of: a stage, 'cancelled', or - nothing when the order was deleted, so their files can be removed.""" + """What the Kanban's automatic folders should hold. `early` is Dropstar's + three folders (2026-10-26): the files of orders in Arte recebida and Arte + conferida, and, for the orders the folders already hold, their files while + they print, are checked in Revisão and sit in Finalizado, so one taken out + of a folder can be fetched again when the order moves on. Without it, only + the queue's (Firefox's downloads). `states` answers for the orders the + folders hold files of: a stage, 'cancelled', or nothing when the order was + deleted, so their files can be removed.""" with db.connect() as c: - files = named_files(print_ready(c, request, ('rec', 'tra') if body.early else ('tra',))) + rows = print_ready(c, request, ('rec', 'tra') if body.early else ('tra',)) + if body.early and body.held: + rows += print_ready(c, request, ('imp', 'rev', 'fin'), only=body.held) + files = named_files(rows) held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)', (body.held,)).fetchall() if body.held else [] return {'files': files, diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 4885fe1..25c741f 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -336,15 +336,21 @@ docs/guias/telas/. ### Kanban automatic folder (agreed in the 2026-10-07 meeting) -The Kanban, open on the print room's computer, saves the files to a folder -chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer, -it downloads as soon as the order arrives in Arte recebida (the default since -2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when -the order enters the queue (Arte conferida since 2026-10-26); or only when the -order enters the queue. -Files of orders cancelled, deleted or sent back for correction, and files -replaced by another final, are removed from the folder -(`POST /api/operator/queue/folder`). +Dropstar's three folders (asked 2026-10-23, agreed 2026-10-26): the Kanban, +open in Chrome or Edge on a factory computer that reaches the server's +folder, signed in with a profile that sees every order (Gestão), keeps the +orders' files in three folders it creates inside the one chosen in +Integrações ("Pastas dos pedidos"): Arte recebida (the file arrives when the +order does), Arte conferida (the queue; the file moves there with the card +and stays while it prints and is checked in Revisão) and Finalizado (when the +order is released, kept 30 days there). Correção, a cancellation or a +deletion takes the file out; a replaced final is swapped. Orders already +printing when the folder is chosen are not downloaded. A file someone took +out is fetched again only when its order moves on (`POST +/api/operator/queue/folder`, which also returns the files of orders the +folders hold once they print). Who opens each folder is set in the server's +folder permissions. Firefox cannot write into folders: it only downloads the +files entering Arte conferida. Integrações (2026-10-20): only the superadmin (us) has the buttons, the details and the Tiny log there (`integrations` capability, app/core/auth.py). @@ -430,9 +436,11 @@ Still to do (2026-10-26): - Waiting on Dropstar: the DTF SITE category's numeric id (CATEGORY in app/tiny.py is still DUPLICADO DROP), the internal rules document (D-16 to D-23), and the montador spec (and which "histórico" Marcus means for its - orders). Their three server folders moved on card moves need a written - decision: the Kanban in the room's browser can do it; a program on their - server is the factory agent left out of this scope. + orders). +- The three folders, once deployed: Marcus sets the main folder on the + factory computer (Chrome, Integrações > Pastas dos pedidos); check on the + first print whether FlexiPRINT keeps reading the file in Arte conferida + after import (the file only leaves that folder at Finalizado). - Anchor-customer orders from the montador: after the launch; the team's idea is that Graphs handles that side and sends the orders to this Kanban. diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index cc1ff29..9c55306 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -183,7 +183,7 @@ try{ assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva'); assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`), {kind:'sheet',copies:1,length:101,height:101,placed:1}); - // The print queue's folder, switched on in Integrações. The native picker + // The orders' three folders, switched on in Integrações. The native picker // cannot be driven headless: it answers with a folder in the browser's own // storage, which has the same file API. await kanban.click('[data-tab="integrations"]'); @@ -193,11 +193,10 @@ try{ window.showDirectoryPicker=async()=>window.picked;FOLDER.mode='folder';renderIntegrations(); [...document.querySelectorAll('#folder-card button')].find(b=>b.textContent==='Escolher pasta').click();})()`); await waitFor(()=>kanban.eval('folderActive()&&!FOLDER.busy'),'folder chosen'); - // Downloaded as the order arrives, into Recebidos; up to the folder at the queue. - await waitFor(()=>kanban.eval(`!!document.querySelector('#folder-card select')`),'download timing choice'); - await kanban.eval(`(()=>{const s=document.querySelector('#folder-card select');s.value='rec';s.dispatchEvent(new Event('change'));})()`); - await waitFor(()=>kanban.eval(`FOLDER.when==='rec'&&!FOLDER.busy`),'download on arrival'); - const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=${sub?`await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true})`:'window.picked'}; + // Dropstar's three folders (2026-10-26): the file arrives in Arte recebida, + // goes to Arte conferida with the card and to Finalizado at the end. + await waitFor(()=>kanban.eval(`!FOLDER.busy`),'folder idle'); + const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true}); const out=[];for await(const [name,h] of dir.entries())if(h.kind==='file')out.push(name);return out;})()`); // Open the order's panel from its card, then click the real transition // buttons there, including the rerender after each move. @@ -220,31 +219,40 @@ try{ await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file'); await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval'); - // Approved before the queue: already on this computer, in Recebidos. + // Approved before the queue: already on this computer, in Arte recebida. const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1'; await kanban.eval('syncFolder(true)'); - await waitFor(async()=>(await savedFiles('Recebidos')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Recebidos',45000); - assert.equal((await savedFiles()).some(n=>n.startsWith(early)),false); + await waitFor(async()=>(await savedFiles('Arte recebida')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Arte recebida',45000); + assert.equal((await savedFiles('Arte conferida')).some(n=>n.startsWith(early)),false); } await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title); await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state); if(state==='tra'){ - // Entering the queue saves its final file there, whole and named after the order. + // Entering the queue moves its file to Arte conferida, whole and named after the order. const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1'; - await waitFor(async()=>(await savedFiles()).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file saved in the folder',45000); + await waitFor(async()=>(await savedFiles('Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000); // Other orders the earlier suites left in the queue may still be coming // down: only once the round ends must no half-written file be left. await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000); - assert.equal((await savedFiles()).some(n=>n.endsWith('.baixando')),false); - assert.equal((await savedFiles('Recebidos')).some(n=>n.startsWith(prefix)),false); + assert.equal((await savedFiles('Arte conferida')).some(n=>n.endsWith('.baixando')),false); + assert.equal((await savedFiles('Arte recebida')).some(n=>n.startsWith(prefix)),false); // A file whose order was deleted leaves the folder. - await kanban.eval(`(async()=>{const f=await window.picked.getFileHandle('pedido-0-item-1-excluido.png',{create:true}); + await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('Arte conferida',{create:true}); + const f=await dir.getFileHandle('pedido-0-item-1-excluido.png',{create:true}); const w=await f.createWritable();await w.write('x');await w.close(); - FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',place:'queue'});})()`); + FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',folder:'Arte conferida'});})()`); await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000); await kanban.eval('syncFolder(true)'); - await waitFor(async()=>!(await savedFiles()).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000); + await waitFor(async()=>!(await savedFiles('Arte conferida')).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000); + } + if(state==='fin'){ + // Finalized: the file goes to Finalizado, out of the queue. + const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1'; + await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000); + await kanban.eval('syncFolder(true)'); + await waitFor(async()=>(await savedFiles('Finalizado')).some(n=>n.startsWith(prefix)),'final file in Finalizado',30000); + assert.equal((await savedFiles('Arte conferida')).some(n=>n.startsWith(prefix)),false); } } // Undo a mistaken move from the panel: one stage back with an internal reason. diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 8c1df6b..f98d1c4 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -113,6 +113,15 @@ def run(): # Arte conferida is the print queue (2026-10-23). client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True) version += 1 + # Printing, the folders still get the file of an order they hold (to take + # it to Finalizado later), and no one else's. + client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True) + version += 1 + held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True) + assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held + assert held['states'] == {oid: 'imp'} + others = client.call('/operator/queue/folder', {'early': True, 'held': []}, operator=True) + assert not [f for f in others['files'] if f['order'] == oid], others['files'] # Once queued for printing, the final set can no longer change. client.call('/operator/orders/' + oid + '/final-files', {'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], diff --git a/web/kanban.js b/web/kanban.js index 3f55f8a..eb94e47 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -207,37 +207,37 @@ function download(uid){return async()=>{ const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click(); };} // ---- Automatic folder ------------------------------------------------------ -// The print queue's files, saved by this browser as orders enter Arte -// conferida (the queue since 2026-10-23), while the Kanban is open. It is switched on in Integrações, on -// the print room's computer: the folder belongs to that browser, not to the -// account. Chrome and Edge write into a folder the operator chose -// (FlexiPRINT's, or the internal server's share), remembered, with one click -// to release it after the browser restarts. Brave has the same API behind a -// flag that is off by default; the card says how to turn it on. Firefox cannot -// write into a chosen folder: there each file is downloaded, and Firefox's own -// download folder is set to FlexiPRINT's. +// The orders' files, kept by this browser in Dropstar's three folders +// (2026-10-26) inside the one chosen, while the Kanban is open. It is switched +// on in Integrações, on a computer of the factory that reaches the server's +// folder: the folder belongs to that browser, not to the account. Chrome and +// Edge write into the folder chosen, remembered, with one click to release it +// after the browser restarts. Brave has the same API behind a flag that is off +// by default; the card says how to turn it on. Firefox cannot write into a +// chosen folder: there each file entering the queue is downloaded, and +// Firefox's own download folder is set to FlexiPRINT's. const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1); r.onupgradeneeded=()=>r.result.createObjectStore('kv');r.onsuccess=()=>ok(r.result);r.onerror=()=>fail(r.error);})); const run=async(mode,fn)=>{const db=await open();return new Promise((ok,fail)=>{const t=db.transaction('kv',mode);const req=fn(t.objectStore('kv')); t.oncomplete=()=>ok(req?.result);t.onerror=()=>fail(t.error);});}; return {get:k=>run('readonly',s=>s.get(k)),set:(k,v)=>run('readwrite',s=>s.put(v,k)),del:k=>run('readwrite',s=>s.delete(k))};})(); const BRAVE_FLAG='brave://flags/#file-system-access-api'; -// `when`: download as soon as the order arrives in Arte recebida ('rec', the -// default), into a "Recebidos" folder inside the chosen one; the file moves up -// when the order enters the queue; or only at the queue ('tra'; computers set -// before 2026-10-23 kept 'fil', read the same). Only a chosen folder can do -// that: Firefox downloads cannot be moved or removed afterwards. +// Where an order's file is, by its stage: it arrives in Arte recebida, moves +// to Arte conferida (the queue) with the card and stays there while it prints +// and is checked in Revisão, then goes to Finalizado, kept 30 days. Correção, +// a cancellation or a deletion takes it out; a replaced final is swapped. +const STAGE_FOLDERS={rec:'Arte recebida',tra:'Arte conferida',imp:'Arte conferida',rev:'Arte conferida',fin:'Finalizado'}; +const KEEP_FINISHED_DAYS=30; const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', - brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'rec', + brave:!!navigator.brave,handle:null,granted:false,downloads:false, saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null}; -const RECEIVED='Recebidos'; // Switched on: a chosen folder released, or automatic downloads. const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads; -const early=()=>FOLDER.mode==='folder'&&FOLDER.when==='rec'; -const savedKey=()=>FOLDER.mode==='folder'?'saved:'+FOLDER.handle.name:'saved:downloads'; -// What this folder received, by upload: its order, item, name and where it is -// ('early' in Recebidos, 'queue' in the folder, 'done' once printing). Older -// versions kept only the upload ids. +// The three folders started their own record: files saved by the single +// folder of before 2026-10-26 are left where they are. +const savedKey=()=>FOLDER.mode==='folder'?'stages:'+FOLDER.handle.name:'saved:downloads'; +// What this folder received, by upload: its order, item, name, the folder it +// is in and, in Finalizado, since when. Older versions kept only the upload ids. const savedMap=list=>new Map((list||[]).map(e=>typeof e==='string'?[e,{place:'done'}]:e)); const loadSaved=async()=>savedMap(await kv.get(savedKey()).catch(()=>null)); const keepSaved=()=>kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{}); @@ -248,18 +248,17 @@ async function restoreFolder(){ return; } if(FOLDER.mode!=='folder')return; - try{FOLDER.when=['tra','fil'].includes(await kv.get('folder-when'))?'tra':'rec'; - FOLDER.handle=await kv.get('folder')||null; + try{FOLDER.handle=await kv.get('folder')||null; if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted'; FOLDER.saved=await loadSaved(); - if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos da fila na pasta, abra Integrações e clique em “Liberar pasta”.',false,10000),2500);}} + if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos nas pastas, abra Integrações e clique em “Liberar pasta”.',false,10000),2500);}} catch{FOLDER.handle=null;} } // The folder's row in Integrações, redrawn whenever its state changes. The // row says what is happening; the how-to and the secondary buttons are under // "Detalhes". function folderCard(){ - const name='Pasta da fila (Arte conferida)', h=FOLDER.handle; + const name='Pastas dos pedidos', h=FOLDER.handle; const act=(text,fn)=>button(text,fn,'btn small'); const ghost=(text,fn)=>button(text,fn,'btn ghost small'); const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;}; @@ -280,30 +279,25 @@ function folderCard(){ ? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok', summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(), details:how,extra:[ghost('Desligar',()=>setDownloads(false))]}) - : integration({name,state:'Desligada',tone:'off',summary:'Baixa sozinho, no Firefox, os arquivos que entram na fila.', + : integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as três pastas pedem o Chrome ou o Edge.', actions:[act('Ligar',()=>setDownloads(true))],details:how}); }else if(!h){ - row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho, numa pasta, os arquivos que entram na fila.', + row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos em três pastas: Arte recebida, Arte conferida e Finalizado.', actions:[act('Escolher pasta',chooseFolder)], - details:[node('p','Escolha a pasta que o FlexiPRINT lê, ou a pasta da rede do servidor. Os arquivos levam o número do pedido no nome. '+ - 'Funciona neste computador, com o Kanban aberto.')]}); + details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as três pastas e move o arquivo conforme o card anda. '+ + 'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]}); }else if(!FOLDER.granted){ row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.', actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]}); }else{ - const when=node('select',undefined,'machine-select');when.setAttribute('aria-label','Quando baixar'); - for(const [value,text] of [['rec','Baixar em Arte recebida'],['tra','Baixar em Arte conferida']]){ - const o=node('option',text);o.value=value;o.selected=FOLDER.when===value;when.append(o);} - when.onchange=()=>setWhen(when.value); row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok', - summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),actions:[when], + summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(), details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)], ['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'], - node('p',FOLDER.when==='rec' - ?'Em Arte recebida: o arquivo do pedido é baixado em “'+h.name+'/'+RECEIVED+'” assim que o pedido chega, e passa para “'+h.name+'” quando entra em Arte conferida, a fila.' - :'Em Arte conferida: o arquivo é baixado em “'+h.name+'” quando o pedido entra em Arte conferida, a fila.'), - node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai. '+ - 'Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')], + node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em Arte recebida, passa para Arte conferida quando o card vai para lá '+ + '(e fica lá enquanto imprime e na Revisão) e vai para Finalizado quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'), + node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+ + 'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Deixe o Kanban aberto neste computador.')], extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]}); } row.id='folder-card';return row; @@ -326,7 +320,7 @@ async function chooseFolder(){ FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null; FOLDER.saved=await loadSaved(); await kv.set('folder',handle).catch(()=>{}); - paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder(); + paintFolder();say('Os arquivos dos pedidos vão ser salvos nas três pastas dentro de “'+handle.name+'”.');syncFolder(); } async function releaseFolder(){ FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted'; @@ -343,13 +337,6 @@ async function setDownloads(on){ paintFolder();say(on?'Download automático ligado.':'Download automático desligado.'); if(on)syncFolder(); } -async function setWhen(when){ - FOLDER.when=when;FOLDER.lastSig=null; - await kv.set('folder-when',when).catch(()=>{}); - paintFolder();say(when==='rec'?'Os arquivos vão ser baixados assim que o pedido chegar, em “'+RECEIVED+'”.':'Os arquivos vão ser baixados quando o pedido entrar em Arte conferida.'); - syncFolder(true); -} - // A whole file in a folder: written under another name and renamed at the // end, so the FlexiPRINT never sees half of it. `source` is a download's body // or a file. @@ -364,83 +351,94 @@ async function writeWhole(dir,name,source){ catch{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable(); await whole.write(await temp.getFile());await whole.close();await dir.removeEntry(temp.name);} } -const received=()=>FOLDER.handle.getDirectoryHandle(RECEIVED,{create:true}); -// Remove a saved file from where it is; one already gone (the FlexiPRINT -// took it) is fine. +const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true}); +// Remove a saved file from its folder; one already gone (someone took it) is fine. async function removeSaved(rec){ - const dir=rec.place==='early'?await received():FOLDER.handle; + const dir=await stageDir(rec.folder); await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;}); } -// From Recebidos up to the folder, when the order enters the queue. False when -// the file is no longer there, so it is downloaded again. -async function moveToQueue(rec){ - const from=await received();let file; +// To another of the three folders. False when the file is no longer where it was. +async function moveSaved(rec,to){ + const from=await stageDir(rec.folder), dest=await stageDir(to);let file; try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;} - await FOLDER.handle.removeEntry(rec.name).catch(()=>{}); - try{await file.move(FOLDER.handle);} - catch{await writeWhole(FOLDER.handle,rec.name,await file.getFile());await from.removeEntry(rec.name);} + await dest.removeEntry(rec.name).catch(()=>{}); + try{await file.move(dest);} + catch{await writeWhole(dest,rec.name,await file.getFile());await from.removeEntry(rec.name);} return true; } +// One file from storage, whole, into a folder. +async function fetchInto(dir,file){ + const r=await fetch(file.url,{referrerPolicy:'no-referrer'}); + if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').'); + await writeWhole(dir,file.name,r.body); +} -// Bring the folder in line with the board: remove the files of orders that -// were cancelled, deleted, sent back for correction or given another file; -// move up what entered the queue; download what is missing. A file the -// FlexiPRINT moved away after importing is not downloaded again. After a +// Bring the folders in line with the board: remove the files of orders that +// were cancelled, deleted, sent back for correction or given another file, +// and those kept their days in Finalizado; move each file to its stage's +// folder; download what arrived in Arte recebida or Arte conferida. A file +// someone took out is downloaded again only when its order moves on. After a // board load it asks only when something it follows changed; the folder's // own timer always asks, since another computer may have moved the order. async function syncFolder(force=false){ if(!folderActive()||FOLDER.busy||!board||!may('print'))return; - const follows=early()?['rec','tra','cor']:['tra']; - const sig=FOLDER.when+'|'+board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at) + const stages=FOLDER.mode==='folder'; + const follows=stages?['rec','tra','imp','rev','fin','cor']:['tra']; + const sig=board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at) .map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(','); if(!force&&sig===FOLDER.lastSig)return; FOLDER.busy=true; try{ - const tidy=FOLDER.mode==='folder'; - const held=tidy?[...new Set([...FOLDER.saved.values()].filter(r=>r.order&&r.place!=='done').map(r=>r.order))]:[]; - const {files,states}=await api('/queue/folder',{early:early(),held}); + const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[]; + const {files,states}=await api('/queue/folder',{early:stages,held}); const wanted=new Map(files.map(f=>[f.order+':'+f.item,f])); - const where=FOLDER.mode==='folder'?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; - let removed=0; - if(tidy)for(const [uid,rec] of [...FOLDER.saved]){ - if(!rec.order||rec.place==='done')continue; - const state=states[rec.order]; - if(state==='imp'||state==='rev'||state==='fin'){rec.place='done';continue;} + const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; + let removed=0, moved=0, saved=0; + const record=async(uid,file,folder)=>{ + FOLDER.saved.set(uid,{order:file.order,item:file.item,name:file.name,folder, + ...(folder===STAGE_FOLDERS.fin?{at:Date.now()}:{})}); + FOLDER.last=new Date();await keepSaved();}; + if(stages)for(const [uid,rec] of [...FOLDER.saved]){ + if(!rec.order||!rec.folder)continue; + const state=states[rec.order], target=STAGE_FOLDERS[state]; const now=wanted.get(rec.order+':'+rec.item); - const expected=state==='tra'||early()&&state==='rec'; - if(state&&state!=='cancelled'&&state!=='cor'&&!(expected&&(!now||now.upload_id!==uid)))continue; - await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved(); + const replaced=(state==='rec'||state==='tra')&&(!now||now.upload_id!==uid); + const kept=rec.folder===STAGE_FOLDERS.fin&&Date.now()-(rec.at||0)>KEEP_FINISHED_DAYS*86400000; + if(!target||replaced||kept){await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();continue;} + if(rec.folder===target)continue; + if(await moveSaved(rec,target)){await record(uid,{...rec},target);moved++;continue;} + // Not where it was: downloaded again into its new folder while storage has it. + if(now&&now.upload_id===uid){await fetchInto(await stageDir(target),now);await record(uid,now,target);moved++;} + else{FOLDER.saved.delete(uid);await keepSaved();} } - const pending=files.filter(f=>{const r=FOLDER.saved.get(f.upload_id);return !r||r.place==='early'&&f.state==='tra';}); + // New files: only orders in Arte recebida or Arte conferida. One already + // printing when the folder was chosen is the room's already. + const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id)&&(stages?f.state==='rec'||f.state==='tra':f.state==='tra')); for(const [i,file] of pending.entries()){ - const rec=FOLDER.saved.get(file.upload_id); - const up=!!rec&&await moveToQueue(rec); - if(!up){ - FOLDER.status=(FOLDER.mode==='folder'?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); - say(FOLDER.status,false,60000); - if(FOLDER.mode==='downloads'){ - // Firefox writes it as .part and renames it when whole. - const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click(); - await new Promise(r=>setTimeout(r,900)); - }else{ - const r=await fetch(file.url,{referrerPolicy:'no-referrer'}); - if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').'); - await writeWhole(file.state==='tra'?FOLDER.handle:await received(),file.name,r.body); - } + FOLDER.status=(stages?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); + say(FOLDER.status,false,60000); + if(stages){ + await fetchInto(await stageDir(STAGE_FOLDERS[file.state]),file); + await record(file.upload_id,file,STAGE_FOLDERS[file.state]); + }else{ + // Firefox writes it as .part and renames it when whole. + const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click(); + await new Promise(r=>setTimeout(r,900)); + FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name}); + FOLDER.last=new Date();await keepSaved(); } - FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name, - place:file.state==='tra'||FOLDER.mode!=='folder'?'queue':'early'}); - FOLDER.last=new Date();await keepSaved(); + saved++; } FOLDER.lastSig=sig;FOLDER.error=''; FOLDER.status=''; - if(pending.length)say((FOLDER.mode==='folder'?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where+'.'); - if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos ou trocados saíram da pasta.'); + if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.'); + if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.'); + if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.'); }catch(e){ if(e.name==='NotAllowedError')FOLDER.granted=false; else if(e.name==='NotFoundError')FOLDER.error='A pasta “'+FOLDER.handle?.name+'” não foi encontrada. Ela foi apagada ou a rede caiu? Escolha a pasta de novo.'; else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.'; - FOLDER.status='';say('Pasta automática: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true); + FOLDER.status='';say('Pastas automáticas: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true); }finally{FOLDER.busy=false;paintFolder();} } setInterval(()=>syncFolder(true),30000);