feat: an approved payment becomes the order by asking Mercado Pago, not only by its notice
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m14s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 55s

Production approved a test card while every notification was refused by
signature, and the order never appeared. payments.reconcile() asks the
provider about the payments of open quotes and applies its answer through the
same path as the webhook: the amount must match the reviewed quote, and the
event id (payment id and status) makes a notice and a lookup one delivery,
applied once. The payment page's polling checks an approved card at once; the
worker checks every minute for the rest, such as a PIX paid after the page was
closed. The webhook stays; it is no longer the only way in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-02 15:58:40 -03:00
parent 0218f119aa
commit 7877489563
5 changed files with 135 additions and 5 deletions

View File

@@ -14,7 +14,7 @@ from ..core.models import QuoteRequest
from ..core.pricing import price
from .. import quote_review
from ..grade_check import Files, mismatch
from ..runtime import freight, quote_view, require_delivery_available, storage, upload_row
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
router = APIRouter()
@@ -69,4 +69,12 @@ def get_quote(uid: UUID, session_id=Depends(owner)):
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
if not row:
raise HTTPException(404, 'Quote not found')
return quote_view(c, row)
view = quote_view(c, row)
# The payment page asks every few seconds while it waits for the order. An
# approved card with no order yet is checked with the provider now, rather
# than waiting for its notification.
if view['status'] == 'approved' and (view['payment'] or {}).get('status') == 'approved':
if payments.reconcile(db.connect, payment, quote_id=uid, limit=3):
with db.connect() as c:
view = quote_view(c, c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (uid,)).fetchone())
return view

View File

@@ -6,9 +6,11 @@ or a second WhatsApp message. Every delivery is recorded under the provider's
own event id and applied inside one transaction, so a duplicate is a no-op and a
crash mid-way is retried rather than half-applied.
Order creation lives here rather than in a route because two paths reach it: the
webhook, and the local development checkout. They must agree.
Order creation lives here rather than in a route because the paths that reach
it must agree: the webhook, reconcile() (the provider asked directly) and the
local development checkout.
"""
import logging
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
@@ -156,3 +158,39 @@ def apply(c, event):
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw})
return f"order {order['number']}" + ('' if created else ' (already existed)')
def reconcile(connect, provider, quote_id=None, limit=20):
"""Ask the provider about the payments of quotes that have no order yet and
apply what it says, exactly as a notification would. A notification can be
refused, lost or late; the provider's API is the authority either way, and
the event id (payment id and status) makes a webhook and this the same
delivery, applied once. Returns the outcomes of what was new."""
if not hasattr(provider, 'lookup'):
return []
from .mercadopago import event_from_payment
with connect() as c:
rows = c.execute('''SELECT i.provider_payment_id FROM dtf_local.payment_intents i
LEFT JOIN dtf_local.orders o ON o.quote_id=i.quote_id
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()
outcomes = []
for row in rows:
# Asked outside any transaction: no lock is held while the provider answers.
try:
event = event_from_payment(provider.lookup(row['provider_payment_id']))
except Exception:
logging.exception('Payment reconciliation lookup failed')
continue
with connect() as c:
stored = record(c, provider.name, event)
if stored is None:
continue
outcome = apply(c, event)
c.execute('UPDATE dtf_local.payment_events SET processed_at=now(), outcome=%s WHERE id=%s',
(outcome, stored['id']))
audit('payment_reconciled', payment_event=event.event_id, status=event.status, outcome=outcome)
outcomes.append(outcome)
return outcomes

View File

@@ -21,6 +21,7 @@ if os.environ.get('TINY_ADAPTER') == 'tiny':
adapters['tiny'] = TinyOrders()
last_tick = 0.0
last_cleanup = 0.0
last_reconcile = 0.0
last_tiny_keepalive = 0.0
storage = LocalS3Storage()
scan_thread = None
@@ -75,6 +76,17 @@ def tiny_keepalive():
except Exception:
logging.exception('Tiny connection refresh failed')
def reconcile_payments():
"""Every minute: the payments of open quotes, asked of the provider, so an
approval becomes the order even when its notification never arrives."""
global last_reconcile
if time.monotonic()-last_reconcile < 60:
return
last_reconcile = time.monotonic()
from . import payments
from .runtime import payment
payments.reconcile(connect, payment)
def loop():
global last_cleanup
while True:
@@ -84,6 +96,7 @@ def loop():
cleanup()
last_cleanup = time.monotonic()
tiny_keepalive()
reconcile_payments()
except Exception:
logging.exception('Local worker tick failed')
time.sleep(1)