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
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:
@@ -90,7 +90,7 @@ def backup_status(c):
|
||||
|
||||
|
||||
@router.post('/api/operator/backup/run')
|
||||
def backup_now(user=Depends(can('manage'))):
|
||||
def backup_now(user=Depends(can('integrations'))):
|
||||
"""A backup now, outside the daily hour: the backup service, which alone
|
||||
may read the whole database, starts it within a minute."""
|
||||
with db.connect() as c:
|
||||
@@ -271,7 +271,7 @@ def events(provider: Literal['tiny'] | None = None,
|
||||
status: Literal['delivered','queued','failing'] | None = None,
|
||||
event: Literal['payment_approved','production_started','correction_needed','ready','cancelled'] | None = None,
|
||||
order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0),
|
||||
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))):
|
||||
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('integrations'))):
|
||||
"""The integration send log, newest first, filtered, by page with a total."""
|
||||
clauses, params = [], []
|
||||
if provider:
|
||||
@@ -676,7 +676,7 @@ def tiny_status():
|
||||
**tiny.TinyAuth().status()}
|
||||
|
||||
@router.post('/api/operator/tiny/connect')
|
||||
def tiny_connect(user=Depends(can('manage'))):
|
||||
def tiny_connect(user=Depends(can('integrations'))):
|
||||
"""Start the one-time authorisation of this system in the client's Tiny."""
|
||||
if not tiny.configured():
|
||||
raise HTTPException(503, 'Tiny application is not configured')
|
||||
@@ -684,7 +684,7 @@ def tiny_connect(user=Depends(can('manage'))):
|
||||
return {'url': tiny.TinyAuth().authorize_url(user)}
|
||||
|
||||
@router.post('/api/operator/tiny/test')
|
||||
def tiny_test(user=Depends(can('manage'))):
|
||||
def tiny_test(user=Depends(can('integrations'))):
|
||||
"""Read one order and one contact from Tiny. Creates nothing."""
|
||||
if not tiny.configured():
|
||||
raise HTTPException(503, 'Tiny application is not configured')
|
||||
@@ -696,7 +696,7 @@ def tiny_test(user=Depends(can('manage'))):
|
||||
return {'ok': all(v == 'ok' for v in results.values()), 'results': results}
|
||||
|
||||
@router.post('/api/operator/mercadopago/check')
|
||||
def mercadopago_check(user=Depends(can('manage'))):
|
||||
def mercadopago_check(user=Depends(can('integrations'))):
|
||||
"""The Mercado Pago account behind the configured token; reads only."""
|
||||
if payment.name != 'mercadopago':
|
||||
raise HTTPException(409, 'Mercado Pago não está configurado')
|
||||
|
||||
@@ -211,7 +211,7 @@ def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||
|
||||
|
||||
@router.post('/api/operator/mail/test')
|
||||
def test_mail(request: Request, user=Depends(can('manage'))):
|
||||
def test_mail(request: Request, user=Depends(can('integrations'))):
|
||||
"""A message to whoever asked, to prove the mail server works."""
|
||||
with db.connect() as c:
|
||||
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
||||
|
||||
@@ -115,14 +115,17 @@ def login_failed(email):
|
||||
rate_limit('auth-account', email, 1_000_000)
|
||||
|
||||
# What each Kanban profile may do. "view" is reading; "produce" moves cards and
|
||||
# handles artwork; "manage" covers quotes, cancellations, payments and the
|
||||
# integrations; "users" is the Usuários page.
|
||||
# handles artwork; "manage" covers quotes, cancellations and payments; "users"
|
||||
# is the Usuários page; "integrations" is everything in Integrações but the
|
||||
# print room's folder (connecting Tiny, the checks, the backup, the Tiny log):
|
||||
# the others see there only what is on and off.
|
||||
ROLES = ('superadmin', 'admin', 'gestao', 'operador', 'vendedor')
|
||||
CAPABILITIES = {
|
||||
'view': set(ROLES),
|
||||
'produce': {'superadmin', 'admin', 'gestao', 'operador'},
|
||||
'manage': {'superadmin', 'admin', 'gestao'},
|
||||
'users': {'superadmin', 'admin'},
|
||||
'integrations': {'superadmin'},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -316,11 +316,17 @@ docs/guias/telas/.
|
||||
|
||||
The Kanban, open on the print room's computer, saves the files to a folder
|
||||
chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer,
|
||||
it downloads either when the order enters the print queue, or as soon as the
|
||||
order arrives: then into a `Recebidos` folder inside the chosen one, moved up
|
||||
when the order enters the queue. Files of orders cancelled, deleted or sent
|
||||
back for correction, and files replaced by another final, are removed from
|
||||
the folder (`POST /api/operator/queue/folder`).
|
||||
it downloads as soon as the order arrives in Arte recebida (the default since
|
||||
2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when
|
||||
the order enters the queue; or only when the order enters the print queue.
|
||||
Files of orders cancelled, deleted or sent back for correction, and files
|
||||
replaced by another final, are removed from the folder
|
||||
(`POST /api/operator/queue/folder`).
|
||||
|
||||
Integrações (2026-10-20): only the superadmin (us) has the buttons, the
|
||||
details and the Tiny log there (`integrations` capability, app/core/auth.py).
|
||||
Admins and gestão see each integration's state and summary; anyone who
|
||||
produces also gets the folder's row with its buttons.
|
||||
|
||||
### Active localhost milestone (2026-09-15)
|
||||
|
||||
|
||||
@@ -40,6 +40,13 @@ def run():
|
||||
su.call('/operator/users', {'name': 'X', 'email': f'x-{tag}@example.test', 'role': 'superadmin',
|
||||
'password': PASSWORD}, operator=True, expected=422)
|
||||
admin = signed_in(emails['admin'])
|
||||
# Integrações: an administrator sees what is on and off; only the superadmin acts there.
|
||||
assert 'integrations' not in admin.call('/operator/me')['can']
|
||||
assert 'integrations' in su.call('/operator/me', operator=True)['can']
|
||||
for path in ('/operator/tiny/connect', '/operator/tiny/test', '/operator/mercadopago/check',
|
||||
'/operator/mail/test', '/operator/backup/run'):
|
||||
admin.call(path, {}, expected=403)
|
||||
admin.call('/operator/events', expected=403)
|
||||
admin.call('/operator/users', {'name': 'Op', 'email': emails['operador'], 'role': 'operador',
|
||||
'password': PASSWORD, 'machines': [uv]})
|
||||
admin.call('/operator/users', {'name': 'Vendas', 'email': emails['vendedor'], 'role': 'vendedor',
|
||||
|
||||
@@ -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).');})],
|
||||
|
||||
Reference in New Issue
Block a user