Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
The price came from the layout the browser sent, checked only in part: - Pieces on top of each other passed: 100 copies stacked in one place bill 10 cm and print over each other. The layout validator now refuses any overlap. - A file laid out at proportions it does not have (a 5 m sheet sent as 10 cm) was found only by the print file, after payment. The quote now checks each raster file's proportions from the bytes it already reads. - The empty strips the Site cuts from a ready sheet were cut on its word. The print file now reads them: a strip with ink sends the item to hand preparation with the reason, instead of printing the art cut off. Test fixtures that laid real images out at impossible proportions now keep the image's own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
116 lines
6.0 KiB
Python
116 lines
6.0 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 cart_pricing, payments
|
|
from ..core import db
|
|
from ..core.auth import owner
|
|
from ..core.models import QuoteRequest
|
|
from .. import quote_review
|
|
from ..grade_check import Files, mismatch, proportion_issue, 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:
|
|
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
|
|
names = {uid: row['name'] for uid, row in rows.items()}
|
|
# One pricing module for the pre-check and the approval (plan 003). It
|
|
# also applies the grade rules and the coupon, as before.
|
|
try:
|
|
cart = cart_pricing.price_cart(
|
|
c, draft['items'], names, coupon_code=code,
|
|
customer_document=body.customer.cnpj,
|
|
wants_treatment=draft.get('treatment', False),
|
|
wants_redesign=draft.get('redesign', []))
|
|
if reason is not None:
|
|
freight.quote(body.freight.service, body.freight.postal_code,
|
|
sum(Decimal(i['billed_metres']) for i in cart['items']),
|
|
cart['items_total'])
|
|
except ValueError as exc:
|
|
raise HTTPException(422, str(exc))
|
|
# 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 = proportion_issue(files, draft['items'], rows) or 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
|