From 05da6d78ad1dd1de1598014d2a3c5f6ce7d6c101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 2 Oct 2026 16:20:27 -0300 Subject: [PATCH] feat: discard an unpaid quote, delete a test order, cancel a paid one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .gitea/workflows/deploy.yml | 2 +- app/api/customer.py | 6 +-- app/api/operator.py | 63 +++++++++++++++++++++++++++--- app/payments.py | 2 + app/runtime.py | 3 +- app/schema.sql | 9 +++++ tests/order_actions_test.py | 77 +++++++++++++++++++++++++++++++++++++ web/checkout.js | 4 +- web/kanban.css | 9 +++++ web/kanban.html | 2 +- web/kanban.js | 56 ++++++++++++++++++++++----- web/portal.js | 1 + 12 files changed, 213 insertions(+), 21 deletions(-) create mode 100644 tests/order_actions_test.py diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index d793e66..be5e7ff 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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 \ diff --git a/app/api/customer.py b/app/api/customer.py index 0bccef5..caa3fdc 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -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 diff --git a/app/api/operator.py b/app/api/operator.py index 1f8b820..1797588 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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 diff --git a/app/payments.py b/app/payments.py index 7155730..7aa9c95 100644 --- a/app/payments.py +++ b/app/payments.py @@ -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): diff --git a/app/runtime.py b/app/runtime.py index 1f0190d..1f06a8f 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -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, diff --git a/app/schema.sql b/app/schema.sql index 4582fda..1e52123 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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; diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py new file mode 100644 index 0000000..62743a0 --- /dev/null +++ b/tests/order_actions_test.py @@ -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() diff --git a/web/checkout.js b/web/checkout.js index 10b2fcd..30888b9 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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) { diff --git a/web/kanban.css b/web/kanban.css index 127d38b..4c2f1d5 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -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)} diff --git a/web/kanban.html b/web/kanban.html index fc2e930..b3b822d 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -44,7 +44,7 @@