diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 6b80f86..d793e66 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test print_file_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test print_file_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/quotes.py b/app/api/quotes.py index dbfb6fe..d228a7b 100644 --- a/app/api/quotes.py +++ b/app/api/quotes.py @@ -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 diff --git a/app/payments.py b/app/payments.py index 43418d6..7155730 100644 --- a/app/payments.py +++ b/app/payments.py @@ -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 diff --git a/app/worker.py b/app/worker.py index a0a2109..1c5e917 100644 --- a/app/worker.py +++ b/app/worker.py @@ -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) diff --git a/tests/reconcile_test.py b/tests/reconcile_test.py new file mode 100644 index 0000000..1acfacd --- /dev/null +++ b/tests/reconcile_test.py @@ -0,0 +1,71 @@ +"""An approved payment becomes the order even when its notification never arrives. + +Run inside the API container: python -m tests.reconcile_test +""" +from uuid import uuid4 + +from psycopg.types.json import Jsonb + +from app import payments +from app.core import db + + +class Provider: + """Answers lookups as Mercado Pago would; counts them.""" + name = 'mercadopago' + + def __init__(self, payment): + self.payment, self.asked = payment, 0 + + def lookup(self, payment_id): + self.asked += 1 + assert payment_id == str(self.payment['id']) + return self.payment + + +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 + try: + 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())''', + (quote, uuid4(), uuid4(), Jsonb({'customer': approved['customer'], 'items': []}), Jsonb(approved))) + c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,amount_cents,response) + VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,'{}')''', (uuid4(), quote, payment_id)) + + # Paid less than owed: no order, and nothing applied twice. + short = Provider({'id': payment_id, 'status': 'approved', 'currency_id': 'BRL', + 'transaction_amount': 14.0, 'external_reference': str(quote)}) + assert payments.reconcile(db.connect, short, quote_id=quote) == ['refused: paid 1400 but quote total is 1490'] + assert payments.reconcile(db.connect, short, quote_id=quote) == [] + + # The provider is asked; its approval of the right amount is the order. + with db.connect() as c: + c.execute("DELETE FROM dtf_local.payment_events WHERE provider='mercadopago' AND event_id=%s", + (f'{payment_id}:approved',)) + paid = Provider({'id': payment_id, 'status': 'approved', 'currency_id': 'BRL', + 'transaction_amount': 14.9, 'external_reference': str(quote)}) + outcomes = payments.reconcile(db.connect, paid, quote_id=quote) + assert len(outcomes) == 1 and outcomes[0].startswith('order '), outcomes + with db.connect() as c: + order_id = c.execute('SELECT id FROM dtf_local.orders WHERE quote_id=%s', (quote,)).fetchone()['id'] + # With the order made, the quote is no longer asked about. + 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') + finally: + with db.connect() as c: + if order_id: + c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',)) + c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (order_id,)) + c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,)) + c.execute("DELETE FROM dtf_local.payment_events WHERE provider='mercadopago' AND event_id LIKE %s", + (f'{payment_id}:%',)) + c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (quote,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,)) + + +if __name__ == '__main__': + run()