Files
dtf-system/web/checkout.js
Cauê Faleiros d840d2741f Merge main into bugs-uploads
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:49:04 -03:00

831 lines
43 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Checkout bridge only: approved commercial functions in web/index.html stay intact.
The cart sends the order; the quote is paid on its own page (/pagamento). */
(() => {
const status = document.getElementById('checkoutStatus');
const actions = document.getElementById('checkoutActions');
const resumo = document.getElementById('pagResumo');
const naPagina = () => ['pagamento','pix'].includes(document.documentElement.dataset.rota);
const naPix = () => document.documentElement.dataset.rota === 'pix';
let shownCart = null;
let pixClock = null;
let busy = false;
// Every product switched off in the Kanban's Site tab (front 8).
let semPedidos = false;
let draftId = localStorage.getItem('dtf-quote');
let requestKey = localStorage.getItem('dtf-request-key');
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=>({
mode:item.modo,metres:item.metros,grade:item.nota,production:item.production,
quality:item.qualityStatus,
acknowledged:item.qualityAcknowledged,
residue:item.residueAccepted||0,
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:ajusteSnapshot(),coupon:cupomCode()});
}
// The quote this browser is paying, forgotten. clearDraft also empties the
// payment area; forgetDraft leaves on screen what is there (a confirmation).
function forgetDraft() {
draftId=null;quotedCart=null;requestKey=null;requestBody=null;
for(const key of ['dtf-quote','dtf-quote-cart','dtf-request-key','dtf-request-body'])
localStorage.removeItem(key);
}
function clearDraft() { forgetDraft(); actions.replaceChildren(); }
const api = async (path, body) => {
const response = await fetch('/api'+path, {
credentials: 'same-origin', headers: {'Content-Type':'application/json'},
...(body === undefined ? {} : {method:'POST', body:JSON.stringify(body)})
});
const text = await response.text();
let data;
try { data = text ? JSON.parse(text) : {}; }
catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); }
if (!response.ok) {
const text=problem(data.detail);
// A validation the customer cannot read still needs to reach us (Sentry
// picks up console.error later); the customer keeps the generic sentence.
if (response.status===422 && text==='Não foi possível concluir. Confira os dados e tente de novo.')
console.error('Detalhe da validação recusada:',data.detail);
const error=new Error(text);error.status=response.status;
const retry=response.headers.get('Retry-After');
if(retry!=null)error.retryAfter=retry;
throw error;
}
return data;
};
// A refusal as one sentence: the server's own, or the first field a form
// check named, never a status code.
function problem(detail){
if (typeof detail === 'string') return detail;
// Only the checks written for customers speak Portuguese ("Value error, …").
const ours=Array.isArray(detail)&&detail.find(d=>typeof d?.msg==='string'&&d.msg.startsWith('Value error, '));
if (ours) return ours.msg.slice('Value error, '.length);
return 'Não foi possível concluir. Confira os dados e tente de novo.';
}
const ready = api('/session');
ready.then(session=>{
window.dtfUploadMaxBytes=session.max_upload_bytes;
const limit=document.getElementById('zLimite');
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
// What the server charges for a file opened by hand, never the page's own text.
const zona=document.getElementById('zManual');
const extra=session.manual_extra_cents>0?rs(session.manual_extra_cents/100):'';
if(zona)zona.innerHTML='Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também. Alguém abre na mão'+
(extra?', e o metro custa '+extra+' a mais':'')+'.';
const duvida=document.getElementById('duvidaManual');
if(duvida)duvida.textContent='alguém abre na mão'+(extra?', sai mais devagar e o metro custa '+extra+' a mais':' e sai mais devagar');
const tabela=document.getElementById('tabelaManual');
if(tabela){tabela.hidden=!extra;tabela.textContent='Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + '+extra+' por metro.';}
if(session.manual_extra_cents>0){
TAXA_MANUAL=session.manual_extra_cents/100;
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
}
// The art grade rules (front 8.5): the Site uses only the treatment rule,
// forcing the checkbox when the cart's worst grade is below it.
window.dtfGradeRules=session.grade_rules||{};
// Ajuste Fino (front 1a): per art, with a band by the order's number of
// arts. Only offered when TREATMENT_CENTS is set; the server adds the
// same amount and the 24 h to the quote.
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;
FAIXAS.tratamento=session.treatment_bands||[];
const tratamentoBox=document.getElementById('tratamentoBox');
if(tratamentoBox){
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
const preco=document.getElementById('tratamentoPreco');
if(preco)preco.textContent=TAXA_TRATAMENTO>0?rs(TAXA_TRATAMENTO):'';
if(!(TAXA_TRATAMENTO>0)&&document.getElementById('fTratamento'))document.getElementById('fTratamento').checked=false;
}
// What the Site sells and at what price, from the database (front 8). An
// older server sends no `products`: the page keeps PRECO.
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+'"]');
// Premium starts hidden in the HTML and only appears once enabled.
if(card)card.hidden=!product.enabled;
}
document.querySelectorAll('[data-preco]').forEach(el=>{
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 artes!=='undefined'&&artes.length&&typeof pintaArtes==='function')pintaArtes();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
if(typeof pintaTipoEnvio==='function')pintaTipoEnvio();
semPedidos=!Object.values(session.products).some(product=>product.enabled);
if(semPedidos)message('No momento não estamos recebendo pedidos pelo site.','warn');
}
if(typeof pintaPedido==='function')pintaPedido();
}).catch(()=>{});
window.dtfSessionReady=ready;
window.dtfApi=api;
ready.catch(error => { status.textContent = error.message; });
// One message line under the steps. Its tone says what it is: a refusal or
// a missing field is an error (red), a cart that changed a warning, a
// created order a confirmation, the rest information.
function message(text, tone='info') { status.textContent = text; status.dataset.tone = text ? tone : ''; }
function button(label, handler, into = actions, className = 'pagBtn') {
const el = document.createElement('button');
el.type = 'button';
el.className = className;
el.textContent = label;
el.onclick = handler;
into.append(el);
return el;
}
function node(tag, text, className) {
const el=document.createElement(tag);
if (text!=null) el.textContent=text;
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;
resumo.hidden = !approved;
if (!approved) { resumo.replaceChildren(); return; }
const linha = (label, value, className='l') => {
const row=document.createElement('div'); row.className=className;
const name=document.createElement('span'); name.textContent=label;
const amount=document.createElement('b'); amount.textContent=value;
row.append(name,amount); return row;
};
// The sheets of a split (item 17) are one line, as in the cart.
const linhas=[];
for (const item of approved.items) {
const grupo=item.split && linhas.find(l=>l.split?.group===item.split.group);
if (grupo) { grupo.billed_metres=String(Number(grupo.billed_metres)+Number(item.billed_metres)); grupo.total_cents+=item.total_cents; grupo.folhas++; }
else linhas.push({...item,folhas:1});
}
const rows = linhas.map(item => linha(
(MODOS[item.mode]?.tit || item.mode)+(item.folhas>1?' · '+item.folhas+' folhas':'')+' · '+
fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
const pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
if(quote.treatment?.cents){
const arts=Number(quote.treatment.arts)||0;
rows.push(linha('Ajuste Fino'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +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){
prumoBox.append(node('b','O que o Prumo fez'));
for(const line of quote.prumo) prumoBox.append(node('span',line));
}
resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows, ...(quote.prumo?.length?[prumoBox]:[]));
}
function esqueletoPagamento() {
const linhas=['skel skelLinha','skel skelLinha','skel skelLinha curta'].map(c=>node('div',null,c));
resumo.hidden=false; resumo.replaceChildren(node('h4','Resumo do pedido'),...linhas);
actions.replaceChildren(node('div',null,'skel skelLinha curta'),node('div',null,'skel skelBloco'));
}
function semPedido() {
pintaResumo(null);
actions.replaceChildren();
message('Nenhum pedido aguardando pagamento.');
button('Ir para o carrinho', () => vaiPara(CARRINHO));
}
// Files start uploading as soon as they are on the product page (Dropstar,
// 2026-10-29; before, once in the cart), so a sheet of several GB is on its
// way while the customer builds the order. The checkout waits for whatever
// is still going.
const envios=new Map();
const chaveArquivo=f=>[f.name,f.size,f.lastModified].join('|');
function enviar(file) {
const k=chaveArquivo(file);
let e=envios.get(k);
if (!e) {
const T=window.dtfTimings;
if(T){ if(T.uploadStart==null)T.uploadStart=performance.now();
if(!T.uploadSeen.has(k)){T.uploadSeen.add(k);T.uploadBytes+=file.size;} }
e={file, sent:0, done:false, failed:null, stop:new AbortController()};
e.promise=(async()=>{
const session=await ready;
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal,
onBytes:n=>{e.sent=n;pintaEnvio();}});
})();
e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();},
error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();});
envios.set(k,e);
}
return e.promise;
}
// Each file's upload as the product page shows it, under the uploader.
window.dtfEnvio={
enviar:file=>{if(!falhas.has(chaveArquivo(file)))enviar(file).catch(()=>{});},
estado:file=>{const k=chaveArquivo(file),e=envios.get(k),f=falhas.get(k);
return f?{fase:'falhou',erro:f.error?.message||'erro no envio'}
:!e?null:e.done?{fase:'pronto'}:e.sent>=file.size?{fase:'verificando'}:{fase:'enviando',enviado:e.sent};},
deNovo:file=>{falhas.delete(chaveArquivo(file));enviar(file).catch(()=>{});pintaEnvio();},
// A file taken off the page, and in no cart item, stops going.
manter:files=>{
const quero=new Set([...files,...pedido.flatMap(it=>it.localFiles||[]),...(itemAtual?.localFiles||[])].map(chaveArquivo));
for(const [k,e] of envios) if(!e.done && !quero.has(k)) e.stop.abort();
for(const k of falhas.keys()) if(!quero.has(k)) falhas.delete(k);
},
};
// The Kanban shows each order's artwork from the small picture this page
// already made of it (site-upload.js). Never blocks the order: a picture that
// fails to go leaves the Kanban with the layout drawing it shows today.
const fotosEnviadas=new Set();
function enviaFoto(uid, foto) {
if (!uid || !foto || fotosEnviadas.has(uid)) return;
fotosEnviadas.add(uid);
try {
const [cabecalho, dados] = foto.split(',');
const bin = atob(dados), bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
fetch('/api/uploads/'+uid+'/thumbnail', {method:'PUT', body:bytes,
headers:{'Content-Type':cabecalho.slice(5).split(';')[0]}})
.then(r=>{ if (!r.ok) fotosEnviadas.delete(uid); }, ()=>fotosEnviadas.delete(uid));
} catch (e) { fotosEnviadas.delete(uid); }
}
// A failed upload is shown and waits for the customer, never retried behind
// their back: a file the check refused would fail again on every change.
const falhas=new Map();
function tentaDeNovo() {
const arquivos=[...falhas.values()].map(f=>f.file);
falhas.clear();
arquivos.forEach(f=>enviar(f).catch(()=>{}));
pintaEnvio();
}
const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]);
// Every file of the paying cart must be sent (and none failed) before the
// quote and before the payment button (bugs B2 and B4, Marcus 2026-11-11).
function faltaEnvio(){
const files=arquivosDoCarrinho();
let pending=0,failed=0;
for(const f of files){
const k=chaveArquivo(f);
if(falhas.has(k)){failed++;continue;}
const e=envios.get(k);
if(!e||!e.done)pending++;
}
return {total:files.length,pending,failed,falta:pending+failed};
}
window.dtfFaltaEnvio=faltaEnvio;
function faltaEnvioMensagem(){
const missing=[];
for(const f of arquivosDoCarrinho()){
const k=chaveArquivo(f),e=envios.get(k);
if(falhas.has(k)||!e||!e.done)missing.push(f);
}
if(!missing.length) return '';
return 'Falta enviar '+missing[0].name+
(missing.length>1?' (e mais '+(missing.length-1)+')':'');
}
const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB';
const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB';
// Where the uploads stand, and roughly how long is left from the recent speed.
const amostras=[];
let ultimaFalta=null;
function estadoEnvio() {
const files=arquivosDoCarrinho(); if(!files.length) return null;
let total=0, sent=0, pendentes=0;
for (const f of files) {
const e=envios.get(chaveArquivo(f));
total+=f.size; sent+=e ? Math.min(e.sent,f.size) : 0;
if (!e || !e.done) pendentes++;
}
const agora=Date.now();
amostras.push([agora,sent]); while(amostras.length>2 && agora-amostras[0][0]>15000) amostras.shift();
const [t0,s0]=amostras[0], taxa=agora>t0 ? (sent-s0)/((agora-t0)/1000) : 0;
const fase=!pendentes ? 'pronto' : sent>=total ? 'verificando' : 'enviando';
return {total, sent, fase, pct:Math.floor(sent/total*100),
restante: fase==='enviando' && taxa>0 ? (total-sent)/taxa : null};
}
const falta=s=>s<60 ? 'falta menos de 1 min' : 'faltam cerca de '+duracao(s);
// The time left, measured from the upload's own speed; until there is a
// measure, a range from the size.
const restante=e=>e.restante!=null ? falta(e.restante) : 'estimativa '+faixaEnvio(e.total-e.sent);
function textoEnvio(e) {
if (!e) return '';
if (e.fase==='pronto') return 'Arquivos enviados';
if (e.fase==='verificando') return 'Arquivos enviados · verificando a segurança…';
return 'Enviando seus arquivos · '+restante(e);
}
function pintaEnvio() {
// The cart button carries the uploads too (B2): repaint it only when the
// number of missing files changes, not on every progress tick.
const falta=faltaEnvio().falta;
if(falta!==ultimaFalta){
ultimaFalta=falta;
if(typeof pintaPedido==='function')pintaPedido();
}
window.dispatchEvent(new Event('dtf-envio'));
const e=estadoEnvio(), texto=textoEnvio(e);
const el=document.getElementById('envioArq');
const falhou=arquivosDoCarrinho().map(f=>falhas.get(chaveArquivo(f))).filter(Boolean);
const topo=document.getElementById('cartEnvio');
if (falhou.length) {
if (el) {
el.replaceChildren(document.createTextNode('Não foi possível enviar '+falhou[0].file.name+': '+
(falhou[0].error?.message||'erro no envio').replace(/\.$/,'')+(falhou.length>1?' (e mais '+(falhou.length-1)+')':'')+'. '));
const b=document.createElement('button'); b.type='button'; b.className='envioDeNovo'; b.textContent='Tentar de novo';
b.onclick=tentaDeNovo; el.append(b);
el.classList.remove('ok'); el.classList.add('erro');
}
if (topo) topo.textContent='· falha no envio';
return;
}
if (el) el.classList.remove('erro');
if (el) {
el.replaceChildren();
if (e && e.fase!=='pronto') {
const barra=document.createElement('div'); barra.className='envioBarra';
const i=document.createElement('i'); i.style.width=(e.fase==='verificando'?100:e.pct)+'%'; barra.append(i);
el.append(barra);
}
if (e?.fase==='pronto') el.insertAdjacentHTML('beforeend', icone('okCirculo'));
if (texto) el.append(document.createTextNode(texto));
if (e?.fase==='enviando') {
const nota=document.createElement('small'); nota.className='envioNota';
nota.textContent='O tempo depende da velocidade da sua internet. Mantenha a página aberta.';
el.append(nota);
}
el.classList.toggle('ok', e?.fase==='pronto');
}
// Visible on every page while it runs.
if (topo) topo.textContent = !e || e.fase==='pronto' ? '' : e.fase==='verificando' ? '· verificando' : e.restante!=null ? '· '+duracao(e.restante) : '· enviando';
if (busy && texto) {
message(texto);
$('bPagarTx').textContent = e && e.fase!=='pronto' ? (e.fase==='verificando' ? 'Verificando os arquivos…' : 'Enviando arquivos… '+restante(e)) : $('bPagarTx').textContent;
}
}
// Leaving the page pauses an upload; it resumes, but the customer is warned.
window.addEventListener('beforeunload',event=>{
const e=estadoEnvio();
if (e && e.fase==='enviando') { event.preventDefault(); event.returnValue=''; }
});
// Only what is in the cart: the item on the product page may still change.
window.addEventListener('dtf-cart-changed',()=>{
arquivosDoCarrinho().forEach(f=>{ if(!falhas.has(chaveArquivo(f))) enviar(f).catch(()=>{}); });
pintaEnvio();
});
async function upload(file) {
return enviar(file);
}
// The cart's package: billed metres and value. The charged freight is
// quoted again by the server from the approved items.
const pacote = () => {
const items=itensAPagar();
return {metres:items.reduce((t,it)=>t+(it.cob||0),0), cents:Math.round(items.reduce((t,it)=>t+(it.total||0),0)*100)};
};
let freightQuoted = null;
// Every carrier's option for the CEP; the customer's choice stays chosen
// when the cart changes, else the cheapest is.
window.dtfFreight = async () => {
const cep = entrega.cep;
if (!(await ready).freight_services?.length) {
$('cepMsg').textContent = 'A entrega ainda não está disponível. Escolha a retirada em Franca.';
return;
}
const {metres, cents} = pacote();
if (!metres) { $('cepMsg').textContent = 'Adicione um item ao pedido para cotar o frete.'; return; }
$('cepMsg').textContent = 'Cotando o frete…';
try {
const result = await api('/freight/options',{postal_code:cep,metres:metres.toFixed(2),declared_cents:cents});
if (entrega.cep !== cep || entrega.tipo !== 'frete') return;
entrega.opcoes = result.options;
const chosen = result.options.find(o=>o.service===entrega.servico) || result.options[0];
entrega.servico = chosen.service;
entrega.valor = chosen.total_cents/100;
entrega.dias = chosen.days || null;
entrega.cotado = true;
freightQuoted = JSON.stringify(pacote());
$('cepMsg').textContent = '';
pintaFretes(); pintaEntrega();
} catch(error) { entrega.opcoes=[]; pintaFretes(); $('cepMsg').textContent = error.message; }
};
// A different package is a different freight: quote it again.
window.addEventListener('dtf-cart-changed',()=>{
if (entrega.tipo==='frete' && entrega.cotado && freightQuoted && freightQuoted!==JSON.stringify(pacote())) {
entrega.cotado=false; freightQuoted=null; window.dtfFreight();
}
});
window.dtfCheckout = async () => {
if (busy) return;
// The cart that was sent goes straight to its payment; a changed cart is sent again.
if (draftId && quotedCart === cartSnapshot()) { await refresh(true); return; }
if (draftId) clearDraft();
if (!clienteOk() || !entrega.cotado) return;
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error');
const semArquivo=faltaEnvioMensagem();
if (semArquivo) return message(semArquivo+'.','error');
const cart = itensAPagar();
if (!cart.length) return message('Adicione um item ao pedido.','error');
const initialCart=cartSnapshot();
busy = true;
$('bPagar').disabled = true;
try {
await ready;
if((await api('/session')).cart_scope !== (await ready).cart_scope) throw new Error('Sua conta ou sessão mudou. Recarregue a página antes de enviar o carrinho.');
const items=[];
pintaEnvio();
// Loose art split by stroke (item 17) is one cart line and one order item
// per sheet, billed together.
const sheets=cart.flatMap((line,index)=>line.partes?.length
? line.partes.map((part,i)=>({...line,...part,split:{group:'f'+index,part:i+1,of:line.partes.length}}))
: [line]);
for (const item of sheets) {
if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.');
const uploads=[];
for (const [index,file] of item.localFiles.entries()) {
uploads.push(await upload(file));
enviaFoto(uploads[index], item.fotos?.[index]);
}
// Layout versions the server takes: 3 since 2026-10-21, 2 for a cart saved before.
if (![2,3].includes(item.production?.version) || item.production.sources?.length!==uploads.length)
throw new Error('A montagem deste item precisa ser refeita antes da cotação.');
items.push({mode:item.modo, metres:String(item.metros), grade:item.nota, uploads,
production:{...item.production,sources:item.production.sources.map((source,index)=>({
upload_id:uploads[index],...source}))},
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged,
residue_accepted:item.residueAccepted||0,
...(item.strokeClass?{stroke_px:item.strokePx,stroke_class:item.strokeClass}:{}),
...(item.strokeChoice?{stroke_choice:item.strokeChoice}:{}),
...(item.proofYFraction!=null?{proof_y_fraction:item.proofYFraction}:{}),
...(item.split?{split:item.split}:{})});
}
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 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.
if ($('fProva')?.checked) content.proof = true;
// Ajuste Fino: true for every art, or the [item, source] pairs chosen.
const treatment=tratamentoParaItens(sheets);
if (treatment) content.treatment = treatment;
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
// Browser timings for Números (item 0.12); they never affect the price.
const T=window.dtfTimings, timings={};
const nav=performance.getEntriesByType?.('navigation')?.[0];
const pageMs=nav?.domContentLoadedEventEnd || (T?.pageStart!=null?performance.now()-T.pageStart:0);
if(pageMs>0)timings.page_ms=Math.round(pageMs);
if(T?.uploadStart!=null&&T.uploadEnd!=null){
timings.upload_ms=Math.round(T.uploadEnd-T.uploadStart);
timings.upload_bytes=Math.round(T.uploadBytes||0);
}
if(T?.analysisStart!=null&&T.analysisEnd!=null)timings.analysis_ms=Math.round(T.analysisEnd-T.analysisStart);
if(T?.montageStart!=null&&T.montageEnd!=null)timings.montage_ms=Math.round(T.montageEnd-T.montageStart);
const serialized = JSON.stringify({...content,timings});
if (!requestKey || serialized !== requestBody) {
requestKey = crypto.randomUUID(); requestBody = serialized;
localStorage.setItem('dtf-request-key',requestKey);
localStorage.setItem('dtf-request-body',requestBody);
}
const quote = await api('/quotes',{request_key:requestKey,...content,timings});
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
await refresh(true);
} catch(error) { message(error.message,'error'); }
finally { busy=false; pintaEntrega(); }
};
// `go`: the customer asked to pay, so the cart page moves to the payment page.
async function refresh(go) {
if (!naPagina()) { if (!go || !draftId) return; }
else if (!draftId) { semPedido(); return; }
const version=++refreshVersion, shownId=draftId;
if (naPagina() && !actions.children.length) esqueletoPagamento();
try {
await ready;
const quote=await api('/quotes/'+shownId);
if(version!==refreshVersion || draftId!==shownId) return;
// Asked to pay a cart identical to one already paid (the same test
// repeated): that is a new order, never the paid one shown again. The
// confirmation itself keeps its quote, so it stays on screen.
if (go && quote.status==='paid') { forgetDraft(); return window.dtfCheckout(); }
if (!naPagina()) { message(''); vaiPara(PAGAMENTO); return; }
shownCart=cartSnapshot();
clearInterval(pixClock);
unmountCard();
actions.replaceChildren();
message('');
pintaResumo(quote);
document.querySelector('.pagVolta').hidden = quote.status==='paid';
if (quote.status==='paid') { confirmado(quote); return; }
if (naPix() && quote.status!=='approved') { vaiPara(PAGAMENTO); return; }
if (!quotedCart || quotedCart!==cartSnapshot()) {
message('O carrinho mudou ou não está disponível neste navegador. A cotação anterior continua separada; envie o carrinho atual para uma nova revisão.','warn');
button('Enviar carrinho atual',()=>{clearDraft();window.dtfCheckout();});
return;
}
if (quote.status==='pending_review') {
message((await ready).environment==='local'
? 'Arquivos enviados. No Kanban, confira a metragem e os arquivos e aprove a cotação '+draftId.slice(0,8)+'.'
: 'Arquivos enviados. Nossa equipe está conferindo a cotação '+draftId.slice(0,8)+'; o valor final aparece aqui em seguida.');
} else if (quote.status==='approved') {
if ((await ready).payment_provider === 'mercadopago') {
if (naPix()) await paginaPix(quote, version);
else await escolhaPagamento(quote, version);
return;
}
if ((await ready).environment !== 'local') {
message('Cotação revisada. O pagamento online ainda não está disponível.');
return;
}
// Local stack only: the simulated payment.
message('Total validado no servidor: '+rs(quote.approved.total_cents/100)+' · inclui frete. Cotação válida por 24 horas.');
button('Criar pedido de teste',async event=>{
if (!quotedCart || quotedCart!==cartSnapshot()) { await refresh(); return; }
event.target.disabled=true;
try {
const order=await api('/orders/dev-paid',{quote_id:draftId});
await pagos();
message('Pedido #'+order.number+' criado e disponível no Kanban.','ok');
await refresh();
} catch(error) { message(error.message,'error'); event.target.disabled=false; }
});
} else {
message(quote.status==='discarded'
? 'Esta cotação foi cancelada pela nossa equipe. Envie o carrinho de novo ou fale com a gente.'
: 'Cotação expirada. Envie o carrinho de novo para pagar.','warn');
button('Voltar ao carrinho',()=>{clearDraft();vaiPara(CARRINHO);});
}
} catch(error) {
if(version!==refreshVersion || draftId!==shownId) return;
message(error.message,'error');
actions.replaceChildren();
button('Limpar referência e tentar de novo',clearDraft);
}
}
// The order is created by Mercado Pago's notification, never by this page,
// so after paying the page only waits for the order to exist.
let waitTimer=null;
function waitForOrder() {
clearInterval(waitTimer);
waitTimer=setInterval(async()=>{
try {
const quote=await api('/quotes/'+draftId);
if (quote.status==='paid') {
clearInterval(waitTimer);
await pagos();
await refresh();
} else if (quote.payment?.status==='rejected') {
// Refused after the bank's confirmation or the provider's review.
clearInterval(waitTimer);
await refresh();
message(quote.payment.message||'O pagamento foi recusado. Tente de novo ou escolha outra forma de pagamento.','error');
}
} catch(_) {}
},3000);
}
// 3-D Secure: the bank's own page, opened by posting its request in a frame.
function showChallenge(challenge, into) {
unmountCard();
const frame=document.createElement('iframe');
frame.name='confirmacaoBanco'; frame.title='Confirmação do banco'; frame.className='desafio';
const form=document.createElement('form');
form.method='POST'; form.action=challenge.url; form.target=frame.name;
const input=document.createElement('input');
input.type='hidden'; input.name='creq'; input.value=challenge.creq;
form.append(input);
into.replaceChildren(node('p','Confirme o pagamento na página do seu banco, abaixo.','pagNota'),frame,form);
form.submit();
form.remove();
}
function confirmado(quote) {
clearInterval(waitTimer);
const box=node('div',null,'confirmado');
const titulo=node('h4','Pagamento confirmado');
titulo.insertAdjacentHTML('afterbegin', icone('okCirculo'));
box.append(titulo,
node('p','Recebemos seu pedido e ele já está na produção. Você acompanha cada etapa em Meus pedidos.'),
node('p','Seu pedido já aparece em Meus pedidos. O Prumo está preparando o arquivo de impressão; você pode acompanhar o andamento por lá.'));
button('Ver meus pedidos',()=>location.assign('/conta/pedidos?order='+quote.order.id),box);
actions.append(box);
}
const cartOk=()=>!!quotedCart && quotedCart===cartSnapshot();
// What was paid leaves the cart; unchecked items stay for another order.
async function pagos() {
pedido=pedido.filter(it=>it.marcado===false); itemAtual=null; limpaPaineis();
if (pedido.length) pintaPedido(); else await window.dtfClearCart?.();
}
// Paying: card (the default, paid on this page) or PIX (paid on its own page).
async function escolhaPagamento(quote, version) {
const session=await ready;
// Credit card and PIX: the store does not take debit cards.
const opcoes=[...(session.payment_public_key?[['credito','Cartão de crédito']]:[]),['pix','PIX']];
let escolhido=opcoes[0][0];
const grupo=node('div',null,'metodos');
grupo.setAttribute('role','radiogroup'); grupo.setAttribute('aria-label','Forma de pagamento');
const area=node('div',null,'area');
const radios=opcoes.map(([key,label])=>{
const el=button(label,()=>{ if(escolhido!==key){ escolhido=key; pinta(); } },grupo,'metodo');
el.setAttribute('role','radio'); el.dataset.metodo=key;
el.insertAdjacentHTML('afterbegin', icone(key==='pix'?'qrcode':'cartao'));
return el;
});
actions.append(node('h4','Forma de pagamento'),grupo,area);
async function pinta() {
radios.forEach(el=>el.setAttribute('aria-checked',String(el.dataset.metodo===escolhido)));
unmountCard(); area.replaceChildren(); message('');
if (escolhido!=='pix') { await showCard(quote.approved, area, version); return; }
area.append(node('p','Clique em Pagar para gerar o QR code do PIX.','pagNota'));
button('Pagar',async event=>{
if (!cartOk()) { await refresh(); return; }
event.target.disabled=true;
try {
await api('/payments/intent',{quote_id:draftId,method:{type:'pix'}});
vaiPara(PAGAMENTO_PIX);
} catch(error) { message(error.message,'error'); event.target.disabled=false; }
},area);
}
await pinta();
}
// The PIX page. The intent is idempotent on the quote, so reopening this
// page shows the same QR code instead of creating another charge.
async function paginaPix(quote, version) {
let intent;
try { intent=await api('/payments/intent',{quote_id:draftId,method:{type:'pix'}}); }
catch(error) {
if (version!==refreshVersion) return;
message(error.message,'error');
button('Escolher outra forma de pagamento',()=>vaiPara(PAGAMENTO),actions,'pagBtn sec');
return;
}
if (version!==refreshVersion) return;
if (!intent.pix_qr_code) { message('Não foi possível gerar o PIX. Tente de novo em instantes.','error'); return; }
const box=node('div',null,'pixBox');
box.append(node('h4','Pague com PIX'),
node('p','Abra o app do seu banco, escolha pagar com PIX e leia o QR code ou cole o código abaixo.','pagNota'));
if (intent.pix_qr_code_base64) {
const img=document.createElement('img');
img.src='data:image/png;base64,'+intent.pix_qr_code_base64;
img.alt='QR code do PIX';img.width=240;img.height=240;
box.append(img);
}
const linha=node('div',null,'codigo');
const code=document.createElement('input');
code.readOnly=true;code.value=intent.pix_qr_code;code.setAttribute('aria-label','Código PIX copia e cola');
linha.append(code);
const copiar=button('Copiar código',async()=>{
try{ await navigator.clipboard.writeText(intent.pix_qr_code);
copiar.replaceChildren(); copiar.insertAdjacentHTML('beforeend', icone('ok')+'<span>Código copiado</span>'); }
catch(_){ code.select(); }
},linha);
copiar.insertAdjacentHTML('afterbegin', icone('copiar'));
const prazo=node('p',null,'prazo');
prazo.insertAdjacentHTML('afterbegin', icone('relogio'));
const prazoTx=node('span'); prazo.append(prazoTx);
box.append(linha,prazo,node('p','Aguardando a confirmação do pagamento…','aguarda'));
actions.append(box);
waitForOrder();
// The code stops working when it expires; a new one is a click away.
const fim=Date.parse(intent.expires_at);
if (!Number.isFinite(fim)) { prazo.remove(); return; }
const tick=()=>{
const s=Math.max(0,Math.ceil((fim-Date.now())/1000));
prazoTx.textContent='Pague em '+String(Math.floor(s/60)).padStart(2,'0')+':'+String(s%60).padStart(2,'0');
if (s>0) return;
clearInterval(pixClock);
const fimBox=node('div',null,'pixBox');
fimBox.append(node('h4','O código PIX expirou'),
node('p','Gere um novo código para pagar. O anterior não pode mais ser pago.','pagNota'));
button('Gerar novo PIX',()=>refresh(),fimBox);
actions.replaceChildren(fimBox);
};
tick();
pixClock=setInterval(tick,1000);
}
// Card: Mercado Pago's own form (Card Payment Brick). The card is typed into
// Mercado Pago's secure fields and becomes a one-time token; the number never
// reaches this page's code or our server.
let sdkLoading=null;
function loadMercadoPago() {
if (window.MercadoPago) return Promise.resolve();
sdkLoading = sdkLoading || new Promise((resolve,reject)=>{
const script=document.createElement('script');
script.src='https://sdk.mercadopago.com/js/v2';
script.onload=resolve;
script.onerror=()=>{sdkLoading=null;reject(new Error('Não foi possível carregar o formulário do Mercado Pago.'));};
document.head.append(script);
});
return sdkLoading;
}
// The cardholder's document as the card form collected it.
function cardholder(id) {
const number=String(id?.number||'').replace(/\D/g,'');
const type=String(id?.type||'').toUpperCase();
return ['CPF','CNPJ'].includes(type) && /^[0-9]{11,14}$/.test(number)
? {payer_document_type:type, payer_document:number} : {};
}
let cardBrick=null;
function unmountCard() {
if (cardBrick) { try { cardBrick.unmount(); } catch(_) {} cardBrick=null; }
}
async function showCard(approved, into, version) {
const holder=node('div');
holder.id='cardPaymentBrick';
const espera=node('div',null,'skel skelBloco');
into.append(espera,holder);
try { await loadMercadoPago(); }
catch(error) { espera.remove(); message(error.message,'error'); return; }
const session=await ready;
// The customer may have switched to PIX, or the page re-rendered, meanwhile.
if (!holder.isConnected || version!==refreshVersion) return;
unmountCard();
const mp=new window.MercadoPago(session.payment_public_key,{locale:'pt-BR'});
cardBrick=await mp.bricks().create('cardPayment','cardPaymentBrick',{
initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail}},
// Credit cards only, in up to 3 installments, as Dropstar decided.
customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}},
// The option above already names the card; the form's own title
// ("crédito ou débito") would contradict it.
visual:{hideFormTitle:true,
style:{customVariables:{baseColor:'#FFA81A',buttonTextColor:'#03060B'}}}},
callbacks:{
onReady:()=>{ espera.remove(); },
onError:error=>{ console.error(error); message('Erro no formulário do cartão. Confira os dados e tente de novo.','error'); },
onSubmit:async data=>{
if (!cartOk()) { await refresh(); throw new Error('cart changed'); }
message('');
let result;
try {
result=await api('/payments/intent',{quote_id:draftId,method:{
type:'card', token:data.token, payment_method_id:data.payment_method_id,
installments:Number(data.installments)||1,
issuer_id:data.issuer_id==null?null:String(data.issuer_id),
...cardholder(data.payer?.identification)}});
} catch(error) {
// Rejecting stops the form's spinner; the reason is shown above it.
message(error.message || 'Não foi possível concluir o pagamento. Tente de novo.','error');
status.scrollIntoView({behavior:'smooth',block:'center'});
throw error;
}
if (result.challenge) { showChallenge(result.challenge, into); waitForOrder(); return; }
if (result.status==='approved' || result.status==='pending') {
unmountCard();
into.replaceChildren(node('p',result.status==='approved'
? 'Pagamento aprovado. Confirmando seu pedido…'
: 'Pagamento em análise pelo Mercado Pago. Esta página atualiza assim que ele for confirmado.','pagNota'));
waitForOrder();
} else {
message(result.message||'O pagamento foi recusado. Confira os dados ou use outro cartão ou pague com PIX.','error');
throw new Error('rejected');
}
}
}
});
if (!holder.isConnected || version!==refreshVersion) unmountCard();
}
const quoteFromPortal=new URLSearchParams(location.search).get('quote');
if(quoteFromPortal && /^[0-9a-f-]{36}$/.test(quoteFromPortal)){
if(draftId!==quoteFromPortal){quotedCart=null;localStorage.removeItem('dtf-quote-cart');}
draftId=quoteFromPortal;localStorage.setItem('dtf-quote',draftId);
}
// Re-render the payment page only when the cart really changed: re-rendering
// would remount the card form under the customer's typing.
window.addEventListener('dtf-cart-changed',()=>{if(draftId && naPagina() && shownCart!==cartSnapshot()) refresh();});
// The cart page keeps only the sending progress and errors, never a payment.
window.addEventListener('dtf-page-changed',()=>{
if (naPagina()) refresh();
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();
})();