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>
315 lines
15 KiB
Python
315 lines
15 KiB
Python
"""Turning a payment into an order, once.
|
|
|
|
A provider may deliver the same notification several times, out of order, or
|
|
long after the fact. None of that may produce a second order, a second charge,
|
|
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 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
|
|
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from . import mail, proof
|
|
from .core.auth import audit
|
|
from .core.models import PRODUCTION_VERSIONS
|
|
from .printjobs import queue as queue_print_files
|
|
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, 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:
|
|
raise PaymentRefused('quote not found')
|
|
if not row['approved']:
|
|
raise PaymentRefused('quote was never reviewed')
|
|
if row.get('discarded_at'):
|
|
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')
|
|
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
|
|
|
|
|
|
TEST_PROVIDER = 'teste'
|
|
|
|
|
|
def is_test(order):
|
|
"""An operator's test order: it goes through production and notifies no one."""
|
|
return (order.get('payment') or {}).get('provider') == TEST_PROVIDER
|
|
|
|
|
|
# An order paid outside the system (Pix or cash at the counter, a card machine,
|
|
# the customer's credit) and registered by the team from its Site quote
|
|
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
|
MANUAL_PROVIDER = 'manual'
|
|
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
|
# A montador Venda order is invoiced, not paid at the counter: it is not one of
|
|
# the Cotações "registrar" methods. It goes to Tiny as an approved quote does.
|
|
INVOICED_METHOD = 'faturado'
|
|
# A montador Interno order: the marketplace's own sale, already invoiced there.
|
|
# It stays in house and never reaches Tiny (Marcus, 2026-11-10).
|
|
INTERNAL_METHOD = 'interno'
|
|
|
|
|
|
def in_tiny(order):
|
|
"""Whether the order goes to Tiny: every order but an internal one, a test
|
|
or a proof card (app/proof.py), which is no sale. A Dropflow order goes in
|
|
its own revenue category (app/tiny.py, CATEGORIES)."""
|
|
if (order.get('payment') or {}).get('method') == INTERNAL_METHOD:
|
|
return False
|
|
return not is_test(order) and not order.get('parent_id')
|
|
|
|
|
|
# What a stage tells Tiny: entering the queue (Arte conferida) is its
|
|
# "Preparando envio", Finalizado its "Pronto para envio" (Dropstar's flow,
|
|
# 2026-10-23); a correction has no situação and is only recorded.
|
|
STAGE_EVENTS = {'tra': 'production_started', 'cor': 'correction_needed', 'fin': 'ready'}
|
|
|
|
|
|
def stage_event(c, order, state, reason, version):
|
|
"""Queue Tiny's event for an order that entered `state` (not by a step
|
|
back), whoever moved it: a card dragged, or the Prova OK that puts the
|
|
order in the queue (app/proof.py). `order` is its row before the move,
|
|
`version` its version after."""
|
|
if state not in STAGE_EVENTS or not in_tiny(order):
|
|
return
|
|
# "Production started" and "ready" reach the customer once per order,
|
|
# even if a mistaken move is undone and made again. Each correction is a
|
|
# new request, so it keeps one message per movement.
|
|
once = state in ('tra', 'fin')
|
|
event = {'order_id': str(order['id']), 'number': order['number'], 'event': STAGE_EVENTS[state],
|
|
'reason': reason, 'customer_path': f"/portal.html?order={order['id']}"}
|
|
# Tiny needs the order (customer, pickup or delivery) and, once the sale
|
|
# reached it, its id, to set the situação without a search.
|
|
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
|
(f"{order['id']}:paid:tiny",)).fetchone()
|
|
tiny = {**event, 'order': order['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
|
|
key = f"{order['id']}:{STAGE_EVENTS[state]}:tiny" if once else f"{order['id']}:{version}:tiny"
|
|
enqueue(c, key, 'tiny', tiny)
|
|
|
|
|
|
# How long a file is kept while nothing has been paid for it. A cart's files
|
|
# are uploaded before payment, so the price and the security check are done on
|
|
# the file itself; a cart that is never paid must not keep them for 30 days.
|
|
UNPAID_HOLD = '2 days'
|
|
# A quote waiting for an operator's review keeps its files this long.
|
|
REVIEW_HOLD = '7 days'
|
|
# Once paid, the order keeps its originals for this long from the upload.
|
|
ORDER_RETENTION = '30 days'
|
|
|
|
|
|
def quote_uploads(quote_or_draft):
|
|
return [uid for item in quote_or_draft['items'] for uid in item['uploads']]
|
|
|
|
|
|
def hold_uploads(c, upload_ids, interval):
|
|
"""Keep these files at least `interval` from now; never shortens a hold."""
|
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, now()+%s::interval)
|
|
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
|
|
|
|
|
def release_files(c, uploads):
|
|
"""Expire these uploads now, except any another order or an open quote
|
|
still uses: a customer can buy the same file again. Returns how many."""
|
|
free = []
|
|
for upload in uploads:
|
|
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
|
|
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
|
|
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
|
|
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
|
|
WHERE i->'uploads' ? %s
|
|
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
|
|
WHERE q.discarded_at IS NULL AND q.expired_at IS NULL
|
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
|
|
AND i->'uploads' ? %s
|
|
LIMIT 1''', (upload,) * 5).fetchone()
|
|
if not used:
|
|
free.append(upload)
|
|
if free:
|
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
|
|
AND purged_at IS NULL''', (free,))
|
|
return len(free)
|
|
|
|
|
|
def create_order(c, quote, payment, origin):
|
|
"""Create the order for a reviewed quote, or return the one already there.
|
|
`origin` is where it came from (D-21): each way in names its own.
|
|
|
|
Returns (order, created). The caller decides what to do about a duplicate;
|
|
the important part is that asking twice cannot produce two orders, because
|
|
orders.quote_id is unique and this runs inside the caller's transaction.
|
|
"""
|
|
existing = c.execute('SELECT * FROM dtf_local.orders WHERE quote_id=%s', (quote['id'],)).fetchone()
|
|
if existing:
|
|
return existing, False
|
|
|
|
approved = quote['approved']
|
|
for item in approved['items']:
|
|
for upload_id in item['uploads']:
|
|
require_clean(upload_row(c, UUID(upload_id), quote['owner']))
|
|
|
|
order = c.execute(
|
|
'''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
|
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
|
|
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment), origin)).fetchone()
|
|
# Paid: the files are kept for the order's retention, counted from upload.
|
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)
|
|
WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
|
|
queue_print_files(c, order['id'], len(approved['items']))
|
|
if approved.get('proof'):
|
|
# The customer asked for a proof: the order waits for their word.
|
|
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
|
|
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
|
|
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
|
# An order with a proof gets its proof card (app/proof.py).
|
|
proof.create_child(c, order)
|
|
if is_test(order):
|
|
return order, True
|
|
# An invoiced or internal montador order was not paid here: no "pedido
|
|
# pago" e-mail for either (front 7a.3).
|
|
if payment.get('method') not in (INVOICED_METHOD, INTERNAL_METHOD):
|
|
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
|
if not in_tiny(order):
|
|
return order, True
|
|
# How it was paid, for the order's payment in Tiny.
|
|
if payment.get('provider') == MANUAL_PROVIDER:
|
|
paid = {'method': payment['method'], 'outside': True}
|
|
else:
|
|
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
|
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
|
|
enqueue(c, f"{order['id']}:paid:tiny", 'tiny',
|
|
{'order_id': str(order['id']), 'number': order['number'],
|
|
'event': 'payment_approved', 'order': approved, 'origin': origin,
|
|
'payment': dict(paid) if paid else {}})
|
|
return order, True
|
|
|
|
|
|
def record(c, provider, event):
|
|
"""Store a delivery. Returns None if this exact event was already seen."""
|
|
inserted = c.execute(
|
|
'''INSERT INTO dtf_local.payment_events(id,provider,event_id,reference,status,amount_cents,payload)
|
|
VALUES(%s,%s,%s,%s,%s,%s,%s) ON CONFLICT(provider,event_id) DO NOTHING RETURNING *''',
|
|
(uuid4(), provider, event.event_id, event.reference, event.status,
|
|
event.amount_cents, Jsonb(event.raw))).fetchone()
|
|
return inserted
|
|
|
|
|
|
def apply(c, event):
|
|
"""Act on a payment notification. Returns the outcome recorded against it.
|
|
|
|
Outcomes starting 'refused' (money arrived, no order) or 'attention' (an
|
|
order exists but its payment was reversed) stay on the Kanban until an
|
|
operator records a resolution.
|
|
"""
|
|
provider_id = event.raw.get('payment_id')
|
|
if provider_id:
|
|
c.execute('''UPDATE dtf_local.payment_intents SET status=%s, updated_at=now()
|
|
WHERE provider_payment_id=%s''', (event.status, provider_id))
|
|
if event.status in ('refunded', 'cancelled'):
|
|
try:
|
|
order = c.execute('SELECT number FROM dtf_local.orders WHERE quote_id=%s',
|
|
(UUID(event.reference),)).fetchone()
|
|
except (ValueError, AttributeError):
|
|
order = None
|
|
if order:
|
|
audit('payment_reversed', order=order['number'], status=event.status, c=c)
|
|
return f"attention: payment {event.status} for order {order['number']}"
|
|
if event.status != 'approved':
|
|
return f'ignored: {event.status}'
|
|
|
|
try:
|
|
quote_id = UUID(event.reference)
|
|
except (ValueError, AttributeError):
|
|
return 'refused: reference is not a quote id'
|
|
|
|
try:
|
|
quote = approved_quote(c, quote_id, payment_id=provider_id)
|
|
except PaymentRefused as refusal:
|
|
return f'refused: {refusal}'
|
|
|
|
# The provider is the authority on what was paid, and the reviewed quote is
|
|
# the authority on what was owed. If they disagree, no order is created:
|
|
# underpayment would ship artwork that was not paid for, and overpayment
|
|
# means something is wrong that a person should look at.
|
|
expected = quote['approved']['total_cents']
|
|
if type(event.amount_cents) is not int or event.amount_cents != expected:
|
|
audit('payment_amount_mismatch', quote=str(quote_id),
|
|
expected_cents=expected, paid_cents=event.amount_cents, c=c)
|
|
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')
|
|
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):
|
|
"""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, 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.
|
|
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
|