feat: Kanban profiles, a Usuários page, and machines that route orders

Every operator could do everything, and accounts were made from the
console. Each account now has a profile, checked by the server on every
action: Administrador (everything, plus users and machines), Gestão
(everything but users), Operador (moves cards and handles artwork) and
Vendedor (reads orders, quotes and Números, changes nothing). The
superadmin is the system's own account, set from the console and kept by
the account OPERATOR_EMAIL seeds; administrators cannot change it, and
nobody can delete, disable or demote themselves.

The Usuários tab creates, edits, disables and deletes users with a first
password (there is no e-mail yet), and registers machines with the
products each prints. An order goes to the first active machine that
prints its product, or to the one chosen in its panel; an operator tied
to machines sees and downloads only their orders. Everyone changes their
own password in the account menu, which now holds the name and Sair too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-07 15:00:00 -03:00
parent 6c2dcc77b0
commit c75c40ff28
12 changed files with 719 additions and 66 deletions

View File

@@ -73,9 +73,12 @@ input[type=file]{font-size:14px;color:var(--muted);max-width:100%}
.tinydot{display:flex;align-items:center;gap:8px;font-size:14px;color:var(--muted);white-space:nowrap}
.tinydot::before{content:"";width:8px;height:8px;border-radius:999px;background:var(--dot,#5B6168)}
.tinydot:empty{display:none}
.who{font-size:14px;color:var(--muted);white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis}
/* With five tabs, the operator's e-mail is the first thing to give way; it stays on Sair's tooltip. */
@media (max-width:1560px){.who{display:none}}
.account{margin-left:0}
.account .btn{min-width:38px;padding:0 10px;font-weight:800;letter-spacing:.02em}
.account .menu{min-width:240px}
.menu-head{display:flex;flex-direction:column;gap:2px;padding:8px 10px 10px;border-bottom:1px solid var(--line2);margin-bottom:4px}
.menu-head b{font-size:14.5px}
.menu-head span{font-size:12.5px;color:var(--faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#status{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:20;margin:0;max-width:min(640px,calc(100vw - 32px));padding:10px 16px;border-radius:10px;border:1px solid var(--line3);background:#1E2226;color:var(--tx);font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.45)}
#status:empty,#login-status:empty{display:none}
#status.error{border-color:var(--bad-line);color:var(--bad)}
@@ -422,3 +425,23 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
.refresh .btn{border:0;border-radius:0;display:inline-flex;align-items:center;gap:6px}
.refresh select{width:88px;height:36px;padding:0 24px 0 10px;border:0;border-left:1px solid var(--line2);background:transparent;color:var(--muted);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer}
.refresh select option{background:var(--card);color:var(--tx)}
/* Usuários: dialogs for users and machines, and the tables. */
.modal{position:fixed;inset:0;z-index:50;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;padding:16px}
.modal-box{width:min(460px,100%);max-height:calc(100vh - 32px);overflow:auto;display:flex;flex-direction:column;gap:14px;padding:22px;
border-radius:14px;border:1px solid var(--line3);background:var(--panel)}
.modal-box h2{margin:0;font-size:18px}
.mfield{display:flex;flex-direction:column;gap:6px;font-size:13.5px;font-weight:600;color:var(--muted)}
.mfield input:not([type=checkbox]),.mfield select{height:40px;padding:0 12px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px;font-weight:500}
.mfield .check{font-weight:500}
.modal-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:4px}
#tab-users .pagehead h2{margin:0}
#tab-users .pagehead .btn{margin-left:auto}
#tab-users td.actions{text-align:right;white-space:nowrap}
#tab-users td.actions .btn+.btn{margin-left:6px}
#tab-users tr.off td{opacity:.55}
.faint.block{display:block;font-size:13px}
.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)}

View File

@@ -22,6 +22,7 @@
<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="users" aria-selected="false" hidden>Usuários</button>
</nav>
<div class="searchbox">
<label class="search">
@@ -32,7 +33,7 @@
<div id="search-results" class="results" role="listbox" aria-label="Resultados da busca" hidden></div>
</div>
<span id="tiny" class="tinydot"></span>
<span id="who" class="who"></span>
<div class="refresh">
<button class="btn ghost" id="refresh" type="button"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"></path><path d="M21 3v6h-6"></path></svg>Atualizar</button>
<select id="refresh-every" aria-label="Atualizar sozinho a cada">
@@ -40,7 +41,14 @@
<option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option>
</select>
</div>
<button class="btn ghost" id="logout" type="button">Sair</button>
<div class="morewrap account">
<button class="btn ghost" id="account" type="button" aria-haspopup="menu" aria-label="Minha conta"><span id="initials">·</span></button>
<div class="menu" id="account-menu" role="menu" hidden>
<div class="menu-head"><b id="who"></b><span id="who-role"></span></div>
<button class="menuitem" id="my-password" type="button">Minha senha</button>
<button class="menuitem" id="logout" type="button">Sair</button>
</div>
</div>
</header>
<p id="status" role="status"></p>
<main>
@@ -77,6 +85,16 @@
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>
</section>
</section>
<section id="tab-users" class="page" hidden>
<div class="pagehead"><h1>Usuários</h1><button class="btn primary" id="new-user" type="button">Novo usuário</button></div>
<p class="faint stats-note">Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página.
Gestão: tudo, menos usuários. Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquinas</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
<p class="faint stats-note">Cada pedido vai para a primeira máquina ativa que imprime o produto dele; no pedido dá para escolher outra.
Um operador ligado a máquinas vê só os pedidos delas.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Produtos</th><th scope="col">Situação</th><th scope="col"></th></tr></thead><tbody id="machines-list"></tbody></table></section>
</section>
<section id="tab-integrations" class="page" hidden>
<h1>Integrações</h1>
<section><div class="grid4" id="integrations"></div></section>

View File

@@ -33,6 +33,17 @@ let quoteKind='pending', pickedQuote=null;
let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=null;
// Uploads that have an artwork picture (the customer's browser made it). Every
// list the API returns says which, so only pictures that exist are asked for.
// The signed-in operator and what their profile allows (app/core/auth.py).
let ME=null;
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')};
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');
}
const THUMBS=new Set();
// Company names by CNPJ, from the public registry (app/cnpj.py).
const NAMES=new Map();
@@ -83,6 +94,7 @@ const ICON_OK=['M5 12l4 4 10-10'], ICON_WARN=['M12 8v5M12 17h.01','circle 12 12
const ICON_TRUCK=['M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2','M15 18H9',
'M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14','circle 17 18 2','circle 7 18 2'];
const ICON_PIN=['M20 10c0 4.99-5.54 10.19-7.4 11.8a1 1 0 0 1-1.2 0C9.54 20.19 4 14.99 4 10a8 8 0 0 1 16 0','circle 12 10 3'];
const ICON_PRINTER=['M6 9V2h12v7','M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2','M6 14h12v8H6z'];
const ICON_DOWNLOAD=['M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4','m7 10 5 5 5-5','M12 15V3'];
const ICON_CHAT=['M7.9 20A9 9 0 1 0 4 16.1L2 22Z'];
const ICON_COPY=['M9 9h12v12H9z','M5 15V5a2 2 0 0 1 2-2h10'];
@@ -241,7 +253,8 @@ function itemPreview(item){
let seenOrders=null, seenPending=null, unseen=0;
async function load(quiet=false){
try{
board=absorb(await api('/board'));
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
board=absorb(loaded);ME=me;applyRole();
noticeNew(quiet);
const known=new Set(board.orders.map(o=>o.id));
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
@@ -259,18 +272,20 @@ async function load(quiet=false){
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'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents};
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};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
}
function render(){
$('who').textContent=board.operator||'';$('logout').title=board.operator?'Sair ('+board.operator+')':'Sair';
$('who').textContent=ME?(ME.name||ME.email):'';
$('who-role').textContent=ME?(ROLE_NAMES[ME.role]||ME.role)+' · '+ME.email:'';
$('initials').textContent=ME?((ME.name||ME.email).trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()):'·';
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
$('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};
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents,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();}
}
@@ -333,7 +348,7 @@ function renderBoard(){
line.append(swatch,node('h2',title),node('span',count,'n'));
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+' no total':'vazio'));
// The print queue's files, all at once, to import into FlexiPRINT.
if(state==='fil'&&orders.length){
if(state==='fil'&&orders.length&&may('produce')){
const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';
sub.append(all);
}
@@ -361,7 +376,7 @@ function renderBoard(){
// An operator's test order: no payment, no Tiny, no WhatsApp.
const isTest=order=>order.payment?.provider==='teste';
function card(order){
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at;
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at&&may('produce');
if(order.id===openOrder)c.classList.add('open');
const s=order.snapshot;
const top=node('div',undefined,'row');
@@ -379,6 +394,7 @@ function card(order){
if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
}
c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination));
if(order.machine&&order.state!=='fin'){const m=node('div',undefined,'place machine');m.append(icon(ICON_PRINTER),order.machine.name);c.append(m);}
if(flags.children.length)c.append(flags);
c.onclick=()=>openPanel(order.id);
c.ondragstart=e=>{
@@ -489,6 +505,7 @@ function renderPanel(order){
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'Cliente retira na fábrica'));
if(dest&&s.freight?.total_cents)where.append(node('span','Jadlog · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
facts.append(who,where);
if(order.machine||board.machines?.length)facts.append(machineCard(order));
const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow'));
const itemsList=node('div');itemsList.style.display='flex';itemsList.style.flexDirection='column';itemsList.style.gap='10px';
s.items.forEach((item,index)=>itemsList.append(itemCard(order,item,index)));
@@ -503,6 +520,12 @@ function renderPanel(order){
}
function moves(order){
const box=node('div',undefined,'panel-actions');
if(!may('produce')){
// Sellers read the order; a correction's notice is theirs to send too.
if(order.state==='cor'&&!order.cancelled_at)box.append(correctionNotice(order));
box.append(node('p',order.cancelled_at?'Pedido cancelado.':'Somente consulta: seu perfil não move pedidos.','muted'));
return box;
}
if(order.cancelled_at){
const note=node('div',undefined,'callout bad');
note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason));
@@ -510,7 +533,7 @@ function moves(order){
if(!window.confirm('Excluir o pedido #'+order.number+' de vez? Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.'))return;
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load();
},'btn danger');remove.style.alignSelf='flex-start';
box.append(note,remove);return box;
box.append(note,...(may('manage')?[remove]:[]));return box;
}
// In correction, the customer has to be told: a message ready to send on
// WhatsApp with the reason and where to send the new file.
@@ -592,7 +615,7 @@ function moves(order){
more.setAttribute('aria-haspopup','menu');
more.onclick=e=>{e.stopPropagation();menu.hidden=!menu.hidden;
if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;},{once:true});};
const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);row.append(wrap);
const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);if(may('manage'))row.append(wrap);
const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true;
const sendFix=node('button','Enviar para correção','btn danger');
reason.append(text,sendFix);
@@ -728,7 +751,7 @@ function itemCard(order,item,index){
else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
if(!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
buttons.append(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn ghost'));
body.append(buttons);
box.append(preview,body);return box;
@@ -746,7 +769,7 @@ function finalsSection(order,revisions,section){
// Approving is the button at the top; this is for replacing an approved
// final, or sending one before the art is marked as handled.
// Before approval in Arte tratada, the step at the top is the way in.
if(!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
if(!may('produce')||!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
const form=finalForm(order,readyFinals(order).map(()=>null));
const open=node('button',finalDone(order)?'Enviar nova versão':'Enviar arquivo final','btn ghost');open.type='button';
open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();};
@@ -765,6 +788,126 @@ function historySection(order,rows,section){
section.replaceChildren(node('p','Histórico','eyebrow'),list);
}
// ---- Machines and users ----------------------------------------------------
// The order's machine: chosen, or the first that prints its product.
function machineCard(order){
const box=node('div',undefined,'fcard');box.append(node('p','Máquina','eyebrow'));
const current=order.machine;
if(!may('produce')||!board.machines?.length){
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'));return box;
}
const select=node('select',undefined,'machine-select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Automática'+(current&&!current.chosen?' ('+current.name+')':''));auto.value='';select.append(auto);
for(const m of board.machines.filter(m=>m.active||m.id===current?.id)){
const o=node('option',m.name);o.value=m.id;select.append(o);
}
select.value=current?.chosen?current.id:'';
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'Máquina automática pelo produto.');await load();}
catch(e){say(e.message,true);}};
box.append(select,node('span',current?.chosen?'Escolhida para este pedido.':'Pelo produto do pedido.','faint'));
return box;
}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
let usersData=null;
async function loadUsers(){
usersData=await api('/users');
renderUsers();
}
function renderUsers(){
const {users,machines}=usersData;
const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
const rows=users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email,'faint block'));
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—'));
const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint');
const actions=node('td',undefined,'actions');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
if(editable)actions.append(button('Editar',()=>userForm(u),'btn ghost small'));
if(editable&&u.email!==ME.email)actions.append(button('Excluir',async()=>{
if(!window.confirm('Excluir o usuário '+(u.name||u.email)+'? Ele perde o acesso na hora. O histórico dos pedidos continua com o e-mail dele.'))return;
await api('/users/'+u.id+'/delete',{});say('Usuário excluído.');await loadUsers();},'btn ghost small danger-text'));
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':' · desativado')),machinesTd,seen,actions);return tr;
});
$('users-list').replaceChildren(...rows);
$('machines-list').replaceChildren(...(machines.length?machines.map(m=>{
const tr=node('tr');if(!m.active)tr.classList.add('off');
const actions=node('td',undefined,'actions');
actions.append(button('Editar',()=>machineForm(m),'btn ghost small'),button('Excluir',async()=>{
if(!window.confirm('Excluir a máquina '+m.name+'? Os pedidos dela voltam para a escolha automática.'))return;
await api('/machines/'+m.id+'/delete',{});say('Máquina excluída.');await loadUsers();await load();},'btn ghost small danger-text'));
tr.append(node('td',m.name),node('td',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto'),
node('td',m.active?'Ativa':'Desativada'),actions);return tr;
}):[(()=>{const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada. Sem máquinas, todos os pedidos aparecem para todos.','faint');td.colSpan=4;tr.append(td);return tr;})()]));
}
// One dialog for creating and editing, for users and machines alike.
function dialog(title,fields,onsave){
const back=node('div',undefined,'modal');const form=node('form',undefined,'modal-box');
form.append(node('h2',title),...fields);
const row=node('div',undefined,'modal-actions');
const cancel=node('button','Cancelar','btn ghost');cancel.type='button';cancel.onclick=()=>back.remove();
const save=node('button','Salvar','btn primary');row.append(cancel,save);form.append(row);
form.onsubmit=async e=>{e.preventDefault();save.disabled=true;try{await onsave();back.remove();}catch(err){say(err.message,true);save.disabled=false;}};
back.onclick=e=>{if(e.target===back)back.remove();};
back.append(form);document.body.append(back);form.querySelector('input,select')?.focus();
}
function field(label,input){const l=node('label',undefined,'mfield');l.append(label,input);return l;}
function userForm(u){
const editing=!!u;
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';
const role=node('select');
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','operador','vendedor'];
for(const r of roles){const o=node('option',ROLE_NAMES[r]);o.value=r;role.append(o);}
role.value=u?.role||'operador';role.disabled=u?.role==='superadmin'||u?.email===ME.email;
const pass=node('input');pass.type='password';pass.minLength=12;pass.maxLength=128;pass.autocomplete='new-password';
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'12 caracteres ou mais';
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
const boxes=usersData.machines.map(m=>{const c=node('input');c.type='checkbox';c.value=m.id;c.checked=!!u?.machines.includes(m.id);
const l=node('label',undefined,'check');l.append(c,m.name);return l;});
const machinesField=node('div',undefined,'mfield');
machinesField.append('Máquinas (só para operadores; nenhuma = todas)',...(boxes.length?boxes:[node('span','Nenhuma máquina cadastrada.','faint')]));
const syncMachines=()=>{machinesField.hidden=role.value!=='operador';};role.onchange=syncMachines;syncMachines();
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
machines:role.value==='operador'?boxes.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value):[],
password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
});
}
function machineForm(m){
const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';
const prods=['textil','uv'].map(p=>{const c=node('input');c.type='checkbox';c.value=p;c.checked=!!m?.products.includes(p);
const l=node('label',undefined,'check');l.append(c,'Imprime '+PRODUCT_LABEL[p]);return l;});
const active=node('input');active.type='checkbox';active.checked=m?m.active:true;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativa (recebe pedidos)');
const prodField=node('div',undefined,'mfield');prodField.append('Produtos',...prods);
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),prodField,activeLabel],async()=>{
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,
products:prods.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value)});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
});
}
function passwordForm(){
const current=node('input');current.type='password';current.required=true;current.autocomplete='current-password';
const next=node('input');next.type='password';next.required=true;next.minLength=12;next.autocomplete='new-password';
const again=node('input');again.type='password';again.required=true;again.minLength=12;again.autocomplete='new-password';
dialog('Minha senha',[field('Senha atual',current),field('Nova senha (12 caracteres ou mais)',next),field('Repita a nova senha',again)],async()=>{
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
});
}
$('my-password').onclick=()=>{$('account-menu').hidden=true;passwordForm();};
$('account').onclick=e=>{e.stopPropagation();const m=$('account-menu');m.hidden=!m.hidden;
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;},{once:true});};
$('new-user').onclick=()=>userForm(null);
$('new-machine').onclick=()=>machineForm(null);
// ---- Numbers -------------------------------------------------------------
let statsDays=30;
@@ -947,7 +1090,7 @@ function review(quote){
content.append(sums);
}
card.append(head,content);
if(quote.status==='approved'){
if(quote.status==='approved'&&may('manage')){
foot.append(discardButton(quote));
// Tries the whole production flow without a payment.
foot.append(button('Criar pedido de teste',async()=>{
@@ -959,6 +1102,10 @@ function review(quote){
}
return card;
}
if(!may('manage')){
quote.draft.items.forEach(item=>content.append(quoteItem(item,null)));
card.append(head,content);return card;
}
const form=node('form');form.style.display='contents';
const edits=quote.draft.items.map(item=>{const fields={};content.append(quoteItem(item,fields));
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});