Files
dtf-system/tests/unpaid_test.py
Cauê Faleiros 6970434e5d
All checks were successful
Build and deploy / Validate source (push) Successful in 13s
Build and deploy / Integration suite on a real stack (push) Successful in 8m10s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m17s
fix: a payment started in time is the order when approved late, a second payment is listed for a refund, a coupon's limit is checked at payment
- A PIX paid in its last minutes after the quote's 24 h, or a card approved
  after Mercado Pago's review, was refused ("quote expired before payment"):
  money in, no order. A payment whose attempt began while the quote was
  valid is now honoured; a card in review keeps its quote, files and the
  reconciliation for 72 h.
- A second approved payment of the same cart (a PIX and a card) was taken
  for a re-sent approval and logged only. It is now listed on the Kanban as
  attention, with the order, for a refund.
- A coupon's uses were counted only when the cart was made, so carts made
  before it ran out, or before it was paused or ended, still paid with the
  discount. The intent checks it again and asks for a new cart without it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:29:58 -03:00

123 lines
6.2 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')
# A card in review (Mercado Pago "em análise") tried 30 h ago is still
# live: it may be approved days later (payments.CARD_REVIEW_HOURS).
with db.connect() as c:
c.execute('''UPDATE dtf_local.payment_intents SET status='expired', created_at=now()-interval '31 hours'
WHERE quote_id=%s''', (quote_id,))
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,
amount_cents,response,created_at) VALUES(%s,%s,'fake',%s,'card','pending',%s,'{}',now()-interval '30 hours')''',
(uuid4(), quote_id, 'unpaid-card-' + uuid4().hex, approved['total_cents']))
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '31 hours' WHERE id=%s", (quote_id,))
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
print('PASS: a card in review keeps its quote and files past the 24 h')
# 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()