diff --git a/app/api/operator.py b/app/api/operator.py index 1797588..a1d7af0 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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} diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index 62743a0..4f4dbed 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -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)): diff --git a/web/kanban.js b/web/kanban.js index 2ab8b6b..15e58cc 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -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';