refactor: app/api/operator.py split by area into a package

A pure move: the 48 Kanban routes, their code and comments are unchanged,
grouped in session, board, quotes, orders, rework, integrations, stats
and files, with shared helpers in common. The fast CI check now compiles
the package's files too (app/**/*.py does not reach a third level without
globstar).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 17:11:19 -03:00
parent a6e4d4cb08
commit f5df5b96e4
12 changed files with 2051 additions and 1921 deletions

View File

@@ -0,0 +1,198 @@
"""Integrations: freight, backup, payment events, Tiny and Mercado Pago."""
import os
from datetime import datetime, timezone
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import RedirectResponse
from ... import tiny
from ...core import db
from ...core.auth import audit, can
from ...core.models import Resolution
from ...runtime import freight, payment
from .common import thumbnails
router = APIRouter()
def freight_status():
"""What delivery the Site offers, and the package rule it prices with."""
real = [carrier for carrier in freight.carriers if carrier.name != 'fake']
status = {'carriers': [carrier.name for carrier in real], 'services': freight.services if real else {}}
if real:
# One package for every carrier (app/package.py).
status.update(real[0].status())
return status
def backup_status(c):
"""The latest database backup and the latest run, which may have failed."""
ok = c.execute('''SELECT finished_at,bytes FROM dtf_local.backups WHERE status='ok'
ORDER BY finished_at DESC LIMIT 1''').fetchone()
last = c.execute('SELECT started_at,finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').fetchone()
asked = c.execute('''SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1''',
(last['started_at'] if last else datetime(2000, 1, 1, tzinfo=timezone.utc),)).fetchone()
return {'last_ok': ok['finished_at'].isoformat() if ok else None, 'bytes': ok['bytes'] if ok else None,
'failed': last['detail'] if last and last['status'] == 'failed' else None,
'failed_at': last['finished_at'].isoformat() if last and last['status'] == 'failed' else None,
'requested': asked is not None}
@router.post('/api/operator/backup/run')
def backup_now(user=Depends(can('integrations'))):
"""A backup now, outside the daily hour: the backup service, which alone
may read the whole database, starts it within a minute."""
with db.connect() as c:
c.execute('INSERT INTO dtf_local.backup_requests(requested_by) VALUES(%s)', (user,))
audit('backup_requested', operator=user)
return {'ok': True}
@router.get('/api/operator/payment-events')
def payment_events(state: Literal['open','resolved','all'] = 'open',
offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('payments'))):
"""Payments that needed a person, newest first: open ones to act on, resolved ones as history."""
where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state]
with db.connect() as c:
rows = c.execute('''SELECT id,provider,event_id,reference,status,amount_cents,received_at,outcome,
resolved_at,resolved_by,resolution
FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') ''' + where + '''
ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall()
total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n']
for row in rows:
row.update(payment_context(c, row))
return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])}
def payment_context(c, row):
"""Who tried to pay and for what: the quote the payment points to (its
customer, items and total), its order if there is one, the method of the
last attempt and Mercado Pago's own words about the payment."""
payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {}
out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None}
try:
quote_id = UUID(str(row.get('reference') or ''))
except ValueError:
return out
quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
if not quote:
return out
out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'],
'total_cents': (quote['approved'] or {}).get('total_cents')}
out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone()
attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s
ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone()
out['method'] = attempt['method'] if attempt else None
return out
@router.get('/api/operator/events')
def events(provider: Literal['tiny'] | None = None,
status: Literal['delivered','queued','failing'] | None = None,
event: Literal['payment_approved','production_started','correction_needed','ready','cancelled'] | None = None,
order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('integrations'))):
"""The integration send log, newest first, filtered, by page with a total."""
clauses, params = [], []
if provider:
clauses.append('provider=%s'); params.append(provider)
if status == 'delivered':
clauses.append('delivered_at IS NOT NULL')
elif status == 'queued':
clauses.append('delivered_at IS NULL AND last_error IS NULL')
elif status == 'failing':
clauses.append('delivered_at IS NULL AND last_error IS NOT NULL')
if event:
clauses.append("payload->>'event'=%s"); params.append(event)
if order:
clauses.append("payload->>'number'=%s"); params.append(str(order))
where = ('WHERE ' + ' AND '.join(clauses)) if clauses else ''
with db.connect() as c:
rows = c.execute(f'SELECT * FROM dtf_local.outbox {where} ORDER BY id DESC LIMIT %s OFFSET %s',
(*params, limit, offset)).fetchall()
total = c.execute(f'SELECT count(*) AS n FROM dtf_local.outbox {where}', params).fetchone()['n']
return {'events': rows, 'total': total}
@router.post('/api/operator/payment-events/{uid}/resolve')
def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s
WHERE id=%s AND (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') AND resolved_at IS NULL RETURNING id''',
(user, body.note, uid)).fetchone()
if not row:
raise HTTPException(404, 'No open payment issue with this id')
audit('payment_issue_resolved', payment_event=str(uid), operator=user)
return {'ok': True}
def tiny_status():
if not tiny.configured():
return {'configured': False}
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
**tiny.TinyAuth().status()}
@router.post('/api/operator/tiny/connect')
def tiny_connect(user=Depends(can('integrations'))):
"""Start the one-time authorisation of this system in the client's Tiny."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
audit('tiny_connect_started', operator=user)
return {'url': tiny.TinyAuth().authorize_url(user)}
@router.post('/api/operator/tiny/test')
def tiny_test(user=Depends(can('integrations'))):
"""Read one order and one contact from Tiny. Creates nothing."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
try:
results = tiny.check()
except tiny.TinyNotConnected as exc:
raise HTTPException(409, str(exc))
audit('tiny_tested', operator=user, ok=all(v == 'ok' for v in results.values()))
return {'ok': all(v == 'ok' for v in results.values()), 'results': results}
@router.post('/api/operator/mercadopago/check')
def mercadopago_check(user=Depends(can('integrations'))):
"""The Mercado Pago account behind the configured token; reads only."""
if payment.name != 'mercadopago':
raise HTTPException(409, 'Mercado Pago não está configurado')
from ..mercadopago_probe import check
audit('mercadopago_check', operator=user)
result = check(payment.access_token)
# Whether Mercado Pago's notifications reach this server and pass the
# signature: every accepted one is recorded, a refused one is audited.
with db.connect() as c:
received = c.execute('''SELECT count(*) AS n, max(received_at) AS last FROM dtf_local.payment_events
WHERE provider='mercadopago' AND received_at > now()-interval '24 hours' ''').fetchone()
last = c.execute('''SELECT received_at,status,outcome FROM dtf_local.payment_events
WHERE provider='mercadopago' ORDER BY received_at DESC LIMIT 1''').fetchone()
refused = c.execute('''SELECT count(*) AS n FROM dtf_local.security_events
WHERE event='payment_webhook_rejected' AND created_at > now()-interval '24 hours' ''').fetchone()
result['webhooks'] = {'accepted_24h': received['n'], 'refused_24h': refused['n'], 'last': last}
return result
@router.get('/api/operator/tiny/callback')
def tiny_callback(code: str = Query('', max_length=4096), state: str = Query('', max_length=128),
error: str = Query('', max_length=128)):
"""Tiny's redirect back. Cross-site, so the operator cookie is absent: the
single-use state an operator created is what authorises it. Tiny reports a
refusal (the operator declined, or offline access is not allowed for this
application) with `error` instead of a code."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
try:
if error == 'invalid_scope':
retry = tiny.TinyAuth().without_offline(state)
audit('tiny_offline_refused')
return RedirectResponse(retry, status_code=303)
if error or not code:
raise tiny.TinyError(f'Tiny returned {error or "no code"}')
who = tiny.TinyAuth().complete(code, state)
except tiny.TinyError:
audit('tiny_connect_failed')
return RedirectResponse('/?tiny=failed', status_code=303)
audit('tiny_connected', operator=who)
return RedirectResponse('/?tiny=connected', status_code=303)