"""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()