feat: Integrações buttons only for the superadmin; the folder downloads in Arte recebida by default
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 47s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-20 09:55:31 -03:00
parent c8857a5bf5
commit df30046027
6 changed files with 52 additions and 33 deletions

View File

@@ -207,12 +207,12 @@ 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
// `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 ('fil'). 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,when:'fil',
brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'rec',
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
const RECEIVED='Recebidos';
// Switched on: a chosen folder released, or automatic downloads.
@@ -232,7 +232,7 @@ async function restoreFolder(){
return;
}
if(FOLDER.mode!=='folder')return;
try{FOLDER.when=await kv.get('folder-when')==='rec'?'rec':'fil';
try{FOLDER.when=await kv.get('folder-when')==='fil'?'fil':'rec';
FOLDER.handle=await kv.get('folder')||null;
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
FOLDER.saved=await loadSaved();
@@ -276,7 +276,7 @@ function folderCard(){
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']]){
for(const [value,text] of [['rec','Baixar em Arte recebida'],['fil','Baixar na Fila de impressão']]){
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',
@@ -284,8 +284,8 @@ function folderCard(){
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'
?'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.'),
?'Em Arte recebida: 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 de impressão: 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)]});
@@ -1625,22 +1625,25 @@ 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();};
// Integrações: the print room's folder for whoever produces, what is on and off
// for the managers, and the buttons, details and the Tiny log for the superadmin.
const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();};
// A row with only its name, state and summary, for whoever may not change it.
const integRow=o=>may('integrations')?integration(o):integration({name:o.name,state:o.state,tone:o.tone,summary:o.summary});
let mpCheck=null;
function renderIntegrations(){
const t=board.tiny||{};const rows=may('produce')?[folderCard()]:[];
$('event-log').hidden=!may('manage');
$('event-log').hidden=!may('integrations');
if(!may('manage')){$('integrations').replaceChildren(...rows);return;}
const act=(text,fn)=>button(text,fn,'btn small');
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
if(!t.configured)rows.push(integration({name:'Tiny',state:'Não configurado',tone:'off',summary:'Credenciais ausentes no servidor.'}));
if(!t.configured)rows.push(integRow({name:'Tiny',state:'Não configurado',tone:'off',summary:'Credenciais ausentes no servidor.'}));
else{
const connect=(text,cls)=>button(text,async()=>{const r=await api('/tiny/connect',{});location.href=r.url;},cls);
const test=act('Testar conexão',async()=>{const r=await api('/tiny/test',{});
say(r.ok?'Conexão com o Tiny ok: pedidos, contatos, os 4 produtos e a retirada conferidos.':'Tiny: '+Object.entries(r.results).filter(([,v])=>v!=='ok').map(([k,v])=>k+': '+v).join(' · '),!r.ok);});
const problem=TINY_PROBLEMS[t.problem];
rows.push(integration({name:'Tiny',state:!t.connected?'Não conectado':t.problem?'Verificar':'Conectado',tone:t.connected&&!t.problem?'ok':'warn',
rows.push(integRow({name:'Tiny',state:!t.connected?'Não conectado':t.problem?'Verificar':'Conectado',tone:t.connected&&!t.problem?'ok':'warn',
summary:problem||(t.connected_by?t.connected_by+' · envio de pedidos '+(t.orders_enabled?'ativo':'desativado'):'Conecte com uma conta do Tiny.'),
actions:t.connected?[test]:[connect('Conectar Tiny','btn small')],
details:t.connected_by?[['Conta',t.connected_by],['Conectado em',when(t.connected_at)],['Renovado em',when(t.renewed_at)],
@@ -1650,7 +1653,7 @@ function renderIntegrations(){
extra:t.connected?[connect('Reconectar','btn ghost small')]:[]}));
}
const mp=board.providers?.payment==='mercadopago';
rows.push(integration({name:'Mercado Pago',state:mp?'Ativo':'Não configurado',tone:mp?'ok':'off',
rows.push(integRow({name:'Mercado Pago',state:mp?'Ativo':'Não configurado',tone:mp?'ok':'off',
summary:mp?'PIX e cartão ativos.':'Aguardando credenciais.',
actions:mp?[ghost('Verificar conta',async()=>{mpCheck=await api('/mercadopago/check',{});OPEN_INTEG.add('Mercado Pago');renderIntegrations();})]:[],
details:mp&&mpCheck?mercadoPagoCheck(mpCheck):[]}));
@@ -1659,7 +1662,7 @@ function renderIntegrations(){
const carriers=Object.values(fr.services||{});
const list=names=>names.length>1?names.slice(0,-1).join(', ')+' e '+names.at(-1):names[0];
rows.push(carriers.length
? integration({name:'Frete',state:fr.box_cm?'Ativo':'Verificar',tone:fr.box_cm?'ok':'warn',
? integRow({name:'Frete',state:fr.box_cm?'Ativo':'Verificar',tone:fr.box_cm?'ok':'warn',
summary:fr.box_cm?list([...carriers,'retirada em Franca'])+' · prazo + '+fr.production_days+' dia(s) de produção.'
:'Caixa não configurada: as transportadoras podem cobrar mais que a cotação.',
details:[['Opções',list(carriers)],['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
@@ -1668,17 +1671,17 @@ function renderIntegrations(){
...(fr.metres_per_box?[['Por caixa','Até '+String(fr.metres_per_box).replace('.',',')+' m']]:[])]:[]),
// Each carrier charges the larger of the real and the cubed weight.
node('p','No carrinho o cliente vê todas as opções, da mais barata para a mais cara, com o prazo. Cada transportadora cobra o maior entre o peso real e o cubado.')]})
: integration({name:'Frete',state:'Não configurado',tone:'off',summary:'Somente retirada.'}));
: integRow({name:'Frete',state:'Não configurado',tone:'off',summary:'Somente retirada.'}));
rows.push(mailRow(board.providers?.mail||{}));
const bk=board.providers?.backup||{};
const ontem=bk.last_ok&&Date.now()-new Date(bk.last_ok)<26*3600e3;
const tam=bk.bytes?(bk.bytes<1048576?Math.max(1,Math.round(bk.bytes/1024))+' KB':(bk.bytes/1048576).toFixed(1).replace('.',',')+' MB'):'';
const never=!bk.last_ok&&!bk.failed;
const now=may('manage')&&!never?[button(bk.requested?'Pedido…':'Fazer backup agora',async()=>{
const now=may('integrations')&&!never?[button(bk.requested?'Pedido…':'Fazer backup agora',async()=>{
try{await api('/backup/run',{});say('Backup pedido: começa em até 1 minuto. Atualize para ver o resultado.');await load();}
catch(e){say(e.message,true);}},'btn small')]:[];
if(bk.requested&&now[0])now[0].disabled=true;
rows.push(integration({name:'Backup do banco',state:never?'Não configurado':ontem&&!bk.failed?'Em dia':'Verificar',
rows.push(integRow({name:'Backup do banco',state:never?'Não configurado':ontem&&!bk.failed?'Em dia':'Verificar',
tone:never?'off':ontem&&!bk.failed?'ok':'warn',actions:now,
summary:bk.requested?'Backup pedido · começa em até 1 minuto.':
bk.failed?'A última tentativa falhou ('+when(bk.failed_at)+').':bk.last_ok?'Último em '+when(bk.last_ok)+(tam?' · '+tam:''):'Nenhum backup feito ainda.',
@@ -1690,10 +1693,10 @@ function renderIntegrations(){
// E-mail: the customers' messages (app/mail.py).
function mailRow(m){
const name='E-mail';
if(m.adapter!=='smtp'&&m.adapter!=='log')return integration({name,state:'Não configurado',tone:'off',
if(m.adapter!=='smtp'&&m.adapter!=='log')return integRow({name,state:'Não configurado',tone:'off',
summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'});
const local=m.adapter==='log';
return integration({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
return integRow({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'E-mails dos clientes: confirmação de pedido, recuperação de senha e códigos de confirmação.',
actions:[button('Enviar teste',async()=>{const r=await api('/mail/test',{});
say(local?'Teste registrado. Neste ambiente os e-mails ficam só no registro do servidor.':'Teste enviado para '+r.to+'. Confira a caixa de entrada (e o spam).');})],