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
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:
@@ -159,6 +159,17 @@ try{
|
||||
const oid=await kanban.eval(`board.orders.find(o=>o.quote_id===${JSON.stringify(qid)}).id`);
|
||||
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
|
||||
{kind:'sheet',copies:1,length:101,height:101,placed:1});
|
||||
// The print queue's folder, switched on in Integrações. The native picker
|
||||
// cannot be driven headless: it answers with a folder in the browser's own
|
||||
// storage, which has the same file API.
|
||||
await kanban.click('[data-tab="integrations"]');
|
||||
await waitFor(()=>kanban.eval('!!document.getElementById("folder-card")'),'folder card');
|
||||
await kanban.eval(`(async()=>{const root=await navigator.storage.getDirectory();
|
||||
window.picked=await root.getDirectoryHandle('fila-'+Date.now(),{create:true});
|
||||
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;})()`);
|
||||
// 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"]');
|
||||
@@ -183,6 +194,12 @@ try{
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
||||
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
||||
if(state==='fil'){
|
||||
// Entering the queue saves its final file there, whole and named after the order.
|
||||
const prefix='pedido-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||
await waitFor(async()=>(await savedFiles()).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file saved in the folder',45000);
|
||||
assert.equal((await savedFiles()).some(n=>n.endsWith('.baixando')),false);
|
||||
}
|
||||
}
|
||||
// Undo a mistaken move from the panel: one stage back with an internal reason.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="imp"]')`),'back button');
|
||||
|
||||
@@ -249,7 +249,7 @@ main{padding:0 24px 24px}
|
||||
.charttable summary{cursor:pointer}
|
||||
.charttable table{margin-top:8px}
|
||||
#stats-stages .swatch{display:inline-block;width:10px;height:10px;border-radius:3px;background:var(--c);margin-right:8px}
|
||||
.grid4{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px}
|
||||
.grid4{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px}
|
||||
.integration{display:flex;flex-direction:column;gap:10px;padding:16px;border-radius:12px;border:1px solid var(--line2);background:var(--card)}
|
||||
.integration .head{display:flex;align-items:center;gap:8px}
|
||||
.integration .head b{font-size:15px}
|
||||
@@ -257,6 +257,7 @@ main{padding:0 24px 24px}
|
||||
.integration .head em{margin-left:auto;font-style:normal;font-size:13.5px;font-weight:700;color:var(--dotx,var(--muted))}
|
||||
.integration p{margin:0;font-size:14px;color:var(--muted)}
|
||||
.integration .buttons{margin-top:auto}
|
||||
.integration code.flag{font-size:13px;padding:6px 8px;border-radius:8px;background:var(--card2);color:var(--tx2);user-select:all;overflow-wrap:anywhere}
|
||||
table.log{width:100%;border-collapse:collapse;font-size:14px}
|
||||
table.log th{text-align:left;color:var(--faint);font-weight:600;padding:8px 12px;border-bottom:1px solid var(--line)}
|
||||
table.log td{padding:10px 12px;border-bottom:1px solid #1E2226;vertical-align:top}
|
||||
@@ -444,12 +445,6 @@ 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). */
|
||||
/* Fila de impressão's tools: Baixar. */
|
||||
.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}}
|
||||
.steps-list{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:6px;font-size:14px;color:var(--tx2)}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<button type="button" data-tab="quotes" aria-selected="false">Cotações <span class="badge" id="badge-quotes"></span></button>
|
||||
<button type="button" data-tab="payments" aria-selected="false">Pagamentos <span class="badge warn" id="badge-payments"></span></button>
|
||||
<button type="button" data-tab="stats" aria-selected="false">Números</button>
|
||||
<button type="button" data-tab="integrations" aria-selected="false">Integrações</button>
|
||||
<button type="button" data-tab="integrations" aria-selected="false">Integrações <span class="badge warn" id="badge-integrations" title="A pasta da Fila de impressão precisa de atenção"></span></button>
|
||||
<button type="button" data-tab="users" aria-selected="false" hidden>Usuários</button>
|
||||
</nav>
|
||||
<div class="searchbox">
|
||||
@@ -98,7 +98,7 @@
|
||||
<section id="tab-integrations" class="page" hidden>
|
||||
<h1>Integrações</h1>
|
||||
<section><div class="grid4" id="integrations"></div></section>
|
||||
<section><h2>Registro de envios</h2>
|
||||
<section id="event-log"><h2>Registro de envios</h2>
|
||||
<div class="filters" id="event-filters"></div>
|
||||
<table class="log"><thead><tr><th scope="col">Quando</th><th scope="col">Pedido</th><th scope="col">Destino</th><th scope="col">Evento</th><th scope="col">Resultado</th></tr></thead><tbody id="events"></tbody></table>
|
||||
<div id="events-more"></div>
|
||||
|
||||
216
web/kanban.js
216
web/kanban.js
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user