feat: the pickup receipt in Recibos/ and "Retirado" on the card (Dropstar's third round, item 14)
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s

A pickup order reaching Finalizado has its receipt due: a PDF for the
80 mm roll with the order number large at the top, the customer and
CPF/CNPJ, each product and its metres, the amount and how it was paid,
the date issued, and the "Retirado em" and "Assinatura" lines
(app/receipt.py). The Kanban's folder saves it in Recibos/, where the
counter's print queue sends it to the Bematech. One computer claims each
receipt on the server before writing it, so it is never printed twice,
and gives it back if it could not save it. Orders sent by carrier have
none.

"Retirado" on a pickup in Finalizado records when and who handed it
over, with an optional photo of the signed receipt (kept 30 days). Anyone
but the seller may mark it (new "deliver" capability); the order panel
also opens the receipt to print it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-29 18:39:17 -03:00
parent a5417d200e
commit d962865944
8 changed files with 378 additions and 14 deletions

View File

@@ -191,6 +191,8 @@ main{padding:0 24px 24px}
.finalform input[type=file]::file-selector-button{height:34px;padding:0 12px;margin-right:10px;border-radius:8px;border:1px solid var(--line2);background:var(--card2);color:var(--tx);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer}
.finalform .slot{display:flex;flex-direction:column;gap:6px;font-size:14px;font-weight:600}
.treatline{display:flex;align-items:center;gap:8px}
.pickup{display:flex;flex-direction:column;gap:10px}
.pickup .buttons[hidden]{display:none}
.treatpath{flex:1;min-width:0;padding:7px 10px;border-radius:8px;background:var(--card2);font-family:var(--mono);font-size:13px;font-weight:500;color:var(--tx);word-break:break-all}
.timeline{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:10px}
.timeline li::before{content:"";width:8px;height:8px;margin-top:6px;border-radius:999px;background:var(--c,var(--muted));flex-shrink:0}

View File

@@ -229,6 +229,8 @@ const BRAVE_FLAG='brave://flags/#file-system-access-api';
// Numbered so a folder listing shows them in the flow's order.
const STAGE_FOLDERS={rec:'1. Arte recebida',tra:'2. Arte conferida',imp:'2. Arte conferida',rev:'2. Arte conferida',fin:'3. Finalizado'};
const KEEP_FINISHED_DAYS=30;
// The pickup receipts (item 14): the counter's print queue watches this one.
const RECEIPTS_FOLDER='Recibos';
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null,
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
@@ -291,7 +293,7 @@ function folderCard(){
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as três pastas pedem o Chrome ou o Edge.',
actions:[act('Ligar',()=>setDownloads(true))],details:how});
}else if(!h){
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos em três pastas: Arte recebida, Arte conferida e Finalizado.',
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos em três pastas, Arte recebida, Arte conferida e Finalizado, e o recibo de cada retirada em Recibos.',
actions:[act('Escolher pasta',chooseFolder)],
details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as três pastas e move o arquivo conforme o card anda. '+
'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]});
@@ -305,6 +307,7 @@ function folderCard(){
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em Arte recebida, passa para Arte conferida quando o card vai para lá '+
'(e fica lá enquanto imprime e na Revisão) e vai para Finalizado quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'),
node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada.'),
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+
'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')],
@@ -405,7 +408,7 @@ async function syncFolder(force=false){
try{
if(stages)await makeStageFolders();
const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[];
const {files,states}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
const {files,states,receipts=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
const wanted=new Map(files.map(f=>[f.order+':'+f.item,f]));
const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
let removed=0, moved=0, saved=0;
@@ -446,9 +449,22 @@ async function syncFolder(force=false){
}
saved++;
}
// Each pickup receipt saved once, by the computer that takes it, so the
// counter's queue never prints one twice; one this computer could not
// save goes back for another to take. Written whole, then named .pdf.
let printed=0;
for(const r of receipts){
try{await api('/orders/'+r.order+'/receipt/claim',{});}catch(e){if(e.status===409)continue;throw e;}
try{
const res=await fetch('/api/operator/orders/'+r.order+'/receipt');
if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').');
await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res.body);printed++;
}catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;}
}
FOLDER.lastSig=sig;FOLDER.error='';
FOLDER.status='';
if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.');
if(printed)say(printed+' recibo(s) de retirada salvos em '+RECEIPTS_FOLDER+'.');
if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.');
if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.');
}catch(e){
@@ -783,6 +799,7 @@ function card(order){
? badge('✓ Prova OK','ok','Conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at))
: badge('Prova','warn',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto'));
}
if(!order.cancelled_at&&order.picked_up_at)flags.append(badge('✓ Retirado','ok','Retirado em '+when(order.picked_up_at)+' por '+order.picked_up_by));
const redo=(order.reworks||[]).filter(r=>r.authorized!==false);
if(!order.cancelled_at&&redo.length)flags.append(badge('Retrabalho','bad',redo.map(r=>REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join('\n')));
// Arte tratada (Dropstar, 2026-10-27): the final is not the customer's art, someone prepared it.
@@ -1066,7 +1083,40 @@ function moves(order){
reason.append(text,sendFix);
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
const contactNow=waitingContact(order)?contactNotice(order,may('produce')):null;
box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
const pickup=order.state==='fin'&&isPickup(order)?pickupBox(order):null;
box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(pickup?[pickup]:[]),
...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
}
// Pickup (item 14): the receipt, to print again, and "Retirado", which closes
// the cycle with who handed the order over and the photo of the signed receipt.
const isPickup=order=>order.snapshot.freight?.service==='pickup';
function pickupBox(order){
const box=node('div',undefined,'pickup');
const actions=node('div',undefined,'buttons');
const paper=button('Recibo',()=>window.open('/api/operator/orders/'+order.id+'/receipt','_blank','noopener'),'btn ghost');
paper.title='Abrir o recibo de retirada para imprimir de novo';actions.append(paper);
if(order.picked_up_at){
const line=node('div',undefined,'file');line.append(icon(ICON_OK),node('span','Retirado em '+when(order.picked_up_at)+' por '+order.picked_up_by,'ok'));
if(order.picked_up_photo)actions.append(downloadButton('Foto do recibo',download(order.picked_up_photo),'btn ghost small'));
box.append(line,actions);return box;
}
if(!may('deliver')){box.append(actions);return box;}
const form=node('form',undefined,'finalform');form.hidden=true;
const photo=node('input');photo.type='file';photo.accept='image/*';photo.setAttribute('aria-label','Foto do recibo assinado');
const field=node('label',undefined,'slot');field.append('Foto do recibo assinado (opcional)',photo);
const go=node('button','Confirmar retirada','btn primary');
const open=node('button','Retirado','btn primary');open.type='button';open.dataset.pickedUp='';
const cancel=node('button','Cancelar','linkbtn');cancel.type='button';cancel.onclick=()=>{form.hidden=true;actions.hidden=false;};
open.onclick=()=>{form.hidden=false;actions.hidden=true;};
actions.prepend(open);form.append(field,go,cancel);
form.onsubmit=async e=>{e.preventDefault();go.disabled=true;
try{
const uid=photo.files[0]?await dtfUpload(photo.files[0],{api,startPath:'/orders/'+order.id+'/pickup-uploads',
scope:'operator:pickup:'+order.id,progress:text=>say(text)}):null;
await api('/orders/'+order.id+'/picked-up',{photo:uid});
await load();say('Pedido #'+order.number+' marcado como retirado.');
}catch(error){say(error.message,true);go.disabled=false;}};
box.append(actions,form);return box;
}
function contactNotice(order,canClear){
const box=node('div',undefined,'callout contact');