diff --git a/app/api/operator.py b/app/api/operator.py index 56701c8..362ddf4 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -793,21 +793,9 @@ def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(o 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}} -@router.get('/api/operator/queue/finals') -def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce'))): - """The approved final files of every order in the print queue, in queue - order, each named after its order so a folder of them stays readable. The - browser downloads them straight from storage: a zip of multi-GB sheets - would go through the server.""" - with db.connect() as c: - rows = c.execute(f'''SELECT o.number,f.item_index,f.upload_id,u.object_key,u.name 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='fil' AND o.cancelled_at IS NULL AND {FINAL_OK} - ORDER BY COALESCE(o.queue_key, extract(epoch FROM o.created_at)),o.id,f.item_index,f.created_at''').fetchall() - # A machine's operator downloads only that machine's queue. - queued = assign_machines(c, c.execute("SELECT * FROM dtf_local.orders WHERE state='fil' AND cancelled_at IS NULL").fetchall()) - mine = {o['number'] for o in visible(request, queued)} - rows = [row for row in rows if row['number'] in mine] +def named_files(rows): + """Each file named after its order and item, so a folder of them stays + readable, with a link straight to storage.""" files, names = [], set() for row in rows: prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}" @@ -818,14 +806,72 @@ def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce name = f'{stem} ({copy}).{ext}' if dot else f'{ext} ({copy})' copy += 1 names.add(name) - files.append({'number': row['number'], 'item': row['item_index'] + 1, 'name': name, - 'upload_id': str(row['upload_id']), 'url': storage.download(row['object_key'], name)}) + files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'], + 'item': row['item_index'] + 1, 'name': name, 'upload_id': str(row['upload_id']), + 'url': storage.download(row['object_key'], name)}) + return files + + +def print_ready(c, request, states): + """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.""" + 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} + 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' + 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() + staged = assign_machines(c, c.execute('''SELECT * FROM dtf_local.orders + WHERE state=ANY(%s) AND cancelled_at IS NULL''', (list(states),)).fetchall()) + mine = {o['id'] for o in visible(request, staged)} + return [row for row in rows if row['order_id'] in mine] + + +@router.get('/api/operator/queue/finals') +def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce'))): + """The approved final files of every order in the print queue. The browser + downloads them straight from storage: a zip of multi-GB sheets would go + through the server.""" + with db.connect() as c: + files = named_files(print_ready(c, request, ('fil',))) # The automatic folder asks whenever the queue changes; only a person's download is logged. if not auto: audit('queue_finals_downloaded', operator=user, files=len(files)) return {'files': files} +class FolderSync(StrictModel): + early: bool = False + held: list[UUID] = Field(default_factory=list, max_length=1000) + + +@router.post('/api/operator/queue/folder') +def queue_folder(body: FolderSync, request: Request, user=Depends(can('produce'))): + """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.""" + with db.connect() as c: + files = named_files(print_ready(c, request, ('rec', 'tra', 'fil') if body.early else ('fil',))) + 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, + 'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}} + + @router.get('/api/operator/uploads/{uid}/download') def download(uid: UUID, user=Depends(operator)): with db.connect() as c: diff --git a/app/bootstrap.py b/app/bootstrap.py index c5797eb..7ed1a3d 100644 --- a/app/bootstrap.py +++ b/app/bootstrap.py @@ -46,6 +46,11 @@ def main(): c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role))) c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role))) c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role))) + # ops.launch_reset starts the order numbers again at #1 (setval), once + # the test orders are gone; nothing else may change a sequence. + numbers = c.execute("SELECT pg_get_serial_sequence('dtf_local.orders','number')").fetchone()[0] + c.execute(sql.SQL('GRANT UPDATE ON SEQUENCE {} TO {}').format( + sql.Identifier(*numbers.split('.', 1)), sql.Identifier(role))) # Turn the configured credential into a real account so an existing # deployment keeps logging in exactly as before. Inserts only when that # email is absent, so a password changed with local.operators is never diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 2f88f89..a6b1c1f 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -293,6 +293,16 @@ supports subsequent corrections or scoped enhancements. ## Known implementation status +### 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 either when the order enters the print queue, or as soon as the +order arrives: then into a `Recebidos` folder inside the chosen one, moved up +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`). + ### Active localhost milestone (2026-09-15) The current implementation target is localhost before any production connection. diff --git a/ops/launch_reset.py b/ops/launch_reset.py index 777bcb5..9110691 100644 --- a/ops/launch_reset.py +++ b/ops/launch_reset.py @@ -14,9 +14,8 @@ minute. Operators, the Tiny connection and the backups are kept. It refuses if any payment was made with real money (Mercado Pago's live_mode): those are customers' orders, not tests. -Order numbers start again at #1 only with the database administrator's -rights, which the worker does not have. The script prints the one command -to run in the database container's console for that. +Order numbers start again at #1. A database set up before the worker could +do that prints the one command to run in the database container's console. """ import argparse import sys @@ -37,6 +36,8 @@ TABLES = [ # in an order the foreign keys allow ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')] CONFIRM = 'APAGAR' RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;' +# What the worker's role may do itself (app/bootstrap.py grants it). +RENUMBER = "SELECT setval(pg_get_serial_sequence('dtf_local.orders','number'), 1, false)" def counts(c, tables): @@ -69,7 +70,7 @@ def main(argv=None, out=print, connect=db.connect): out('Apagado.') try: with connect() as c: - c.execute(RESTART) + c.execute(RENUMBER) out('A numeração dos pedidos recomeça em #1.') except Exception as exc: # the application's role cannot alter the table if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower(): diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 681e02f..f30b379 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -184,7 +184,12 @@ 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'); - const savedFiles=()=>kanban.eval(`(async()=>{const out=[];for await(const [name] of window.picked.entries())out.push(name);return out;})()`); + // 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'}; + 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. await kanban.click('[data-tab="board"]'); @@ -205,6 +210,11 @@ 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===2`),'final file approval'); + // Approved before the queue: already on this computer, in Recebidos. + const early='pedido-'+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(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title); await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`); @@ -217,6 +227,14 @@ try{ // 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); + // 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}); + 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'});})()`); + 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); } } // Undo a mistaken move from the panel: one stage back with an internal reason. diff --git a/tests/launch_reset_test.py b/tests/launch_reset_test.py index 212902e..b66aa00 100644 --- a/tests/launch_reset_test.py +++ b/tests/launch_reset_test.py @@ -45,7 +45,19 @@ def run(): assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL AND expires_at>now()''').fetchone() assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1 - assert 'Apagado.' in lines and any('#1' in line for line in lines), lines + assert 'Apagado.' in lines and 'A numeração dos pedidos recomeça em #1.' in lines, lines + # The worker's own role restarts the numbers: the next order is #1. + with db.connect() as c: + quote = uuid4() + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) + VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''', + (quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490}))) + first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) + VALUES(%s,%s,%s,%s,%s) RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}), + Jsonb({'provider': 'teste'}))).fetchone()['number'] + assert first == 1, first + c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,)) print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes') diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index b376dc3..0252d17 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -72,6 +72,10 @@ def run(): board = client.call('/operator/board', operator=True) order = next(o for o in board['orders'] if o['id'] == str(paid_order)) assert order['cancelled_at'] and order['cancel_reason'] == 'Cliente desistiu' + # The automatic folder hears it is cancelled, and so removes its files. + held = client.call('/operator/queue/folder', {'early': True, 'held': [str(paid_order)]}, operator=True) + assert held['states'] == {str(paid_order): 'cancelled'}, held['states'] + assert not [f for f in held['files'] if f['order'] == str(paid_order)] client.call(f'/operator/orders/{paid_order}/move', {'state': 'tra', 'version': order['version'], 'reason': ''}, operator=True, expected=409) client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'de novo'}, operator=True, expected=404) @@ -94,6 +98,9 @@ def run(): client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True) with db.connect() as c: assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone() + # Deleted: no state at all, so the folder removes its files too. + assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {} + with db.connect() as c: assert c.execute('SELECT discarded_at FROM dtf_local.quotes WHERE id=%s', (paid_quote,)).fetchone()['discarded_at'] assert str(paid_quote) not in listed() diff --git a/tests/print_file_test.py b/tests/print_file_test.py index cda309e..75f458f 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -90,9 +90,20 @@ def run(): assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 10 * PT_PER_CM) < 0.01, (width, height) print('PASS: paid order generated a 57 x 10 cm print file with both copies') + # The automatic folder, downloading on arrival, gets the generated file + # before anyone approves it; at the queue only, it does not. + oid = order['id'] + early = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True) + mine = [f for f in early['files'] if f['order'] == oid] + assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files'] + assert mine[0]['name'].startswith('pedido-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'} + late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True) + assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {} + client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401) + print('PASS: the folder gets a received order\'s generated file early, and only at the queue otherwise') + # The operator approves the generated file as the final one, with no upload, # and the order can then enter the print queue. - oid = order['id'] result = client.call('/operator/orders/' + oid + '/final-files', {'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], 'note': 'Generated print file checked'}, operator=True) diff --git a/web/kanban.js b/web/kanban.js index cbb27d2..b32fce3 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -207,22 +207,35 @@ const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=> 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 at the queue ('fil'), or as soon as the order arrives +// ('rec'), into a "Recebidos" folder inside the chosen one; the file moves up +// when the order enters the queue. Only a chosen folder can do that: Firefox +// downloads cannot be moved or removed afterwards. const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', - brave:!!navigator.brave,handle:null,granted:false,downloads:false, - saved:new Set(),busy:false,status:'',error:'',last:null,lastSig:null}; + brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'fil', + saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null}; +const RECEIVED='Recebidos'; // Switched on: a chosen folder released, or automatic downloads. const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads; +const early=()=>FOLDER.mode==='folder'&&FOLDER.when==='rec'; const savedKey=()=>FOLDER.mode==='folder'?'saved:'+FOLDER.handle.name:'saved:downloads'; +// What this folder received, by upload: its order, item, name and where it is +// ('early' in Recebidos, 'queue' in the folder, 'done' once printing). Older +// versions kept only the upload ids. +const savedMap=list=>new Map((list||[]).map(e=>typeof e==='string'?[e,{place:'done'}]:e)); +const loadSaved=async()=>savedMap(await kv.get(savedKey()).catch(()=>null)); +const keepSaved=()=>kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{}); async function restoreFolder(){ if(FOLDER.mode==='downloads'){ try{FOLDER.downloads=localStorage.getItem('dtf-auto-downloads')==='1';}catch{} - if(FOLDER.downloads)FOLDER.saved=new Set(await kv.get('saved:downloads').catch(()=>null)||[]); + if(FOLDER.downloads)FOLDER.saved=await loadSaved(); return; } if(FOLDER.mode!=='folder')return; - try{FOLDER.handle=await kv.get('folder')||null; + try{FOLDER.when=await kv.get('folder-when')==='rec'?'rec':'fil'; + FOLDER.handle=await kv.get('folder')||null; if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted'; - FOLDER.saved=new Set(await kv.get(savedKey())||[]); + FOLDER.saved=await loadSaved(); if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos da fila na pasta, abra Integrações e clique em “Liberar pasta”.',false,10000),2500);}} catch{FOLDER.handle=null;} } @@ -262,11 +275,19 @@ function folderCard(){ 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 [['fil','Baixar na Fila'],['rec','Baixar ao chegar']]){ + 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(), + summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),actions:[when], details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)], ['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'], - node('p','Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')], + node('p',FOLDER.when==='rec' + ?'Ao chegar: o arquivo do pedido é baixado em “'+h.name+'/'+RECEIVED+'” assim que o pedido chega, e passa para “'+h.name+'” quando entra na Fila de impressão.' + :'Na Fila: o arquivo é baixado em “'+h.name+'” quando o pedido entra na Fila de impressão.'), + node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai. '+ + 'Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')], extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]}); } row.id='folder-card';return row; @@ -287,7 +308,7 @@ async function chooseFolder(){ try{handle=await window.showDirectoryPicker({id:'dtf-fila',mode:'readwrite'});} catch(e){if(e.name==='AbortError')return;throw e;} FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null; - FOLDER.saved=new Set(await kv.get(savedKey()).catch(()=>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(); } @@ -302,53 +323,103 @@ async function forgetFolder(){ async function setDownloads(on){ FOLDER.downloads=on;FOLDER.lastSig=null;FOLDER.error='';FOLDER.status=''; try{localStorage.setItem('dtf-auto-downloads',on?'1':'0');}catch{} - if(on)FOLDER.saved=new Set(await kv.get('saved:downloads').catch(()=>null)||[]); + if(on)FOLDER.saved=await loadSaved(); paintFolder();say(on?'Download automático ligado.':'Download automático desligado.'); if(on)syncFolder(); } +async function setWhen(when){ + FOLDER.when=when;FOLDER.lastSig=null; + await kv.set('folder-when',when).catch(()=>{}); + paintFolder();say(when==='rec'?'Os arquivos vão ser baixados assim que o pedido chegar, em “'+RECEIVED+'”.':'Os arquivos vão ser baixados quando o pedido entrar na Fila.'); + syncFolder(true); +} -// Save what the queue has and this folder has not received yet. A file the -// FlexiPRINT moved away after importing is not downloaded again. After a board -// load it asks only when the queue changed; the folder's own timer always asks, -// since another computer may have moved the order while the board here is not -// refreshing by itself. +// A whole file in a folder: written under another name and renamed at the +// end, so the FlexiPRINT never sees half of it. `source` is a download's body +// or a file. +async function writeWhole(dir,name,source){ + const temp=await dir.getFileHandle(name+'.baixando',{create:true}); + const out=await temp.createWritable(); + try{if(source instanceof Blob){await out.write(source);await out.close();}else await source.pipeTo(out);} + catch(e){await out.abort().catch(()=>{});await dir.removeEntry(temp.name).catch(()=>{});throw e;} + await dir.removeEntry(name).catch(()=>{}); + // A browser that cannot rename a file outside its own storage copies it. + try{await temp.move(name);} + catch{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable(); + await whole.write(await temp.getFile());await whole.close();await dir.removeEntry(temp.name);} +} +const received=()=>FOLDER.handle.getDirectoryHandle(RECEIVED,{create:true}); +// Remove a saved file from where it is; one already gone (the FlexiPRINT +// took it) is fine. +async function removeSaved(rec){ + const dir=rec.place==='early'?await received():FOLDER.handle; + await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;}); +} +// From Recebidos up to the folder, when the order enters the queue. False when +// the file is no longer there, so it is downloaded again. +async function moveToQueue(rec){ + const from=await received();let file; + try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;} + await FOLDER.handle.removeEntry(rec.name).catch(()=>{}); + try{await file.move(FOLDER.handle);} + catch{await writeWhole(FOLDER.handle,rec.name,await file.getFile());await from.removeEntry(rec.name);} + return true; +} + +// Bring the folder in line with the board: remove the files of orders that +// were cancelled, deleted, sent back for correction or given another file; +// move up what entered the queue; download what is missing. A file the +// FlexiPRINT moved away after importing is not downloaded again. After a +// board load it asks only when something it follows changed; the folder's +// own timer always asks, since another computer may have moved the order. async function syncFolder(force=false){ if(!folderActive()||FOLDER.busy||!board||!may('produce'))return; - const sig=board.orders.filter(o=>o.state==='fil'&&!o.cancelled_at).map(o=>o.id+':'+o.version).join(','); + const follows=early()?['rec','tra','cor','fil']:['fil']; + const sig=FOLDER.when+'|'+board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at) + .map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(','); if(!force&&sig===FOLDER.lastSig)return; FOLDER.busy=true; try{ - const {files}=await api('/queue/finals?auto=1'); - const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id)); + const tidy=FOLDER.mode==='folder'; + const held=tidy?[...new Set([...FOLDER.saved.values()].filter(r=>r.order&&r.place!=='done').map(r=>r.order))]:[]; + const {files,states}=await api('/queue/folder',{early:early(),held}); + const wanted=new Map(files.map(f=>[f.order+':'+f.item,f])); const where=FOLDER.mode==='folder'?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; + let removed=0; + if(tidy)for(const [uid,rec] of [...FOLDER.saved]){ + if(!rec.order||rec.place==='done')continue; + const state=states[rec.order]; + if(state==='imp'||state==='fin'){rec.place='done';continue;} + const now=wanted.get(rec.order+':'+rec.item); + const expected=state==='fil'||early()&&(state==='rec'||state==='tra'); + if(state&&state!=='cancelled'&&state!=='cor'&&!(expected&&(!now||now.upload_id!==uid)))continue; + await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved(); + } + const pending=files.filter(f=>{const r=FOLDER.saved.get(f.upload_id);return !r||r.place==='early'&&f.state==='fil';}); for(const [i,file] of pending.entries()){ - 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{ - // The FlexiPRINT sees the file only once it is whole: it is written - // under another name and renamed at the end. - const temp=await FOLDER.handle.getFileHandle(file.name+'.baixando',{create:true}); - const out=await temp.createWritable(); - const r=await fetch(file.url,{referrerPolicy:'no-referrer'}); - if(!r.ok||!r.body){await out.abort();await FOLDER.handle.removeEntry(temp.name).catch(()=>{}); - throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');} - await r.body.pipeTo(out); - await FOLDER.handle.removeEntry(file.name).catch(()=>{}); - // A browser that cannot rename a file outside its own storage copies it. - try{await temp.move(file.name);} - catch{const whole=await (await FOLDER.handle.getFileHandle(file.name,{create:true})).createWritable(); - await whole.write(await temp.getFile());await whole.close();await FOLDER.handle.removeEntry(temp.name);} + const rec=FOLDER.saved.get(file.upload_id); + const up=!!rec&&await moveToQueue(rec); + if(!up){ + FOLDER.status=(FOLDER.mode==='folder'?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); + say(FOLDER.status,false,60000); + if(FOLDER.mode==='downloads'){ + // Firefox writes it as .part and renames it when whole. + const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click(); + await new Promise(r=>setTimeout(r,900)); + }else{ + const r=await fetch(file.url,{referrerPolicy:'no-referrer'}); + if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').'); + await writeWhole(file.state==='fil'?FOLDER.handle:await received(),file.name,r.body); + } } - FOLDER.saved.add(file.upload_id);FOLDER.last=new Date(); - await kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{}); + FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name, + place:file.state==='fil'||FOLDER.mode!=='folder'?'queue':'early'}); + FOLDER.last=new Date();await keepSaved(); } FOLDER.lastSig=sig;FOLDER.error=''; FOLDER.status=''; if(pending.length)say((FOLDER.mode==='folder'?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where+'.'); + if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos ou trocados saíram da pasta.'); }catch(e){ if(e.name==='NotAllowedError')FOLDER.granted=false; else if(e.name==='NotFoundError')FOLDER.error='A pasta “'+FOLDER.handle?.name+'” não foi encontrada. Ela foi apagada ou a rede caiu? Escolha a pasta de novo.';