feat: a cancelled order can be deleted
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 2m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m2s

"Excluir pedido" now also works on a paid order once it is cancelled; one in
progress must be cancelled first, with its reason. Deleting a cancelled order
also discards its quote, so it neither returns to Cotações as unpaid nor can
be paid again. The payment stays recorded and the audit log keeps who deleted
which order and the cancellation reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-02 16:32:26 -03:00
parent dfa297d9b5
commit 8236ad8f0a
3 changed files with 32 additions and 12 deletions

View File

@@ -357,21 +357,29 @@ def discard_quote(uid: UUID, user=Depends(operator)):
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."""
@router.post('/api/operator/orders/{uid}/delete')
def delete_order(uid: UUID, user=Depends(operator)):
"""Deletes a test order, or a paid order already cancelled, with its
history and files' records. A paid order in progress must be cancelled
first, with its reason. A test order's quote is unpaid again; a cancelled
one's is discarded, so it neither returns to Cotações nor can be paid twice.
The payment itself stays recorded, and the audit log keeps who deleted what."""
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.')
test = payments.is_test(row)
if not test and not row.get('cancelled_at'):
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
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)
if not test:
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
(user, row['quote_id']))
audit('order_deleted', order=row['number'], test=test, operator=user,
reason=row.get('cancel_reason') or '')
return {'ok': True}

View File

@@ -45,14 +45,15 @@ def run():
# 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)
client.call(f'/operator/orders/{test_order}/delete', {}, 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)
# A paid order in progress is not deleted: it is cancelled first.
client.call(f'/operator/orders/{paid_order}/delete', {}, 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)
@@ -61,7 +62,14 @@ def run():
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')
# Cancelled, it can be deleted; its quote is discarded, not unpaid again.
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
assert c.execute('SELECT discarded_at FROM dtf_local.quotes WHERE id=%s', (paid_quote,)).fetchone()['discarded_at']
assert str(paid_quote) not in listed()
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete')
finally:
with db.connect() as c:
for oid in filter(None, (test_order, paid_order)):

View File

@@ -434,7 +434,11 @@ function moves(order){
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 remove=button('Excluir pedido',async()=>{
if(!window.confirm('Excluir o pedido #'+order.number+' de vez? Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.'))return;
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load();
},'btn danger');remove.style.alignSelf='flex-start';
box.append(note,remove);return box;
}
const row=node('div',undefined,'moves');
const reason=node('form',undefined,'reason');reason.hidden=true;
@@ -464,7 +468,7 @@ function moves(order){
if(isTest(order)){
row.append(button('Excluir pedido de teste',async()=>{
if(!window.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();
await api('/orders/'+order.id+'/delete',{});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';