feat: the machine is chosen at sign-in, per session (Dropstar's third round, item 12)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped

After signing in, the Kanban asks "Em qual máquina você está?": required
for the operator, optional for Gestão and Administrador ("Não estou em
máquina"), never for the other profiles. The session keeps it until it
ends or is changed from the header, where the machine shows in green;
one person on two computers runs two machines. Someone else already on
the machine is a warning, not a refusal.

Operators see the whole board (no more per-machine filter). From Arte
conferida they pull any card, which becomes their machine's (a machine
that does not print its product refuses it); they move only their
machine's cards, and the others show without drag or buttons. Their
cards and their machine's row in Imprimindo are outlined in green. The
history records the machine with the person: "Imprimindo · Thales ·
máquina2". Usuários shows who is on each machine now, read-only; the old
operator/machine assignment is no longer read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-30 13:18:24 -03:00
parent 8c053596b7
commit db877c52e6
9 changed files with 288 additions and 113 deletions

View File

@@ -48,6 +48,12 @@ const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão'
// server's own list (app/core/auth.py MOVES), never worked out here.
const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to);
const mayReorder=state=>!!ME?.reorder?.includes(state);
// The session's machine (item 12). An operator pulls any card from the queue,
// which becomes their machine's, and moves only their machine's cards; the
// others show, without drag or buttons.
const myMachine=()=>ME?.machine||null;
const isMine=order=>!!myMachine()&&order.machine?.id===myMachine().id;
const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order);
// Which tabs each capability opens.
// Vendedor and Financeiro consult Cotações and Números without acting there.
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
@@ -550,7 +556,7 @@ let seenOrders=null, seenPending=null, unseen=0;
async function load(quiet=false){
try{
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
board=absorb(loaded);ME=me;applyRole();
board=absorb(loaded);ME=me;applyRole();paintMyMachine();
noticeNew(quiet);
const known=new Set(board.orders.map(o=>o.id));
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
@@ -558,6 +564,7 @@ async function load(quiet=false){
$('login').hidden=true;$('app').hidden=false;
if(!quiet)say('Atualizado às '+new Date().toLocaleTimeString('pt-BR')+tinyNotice,false,tinyNotice?6000:2500);
render();
askMachine();
syncFolder();
}catch(e){
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
@@ -631,8 +638,8 @@ const PRINTING={imprimindo:['Imprimindo','ok','Já ripou, está rodando'],
// machines with nothing printing share one line. An operator who works on
// some machines sees those.
function printingRoom(){
const cap=board.printing_cap, mine=ME?.role==='operador'&&ME.machines?.length?ME.machines:null;
const list=(board.machines||[]).filter(m=>(m.active||m.states.imp)&&(!mine||mine.includes(m.id)));
const cap=board.printing_cap;
const list=(board.machines||[]).filter(m=>m.active||m.states.imp);
if(!list.length)return null;
const room=node('div',undefined,'slots'), free=[];
for(const m of list){
@@ -640,7 +647,7 @@ function printingRoom(){
.sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1));
const n=Math.max(m.states.imp||0,here.length);
if(!n){free.push(m.name);continue;}
const row=node('div',undefined,'slot-row');
const row=node('div',undefined,'slot-row'+(myMachine()?.id===m.id?' mine':''));
row.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':' · '+(cap-n)+' vaga');
// The places go under the name when the column is too narrow for both.
const places=node('div',undefined,'slot-places');
@@ -802,8 +809,9 @@ function renderBoard(){
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&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
c.draggable=!order.cancelled_at&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
if(order.id===openOrder)c.classList.add('open');
if(isMine(order)&&order.state!=='fin'&&!order.cancelled_at)c.classList.add('mine');
const s=order.snapshot;
const top=node('div',undefined,'row');
top.append(node('span','#'+order.number,'num'),originTag(order),...(isTest(order)?[node('span','TESTE','tag-teste')]:[]),node('span',ago(order.updated_at),'age'));
@@ -1038,14 +1046,15 @@ function moves(order){
if(may('print')){const actions=node('div',undefined,'stepactions');
const b=button('Prova OK',()=>proofOk(order),'btn primary');b.dataset.proof='';actions.append(b);text.append(actions);}
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
}else if(mayMove(order.state,next)){
}else if(mayMove(order.state,next)&&mayAct(order)){
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
}
}
if(!row.children.length&&!step)row.append(node('span',order.state==='fin'?'Pedido concluído.'
:!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.'
:order.state==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.','muted'));
// Undo a mistaken move: one stage back, internal reason, no customer message.
const previous=mayMove(order.state,board.back?.[order.state])?board.back?.[order.state]:null;
const previous=mayMove(order.state,board.back?.[order.state])&&mayAct(order)?board.back?.[order.state]:null;
const sub=node('div',undefined,'subactions');
const backForm=node('form',undefined,'reason');backForm.hidden=true;forms.push(backForm);
if(previous){
@@ -1444,7 +1453,8 @@ function historySection(order,rows,section){
if(reason)text.append(node('span',' · '+reason,'muted'));
li.append(text,node('small',when(at)));return li;
};
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),r.operator,r.created_at,r.reason));
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
r.operator+(r.machine?' · '+r.machine:''),r.created_at,r.reason));
list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
paidOutside(order)?ORIGINS[order.origin]+' · pago fora do site ('+PAID_OUTSIDE[order.payment.method]+') · registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
order.created_at,paidOutside(order)?order.payment.note:''));
@@ -1453,11 +1463,53 @@ function historySection(order,rows,section){
// ---- Machines and users ----------------------------------------------------
// "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';
const back=node('div',undefined,'modal');const box=node('div',undefined,'modal-box');
const close=()=>{back.remove();askingMachine=false;};
box.append(node('h2','Em qual máquina você está?'),
node('p','O que você puxar para Imprimindo vai para ela, e o histórico grava a máquina com o seu nome.','faint'));
const choose=async(id,confirm=false)=>{
try{await api('/me/machine',{machine_id:id,confirm});close();await load(true);}
catch(e){if(e.status===409&&!confirm&&window.confirm(e.message+' Continuar mesmo assim?'))return choose(id,true);say(e.message,true);}};
const list=node('div',undefined,'machine-choices');
for(const m of (board.machines||[]).filter(m=>m.active)){
const b=node('button',undefined,'machine-choice'+(myMachine()?.id===m.id?' on':''));b.type='button';
b.append(node('b',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e '),'faint'));
b.onclick=()=>choose(m.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.','faint'));
const row=node('div',undefined,'modal-actions');
if(!required)row.append(button('Não estou em máquina',()=>choose(null),'btn ghost'));
if(again&&ME.machine_answered)row.append(button('Cancelar',close,'btn ghost'));
if(required&&!ME.machine_answered)row.append(button('Sair',()=>$('logout').click(),'btn ghost'));
box.append(list,...(row.children.length?[row]:[]));
back.append(box);document.body.append(back);
}
// The machine beside the account button: green, and a click changes it.
function paintMyMachine(){
const pill=$('my-machine');
pill.hidden=!ME?.machine_question;
if(pill.hidden)return;
pill.replaceChildren(icon(ICON_PRINTER),myMachine()?myMachine().name:'Sem máquina');
pill.classList.toggle('on',!!myMachine());
pill.title=myMachine()?'Você está na '+myMachine().name+'. Clique para trocar.':'Você não está em máquina. Clique para escolher.';
}
$('my-machine').onclick=()=>askMachine(true);
// 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('print')||!board.machines?.length){
// The operator's orders go to the machine that pulls them (item 12).
if(!may('print')||ME?.role==='operador'||!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');
@@ -1499,7 +1551,7 @@ function renderUsers(){
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 machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):'—');
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';
@@ -1533,7 +1585,8 @@ function machineTile(m){
tile.append(head,node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','meta'),
...(m.active||m.open_orders?[bar,used]:[]),
node('span',stages||'Nenhum pedido em aberto','meta'),
node('span',m.operators.length?'Operadores: '+m.operators.map(o=>o.name).join(', '):'Nenhum operador ligado','meta'),actions);
node('span',m.operators.length?'Ligados agora: '+m.operators.map(o=>o.name+(o.since?' (desde '+new Date(o.since).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'})+')':'')).join(', ')
:'Ninguém ligado agora','meta'),actions);
return tile;
}
// One dialog for creating and editing, for users and machines alike.
@@ -1560,13 +1613,9 @@ function userForm(u){
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'8 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 picks=pills(usersData.machines.map(m=>[m.id,m.name]),u?.machines||[]);
const machinesField=group('Máquinas',picks);
const syncMachines=()=>{machinesField.hidden=role.value!=='operador'||!usersData.machines.length;};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()=>{
field(editing?'Nova senha':'Senha inicial',pass),activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
machines:role.value==='operador'?picks.values():[],
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();
@@ -1578,15 +1627,12 @@ function machineForm(m){
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 unit=node('div',undefined,'unit');unit.append(limit,node('span','metros em aberto','faint'));
const operators=usersData.users.filter(u=>u.role==='operador');
const crew=pills(operators.map(u=>[u.id,u.name||u.email]),(m?.operators||[]).map(o=>o.id));
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)');
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),group('Imprime',products),field('Limite',unit),
group('Operadores',operators.length?crew:node('span','Nenhum operador cadastrado.','faint')),activeLabel],async()=>{
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),group('Imprime',products),field('Limite',unit),activeLabel],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,operators:crew.values()});
limit_metres:limit.value?Number(limit.value):null});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
});
}