diff --git a/app/api/operator.py b/app/api/operator.py index 57d4ede..98efdc2 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -771,13 +771,13 @@ def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(o @router.get('/api/operator/queue/finals') -def queue_finals(request: Request, user=Depends(can('produce'))): +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,u.object_key,u.name FROM dtf_local.orders o + 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() @@ -796,8 +796,10 @@ def queue_finals(request: Request, user=Depends(can('produce'))): copy += 1 names.add(name) files.append({'number': row['number'], 'item': row['item_index'] + 1, 'name': name, - 'url': storage.download(row['object_key'], name)}) - audit('queue_finals_downloaded', operator=user, files=len(files)) + 'upload_id': str(row['upload_id']), 'url': storage.download(row['object_key'], name)}) + # 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} diff --git a/web/kanban.css b/web/kanban.css index ca2e42a..d051d84 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -444,4 +444,11 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom} .danger-text{color:var(--bad)} .machine-select{height:36px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px} .card .machine{color:var(--accent-tx)} +/* Fila de impressão's tools: Baixar, and the automatic folder (grey off, green saving, orange to release). */ +.coltools{display:flex;gap:6px;flex-shrink:0} +.autofolder{color:var(--faint);padding:0 8px} +.autofolder.on{color:var(--ok);border-color:rgba(111,209,156,.4)} +.autofolder.warn{color:var(--warn);border-color:rgba(242,179,61,.5)} +.autofolder.busy svg{animation:pulse 1s ease-in-out infinite alternate} +@keyframes pulse{to{opacity:.35}} diff --git a/web/kanban.js b/web/kanban.js index 6d0a313..7ba72b4 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -189,6 +189,99 @@ function download(uid){return async()=>{ const result=await api('/uploads/'+uid+'/download'); const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click(); };} +// ---- Automatic folder ------------------------------------------------------ +// The print queue's files, saved by this browser into a folder the operator +// chose (the FlexiPRINT folder, or the internal server's share), as orders +// enter Fila de impressão. Chrome and Edge only, while the Kanban is open. +// The folder is remembered; after the browser restarts it needs one click. +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 FOLDER={supported:'showDirectoryPicker' in window,handle:null,granted:false,saved:new Set(),busy:false,status:'',lastSig:null}; +async function restoreFolder(){ + if(!FOLDER.supported)return; + try{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('saved:'+FOLDER.handle.name)||[]); + if(!FOLDER.granted)setTimeout(()=>say('Clique na pasta laranja em Fila de impressão para voltar a salvar os arquivos sozinho.',false,10000),2500);}} + catch{FOLDER.handle=null;} +} +function folderLine(){ + const b=node('button',undefined,'btn ghost small autofolder');b.type='button';b.id='autofolder'; + b.append(icon(['M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z'])); + paintFolder(b);b.onclick=folderClick;return b; +} +function folderText(){ + const h=FOLDER.handle; + return !h?'Pasta automática desligada: clique para escolher a pasta onde os arquivos da fila são salvos sozinhos' + :!FOLDER.granted?'Clique para liberar a pasta “'+h.name+'” e voltar a salvar os arquivos da fila' + :FOLDER.status||'Salvando os arquivos da fila em “'+h.name+'”'; +} +function paintFolder(b=$('autofolder')){ + if(!b)return; + const h=FOLDER.handle;b.classList.toggle('on',!!h&&FOLDER.granted);b.classList.toggle('warn',!!h&&!FOLDER.granted); + b.classList.toggle('busy',FOLDER.busy);b.title=folderText();b.setAttribute('aria-label',folderText()); +} +async function chooseFolder(){ + const handle=await window.showDirectoryPicker({id:'dtf-fila',mode:'readwrite'}); + FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null; + FOLDER.saved=new Set(await kv.get('saved:'+handle.name).catch(()=>null)||[]); + await kv.set('folder',handle).catch(()=>{}); + paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder(); +} +async function folderClick(){ + try{ + if(FOLDER.handle&&!FOLDER.granted){ + FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted'; + FOLDER.lastSig=null;paintFolder();if(FOLDER.granted)syncFolder();return; + } + const back=node('div',undefined,'modal');const box=node('div',undefined,'modal-box'); + box.append(node('h2','Pasta automática'),node('p','Os arquivos finais dos pedidos que entram na Fila de impressão são salvos sozinhos '+ + 'nesta pasta, com o número do pedido no nome. Escolha a pasta que o FlexiPRINT lê, ou a pasta da rede do servidor. '+ + 'Funciona no Chrome e no Edge, enquanto o Kanban estiver aberto neste computador.','muted')); + if(FOLDER.handle)box.append(node('p','Pasta atual: “'+FOLDER.handle.name+'” · '+FOLDER.saved.size+' arquivo(s) já salvos','faint')); + const row=node('div',undefined,'modal-actions'); + const close=node('button','Fechar','btn ghost');close.type='button';close.onclick=()=>back.remove(); + const pick=button(FOLDER.handle?'Trocar pasta':'Escolher pasta',async()=>{back.remove();await chooseFolder();},'btn primary'); + if(FOLDER.handle)row.append(button('Desligar',async()=>{back.remove();FOLDER.handle=null;FOLDER.granted=false; + await kv.del('folder').catch(()=>{});paintFolder();say('Pasta automática desligada.');},'btn ghost')); + row.append(close,pick);box.append(row);back.append(box);back.onclick=e=>{if(e.target===back)back.remove();};document.body.append(back); + }catch(e){if(e.name!=='AbortError')say(e.message,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. +async function syncFolder(){ + if(!FOLDER.handle||!FOLDER.granted||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(','); + if(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)); + for(const [i,file] of pending.entries()){ + FOLDER.status='Salvando '+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); + say(FOLDER.status,false,60000); + 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();throw new Error('Não foi possível baixar '+file.name+'.');} + await r.body.pipeTo(out); + // The FlexiPRINT sees the file only once it is whole. + await FOLDER.handle.removeEntry(file.name).catch(()=>{}); + if('move' in temp)await temp.move(file.name); + FOLDER.saved.add(file.upload_id); + await kv.set('saved:'+FOLDER.handle.name,[...FOLDER.saved].slice(-3000)).catch(()=>{}); + } + FOLDER.lastSig=sig;FOLDER.status=pending.length?'Salvos '+pending.length+' arquivo(s) em “'+FOLDER.handle.name+'”':''; + if(pending.length)say(FOLDER.status+'.'); + }catch(e){ + if(e.name==='NotAllowedError'){FOLDER.granted=false;} + FOLDER.status='';say('Pasta automática: '+e.message,true); + }finally{FOLDER.busy=false;paintFolder();} +} + async function downloadQueue(){ const {files}=await api('/queue/finals'); if(!files.length){say('Nenhum arquivo final aprovado na fila.');return;} @@ -262,6 +355,7 @@ async function load(quiet=false){ $('login').hidden=true;$('app').hidden=false; if(!quiet)say('Atualizado às '+new Date().toLocaleTimeString('pt-BR')+tinyNotice,false,tinyNotice?6000:2500); render(); + syncFolder(); }catch(e){ if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;} // Not being signed in yet is the normal start, not an error. @@ -346,11 +440,15 @@ function renderBoard(){ // Finished orders are a recent window, not the whole history: say so. const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length); line.append(swatch,node('h2',title),node('span',count,'n')); - const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+' no total':'vazio')); + // The print queue's tools need the room: there it says only the metres. + const tools=state==='fil'&&may('produce'); + const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+(tools?'':' no total'):'vazio')); // The print queue's files, all at once, to import into FlexiPRINT. - if(state==='fil'&&orders.length&&may('produce')){ - const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila'; - sub.append(all); + if(tools){ + const tools=node('div',undefined,'coltools'); + if(orders.length){const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';tools.append(all);} + if(FOLDER.supported)tools.append(folderLine()); + sub.append(tools); } head.append(line,sub); column.append(head); @@ -1502,4 +1600,4 @@ function scheduleAuto(){ }; scheduleAuto(); })(); -load(); +restoreFolder().finally(()=>load());