feat: progressive price bands per product (front 8.2)

A price may carry up to five bands, "from N m, R$ Y": the order's total
billed metres of that product chooses one price for its whole quantity,
the manual-file extra still on top. Bands start and become history with
their price row. The Site charges the same band for the cart, shows
"Faltam X m para R$ Y o metro" and lists the bands under the price
table; the Kanban's Site tab edits them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 14:30:15 -03:00
parent c5e7a80b64
commit 2a6732eb37
16 changed files with 334 additions and 23 deletions

View File

@@ -49,7 +49,12 @@ def session(request: Request, response: Response):
# Zero keeps the designer's treatment hidden, as an off product does.
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
# What the Site sells now: a switched-off product is hidden there.
'products': {mode: products[mode] for mode in catalog.MODES},
# Bands travel with the price; the Site reads them as numbers.
'products': {mode: {**products[mode],
'bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in products[mode]['bands']]}
for mode in catalog.MODES},
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.

View File

@@ -12,7 +12,7 @@ from .. import catalog, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from ..core.pricing import price
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
@@ -42,8 +42,21 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
priced = []
for item in body.items:
catalog.require_enabled(c, item.mode)
priced.append(price(item.mode, str(item.metres), item.grade,
unit_cents=catalog.unit_cents(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)
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:

View File

@@ -9,6 +9,7 @@ quotes and approvals with 422.
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import catalog
from ..core import db
@@ -19,11 +20,32 @@ router = APIRouter()
def price_row(row):
return {'id': row['id'], 'unit_cents': row['unit_cents'],
return {'id': row['id'], 'unit_cents': row['unit_cents'], 'bands': row['bands'] or [],
'starts_at': row['starts_at'].isoformat(), 'created_by': row['created_by'],
'created_at': row['created_at'].isoformat()}
def checked_bands(product, bands):
"""The bands the row will store; 422 in Portuguese for anything invalid."""
if product == 'tratamento' and bands:
raise HTTPException(422, 'O tratamento é um valor por pedido: não tem faixas.')
if len(bands) > 5:
raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.')
checked, last = [], None
for band in bands:
if not band.from_metres.is_finite() or band.from_metres <= 0:
raise HTTPException(422, 'A metragem de cada faixa precisa ser maior que zero.')
if band.unit_cents <= 0:
raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.')
if band.unit_cents > 10000000:
raise HTTPException(422, 'O preço de cada faixa é alto demais.')
if last is not None and band.from_metres <= last:
raise HTTPException(422, 'As faixas precisam estar em ordem crescente de metragem.')
last = band.from_metres
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
return checked
@router.get('/api/operator/site/products')
def site_products(user=Depends(can('manage'))):
with db.connect() as c:
@@ -34,7 +56,7 @@ def site_products(user=Depends(can('manage'))):
FROM dtf_local.product_prices
WHERE starts_at <= now()
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
rows = c.execute('''SELECT id, product, unit_cents, starts_at, created_by, created_at
rows = c.execute('''SELECT id, product, unit_cents, bands, starts_at, created_by, created_at
FROM dtf_local.product_prices ORDER BY product, created_at DESC, id DESC''').fetchall()
products = []
for product in catalog.PRODUCTS:
@@ -45,6 +67,7 @@ def site_products(user=Depends(can('manage'))):
'id': product, 'title': catalog.TITLES[product], 'unit': catalog.UNITS[product],
'enabled': state[product]['enabled'],
'unit_cents': state[product]['unit_cents'],
'bands': state[product]['bands'],
'fallback': product not in started,
'scheduled': [price_row(row) for row in future],
'history': [price_row(row) for row in prices[:20]],
@@ -72,6 +95,7 @@ def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))
raise HTTPException(404, 'Produto não encontrado.')
if product != 'tratamento' and body.unit_cents <= 0:
raise HTTPException(422, 'O preço precisa ser maior que zero.')
bands = checked_bands(product, body.bands)
now = datetime.now(timezone.utc)
starts_at = body.starts_at or now
if starts_at.tzinfo is None:
@@ -79,10 +103,10 @@ def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))
if starts_at < now - timedelta(minutes=1):
raise HTTPException(422, 'A data de início não pode estar no passado.')
with db.connect() as c:
row = c.execute('''INSERT INTO dtf_local.product_prices(product, unit_cents, starts_at, created_by)
VALUES(%s,%s,%s,%s) RETURNING id''',
(product, body.unit_cents, starts_at, user)).fetchone()
audit('site_price_changed', product=product, unit_cents=body.unit_cents,
row = c.execute('''INSERT INTO dtf_local.product_prices(product, unit_cents, starts_at, created_by, bands)
VALUES(%s,%s,%s,%s,%s) RETURNING id''',
(product, body.unit_cents, starts_at, user, Jsonb(bands))).fetchone()
audit('site_price_changed', product=product, unit_cents=body.unit_cents, bands=bands,
starts_at=starts_at.isoformat(), operator=user)
return {'id': row['id']}

View File

@@ -9,8 +9,13 @@ and an approved quote keeps the price it was approved with.
`tratamento` is the designer's treatment (front 5), a fixed amount per order:
it counts as offered only when it is switched on and priced above zero.
A price row may carry bands by the order's total metres of that product (front
8.2): below the first band the base price, then the highest band reached wins
and the whole quantity is charged at that one price. The bands travel with the
row, so they start and become history with it.
"""
from fastapi import HTTPException
from decimal import Decimal
from .core import pricing
@@ -34,30 +39,58 @@ def fallback_cents(product: str) -> int:
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
def band_price(base_cents: int, bands: list, metres: Decimal) -> int:
"""The per-metre price for this quantity: the base, or the highest band
reached. The whole quantity is charged at one price, not in steps."""
metres = Decimal(str(metres))
price = base_cents
best = None
for band in bands or []:
start = Decimal(str(band['from_metres']))
if metres >= start and (best is None or start >= best):
best = start
price = band['unit_cents']
return price
def current(c) -> dict:
"""{'file': {'enabled': bool, 'unit_cents': int}, ...}: what is sold now."""
"""{'file': {'enabled': bool, 'unit_cents': int, 'bands': [...]}, ...}."""
enabled = {row['id']: row['enabled'] for row in
c.execute('SELECT id, enabled FROM dtf_local.products').fetchall()}
prices = {row['product']: row['unit_cents'] for row in c.execute('''
SELECT DISTINCT ON (product) product, unit_cents
prices = {row['product']: row for row in c.execute('''
SELECT DISTINCT ON (product) product, unit_cents, bands
FROM dtf_local.product_prices
WHERE starts_at <= now()
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
return {product: {'enabled': bool(enabled.get(product, True)),
'unit_cents': prices.get(product, fallback_cents(product))}
'unit_cents': prices[product]['unit_cents'] if product in prices else fallback_cents(product),
'bands': prices[product]['bands'] if product in prices else []}
for product in PRODUCTS}
def unit_cents(c, product: str) -> int:
"""The current price of one product, or the fallback."""
"""The current base price of one product, or the fallback."""
row = c.execute('''SELECT unit_cents FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
return row['unit_cents'] if row else fallback_cents(product)
def unit_cents_for(c, product: str, metres: Decimal) -> int:
"""The current price of one product for this quantity, bands included."""
row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
if not row:
return fallback_cents(product)
return band_price(row['unit_cents'], row['bands'], metres)
def require_enabled(c, product: str) -> None:
"""Refuse a product someone switched off in the Kanban's Site tab."""
# Imported here so the pure helpers above load without the web framework
# (tests/test_pricing.py runs on the host, where FastAPI is not installed).
from fastapi import HTTPException
row = c.execute('SELECT enabled FROM dtf_local.products WHERE id=%s', (product,)).fetchone()
if row and not row['enabled']:
raise HTTPException(422, 'Este produto não está à venda agora.')

View File

@@ -357,10 +357,18 @@ class SiteProductToggle(StrictModel):
enabled: bool
class PriceBand(StrictModel):
"""Uma faixa por metragem: a partir de X m, o metro passa a custar Y."""
from_metres: Decimal
unit_cents: int = Field(strict=True)
class SitePriceNew(StrictModel):
"""Um novo preço e a data em que começa; sem data, começa agora."""
unit_cents: int = Field(ge=0, le=10000000, strict=True)
starts_at: datetime | None = None
# As faixas viajam com o preço (front 8.2); vazio é o preço único.
bands: list[PriceBand] = Field(default_factory=list)
class Contraction(StrictModel):

View File

@@ -80,6 +80,18 @@ def bill_splits(priced: list) -> list:
return priced
def apply_bands(priced: list, unit_by_mode: dict) -> list:
"""Rewrite the items of each mode to the band price for the order's total
metres of that product (front 8.2). The manual-file extra stays on top of
each item; a mode absent from `unit_by_mode` is untouched."""
for item in priced:
if item['mode'] in unit_by_mode:
unit = unit_by_mode[item['mode']] + item.get('manual_extra_cents', 0)
item['unit_cents'] = unit
item['total_cents'] = int(Decimal(str(item['billed_metres'])) * unit)
return priced
def sheet_label(item: dict) -> str:
"""' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
split = item.get('split')

View File

@@ -22,7 +22,7 @@ from psycopg.types.json import Jsonb
from . import catalog, payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import bill_splits, is_manual, manual_extra_cents, price
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
@@ -92,6 +92,17 @@ def approve(c, row, items, reviewer):
**({'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)
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),

View File

@@ -617,3 +617,8 @@ CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);
-- Front 8.2: a price may also have bands by the order's total metres of that
-- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of
-- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5).
ALTER TABLE dtf_local.product_prices ADD COLUMN IF NOT EXISTS bands jsonb NOT NULL DEFAULT '[]';