feat: the print queue's automatic folder is switched on in Integrações
All checks were successful
Build and deploy / Validate source (push) Successful in 1m8s
Build and deploy / Integration suite on a real stack (push) Successful in 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m2s

The folder was a small icon beside "Baixar" in Fila de impressão, easy to
miss, and in Brave it silently fell back to downloads that Brave blocks.
It is now a card in Integrações, which operators also see (only that card):
choose the folder FlexiPRINT reads, or the internal server's share, and
every order that enters the queue has its final files saved there.

- Brave hides the folder API behind a flag; the card says so, shows the
  flag's address with a copy button, and points to Chrome or Edge.
- After a browser restart, a "!" on the Integrações tab and a "Liberar
  pasta" button ask for the one click the browser requires.
- The folder checks the queue every 30 s on its own, so an order moved on
  another computer is saved even with the board's auto-refresh off.
- A browser that cannot rename the finished file copies it instead of
  leaving it as .baixando; errors stay on the card until the next success.

Tested in Brave (flag off: the card explains; flag on: 12 queued files
saved, and an order moved by another session saved 23 s later), and the
browser test now checks that an order entering the queue lands in the folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-09 11:15:59 -03:00
parent 87cd7d77fb
commit 58ce0a4166
4 changed files with 142 additions and 106 deletions

View File

@@ -39,7 +39,7 @@ const may=cap=>!!ME?.can?.includes(cap);
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',operador:'Operador',vendedor:'Vendedor'};
// Which tabs each capability opens.
const TAB_NEEDS={quotes:o=>may('manage')||ME?.role==='vendedor',payments:()=>may('manage'),
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage'),users:()=>may('users')};
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage')||may('produce'),users:()=>may('users')};
function applyRole(){
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
@@ -191,9 +191,12 @@ function download(uid){return async()=>{
};}
// ---- Automatic folder ------------------------------------------------------
// The print queue's files, saved by this browser as orders enter Fila de
// impressão, while the Kanban is open. 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. Firefox cannot
// impressão, 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.
const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1);
@@ -201,131 +204,149 @@ const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>
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,downloads:false,
saved:new Set(),busy:false,status:'',lastSig:null};
const BRAVE_FLAG='brave://flags/#file-system-access-api';
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};
// Switched on: a chosen folder released, or automatic downloads.
const folderActive=()=>FOLDER.supported?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
const savedKey=()=>FOLDER.mode==='folder'?'saved:'+FOLDER.handle.name:'saved:downloads';
async function restoreFolder(){
if(!FOLDER.supported){
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)||[]);
return;
}
if(FOLDER.mode!=='folder')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);}}
FOLDER.saved=new Set(await kv.get(savedKey())||[]);
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;}
}
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;
// The card in Integrações, redrawn whenever the folder's state changes.
function folderCard(){
const name='Pasta da Fila de impressão', h=FOLDER.handle;
const primary=(text,fn)=>button(text,fn,'btn');
const ghost=(text,fn)=>button(text,fn,'btn ghost');
let card;
if(FOLDER.mode==='none'){
card=FOLDER.brave
? integration(name,'Desligada no Brave','warn','O Brave vem com o acesso a pastas desligado. Copie o endereço abaixo, cole na barra do Brave, '+
'mude “File System Access API” para “Enabled” e reinicie o Brave. Ou abra o Kanban no Chrome ou no Edge.',
[ghost('Copiar endereço',async()=>{await navigator.clipboard.writeText(BRAVE_FLAG);say('Endereço copiado: cole na barra do Brave.');})])
: integration(name,'Não funciona aqui','off','Este navegador não salva arquivos numa pasta. Abra o Kanban no Chrome ou no Edge. '+
'Aqui, use “Baixar” na Fila de impressão.');
if(FOLDER.brave)card.querySelector('p').after(node('code',BRAVE_FLAG,'flag'));
}else if(FOLDER.mode==='downloads'){
card=FOLDER.downloads
? integration(name,FOLDER.error?'Verificar':'Ligada',FOLDER.error?'warn':'ok',FOLDER.error||FOLDER.status||
'Os arquivos que entram na Fila de impressão são baixados sozinhos na pasta de downloads do Firefox. '+folderCount(),
[ghost('Desligar',()=>setDownloads(false))])
: integration(name,'Desligada','off','No Firefox, os arquivos vão para a pasta de downloads. Em Configurações → Geral → Arquivos e aplicativos, '+
'escolha em “Salvar arquivos em” a pasta do FlexiPRINT e desmarque “Sempre perguntar onde salvar arquivos”. '+
'Use um perfil do Firefox só para o Kanban: os outros downloads também vão para lá.',
[primary('Ligar download automático',()=>setDownloads(true))]);
}else if(!h){
card=integration(name,'Desligada','off','Escolha a pasta que o FlexiPRINT lê, ou a pasta da rede do servidor. Cada pedido que entra na '+
'Fila de impressão tem os arquivos finais salvos lá sozinhos, com o número do pedido no nome. Vale para este computador, com o Kanban aberto.',
[primary('Escolher pasta',chooseFolder)]);
}else if(!FOLDER.granted){
card=integration(name,'Liberar','warn','O navegador foi reaberto e pede um clique para voltar a salvar em “'+h.name+'”.',
[primary('Liberar pasta',releaseFolder),ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]);
}else{
card=integration(name,FOLDER.error?'Verificar':'Ligada',FOLDER.error?'warn':'ok',FOLDER.error||FOLDER.status||
'Os arquivos que entram na Fila de impressão são salvos em “'+h.name+'”. '+folderCount()+' Deixe o Kanban aberto neste computador.',
[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]);
}
card.id='folder-card';return card;
}
function folderText(){
const h=FOLDER.handle;
if(!FOLDER.supported)return FOLDER.downloads?FOLDER.status||'Baixando sozinho os arquivos que entram na fila (pasta de downloads do Firefox)'
:'Download automático desligado: clique para baixar sozinho os arquivos que entram na fila';
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 folderCount(){
const n=FOLDER.saved.size;
return (n?n+(n>1?' arquivos salvos':' arquivo salvo')+' neste computador':'Nenhum arquivo salvo ainda')+
(FOLDER.last?', o último às '+FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'')+'.';
}
function paintFolder(b=$('autofolder')){
if(!b)return;
const h=FOLDER.handle;b.classList.toggle('on',folderActive());b.classList.toggle('warn',FOLDER.supported&&!!h&&!FOLDER.granted);
b.classList.toggle('busy',FOLDER.busy);b.title=folderText();b.setAttribute('aria-label',folderText());
// The card and the tab's warning sign, which shows the folder needs a click.
function paintFolder(){
$('folder-card')?.replaceWith(folderCard());
const attention=may('produce')&&(FOLDER.mode==='folder'&&!!FOLDER.handle&&!FOLDER.granted||folderActive()&&!!FOLDER.error);
$('badge-integrations').textContent=attention?'!':'';
}
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)||[]);
let handle;
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)||[]);
await kv.set('folder',handle).catch(()=>{});
paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder();
}
async function folderClick(){
if(!FOLDER.supported)return downloadsDialog();
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);}
async function releaseFolder(){
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
FOLDER.lastSig=null;FOLDER.error='';paintFolder();if(FOLDER.granted)syncFolder();
}
// Firefox: the same, through ordinary downloads into Firefox's download folder.
function downloadsDialog(){
const back=node('div',undefined,'modal');const box=node('div',undefined,'modal-box');
box.append(node('h2','Download automático'),
node('p','Com o Kanban aberto, os arquivos finais dos pedidos que entram na Fila de impressão são baixados sozinhos, '+
'com o número do pedido no nome. Eles vão para a pasta de downloads do Firefox.','muted'));
const steps=node('ol',undefined,'steps-list');
for(const t of ['No Firefox, abra Configurações → Geral → Arquivos e aplicativos.',
'Em “Salvar arquivos em”, escolha a pasta que o FlexiPRINT lê (ou a pasta da rede do servidor).',
'Desmarque “Sempre perguntar onde salvar arquivos”.'])steps.append(node('li',t));
box.append(node('p','Para cair direto na pasta do FlexiPRINT:','muted'),steps,
node('p','Outros downloads deste Firefox também vão para essa pasta; por isso, use um perfil do Firefox só para o Kanban na sala de impressão.','faint'));
const row=node('div',undefined,'modal-actions');
const close=node('button','Fechar','btn ghost');close.type='button';close.onclick=()=>back.remove();
const toggle=button(FOLDER.downloads?'Desligar':'Ligar download automático',async()=>{
back.remove();FOLDER.downloads=!FOLDER.downloads;FOLDER.lastSig=null;
try{localStorage.setItem('dtf-auto-downloads',FOLDER.downloads?'1':'0');}catch{}
if(FOLDER.downloads){FOLDER.saved=new Set(await kv.get('saved:downloads').catch(()=>null)||[]);say('Download automático ligado.');syncFolder();}
else say('Download automático desligado.');
paintFolder();},FOLDER.downloads?'btn ghost':'btn primary');
row.append(close,toggle);box.append(row);back.append(box);back.onclick=e=>{if(e.target===back)back.remove();};document.body.append(back);
async function forgetFolder(){
FOLDER.handle=null;FOLDER.granted=false;FOLDER.error='';FOLDER.status='';
await kv.del('folder').catch(()=>{});paintFolder();say('Pasta automática desligada.');
}
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)||[]);
paintFolder();say(on?'Download automático ligado.':'Download automático desligado.');
if(on)syncFolder();
}
// 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(){
// 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.
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(',');
if(sig===FOLDER.lastSig)return;
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 where=FOLDER.supported?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
const memory=FOLDER.supported?'saved:'+FOLDER.handle.name:'saved:downloads';
const where=FOLDER.mode==='folder'?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
for(const [i,file] of pending.entries()){
FOLDER.status=(FOLDER.supported?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
FOLDER.status=(FOLDER.mode==='folder'?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
say(FOLDER.status,false,60000);
if(!FOLDER.supported){
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();
FOLDER.saved.add(file.upload_id);
await kv.set(memory,[...FOLDER.saved].slice(-3000)).catch(()=>{});
await new Promise(r=>setTimeout(r,900));
continue;
}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 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(memory,[...FOLDER.saved].slice(-3000)).catch(()=>{});
FOLDER.saved.add(file.upload_id);FOLDER.last=new Date();
await kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{});
}
FOLDER.lastSig=sig;FOLDER.status=pending.length?(FOLDER.supported?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where:'';
if(pending.length)say(FOLDER.status+'.');
FOLDER.lastSig=sig;FOLDER.error='';
FOLDER.status='';
if(pending.length)say((FOLDER.mode==='folder'?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where+'.');
}catch(e){
if(e.name==='NotAllowedError'){FOLDER.granted=false;}
FOLDER.status='';say('Pasta automática: '+e.message,true);
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);
}finally{FOLDER.busy=false;paintFolder();}
}
setInterval(()=>syncFolder(true),30000);
async function downloadQueue(){
const {files}=await api('/queue/finals');
@@ -412,7 +433,7 @@ function showTab(name){
tab=name;
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
for(const id of ['board','quotes','payments','stats','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents,users:loadUsers};
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
}
function render(){
@@ -424,7 +445,7 @@ function render(){
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
tinyHeader();renderBoard();renderIntegrations();
// Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents,users:loadUsers};
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
}
@@ -492,7 +513,6 @@ function renderBoard(){
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);}
tools.append(folderLine());
sub.append(tools);
}
head.append(line,sub);
@@ -1467,8 +1487,12 @@ function renderEvents(){
onSize:n=>{eventSize=n;eventPage=1;loadEvents().catch(e=>say(e.message,true));}}));
}
// An operator opens Integrações only for the print room's folder.
const eventsIfAllowed=async()=>{if(may('manage'))await loadEvents();};
function renderIntegrations(){
const t=board.tiny||{};const cards=[];
const t=board.tiny||{};const cards=may('produce')?[folderCard()]:[];
$('event-log').hidden=!may('manage');
if(!may('manage')){$('integrations').replaceChildren(...cards);return;}
if(!t.configured)cards.push(integration('Tiny','Não configurado','off','Credenciais ausentes no servidor.'));
else{
const connect=button(t.connected?'Reconectar':'Conectar Tiny',async()=>{const r=await api('/tiny/connect',{});location.href=r.url;},t.connected?'btn ghost':'btn');