All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 8m24s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m14s
Marcus: "o pedido mínimo de um metro deve ser somente para o primeiro metro, após isso deve se somar a metragem de cada arquivo", "Soma tudo e arredonda uma vez só", and for different products "Pode ser sim": each product apart at its price, the minimum for the whole order. Order #246 (three ready sheets of 3,74, 0,24 and 0,22 m) was 5,80 m with 1 m per item; it is now 4,20 m. pricing.bill_order replaces the per-item minimum and bill_splits: per product the exact lengths (a ready sheet without its gaps) are rounded once with the 8 mm grace, the minimum's difference goes to the first item's product, and each product's total is shared back to its items in 10 cm steps (each its length rounded down, the missing steps to the largest fractions, the minimum to the product's first item), for Tiny's 10 cm SKUs and the cards. A share of 0 m adds no Tiny line. The print file's guard allows an item one 10 cm step under its length. The Site cart shares the same way (cobrarPedido), split sheets round once, the buy box says the items of a product are summed and rounded once, and the Montador's estimate rounds its sum once. Contract: output/revisao/contrato-minimo-pedido.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
147 lines
6.8 KiB
Python
147 lines
6.8 KiB
Python
"""One pricing module for every way a cart is priced (Critical Corrections 3).
|
|
|
|
The Site's pre-check and the approval used to repeat the same chain and had
|
|
already drifted: the pre-check ignored the manual-file extra. Everything that
|
|
turns items into money lives here now. The catalog is read once, the arithmetic
|
|
is pure, and a new price rule only has to be added in one place.
|
|
"""
|
|
from decimal import Decimal
|
|
|
|
from . import catalog, coupons, grade_rules
|
|
from .core import pricing
|
|
|
|
|
|
def art_pairs(items):
|
|
"""[item_index, source_index] for every art in the cart: one artwork of
|
|
loose art, or one sheet file of a ready sheet."""
|
|
return [[index, source] for index, item in enumerate(items)
|
|
for source in range(len((item.get('production') or {}).get('sources') or []))]
|
|
|
|
|
|
def chosen_arts(items, choice):
|
|
"""The arts the draft's treatment selects: all of them for True (old carts
|
|
and the grade rule), the valid pairs for a list."""
|
|
if choice is True:
|
|
return art_pairs(items)
|
|
if not isinstance(choice, (list, tuple)):
|
|
return []
|
|
valid = {tuple(pair) for pair in art_pairs(items)}
|
|
return [list(pair) for pair in choice
|
|
if isinstance(pair, (list, tuple)) and len(pair) == 2 and tuple(pair) in valid]
|
|
|
|
|
|
def treatment_price(items, choice, offer):
|
|
"""Ajuste Fino for the chosen arts, with the row's bands counted in arts.
|
|
{} when it is not offered or no art is chosen."""
|
|
if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
|
|
return {}
|
|
arts = chosen_arts(items, choice)
|
|
if not arts:
|
|
return {}
|
|
count = len(arts)
|
|
unit = catalog.band_price(offer['unit_cents'], offer.get('bands') or [], count)
|
|
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
|
|
|
|
|
|
def redesign_price(items, choice, offer):
|
|
"""Ajuste Fino Redesenho for the chosen arts: one price per art, never a
|
|
band. {} when it is not offered or no art is chosen."""
|
|
if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
|
|
return {}
|
|
arts = chosen_arts(items, choice)
|
|
if not arts:
|
|
return {}
|
|
count = len(arts)
|
|
unit = offer['unit_cents']
|
|
return {'cents': unit * count, 'hours': 48, 'arts': count, 'unit_cents': unit}
|
|
|
|
|
|
def designer_hours(snapshot):
|
|
"""The extra hours the paid designer work adds to the deadline: 48 h when
|
|
any art was sent to Redesenho, else 24 h for the basic Ajuste Fino."""
|
|
# The hours recorded with the order win (an order keeps what it was sold
|
|
# with); 48 and 24 are the defaults for snapshots that carry none.
|
|
hours = [int((snapshot[key] if isinstance(snapshot.get(key), dict) else {}).get('hours') or default)
|
|
for key, default in (('redesign', 48), ('treatment', 24)) if snapshot.get(key)]
|
|
return max(hours, default=0)
|
|
|
|
|
|
def needs_designer(snapshot):
|
|
"""Whether a designer must prepare the final PNG before the print queue:
|
|
a paid Ajuste Fino or Redesenho on any art."""
|
|
return bool(snapshot.get('treatment') or snapshot.get('redesign'))
|
|
|
|
|
|
def price_items(items, names, catalog_now, manual_extra):
|
|
"""Price the items without a database: price() per item with the product's
|
|
base price and the manual extra, bill_splits, then the band of each mode's
|
|
total, then apply_bands. Exactly as an order is charged."""
|
|
priced, lengths = [], []
|
|
for item in items:
|
|
extra = manual_extra if pricing.is_manual(item, names) else 0
|
|
product = catalog_now[item['mode']]
|
|
# Billed on the length less a ready sheet's gaps; `metres` stays the
|
|
# film the layout uses, which the print file and the folders follow.
|
|
length = pricing.billable_metres(item)
|
|
charged = pricing.price(item['mode'], str(length), item['grade'], extra,
|
|
minimum=Decimal('0'), unit_cents=product['unit_cents'])
|
|
priced.append({**charged, 'metres': str(item['metres']),
|
|
**({'split': item['split']} if item.get('split') else {})})
|
|
lengths.append(length)
|
|
# One rounding per product and the 1 m minimum once for the order (Marcus,
|
|
# 2026-12-03); it also covers the split sheets of item 17.
|
|
pricing.bill_order(priced, lengths)
|
|
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():
|
|
product = catalog_now[mode]
|
|
price_for_total = catalog.band_price(product['unit_cents'], product['bands'], total)
|
|
if price_for_total != product['unit_cents']:
|
|
banded[mode] = price_for_total
|
|
pricing.apply_bands(priced, banded)
|
|
return priced
|
|
|
|
|
|
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
|
wants_treatment=False, wants_redesign=(), treatment_rule=True):
|
|
"""Price a cart exactly as an order is charged. Returns
|
|
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
|
|
'treatment': dict, 'treatment_cents': int, 'redesign': dict,
|
|
'redesign_cents': int, 'grade_flags': dict}.
|
|
Raises HTTPException(422) for a product switched off, a Redesenho not
|
|
offered, a required designer service the cart did not ask for, or a
|
|
refused coupon. `treatment_rule=False` is for the montador, which
|
|
assembles the sheet."""
|
|
from fastapi import HTTPException
|
|
catalog_now = catalog.current(c)
|
|
for item in items:
|
|
if not catalog_now[item['mode']]['enabled']:
|
|
raise HTTPException(422, 'Este produto não está à venda agora.')
|
|
priced = price_items(items, names, catalog_now, pricing.manual_extra_cents())
|
|
offer = catalog_now['tratamento']
|
|
offered = bool(offer['enabled'] and offer['unit_cents'] > 0)
|
|
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
|
|
if not treatment_rule:
|
|
flags.pop('tratamento', None)
|
|
treatment = treatment_price(items, wants_treatment, offer)
|
|
redesign = redesign_price(items, wants_redesign, catalog_now['redesenho'])
|
|
if chosen_arts(items, wants_redesign) and not redesign:
|
|
raise HTTPException(422, 'O Redesenho não está disponível agora.')
|
|
# The grade rule wants a designer on the art: the stronger Redesenho
|
|
# satisfies it just as the basic Ajuste Fino does.
|
|
if 'tratamento' in flags and not treatment and not redesign:
|
|
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
|
|
coupon = None
|
|
if coupon_code:
|
|
coupon = coupons.check(c, coupon_code, customer_document, priced)
|
|
return {'items': priced,
|
|
'items_total': sum(i['total_cents'] for i in priced),
|
|
'coupon': coupon,
|
|
'treatment': treatment,
|
|
'treatment_cents': treatment.get('cents', 0),
|
|
'redesign': redesign,
|
|
'redesign_cents': redesign.get('cents', 0),
|
|
'grade_flags': flags}
|