feat: discount coupons (front 8.3)
Gestão creates coupons in the Site tab: a code, a percentage or an amount per billed metre, validity, a minimum of metres, use limits in all and per customer, one product or all, and a note; they can be paused and deleted (kept for history). The customer types the code at checkout; the server checks it when the quote is made and again at approval, discounts only the eligible items after the bands (never freight or the treatment) and keeps the coupon on the order. Tiny gets the discount, the e-mail and receipt show it, the order panel carries a badge and Números counts orders, metres, discount and money per coupon. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
let requestBody = localStorage.getItem('dtf-request-body');
|
||||
let quotedCart = localStorage.getItem('dtf-quote-cart');
|
||||
let refreshVersion = 0;
|
||||
const cupomCode=()=>{const el=document.getElementById('fCupom');return el?el.value.trim().toUpperCase():'';};
|
||||
function cartSnapshot() {
|
||||
const items=itensAPagar();
|
||||
return JSON.stringify({customer:cliente,delivery:entrega,items:items.map(item=>({
|
||||
@@ -26,7 +27,7 @@
|
||||
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
|
||||
sheets:(item.partes||[]).map(part=>part.production),
|
||||
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
|
||||
})),treatment:!!$('fTratamento')?.checked});
|
||||
})),treatment:!!$('fTratamento')?.checked,coupon:cupomCode()});
|
||||
}
|
||||
// The quote this browser is paying, forgotten. clearDraft also empties the
|
||||
// payment area; forgetDraft leaves on screen what is there (a confirmation).
|
||||
@@ -171,6 +172,8 @@
|
||||
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
|
||||
if(quote.treatment?.cents)
|
||||
rows.push(linha('Tratamento da arte pelo designer · +24 h', rs(quote.treatment.cents/100)));
|
||||
if(approved.coupon)
|
||||
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
|
||||
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
||||
const prumoBox=node('div',null,'prumoResumo');
|
||||
if(quote.prumo?.length){
|
||||
@@ -421,7 +424,9 @@
|
||||
}
|
||||
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
|
||||
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
|
||||
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
|
||||
const cupom=cupomCode();
|
||||
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep},
|
||||
...(cupom?{coupon:cupom}:{})};
|
||||
const destination = destinoApi();
|
||||
if (destination) content.destination = destination;
|
||||
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||
@@ -757,5 +762,13 @@
|
||||
else if (!busy) { refreshVersion++; clearInterval(pixClock); message(''); actions.replaceChildren(); pintaResumo(null); }
|
||||
if (!naPagina() && semPedidos) message('No momento não estamos recebendo pedidos pelo site.','warn');
|
||||
});
|
||||
// "Aplicar" sends the coupon with the cart: there is no public route to test
|
||||
// a code, so the server's answer comes with the quote (front 8.3).
|
||||
const aplicarCupom=document.getElementById('bCupom');
|
||||
if(aplicarCupom)aplicarCupom.onclick=()=>window.dtfCheckout();
|
||||
const campoCupom=document.getElementById('fCupom');
|
||||
if(campoCupom)campoCupom.addEventListener('keydown',e=>{
|
||||
if(e.key==='Enter'){e.preventDefault();window.dtfCheckout();}
|
||||
});
|
||||
refresh();
|
||||
})();
|
||||
|
||||
@@ -1089,6 +1089,19 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cxE">
|
||||
<h4>Cupom</h4>
|
||||
<div class="campos">
|
||||
<div class="cp larga">
|
||||
<label for="fCupom">Código do cupom</label>
|
||||
<div class="cepL">
|
||||
<input id="fCupom" autocomplete="off" maxlength="30" placeholder="Ex.: REINA-2026">
|
||||
<button type="button" id="bCupom">Aplicar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cxE">
|
||||
<h4>Prova antes de imprimir</h4>
|
||||
<label class="provaOp"><input type="checkbox" id="fProva">
|
||||
|
||||
@@ -148,11 +148,156 @@ function sitePriceBlock(product){
|
||||
return block;
|
||||
}
|
||||
|
||||
// ── Cupons (front 8.3) ──────────────────────────────────────────────────────
|
||||
// A "ficha" of the date in the browser's timezone, for datetime-local inputs.
|
||||
function couponDate(iso){
|
||||
const d=new Date(iso),p=n=>String(n).padStart(2,'0');
|
||||
return d.getFullYear()+'-'+p(d.getMonth()+1)+'-'+p(d.getDate())+'T'+p(d.getHours())+':'+p(d.getMinutes());
|
||||
}
|
||||
|
||||
function ensureCouponsPanel(){
|
||||
let panel=$('site-coupons-panel');
|
||||
if(panel)return panel;
|
||||
panel=node('section',undefined,'panel clip');panel.id='site-coupons-panel';
|
||||
const head=node('div',undefined,'phead');
|
||||
head.append(node('h2','Cupons'),button('Novo cupom',()=>couponDialog(null),'btn right'));
|
||||
panel.append(head,node('p','Cupons de desconto do checkout: validade, mínimo de metros, limite de usos e produto. Um cupom por pedido.','phint'));
|
||||
const list=node('div',undefined,'siteCouponList');list.id='site-coupons';panel.append(list);
|
||||
const videos=$('site-videos-panel');
|
||||
if(videos)videos.before(panel); else $('tab-site').append(panel);
|
||||
return panel;
|
||||
}
|
||||
|
||||
function couponRow(coupon){
|
||||
const expired=coupon.valid_until && new Date(coupon.valid_until)<=new Date();
|
||||
const status=coupon.paused?['Pausado','warn']:expired?['Expirado','']:['Ativo','ok'];
|
||||
const row=node('div',undefined,'siteCouponRow');
|
||||
const top=node('div',undefined,'siteCouponTop');
|
||||
top.append(node('b',coupon.code),badge(status[0],status[1]),
|
||||
node('span',coupon.kind==='percent'?coupon.value+'%':money(coupon.value)+'/m','siteCouponOffer'));
|
||||
const meta=node('div',undefined,'siteCouponMeta');
|
||||
meta.append(node('span','Validade: de '+when(coupon.valid_from)+
|
||||
(coupon.valid_until?' até '+when(coupon.valid_until):' sem fim')),
|
||||
node('span','Produto: '+(coupon.product?SHORT[coupon.product]:'todos')),
|
||||
node('span','Usos: '+coupon.uses+(coupon.max_uses?' de '+coupon.max_uses:'')));
|
||||
const actions=node('div',undefined,'siteCouponActions');
|
||||
actions.append(button(coupon.paused?'Retomar':'Pausar',async()=>{
|
||||
await api('/site/coupons/'+coupon.id,{paused:!coupon.paused});
|
||||
say('Cupom '+coupon.code+(coupon.paused?' retomado.':' pausado.'));
|
||||
await loadSiteCoupons();
|
||||
},'btn'),
|
||||
button('Editar',()=>couponDialog(coupon),'btn ghost'),
|
||||
button('Apagar',async()=>{
|
||||
if(!(await ask('Apagar cupom',
|
||||
'O cupom '+coupon.code+' deixa de valer. Os pedidos que já o usaram continuam no histórico.',
|
||||
'Apagar',{tone:'red'})))return;
|
||||
await api('/site/coupons/'+coupon.id+'/delete',{});
|
||||
say('Cupom '+coupon.code+' apagado.');
|
||||
await loadSiteCoupons();
|
||||
},'btn quiet'));
|
||||
row.append(top,meta,actions);
|
||||
if(coupon.note)row.append(node('p',coupon.note,'siteCouponNote'));
|
||||
return row;
|
||||
}
|
||||
|
||||
function couponDialog(coupon){
|
||||
const editing=!!coupon;
|
||||
const code=node('input');code.maxLength=30;code.value=coupon?coupon.code:'';code.placeholder='Ex.: REINA-2026';
|
||||
if(editing)code.disabled=true;
|
||||
const kind=node('select');
|
||||
for(const [value,label] of [['percent','Porcentagem (%)'],['per_metre','Por metro (R$)']]){
|
||||
const option=node('option',label);option.value=value;kind.append(option);
|
||||
}
|
||||
kind.value=coupon?coupon.kind:'percent';
|
||||
const pct=node('input');pct.type='number';pct.min='1';pct.max='90';pct.step='1';
|
||||
pct.value=coupon&&coupon.kind==='percent'?String(coupon.value):'';
|
||||
const price=node('input');price.type='text';price.inputMode='decimal';price.placeholder='2,00';
|
||||
if(coupon&&coupon.kind==='per_metre')price.value=(coupon.value/100).toFixed(2).replace('.',',');
|
||||
const from=node('input');from.type='datetime-local';from.value=coupon?couponDate(coupon.valid_from):'';
|
||||
const until=node('input');until.type='datetime-local';
|
||||
until.value=coupon&&coupon.valid_until?couponDate(coupon.valid_until):'';
|
||||
const min=node('input');min.type='text';min.inputMode='decimal';min.placeholder='5';
|
||||
if(coupon&&coupon.min_metres!=null)min.value=String(coupon.min_metres).replace('.',',');
|
||||
const max=node('input');max.type='number';max.min='1';max.step='1';
|
||||
max.value=coupon&&coupon.max_uses?String(coupon.max_uses):'';
|
||||
const per=node('input');per.type='number';per.min='1';per.step='1';
|
||||
per.value=coupon&&coupon.max_uses_per_customer?String(coupon.max_uses_per_customer):'';
|
||||
const product=node('select');
|
||||
for(const [value,label] of [['','Todos os produtos'],...Object.entries(SHORT)]){
|
||||
const option=node('option',label);option.value=value;product.append(option);
|
||||
}
|
||||
product.value=coupon?coupon.product||'':'';
|
||||
const note=node('textarea');note.maxLength=1000;note.value=coupon?coupon.note:'';
|
||||
const pctField=field('Desconto (%)',pct,'De 1 a 90.');
|
||||
const priceField=field('Desconto por metro (R$)',price,'Valor em reais por metro, como 2,00.');
|
||||
const paint=()=>{pctField.hidden=kind.value!=='percent';priceField.hidden=kind.value!=='per_metre';};
|
||||
kind.onchange=paint;paint();
|
||||
const fields=[
|
||||
field('Código',code,editing?'O código não muda depois de criado.':'De 3 a 30 letras, números ou hífens.'),
|
||||
field('Tipo de desconto',kind),
|
||||
pctField,priceField,
|
||||
field('Válido a partir de',from,'Vazio: agora.'),
|
||||
field('Válido até',until,'Vazio: sem fim.'),
|
||||
field('Mínimo de metros',min,'Vazio: sem mínimo. Conta só os metros dos itens do produto.'),
|
||||
field('Limite de usos',max,'Vazio: sem limite.'),
|
||||
field('Limite por cliente',per,'Vazio: sem limite.'),
|
||||
field('Produto',product,'Todos os produtos, ou só um.'),
|
||||
field('Observação',note,'Aparece só no Kanban.'),
|
||||
];
|
||||
formDialog(editing?'Editar cupom':'Novo cupom',{width:640,fields,label:'Salvar cupom',onsave:async()=>{
|
||||
const rawMin=min.value.trim().replace(',','.');
|
||||
const payload={
|
||||
kind:kind.value,
|
||||
value:kind.value==='percent'?Number(pct.value):moneyInputCents(price.value),
|
||||
valid_from:from.value?new Date(from.value).toISOString():null,
|
||||
valid_until:until.value?new Date(until.value).toISOString():null,
|
||||
min_metres:rawMin||null,
|
||||
max_uses:max.value.trim()?Number(max.value):null,
|
||||
max_uses_per_customer:per.value.trim()?Number(per.value):null,
|
||||
product:product.value||null,
|
||||
note:note.value.trim(),
|
||||
};
|
||||
if(kind.value==='percent'&&(!Number.isInteger(payload.value)||payload.value<1||payload.value>90))
|
||||
throw new Error('A porcentagem precisa ser de 1 a 90.');
|
||||
if(kind.value==='per_metre'&&(payload.value===null||payload.value<=0))
|
||||
throw new Error('Informe o desconto por metro em reais, como 2,00.');
|
||||
if(rawMin&&!/^\d+([.,]\d)?$/.test(rawMin))
|
||||
throw new Error('O mínimo de metros usa no máximo uma casa decimal.');
|
||||
if(payload.min_metres!==null&&(!Number.isFinite(Number(payload.min_metres))||Number(payload.min_metres)<=0))
|
||||
throw new Error('O mínimo de metros precisa ser maior que zero.');
|
||||
if(payload.max_uses!==null&&(!Number.isInteger(payload.max_uses)||payload.max_uses<=0))
|
||||
throw new Error('O limite de usos precisa ser um número inteiro maior que zero.');
|
||||
if(payload.max_uses_per_customer!==null&&
|
||||
(!Number.isInteger(payload.max_uses_per_customer)||payload.max_uses_per_customer<=0))
|
||||
throw new Error('O limite por cliente precisa ser um número inteiro maior que zero.');
|
||||
if(editing){
|
||||
await api('/site/coupons/'+coupon.id,payload);
|
||||
}else{
|
||||
const clean=code.value.trim().toUpperCase();
|
||||
if(!/^[A-Z0-9-]{3,30}$/.test(clean))
|
||||
throw new Error('O código precisa ter de 3 a 30 letras, números ou hífens.');
|
||||
await api('/site/coupons',{code:clean,...payload});
|
||||
}
|
||||
say(editing?'Cupom salvo.':'Cupom criado.');
|
||||
await loadSiteCoupons();
|
||||
}});
|
||||
}
|
||||
|
||||
async function loadSiteCoupons(){
|
||||
if(!may('manage'))return;
|
||||
ensureCouponsPanel();
|
||||
const data=await api('/site/coupons');
|
||||
const host=$('site-coupons');
|
||||
host.replaceChildren(...(data.coupons.length?data.coupons.map(couponRow)
|
||||
:[node('p','Nenhum cupom criado ainda.','empty')]));
|
||||
}
|
||||
|
||||
async function loadSiteAdmin(){
|
||||
if(!may('manage'))return;
|
||||
const data=await api('/site/products');
|
||||
$('site-products').replaceChildren(...data.products.map(siteProductRow));
|
||||
$('site-prices').replaceChildren(...data.products.map(sitePriceBlock));
|
||||
await loadSiteCoupons();
|
||||
await loadSiteVideos();
|
||||
}
|
||||
|
||||
|
||||
@@ -663,6 +663,15 @@ label.fopt{cursor:pointer;user-select:none}
|
||||
#tab-site .siteScheduledRow .btn{height:30px;padding:0 10px;font-size:12.5px}
|
||||
#tab-site .siteHistory{display:flex;flex-direction:column;gap:6px}
|
||||
#tab-site .siteHistory h4{margin:0;font-size:12.5px;font-weight:600;color:var(--tx3)}
|
||||
#tab-site .siteCouponList{display:flex;flex-direction:column;padding:0 18px 18px}
|
||||
#tab-site .siteCouponRow{display:flex;flex-direction:column;gap:8px;padding:16px 0;border-top:1px solid var(--ln)}
|
||||
#tab-site .siteCouponTop{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
||||
#tab-site .siteCouponTop b{font-size:14px}
|
||||
#tab-site .siteCouponOffer{font-size:13.5px;font-weight:650;color:var(--tx2)}
|
||||
#tab-site .siteCouponMeta{display:flex;gap:16px;flex-wrap:wrap;font-size:12.5px;color:var(--tx3)}
|
||||
#tab-site .siteCouponActions{display:flex;gap:8px;flex-wrap:wrap}
|
||||
#tab-site .siteCouponActions .btn{height:32px;padding:0 10px;font-size:12.5px}
|
||||
#tab-site .siteCouponNote{margin:0;font-size:13px;color:var(--tx2)}
|
||||
#tab-site .siteHistory .table{font-size:13px}
|
||||
#tab-site .siteHistory .table th,#tab-site .siteHistory .table td{padding:8px 12px}
|
||||
.page>*{flex-shrink:0}
|
||||
|
||||
@@ -1426,6 +1426,8 @@ function renderPanel(order){
|
||||
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
|
||||
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
|
||||
sub.append(paid,node('span','Entrou pelo '+(ORIGINS[order.origin]||order.origin)),code,theirs);
|
||||
if(s.coupon && !order.proof_parent)
|
||||
sub.append(badge('Cupom '+s.coupon.code,'','Desconto de '+money(s.coupon.discount_cents)));
|
||||
if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
|
||||
if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
|
||||
const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas');
|
||||
@@ -3274,6 +3276,30 @@ async function loadStats(){
|
||||
node('td',String(s.samples),'r'));
|
||||
if(!s.samples)tr.classList.add('off');
|
||||
return tr;}));
|
||||
// Coupons of the period (front 8.3): the page's sections live in the HTML,
|
||||
// so this panel is built here once and kept beside "Pedidos sem pagamento".
|
||||
let couponPanel=$('stats-coupons-panel');
|
||||
if(!couponPanel){
|
||||
couponPanel=node('section',undefined,'panel clip');couponPanel.id='stats-coupons-panel';
|
||||
const head=node('div',undefined,'phead');head.append(node('h2','Cupons'));
|
||||
const table=node('table',undefined,'table');
|
||||
const thead=node('thead'),headRow=node('tr');
|
||||
for(const [label,cls] of [['Cupom',''],['Pedidos','r'],['Metros','r'],['Desconto','r'],['Recebido','r']])
|
||||
headRow.append(node('th',label,cls));
|
||||
thead.append(headRow);
|
||||
const tbody=node('tbody');tbody.id='stats-coupons';
|
||||
table.append(thead,tbody);
|
||||
couponPanel.append(head,node('p','Cupons usados pelos pedidos pagos do período.','phint'),table);
|
||||
const anchor=$('stats-unpaid')?.closest('section');
|
||||
if(anchor)anchor.after(couponPanel);else $('tab-stats').append(couponPanel);
|
||||
}
|
||||
const couponRows=data.coupons||[];
|
||||
$('stats-coupons').replaceChildren(...(couponRows.length?couponRows.map(coupon=>{
|
||||
const tr=node('tr');
|
||||
tr.append(node('td',coupon.code),node('td',String(coupon.orders),'r'),
|
||||
node('td',metres(coupon.metres).replace(' m',''),'r'),
|
||||
node('td',money(coupon.discount_cents),'r'),node('td',money(coupon.cents),'r'));
|
||||
return tr;}):[emptyRow('Nenhum cupom usado no período.',5)]));
|
||||
}
|
||||
const emptyRow=(text,span)=>{const tr=node('tr');const td=node('td',text,'empty');td.colSpan=span;tr.append(td);return tr;};
|
||||
// Metres per day: one series of columns from one baseline, the period's
|
||||
|
||||
Reference in New Issue
Block a user