feat: discard an unpaid quote, delete a test order, cancel a paid one
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m44s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 54s

Cotações (now subtitled "pedidos ainda não pagos") can discard a quote: it
leaves every list and the search, and a payment for it is refused like an
expired one. A test order can be deleted with its history; its quote is unpaid
again. A paid order is cancelled with a required reason: it leaves the board
for a "Cancelados" chip, keeps its payment and history, can no longer move,
and the customer's account shows it as cancelled. Refunds stay at Mercado
Pago and Tiny is not told; the cancel form says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-02 16:20:27 -03:00
parent 7877489563
commit 05da6d78ad
12 changed files with 213 additions and 21 deletions

View File

@@ -17,6 +17,7 @@ function outcomeText(outcome){
[/^refused: paid (\S+) but quote total is (\d+)/,m=>'valor pago ('+(m[1]==='None'?'não informado':money(Number(m[1])))+') diferente do total da cotação ('+money(Number(m[2]))+')'],
[/^refused: quote expired/,()=>'a cotação venceu antes do pagamento'],
[/^refused: quote not found/,()=>'cotação não encontrada'],
[/^refused: quote was discarded/,()=>'a cotação tinha sido descartada no Kanban'],
[/^refused: reference is not a quote id/,()=>'a referência do pagamento não é uma cotação'],
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'],
@@ -242,7 +243,7 @@ function showTab(name){
}
function render(){
$('who').textContent=board.operator||'';
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin').length);
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
tinyHeader();renderBoard();renderIntegrations();
@@ -268,6 +269,9 @@ function printState(order){
}
const stalled=order=>['rec','tra','fil','imp'].includes(order.state)&&Date.now()-new Date(order.updated_at)>LATE_HOURS*3600000;
function matchesFilter(order,key){
// A cancelled order shows only under "Cancelados", and only there.
if(key==='cancelados')return !!order.cancelled_at;
if(order.cancelled_at)return false;
const modes=order.snapshot.items.map(i=>i.mode);
if(key==='textil')return modes.some(m=>m==='file'||m==='avulsa');
if(key==='uv')return modes.some(m=>m==='uvfile'||m==='uv');
@@ -280,12 +284,12 @@ function matchesFilter(order,key){
const matches=order=>matchesFilter(order,filter);
function renderBoard(){
const filters=[['all','Todos'],['textil','Têxtil'],['uv','UV'],['entrega','Entrega'],['retirada','Retirada'],
['parados','Parados'],['manual','Preparar à mão']];
['parados','Parados'],['manual','Preparar à mão'],['cancelados','Cancelados']];
// Each chip says how many orders in progress it would show.
const inProgress=board.orders.filter(o=>o.state!=='fin');
const inProgress=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at);
$('filters').replaceChildren(...filters.map(([key,label])=>{
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(filter===key));
b.append(node('span',String(inProgress.filter(o=>matchesFilter(o,key)).length),'chip-n'));
b.append(node('span',String((key==='cancelados'?board.orders:inProgress).filter(o=>matchesFilter(o,key)).length),'chip-n'));
if(key==='parados')b.title='Sem mudar de etapa há mais de '+LATE_HOURS+' h';
b.onclick=()=>{filter=key;renderBoard();};return b;}));
const active=board.orders.filter(o=>['rec','tra','fil','imp'].includes(o.state));
@@ -317,7 +321,7 @@ function renderBoard(){
// An operator's test order: no payment, no Tiny, no WhatsApp.
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=true;
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at;
if(order.id===openOrder)c.classList.add('open');
const s=order.snapshot;
const top=node('div',undefined,'row');
@@ -327,7 +331,8 @@ function card(order){
node('b',metres(s.items.reduce((t,i)=>t+Number(i.billed_metres),0)),'mtr'));
// What needs attention, as badges; a finished order needs none.
const flags=node('div',undefined,'flags');
if(order.state!=='fin'){
if(order.cancelled_at)flags.append(badge('Cancelado','bad','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason));
else if(order.state!=='fin'){
const p=printState(order);
flags.append(badge((p.tone==='ok'?'✓ ':p.tone==='warn'?'! ':'')+p.text,p.tone));
if(s.items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva','warn','O cliente aceitou a ressalva de resolução'));
@@ -390,7 +395,8 @@ function renderPanel(order){
// What was paid and when, and whether it is stuck: the first things asked of an order.
const paid=node('div',undefined,'paidline');
paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at):' pago em '+when(order.created_at));
if(stalled(order))paid.append(badge('⏱ Parado há '+hoursSince(order.updated_at)+' h','bad'));
if(order.cancelled_at)paid.append(badge('Cancelado','bad'));
else if(stalled(order))paid.append(badge('⏱ Parado há '+hoursSince(order.updated_at)+' h','bad'));
const steps=node('ol',undefined,'steps');steps.setAttribute('aria-label','Etapas');
const at=FLOW.indexOf(order.state);
for(const [i,s] of FLOW.entries()){const li=node('li',board.states[s]);li.style.setProperty('--c',STAGE_COLORS[s]);
@@ -425,6 +431,11 @@ function renderPanel(order){
}
function moves(order){
const box=node('div');box.style.display='flex';box.style.flexDirection='column';box.style.gap='10px';
if(order.cancelled_at){
const note=node('div',undefined,'callout bad');
note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason));
box.append(note);return box;
}
const row=node('div',undefined,'moves');
const reason=node('form',undefined,'reason');reason.hidden=true;
for(const next of board.transitions[order.state]){
@@ -448,11 +459,29 @@ function moves(order){
backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}};
}
if(!row.children.length)row.append(node('span','Pedido concluído.','muted'));
// A test order is deleted; a paid one is cancelled, with a reason, and kept.
const cancelForm=node('form',undefined,'reason');cancelForm.hidden=true;
if(isTest(order)){
row.append(button('Excluir pedido de teste',async()=>{
if(!confirm('Excluir o pedido de teste #'+order.number+'? Ele some do Kanban, com o histórico.'))return;
await api('/orders/'+order.id+'/delete-test',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();
},'btn ghost'));
}else{
const b=node('button','Cancelar pedido','btn ghost');b.type='button';
b.onclick=()=>{cancelForm.hidden=!cancelForm.hidden;reason.hidden=true;backForm.hidden=true;if(!cancelForm.hidden)cancelForm.querySelector('input').focus();};
row.append(b);
const why=node('input');why.placeholder='Motivo do cancelamento';why.setAttribute('aria-label','Motivo do cancelamento');why.required=true;why.minLength=3;why.maxLength=1000;
const go=node('button','Cancelar pedido #'+order.number,'btn danger');
cancelForm.append(node('span','O pedido sai do quadro e fica em "Cancelados", com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago, e o pedido no Tiny se cancela lá.','muted'),why,go);
cancelForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;
try{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}
catch(error){say(error.message,true);go.disabled=false;}};
}
const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true;
const confirm=node('button','Enviar para correção','btn danger');
reason.append(text,confirm);
reason.onsubmit=async e=>{e.preventDefault();confirm.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);confirm.disabled=false;}};
box.append(row,reason,backForm);return box;
box.append(row,reason,backForm,cancelForm);return box;
}
const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'PDF gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'};
function itemCard(order,item,index){
@@ -674,6 +703,7 @@ function review(quote){
}
card.append(head,content);
if(quote.status==='approved'){
foot.append(discardButton(quote));
// Tries the whole production flow without a payment.
foot.append(button('Criar pedido de teste',async()=>{
if(!confirm('Criar um pedido de TESTE para esta cotação? Não cobra nada e não vai para o Tiny nem para o WhatsApp.'))return;
@@ -687,6 +717,7 @@ function review(quote){
const form=node('form');form.style.display='contents';
const edits=quote.draft.items.map(item=>{const fields={};content.append(quoteItem(item,fields));
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});
foot.append(discardButton(quote));
const check=node('input');check.type='checkbox';check.required=true;
// Not "confirm": that name in this function hid window.confirm from the
// test-order button above, which then failed before asking anything.
@@ -701,6 +732,13 @@ function review(quote){
catch(error){say(error.message,true);submit.disabled=false;}};
card.append(head,form);return card;
}
// An unpaid quote leaves the list and can no longer be paid.
function discardButton(quote){
return button('Descartar cotação',async()=>{
if(!confirm('Descartar esta cotação? Ela sai do Kanban e o cliente não consegue mais pagá-la.'))return;
await api('/quotes/'+quote.id+'/discard',{});currentQuote=null;say('Cotação descartada.');await load();
},'btn ghost discard');
}
function quoteItem(item,fields,priced){
const box=node('div',undefined,'item');
const preview=itemPreview(item);
@@ -982,7 +1020,7 @@ function orderHit(order){
const s=order.snapshot;
return hitRow(s.items,'#'+order.number,buyer(s).title,
s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(s.destination?'Entrega':'Retirada')+' · pago '+when(order.created_at),
board.states[order.state],STAGE_COLORS[order.state],()=>{
order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'var(--bad)':STAGE_COLORS[order.state],()=>{
// An older finished order is not on the board yet: it joins, like "Carregar mais".
if(!board.orders.some(o=>o.id===order.id)){olderFinished.push(order);board.orders.push(order);}
showTab('board');openPanel(order.id);});