diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 6adb633..d583b58 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -22,6 +22,7 @@ jobs: tests.test_staging_readiness \ deploy.test_production_preflight \ tests.test_pricing \ + tests.test_cart_pricing \ tests.test_coupons \ tests.test_grade_rules \ tests.test_migrate \ diff --git a/app/api/quotes.py b/app/api/quotes.py index 09a762d..54ed727 100644 --- a/app/api/quotes.py +++ b/app/api/quotes.py @@ -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. diff --git a/app/cart_pricing.py b/app/cart_pricing.py new file mode 100644 index 0000000..96e414b --- /dev/null +++ b/app/cart_pricing.py @@ -0,0 +1,69 @@ +"""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 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 = [] + for item in items: + extra = manual_extra if pricing.is_manual(item, names) else 0 + product = catalog_now[item['mode']] + priced.append({**pricing.price(item['mode'], str(item['metres']), item['grade'], extra, + minimum=Decimal('0') if item.get('split') else Decimal('1'), + unit_cents=product['unit_cents']), + **({'split': item['split']} if item.get('split') else {})}) + pricing.bill_splits(priced) + 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, treatment_rule=True): + """Price a cart exactly as an order is charged. Returns + {'items': [priced item dicts], 'items_total': int, 'coupon': dict|None, + 'treatment_cents': int, 'grade_flags': dict}. + Raises HTTPException(422) for a product switched off, a required treatment + the cart did not ask for, or a refused coupon (the same messages as today). + `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) + if 'tratamento' in flags and not wants_treatment: + raise HTTPException(422, grade_rules.treatment_message(flags['tratamento'])) + coupon = None + if coupon_code: + coupon = coupons.check(c, coupon_code, customer_document, priced) + treatment = offer['unit_cents'] if wants_treatment and offer['enabled'] else 0 + return {'items': priced, + 'items_total': sum(i['total_cents'] for i in priced), + 'coupon': coupon, + 'treatment_cents': treatment, + 'grade_flags': flags} diff --git a/app/quote_review.py b/app/quote_review.py index 5d47771..20359d4 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -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). diff --git a/tests/test_cart_pricing.py b/tests/test_cart_pricing.py new file mode 100644 index 0000000..95e91d9 --- /dev/null +++ b/tests/test_cart_pricing.py @@ -0,0 +1,161 @@ +"""One pricing module: the same arithmetic for every cart (plan 003). + +Run from repository root: python3 -m unittest tests.test_cart_pricing -v. +old_way() reproduces today's approval arithmetic with the functions that were +already there; the matrix pins price, split minimums, bands and the manual +extra. app/cart_pricing.price_items must return exactly the same list. +""" +import unittest +from decimal import Decimal + +from app import catalog +from app.cart_pricing import price_items +from app.core import pricing + + +BASE = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990} +UV_BANDS = [{'from_metres': '5', 'unit_cents': 8000}, + {'from_metres': '20', 'unit_cents': 7000}] + + +def catalog_now(bands=None, prices=None): + prices = prices or BASE + bands = bands or {} + now = {mode: {'enabled': True, 'unit_cents': prices[mode], + 'bands': bands.get(mode, [])} for mode in BASE} + now['tratamento'] = {'enabled': True, 'unit_cents': 1000, 'bands': []} + return now + + +def item(mode, metres, grade=90, uid='u1', measurement='file', split=None): + kind = 'sheet' if mode in ('file', 'uvfile') else 'artwork' + data = {'mode': mode, 'metres': str(metres), 'grade': grade, 'uploads': [uid], + 'production': { + 'version': 3, + 'film_width_cm': 27 if mode in ('uvfile', 'uv') else 57, + 'height_cm': float(Decimal(str(metres)) * 100), + 'sources': [{'upload_id': uid, 'kind': kind, 'width_cm': 10, + 'length_cm': 10, 'copies': 1, 'rotation_degrees': 0, + 'mirrored': False, 'measurement': measurement}], + 'placements': []}, + 'quality_status': 'ok', 'quality_acknowledged': False} + if split: + data['split'] = split + return data + + +def old_way(items, names, catalog_now, manual_extra): + """Today's approve arithmetic (app/quote_review.py before plan 003).""" + priced = [] + for item in items: + extra = manual_extra if pricing.is_manual(item, names) else 0 + priced.append({**pricing.price(item['mode'], str(item['metres']), item['grade'], extra, + minimum=Decimal('0') if item.get('split') else Decimal('1'), + unit_cents=catalog_now[item['mode']]['unit_cents']), + **({'split': item['split']} if item.get('split') else {})}) + pricing.bill_splits(priced) + 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 carts(): + plain = {'u1': 'ARTE.PNG'} + manual = {'u1': 'ARTE.CDR'} + split = {'group': 'g', 'part': 1, 'of': 2} + split2 = {'group': 'g', 'part': 2, 'of': 2} + return { + 'file-one': {'items': [item('file', '1')], 'names': plain, + 'catalog': catalog_now(), 'manual': 0}, + 'avulsa-one': {'items': [item('avulsa', '2.75')], 'names': plain, + 'catalog': catalog_now(), 'manual': 0}, + 'uvfile-one': {'items': [item('uvfile', '1.01')], 'names': plain, + 'catalog': catalog_now(), 'manual': 0}, + 'uv-one': {'items': [item('uv', '1')], 'names': plain, + 'catalog': catalog_now(), 'manual': 0}, + 'same-mode-band-together': { + 'items': [item('uv', '2.5', uid='u1'), item('uv', '2.5', uid='u2')], + 'names': {'u1': 'A.PNG', 'u2': 'B.PNG'}, + 'catalog': catalog_now(bands={'uv': UV_BANDS}), 'manual': 0}, + 'same-mode-below-band': { + 'items': [item('uv', '2.4', uid='u1'), item('uv', '2.5', uid='u2')], + 'names': {'u1': 'A.PNG', 'u2': 'B.PNG'}, + 'catalog': catalog_now(bands={'uv': UV_BANDS}), 'manual': 0}, + 'split-under-one-metre': { + 'items': [item('avulsa', '0.3', uid='u1', split=split), + item('avulsa', '0.2', uid='u2', split=split2)], + 'names': {'u1': 'A.PNG', 'u2': 'B.PNG'}, + 'catalog': catalog_now(), 'manual': 0}, + 'split-and-band': { + 'items': [item('avulsa', '0.3', uid='u1', split=split), + item('avulsa', '0.2', uid='u2', split=split2)], + 'names': {'u1': 'A.PNG', 'u2': 'B.PNG'}, + 'catalog': catalog_now(bands={'avulsa': [{'from_metres': '1', + 'unit_cents': 1990}]}), + 'manual': 0}, + 'manual-cdr-extra': {'items': [item('file', '1', split=None)], + 'names': manual, 'catalog': catalog_now(), 'manual': 200}, + 'manual-customer-measure': { + 'items': [item('file', '1.01', measurement='customer')], + 'names': plain, 'catalog': catalog_now(), 'manual': 200}, + 'mixed-modes': { + 'items': [item('file', '1', uid='u1'), item('avulsa', '2', uid='u2'), + item('uvfile', '0.5', uid='u3'), item('uv', '3', uid='u4')], + 'names': {'u1': 'A.PNG', 'u2': 'B.PNG', 'u3': 'C.PNG', 'u4': 'D.PNG'}, + 'catalog': catalog_now(), 'manual': 0}, + 'no-bands': {'items': [item('avulsa', '1.2'), item('avulsa', '1.3')], + 'names': plain, 'catalog': catalog_now(bands={}), 'manual': 0}, + 'band-exact-boundary': { + 'items': [item('uv', '5')], 'names': plain, + 'catalog': catalog_now(bands={'uv': UV_BANDS}), 'manual': 0}, + 'band-floating-metres': { + 'items': [item('uv', '2.8000000000000003')], 'names': plain, + 'catalog': catalog_now(bands={'uv': [{'from_metres': '2.8', 'unit_cents': 8500}]}), + 'manual': 0}, + 'manual-plus-band': { + 'items': [item('file', '2.5')], 'names': manual, + 'catalog': catalog_now(bands={'file': [{'from_metres': '2', 'unit_cents': 1890}]}), + 'manual': 200}, + 'mixed-modes-with-bands': { + 'items': [item('file', '2', uid='u1'), item('file', '3', uid='u2'), + item('uv', '2', uid='u3')], + 'names': {'u1': 'A.PNG', 'u2': 'B.PNG', 'u3': 'C.PNG'}, + 'catalog': catalog_now(bands={'file': [{'from_metres': '5', 'unit_cents': 1790}], + 'uv': UV_BANDS}), + 'manual': 0}, + } + + +class CartPricingCharacterizationTest(unittest.TestCase): + def test_price_items_matches_todays_approval(self): + for name, cart in carts().items(): + with self.subTest(cart=name): + self.assertEqual( + price_items(cart['items'], cart['names'], cart['catalog'], cart['manual']), + old_way(cart['items'], cart['names'], cart['catalog'], cart['manual'])) + + def test_the_matrix_is_anchored_to_the_table_prices(self): + def priced(name): + cart = carts()[name] + return price_items(cart['items'], cart['names'], cart['catalog'], cart['manual']) + self.assertEqual(priced('file-one')[0]['total_cents'], 1990) + self.assertEqual(priced('uv-one')[0]['total_cents'], 8990) + self.assertEqual([p['unit_cents'] for p in priced('same-mode-band-together')], + [8000, 8000]) + split = priced('split-under-one-metre') + self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split], + [('0.8', 1752), ('0.2', 438)]) + floating = priced('band-floating-metres')[0] + self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650)) + + +if __name__ == '__main__': + unittest.main()