Files
dtf-system/app/api/quotes.py
Cauê Faleiros b10eeead6e
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 4m41s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s
feat: Prumo tells the card and the customer what it did (front 6)
Every order now carries a short report of the decisions that happened:
original format, conversion, resolution, background, residue, montage,
billed length, contraction, thin-stroke warning, parts and generation time.
The card shows it above the file; the payment summary shows the customer's
version. The upload keeps the original name so a renamed CDR/PDF is told.
2026-11-06 12:37:08 -03:00

106 lines
5.4 KiB
Python

"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
import hashlib
import json
from datetime import datetime, timezone
from decimal import Decimal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from ..core.pricing import price
from .. import quote_review
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
router = APIRouter()
@router.post('/api/quotes')
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
for item in body.items:
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
require_delivery_available(body.freight.service)
draft = body.model_dump(mode='json', exclude={'request_key'})
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
accepted_at = datetime.now(timezone.utc).isoformat()
for item in draft['items']:
if item.get('residue_accepted'):
item['residue_accepted_at'] = accepted_at
if item.get('stroke_choice'):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
if reason is not None:
# Waits for review: check the delivery now, priced at approval.
try:
priced = [price(item.mode, str(item.metres), item.grade) for item in body.items]
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
with db.connect() as c:
rows = {}
for item in body.items:
for uid in item.uploads:
row = upload_row(c, uid, session_id)
if not row['complete']:
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
# No transparency: the background prints, and loose art packs as a box (2026-10-23).
if row['name'].lower().endswith(('.jpg', '.jpeg')):
raise HTTPException(422, 'JPG não tem fundo transparente. Envie a arte em PNG ou PDF.')
require_clean(row)
rows[str(uid)] = row
# The grade came from the browser and is shown with the order (it no
# longer sets the price): before a cart is approved at checkout, the
# server works it out from the files.
files = Files(storage)
# Record the lowest source resolution for the Prumo report (front 6).
for draft_item, item in zip(draft['items'], body.items):
dpis = []
for source in item.production.sources:
row = rows.get(str(source.upload_id))
dpi = source_dpi(files, row, source.model_dump(mode='json')) if row else None
if dpi:
dpis.append(dpi)
if dpis:
draft_item['source_dpi'] = round(min(dpis))
issue = resolution_issue(files, draft['items'], rows)
if issue:
raise HTTPException(422, issue)
note = mismatch(files, draft['items'], rows) if reason is None else None
reason = reason or note
uid = uuid4()
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
(uid, session_id, body.request_key, digest, Jsonb(draft), note))
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE', (session_id, body.request_key)).fetchone()
if row['request_hash'] != digest:
raise HTTPException(409, 'O carrinho mudou durante o envio. Tente de novo.')
if row['id'] == uid and reason is None:
quote_review.approve(c, row, body.items, quote_review.AUTO)
return {'id': row['id'], 'status': 'approved'}
if row['id'] == uid:
# An operator reviews it first; the files wait for that review.
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD)
return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
@router.get('/api/quotes/{uid}')
def get_quote(uid: UUID, session_id=Depends(owner)):
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
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