/* 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;iop.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)=>{ // Someone else on the machine is a question, not an error (Sentry DTF-WEB-1J). try{await api('/me/machine',{machine_id:id,confirm},{expected:confirm?[]:[409]});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); // No network (an iPhone between Wi-Fi and data, Sentry DTF-WEB-1Q): a // warning to try again, not an error; load() reports one that lasts. if(e.offline){say('Sem conexão com o servidor. Confira a internet e escolha a máquina de novo.');return;} 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 that printed the order's approved proof: the order prints // there too, and the server refuses any other (Sentry DTF-WEB-19, 1F). function proofMachine(order){ const card=order.proof_card; return card?.proof_result==='ok'&&card.machine_id?(board.machines||[]).find(m=>m.id===card.machine_id)||{id:card.machine_id,name:'máquina da prova'}:null; } // 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')||printOnlyAsOperator()||!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 proofAt=proofMachine(order); if(proofAt){ box.append(node('b',proofAt.name),node('span','A máquina que imprimiu a prova #'+order.proof_card.number)); 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',rolesLabel(u.roles||[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(rolesLabel(u.roles||[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, in one compact line: name, products, its open metres and orders, // who is on it, and the alert mark. The stage breakdown and the limit stay in // the row's tooltip, so the numbers of the old tile are not lost. const STAGE_FILL={rec:'var(--tx3)',tra:'var(--ln3)',imp:'var(--ink)',cor:'var(--bad)',rev:'var(--tx2)'}; function machineTile(m){ const row=node('div',undefined,'mt'+(m.active?'':' off')); const body=node('div',undefined,'mtbody'); const top=node('div',undefined,'mtname'); top.append(node('b',m.name)); for(const p of m.products||[])top.append(node('span',PRODUCT_LABEL[p],'tag')); if(!m.active)top.append(node('span','Desativada','tag')); if((m.alerts||[]).length){const dot=node('span',undefined,'mtwarn');dot.title='Aviso na ficha';top.append(dot);} const stages=Object.keys(STAGE_FILL).filter(state=>m.states?.[state]); const stageText=stages.map(state=>(board?.states?.[state]||state)+': '+m.states[state]).join(' · '); const limit=m.limit_metres?'limite de '+metres(m.limit_metres):''; if(limit||stageText)row.title=[limit,stageText].filter(Boolean).join(' · '); const mine=myMachine()?.id===m.id; const others=(m.operators||[]).filter(op=>op.name!==(ME.name||ME.email)); const who=mine?'Ficha está nela agora':others.length?others.map(op=>op.name).join(', ')+(others.length>1?' estão nela':' está nela'):'ninguém nela agora'; const open=Number(m.open_orders||0)>0||Number(m.open_metres||0)>0; if(open){ const status=node('div',undefined,'mtstatus'); const amount=node('b',metres(m.open_metres)); if(m.limit_metres&&m.open_metres>m.limit_metres)amount.classList.add('bad'); status.append(amount,' em aberto · ',plural(m.open_orders,'pedido','pedidos'),' · ',who); body.append(top,status); }else{ top.append(node('span','Livre · '+who,'mtfree')); body.append(top); } row.append(body,button('Ficha',()=>openMachineSheet(m.id),'btn sm'),button('Editar',()=>machineForm(m),'btn ghost sm')); return row; } 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); // More than one profile (Marcus, 2026-11-26): the person may do what any of them may. const others=pills(roles.filter(r=>r!=='superadmin').map(r=>[r,ROLE_NAMES[r]]),(u?.roles||[]).filter(r=>r!==u?.role)); if(u?.role==='superadmin'||u?.email===ME.email)others.querySelectorAll('button').forEach(b=>b.disabled=true); const othersField=group('Outros perfis',others,node('small','Some as permissões de mais perfis, por exemplo Operador e Revisor.')); 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)); // The Tiny seller this person is: a Venda they assemble in Montar reaches // Tiny with it (Marcus, 2026-11-17). The list comes from Tiny itself. const seller=node('select'); const none=node('option','Nenhum: o pedido vai sem vendedor');none.value='';seller.append(none); if(u?.tiny_seller){const o=node('option',u.tiny_seller.name);o.value=String(u.tiny_seller.id);seller.append(o);seller.value=o.value;} const sellerNote=node('small','Num pedido de Venda montado por esta pessoa no Montar, o Tiny recebe este vendedor.'); api('/tiny/sellers').then(list=>{ const keep=seller.value; seller.replaceChildren(none,...list.map(x=>{const o=node('option',x.name);o.value=String(x.id);return o;})); if(keep&&!list.some(x=>String(x.id)===keep)&&u?.tiny_seller){const o=node('option',u.tiny_seller.name+' (não está mais no Tiny)');o.value=keep;seller.append(o);} seller.value=keep; }).catch(e=>{sellerNote.textContent='Não foi possível ler os vendedores do Tiny: '+e.message;}); 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,othersField,field(editing?'Nova senha':'Senha inicial',pass),field('Vendedor no Tiny',seller,sellerNote),checkbox('Ativo: pode entrar no sistema',active)], label:editing?'Salvar':'Criar usuário',onsave:async()=>{ const picked=seller.value?{id:Number(seller.value),name:seller.selectedOptions[0].textContent.replace(/ \(não está mais no Tiny\)$/,'')}:null; const main=role.value()==='superadmin'?'admin':role.value(); const body={name:name.value,email:email.value,role:main,roles:others.values().filter(r=>r!==main),active:active.checked,password:pass.value||null,tiny_seller:picked}; // An e-mail already in use is said in the form, not an error (Sentry DTF-WEB-1D). await api(editing?'/users/'+u.id:'/users',body,{expected:[409]}); say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers(); }}); } // A machine's places in Imprimindo, which are also the files at once in its // hot folder (app/machines.py): Admin and Gestão set them (Marcus, 2026-11-17). const PLACES_NOTE='Quantos pedidos a máquina aceita em Imprimindo, e quantos arquivos ficam juntos na hot folder dela.'; function placesSelect(value){ const select=node('select'); for(let n=1;n<=6;n++){const o=node('option',String(n));o.value=String(n);select.append(o);} select.value=String(value||3);return select; } 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 places=placesSelect(m?.places); 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.'), field('Vagas em Imprimindo',places,PLACES_NOTE), 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,places:Number(places.value)}); 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, tab='situacao'){ let data; try{data=await api('/machines/'+machineId+'/sheet');} catch(e){say(e.message,true);return;} const machine=data.machine; const machineState=(board.machines||[]).find(row=>row.id===machine.id)||null; const launch=may('print')&&(!printOnlyAsOperator()||myMachine()?.id===machine.id); const manage=may('manage'); let sheetModal=null; let activeTab=tab; const refresh=async(next=activeTab)=>{sheetModal?.close();await load();openMachineSheet(machine.id,next);}; const minimum=value=>Number(value).toLocaleString('pt-BR',{maximumFractionDigits:3}); const situacao=node('div',undefined,'msheet-pane');situacao.setAttribute('role','tabpanel'); const lancamentos=node('div',undefined,'msheet-pane');lancamentos.setAttribute('role','tabpanel'); const dados=node('div',undefined,'msheet-pane');dados.setAttribute('role','tabpanel'); // Situação: the alerts, the counters and the supplies. if(data.alerts.length){ const box=node('div',undefined,'msheet-alerts'); 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(activeTab); }; for(const alert of data.alerts){ const row=node('div',undefined,'msheet-alert'); const ico=node('span',undefined,'msheet-alertico');ico.append(svgIcon(IC.alert,'i m')); const words=node('div',undefined,'msheet-alertwords'); words.append(node('b',alert.text),node('span',alert.blocking?'pendente':'adiado neste ciclo','sub')); row.append(ico,words); if(launch){ const actions=node('span',undefined,'prow'); 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(activeTab); },'btn ghost')); actions.append(button('Marcar como feito',()=>done(alert),'btn')); row.append(actions); } box.append(row); } situacao.append(box); } const clean=data.counters.clean, film=data.counters.film; const counters=node('div',undefined,'msheet-counters'); const counter=(label,value,note)=>{ const card=node('div',undefined,'msheet-ctr'); card.append(node('span',label),node('b',value),node('small',note));counters.append(card); }; counter('Desde a última limpeza',m1(clean.metres)+' m', clean.since?'Limpeza lançada em '+when(clean.since):'Nenhuma limpeza lançada ainda'); counter('Desde a troca de filme',film.since?m1(film.metres)+' m':'—', film.since?'Troca lançada em '+when(film.since)+(film.aligned?', cabeça alinhada':', falta alinhar'):'Sem registro'); situacao.append(counters); situacao.append(node('h4','Insumos','msheet-h')); const supplies=node('div',undefined,'msheet-supplies'); for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){ const value=data.supplies[item]; const typed=data.minimums[item], fallback=data.default_minimums?.[item]; const floor=typed!==null&&typed!==undefined?typed:fallback; const row=node('div',undefined,'msheet-supply'); row.append(node('b',label), node('span',value?'acaba em ~'+m1(value.metres_left)+' m':'lance duas reposições para estimar'), node('em',floor!==null&&floor!==undefined?'mín. '+minimum(floor)+' '+unit:'')); supplies.append(row); } situacao.append(supplies); // Lançamentos: the log. The footer's Lançar opens the form. const entries=node('div',undefined,'mlist'); 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')); lancamentos.append(entries); // Dados da máquina: price, installation and the minimums (management). if(manage){ const price=node('input');price.type='number';price.min='0';price.step='0.01';price.inputMode='decimal'; price.value=machine.price_cents!==null&&machine.price_cents!==undefined?(machine.price_cents/100).toFixed(2):''; const installed=node('input');installed.type='date';installed.value=machine.installed_on||''; const places=placesSelect(machineState?.places); const minimums={}; const box=node('div',undefined,'mblock'); box.append(field('Vagas em Imprimindo',places,PLACES_NOTE),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'; 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{ if(machineState&&Number(places.value)!==machineState.places) await api('/machines/'+machine.id+'/places',{places:Number(places.value)}); 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('dados'); }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')); dados.append(box); } // The tabs keep the fixed head while the active section scrolls. const tabs=node('div',undefined,'msheet-tabs');tabs.setAttribute('role','tablist'); const panes=node('div',undefined,'msheet-panes'); const labels=[['situacao','Situação',situacao],['lancamentos','Lançamentos',lancamentos],...(manage?[['dados','Dados da máquina',dados]]:[])]; if(!labels.some(([key])=>key===activeTab))activeTab='situacao'; const paintTabs=()=>{ for(const button of tabs.children){const on=button.dataset.tab===activeTab;button.classList.toggle('on',on);button.setAttribute('aria-selected',String(on));} for(const pane of panes.children)pane.hidden=pane.dataset.tab!==activeTab; }; for(const [key,label,pane] of labels){ const b=node('button',label,'msheet-tab');b.type='button';b.dataset.tab=key;b.setAttribute('role','tab'); b.onclick=()=>{activeTab=key;paintTabs();}; tabs.append(b);pane.dataset.tab=key;panes.append(pane); } paintTabs(); const wrap=node('div',undefined,'msheet');wrap.append(tabs,panes); const note=node('span','Lançar registra limpeza, filme, alinhamento ou reposição.','msheet-note'); const foot=[note,button('Fechar',()=>sheetModal?.close(),'btn ghost')]; if(launch)foot.push(button('Lançar',async()=>{ const saved=await machineEntryForm(machine.id,{},data); if(!saved)return; say('Lançamento registrado.'); await refresh('lancamentos'); },'btn pri')); const mine=myMachine()?.id===machine.id; const others=(machineState?.operators||[]).filter(op=>op.name!==(ME.name||ME.email)); const who=mine?'Ficha está nela agora':others.length?others.map(op=>op.name).join(', ')+(others.length>1?' estão nela':' está nela'):'Livre'; const products=(machineState?.products||[]).map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto'; const state=[products,machineState?.active===false?'Desativada':null,who, machineState?.open_orders?plural(machineState.open_orders,'pedido','pedidos')+' em aberto':''].filter(Boolean).join(' · '); sheetModal=modal('Ficha da '+machine.name,{text:state,host:dialogHost(),width:720,body:[wrap],foot}); sheetModal.box.classList.add('machine-sheet-dlg'); } // 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=!printOnlyAsOperator()||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(machineBound('tra','imp')){ const mine=myMachine(); if(!mine){askMachine(true);return;} // Guidance, not an error: the pull goes to the session's machine (Sentry DTF-WEB-1A). if(machineId&&machineId!==mine.id){ say('Você está na '+mine.name+': o que você puxa vai para ela.');return; } target=mine.id; }else{ target=machineId||proofMachine(order)?.id||order.machine?.id||myMachine()?.id||null; if(!target){ target=await choosePullMachine(order); if(!target)return; } } const proofAt=proofMachine(order); if(proofAt&&target!==proofAt.id){ say('O #'+order.number+' imprime na '+proofAt.name+', a máquina que imprimiu a prova #'+order.proof_card.number+'.');return; } const machine=(board.machines||[]).find(row=>row.id===target); // A lane drop, or a machine chosen before, may be one that does not print // this product (by its first item, as app/machines.py product_family): said // here, as the chooser filters, and the card stays put (Sentry DTF-WEB-12). if(machine&&!(machine.products||[]).includes(/^uv/.test(order.snapshot.items[0]?.mode||'')?'uv':'textil')){ say('A '+machine.name+' não imprime este produto.');return; } const alert=(machine?.alerts||[]).find(row=>row.blocking); if(alert&&!await machineAlertDialog(order,target,alert))return; try{ await pullMove(order,target); }catch(e){ if(e.status===409&&String(e.message).startsWith('Antes do próximo arquivo')){say(e.message,true);return;} throw e; } } // The card changed elsewhere between the board's load and the pull (another // tab or person; the machine alert in between gives it time): reload and, if // it still waits in Arte conferida, pull once more with the fresh version; // the server checks everything again (Sentry DTF-WEB-K, as DTF-WEB-7). async function pullMove(order,target){ try{ await move(order,'imp','',target); }catch(error){ if(error.status!==409||!String(error.message).startsWith('O pedido mudou'))throw error; await load(); const fresh=(board.orders||[]).find(row=>row.id===order.id); if(fresh?.state==='imp'&&fresh.machine?.id===target){say('O pedido já estava imprimindo nesta máquina.');return;} if(!fresh||fresh.cancelled_at||fresh.state!=='tra')throw error; await move(fresh,'imp','',target); } } // 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',rolesLabel(myRoles())],...(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:rolesLabel(myRoles())+(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='M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm72,88a64,64,0,1,1-64-64A64.07,64.07,0,0,1,192,128Zm-16,0a48,48,0,1,0-48,48A48.05,48.05,0,0,0,176,128ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z'; const ICON_MOON='M233.54,142.23a8,8,0,0,0-8-2,88.08,88.08,0,0,1-109.8-109.8,8,8,0,0,0-10-10,104.84,104.84,0,0,0-52.91,37A104,104,0,0,0,136,224a103.09,103.09,0,0,0,62.52-20.88,104.84,104.84,0,0,0,37-52.91A8,8,0,0,0,233.54,142.23ZM188.9,190.34A88,88,0,0,1,65.66,67.11a89,89,0,0,1,31.4-26A106,106,0,0,0,96,56,104.11,104.11,0,0,0,200,160a106,106,0,0,0,14.92-1.06A89,89,0,0,1,188.9,190.34Z'; 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);