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
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
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
- 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>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user