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:
@@ -19,10 +19,9 @@ from decimal import Decimal
|
||||
from fastapi import HTTPException
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from . import catalog, coupons, grade_rules, payments
|
||||
from . import cart_pricing, payments
|
||||
from .proof import PROOF_ABOVE_METRES
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
from .core.pricing import apply_bands, bill_splits, is_manual, manual_extra_cents, price
|
||||
from .runtime import freight, upload_row
|
||||
from .scanning import require_clean
|
||||
|
||||
@@ -60,76 +59,53 @@ def approve(c, row, items, reviewer):
|
||||
raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
|
||||
if len(items) != len(draft['items']):
|
||||
raise HTTPException(422, 'Confira todos os itens da cotação.')
|
||||
priced = []
|
||||
names = {}
|
||||
for item, original in zip(items, draft['items']):
|
||||
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
|
||||
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
|
||||
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
|
||||
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
|
||||
names = {}
|
||||
for upload_id in item.uploads:
|
||||
upload = upload_row(c, upload_id, row['owner'])
|
||||
require_clean(upload)
|
||||
names[str(upload_id)] = upload['name']
|
||||
catalog.require_enabled(c, item.mode)
|
||||
extra = manual_extra_cents() if is_manual(original, names) else 0
|
||||
priced.append({**price(item.mode, str(item.metres), item.grade, extra,
|
||||
minimum=Decimal('0') if item.split else Decimal('1'),
|
||||
unit_cents=catalog.unit_cents(c, item.mode)),
|
||||
'uploads': original['uploads'], 'production': original['production'],
|
||||
'quality_status': original['quality_status'],
|
||||
'quality_acknowledged': original['quality_acknowledged'],
|
||||
'residue_accepted': original.get('residue_accepted', 0),
|
||||
**({'residue_accepted_at': original['residue_accepted_at']}
|
||||
if original.get('residue_accepted_at') else {}),
|
||||
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
|
||||
if original.get('stroke_class') else {}),
|
||||
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
|
||||
**({'stroke_choice_at': original['stroke_choice_at']}
|
||||
if original.get('stroke_choice_at') else {}),
|
||||
**({'proof_y_fraction': original['proof_y_fraction']}
|
||||
if original.get('proof_y_fraction') is not None else {}),
|
||||
**({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}),
|
||||
**({'split': original['split']} if original.get('split') else {})})
|
||||
bill_splits(priced)
|
||||
# Progressive bands (front 8.2): one price for the whole quantity of each
|
||||
# product, chosen by the order's total billed metres of that 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)
|
||||
# The art grade rules (front 8.5): the worst item may require the designer's
|
||||
# treatment and/or flag the order for the designer, stored with the approval.
|
||||
offer = catalog.current(c)['tratamento']
|
||||
offered = bool(offer['enabled'] and offer['unit_cents'] > 0)
|
||||
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
|
||||
# A montador sheet (front 7a) is assembled by the team from Estampas/, not
|
||||
# sent by a customer: the treatment rule does not apply to it.
|
||||
if draft.get('montador'):
|
||||
flags.pop('tratamento', None)
|
||||
if 'tratamento' in flags and not draft.get('treatment'):
|
||||
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
|
||||
items_total = sum(i['total_cents'] for i in priced)
|
||||
# The coupon discounts the items, after their bands, never freight or the
|
||||
# treatment (front 8.3). It is checked again here: a quote that waited may
|
||||
# have met an expiry or a use limit since it was created.
|
||||
coupon = None
|
||||
if draft.get('coupon'):
|
||||
coupon = coupons.check(c, draft['coupon'], (draft.get('customer') or {}).get('cnpj'), priced)
|
||||
# The montador assembles the sheet itself: the treatment rule does not apply.
|
||||
cart = cart_pricing.price_cart(
|
||||
c, [item.model_dump(mode='json') for item in items], names,
|
||||
coupon_code=draft.get('coupon'),
|
||||
customer_document=(draft.get('customer') or {}).get('cnpj'),
|
||||
wants_treatment=bool(draft.get('treatment')),
|
||||
treatment_rule=not draft.get('montador'))
|
||||
# Keep the review snapshot's own fields with each priced item.
|
||||
priced = cart['items']
|
||||
for priced_item, original in zip(priced, draft['items']):
|
||||
priced_item.update({
|
||||
'uploads': original['uploads'], 'production': original['production'],
|
||||
'quality_status': original['quality_status'],
|
||||
'quality_acknowledged': original['quality_acknowledged'],
|
||||
'residue_accepted': original.get('residue_accepted', 0),
|
||||
**({'residue_accepted_at': original['residue_accepted_at']}
|
||||
if original.get('residue_accepted_at') else {}),
|
||||
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
|
||||
if original.get('stroke_class') else {}),
|
||||
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
|
||||
**({'stroke_choice_at': original['stroke_choice_at']}
|
||||
if original.get('stroke_choice_at') else {}),
|
||||
**({'proof_y_fraction': original['proof_y_fraction']}
|
||||
if original.get('proof_y_fraction') is not None else {}),
|
||||
**({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}),
|
||||
**({'split': original['split']} if original.get('split') else {})})
|
||||
items_total = cart['items_total']
|
||||
coupon = cart['coupon']
|
||||
discount = coupon['discount_cents'] if coupon else 0
|
||||
flags = cart['grade_flags']
|
||||
treatment = cart['treatment_cents']
|
||||
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||
try:
|
||||
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
||||
metres, items_total)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc))
|
||||
# The designer's treatment is offered only when switched on and priced.
|
||||
treatment = offer['unit_cents'] if draft.get('treatment') and offer['enabled'] else 0
|
||||
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
|
||||
'destination': draft.get('destination'),
|
||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
||||
|
||||
Reference in New Issue
Block a user