All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s
Marcus, 2026-11-17: - Each machine has its own places (machines.places, 1 to 6, three to start): orders at once in Imprimindo and files at once in its hot folder. Admin sets it in the machine dialog; Admin and Gestão in the machine sheet's Dados da máquina. A third order shows as "Na vez". - Whoever is signed in on a machine drops a card anywhere in Imprimindo and it goes to that machine; without one, the lane under the pointer. - Each Kanban user may name their Tiny seller (Usuários, read from Tiny's own list); a montador Venda reaches Tiny with the seller of who assembled it. Every other order still sends no seller. - A folder download that never reached storage (a network drop) waits for the next pass as a warning and is reported only if it keeps failing (Sentry DTF-WEB-V). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
234 lines
12 KiB
Python
234 lines
12 KiB
Python
"""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(c=None):
|
|
if not tiny.configured():
|
|
return {'configured': False}
|
|
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
|
|
**tiny.TinyAuth().status(c)}
|
|
|
|
@router.get('/api/operator/tiny/contacts')
|
|
def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can('assemble'))):
|
|
"""The Tiny contacts a Venda customer is picked from (Fase 2, front
|
|
7a.3): by name, or by CPF/CNPJ when only digits were typed. The fake
|
|
adapter answers with two fixed contacts on the local stack and in CI."""
|
|
if os.environ.get('TINY_ADAPTER') != 'tiny':
|
|
from ...adapters import FakeTiny
|
|
return FakeTiny().search_contacts(q)
|
|
if not tiny.configured():
|
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
|
try:
|
|
return tiny.search_contacts(tiny.TinyOrders(), q)
|
|
except tiny.TinyNotConnected:
|
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
|
|
|
|
|
@router.get('/api/operator/tiny/sellers')
|
|
def tiny_sellers(user=Depends(can('users'))):
|
|
"""Tiny's sellers, for the "Vendedor no Tiny" of each Kanban user: a
|
|
Venda they assemble reaches Tiny with that seller (Marcus, 2026-11-17)."""
|
|
if os.environ.get('TINY_ADAPTER') != 'tiny':
|
|
from ...adapters import FakeTiny
|
|
return FakeTiny().list_sellers()
|
|
if not tiny.configured():
|
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
|
try:
|
|
return tiny.list_sellers(tiny.TinyOrders())
|
|
except tiny.TinyNotConnected:
|
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
|
except tiny.TinyError as exc:
|
|
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
|
|
raise HTTPException(409, 'O aplicativo do Tiny não tem permissão para ler os vendedores (Contatos, leitura).')
|
|
raise
|
|
|
|
|
|
@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)
|