feat: an approved order nobody paid expires in 24 h (front 9)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m15s
Build and deploy / Integration suite on a real stack (push) Successful in 5m10s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m29s

An approved quote with no payment expires on its own after 24 h, never
while a Pix or card attempt is still live: the worker marks
quotes.expired_at, frees its files and e-mails the customer that the
order expired and can be sent again on the Site. The backlog from before
this front expires silently.

Kanban: Cotações › Aguardando pagamento shows when each one expires and
the review gets an "Abrir conversa" WhatsApp button; Números gets
"Pedidos sem pagamento" (made, paid, expired, waiting, abandonment rate).

release_files moves to app/payments.py so the worker can use it; an
expired quote no longer counts as open there. New tests/unpaid_test.py
in the integration job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 10:01:26 -03:00
parent 448a7fa8c3
commit 1a9611942d
11 changed files with 269 additions and 32 deletions

View File

@@ -18,8 +18,9 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can,
login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files
from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt
from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt, unpaid
from .. import tiny
from ..payments import release_files
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, quote_views, storage, upload_row)
from .uploads import begin_upload
@@ -27,10 +28,10 @@ from ..scanning import require_clean
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.discarded_at IS NULL AND (q.approved_at IS NULL OR "
f"q.approved_at > now() - interval '{int(payments.QUOTE_VALID_HOURS)} hours'))")
# A quote that can still become an order: waiting for review, or approved and
# not expired yet. The worker marks it expired at 24 h (app/unpaid.py); until
# then it stays, even past the payment window while an attempt is still live.
LIVE_QUOTE = "(q.discarded_at IS NULL AND q.expired_at IS NULL)"
@router.post('/api/operator/login')
def operator_login(body: OperatorLogin, request: Request, response: Response):
@@ -723,28 +724,6 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
return {'ok': True}
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload,) * 5).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
"""A paid order leaves the board but keeps its payment and history. Nothing
@@ -1414,6 +1393,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
AND m.to_state='cor' AND NOT m.back)) AS corrected
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}''', period).fetchone()
# Approved quotes of the period nobody paid (front 9).
unpaid_figures = unpaid.figures(c, start, end)
daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders,
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
GROUP BY 1''', period).fetchall()}
@@ -1553,6 +1534,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
'finished': origins[name]['finished'] if name in origins else 0,
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
for name in ORIGINS],
'unpaid': unpaid_figures,
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
'stage_limits': limits, 'late': late,
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],