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

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test print_file_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

View File

@@ -147,15 +147,15 @@ ENTRIES = '''WITH live_quote AS (
-- files are gone can no longer be paid.
SELECT q.id, q.created_at, q.approved FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE q.owner=%(me)s AND o.id IS NULL
WHERE q.owner=%(me)s AND o.id IS NULL AND q.discarded_at IS NULL
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i
CROSS JOIN LATERAL jsonb_array_elements_text(i->'uploads') u(uid)
JOIN dtf_local.uploads up ON up.id=u.uid::uuid
WHERE up.purged_at IS NOT NULL OR up.expires_at<=now())
ORDER BY q.created_at DESC LIMIT 1
), entries AS (
SELECT 'order' AS kind, o.id, o.number, o.state,
CASE WHEN o.state='fin' THEN 'fin' WHEN o.state='cor' THEN 'cor' ELSE 'prod' END AS grp,
SELECT 'order' AS kind, o.id, o.number, CASE WHEN o.cancelled_at IS NOT NULL THEN 'cancelled' ELSE o.state END,
CASE WHEN o.cancelled_at IS NOT NULL OR o.state='fin' THEN 'fin' WHEN o.state='cor' THEN 'cor' ELSE 'prod' END AS grp,
(o.snapshot->>'total_cents')::bigint AS total_cents, o.created_at, o.snapshot->'items' AS items
FROM dtf_local.orders o WHERE o.owner=%(me)s
UNION ALL

View File

@@ -25,7 +25,8 @@ router = APIRouter()
# A quote that can still become an order: waiting for review, or approved within
# the payment window. Expired ones leave the Kanban; they can never be paid.
LIVE_QUOTE = f"(q.approved_at IS NULL OR q.approved_at > now() - interval '{int(payments.QUOTE_VALID_HOURS)} hours')"
LIVE_QUOTE = (f"(q.discarded_at IS NULL AND (q.approved_at IS NULL OR "
f"q.approved_at > now() - interval '{int(payments.QUOTE_VALID_HOURS)} hours'))")
@router.post('/api/operator/login')
def operator_login(body: OperatorLogin, request: Request, response: Response):
@@ -97,17 +98,17 @@ def board(user=Depends(operator)):
finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s",
(BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n']
pending = c.execute('''SELECT q.* FROM dtf_local.quotes q
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NULL
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', (BOARD_QUOTE_LIMIT,)).fetchall()
approved = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}
ORDER BY q.created_at DESC,q.id DESC LIMIT 20''').fetchall()
pending_total = c.execute('''SELECT count(*) AS n FROM dtf_local.quotes q
pending_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NULL''').fetchone()['n']
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}''').fetchone()['n']
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
@@ -338,6 +339,56 @@ def test_order(uid: UUID, user=Depends(operator)):
return order
@router.post('/api/operator/quotes/{uid}/discard')
def discard_quote(uid: UUID, user=Depends(operator)):
"""An unpaid quote leaves the Kanban and can no longer be paid. Its files
keep their normal expiry; a payment that still arrives for it is refused
and listed under Pagamentos."""
with db.connect() as c:
# Locked like a payment locks it, so a discard and a payment never cross.
row = c.execute('SELECT id FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Quote not found')
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (uid,)).fetchone():
raise HTTPException(409, 'Esta cotação já virou pedido.')
c.execute('UPDATE dtf_local.quotes SET discarded_at=now(), discarded_by=%s WHERE id=%s AND discarded_at IS NULL',
(user, uid))
audit('quote_discarded', quote=str(uid), operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/delete-test')
def delete_test_order(uid: UUID, user=Depends(operator)):
"""A test order (no payment, never sent to Tiny or WhatsApp) is deleted
with its history and files' records. Its quote is unpaid again."""
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
if not payments.is_test(row):
raise HTTPException(409, 'Só pedidos de teste podem ser excluídos. Um pedido pago se cancela.')
for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
audit('test_order_deleted', order=row['number'], operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(operator)):
"""A paid order leaves the board but keeps its payment and history. Nothing
is refunded here (that is done at the provider) and Tiny is not told."""
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING number''',
(user, body.note, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
audit('order_cancelled', order=row['number'], operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/move')
def move(uid: UUID, body: Move, user=Depends(operator)):
with db.connect() as c:
@@ -346,6 +397,8 @@ def move(uid: UUID, body: Move, user=Depends(operator)):
raise HTTPException(404, 'Order not found')
if body.version != row['version']:
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
if row.get('cancelled_at'):
raise HTTPException(409, 'Pedido cancelado.')
if body.state == row['state']:
return row
back = BACK.get(row['state']) == body.state

View File

@@ -36,6 +36,8 @@ def approved_quote(c, quote_id, owner=None):
raise PaymentRefused('quote not found')
if not row['approved']:
raise PaymentRefused('quote was never reviewed')
if row.get('discarded_at'):
raise PaymentRefused('quote was discarded')
if any(item.get('production', {}).get('version') != 2 for item in row['approved']['items']):
raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):

View File

@@ -85,7 +85,8 @@ def quote_view(c, row):
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'status': 'paid' if order else 'expired' if expired else 'approved' if row['approved'] else 'pending_review',
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',
'review_reason': None if row['approved'] else (row.get('review_note') or review_reason(row['draft'])),
'payment': attempt,

View File

@@ -213,3 +213,12 @@ CREATE TABLE IF NOT EXISTS dtf_local.upload_thumbnails (
upload_id uuid PRIMARY KEY REFERENCES dtf_local.uploads(id),
mime text NOT NULL, data bytea NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
);
-- An operator may discard an unpaid quote (it leaves the Kanban and can no
-- longer be paid) and cancel a paid order (it leaves the board but keeps its
-- payment and history; a refund is made at the provider).
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_at timestamptz;
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text;

View File

@@ -0,0 +1,77 @@
"""Discarding an unpaid quote, deleting a test order, cancelling a paid one.
Run inside the API container: python -m tests.order_actions_test
"""
from urllib.parse import urlencode
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import payments
from app.core import db
from tests.smoke_test import Client
def run():
client = Client()
owner = uuid4()
mail = f'actions-{uuid4().hex[:8]}@example.test'
approved = {'customer': {'mail': mail}, 'items': [], 'total_cents': 1490}
discard, test_quote, paid_quote, paid_order = uuid4(), uuid4(), uuid4(), uuid4()
test_order = None
try:
with db.connect() as c:
for qid in (discard, test_quote, paid_quote):
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''',
(qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved)))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)''',
(paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'})))
listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}),
operator=True)['quotes']}
assert {str(discard), str(test_quote)} <= listed()
# Discarded: gone from the list, and no payment can make it an order.
client.call(f'/operator/quotes/{discard}/discard', {}, operator=True)
assert str(discard) not in listed()
with db.connect() as c:
try:
payments.approved_quote(c, discard)
raise AssertionError('a discarded quote was payable')
except payments.PaymentRefused as refusal:
assert str(refusal) == 'quote was discarded'
client.call(f'/operator/quotes/{paid_quote}/discard', {}, operator=True, expected=409)
# A test order is deleted, and its quote is unpaid again.
test_order = client.call(f'/operator/quotes/{test_quote}/test-order', {}, operator=True)['id']
assert str(test_quote) not in listed()
client.call(f'/operator/orders/{test_order}/delete-test', {}, operator=True)
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (test_order,)).fetchone()
test_order = None
assert str(test_quote) in listed()
# A paid order is cancelled with a reason, kept, and can no longer move.
client.call(f'/operator/orders/{paid_order}/delete-test', {}, operator=True, expected=409)
client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'x'}, operator=True, expected=422)
client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'Cliente desistiu'}, operator=True)
board = client.call('/operator/board', operator=True)
order = next(o for o in board['orders'] if o['id'] == str(paid_order))
assert order['cancelled_at'] and order['cancel_reason'] == 'Cliente desistiu'
client.call(f'/operator/orders/{paid_order}/move', {'state': 'tra', 'version': order['version'], 'reason': ''},
operator=True, expected=409)
client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'de novo'}, operator=True, expected=404)
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel and stay')
finally:
with db.connect() as c:
for oid in filter(None, (test_order, paid_order)):
for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{oid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
c.execute('DELETE FROM dtf_local.orders WHERE quote_id=ANY(%s)', ([discard, test_quote, paid_quote],))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([discard, test_quote, paid_quote],))
if __name__ == '__main__':
run()

View File

@@ -366,7 +366,9 @@
} catch(error) { message(error.message,'error'); event.target.disabled=false; }
});
} else {
message('Cotação expirada. Envie o carrinho de novo para pagar.','warn');
message(quote.status==='discarded'
? 'Esta cotação foi cancelada pela nossa equipe. Envie o carrinho de novo ou fale com a gente.'
: 'Cotação expirada. Envie o carrinho de novo para pagar.','warn');
button('Voltar ao carrinho',()=>{clearDraft();vaiPara(CARRINHO);});
}
} catch(error) {

View File

@@ -344,3 +344,12 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
.buyer-mail{font-size:12.5px;color:var(--faint);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.card .buyer b{font-size:14px;font-weight:600}
.qname .buyer b{font-size:19px}
/* Cotações' heading says what the list is. */
.lhead{display:flex;align-items:baseline;gap:10px}
.lhead span{font-size:13.5px;color:var(--faint)}
/* Discard and cancel: quiet until meant. */
.btn.discard{margin-right:auto}
.btn.discard:hover{color:var(--bad);border-color:var(--bad-line)}
.callout.bad{background:rgba(244,150,139,.12)}
.callout.bad b{color:var(--bad)}

View File

@@ -44,7 +44,7 @@
<section id="tab-quotes" hidden>
<div class="split">
<div class="list">
<h1>Cotações</h1>
<div class="lhead"><h1>Cotações</h1><span>pedidos ainda não pagos</span></div>
<div class="chips" id="quote-filters"></div>
<label class="qsearch">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg>

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);});

View File

@@ -88,6 +88,7 @@ function trilha(state){
}
function estado(e){
if(e.kind==='quote')return e.state==='review'?['Em conferência','est-rev']:['Aguardando pagamento','est-pay'];
if(e.state==='cancelled')return ['Cancelado','est-cor'];
return [states[e.state]||e.state,'est-'+e.state];
}
function resumoItens(items){