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

@@ -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