diff --git a/app/api/payments.py b/app/api/payments.py index 4dcffcc..2c1478f 100644 --- a/app/api/payments.py +++ b/app/api/payments.py @@ -11,7 +11,7 @@ import httpx from fastapi import APIRouter, Depends, HTTPException, Request from psycopg.types.json import Jsonb -from .. import payment_messages as messages, payments +from .. import coupons, payment_messages as messages, payments from ..core import db from ..core.auth import audit, client_ip, owner, rate_limit from ..core.models import PaymentIntent @@ -104,6 +104,15 @@ def intent(body: PaymentIntent, session_id=Depends(owner)): raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal)) if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone(): raise HTTPException(409, 'Este pedido já foi pago.') + # A coupon's limits are spent at payment (app/coupons.py): one used up, + # paused or ended since the cart was made no longer gives its discount. + coupon = quote['approved'].get('coupon') + if coupon: + try: + coupons.check(c, coupon['code'], (quote['approved'].get('customer') or {}).get('cnpj'), + quote['approved']['items']) + except HTTPException as refusal: + raise HTTPException(409, f'{refusal.detail} Monte o carrinho de novo, sem o cupom, para pagar.') # Never charge for files that are gone: an unpaid cart's files are # removed after a while. A payment under way keeps them a day longer, # time enough for the provider's notice to become the order. @@ -113,7 +122,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)): if live != len(set(uploads)): raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. ' 'Monte o pedido de novo para pagar.') - payments.hold_uploads(c, uploads, '1 day') + # A card may sit in review for days (payments.CARD_REVIEW_HOURS). + payments.hold_uploads(c, uploads, f'{payments.CARD_REVIEW_HOURS} hours' if body.method.type == 'card' else '1 day') # Never a second charge: an approved payment is waiting for its # notification to become the order, and a card in review may still be. # A card waiting for the bank's confirmation (3-D Secure) blocks only diff --git a/app/payments.py b/app/payments.py index c0f4fe1..c50908c 100644 --- a/app/payments.py +++ b/app/payments.py @@ -24,14 +24,20 @@ from .runtime import PUBLIC_ORIGIN, enqueue, upload_row from .scanning import require_clean QUOTE_VALID_HOURS = 24 +# A card the provider holds "em análise" may be approved hours or days later: +# its quote stays open, its files kept and the provider asked this long. +CARD_REVIEW_HOURS = 72 class PaymentRefused(Exception): """The payment cannot become an order, with a reason worth recording.""" -def approved_quote(c, quote_id, owner=None): - """The reviewed quote behind a payment, or a refusal explaining why not.""" +def approved_quote(c, quote_id, owner=None, payment_id=None): + """The reviewed quote behind a payment, or a refusal explaining why not. + `payment_id`, from a provider's notice: a payment started while the quote + was valid is honoured whenever its approval arrives (a PIX paid in its + last minutes, a card approved after review).""" sql = 'SELECT * FROM dtf_local.quotes WHERE id=%s' + (' AND owner=%s' if owner else '') row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone() if not row: @@ -42,8 +48,13 @@ def approved_quote(c, quote_id, owner=None): raise PaymentRefused('quote was discarded') if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']): raise PaymentRefused('quote uses an obsolete production layout; request a new quote') - if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS): - raise PaymentRefused('quote expired before payment') + deadline = row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS) + if deadline < datetime.now(timezone.utc): + started = payment_id and c.execute('''SELECT 1 FROM dtf_local.payment_intents + WHERE quote_id=%s AND provider_payment_id=%s AND created_at <= %s''', + (quote_id, str(payment_id), deadline)).fetchone() + if not started: + raise PaymentRefused('quote expired before payment') return row @@ -240,7 +251,7 @@ def apply(c, event): return 'refused: reference is not a quote id' try: - quote = approved_quote(c, quote_id) + quote = approved_quote(c, quote_id, payment_id=provider_id) except PaymentRefused as refusal: return f'refused: {refusal}' @@ -255,7 +266,16 @@ def apply(c, event): return f'refused: paid {event.amount_cents} but quote total is {expected}' order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site') - return f"order {order['number']}" + ('' if created else ' (already existed)') + if created: + return f"order {order['number']}" + # The order exists, paid by another payment (a PIX and a card for the same + # cart, or paid outside the site too): the customer paid twice. Listed on + # the Kanban until someone refunds one, like a reversal. + first = str((order.get('payment') or {}).get('payment_id') or '') + if provider_id and str(provider_id) != first: + audit('payment_duplicate', order=order['number'], payment=str(provider_id), c=c) + return f"attention: second payment {provider_id} for order {order['number']}; refund one" + return f"order {order['number']} (already existed)" def reconcile(connect, provider, quote_id=None, limit=20): @@ -273,7 +293,7 @@ def reconcile(connect, provider, quote_id=None, limit=20): WHERE o.id IS NULL AND i.provider=%s AND i.status IN ('pending','approved') AND i.created_at > now() - make_interval(hours => %s)''' + (' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %s', - (provider.name, QUOTE_VALID_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall() + (provider.name, CARD_REVIEW_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall() outcomes = [] for row in rows: # Asked outside any transaction: no lock is held while the provider answers. diff --git a/app/unpaid.py b/app/unpaid.py index ec0f653..9da33fe 100644 --- a/app/unpaid.py +++ b/app/unpaid.py @@ -13,7 +13,7 @@ abandonment rate. from datetime import datetime, timedelta, timezone from . import mail, payments -from .payments import QUOTE_VALID_HOURS +from .payments import CARD_REVIEW_HOURS, 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). @@ -34,11 +34,12 @@ def expire(c, origin): 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) + -- a card in review may be approved days later (payments.CARD_REVIEW_HOURS) + AND i.created_at > now() - make_interval(hours => CASE WHEN i.method='card' THEN %s ELSE %s END) 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() + (QUOTE_VALID_HOURS, list(FINAL_INTENT), CARD_REVIEW_HOURS, 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 diff --git a/tests/coupons_test.py b/tests/coupons_test.py index 4423d5f..026613f 100644 --- a/tests/coupons_test.py +++ b/tests/coupons_test.py @@ -33,6 +33,7 @@ def run(): manager = manager.operator_client coupon_id = None quote_id = None + early_id = None order_id = None upload_id = None try: @@ -61,6 +62,9 @@ def run(): assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved assert approved['total_cents'] == 16081, approved + # A second cart with the coupon, made while it still had uses. + early_id = quote(client, items, code, mail)['id'] + # One paid order spends a use (a fake payment, no print job). order_id = uuid4() with db.connect() as c: @@ -110,6 +114,10 @@ def run(): manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1}) refused = quote(client, items, code, mail, expected=422) assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused + # The limit is spent at payment: the cart made before it ran out no + # longer pays with its discount. + refused = client.call('/payments/intent', {'quote_id': early_id, 'method': {'type': 'pix'}}, expected=409) + assert 'máximo de vezes' in refused['detail'] and 'sem o cupom' in refused['detail'], refused manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': None, 'max_uses_per_customer': 1}) refused = quote(client, items, code, mail, expected=422) @@ -135,13 +143,16 @@ def run(): stats = manager.call('/operator/stats?days=30') assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons'] print('PASS: a coupon discounts one product, refuses paused/expired/not-started/' - 'minimum/product/use states, reaches Tiny data and Números, and soft delete keeps history') + 'minimum/product/use states, also at payment, reaches Tiny data and Números, and soft delete keeps history') finally: with db.connect() as c: if order_id: c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,)) if quote_id: c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,)) + if early_id: + c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (early_id,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (early_id,)) if coupon_id: c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,)) if upload_id: diff --git a/tests/payment_test.py b/tests/payment_test.py index a57e6a4..8dc5899 100644 --- a/tests/payment_test.py +++ b/tests/payment_test.py @@ -121,7 +121,12 @@ def run(): later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex}) assert 'already existed' in later.get('outcome', ''), later assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared' - print('PASS: one order from a repeated and re-sent approval') + # Another payment of the same cart (a PIX and a card): the customer paid + # twice, and it is listed for a refund, not taken for a re-sent approval. + second = deliver({**payload, 'event_id': 'second-' + uuid4().hex, 'payment_id': 'second-' + uuid4().hex[:8]}) + assert second.get('outcome', '').startswith('attention: second payment'), second + assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared' + print('PASS: one order from a repeated and re-sent approval; a second payment is listed for a refund') assert customer.call('/orders/dev-paid', {'quote_id': quote_id})['id'] == order['id'] other = Client() diff --git a/tests/reconcile_test.py b/tests/reconcile_test.py index 1acfacd..6935ed7 100644 --- a/tests/reconcile_test.py +++ b/tests/reconcile_test.py @@ -27,6 +27,7 @@ def run(): quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999) approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490} order_id = None + extra = [] try: with db.connect() as c: c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) @@ -55,7 +56,36 @@ def run(): asked = paid.asked assert payments.reconcile(db.connect, paid, quote_id=quote) == [] and paid.asked == asked print('PASS: an approved payment is found by asking the provider; a short one is refused; each applies once') + + # Approved after the quote's 24 h: a payment started in time (a PIX paid + # in its last minutes, a card approved after review) is the order; one + # started after the deadline is refused. + for started, expected in (("now()-interval '3 hours'", 'order '), ("now()-interval '1 hour'", 'refused: quote expired')): + late, late_payment = uuid4(), str(800_000_000 + uuid4().int % 99_999_999) + extra.append((late, late_payment)) + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) + VALUES(%s,%s,%s,'reconcile-fixture',%s,%s,now()-interval '26 hours')''', + (late, uuid4(), uuid4(), Jsonb({'customer': approved['customer'], 'items': []}), Jsonb(approved))) + c.execute(f'''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status, + amount_cents,response,created_at) VALUES(%s,%s,'mercadopago',%s,'card','pending',1490,'{{}}',{started})''', + (uuid4(), late, late_payment)) + provider = Provider({'id': late_payment, 'status': 'approved', 'currency_id': 'BRL', + 'transaction_amount': 14.9, 'external_reference': str(late)}) + outcomes = payments.reconcile(db.connect, provider, quote_id=late) + assert len(outcomes) == 1 and outcomes[0].startswith(expected), (started, outcomes) + print('PASS: a payment started within the 24 h is the order whenever approved; one started later is refused') finally: + for late, late_payment in extra: + with db.connect() as c: + for row in c.execute('SELECT id FROM dtf_local.orders WHERE quote_id=%s', (late,)).fetchall(): + c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f"{row['id']}:%",)) + c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (row['id'],)) + c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (row['id'],)) + c.execute("DELETE FROM dtf_local.payment_events WHERE provider='mercadopago' AND event_id LIKE %s", + (f'{late_payment}:%',)) + c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (late,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (late,)) with db.connect() as c: if order_id: c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',)) diff --git a/tests/unpaid_test.py b/tests/unpaid_test.py index c291793..3aeff3f 100644 --- a/tests/unpaid_test.py +++ b/tests/unpaid_test.py @@ -58,6 +58,21 @@ def run(): 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: diff --git a/web/kanban.js b/web/kanban.js index fe7f080..66a22d5 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -27,6 +27,8 @@ function outcomeText(outcome){ [/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'], [/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'], [/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]], + // The customer paid the same cart twice (a PIX and a card): one is refunded. + [/^attention: second payment (\S+) for order (\d+)/,m=>'segundo pagamento ('+m[1]+') do pedido #'+m[2]+': o cliente pagou duas vezes, estorne um no Mercado Pago'], ]; for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);} return outcome;