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>
This commit is contained in:
Cauê Faleiros
2026-11-12 15:48:41 -03:00
parent 7abd215d13
commit d0ec629c4e
3 changed files with 110 additions and 36 deletions

View File

@@ -227,12 +227,10 @@ try{
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
// The Prumo report is on the card before the designer opens the file.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] .prumo')`),'Prumo report');
// No machine at payment (Dropstar, 2026-11-05): the pull chooses one. It is
// the machine this test made after sign-in.
// No machine at payment (Dropstar, 2026-11-05): pulling without a session
// machine asks which machine takes the card (DTF-WEB-4). It is the machine
// this test made after sign-in.
const machineId=testMachine;
await kanban.eval(`(()=>{const s=document.querySelector('[data-order="${oid}"] select[aria-label="Máquina do pedido"]');
s.value=${JSON.stringify(machineId)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'machine chosen');
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
if(state==='tra'){
@@ -275,6 +273,12 @@ try{
}
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
if(state==='imp'){
// The order has no machine and the session has none: pick it here.
await waitFor(()=>kanban.eval(`!!document.querySelector('.mchoice[data-machine="${machineId}"]')`),'machine chooser');
await kanban.click(`.mchoice[data-machine="${machineId}"]`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'card machine chosen');
}
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
if(state==='tra'){
// The file opens from the card itself, without first expanding the order.

View File

@@ -5,6 +5,26 @@
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
@@ -23,21 +43,7 @@ function askMachine(again=false){
// 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 mine=current?.id===machine.id;
const b=node('button',undefined,'mchoice'+(mine?' on':''));b.type='button';b.setAttribute('aria-pressed',String(mine));
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'));}
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'));
@@ -500,14 +506,19 @@ async function machineEntryForm(machineId, preset={}, data=null){
// 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,
role:'alertdialog',foot:[...(alert.snoozable?[later]:[]),back,made],
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=>{
@@ -537,15 +548,53 @@ function machineAlertDialog(order,machineId,alert){
});
}
// 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.
async function pullTo(order, machineId){
const target=machineId||order.machine?.id||myMachine()?.id||null;
if(target){
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;
// 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){

View File

@@ -1886,13 +1886,34 @@ function readyFinals(order){
return {files,name:files[0].name,source:original?'original':'generated',label:(original?'O original (':'Gerado pelo sistema (')+names+')'};
});
}
// Sends final-files from a dialog that may have been opened before another
// screen approved the same files (DTF-WEB-7). A stale version gets 409 "O
// pedido mudou"; when the approval is already there, or the order left Arte
// recebida/Correção, reload and say so; true tells the caller to stop, and a
// form dialog then closes itself. Anything else is still an error, and the
// version is never resent blindly.
async function saveFinalFiles(order, files, note){
try{
await api('/orders/'+order.id+'/final-files',{version:order.version,files,note});
return false;
}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&&(finalDone(fresh)||!['rec','cor'].includes(fresh.state))){
say('O arquivo final já estava aprovado.');
return true;
}
throw error;
}
}
async function approveReady(order,ready){
const many=ready.length>1;
if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+
ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return;
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
await api('/orders/'+order.id+'/final-files',{version:order.version,
files:ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note});
if(await saveFinalFiles(order,
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return;
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
}
// The file the operator prepared, per item; a ready file comes ticked.
@@ -1930,7 +1951,7 @@ function finalDialog(order,ready,{replace=false}={}){
refs.push({item_index:index,upload_id:uid});
}
}
await api('/orders/'+order.id+'/final-files',{version:order.version,files:refs,note:note.value});
if(await saveFinalFiles(order,refs,note.value))return;
await load();say('Arquivo final aprovado.');
}});
}
@@ -2151,9 +2172,9 @@ function isOk(order){
for(const [index,select] of selects.entries())
if(select.value!==contractionOf(order,index))
await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value});
if(!finalDone(order))
await api('/orders/'+order.id+'/final-files',{version:order.version,
files:ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note:'Conferido em Abrir e conferir'});
if(!finalDone(order)&&await saveFinalFiles(order,
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),
'Conferido em Abrir e conferir'))return;
await load();
await move(board.orders.find(o=>o.id===order.id)||order,'tra');
say('Pedido #'+order.number+' em Arte conferida.');
@@ -2210,7 +2231,7 @@ function treatDialog(order){
const uid=await dtfUpload(p.file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)});
refs.push({item_index:index,upload_id:uid});
}
await api('/orders/'+order.id+'/final-files',{version:order.version,files:refs,note:TREAT_NOTE});
if(await saveFinalFiles(order,refs,TREAT_NOTE))return;
await load();
say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.');
}});