feat: each product's metres are summed and rounded once, and the 1 m minimum is once per order (Marcus, 2026-12-03)
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
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>
This commit is contained in:
@@ -76,18 +76,21 @@ def price_items(items, names, catalog_now, manual_extra):
|
|||||||
"""Price the items without a database: price() per item with the product's
|
"""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
|
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."""
|
total, then apply_bands. Exactly as an order is charged."""
|
||||||
priced = []
|
priced, lengths = [], []
|
||||||
for item in items:
|
for item in items:
|
||||||
extra = manual_extra if pricing.is_manual(item, names) else 0
|
extra = manual_extra if pricing.is_manual(item, names) else 0
|
||||||
product = catalog_now[item['mode']]
|
product = catalog_now[item['mode']]
|
||||||
# Billed on the length less a ready sheet's gaps; `metres` stays the
|
# 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.
|
# film the layout uses, which the print file and the folders follow.
|
||||||
charged = pricing.price(item['mode'], str(pricing.billable_metres(item)), item['grade'], extra,
|
length = pricing.billable_metres(item)
|
||||||
minimum=Decimal('0') if item.get('split') else Decimal('1'),
|
charged = pricing.price(item['mode'], str(length), item['grade'], extra,
|
||||||
unit_cents=product['unit_cents'])
|
minimum=Decimal('0'), unit_cents=product['unit_cents'])
|
||||||
priced.append({**charged, 'metres': str(item['metres']),
|
priced.append({**charged, 'metres': str(item['metres']),
|
||||||
**({'split': item['split']} if item.get('split') else {})})
|
**({'split': item['split']} if item.get('split') else {})})
|
||||||
pricing.bill_splits(priced)
|
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 = {}
|
totals = {}
|
||||||
for item in priced:
|
for item in priced:
|
||||||
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
|
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
|
||||||
|
|||||||
@@ -105,6 +105,36 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec
|
|||||||
return priced
|
return priced
|
||||||
|
|
||||||
|
|
||||||
|
def bill_order(priced: list, lengths: list) -> list:
|
||||||
|
"""The order's metres (Marcus, 2026-12-03): each product's exact lengths
|
||||||
|
summed and rounded once (billed_length), the 1 m minimum once for the
|
||||||
|
order, on the first item's product. Each product's total is then shared
|
||||||
|
back to its items in 10 cm steps, for Tiny's SKUs and the cards: every
|
||||||
|
item its length rounded down, the missing steps to the largest fractions
|
||||||
|
(ties to the first item), the minimum's difference to the product's first
|
||||||
|
item (output/revisao/contrato-minimo-pedido.md)."""
|
||||||
|
if not priced:
|
||||||
|
return priced
|
||||||
|
steps = [Decimal(str(length)) * 10 for length in lengths]
|
||||||
|
modes = list(dict.fromkeys(item['mode'] for item in priced))
|
||||||
|
totals = {mode: billed_length(sum(Decimal(str(lengths[k])) for k, item in enumerate(priced)
|
||||||
|
if item['mode'] == mode)) for mode in modes}
|
||||||
|
short = Decimal('1') - sum(totals.values())
|
||||||
|
for mode in modes:
|
||||||
|
indexes = [k for k, item in enumerate(priced) if item['mode'] == mode]
|
||||||
|
shares = {k: int(steps[k].to_integral_value(rounding='ROUND_FLOOR')) for k in indexes}
|
||||||
|
missing = int(totals[mode] * 10) - sum(shares.values())
|
||||||
|
by_fraction = sorted(indexes, key=lambda k: (-(steps[k] - shares[k]), k))
|
||||||
|
for k in by_fraction[:missing]:
|
||||||
|
shares[k] += 1
|
||||||
|
if mode == priced[0]['mode'] and short > 0:
|
||||||
|
shares[indexes[0]] += int(short * 10)
|
||||||
|
for k in indexes:
|
||||||
|
billed = Decimal(shares[k]) / 10
|
||||||
|
priced[k].update(billed_metres=str(billed), total_cents=int(billed * priced[k]['unit_cents']))
|
||||||
|
return priced
|
||||||
|
|
||||||
|
|
||||||
def bill_splits(priced: list) -> list:
|
def bill_splits(priced: list) -> list:
|
||||||
"""The order minimum of 1 m once per split group, on its first sheet: the
|
"""The order minimum of 1 m once per split group, on its first sheet: the
|
||||||
customer did not choose the split (item 17), so it never costs a metre more."""
|
customer did not choose the split (item 17), so it never costs a metre more."""
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ from PIL import Image, ImageOps
|
|||||||
from .core.models import PRODUCTION_VERSIONS
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
from .core.pricing import STEP_GRACE_M, unbilled_gaps_cm
|
from .core.pricing import STEP_GRACE_M, unbilled_gaps_cm
|
||||||
|
|
||||||
|
# One 10 cm step: the most an item's share of its product's total falls short.
|
||||||
|
SHARE_STEP_CM = Decimal('10')
|
||||||
|
|
||||||
PT_PER_CM = 72 / 2.54
|
PT_PER_CM = 72 / 2.54
|
||||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
||||||
# real size, on one page: CorelDRAW, where Dropstar checks the files, ignores
|
# real size, on one page: CorelDRAW, where Dropstar checks the files, ignores
|
||||||
@@ -388,9 +391,12 @@ def check_layout(item, sizes, vector=(), proof=False):
|
|||||||
production = item['production']
|
production = item['production']
|
||||||
height = Decimal(str(production['height_cm']))
|
height = Decimal(str(production['height_cm']))
|
||||||
billed = Decimal(str(item['billed_metres'])) * 100
|
billed = Decimal(str(item['billed_metres'])) * 100
|
||||||
# Up to 8 mm past the billed length is the customer's grace, and a ready
|
# Up to 8 mm past the billed length is the customer's grace, a ready
|
||||||
# sheet's gaps are film not billed (app/core/pricing.py).
|
# sheet's gaps are film not billed, and since one rounding per product
|
||||||
allowed = billed + STEP_GRACE_M * 100 + unbilled_gaps_cm(production) + HEIGHT_TOLERANCE_CM
|
# (2026-12-03) an item's share is its length rounded down, short of it by
|
||||||
|
# less than one 10 cm step (app/core/pricing.py bill_order).
|
||||||
|
allowed = (billed + SHARE_STEP_CM + STEP_GRACE_M * 100 + unbilled_gaps_cm(production)
|
||||||
|
+ HEIGHT_TOLERANCE_CM)
|
||||||
if not proof and height > allowed:
|
if not proof and height > allowed:
|
||||||
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||||
lowest = None
|
lowest = None
|
||||||
|
|||||||
@@ -583,6 +583,10 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
|||||||
order = payload['order']
|
order = payload['order']
|
||||||
items = []
|
items = []
|
||||||
for item in order['items']:
|
for item in order['items']:
|
||||||
|
# A very short sheet can share 0 m of its product's total (one
|
||||||
|
# rounding per product, 2026-12-03): it has no line of its own.
|
||||||
|
if not Decimal(str(item['billed_metres'])):
|
||||||
|
continue
|
||||||
note = PRODUCTS[item['mode']] + f" · nota {item['grade']}"
|
note = PRODUCTS[item['mode']] + f" · nota {item['grade']}"
|
||||||
prefix, step = sku_prefix(item['mode']), step_sku(item['mode'])
|
prefix, step = sku_prefix(item['mode']), step_sku(item['mode'])
|
||||||
if step or prefix:
|
if step or prefix:
|
||||||
|
|||||||
@@ -621,6 +621,12 @@ try{
|
|||||||
}finally{carregarPdfJs=realLoader;window.setTimeout=realTimer;temWorker=realWorker;}
|
}finally{carregarPdfJs=realLoader;window.setTimeout=realTimer;temWorker=realWorker;}
|
||||||
})()`);
|
})()`);
|
||||||
assert.deepEqual(timeoutCleanup,{timedOut:true,destroyed:true});
|
assert.deepEqual(timeoutCleanup,{timedOut:true,destroyed:true});
|
||||||
|
// One rounding per product and the 1 m minimum once per order (Marcus,
|
||||||
|
// 2026-12-03): the same shares as app/core/pricing.py bill_order.
|
||||||
|
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:3.7364},{modo:'file',exato:0.2447},{modo:'file',exato:0.2164}])`),[3.7,0.3,0.2]);
|
||||||
|
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:0.25},{modo:'avulsa',exato:0.31}])`),[0.6,0.4]);
|
||||||
|
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:0.3}])`),[1]);
|
||||||
|
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:2.004},{modo:'file',exato:3.004}])`),[2,3]);
|
||||||
// Proof pop-up (Marcus, 2026-12-02): only above 10 m, not mandatory; closing
|
// Proof pop-up (Marcus, 2026-12-02): only above 10 m, not mandatory; closing
|
||||||
// it is going on without a proof, and the cart summary follows the answer.
|
// it is going on without a proof, and the cart summary follows the answer.
|
||||||
assert.deepEqual(await evaluate(`[pedidoLongo([{cob:10}]),pedidoLongo([{cob:6},{cob:4.5}])]`),[false,true]);
|
assert.deepEqual(await evaluate(`[pedidoLongo([{cob:10}]),pedidoLongo([{cob:6},{cob:4.5}])]`),[false,true]);
|
||||||
@@ -653,6 +659,6 @@ try{
|
|||||||
console.log('Supplied image:',JSON.stringify(layout));
|
console.log('Supplied image:',JSON.stringify(layout));
|
||||||
}
|
}
|
||||||
assert.deepEqual(errors,[]);
|
assert.deepEqual(errors,[]);
|
||||||
console.log('PASS: PNG upload and drop, JPG refused, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, proof pop-up above 10 m, stale renders, strict inline CSP.');
|
console.log('PASS: PNG upload and drop, JPG refused, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, proof pop-up above 10 m, one rounding per product, stale renders, strict inline CSP.');
|
||||||
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;}
|
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;}
|
||||||
finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));}
|
finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));}
|
||||||
|
|||||||
@@ -148,7 +148,11 @@ def carts():
|
|||||||
|
|
||||||
class CartPricingCharacterizationTest(unittest.TestCase):
|
class CartPricingCharacterizationTest(unittest.TestCase):
|
||||||
def test_price_items_matches_todays_approval(self):
|
def test_price_items_matches_todays_approval(self):
|
||||||
|
# Since 2026-12-03 the 1 m minimum is once per order, not per item:
|
||||||
|
# only a cart with an item under 1 m beside others bills differently.
|
||||||
for name, cart in carts().items():
|
for name, cart in carts().items():
|
||||||
|
if name == 'mixed-modes':
|
||||||
|
continue
|
||||||
with self.subTest(cart=name):
|
with self.subTest(cart=name):
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
price_items(cart['items'], cart['names'], cart['catalog'], cart['manual']),
|
price_items(cart['items'], cart['names'], cart['catalog'], cart['manual']),
|
||||||
@@ -170,6 +174,26 @@ class CartPricingCharacterizationTest(unittest.TestCase):
|
|||||||
floating = priced('band-floating-metres')[0]
|
floating = priced('band-floating-metres')[0]
|
||||||
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.8', 23800))
|
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.8', 23800))
|
||||||
|
|
||||||
|
def test_one_rounding_per_product_and_one_minimum_per_order(self):
|
||||||
|
# Marcus, 2026-12-03: "Soma tudo e arredonda uma vez só"; the minimum
|
||||||
|
# once for the order; products apart, each at its price ("Pode ser sim").
|
||||||
|
lengths = ['3.7364', '0.2447', '0.2164'] # order #246, three ready sheets
|
||||||
|
priced = price_items([item('file', m, uid=f'u{i}') for i, m in enumerate(lengths)],
|
||||||
|
{}, catalog_now(), 0)
|
||||||
|
self.assertEqual([p['billed_metres'] for p in priced], ['3.7', '0.3', '0.2'])
|
||||||
|
self.assertEqual(sum(p['total_cents'] for p in priced), 8358) # 4,20 m, not 5,80 m
|
||||||
|
# An item under 1 m beside others is not raised to 1 m any more.
|
||||||
|
mixed = carts()['mixed-modes']
|
||||||
|
priced = price_items(mixed['items'], mixed['names'], mixed['catalog'], 0)
|
||||||
|
self.assertEqual([p['billed_metres'] for p in priced], ['1', '2', '0.5', '3'])
|
||||||
|
# Alone under 1 m: the order minimum, on the first item.
|
||||||
|
self.assertEqual(price_items([item('file', '0.3')], {}, catalog_now(), 0)[0]['billed_metres'], '1')
|
||||||
|
# Two products under 1 m together: the difference on the first one's product.
|
||||||
|
priced = price_items([item('file', '0.25', uid='u1'), item('avulsa', '0.31', uid='u2')],
|
||||||
|
{'u1': 'A.PNG', 'u2': 'B.PNG'}, catalog_now(), 0)
|
||||||
|
self.assertEqual([p['billed_metres'] for p in priced], ['0.6', '0.4'])
|
||||||
|
self.assertEqual(sum(p['total_cents'] for p in priced), 6 * 199 + 4 * 219)
|
||||||
|
|
||||||
def test_a_ready_sheet_is_billed_without_its_gaps(self):
|
def test_a_ready_sheet_is_billed_without_its_gaps(self):
|
||||||
# Marcus, 2026-12-03 ("por hora pode tirar a cobrança"): the Lais case,
|
# Marcus, 2026-12-03 ("por hora pode tirar a cobrança"): the Lais case,
|
||||||
# one 100 cm sheet and another with 4 copies, 4 gaps of 8 mm = 503,2 cm.
|
# one 100 cm sheet and another with 4 copies, 4 gaps of 8 mm = 503,2 cm.
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class SheetGapTests(unittest.TestCase):
|
|||||||
item = sheet(copies=10).model_dump(mode='json')
|
item = sheet(copies=10).model_dump(mode='json')
|
||||||
item['billed_metres'] = '2'
|
item['billed_metres'] = '2'
|
||||||
check_layout(item, [(5700, 2000)])
|
check_layout(item, [(5700, 2000)])
|
||||||
item['billed_metres'] = '1.9'
|
item['billed_metres'] = '1.8' # more than one 10 cm step short
|
||||||
with self.assertRaises(Unsupported):
|
with self.assertRaises(Unsupported):
|
||||||
check_layout(item, [(5700, 2000)])
|
check_layout(item, [(5700, 2000)])
|
||||||
|
|
||||||
|
|||||||
@@ -660,6 +660,16 @@ class TinySkuTests(FakeTinyCase):
|
|||||||
self.tiny.deliver('k3', TEXTIL)
|
self.tiny.deliver('k3', TEXTIL)
|
||||||
self.assertNotIn(('POST', '/pedidos'), self.calls)
|
self.assertNotIn(('POST', '/pedidos'), self.calls)
|
||||||
|
|
||||||
|
def test_an_item_sharing_no_metres_has_no_line(self):
|
||||||
|
# One rounding per product (Marcus, 2026-12-03): a very short sheet
|
||||||
|
# beside others may share 0 m of the total; it adds no Tiny line.
|
||||||
|
self.tiny.deliver('k1', TEXTIL)
|
||||||
|
zero = {**TEXTIL['order']['items'][0], 'billed_metres': '0', 'total_cents': 0}
|
||||||
|
with_zero = {**TEXTIL, 'number': 43, 'order': {**TEXTIL['order'],
|
||||||
|
'items': TEXTIL['order']['items'] + [zero]}}
|
||||||
|
self.tiny.deliver('k2', with_zero)
|
||||||
|
self.assertEqual(len(self.orders[1]['itens']), len(self.orders[0]['itens']))
|
||||||
|
|
||||||
def test_other_modes_keep_their_product_id(self):
|
def test_other_modes_keep_their_product_id(self):
|
||||||
self.tiny.deliver('k4', PAID)
|
self.tiny.deliver('k4', PAID)
|
||||||
self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 102})
|
self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 102})
|
||||||
|
|||||||
@@ -154,16 +154,20 @@ function montarQuoteFigures(lines){
|
|||||||
});
|
});
|
||||||
const catalog=MONTAR.catalog?.avulsa;
|
const catalog=MONTAR.catalog?.avulsa;
|
||||||
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
|
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
|
||||||
// Every 10 cm, 8 mm in the customer's favour (app/core/pricing.py billed_length).
|
// The items' lengths summed and rounded once, every 10 cm with 8 mm in the
|
||||||
const billed=heights.map(metres=>Math.max(1,Math.ceil(+((metres-0.008)*10).toFixed(6))/10));
|
// customer's favour, and the 1 m minimum once for the order (Marcus,
|
||||||
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
|
// 2026-12-03; app/core/pricing.py bill_order). One product here: avulsa.
|
||||||
|
const exact=+heights.reduce((sum,metres)=>sum+metres,0).toFixed(6);
|
||||||
|
const total=heights.length?Math.max(1,Math.ceil(+((exact-0.008)*10).toFixed(6))/10):0;
|
||||||
let unit=catalog.unit_cents,best=null;
|
let unit=catalog.unit_cents,best=null;
|
||||||
for(const band of catalog.bands||[]){
|
for(const band of catalog.bands||[]){
|
||||||
const from=Number(band.from_metres);
|
const from=Number(band.from_metres);
|
||||||
if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;}
|
if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;}
|
||||||
}
|
}
|
||||||
return {metres:+heights.reduce((sum,metres)=>sum+metres,0).toFixed(4),
|
return {metres:+heights.reduce((sum,metres)=>sum+metres,0).toFixed(4),
|
||||||
cents:billed.reduce((sum,metres)=>sum+Math.floor(Number((metres*unit).toFixed(6))),0)};
|
// The shares of the total cost the total at one unit price, to the cent
|
||||||
|
// the server's per-item truncation may differ by: an estimate for freight.
|
||||||
|
cents:Math.floor(Number((total*unit).toFixed(6)))};
|
||||||
}
|
}
|
||||||
async function montarCatalog(){
|
async function montarCatalog(){
|
||||||
if(MONTAR.catalog)return MONTAR.catalog;
|
if(MONTAR.catalog)return MONTAR.catalog;
|
||||||
|
|||||||
@@ -247,6 +247,12 @@ function perguntaProva(){
|
|||||||
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
||||||
function pintaPedido(){
|
function pintaPedido(){
|
||||||
const aPagar = itensAPagar();
|
const aPagar = itensAPagar();
|
||||||
|
// Uma arredondada por produto e o mínimo de 1 m uma vez (03/12/2026): a
|
||||||
|
// parte de cada item depende do carrinho inteiro; um item desmarcado mostra
|
||||||
|
// o que pagaria sozinho.
|
||||||
|
const partes=cobrarPedido(aPagar.map(it=>({modo:it.modo, exato:exatoDoItem(it)})));
|
||||||
|
aPagar.forEach((it,k)=>{ it.cob=partes[k]; });
|
||||||
|
for(const it of pedido) if(!aPagar.includes(it)) it.cob=cobrarPedido([{modo:it.modo, exato:exatoDoItem(it)}])[0];
|
||||||
// Faixas progressivas (front 8.2): um preço só para todos os metros de um
|
// 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.
|
// produto no pedido, a mesma regra que o servidor cobra na aprovação.
|
||||||
const metrosPorModo={};
|
const metrosPorModo={};
|
||||||
|
|||||||
@@ -65,8 +65,13 @@
|
|||||||
// 10 cm, e até 8 mm a mais ficam por nossa conta.
|
// 10 cm, e até 8 mm a mais ficam por nossa conta.
|
||||||
const exata=n1(base*100)+' cm';
|
const exata=n1(base*100)+' cm';
|
||||||
const aMais=Math.round((base-it.cob)*1000);
|
const aMais=Math.round((base-it.cob)*1000);
|
||||||
$('cObs').textContent =
|
// Com outros itens do mesmo produto no carrinho, a metragem é a da soma,
|
||||||
it.cob===MINIMO_M && base<MINIMO_M
|
// arredondada uma vez só (Marcus, 03/12/2026).
|
||||||
|
const juntos=itensAPagar().some(x=>x!==it && x.modo===it.modo);
|
||||||
|
$('cObs').textContent = juntos
|
||||||
|
? (ehFolha(it.modo)?'A folha tem ':'A montagem tem ')+exata+
|
||||||
|
'. No carrinho, os itens deste produto somam e arredondam uma vez só, a cada 10 cm.'
|
||||||
|
: it.cob===MINIMO_M && base<MINIMO_M
|
||||||
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
|
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
|
||||||
: 'Pedido mínimo de 1 m: ainda cabem '+sobraCm+' cm de artes sem custo.')
|
: 'Pedido mínimo de 1 m: ainda cabem '+sobraCm+' cm de artes sem custo.')
|
||||||
: it.cob<base-1e-6
|
: it.cob<base-1e-6
|
||||||
|
|||||||
@@ -226,9 +226,36 @@ const larguraFilme=()=>MODOS[modo].larg;
|
|||||||
const TOLERANCIA_M=0.008;
|
const TOLERANCIA_M=0.008;
|
||||||
const arredonda10=m=>Math.max(0.1, Math.ceil(+((m-TOLERANCIA_M)*10).toFixed(6))/10);
|
const arredonda10=m=>Math.max(0.1, Math.ceil(+((m-TOLERANCIA_M)*10).toFixed(6))/10);
|
||||||
const cobrar=m=>Math.max(MINIMO_M, arredonda10(m));
|
const cobrar=m=>Math.max(MINIMO_M, arredonda10(m));
|
||||||
// Com as artes em folhas separadas por traço (item 17), cada folha arredonda
|
// O pedido (Marcus, 03/12/2026): os comprimentos de cada produto somam e
|
||||||
// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar.
|
// arredondam uma vez só, e o mínimo de 1 m vale uma vez, no produto do
|
||||||
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+arredonda10(+(f.alturaCm/100).toFixed(4)),0).toFixed(1));
|
// primeiro item. A parte de cada item, em passos de 10 cm: o seu comprimento
|
||||||
|
// para baixo, os passos que faltam para quem tem a maior fração, o que falta
|
||||||
|
// do mínimo para o primeiro item. A mesma conta do servidor
|
||||||
|
// (app/core/pricing.py bill_order). itens: [{modo, exato}] em metros.
|
||||||
|
function cobrarPedido(itens){
|
||||||
|
if(!itens.length) return [];
|
||||||
|
const passos=itens.map(it=>+(it.exato*10).toFixed(6));
|
||||||
|
const modos=[...new Set(itens.map(it=>it.modo))];
|
||||||
|
const totais={};
|
||||||
|
for(const m of modos) totais[m]=arredonda10(+itens.reduce((t,it)=>t+(it.modo===m?it.exato:0),0).toFixed(6));
|
||||||
|
const falta=Math.max(0, Math.round((MINIMO_M-modos.reduce((t,m)=>t+totais[m],0))*10));
|
||||||
|
const partes=passos.map(p=>Math.floor(p+1e-9));
|
||||||
|
for(const m of modos){
|
||||||
|
const idx=itens.map((it,k)=>it.modo===m?k:-1).filter(k=>k>=0);
|
||||||
|
const faltam=Math.round(totais[m]*10)-idx.reduce((t,k)=>t+partes[k],0);
|
||||||
|
const ordem=[...idx].sort((a,b)=>((passos[b]-partes[b])-(passos[a]-partes[a]))||a-b);
|
||||||
|
for(const k of ordem.slice(0,Math.max(0,faltam))) partes[k]++;
|
||||||
|
if(m===itens[0].modo && falta>0) partes[idx[0]]+=falta;
|
||||||
|
}
|
||||||
|
return partes.map(p=>p/10);
|
||||||
|
}
|
||||||
|
// O comprimento cobrável de um item do carrinho: a folha pronta sem os
|
||||||
|
// espaços, as folhas de traço somadas, a montagem das artes.
|
||||||
|
const exatoDoItem=it=>it.partes?.length ? +it.partes.reduce((t,p)=>t+(p.metros||0),0).toFixed(4)
|
||||||
|
: (it.cobravel ?? it.metros);
|
||||||
|
// Com as artes em folhas separadas por traço (item 17), as folhas somam e
|
||||||
|
// arredondam uma vez só, com o mínimo de 1 m (Marcus, 03/12/2026).
|
||||||
|
const cobrarFolhas=fs=>cobrar(+fs.reduce((t,f)=>t+f.alturaCm/100,0).toFixed(6));
|
||||||
const cobrarMontagem=()=>ehFolha() ? cobrar(folhaCobradaM())
|
const cobrarMontagem=()=>ehFolha() ? cobrar(folhaCobradaM())
|
||||||
: montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
|
: montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
|
||||||
const fmtM=m=>m.toFixed(2).replace('.',',');
|
const fmtM=m=>m.toFixed(2).replace('.',',');
|
||||||
|
|||||||
@@ -181,7 +181,7 @@ function alturaSimulada(cargas,W,modo){
|
|||||||
// Acima disso o cálculo do vão pesa no celular e a sobra é pequena.
|
// Acima disso o cálculo do vão pesa no celular e a sobra é pequena.
|
||||||
const VAO_MAX_PECAS=300;
|
const VAO_MAX_PECAS=300;
|
||||||
// C2 · as mesmas peças nas duas formas de encaixar, já na metragem cobrada.
|
// C2 · as mesmas peças nas duas formas de encaixar, já na metragem cobrada.
|
||||||
// Com as folhas de traço, cada folha arredonda sozinha e a soma tem o mínimo de 1 m.
|
// Com as folhas de traço, as folhas somam e arredondam uma vez, com o mínimo de 1 m.
|
||||||
let encaixeAlt=null; // {linhas, forma, alturasLinhas, alturasForma}
|
let encaixeAlt=null; // {linhas, forma, alturasLinhas, alturasForma}
|
||||||
let encaixeVao=[]; // C1: [{a,k}] cópias que cabem sem custo
|
let encaixeVao=[]; // C1: [{a,k}] cópias que cabem sem custo
|
||||||
let tVao=null;
|
let tVao=null;
|
||||||
|
|||||||
Reference in New Issue
Block a user