diff --git a/app/cart_pricing.py b/app/cart_pricing.py index cb0d46e..2c06fc0 100644 --- a/app/cart_pricing.py +++ b/app/cart_pricing.py @@ -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 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 = [] + priced, lengths = [], [] for item in items: extra = manual_extra if pricing.is_manual(item, names) else 0 product = catalog_now[item['mode']] # Billed on the length less a ready sheet's gaps; `metres` stays the # film the layout uses, which the print file and the folders follow. - charged = pricing.price(item['mode'], str(pricing.billable_metres(item)), item['grade'], extra, - minimum=Decimal('0') if item.get('split') else Decimal('1'), - unit_cents=product['unit_cents']) + length = pricing.billable_metres(item) + charged = pricing.price(item['mode'], str(length), item['grade'], extra, + minimum=Decimal('0'), unit_cents=product['unit_cents']) priced.append({**charged, 'metres': str(item['metres']), **({'split': item['split']} if item.get('split') else {})}) - 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 = {} for item in priced: totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres']) diff --git a/app/core/pricing.py b/app/core/pricing.py index 49170c9..aaf43ec 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -105,6 +105,36 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec 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: """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.""" diff --git a/app/printfile.py b/app/printfile.py index e672804..ef99ed6 100644 --- a/app/printfile.py +++ b/app/printfile.py @@ -29,6 +29,9 @@ from PIL import Image, ImageOps from .core.models import PRODUCTION_VERSIONS 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 # 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 @@ -388,9 +391,12 @@ def check_layout(item, sizes, vector=(), proof=False): production = item['production'] height = Decimal(str(production['height_cm'])) billed = Decimal(str(item['billed_metres'])) * 100 - # Up to 8 mm past the billed length is the customer's grace, and a ready - # sheet's gaps are film not billed (app/core/pricing.py). - allowed = billed + STEP_GRACE_M * 100 + unbilled_gaps_cm(production) + HEIGHT_TOLERANCE_CM + # Up to 8 mm past the billed length is the customer's grace, a ready + # sheet's gaps are film not billed, and since one rounding per product + # (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: raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados') lowest = None diff --git a/app/tiny.py b/app/tiny.py index d7ba31e..a096815 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -583,6 +583,10 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non order = payload['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']}" prefix, step = sku_prefix(item['mode']), step_sku(item['mode']) if step or prefix: diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index 2e9c0d7..f084064 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -621,6 +621,12 @@ try{ }finally{carregarPdfJs=realLoader;window.setTimeout=realTimer;temWorker=realWorker;} })()`); 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 // 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]); @@ -653,6 +659,6 @@ try{ console.log('Supplied image:',JSON.stringify(layout)); } 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;} finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));} diff --git a/tests/test_cart_pricing.py b/tests/test_cart_pricing.py index 3231ac3..4fbd93d 100644 --- a/tests/test_cart_pricing.py +++ b/tests/test_cart_pricing.py @@ -148,7 +148,11 @@ def carts(): class CartPricingCharacterizationTest(unittest.TestCase): 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(): + if name == 'mixed-modes': + continue with self.subTest(cart=name): self.assertEqual( price_items(cart['items'], cart['names'], cart['catalog'], cart['manual']), @@ -170,6 +174,26 @@ class CartPricingCharacterizationTest(unittest.TestCase): floating = priced('band-floating-metres')[0] 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): # 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. diff --git a/tests/test_sheet_gap.py b/tests/test_sheet_gap.py index 225bba4..a4be952 100644 --- a/tests/test_sheet_gap.py +++ b/tests/test_sheet_gap.py @@ -37,7 +37,7 @@ class SheetGapTests(unittest.TestCase): item = sheet(copies=10).model_dump(mode='json') item['billed_metres'] = '2' 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): check_layout(item, [(5700, 2000)]) diff --git a/tests/test_tiny.py b/tests/test_tiny.py index d892cac..6d71aad 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -660,6 +660,16 @@ class TinySkuTests(FakeTinyCase): self.tiny.deliver('k3', TEXTIL) 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): self.tiny.deliver('k4', PAID) self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 102}) diff --git a/web/kanban-montador.js b/web/kanban-montador.js index bea6886..9c385b0 100644 --- a/web/kanban-montador.js +++ b/web/kanban-montador.js @@ -154,16 +154,20 @@ function montarQuoteFigures(lines){ }); const catalog=MONTAR.catalog?.avulsa; 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). - const billed=heights.map(metres=>Math.max(1,Math.ceil(+((metres-0.008)*10).toFixed(6))/10)); - const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2); + // The items' lengths summed and rounded once, every 10 cm with 8 mm in the + // customer's favour, and the 1 m minimum once for the order (Marcus, + // 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; for(const band of catalog.bands||[]){ const from=Number(band.from_metres); if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;} } 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(){ if(MONTAR.catalog)return MONTAR.catalog; diff --git a/web/site-cart.js b/web/site-cart.js index 2eabafc..fb18b8d 100644 --- a/web/site-cart.js +++ b/web/site-cart.js @@ -247,6 +247,12 @@ function perguntaProva(){ // O carrinho junta itens de produtos diferentes e cobra uma vez só. function pintaPedido(){ 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 // produto no pedido, a mesma regra que o servidor cobra na aprovação. const metrosPorModo={}; diff --git a/web/site-compra.js b/web/site-compra.js index 3ac0c3e..1127132 100644 --- a/web/site-compra.js +++ b/web/site-compra.js @@ -65,8 +65,13 @@ // 10 cm, e até 8 mm a mais ficam por nossa conta. const exata=n1(base*100)+' cm'; const aMais=Math.round((base-it.cob)*1000); - $('cObs').textContent = - it.cob===MINIMO_M && basex!==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 && baseMODOS[modo].larg; const TOLERANCIA_M=0.008; 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)); -// Com as artes em folhas separadas por traço (item 17), cada folha arredonda -// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar. -const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+arredonda10(+(f.alturaCm/100).toFixed(4)),0).toFixed(1)); +// O pedido (Marcus, 03/12/2026): os comprimentos de cada produto somam e +// arredondam uma vez só, e o mínimo de 1 m vale uma vez, no produto do +// 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()) : montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros); const fmtM=m=>m.toFixed(2).replace('.',','); diff --git a/web/site-packing.js b/web/site-packing.js index de0b3ab..0a2d87f 100644 --- a/web/site-packing.js +++ b/web/site-packing.js @@ -181,7 +181,7 @@ function alturaSimulada(cargas,W,modo){ // Acima disso o cálculo do vão pesa no celular e a sobra é pequena. const VAO_MAX_PECAS=300; // 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 encaixeVao=[]; // C1: [{a,k}] cópias que cabem sem custo let tVao=null;