Files
dtf-system/app/api/quotes.py
Cauê Faleiros 0fc01315c7 feat: the site's third-round corrections on acceptance, DPI and the final file
Residue and thin strokes can be accepted on ready sheets and loose art,
with the consent and its time kept on the order. The resolution rule is
96/200 DPI, and a final file must be a transparent 300 DPI PNG. The art
score leaves the customer's cart and buy box (Dropstar, 2026-11-05).
2026-11-06 10:41:14 -03:00

96 lines
4.9 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
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)
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