Files
dtf-system/web/site-cart.js
Cauê Faleiros 4283c93526
All checks were successful
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Successful in 10m50s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 2m6s
copy: the Site says the fact and the next step, in the redesign's words
Help, editor notices, cart, checkout and Minha conta rewritten by the
approved copy guide: no "a gente", no em dashes, no rhetorical questions,
who acts is clear, at most two sentences per notice. The proof text says
30 cm (was 15 cm) and the billed length no longer says it only rounds up
(8 mm grace). Buttons follow the redesign: "Imprimir assim mesmo",
"Subir em dois arquivos".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:28:26 -03:00

390 lines
19 KiB
JavaScript

/* Site DTF — Cart totals and the order summary.
Extracted verbatim from the single inline script in web/index.html.
Loaded as classic scripts in the order listed there: they share one global
scope and run top to bottom, exactly as the original did. */
// ── carrinho
let itemAtual=null;
// Ajuste Fino (front 1a) and Ajuste Fino Redesenho (front 1b): each art may
// be chosen under its warning, or the general switch chooses every art of the
// paying items for the basic service.
function artesDoItem(it){
if(it.partes && it.partes.length)
return it.partes.reduce((t,p)=>t+((p.production&&p.production.sources||[]).length),0);
return (it.production&&it.production.sources||[]).length;
}
function artesSelecionadas(aPagar=itensAPagar()){
if(ajusteTudo) return aPagar.reduce((t,it)=>t+artesDoItem(it),0);
return aPagar.reduce((t,it)=>{
if(it.partes && it.partes.length)
return t+it.partes.reduce((s,p)=>s+(p.ajusteSources||[]).length,0);
return t+(it.ajusteSources||[]).length;
},0);
}
function redesenhosSelecionados(aPagar=itensAPagar()){
return aPagar.reduce((t,it)=>{
if(it.partes && it.partes.length)
return t+it.partes.reduce((s,p)=>s+(p.redesenhoSources||[]).length,0);
return t+(it.redesenhoSources||[]).length;
},0);
}
// While a product is open, its files are not in the cart yet; the rule must
// still see the arts the customer already checked under their warnings.
function artesEscolhidasNaTela(){
if(!modo) return 0;
return (ehFolha()?folhas:artes).filter(x=>x.ajuste).length;
}
function redesenhosEscolhidosNaTela(){
if(!modo) return 0;
return (ehFolha()?folhas:artes).filter(x=>x.redesenho).length;
}
// What the cart snapshot compares: the switch and every chosen source.
function ajusteSnapshot(){
return {tudo:!!ajusteTudo, itens:itensAPagar().map(it=>({
escolhas:it.ajusteSources||[],
redesenhos:it.redesenhoSources||[],
partes:(it.partes||[]).map(p=>({escolhas:p.ajusteSources||[], redesenhos:p.redesenhoSources||[]}))
}))};
}
// A final cart item (after a split sheet becomes its own items) to the pairs.
function tratamentoParaItens(itens){
if(!(TAXA_TRATAMENTO>0)) return false;
if(ajusteTudo) return true;
const pairs=[];
itens.forEach((it,itemIndex)=>{
for(const source of it.ajusteSources||[]) pairs.push([itemIndex,source]);
});
return pairs.length?pairs:false;
}
function redesenhoParaItens(itens){
if(!(TAXA_REDESENHO>0)) return false;
const pairs=[];
itens.forEach((it,itemIndex)=>{
for(const source of it.redesenhoSources||[]) pairs.push([itemIndex,source]);
});
return pairs.length?pairs:false;
}
function materializaAjuste(){
if(!ajusteTudo) return;
ajusteTudo=false;
for(const it of itensAPagar()){
if(it.partes && it.partes.length){
for(const part of it.partes)
part.ajusteSources=Array.from({length:(part.production&&part.production.sources||[]).length},(_,i)=>i);
}else{
it.ajusteSources=Array.from({length:(it.production&&it.production.sources||[]).length},(_,i)=>i);
}
}
for(const x of folhas){x.ajuste=true;x.redesenho=false;}
for(const a of artes){a.ajuste=true;a.redesenho=false;}
}
function limpaAjuste(){
ajusteTudo=false;
for(const it of itensAPagar()){
it.ajusteSources=[];
for(const part of it.partes||[]) part.ajusteSources=[];
}
for(const x of folhas) x.ajuste=false;
for(const a of artes) a.ajuste=false;
}
function limpaRedesenho(){
for(const it of itensAPagar()){
it.redesenhoSources=[];
for(const part of it.partes||[]) part.redesenhoSources=[];
}
for(const x of folhas) x.redesenho=false;
for(const a of artes) a.redesenho=false;
}
// Update the per-art boxes without repainting the list, which would discard
// the item the customer is still building.
function pintaAjusteCheckboxes(){
document.querySelectorAll('[data-ajuste]').forEach(el=>{
const x=folhas[+el.dataset.ajuste]; if(x)el.checked=ajusteTudo||!!x.ajuste;
});
document.querySelectorAll('[data-ajustea]').forEach(el=>{
const a=artes[+el.dataset.ajustea]; if(a)el.checked=ajusteTudo||!!a.ajuste;
});
document.querySelectorAll('[data-redesenho]').forEach(el=>{
const x=folhas[+el.dataset.redesenho]; if(x)el.checked=!!x.redesenho;
});
document.querySelectorAll('[data-redesenhoa]').forEach(el=>{
const a=artes[+el.dataset.redesenhoa]; if(a)el.checked=!!a.redesenho;
});
}
function invalidaItemAtual(){
if(!itemAtual) return;
itemAtual=null;
$('atual').style.display='none';
$('carrLin').innerHTML='';
pintaPedido();
}
function itemPodeEnviar(item){
if(semMargem(item)) return false;
return item.qualityStatus==='ok' || item.qualityStatus==='unverified' ||
(item.qualityStatus==='warning' && item.qualityAcknowledged===true);
}
// Uma folha pronta guardada no carrinho antes dos 8 mm entre as cópias
// (27/11/2026): o servidor a recusa no pagamento, então o carrinho diz já,
// no próprio item, para refazê-lo (Sentry DTF-WEB-22).
function semMargem(item){
if(!['file','uvfile','premium'].includes(item.modo) || !item.production?.placements) return false;
const ps=[...item.production.placements].sort((a,b)=>a.y_cm-b.y_cm);
return ps.some((p,i)=>i>0 && p.y_cm < ps[i-1].y_cm+ps[i-1].length_cm+MARGEM_FOLHA_CM-0.02);
}
// Os itens marcados no carrinho são os que vão para o pagamento; um item
// desmarcado fica guardado para depois. O item aberto no produto sempre vai.
function itensAPagar(){
return [...pedido.filter(it=>it.marcado!==false),...(itemAtual?[itemAtual]:[])];
}
function cartPodeEnviar(){
const items=itensAPagar();
return items.length>0 && items.every(itemPodeEnviar);
}
function limpaPaineis(){
invalidaItemAtual();
['qual','prev'].forEach(id=>$(id).classList.remove('on'));
if(!pedido.length){ $('carr').classList.remove('on'); }
}
// Front 8.5: when the worst grade of the paying items is below the rule and
// Ajuste Fino is offered, it is required. The simple rule the server keeps:
// at least one art must be chosen, basic or Redesenho; with none, the general
// switch selects every art for the basic service.
function mostraAvisoTratamento(texto){
const box=$('tratamentoBox'); if(!box)return;
let el=$('tratamentoAviso');
if(!el){el=document.createElement('p');el.id='tratamentoAviso';el.className='avisoF';box.append(el);}
el.textContent=texto;el.hidden=!texto;
}
function aplicaTratamento(aPagar){
const box=$('tratamentoBox'), check=$('fTratamento');
if(!box||!check)return;
const offered=TAXA_TRATAMENTO>0;
const rule=Number(window.dtfGradeRules?.tratamento)||0;
const grades=aPagar.map(it=>Number(it.nota)||0);
const worst=grades.length?Math.min(...grades):null;
const required=offered&&rule>0&&worst!==null&&worst<rule;
box.hidden=!offered;
if(!(TAXA_REDESENHO>0)) limpaRedesenho();
if(!offered){
check.checked=false;check.disabled=false;
ajusteTudo=false;
for(const it of aPagar){
it.ajusteSources=[];
for(const part of it.partes||[]) part.ajusteSources=[];
}
for(const x of folhas) x.ajuste=false;
for(const a of artes) a.ajuste=false;
mostraAvisoTratamento('');
}else if(required){
const chosen=!!ajusteTudo || artesSelecionadas(aPagar)>0 || artesEscolhidasNaTela()>0 ||
redesenhosSelecionados(aPagar)>0 || redesenhosEscolhidosNaTela()>0;
if(!chosen){
ajusteTudo=true;
for(const x of folhas) x.ajuste=true;
for(const a of artes) a.ajuste=true;
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
}
check.checked=ajusteTudo;check.disabled=true;
mostraAvisoTratamento('Sua arte tem nota '+worst+', então o Ajuste Fino é obrigatório neste pedido.');
}else{
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
}
}
// 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='';}
}
aplicaTratamento(aPagar);
$('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')+
' aria-label="Incluir '+escapeHTML(it.tit)+' no pagamento"></label>'+
'<span class="miniItem">'+(it.mini ? '<img src="'+escapeHTML(it.mini)+'" alt="">' : '<i>'+escapeHTML(it.ext||'')+'</i>')+
(it.arquivos>1 ? '<em>+'+(it.arquivos-1)+'</em>' : '')+'</span>'+
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span>'+
(semMargem(it)?'<span class="avisoF">O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.</span>':'')+'</div>'+
'<div class="vl2">'+rs(it.total)+'</div>'+
'<button type="button" class="x" data-rmi="'+i+'" aria-label="Remover '+escapeHTML(it.tit)+'">'+icone('lixeira')+'<span>Remover</span></button></div>').join('');
$('itens').querySelectorAll('[data-sel]').forEach(c=>c.addEventListener('change',()=>{
pedido[+c.dataset.sel].marcado=c.checked; pintaPedido();
}));
$('itens').querySelectorAll('[data-rmi]').forEach(b=>b.addEventListener('click',()=>{
const i=+b.dataset.rmi, [item]=pedido.splice(i,1);
pintaPedido();
avisaDesfazer(item.tit+' saiu do carrinho.',()=>{
pedido.splice(Math.min(i,pedido.length),0,item); pintaPedido();
});
}));
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
const itens = aPagar.reduce((t,it)=>t+it.total,0);
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
const artesAjuste = TAXA_TRATAMENTO>0 ? artesSelecionadas(aPagar) : 0;
const tratamento = artesAjuste ? Math.round(precoAjuste(artesAjuste)*artesAjuste*100)/100 : 0;
const artesRedesenho = TAXA_REDESENHO>0 ? redesenhosSelecionados(aPagar) : 0;
const redesenho = artesRedesenho ? Math.round(TAXA_REDESENHO*artesRedesenho*100)/100 : 0;
// The whole order waits 48 h when any art was sent to Redesenho, else 24 h.
const prazoTratamento=document.querySelector('#tratamentoBox .provaOp span');
if(prazoTratamento) for(const no of prazoTratamento.childNodes)
if(no.nodeType===3) no.textContent=no.textContent.replace(/leva \d+ h a mais/,
'leva '+(artesRedesenho>0?48:24)+' h a mais');
const soma = itens + frete + tratamento + redesenho;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
$('resLin').innerHTML =
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens)+'</b></div>'+
'<div class="l"><span>Frete'+(entrega.tipo==='frete' && entrega.cotado
? ' · '+escapeHTML((entrega.opcoes||[]).find(o=>o.service===entrega.servico)?.description||'') : '')+
'</span><b>'+
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
(tratamento?'<div class="l"><span>Ajuste Fino · '+artesAjuste+(artesAjuste===1?' arte':' artes')+
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
(redesenho?'<div class="l"><span>Ajuste Fino Redesenho · '+artesRedesenho+
(artesRedesenho===1?' arte':' artes')+' · +48 h</span><b>'+rs(redesenho)+'</b></div>':'')+
'<div class="l"><span>Revisão e reencaixe</span>'+
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
$('carrTot').textContent=rs(soma);
// A file still on its way (or failed) keeps the payment closed (B2).
const faltaEnvio=window.dtfFaltaEnvio?window.dtfFaltaEnvio():null;
const falta=faltaEnvio?.falta||0;
$('bPagarTx').textContent = falta
? 'Falta enviar '+falta+(falta===1?' arquivo':' arquivos')
: n>1
? 'Pagar os '+n+' itens de uma vez'
: 'Ir para o pagamento';
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
const prova=$('fProva');
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
if(pedido.length || itemAtual) $('carr').classList.add('on');
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
$('cartLink').setAttribute('aria-label','Carrinho, '+noCarrinho+(noCarrinho===1?' item':' itens')); }
window.dispatchEvent(new Event('dtf-cart-changed'));
}
// Um preço por produto (Dropstar, 23/10/2026): a nota aparece, mas não entra na conta.
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'});
function carrinho(){
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>';
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>'+(montagemFolhas?'Montagem em '+montagemFolhas.length+' folhas, pela espessura do traço':'Montagem da folha')+'</span><b>inclusa</b></div>';
if(extra) l += '<div class="l"><span>Abertura manual do arquivo</span><b>+'+rs(extra)+'/m</b></div>';
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · a cada 10 cm':'')+
'</span><b>'+fmtM(cob)+' m</b></div>';
l += '<div class="l"><span>Preço final do metro</span><b>'+rs(unit)+'</b></div>'+
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
$('carrLin').innerHTML=l;
$('atual').style.display='';
const escolhidas=lista=>lista.map((x,i)=>ajusteTudo||x.ajuste?i:null).filter(i=>i!==null);
const redesenhadas=lista=>lista.map((x,i)=>x.redesenho?i:null).filter(i=>i!==null);
const sources=(ehFolha()?folhas:artes).map(x=>ehFolha()
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
copies:x.rep||1,rotation_degrees:0,mirrored:false,
measurement:x.med?'file':'customer',
// The empty strips cut from the top and the bottom (aplicaCorte).
...(x.corte?{trim_top_cm:x.corte.topo,trim_bottom_cm:x.corte.fim}:{})}
: fonteDaArte(x));
let layout, partes=null;
if(ehFolha()){
let y=0;
const placements=[];
sources.forEach((source,source_index)=>{
for(let copy_index=0;copy_index<source.copies;copy_index++){
// MARGEM_FOLHA_CM entre uma cópia e a próxima, nunca depois da última.
if(placements.length)y+=MARGEM_FOLHA_CM;
placements.push({source_index,copy_index,x_cm:0,y_cm:+y.toFixed(4),
width_cm:source.width_cm,length_cm:source.length_cm,
rotation_degrees:0,mirrored:false});
y+=source.length_cm;
}
});
layout={height_cm:+y.toFixed(4),placements};
}else if(montagemFolhas){
// Item 17: one order item per sheet, each with its files, layout and class.
partes=montagemFolhas.map((f,i)=>({rotulo:'Folha '+(i+1)+' · '+f.nome,
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
metros:+(f.layout.height_cm/100).toFixed(4),
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
ajusteSources:escolhidas(f.artes),
redesenhoSources:redesenhadas(f.artes),
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
layout=null;
}else{
if(!montagemLayout) return;
layout=montagemLayout;
}
itemAtual={modo, tit:MODOS[modo].tit, nota, metros, cob, unit, extra, total:tot,
localFiles:(ehFolha()?folhas:artes).map(x=>x.f),
mini:(ehFolha()?folhas:artes).map(x=>x.miniSrc).find(Boolean)||null,
fotos:(ehFolha()?folhas:artes).map(x=>x.fotoSrc||null),
ext:extDe(((ehFolha()?folhas:artes)[0]||{f:{name:''}}).f.name),
arquivos:(ehFolha()?folhas:artes).length,
production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
partes,
...(partes?{}:{ajusteSources:escolhidas(ehFolha()?folhas:artes),
redesenhoSources:redesenhadas(ehFolha()?folhas:artes)}),
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
qualityAcknowledged:false,
// The residue dots the customer accepted printing (Dropstar, 2026-10-29).
residueAccepted:residuosAceitos(),
// Peças a menos de 5 mm na folha pronta: a equipe vê no card (Marcus, 26/11/2026).
closePieces:ehFolha()?folhas.reduce((t,x)=>t+(x.an?.encostadas||0),0):0,
// The thinnest stroke and its contraction class (item 9), for the room.
...tracoDoItem(null,layout),
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m'};
pintaPedido();
previa();
}
// Removing is one click, and a wrong click is undone from the notice that follows.
let desfazerAcao=null, desfazerTimer=null;
function avisaDesfazer(texto,acao){
desfazerAcao=acao; clearTimeout(desfazerTimer);
$('desfazerTxt').textContent=texto; $('desfazer').hidden=false;
desfazerTimer=setTimeout(fechaDesfazer,8000);
}
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
addEventListener('dtf-page-changed',fechaDesfazer);
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
$('fTratamento')?.addEventListener('change',()=>{
if($('fTratamento').checked){ ajusteTudo=true; limpaRedesenho(); }
else limpaAjuste();
// The art cards show the same choice, one checkbox under each warning; do
// not repaint them, or the item being built is discarded.
pintaAjusteCheckboxes();
pintaPedido();
});
$('bEsvaziar').addEventListener('click',()=>{
const antes=pedido.slice();
pedido=[]; invalidaItemAtual(); pintaPedido();
avisaDesfazer('Carrinho esvaziado.',()=>{ pedido=antes; pintaPedido(); });
});
function qm(t,c){ const m=$('qmsg'); m.style.display='block'; m.style.color=c||'var(--verde)'; m.innerHTML=t; }