Files
dtf-system/web/kanban-users.js
Cauê Faleiros d0ec629c4e fix: Kanban pulls and final approvals stop failing on stale or missing context
Sentry DTF-WEB-4..7 (12/11):
- Pulling a card with no machine asks which machine takes it (gestão and
  admins); an operator always pulls to the machine of their session.
- The alert before a pull only offers Feito/Adiar to the machine's own
  operator or management, as the machine sheet does.
- A final-file approval from a dialog opened before the same approval
  went through reloads and says it was already approved, instead of the
  409 "O pedido mudou".

Built by Prensa; machine cards shared between the two choosers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:48:41 -03:00

645 lines
38 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Kanban DTF: the Usuários tab. People, print machines and each machine's
sheet (front 1a). Loaded after kanban.js, which defines $, api, node,
button, svgIcon, IC, iconButton, emptyState, may, money, when, ago, say,
plural, metres, field, checkbox, formDialog, modal, dialogHost, ask, board,
ME, myMachine, move, load, openFilters, closeFilters, ROLE_NAMES and kanbanTheme (theme.js). */
// ---- Machines and users ----------------------------------------------------
// One machine to choose: what it prints now, and who else is on it.
function machineChoice(machine,mine=false){
const b=node('button',undefined,'mchoice'+(mine?' on':''));b.type='button';b.setAttribute('aria-pressed',String(mine));
b.dataset.machine=machine.id;
const head=node('span',undefined,'mhead');head.append(node('b',machine.name));
if(mine){const tick=node('span',undefined,'tick');tick.append(svgIcon(IC.check,'i s'));head.append(tick);}
b.append(head,node('span',machine.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','sub'));
const here=board.orders.filter(o=>o.state==='imp'&&!o.cancelled_at&&o.machine?.id===machine.id)
.sort((x,y)=>(x.printing==='imprimindo'?0:1)-(y.printing==='imprimindo'?0:1));
for(let i=0;i<Math.max(board.printing_cap||2,here.length);i++){
const o=here[i],job=node('span',undefined,'job');
if(o)job.append(node('i',undefined,o.printing==='ripando'?'ripmark':'runmark'),node('span','#'+o.number,'code'),node('em',o.printing==='ripando'?'ripando':'imprimindo'));
else job.append(node('i',undefined,'freemark'),node('span','livre','free'));
b.append(job);
}
if(machine.operators){const others=machine.operators.filter(op=>op.name!==(ME.name||ME.email));
b.append(node('span',others.length?others.map(op=>op.name).join(', ')+(others.length>1?' estão nela':' está nela'):'Ninguém mais nela','who'));}
return b;
}
// "Em qual máquina você está?" (Dropstar's third round, item 12): after signing
// in, required for the operator, and for Gestão and the administrators with
// "Não estou em máquina". Per session: one person on two computers runs two
// machines. Someone else already on the machine is a warning, not a refusal.
let askingMachine=false;
function askMachine(again=false){
if(!ME?.machine_question||askingMachine||(ME.machine_answered&&!again))return;
askingMachine=true;
const required=ME.machine_question==='required', current=myMachine();
let m=null;
const choose=async(id,confirm=false)=>{
try{await api('/me/machine',{machine_id:id,confirm});m.close();await load(true);}
catch(e){
if(e.status===409&&!confirm&&await ask('Outra pessoa está nesta máquina',e.message,'Continuar mesmo assim'))return choose(id,true);
say(e.message,true);}};
// Each machine with what it is printing, and who is on it now.
const list=node('div',undefined,'mchoices');
for(const machine of (board.machines||[]).filter(x=>x.active)){
const b=machineChoice(machine,current?.id===machine.id);
b.onclick=()=>choose(machine.id);list.append(b);
}
if(!list.children.length)list.append(node('p','Nenhuma máquina ativa. Peça ao Administrador para cadastrar em Usuários, Máquinas.','empty'));
const foot=[];
if(!required)foot.push(button('Não estou em máquina',()=>choose(null),'btn ghost'));
if(required&&!ME.machine_answered)foot.push(button('Sair',()=>$('logout').click(),'btn ghost'));
if(current&&ME.machine_answered)foot.push(button('Continuar na '+current.name,async()=>m.close(),'btn pri right'));
m=modal('Em qual máquina você está?',{text:'O que você puxar para Imprimindo vai para ela, e o histórico grava a máquina com o seu nome.',
body:[list],foot,width:620,locked:required&&!ME.machine_answered,onclose:()=>{askingMachine=false;}});
}
// The machine beside the account button: green, and a click changes it.
function paintMyMachine(){
const asked=!!ME?.machine_question, mine=myMachine();
for(const id of ['my-machine','rail-machine','account-machine'])$(id).hidden=!asked;
if(!asked)return;
const name=mine?mine.name:'Sem máquina';
const chip=$('my-machine');chip.replaceChildren(node('i'),node('span','Máquina '),node('b',name));
chip.classList.toggle('on',!!mine);
chip.title=mine?'Você está na '+mine.name+'. Clique para trocar.':'Você não está em máquina. Clique para escolher.';
const rail=$('rail-machine');rail.querySelector('b').textContent=mine?mine.name:'Nenhuma';rail.classList.toggle('on',!!mine);rail.title=chip.title;
$('account-machine').querySelector('.lbl').textContent=mine?mine.name:'';
}
for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true);
$('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);};
// The machine is recorded when the card is pulled into Imprimindo.
function machineCard(order){
const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl'));
const current=order.machine;
const pulled=order.machine_pulled;
const detail=pulled?'Puxada por '+pulled.by+' em '+when(pulled.at):current?'Escolhida para este pedido':'Definida quando alguém puxar o card';
// The operator's orders go to the machine that pulls them (item 12).
if(!may('print')||ME?.role==='operador'||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail));
return box;
}
const select=node('select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Sem máquina');auto.value='';select.append(auto);
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
const o=node('option',m.name+', '+machineLoad(m));o.value=m.id;select.append(o);
}
select.value=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+'.':'O pedido aguarda uma máquina.');await load();}
catch(e){say(e.message,true);}};
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail),select);
return box;
}
// "120,00 m de 300,00 m" or "120,00 m em aberto".
function machineLoad(m){
return m.limit_metres?metres(m.open_metres)+' de '+metres(m.limit_metres):metres(m.open_metres)+' em aberto';
}
// Chips that switch on and off (what a machine prints): .values() is what is on.
function pills(options,selected){
const box=node('div',undefined,'fopts'),on=new Set(selected);
for(const [value,label] of options){
const b=node('button',label,'fopt'+(on.has(value)?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on.has(value)));
b.onclick=()=>{if(on.has(value))on.delete(value);else on.add(value);b.classList.toggle('on',on.has(value));b.setAttribute('aria-pressed',String(on.has(value)));};
box.append(b);
}
box.values=()=>options.map(([v])=>v).filter(v=>on.has(v));return box;
}
// A dialog field that is a group (chips, a list) rather than one input.
function group(label,...content){const g=node('div',undefined,'fld');g.append(node('span',label),...content);return g;}
// A list to choose from, drawn by us: each choice with a line on what it means.
function choice(options,value,{label,disabled=false}={}){
const wrap=node('div',undefined,'sel');let current=value;
const btn=node('button',undefined,'selbtn');btn.type='button';btn.disabled=disabled;
btn.setAttribute('aria-haspopup','listbox');btn.setAttribute('aria-expanded','false');if(label)btn.setAttribute('aria-label',label);
const text=node('span');btn.append(text,svgIcon(IC.down,'i m'));
const list=node('div',undefined,'pop sellist');list.setAttribute('role','listbox');list.hidden=true;
const hint=node('small');
const close=()=>{list.hidden=true;btn.classList.remove('open');btn.setAttribute('aria-expanded','false');};
const paint=()=>{const o=options.find(x=>x.value===current)||options[0];text.textContent=o.label;hint.textContent=o.hint||'';
for(const b of list.children){const on=b.dataset.value===current;b.setAttribute('aria-selected',String(on));b.querySelector('.ck').replaceChildren(...(on?[svgIcon(IC.check,'i m')]:[]));}};
for(const o of options){
const b=node('button',undefined,'selopt');b.type='button';b.setAttribute('role','option');b.dataset.value=o.value;
const words=node('span');words.append(node('b',o.label),...(o.hint?[node('small',o.hint)]:[]));
b.append(node('span',undefined,'ck'),words);
b.onclick=()=>{current=o.value;paint();close();btn.focus();};list.append(b);
}
btn.onclick=e=>{e.stopPropagation();if(!list.hidden)return close();list.hidden=false;btn.classList.add('open');btn.setAttribute('aria-expanded','true');
list.querySelector('[aria-selected=true]')?.focus();
setTimeout(()=>document.addEventListener('click',close,{once:true}));};
list.onkeydown=e=>{const items=[...list.children],i=items.indexOf(document.activeElement);
if(e.key==='ArrowDown'){e.preventDefault();items[Math.min(items.length-1,i+1)].focus();}
if(e.key==='ArrowUp'){e.preventDefault();items[Math.max(0,i-1)].focus();}};
wrap.append(btn,list);paint();
wrap.value=()=>current;wrap.hint=hint;wrap.close=close;wrap.isOpen=()=>!list.hidden;
return wrap;
}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
// What each profile is for, in a line (app/core/auth.py).
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa, libera para Finalizado e reimprime a etiqueta.',
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.',
expedicao:'Monta folhas no Kanban e imprime a etiqueta; só consulta o resto.'};
// Who is on the system: used it in the last 15 minutes, signed in before,
// never, or switched off.
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
const presence=u=>!u.active?'off':u.seen_at&&Date.now()-new Date(u.seen_at)<15*60e3?'on':u.last_login_at?'away':'never';
const initialsOf=text=>String(text||'').trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()||'·';
function avatar(u,className='ava'){
const a=node('span',initialsOf(u.name||u.email),className),p=node('i',undefined,'pres '+presence(u));
p.title=PRESENCE[presence(u)];a.append(p);return a;
}
// "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py).
const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'];
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'],
['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'],
['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'],
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY'],
['Imprimir a etiqueta 10×15','YYNNYNNY']];
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||'—';
$('users-count').textContent=String(users.length);
$('users-list').replaceChildren(...users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const who=node('td'),line=node('span',undefined,'who'),words=node('span');
words.append(node('b',u.name||u.email),node('span',u.email,'sub'));line.append(avatar(u),words);who.append(line);
const machine=node('td');
if(u.machines.length){const m=node('span',undefined,'mcell');m.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));machine.append(m);}
else machine.append(node('span','Sem máquina','muted'));
const open=node('td',undefined,'r');
if(editable){open.append(iconButton(IC.right,'Editar '+(u.name||u.email),()=>userForm(u),'btn sq ghost'));tr.classList.add('click');tr.onclick=()=>userForm(u);}
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':', desativado')),machine,
node('td',u.last_login_at?ago(u.last_login_at):'nunca entrou','muted'),open);
return tr;
}));
// On the phone, a list of people, each a row that opens them.
const list=$('users-phone');list.replaceChildren(...users.map(u=>{
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const row=node('button',undefined,'mli');row.type='button';row.disabled=!editable;if(editable)row.onclick=()=>userForm(u);
const words=node('span',undefined,'grow'),sub=node('span',undefined,'sub mcell');
sub.append(ROLE_NAMES[u.role]+(u.active?'':', desativado'));
if(u.machines.length){sub.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));}
words.append(node('b',u.name||u.email),sub);
row.append(avatar(u),words,svgIcon(IC.right,'i m'));return row;}));
const head=node('tr');head.append(node('th',''));for(const r of ROLE_COLUMNS)head.append(node('th',ROLE_NAMES[r]));
for(const th of head.children)th.scope='col';head.firstChild.append(node('span','Ação','vh'));
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const [label,cells] of ROLE_MATRIX){const tr=node('tr');tr.append(node('td',label));
[...cells].forEach(k=>{const td=node('td'),i=node('i',undefined,k==='Y'?'can':k==='V'?'can view':'can no');
td.title=k==='Y'?'Faz':k==='V'?'Só consulta':'Não';td.append(i,node('span',td.title,'vh'));tr.append(td);});tbody.append(tr);}
$('roles-matrix').replaceChildren(thead,tbody);
$('machines-count').textContent=String(machines.length);
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
:[emptyState(IC.printer,'Nenhuma máquina cadastrada','Cadastre as máquinas para os pedidos irem para elas.')]));
}
// A machine: its metres open against its limit, its orders by stage, and who is on it.
const STAGE_FILL={rec:'var(--tx3)',tra:'var(--ln3)',imp:'var(--ink)',cor:'var(--bad)',rev:'var(--tx2)'};
function machineTile(m){
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
const head=node('div',undefined,'row');
head.append(node('h3',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','lbl'));
if(!m.active)head.append(badge('Desativada',''));
head.append(button('Ficha',()=>openMachineSheet(m.id),'btn ghost right'),button('Editar',()=>machineForm(m),'btn ghost'));
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
const load=node('div',undefined,'row base');
load.append(node('b',metres(m.open_metres),over?'bad':''),node('span','em aberto, '+(m.limit_metres?'limite de '+metres(m.limit_metres)+(over?', acima do limite':''):'sem limite'),'lbl'));
const stages=Object.keys(STAGE_FILL).filter(s=>m.states[s]);
const total=stages.reduce((t,s)=>t+m.states[s],0);
tile.append(head,load);
if(total){
const stack=node('div',undefined,'stack'),list=node('ul');
for(const s of stages){const seg=node('i');seg.style.width=(100*m.states[s]/total)+'%';seg.style.background=STAGE_FILL[s];stack.append(seg);
const li=node('li'),dot=node('i');dot.style.background=STAGE_FILL[s];li.append(dot,board?.states?.[s]||s,node('b',String(m.states[s])));list.append(li);}
tile.append(stack,list);
}else tile.append(node('span','Nenhum pedido em aberto','lbl'));
const people=node('div',undefined,'row people');people.append(svgIcon(IC.user,'i s'),
m.operators?.length?m.operators.map(o=>o.name+(o.since?' desde '+new Date(o.since).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'')).join(', ')+(m.operators.length>1?' estão nela':' está nela'):'Ninguém nela agora');
tile.append(people);
return tile;
}
function userForm(u){
const editing=!!u;
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';name.placeholder='Nome e sobrenome';
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';email.placeholder='nome@dropstar.com.br';
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'];
const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador',
{label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email});
const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint);
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter a atual':'8 caracteres ou mais';
const active=node('input');active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const row=node('div',undefined,'frow');row.append(field('Nome',name),field('E-mail',email));
const left=[];
if(editing&&u.email!==ME.email){
const remove=node('button','Excluir usuário','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir '+(u.name||u.email)+'?','A pessoa não entra mais no sistema. Os pedidos continuam com o nome dela no histórico. Para só bloquear o acesso, desmarque Ativo.','Excluir usuário',{tone:'red'}))return;
try{await api('/users/'+u.id+'/delete',{});m.close();say('Usuário excluído.');await loadUsers();}catch(e){say(e.message,true);}};
left.push(remove);
}
const m=formDialog(editing?u.name||u.email:'Novo usuário',{width:560,left,lead:editing?avatar(u,'bigava'):null,
text:editing?PRESENCE[presence(u)].split(':')[0]+', último acesso '+(u.last_login_at?when(u.last_login_at):'nunca'):'A pessoa entra com o e-mail e esta senha, e troca a senha em Minha conta.',
fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),checkbox('Ativo: pode entrar no sistema',active)],
label:editing?'Salvar':'Criar usuário',onsave:async()=>{
const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,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||'';name.placeholder='Ex.: Têxtil 2';
const products=pills([['textil','Têxtil'],['uv','UV']],m?.products||[]);
const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal';
limit.placeholder='Sem limite';limit.value=m?.limit_metres??'';
const active=node('input');active.checked=m?m.active:true;
const left=[];
if(m){
const remove=node('button','Excluir máquina','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir a máquina '+m.name+'?','Os pedidos dela vão para outra máquina do produto.','Excluir máquina',{tone:'red'}))return;
try{await api('/machines/'+m.id+'/delete',{});d.close();say('Máquina excluída.');await loadUsers();await load();}catch(e){say(e.message,true);}};
left.push(remove);
}
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
fields:[field('Nome',name),group('Imprime',products),
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
checkbox('Ativa: recebe pedidos',active)],
onsave:async()=>{
if(!products.values().length)throw new Error('Marque o que a máquina imprime.');
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(),
limit_metres:limit.value?Number(limit.value):null});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
}});
}
// ---- Machine sheet (Fase 2, front 1a) --------------------------------------
//
// What goes into a machine, what the room has printed since the last clean and
// the last film roll, and the alerts that wait between one file and the next.
// The numbers per machine (cost, ROI) are part b and stay in Números.
function machineEntryLine(entry, catalog){
const label=entry.label||entry.item;
let detail='';
if(entry.kind==='supply'){
const unit=catalog.supplies[entry.item]?.[1]||'';
detail=Number(entry.quantity).toLocaleString('pt-BR',{maximumFractionDigits:3})+' '+unit;
if(entry.cost_cents!==null&&entry.cost_cents!==undefined)detail+=' · '+money(entry.cost_cents);
}else if(entry.kind==='part'){
detail=(entry.note?entry.note+' · ':'')+(entry.serial?'série '+entry.serial+' · ':'')+money(entry.cost_cents);
}else if(entry.item==='stop'){
detail=entry.stop_minutes+' min'+(entry.note?' · '+entry.note:'');
}
return [when(entry.created_at),label,detail,entry.created_by].filter(Boolean).join(' · ');
}
async function openMachineSheet(machineId){
let data;
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return;}
const machine=data.machine;
const launch=may('print')&&(ME?.role!=='operador'||myMachine()?.id===machine.id);
const body=[];
let sheetModal=null;
const refresh=async()=>{sheetModal?.close();await load();openMachineSheet(machine.id);};
const minimum=value=>Number(value).toLocaleString('pt-BR',{maximumFractionDigits:3});
const counts=node('div',undefined,'mblock');
const fact=(label,value)=>{const row=node('div',undefined,'mfact');row.append(node('span',label),node('b',value));counts.append(row);};
const clean=data.counters.clean, film=data.counters.film;
fact('Desde a última limpeza',m1(clean.metres)+' m'+(clean.since?'':' (nenhuma limpeza lançada ainda)'));
fact('Desde a troca de filme',film.since?m1(film.metres)+' m '+(film.aligned?'(cabeça alinhada)':'(falta alinhar)'):'sem registro');
body.push(node('h4','Contadores','sh'),counts);
const supplies=node('div',undefined,'mblock');
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const value=data.supplies[item];
const row=node('div',undefined,'mfact');
let text;
if(value){
text='acaba em ~'+m1(value.metres_left)+' m';
if(value.minimum!==null&&value.minimum!==undefined)text+=' · mínimo '+minimum(value.minimum)+' '+unit;
}else text='lance duas reposições para estimar';
row.append(node('span',label),node('b',text));
supplies.append(row);
}
body.push(node('h4','Insumos','sh'),supplies);
if(data.alerts.length){
const box=node('div',undefined,'mblock');
const done=async alert=>{
if(alert.key.startsWith('supply:')){
const saved=await machineEntryForm(machine.id,{kind:'supply',item:alert.key.slice(7),from_alert:true},data);
if(!saved)return;
}else{
await api('/machines/'+machine.id+'/entries',{kind:'event',item:alert.key,from_alert:true});
}
say('Aviso resolvido.');
await refresh();
};
for(const alert of data.alerts){
const row=node('div',undefined,'sheetalert');
const words=node('span',undefined,'grow');
words.append(node('b',alert.text),node('span',alert.blocking?'pendente':'adiado neste ciclo','sub'));
row.append(words);
if(launch){
const actions=node('span',undefined,'prow');
actions.append(button('Marcar como feito',()=>done(alert),'btn'));
if(alert.snoozable)actions.append(button('Adiar uma vez',async()=>{
await api('/machines/'+machine.id+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
say('Aviso adiado: passa um arquivo e ele volta.');
await refresh();
},'btn ghost'));
row.append(actions);
}
box.append(row);
}
body.push(node('h4','Avisos pendentes','sh'),box);
}
const entries=node('div',undefined,'mlist sheetentries');
if(data.entries.length)for(const entry of data.entries)entries.append(node('div',machineEntryLine(entry,data.catalog),'mli'));
else entries.append(node('div','Nenhum lançamento ainda','mli muted'));
body.push(node('h4','Lançamentos','sh'),entries);
if(launch){
const prow=node('div',undefined,'prow');
prow.append(button('Lançar',async()=>{
const saved=await machineEntryForm(machine.id,{},data);
if(!saved)return;
say('Lançamento registrado.');
await refresh();
},'btn pri'));
body.push(prow);
}
if(may('manage')){
const price=node('input');price.type='number';price.min='0';price.step='0.01';price.inputMode='decimal';
price.value=data.machine.price_cents!==null&&data.machine.price_cents!==undefined?(data.machine.price_cents/100).toFixed(2):'';
const installed=node('input');installed.type='date';installed.value=data.machine.installed_on||'';
const minimums={};
const box=node('div',undefined,'mblock');
box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed));
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal';
// Dropstar's fixed minimums are the defaults: a machine with none typed
// shows and uses them until Gestão changes them.
const typed=data.minimums[item], fallback=data.default_minimums?.[item];
input.value=typed!==null&&typed!==undefined?Number(typed).toString()
:fallback!==null&&fallback!==undefined?Number(fallback).toString():'';
minimums[item]=input;
box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input));
}
const error=node('span',undefined,'warn');error.hidden=true;
const save=node('button','Salvar','btn pri');save.type='button';
save.onclick=async()=>{
save.disabled=true;error.hidden=true;
try{
await api('/machines/'+machine.id+'/sheet',{
price_cents:price.value.trim()===''?null:Math.round(Number(price.value)*100),
installed_on:installed.value||null,
minimums:Object.fromEntries(Object.entries(minimums).map(([item,input])=>
[item,input.value.trim()===''?null:Number(input.value)]))});
say('Dados da máquina salvos.');
await refresh();
}catch(e){error.textContent=e.message;error.hidden=false;}
finally{save.disabled=false;}
};
const foot=node('div',undefined,'prow');foot.append(error,save);
box.append(foot,node('small','Preço e data servem para o retorno da máquina em Números.','sub'));
body.push(node('h4','Dados da máquina','sh'),box);
}
sheetModal=modal('Ficha da '+machine.name,{host:dialogHost(),width:640,body});
}
// The launch form: type, item, and only the fields that type uses. Resolves
// true when the entry was saved, false when the dialog was closed.
async function machineEntryForm(machineId, preset={}, data=null){
if(!data){
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return false;}
}
const catalog=data.catalog;
const kind=node('select');
for(const [value,label] of [['supply','Insumo'],['part','Peça'],['event','Evento']]){
const option=node('option',label);option.value=value;kind.append(option);}
kind.value=preset.kind||'supply';
const item=node('select');
const fillItems=()=>{
const map=kind.value==='supply'?catalog.supplies:kind.value==='part'?catalog.parts:catalog.events;
item.replaceChildren(...Object.entries(map).map(([value,meta])=>{
const option=node('option',Array.isArray(meta)?meta[0]:meta);option.value=value;return option;}));
if(preset.item&&kind.value===(preset.kind||'supply'))item.value=preset.item;
};
fillItems();
const quantity=node('input');quantity.type='number';quantity.min='0.001';quantity.step='0.001';quantity.inputMode='decimal';
const cost=node('input');cost.type='number';cost.min='0';cost.step='0.01';cost.inputMode='decimal';
const serial=node('input');serial.maxLength=200;
const note=node('input');note.maxLength=1000;
const minutes=node('input');minutes.type='number';minutes.min='1';minutes.step='1';
const quantityField=field('Quantidade',quantity,'Unidade: ');
const costField=field('Custo (R$)',cost,'Vazio usa o último custo');
const serialField=field('Número de série',serial);
const noteCaption=node('span','Descrição');
const noteField=node('label',undefined,'fld');noteField.append(noteCaption,note);
const minutesField=field('Minutos parados',minutes);
const quantityHint=quantityField.querySelector('small'),costHint=costField.querySelector('small');
const sync=()=>{
const supply=kind.value==='supply',part=kind.value==='part',event=kind.value==='event';
const stop=event&&item.value==='stop';
quantityField.hidden=!supply;
costField.hidden=!(supply||part);
serialField.hidden=!part;
noteField.hidden=!((part&&item.value==='other')||stop);
minutesField.hidden=!stop;
noteCaption.textContent=stop?'Motivo da parada':'Descrição';
quantityHint.textContent=supply?'Unidade: '+(catalog.supplies[item.value]?.[1]||''):'';
costHint.textContent=supply?'Vazio usa o último custo':'';
};
kind.onchange=()=>{preset.item=null;fillItems();sync();};
item.onchange=sync;
sync();
return new Promise(resolve=>{
let settled=false;
const finish=value=>{if(settled)return;settled=true;resolve(value);};
const error=node('span',undefined,'warn');error.hidden=true;
const dialog=formDialog('Lançar na ficha',{host:dialogHost(),width:560,left:[error],
fields:[field('Tipo',kind),field('Item',item),quantityField,costField,serialField,noteField,minutesField],
label:'Lançar',onsave:async()=>{
try{
const payload={kind:kind.value,item:item.value,from_alert:!!preset.from_alert};
if(kind.value==='supply'){
if(quantity.value.trim()==='')throw new Error('Informe a quantidade que entrou.');
payload.quantity=Number(quantity.value);
payload.cost_cents=cost.value.trim()===''?null:Math.round(Number(cost.value)*100);
}else if(kind.value==='part'){
if(cost.value.trim()==='')throw new Error('Informe o custo da peça.');
payload.cost_cents=Math.round(Number(cost.value)*100);
payload.serial=serial.value.trim()||null;
payload.note=note.value.trim()||null;
}else if(item.value==='stop'){
if(!note.value.trim()||minutes.value.trim()==='')throw new Error('Informe o motivo e os minutos da parada.');
payload.note=note.value.trim();
payload.stop_minutes=Number(minutes.value);
}
await api('/machines/'+machineId+'/entries',payload);
}catch(e){error.textContent=e.message;error.hidden=false;return false;}
finish(true);
}});
const close=dialog.close.bind(dialog);
dialog.close=()=>{close();finish(false);};
});
}
// The alert shown when a card is pulled between one file and the next. Resolves
// true when the alert was resolved or postponed, false when the user backs out.
// Only the machine's own operator (or management) may resolve it, as in the
// machine sheet: the API refuses anyone else (DTF-WEB-5/6).
function machineAlertDialog(order,machineId,alert){
return new Promise(resolve=>{
let decided=false;
const machine=(board.machines||[]).find(row=>row.id===machineId);
const allowed=ME?.role!=='operador'||myMachine()?.id===machineId;
const made=node('button','Marcar como feito','btn pri');made.type='button';
const later=node('button','Adiar uma vez','btn');later.type='button';
const back=node('button','Voltar','btn ghost right');back.type='button';
const modalEntry=modal('Antes do próximo arquivo',{text:alert.text,host:dialogHost(),width:520,
body:allowed?[]:[node('p','Só quem está na '+(machine?.name||'máquina')+' resolve este aviso.','nnote')],
role:'alertdialog',foot:allowed?[...(alert.snoozable?[later]:[]),back,made]:[back],
onclose:()=>{if(!decided)resolve(false);}});
back.onclick=()=>modalEntry.close();
const run=async action=>{
made.disabled=true;later.disabled=true;message.hidden=true;
try{
const proceed=await action();
if(proceed===false)return;
decided=true;modalEntry.close();
await load();
resolve(true);
}catch(e){message.textContent=e.message;message.hidden=false;}
finally{made.disabled=false;later.disabled=false;}
};
const message=node('span',undefined,'warn');message.hidden=true;
modalEntry.box.querySelector('.dfoot')?.prepend(message);
made.onclick=()=>run(async()=>{
if(alert.key.startsWith('supply:')){
return await machineEntryForm(machineId,{kind:'supply',item:alert.key.slice(7),from_alert:true});
}
await api('/machines/'+machineId+'/entries',{kind:'event',item:alert.key,from_alert:true});
return true;
});
later.onclick=()=>run(async()=>{
await api('/machines/'+machineId+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
return true;
});
});
}
// Pulling a card as management, with no session machine: which machine takes
// it. The cards look like askMachine's, but the choice only applies to this
// pull; the session machine does not change.
function choosePullMachine(order){
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
const machines=(board.machines||[]).filter(m=>m.active&&m.products.includes(family));
if(!machines.length){
say('Nenhuma máquina ativa faz '+PRODUCT_LABEL[family]+'.',true);
return Promise.resolve(null);
}
return new Promise(resolve=>{
let m=null, chosen=false;
const list=node('div',undefined,'mchoices');
for(const machine of machines){
const b=machineChoice(machine);
b.onclick=()=>{chosen=true;m.close();resolve(machine.id);};
list.append(b);
}
const back=node('button','Voltar','btn ghost right');back.type='button';
back.onclick=()=>m.close();
m=modal('Qual máquina puxa este card?',{host:dialogHost(),width:620,body:[list],foot:[back],
onclose:()=>{if(!chosen)resolve(null);}});
});
}
// Pulling a card to a machine always passes the sheet's blocking alert first,
// then the server re-checks it under the machine's lock. An operator's pulls
// always go to the machine of their session (DTF-WEB-4).
async function pullTo(order, machineId){
let target;
if(ME?.role==='operador'){
const mine=myMachine();
if(!mine){askMachine(true);return;}
if(machineId&&machineId!==mine.id){
say('Você está na '+mine.name+': o que você puxa vai para ela.',true);return;
}
target=mine.id;
}else{
target=machineId||order.machine?.id||myMachine()?.id||null;
if(!target){
target=await choosePullMachine(order);
if(!target)return;
}
}
const machine=(board.machines||[]).find(row=>row.id===target);
const alert=(machine?.alerts||[]).find(row=>row.blocking);
if(alert&&!await machineAlertDialog(order,target,alert))return;
try{
await move(order,'imp','',target);
}catch(e){
if(e.status===409&&String(e.message).startsWith('Antes do próximo arquivo')){say(e.message,true);return;}
throw e;
}
}
// Minha conta: who is signed in, and the password, which only the person changes.
function accountForm(){
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=8;next.autocomplete='new-password';
const again=node('input');again.type='password';again.required=true;again.minLength=8;again.autocomplete='new-password';
const dl=node('dl',undefined,'dl');
for(const [k,v] of [['E-mail',ME.email],['Perfil',ROLE_NAMES[ME.role]||ME.role],...(ME.machine_question?[['Máquina agora',myMachine()?.name||'Nenhuma']]:[])]){
const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);}
const sect=node('div',undefined,'sect');
const row=node('div',undefined,'frow');row.append(field('Nova senha',next,'8 caracteres ou mais'),field('Repita a nova senha',again));
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'),
text:ROLE_NAMES[ME.role]+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect],
note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave: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;accountForm();};
// Dark or light, per browser (web/theme.js): the rail's button and the account
// menu name the one a click gives.
const ICON_SUN='M6.75 10a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M10 2v1.75 M10 16.25V18 M2 10h1.75 M16.25 10H18 M4.35 4.35l1.24 1.24 M14.41 14.41l1.24 1.24 M4.35 15.65l1.24-1.24 M14.41 5.59l1.24-1.24';
const ICON_MOON='M16.25 12.25A6.75 6.75 0 0 1 7.75 3.75a6.75 6.75 0 1 0 8.5 8.5z';
function paintThemeToggle(){
const light=kanbanTheme.get()==='light', label=light?'Mudar para o modo escuro':'Mudar para o modo claro';
$('theme-rail').querySelector('path').setAttribute('d',light?ICON_MOON:ICON_SUN);
$('theme-rail').setAttribute('aria-label',label);$('theme-rail').title=label;
}
$('theme-rail').onclick=()=>{kanbanTheme.toggle();paintThemeToggle();};
paintThemeToggle();
$('account').onclick=e=>{e.stopPropagation();const m=$('account-menu');m.hidden=!m.hidden;
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;},{once:true});};
$('filter-btn').onclick=e=>{e.stopPropagation();if($('filter-pop').hidden)openFilters();else closeFilters();};
$('filter-pop').onclick=e=>e.stopPropagation();
$('filter-pop').onkeydown=e=>{if(e.key==='Escape'){e.stopPropagation();closeFilters();$('filter-btn').focus();}};
document.addEventListener('click',()=>{if(!$('filter-pop').hidden)closeFilters();});
$('new-user').onclick=()=>userForm(null);
$('new-machine').onclick=()=>machineForm(null);