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
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:
@@ -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'],
|
||||
|
||||
23
app/mail.py
23
app/mail.py
@@ -92,6 +92,29 @@ PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · ar
|
||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
||||
|
||||
|
||||
def quote_expired(c, quote, origin):
|
||||
"""The customer's notice that an approved, unpaid order expired after 24 h
|
||||
(Fase 2, front 9): its files were deleted and they can send it again on
|
||||
the Site. Returns whether it was queued (False without an e-mail)."""
|
||||
customer = (quote.get('draft') or {}).get('customer') or {}
|
||||
if not customer.get('mail'):
|
||||
return False
|
||||
from . import mail_html
|
||||
link = f'{origin}/'
|
||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
|
||||
f'Quando quiser, é só montar de novo no site: {link}'])
|
||||
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
|
||||
mail_html.pill('Pedido expirado', 'info'),
|
||||
mail_html.title('Seu pedido expirou'),
|
||||
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
|
||||
'expirou. Os arquivos que você enviou foram apagados.'),
|
||||
mail_html.button('Montar de novo', link),
|
||||
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
|
||||
])
|
||||
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
|
||||
|
||||
|
||||
def money(cents):
|
||||
whole, cents = divmod(int(cents), 100)
|
||||
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
|
||||
|
||||
@@ -89,6 +89,29 @@ def hold_uploads(c, upload_ids, interval):
|
||||
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
||||
|
||||
|
||||
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 q.expired_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)
|
||||
|
||||
|
||||
def create_order(c, quote, payment, origin):
|
||||
"""Create the order for a reviewed quote, or return the one already there.
|
||||
`origin` is where it came from (D-21): each way in names its own.
|
||||
|
||||
@@ -122,6 +122,7 @@ def quote_views(c, rows):
|
||||
|
||||
def quote_view(c, row, order=None, attempt=None, known=False):
|
||||
from .quote_review import review_reason # it imports this module
|
||||
from .payments import QUOTE_VALID_HOURS # it imports this module too
|
||||
if not known:
|
||||
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
|
||||
# The latest payment attempt, so the payment page can tell a refused card
|
||||
@@ -133,13 +134,19 @@ def quote_view(c, row, order=None, attempt=None, known=False):
|
||||
if attempt and attempt['status'] == 'rejected':
|
||||
from .payment_messages import rejection
|
||||
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
|
||||
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
|
||||
expires_at = (row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
|
||||
if row['approved_at'] else None)
|
||||
expired = (bool(row.get('expired_at')) or
|
||||
bool(row['approved_at'] and row['approved_at'] <
|
||||
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
|
||||
items = (row['approved'] or row['draft']).get('items') or []
|
||||
treatment = (row['approved'] or {}).get('treatment')
|
||||
if not treatment and (row['draft'] or {}).get('treatment') and treatment_cents():
|
||||
treatment = {'cents': treatment_cents(), 'hours': 24}
|
||||
return {'id': row['id'], 'created_at': row['created_at'],
|
||||
'draft': row['draft'], 'approved': row['approved'],
|
||||
'expires_at': expires_at.isoformat() if expires_at else None,
|
||||
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
|
||||
'prumo': prumo.customer_summary(items), 'treatment': treatment,
|
||||
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
|
||||
else 'approved' if row['approved'] else 'pending_review',
|
||||
|
||||
@@ -528,3 +528,6 @@ ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timesta
|
||||
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
||||
-- Thales · máquina2".
|
||||
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
|
||||
|
||||
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
|
||||
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;
|
||||
|
||||
72
app/unpaid.py
Normal file
72
app/unpaid.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""Orders made on the Site and never paid (Dropstar's Fase 2, front 9, 05/11/2026).
|
||||
|
||||
An approved quote is an order the customer did not pay yet: Kanban's
|
||||
Cotações › "Aguardando pagamento" lists it, with how long ago it came and
|
||||
when it expires, so the seller can charge it by WhatsApp. After
|
||||
QUOTE_VALID_HOURS (24 h) without payment it expires on its own: its files
|
||||
are freed for deletion and the customer gets an e-mail ("seu pedido expirou,
|
||||
suba de novo quando quiser"). Never while a payment attempt is still live
|
||||
(a Pix not yet expired, a card being processed), so a late payment always
|
||||
finds its files. Números counts orders made, paid and expired, and the
|
||||
abandonment rate.
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import mail, payments
|
||||
from .payments import QUOTE_VALID_HOURS
|
||||
|
||||
# An intent in one of these no longer waits for money: approved (it became an
|
||||
# order), rejected, cancelled, expired or refunded (app/payments.py).
|
||||
FINAL_INTENT = ('approved', 'rejected', 'cancelled', 'expired', 'refunded')
|
||||
|
||||
|
||||
def expire(c, origin):
|
||||
"""Expire the approved, unpaid quotes past QUOTE_VALID_HOURS: set
|
||||
quotes.expired_at, free their files (payments.release_files) and queue the
|
||||
customer's e-mail (mail.quote_expired). Returns how many expired."""
|
||||
rows = c.execute('''SELECT q.* FROM dtf_local.quotes q
|
||||
WHERE q.approved IS NOT NULL AND q.discarded_at IS NULL AND q.expired_at IS NULL
|
||||
AND q.approved_at <= now() - make_interval(hours => %s)
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM dtf_local.payment_intents i
|
||||
WHERE i.quote_id=q.id
|
||||
AND i.id = (SELECT i2.id FROM dtf_local.payment_intents i2
|
||||
WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
|
||||
AND i.status <> ALL(%s)
|
||||
AND i.created_at > now() - make_interval(hours => %s)
|
||||
AND (i.response->>'expires_at' IS NULL
|
||||
OR (i.response->>'expires_at')::timestamptz > now()))
|
||||
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''',
|
||||
(QUOTE_VALID_HOURS, list(FINAL_INTENT), QUOTE_VALID_HOURS + 1)).fetchall()
|
||||
for row in rows:
|
||||
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],))
|
||||
# expired_at is set first: release_files must no longer see this quote
|
||||
# as open, or its own files would stay held.
|
||||
payments.release_files(c, payments.quote_uploads(row['approved']))
|
||||
# Only a quote that just ran out is news to the customer: the backlog
|
||||
# from before this front existed expires silently on the first pass.
|
||||
if row['approved_at'] > datetime.now(timezone.utc) - timedelta(hours=2 * QUOTE_VALID_HOURS):
|
||||
mail.quote_expired(c, row, origin)
|
||||
return len(rows)
|
||||
|
||||
|
||||
def figures(c, start, end):
|
||||
"""Números, for quotes approved between the local days `start` and `end`
|
||||
(inclusive): {'made': n, 'paid': n, 'expired': n, 'waiting': n,
|
||||
'abandon_pct': float | None}. Paid has an order; expired has expired_at;
|
||||
waiting is neither yet. abandon_pct is expired / (paid + expired) * 100,
|
||||
one decimal, None when both are 0."""
|
||||
row = c.execute('''SELECT count(*) AS made,
|
||||
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS paid,
|
||||
count(*) FILTER (WHERE q.expired_at IS NOT NULL) AS expired,
|
||||
count(*) FILTER (WHERE q.expired_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS waiting
|
||||
FROM dtf_local.quotes q
|
||||
WHERE q.discarded_at IS NULL AND q.approved_at IS NOT NULL
|
||||
AND (q.approved_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
|
||||
(start, end)).fetchone()
|
||||
paid, expired = row['paid'], row['expired']
|
||||
decided = paid + expired
|
||||
return {'made': row['made'], 'paid': paid, 'expired': expired, 'waiting': row['waiting'],
|
||||
'abandon_pct': round(expired / decided * 100, 1) if decided else None}
|
||||
@@ -6,7 +6,7 @@ import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from psycopg.types.json import Jsonb
|
||||
from . import mail
|
||||
from . import mail, unpaid
|
||||
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||
from .core.secrets import load as load_secret_files
|
||||
from .core.db import connect
|
||||
@@ -121,6 +121,9 @@ def loop():
|
||||
tick()
|
||||
if time.monotonic()-last_cleanup > 60:
|
||||
cleanup()
|
||||
# Approved quotes unpaid for 24 h expire on their own (front 9).
|
||||
with connect() as c:
|
||||
unpaid.expire(c, os.environ.get('PUBLIC_ORIGIN', 'http://localhost'))
|
||||
last_cleanup = time.monotonic()
|
||||
mail.send_pending(connect)
|
||||
tiny_keepalive()
|
||||
|
||||
Reference in New Issue
Block a user