feat: the folder can download as the order arrives, and removes cancelled orders' files
All checks were successful
Build and deploy / Validate source (push) Successful in 14s
Build and deploy / Integration suite on a real stack (push) Successful in 5m5s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m23s

Integrações gets "Baixar ao chegar" next to "Baixar na Fila". On arrival the
file (the generated print file, or the final once approved) goes into a
Recebidos folder inside the chosen one and moves up when the order enters
the queue. Files of orders cancelled, deleted or sent back for correction,
and files replaced by another final, leave the folder.

The launch reset now restarts order numbers at #1 by itself: the worker's
role may set the orders' number sequence, and nothing else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-16 15:07:29 -03:00
parent b83e60ef0c
commit 4a2ce72764
9 changed files with 244 additions and 63 deletions

View File

@@ -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.';