refactor: one pricing module for the Site's check and the approval

app/cart_pricing.py prices a cart once for every caller: the catalog read
once, a pure price_items (base price, manual extra, splits, bands) pinned
against today's arithmetic by a 16-cart characterization test, then the
grade rules, the coupon and the treatment. create_quote and approve call
it instead of their two drifting copies; the Site's pre-check now counts
the manual-file extra like the approval does.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 17:12:49 -03:00
parent a6e4d4cb08
commit 31b44a4fac
5 changed files with 278 additions and 94 deletions

View File

@@ -8,11 +8,10 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import catalog, coupons, grade_rules, payments
from .. import cart_pricing, 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
@@ -40,42 +39,6 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
with db.connect() as c:
# The art grade rules (front 8.5): the treatment may be required. With
# no rule this is empty and nothing below changes.
flags = grade_rules.triggered(grade_rules.current_rules(c), draft['items'],
catalog.treatment_offered(c))
if 'tratamento' in flags and not draft.get('treatment'):
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
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:
@@ -87,6 +50,20 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
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))
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.