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
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:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user