Files
dtf-system/tests/unpaid_test.py
Cauê Faleiros 1a9611942d
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
feat: an approved order nobody paid expires in 24 h (front 9)
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>
2026-11-09 10:01:26 -03:00

108 lines
5.1 KiB
Python

"""Approved quotes nobody paid expire after 24 h (Fase 2, front 9).
Run inside the API container: python -m tests.unpaid_test
A live payment attempt keeps the files; once it is final, the quote expires,
its files are freed, the customer is e-mailed once and it leaves the Kanban.
"""
from datetime import datetime, timedelta, timezone
from urllib.parse import urlencode
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import unpaid
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
ORIGIN = 'http://localhost'
SUBJECT = 'Seu pedido expirou · DTF Dropstar'
def reviewed_quote():
"""A quote an operator has approved, ready to be paid."""
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'UNPAID EXPIRE TEST')
item = item_spec('file', '1.01', 0, uid)
mail = 'unpaid-' + uuid4().hex[:8] + '@example.test'
profile = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'customer': profile,
'items': [item], 'freight': {'service': 'pickup'}})
approved = approved_quote(customer, quote, [item])
return customer, quote['id'], approved, mail
def attempt(c, quote_id, total, status, expires_at):
"""A payment attempt as the intent route records it."""
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,
method,status,amount_cents,response) VALUES(%s,%s,'fake',%s,'pix',%s,%s,%s)''',
(uuid4(), quote_id, 'unpaid-' + uuid4().hex, status, total,
Jsonb({'status': status, 'expires_at': expires_at.isoformat()})))
def run():
customer, quote_id, approved, mail = reviewed_quote()
uploads = [uid for item in approved['items'] for uid in item['uploads']]
# 25 h old, but a PIX still open: the quote must not expire, nor its files.
with db.connect() as c:
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '25 hours' WHERE id=%s",
(quote_id,))
attempt(c, quote_id, approved['total_cents'], 'pending',
datetime.now(timezone.utc) + timedelta(minutes=30))
with db.connect() as c:
unpaid.expire(c, ORIGIN)
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(quote_id,)).fetchone()['expired_at'] is None
page = customer.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)
assert quote_id in {q['id'] for q in page['quotes']}
print('PASS: a live payment attempt keeps an approved quote and its files')
# The attempt is final now: the quote expires, its files are freed and the
# customer is told once.
with db.connect() as c:
c.execute("UPDATE dtf_local.payment_intents SET status='expired' WHERE quote_id=%s", (quote_id,))
expired = unpaid.expire(c, ORIGIN)
assert expired >= 1, expired
with db.connect() as c:
row = c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
assert row['expired_at'] is not None
files = c.execute('''SELECT count(*) AS total,
count(*) FILTER (WHERE expires_at<=now()) AS released
FROM dtf_local.uploads WHERE id=ANY(%s)''', (uploads,)).fetchone()
assert files['total'] and files['released'] == files['total'], files
mails = c.execute('SELECT kind,subject FROM dtf_local.mail_queue WHERE to_addr=%s ORDER BY id',
(mail,)).fetchall()
assert [m['subject'] for m in mails] == [SUBJECT], mails
page = customer.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)
assert quote_id not in {q['id'] for q in page['quotes']}
print('PASS: the expired quote leaves the Kanban, frees its files and e-mails the customer')
# Expiring again is a no-op: the customer is not told twice.
with db.connect() as c:
unpaid.expire(c, ORIGIN)
with db.connect() as c:
sent = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE to_addr=%s AND subject=%s',
(mail, SUBJECT)).fetchone()['n']
assert sent == 1, sent
print('PASS: a second run does not e-mail the customer again')
# A quote from before this front ran out days ago: it expires silently.
_, old_id, _, old_mail = reviewed_quote()
with db.connect() as c:
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '3 days' WHERE id=%s", (old_id,))
unpaid.expire(c, ORIGIN)
with db.connect() as c:
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(old_id,)).fetchone()['expired_at'] is not None
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s', (old_mail,)).fetchone()
print('PASS: an old backlog quote expires without an e-mail')
stats = customer.call('/operator/stats?days=7', operator=True)
assert stats['unpaid']['expired'] >= 1, stats['unpaid']
print('PASS: Números counts the expired order')
if __name__ == '__main__':
run()