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 '[]';

View File

@@ -81,6 +81,37 @@ def run():
assert approved['items'][0]['unit_cents'] == 12345, approved
assert approved['items'][0]['total_cents'] == 12345, approved
# Bands (front 8.2): from 2 m the metre costs less; two items of uv
# (2 m together) pay the band price on both.
made = manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '2', 'unit_cents': 10000}]})
prices.append(made['id'])
bands = client.call('/session')['products'][UV]['bands']
assert bands == [{'from_metres': 2.0, 'unit_cents': 10000}], bands
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert entry['bands'] == [{'from_metres': '2', 'unit_cents': 10000}], entry
banded = client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item, item], 'freight': {'service': 'pickup'}})
assert banded['status'] == 'approved', banded
approved = client.call('/quotes/' + banded['id'])['approved']
assert [line['unit_cents'] for line in approved['items']] == [10000, 10000], approved
assert [line['total_cents'] for line in approved['items']] == [10000, 10000], approved
assert approved['total_cents'] == 20000, approved
# Invalid bands are refused with 422 and do not become prices.
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '5', 'unit_cents': 1900},
{'from_metres': '5', 'unit_cents': 1800}]}, expected=422)
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '0', 'unit_cents': 1900}]}, expected=422)
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': str(i), 'unit_cents': 1900}
for i in range(1, 7)]}, expected=422)
manager.call('/operator/site/products/tratamento/prices', {
'unit_cents': 1000, 'bands': [{'from_metres': '5', 'unit_cents': 900}]}, expected=422)
# A profile without "manage" cannot see or change the Site tab.
email = f'site-staff-{tag}@example.test'
user = manager.call('/operator/users', {'name': 'Teste Site', 'email': email,

View File

@@ -1,11 +1,13 @@
"""Run from repository root: python3 -m unittest tests.test_pricing -v."""
import json
import os
from decimal import Decimal
from pathlib import Path
from unittest.mock import patch
import subprocess
import unittest
from app.core.pricing import is_manual, price, PRICES, treatment_cents
from app.catalog import band_price
from app.core.pricing import apply_bands, bill_splits, is_manual, price, PRICES, treatment_cents
class PricingTests(unittest.TestCase):
def test_every_length_against_actual_site_javascript(self):
@@ -69,6 +71,67 @@ class PricingTests(unittest.TestCase):
self.assertEqual(extra['billed_metres'], '1.1')
self.assertEqual(extra['total_cents'], 1907)
def test_band_price_below_at_between_and_above(self):
# Front 8.2: the highest band reached wins, and it charges the whole
# quantity, not a staircase.
bands = [{'from_metres': '5', 'unit_cents': 1990},
{'from_metres': '20', 'unit_cents': 1890}]
self.assertEqual(band_price(2190, bands, Decimal('4.9')), 2190)
self.assertEqual(band_price(2190, bands, Decimal('5')), 1990)
self.assertEqual(band_price(2190, bands, Decimal('19.9')), 1990)
self.assertEqual(band_price(2190, bands, Decimal('20')), 1890)
self.assertEqual(band_price(2190, bands, Decimal('12000')), 1890)
# No bands, or a number from the session, is the base price.
self.assertEqual(band_price(2190, [], Decimal('5')), 2190)
self.assertEqual(band_price(2190, [{'from_metres': 5, 'unit_cents': 1990}], Decimal('5')), 1990)
def test_apply_bands_prices_the_whole_product_together(self):
# Two items of the same mode reach the band together: both pay it.
priced = [{'mode': 'file', 'billed_metres': '2.5', 'unit_cents': 2190, 'total_cents': 5475},
{'mode': 'file', 'billed_metres': '2.5', 'unit_cents': 2190, 'total_cents': 5475}]
apply_bands(priced, {'file': 1990})
self.assertEqual([item['unit_cents'] for item in priced], [1990, 1990])
self.assertEqual([item['total_cents'] for item in priced], [4975, 4975])
# A split group counts its billed metres once, after bill_splits.
priced = [{'mode': 'avulsa', 'billed_metres': '0.2', 'unit_cents': 2190, 'total_cents': 438,
'split': {'group': 'g', 'part': 1, 'of': 2}},
{'mode': 'avulsa', 'billed_metres': '0.3', 'unit_cents': 2190, 'total_cents': 657,
'split': {'group': 'g', 'part': 2, 'of': 2}}]
bill_splits(priced)
self.assertEqual(priced[0]['billed_metres'], '0.7')
apply_bands(priced, {'avulsa': 1890})
self.assertEqual(priced[0]['total_cents'], 1323)
self.assertEqual(priced[1]['total_cents'], 567)
# The manual-file extra stays on top of the band price.
priced = [{'mode': 'file', 'billed_metres': '2', 'unit_cents': 2190,
'manual_extra_cents': 200, 'total_cents': 4380}]
apply_bands(priced, {'file': 1890})
self.assertEqual(priced[0]['unit_cents'], 2090)
self.assertEqual(priced[0]['total_cents'], 4180)
# Another mode is untouched.
uv = {'mode': 'uv', 'billed_metres': '1', 'unit_cents': 8990, 'total_cents': 8990}
priced = [{'mode': 'file', 'billed_metres': '1', 'unit_cents': 2190, 'total_cents': 2190}, uv]
apply_bands(priced, {'file': 1990})
self.assertEqual((uv['unit_cents'], uv['total_cents']), (8990, 8990))
def test_band_prices_against_actual_site_javascript(self):
# The Site must show the same band price the server charges: run its
# own precoNaMetragem for the same table and totals.
source = Path('web/site-config.js').read_text()
prices = source.split('const PRECO=')[1].split(';', 1)[0]
body = source.split('function precoNaMetragem', 1)[1].split('\n}', 1)[0]
bands = [{'from_metres': 5, 'unit_cents': 1990},
{'from_metres': 20, 'unit_cents': 1890}]
js = ('const PRECO=' + prices + ';const FAIXAS=' + json.dumps({'file': bands}) + ';'
'function precoNaMetragem' + body + '\n}'
';const results=[];for(const m of ["4.9","5","19.9","20","60"])'
'results.push([m,Math.round(precoNaMetragem("file",Number(m))*100)]);'
'process.stdout.write(JSON.stringify(results));')
cases = json.loads(subprocess.check_output(['node', '-e', js], text=True))
for metres, cents in cases:
with self.subTest(metres=metres):
self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres)))
def test_which_items_are_opened_by_hand(self):
def item(kind, measurement, uid='u1'):
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}

View File

@@ -91,6 +91,7 @@
if(session.products){
for(const [mode,product] of Object.entries(session.products)){
PRECO[mode]=product.unit_cents/100;
FAIXAS[mode]=product.bands||[];
const card=document.querySelector('button.ec[data-modo="'+mode+'"]');
if(card&&!product.enabled)card.hidden=true;
}
@@ -98,6 +99,16 @@
const product=session.products[el.dataset.preco];
el.textContent=product&&!product.enabled?'Indisponível':rs(PRECO[el.dataset.preco]);
});
// The home price table keeps the base price; the bands go under it.
const tabelaFaixas=document.getElementById('tabelaFaixas');
if(tabelaFaixas){
const linhas=Object.entries(session.products)
.filter(([,product])=>product.enabled && product.bands?.length)
.map(([mode,product])=>node('div',MODOS[mode].tit+': '+product.bands
.map(band=>'a partir de '+metrosCurto(band.from_metres)+' m: '+rs(band.unit_cents/100)).join(' · ')));
tabelaFaixas.replaceChildren(...linhas);
tabelaFaixas.hidden=!linhas.length;
}
window.dtfProducts=session.products;
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
@@ -129,6 +140,10 @@
if (className) el.className=className;
return el;
}
// "5" or "5,5": a band's metres as the customer reads them.
function metrosCurto(value){
return String(Number(value)).replace('.',',');
}
// What the customer is paying for, from the server's approval.
function pintaResumo(quote) {
const approved = quote ? quote.approved : null;

View File

@@ -940,6 +940,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
<p class="cObs" id="cObs"></p>
<p class="cObs" id="cProxima"></p>
<div class="cTot"><span>Total</span><b id="cTotal">—</b></div>
<div id="qmsg" style="display:none"></div>
<div class="ciente" id="ciente">
@@ -1155,6 +1156,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<tr><td>Artes avulsas</td><td data-preco="avulsa">R$ 21,90</td><td data-preco="uv">R$ 89,90</td></tr>
</tbody>
</table>
<div class="nota2" id="tabelaFaixas" hidden></div>
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + R$ 2,00 por metro.</p>
</div>
<div class="info2-vant">

View File

@@ -18,6 +18,12 @@ function moneyInputCents(value){
// A price that already started is refused by the server (409).
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
// "5" or "5,5": a band's start in metres, as the table reads it.
function bandMetres(value){return String(Number(value)).replace('.',',');}
function bandsText(bands){
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join('');
}
function siteProductRow(product){
const tr=node('tr');
const name=node('td');name.append(node('b',product.title));
@@ -59,23 +65,57 @@ function sitePriceBlock(product){
const starts=node('input');starts.type='datetime-local';
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
startsLabel.append(starts);
// Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas
// viajam com este preço. O tratamento é um valor por pedido, sem faixas.
const bandRows=node('div',undefined,'siteBandRows');
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;};
const bandRow=()=>{
const row=node('div',undefined,'siteBandRow');
const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)'));
const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom';
from.setAttribute('aria-label','Metragem da faixa de '+product.title);
fromLabel.append(from);
const priceLabel=node('label');priceLabel.append(node('span','R$ por metro'));
const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice';
bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title);
priceLabel.append(bandPrice);
const remove=button('Remover',()=>{row.remove();paintAdd();},'btn ghost');
row.append(fromLabel,priceLabel,remove);
return row;
};
addBand.onclick=()=>{if(bandRows.children.length>=5)return;bandRows.append(bandRow());paintAdd();};
const bands=node('div',undefined,'siteBands');
const bandsHead=node('div',undefined,'siteBandsHead');
bandsHead.append(node('span','Faixas'),addBand);
bands.append(bandsHead,bandRows);
const formBands=()=>[...bandRows.children].map(row=>{
const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.'));
const unit=moneyInputCents(row.querySelector('.siteBandPrice').value);
if(!Number.isFinite(from)||from<=0||unit===null||unit<=0)
throw new Error('Confira as faixas: metragem e preço maiores que zero.');
return {from_metres:String(from),unit_cents:unit};
});
const save=button('Salvar',async()=>{
const cents=moneyInputCents(price.value);
if(cents===null)throw new Error('Informe o preço em reais, como 19,90.');
const whenDate=starts.value?new Date(starts.value):null;
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
await api('/site/products/'+product.id+'/prices',
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null});
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null,
bands:product.id==='tratamento'?[]:formBands()});
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
await loadSiteAdmin();
},'btn pri');
form.append(priceLabel,startsLabel,save);
if(product.id!=='tratamento')form.append(bands);
const scheduled=node('div',undefined,'siteScheduled');
if(product.scheduled.length){
for(const row of product.scheduled){
const line=node('div',undefined,'siteScheduledRow');
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+' a partir de '+when(row.starts_at)));
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands)+
' a partir de '+when(row.starts_at)));
line.append(button('Cancelar',async()=>{
await cancelScheduledPrice(row.id);
say('Preço agendado cancelado.');
@@ -92,7 +132,7 @@ function sitePriceBlock(product){
const body=node('tbody');
for(const row of product.history){
const tr=node('tr');
tr.append(node('td',money(row.unit_cents),'nowrap'),node('td',when(row.starts_at),'nowrap'),
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands),'nowrap'),node('td',when(row.starts_at),'nowrap'),
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
body.append(tr);
}

View File

@@ -651,6 +651,13 @@ label.fopt{cursor:pointer;user-select:none}
#tab-site .sitePriceForm input{height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--sf);color:var(--tx);font-size:14px;font-family:inherit}
#tab-site .sitePriceForm input:focus{border-color:var(--acc);box-shadow:0 0 0 3px color-mix(in srgb,var(--acc) 18%,transparent);outline:none}
#tab-site .siteMoney{width:140px}
#tab-site .siteBands{display:flex;flex-direction:column;gap:8px;flex:1 0 100%}
#tab-site .siteBandsHead{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
#tab-site .siteBandsHead>span{font-size:12px;color:var(--tx2)}
#tab-site .siteBandRows{display:flex;flex-direction:column;gap:8px}
#tab-site .siteBandRow{display:flex;align-items:end;gap:10px;flex-wrap:wrap}
#tab-site .siteBandFrom{width:100px}
#tab-site .siteBandPrice{width:120px}
#tab-site .siteScheduled{display:flex;flex-direction:column;gap:8px;font-size:13.5px}
#tab-site .siteScheduledRow{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
#tab-site .siteScheduledRow .btn{height:30px;padding:0 10px;font-size:12.5px}

View File

@@ -32,6 +32,25 @@ function limpaPaineis(){
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
function pintaPedido(){
const aPagar = itensAPagar();
// Faixas progressivas (front 8.2): um preço só para todos os metros de um
// produto no pedido, a mesma regra que o servidor cobra na aprovação.
const metrosPorModo={};
for(const it of aPagar) metrosPorModo[it.modo]=(metrosPorModo[it.modo]||0)+(it.cob||0);
for(const it of aPagar){
it.unit=precoNaMetragem(it.modo, metrosPorModo[it.modo])+(it.extra||0);
it.total=Math.round(it.cob*it.unit*100)/100;
it.desc=(it.partes?it.partes.length+' folhas · ':'')+fmtM(it.cob)+' m · '+rs(it.unit)+'/m';
}
const aviso=$('cProxima');
if(aviso){
const proxima=itemAtual?proximaFaixa(itemAtual.modo, metrosPorModo[itemAtual.modo]):null;
if(proxima){
const falta=Math.max(0.1, Math.ceil((Number(proxima.from_metres)-metrosPorModo[itemAtual.modo])*10-1e-9)/10);
aviso.textContent='Faltam '+falta.toFixed(1).replace('.',',')+' m para '+rs(proxima.unit_cents/100)+' o metro.';
aviso.hidden=false;
}else{aviso.hidden=true;aviso.textContent='';}
}
$('itens').innerHTML = pedido.map((it,i)=>
'<div class="item'+(it.marcado===false?' fora':'')+'">'+
'<label class="marca"><input type="checkbox" data-sel="'+i+'"'+(it.marcado===false?'':' checked')+
@@ -52,7 +71,6 @@ function pintaPedido(){
});
}));
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
const aPagar = itensAPagar();
const itens = aPagar.reduce((t,it)=>t+it.total,0);
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
const tratamento=$('fTratamento')?.checked&&TAXA_TRATAMENTO>0?TAXA_TRATAMENTO:0;
@@ -90,8 +108,13 @@ const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'});
function carrinho(){
const base=precoMetro(), cob=cobrarMontagem();
const cob=cobrarMontagem();
const extra=folhaManual()? TAXA_MANUAL : 0;
// A faixa é escolhida pelos metros deste produto no carrinho mais o item
// sendo montado (front 8.2), como o servidor cobra.
const metrosModo=pedido.filter(it=>it.marcado!==false && it.modo===modo)
.reduce((t,it)=>t+(it.cob||0),0)+cob;
const base=precoNaMetragem(modo, metrosModo);
const unit=base+extra, tot=cob*unit, sobra=+(cob-metros).toFixed(2);
$('carr').classList.add('on');
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';

View File

@@ -57,6 +57,10 @@ const MODOS={
// tela, para o cliente entender o arquivo dele, mas não mexe no preço.
// O servidor cobra o mesmo (app/core/pricing.py, conferido em tests/test_pricing.py).
const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90};
// Faixas por metragem (front 8.2): o preço do metro depende do total do
// produto no pedido, não de cada item. Vem do servidor (/api/session), que
// cobra o mesmo (app/catalog.py band_price).
const FAIXAS={};
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
let TAXA_MANUAL=0;
@@ -65,6 +69,21 @@ let TAXA_TRATAMENTO=0;
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
const ehFolha=m=>!!MODOS[m||modo].folha;
const precoMetro=m=>PRECO[m||modo];
// Uma faixa vale quando o total do produto no pedido chega à metragem dela;
// a mais alta alcançada manda no preço de todos os itens daquele produto.
function precoNaMetragem(m, metros){
const bands=FAIXAS[m]||[];
let alta=null;
for(const band of bands) if(metros>=Number(band.from_metres) && (!alta || Number(band.from_metres)>=Number(alta.from_metres))) alta=band;
return alta ? alta.unit_cents/100 : PRECO[m];
}
// A próxima faixa à frente, para o aviso de quanto falta.
function proximaFaixa(m, metros){
const bands=FAIXAS[m]||[];
let proxima=null;
for(const band of bands) if(Number(band.from_metres)>metros && (!proxima || Number(band.from_metres)<Number(proxima.from_metres))) proxima=band;
return proxima;
}
const MINIMO_M=1, GAP_CM=0.5, RODAPE_CM=5;
const RENDERIZA=/[.](png|jpe?g|webp|gif|bmp)$/i;
// Folha pronta: dá para medir PNG e PDF. PSD, AI, TIFF e CDR entram, mas