feat: the orders' files in Dropstar's three folders: Arte recebida, Arte conferida, Finalizado
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 4m27s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m19s

Asked by Dropstar on 2026-10-23 and agreed on 2026-10-26. The automatic
folder becomes "Pastas dos pedidos": one main folder is chosen once, in
Chrome or Edge on a factory computer that reaches the server, and the
Kanban keeps three folders inside it, moved with the card.

- Arte recebida: the order's file as soon as the order arrives
- Arte conferida: the queue; the file moves there with the card and stays
  while it prints and is checked in Revisão
- Finalizado: when the order is released, kept 30 days
- 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 comes back only when its order moves on, so the
  server now returns the files of orders the folders hold while they print,
  are checked and finish
- Firefox, which cannot write into folders, still only downloads the files
  entering Arte conferida

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-26 16:31:20 -03:00
parent b6f20733fa
commit ee1159065a
5 changed files with 170 additions and 138 deletions

View File

@@ -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);