"""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 catalog, coupons, payments from ..core import db from ..core.auth import owner from ..core.models import QuoteRequest from ..core.pricing import apply_bands, bill_splits, 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) # The coupon code is stored normalized, so a quote waiting for review keeps # the code the operator will see (front 8.3). code = (body.coupon or '').strip().upper() or None draft = body.model_dump(mode='json', exclude={'request_key'}) draft['coupon'] = code 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) with db.connect() as c: if reason is not None or code: # Waits for review: check the delivery now, priced at approval. A # coupon is checked on the same priced items (front 8.3). try: priced = [] for item in body.items: catalog.require_enabled(c, item.mode) priced.append({**price(item.mode, str(item.metres), item.grade, minimum=Decimal('0') if item.split else Decimal('1'), unit_cents=catalog.unit_cents(c, item.mode)), **({'split': item.split.model_dump()} if item.split else {})}) bill_splits(priced) # Progressive bands (front 8.2), by the order's total per mode. totals = {} for item in priced: totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres']) banded = {} for mode, total in totals.items(): price_for_total = catalog.unit_cents_for(c, mode, total) if price_for_total != catalog.unit_cents(c, mode): banded[mode] = price_for_total apply_bands(priced, banded) if reason is not None: 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)) if code: coupons.check(c, code, body.customer.cnpj, priced) 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