Files
dtf-system/app/runtime.py
Cauê Faleiros 38f947d632 feat: Ajuste Fino Redesenho in the cart (Marcus 12/11, slice R1)
Under each art the Prumo warns about, the customer can choose Ajuste Fino
or Ajuste Fino Redesenho (vectorize or redraw, per art, +48 h, no batch
price). It is a disabled product until Gestão prices it in the Site tab;
the server charges it per chosen art, Tiny gets a DTFIMP.AJF.RED line and
two more business days, the card shows 'Redesenho · N artes' and the
designer gate applies. The preview loop is slice R2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 11:05:17 -03:00

187 lines
9.9 KiB
Python

"""Composition root, and the pieces every router needs.
app.py held the adapters, the configuration, the shared query helpers and all
nineteen of its routes, so customer.py could not import from it without a cycle
and was wired instead by passing nine callables into install_routes. Everything
shared lives here: routers import downwards, never from each other.
"""
import os
from datetime import datetime, timedelta, timezone
from uuid import uuid5, NAMESPACE_URL
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
from .freight import FreightOptions
from .core.secrets import load as load_secret_files
# Secret files must resolve before any configuration below is read.
load_secret_files()
require_runtime()
storage = LocalS3Storage()
if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
from .mercadopago import MercadoPagoPayment
payment = MercadoPagoPayment()
else:
payment = FakePayment()
# Every carrier configured; the simulated one only where there is none.
_carriers = []
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
from .jadlog import JadlogFreight
_carriers.append(JadlogFreight())
from . import correios as _correios
from . import prumo
if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost')
ALLOWED_HOSTS = [host for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host]
ALLOWED_ORIGINS = [origin for origin in os.environ.get('ALLOWED_ORIGINS', PUBLIC_ORIGIN).split(',') if origin]
# Per source and generous: a browser needs one session and keeps the cookie, but
# offices and mobile carriers put many real customers behind one address, so a
# tight per-IP ceiling would lock out the same people the old global one did.
GUEST_SESSION_LIMIT = int(os.environ.get('GUEST_SESSION_LIMIT', '240'))
# The board returned every order ever created. Finished ones are terminal, so
# they were pure growth: at a few hundred a day the response and the page both
# degrade with no operator benefit.
BOARD_FINISHED_LIMIT = int(os.environ.get('BOARD_FINISHED_LIMIT', '50'))
BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
if not 5242880 <= PART_BYTES <= 67108864:
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
# Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
# impressão, 'fil', left the board), and Revisão checks the printed sheet
# before Finalizado. After a correction the new art goes back through Arte
# recebida or Arte conferida; Gestão may also take it straight to Revisão.
# Who may make each move is app/core/auth.py's MOVES.
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'imp': 'Imprimindo',
'cor': 'Correção', 'rev': 'Revisão', 'fin': 'Finalizado'}
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['imp','cor'], 'imp': ['rev','cor'],
'rev': ['fin','cor'], 'cor': ['rec','tra','rev'], 'fin': []}
# Undoing a move made by mistake: one stage back, with an internal reason. It
# is not a correction: the customer is not told and approved finals stay.
BACK = {'tra': 'rec', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'}
def real_delivery():
"""Whether a real carrier is configured; a simulated price is local only."""
return any(carrier.name != 'fake' for carrier in freight.carriers)
def delivery_services():
"""The delivery options the cart may offer: none outside the local stack
without a real carrier, so a customer sees only pickup."""
if ENVIRONMENT != 'local' and not real_delivery():
return []
return [{'service': service, 'description': label} for service, label in freight.services.items()]
def require_delivery_available(service):
"""Outside the local stack, a simulated freight price must never reach a
customer: until a real freight provider exists, only pickup is offered."""
if service != 'pickup' and ENVIRONMENT != 'local' and not real_delivery():
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
def upload_row(c, upload_id, session_id, lock=False):
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND owner=%s' +
(' FOR UPDATE' if lock else ''), (upload_id, session_id)).fetchone()
if not row:
raise HTTPException(404, 'Arquivo não encontrado. Escolha o arquivo de novo.')
days = 30 if row['complete'] else 1
if row['purged_at'] or row['expires_at'] <= datetime.now(timezone.utc) or row['created_at'] < datetime.now(timezone.utc) - timedelta(days=days):
raise HTTPException(410, 'Este arquivo expirou. Escolha o arquivo de novo.')
return row
def order_code(order_id):
"""What a customer calls an order: the first 8 characters of its id, in
capitals ("F6B9CDBC"). It is stable and says nothing about how many orders
the store has, unlike the sequential number the operators work with."""
return str(order_id).replace('-', '')[:8].upper()
def quote_views(c, rows):
"""quote_view for a list of quotes, in two queries whatever its length: the
board shows up to 240 quotes, and asking per quote made 480 queries."""
ids = [row['id'] for row in rows]
if not ids:
return []
orders = {r['quote_id']: {k: r[k] for k in ('id', 'number', 'state')} for r in c.execute(
'SELECT quote_id,id,number,state FROM dtf_local.orders WHERE quote_id=ANY(%s)', (ids,)).fetchall()}
attempts = {r['quote_id']: {k: r[k] for k in ('method', 'status', 'status_detail', 'expires_at', 'created_at')}
for r in c.execute('''SELECT DISTINCT ON (quote_id) quote_id,method,status,
response->>'status_detail' AS status_detail, response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=ANY(%s) ORDER BY quote_id, created_at DESC''', (ids,)).fetchall()}
return [quote_view(c, row, order=orders.get(row['id']), attempt=attempts.get(row['id']), known=True) for row in rows]
def quote_view(c, row, order=None, attempt=None, known=False):
from .quote_review import review_reason # it imports this module
from .payments import QUOTE_VALID_HOURS # it imports this module too
if not known:
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
# The latest payment attempt, so the payment page can tell a refused card
# (the notification updates it) from one still waiting.
# Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
if attempt and attempt['status'] == 'rejected':
from .payment_messages import rejection
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
expires_at = (row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
if row['approved_at'] else None)
expired = (bool(row.get('expired_at')) or
bool(row['approved_at'] and row['approved_at'] <
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
items = (row['approved'] or row['draft']).get('items') or []
treatment = (row['approved'] or {}).get('treatment')
if not treatment and (row['draft'] or {}).get('treatment'):
from .cart_pricing import treatment_price
treatment = treatment_price(items, (row['draft'] or {}).get('treatment'),
catalog.current(c)['tratamento']) or None
redesign = (row['approved'] or {}).get('redesign')
if not redesign and (row['draft'] or {}).get('redesign'):
from .cart_pricing import redesign_price
redesign = redesign_price(items, (row['draft'] or {}).get('redesign'),
catalog.current(c)['redesenho']) or None
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'expires_at': expires_at.isoformat() if expires_at else None,
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
'prumo': prumo.customer_summary(items), 'treatment': treatment,
'redesign': redesign,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',
'review_reason': None if row['approved'] else (row.get('review_note') or review_reason(row['draft'])),
'payment': attempt,
'order': order}
def enqueue(c, event_key, provider, payload):
c.execute('INSERT INTO dtf_local.outbox(event_key,provider,payload) VALUES(%s,%s,%s) ON CONFLICT(event_key) DO NOTHING',
(event_key, provider, Jsonb(payload)))
def owned_order(c, oid, identity, lock=False):
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s AND owner=%s'+(' FOR UPDATE' if lock else ''), (oid,identity)).fetchone()
if not row: raise HTTPException(404, 'Pedido não encontrado.')
return row
def file_rows(c, oid):
return c.execute('''SELECT f.id,f.upload_id,f.item_index,f.kind,f.active,f.note,f.created_at,
u.name,u.size,u.expires_at,(u.expires_at<=now()) AS expired
FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE order_id=%s ORDER BY f.created_at''', (oid,)).fetchall()
def operator_identity(user):
return uuid5(NAMESPACE_URL, 'dtf-local-operator:'+user)