Files
dtf-system/web/site-upload.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

356 lines
18 KiB
JavaScript

/* Site DTF — Accepting files: the drop zone, the accept rules, first measurement.
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. */
// ── upload
// Untrusted filenames and recovered cart text must never become HTML.
function escapeHTML(value){
return String(value).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
// Dropstar's rule D-13 (2026-10-26): what a file is comes from its first bytes,
// never from its name. A ".cdr" that is a PDF is renamed ".pdf" and checked as
// a PDF, without the manual charge; a JPG called ".png" is refused as a JPG.
// A name its content agrees with stays, so an Illustrator file, a PDF inside,
// is still ".ai". The same signatures as the server (app/scanning.py).
const TIFF_INICIOS=['II*\0','MM\0*','II+\0','MM\0+'];
const INICIOS={png:['\x89PNG\r\n\x1a\n'], jpg:['\xff\xd8\xff'], jpeg:['\xff\xd8\xff'],
tif:TIFF_INICIOS, tiff:TIFF_INICIOS, pdf:['%PDF-'], ai:['%PDF-','%!PS'], psd:['8BPS'], psb:['8BPS']};
const RIFF_TIPOS={cdr:/^RIFF[\s\S]{4}CDR/, webp:/^RIFF[\s\S]{4}WEBP/};
const confere=(ext,ini)=>RIFF_TIPOS[ext] ? RIFF_TIPOS[ext].test(ini) : (INICIOS[ext]||[]).some(a=>ini.startsWith(a));
const formatoDe=ini=>['pdf','png','jpg','tif','psd','cdr','webp'].find(e=>confere(e,ini))||null;
async function nomeReal(f){
let ini;
try{ ini=String.fromCharCode(...new Uint8Array(await f.slice(0,16).arrayBuffer())); }
catch(e){ return f; }
const real=formatoDe(ini);
if(!real || confere(extDe(f.name).toLowerCase(),ini)) return f;
const ponto=f.name.lastIndexOf('.');
const g=new File([f], (ponto>0?f.name.slice(0,ponto):f.name)+'.'+real, {type:f.type, lastModified:f.lastModified});
g.nomeEnviado=f.name;
return g;
}
function recusa(lista){
const el=$('recusa'); if(!el) return;
if(!lista.length){ el.style.display='none'; el.innerHTML=''; return; }
const exts=escapeHTML([...new Set(lista.map(f=>extDe(f.name)))].join(', '));
el.style.display='block';
if(lista.every(f=>/\.jpe?g$/i.test(f.name))){
const disfarcados=lista.filter(f=>f.nomeEnviado).map(f=>f.nomeEnviado);
el.innerHTML='<b>JPG não entra.</b> '+
(disfarcados.length ? escapeHTML(disfarcados.join(', '))+' é JPG, mesmo com outro nome. ' : '')+
'JPG não tem fundo transparente, e o fundo '+
'sai branco no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
return;
}
el.innerHTML = ehFolha()
? '<b>'+exts+' não entra aqui.</b> A folha pronta aceita PNG, PDF, TIFF, '+
'PSD, AI e CDR, com fundo transparente.'
: '<b>'+exts+' não entra aqui.</b> Artes avulsas só aceitam PNG com '+
'fundo transparente. Para CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
}
const Z=$('zona'), I=$('inp');
Z.addEventListener('click',()=>I.click());
Z.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){I.click();e.preventDefault();}});
['dragover','dragenter'].forEach(ev=>Z.addEventListener(ev,e=>{e.preventDefault();Z.classList.add('sobre')}));
['dragleave','drop'].forEach(ev=>Z.addEventListener(ev,e=>{
e.preventDefault(); Z.classList.remove('sobre');
if(ev==='drop') sel([...e.dataTransfer.files]);
}));
I.addEventListener('change',()=>sel([...I.files]));
// Each file's upload, under the uploader (Dropstar, 2026-10-29): the bytes
// sent of its size, then the security check; a failure says why. It starts
// as soon as the file is on the page (checkout.js sends it).
// Faixas vazias no começo e no fim de uma folha pronta em PNG saem do preço e
// da impressão (Marcus, 18/11/2026). Fica 0,5 cm de margem, como na montagem,
// e só se corta faixa de mais de 1 cm. O servidor imprime só o que sobra.
const CORTE_MARGEM_CM=0.5, CORTE_MINIMO_CM=1;
function aplicaCorte(x){
x.corte=null;
if(!x.med||!x.an||!/\.png$/i.test(x.f.name)) return;
const corta=v=>v>CORTE_MINIMO_CM ? +(v-CORTE_MARGEM_CM).toFixed(2) : 0;
const topo=corta(x.an.vazioTopoCm||0), fim=corta(x.an.vazioFimCm||0);
if(!(topo||fim) || topo+fim>=x.med.alt) { x.m=x.med.alt/100; return; }
x.corte={topo, fim};
x.m=+((x.med.alt-topo-fim)/100).toFixed(4);
}
const ENVIADO_MS=4000;
const enviadoEm=new WeakMap();
// A few repaints a second, page in view or not: progress comes in far more often.
let envioQuadro=0;
function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); }
// A failed upload must show on the file's own card too (B2, Marcus 11/11):
// the same red block and "Tentar de novo" as the row under the uploader, on
// the sheet/art card itself, so the list does not look complete.
function pintaErrosDosArquivos(){
const lista=$('lista'); if(!lista || !window.dtfEnvio) return;
const decorate=(selector,items,kind)=>{
items.forEach((item,index)=>{
const card=lista.querySelector(selector.replace('{i}',index));
if(!card) return;
const estado=dtfEnvio.estado(item.f);
const atual=card.querySelector('[data-envio-falha]');
if(!estado || estado.fase!=='falhou'){ if(atual) atual.remove(); return; }
if(atual){
// Keep the block while the file is failed: a repaint for another
// file's progress must not take the button from under the pointer.
const texto=atual.querySelector('span');
if(texto) texto.textContent='Não foi possível enviar '+item.f.name+': '+
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
return;
}
const box=document.createElement('div');
box.className='envio erro';box.dataset.envioFalha='1';
const texto=document.createElement('span');
texto.textContent='Não foi possível enviar '+item.f.name+': '+
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
const button=document.createElement('button');
button.type='button';button.textContent='Tentar de novo';
button.dataset.envioCard=kind;button.dataset.envioIndex=String(index);
box.append(texto,button);card.append(box);
});
};
decorate('[data-folha="{i}"]',folhas,'folha');
decorate('[data-arte="{i}"]',artes,'arte');
}
function pintaEnvios(){
const el=$('envios'); if(!el || !window.dtfEnvio) return;
dtfEnvio.manter([...artes,...folhas].map(x=>x.f));
pintaErrosDosArquivos();
// Off the product page there is no uploader to paint under.
if(!MODOS[modo]){ el.innerHTML=''; return; }
const agora=Date.now();
el.innerHTML=(ehFolha()?folhas:artes).map((x,i)=>{
const f=x.f, e=dtfEnvio.estado(f), nome='<b>'+escapeHTML(f.name)+'</b>';
if(!e) return '';
if(e.fase==='pronto'){
if(!enviadoEm.has(f)){ enviadoEm.set(f,agora); setTimeout(agendaEnvios,ENVIADO_MS+50); }
return agora-enviadoEm.get(f)>ENVIADO_MS ? '' : '<div class="envio ok">'+icone('okCirculo')+'<span>'+nome+' enviado</span></div>';
}
if(e.fase==='falhou') return '<div class="envio erro"><span>Não foi possível enviar '+nome+': '+
escapeHTML(e.erro.replace(/\.$/,''))+'.</span><button type="button" data-envio="'+i+'">Tentar de novo</button></div>';
const pct=e.fase==='verificando' ? 100 : Math.floor(e.enviado/f.size*100);
return '<div class="envio"><span>'+(e.fase==='verificando' ? 'Verificando a segurança de '+nome+'…'
: 'Enviando '+nome+' · '+pct+'% · '+fmt(e.enviado)+' de '+fmt(f.size))+'</span>'+
'<div class="envioBarra"><i style="width:'+pct+'%"></i></div></div>';
}).join('');
}
addEventListener('dtf-envio',agendaEnvios);
$('envios').addEventListener('click',e=>{
const b=e.target.closest('[data-envio]'); if(!b || !MODOS[modo]) return;
const x=(ehFolha()?folhas:artes)[+b.dataset.envio]; if(x) dtfEnvio.deNovo(x.f);
});
$('lista').addEventListener('click',e=>{
const b=e.target.closest('[data-envio-card]'); if(!b || !window.dtfEnvio) return;
const x=(b.dataset.envioCard==='folha'?folhas:artes)[+b.dataset.envioIndex];
if(x) dtfEnvio.deNovo(x.f);
});
// A sheet with residue gets its preview circled where the dots are.
async function marcaResiduos(x){
if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return;
const marcada=await previaMarcada(x.previewSrc, x.an.pontos);
if(folhas.includes(x)){ x.previewSrc=marcada; pintaFolha(); }
}
async function sel(fs){
if(!fs.length) return;
const T=window.dtfTimings;
if(T){const now=performance.now();
if(T.montageStart==null)T.montageStart=now;
if(T.analysisStart==null)T.analysisStart=now;}
fs=await Promise.all(fs.map(nomeReal));
// Pixels cannot tell a loose artwork from a finished sheet, so the customer
// declares it by choosing the product in the selector above. The declaration is
// verified in medirFolha; the file never changes product or price on its own.
const regra = ehFolha() ? ACEITA.folha : ACEITA.avulsa;
const fora = fs.filter(f=>!regra.test(f.name));
fs = fs.filter(f=>regra.test(f.name));
recusa(fora);
const max=window.dtfUploadMaxBytes||4294967296;
const grandes=fs.filter(f=>f.size>max);
if(grandes.length){
const el=$('recusa');
el.style.display='block';
el.innerHTML='<b>Arquivo acima do limite de '+(max/1073741824).toFixed(0)+
' GB.</b> Divida a folha em partes menores antes de enviar.';
fs=fs.filter(f=>f.size<=max);
}
// A file of 0 bytes (a copy that failed, a cloud placeholder): said here,
// never sent (Sentry DTF-WEB-1B).
const vazios=fs.filter(f=>!f.size);
if(vazios.length){
const el=$('recusa');
el.style.display='block';
el.innerHTML='<b>'+escapeHTML(vazios.map(f=>f.name).join(', '))+(vazios.length>1?' estão vazios':' está vazio')+
' (0 bytes).</b> Abra o arquivo no seu computador para conferir e escolha de novo.';
fs=fs.filter(f=>f.size);
}
if(!fs.length) return;
// On their way at once; a JPG is refused at the order anyway.
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
if(ehFolha()){
const novas=fs.map(f=>({f, med:null, rep:1, m:0, corte:null, semAnalise:null, analiseInicio:Date.now()}));
folhas=folhas.concat(novas); // soma, não substitui
pintaFolha();
novas.forEach(x=>{
x.pct=5; pintaFolha();
medirFolha(x.f).then(md=>{
if(md && md.rejected){
x.measurementError=md.reason; x.pct=null; pintaFolha(); return;
}
if(md && md.dpiFolha!=null && md.dpiFolha<DPI_RECUSA) return recusaFolha(x, md);
x.med=md; if(md) x.m=md.alt/100; x.pct=55; pintaFolha();
if(md && md.grande){
// Graded at once from its size in pixels. A PNG is then read as a
// stream into a small copy: the preview, and the sheet check.
x.an={dpi:md.dpiFolha, grande:true, artes:0, residuos:0, encostadas:0,
fundoChapado:false, aproveitamento:0, alturaCm:md.alt, fonteDpi:'arquivo'};
// A JPG has no transparency: its background is always solid.
if(/\.jpe?g$/i.test(x.f.name)){ x.an={...x.an, grande:false, fundoChapado:true, residuos:0, pontos:[]}; }
if(!/\.png$/i.test(x.f.name)){ x.pct=null; pintaFolha(); return; }
x.pct=60; x.leitura={inicio:Date.now(), p:0}; pintaFolha();
let mostrado=0;
previaPngGrande(x.f, 600, p=>{
const pct=60+Math.floor(p*38);
x.leitura.p=p;
if(pct-mostrado>=1){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
}, md.larg).then(lido=>{
if(!lido && md.tall){
x.an=null;
x.measurementError='Não foi possível conferir este PNG alto. Divida a folha em partes menores antes de pagar.';
return;
}
if(lido && folhas.includes(x)){
const cv=lido.cv;
x.previewSrc=cv.toDataURL('image/webp',0.85); x.miniSrc=miniatura(cv); x.fotoSrc=miniatura(cv,480,720);
try{
const an=analisarMapa(lido.mapa);
x.an={...an, dpi:md.dpiFolha, fonteDpi:'arquivo', grande:false};
aplicaCorte(x);
}catch(e){
if(md.tall){x.an=null;x.measurementError='Não foi possível conferir este PNG alto. Divida a folha em partes menores antes de pagar.';}
}
}
}).catch(()=>{
if(md.tall){
x.an=null;
x.measurementError='Não foi possível conferir este PNG alto. Divida a folha em partes menores antes de pagar.';
}
}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); });
}else if(md && RENDERIZA.test(x.f.name)){
carregarImagem(x.f).then(async img=>{
if(img){
// Decoded once and kept: drawn from the <img>, a large sheet is
// decoded again for each strip the check reads.
const fonte=await createImageBitmap(img).catch(()=>img);
x.previewSrc=img.src; x.miniSrc=miniatura(fonte); x.fotoSrc=miniatura(fonte,480,720);
x.pct=80; pintaFolha();
let mostrado=80;
try{ x.an={...analisarMapa(await mapaDaImagem(fonte, md.larg, p=>{
const pct=80+Math.floor(p*19);
if(pct>mostrado){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
})), fonteDpi:'arquivo'}; aplicaCorte(x); }catch(e){}
if(fonte.close) fonte.close();
}
x.pct=null; pintaFolha(); marcaResiduos(x);
});
}else if(md && /\.pdf$/i.test(x.f.name) && x.f.size>GRANDE_BYTES){
x.pdfGrande=true; // a warning on the sheet, like a file opened by hand
x.pct=null; pintaFolha();
}else if(md && /\.pdf$/i.test(x.f.name)){
x.pct=70; pintaFolha();
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
if(r && r.erro){
x.semAnalise = r.erro + (r.semWorker
? ' · o navegador bloqueou a leitura em segundo plano'
: '');
}
if(r && r.tela && r.mapa){
x.miniSrc=miniatura(r.tela); x.fotoSrc=miniatura(r.tela,480,720);
x.previewSrc=r.tela.toDataURL('image/webp',0.85);
try{
x.an=analisarMapa(r.mapa);
// vetor puro não tem resolução · nota máxima, e está certo
x.an.dpi = r.dpi==null ? DPI_AVISA : r.dpi;
x.an.vetor = r.dpi==null;
x.an.fonteDpi = r.dpi==null ? 'vetor' : 'imagens';
x.an.res = r.res || null;
}catch(e){}
}
x.pct=null; pintaFolha(); marcaResiduos(x);
});
}else{ x.pct=null; pintaFolha(); }
});
});
return;
}
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:1,prop:1,giro:0,esp:false,analiseInicio:Date.now()}));
artes=novos.concat(artes); // a mais recente fica no topo da fila
recemChegada=novos[0];
pintaArtes();
$('lista').scrollIntoView({behavior:'smooth',block:'nearest'});
Promise.all(novos.map(medir)).then(pintaArtes);
}
function medir(a){
// A large artwork is measured from its header and packed from a small copy
// read as a stream (previaPngGrande); the file itself is never decoded.
if(a.f.size>GRANDE_BYTES){
return dimensoesImagem(a.f).then(async d=>{
if(!d || !(d.w>0) || !(d.h>0)){ a.decodeError=true; return a; }
a.px=d.w; a.py=d.h; a.prop=d.h/d.w; a.grande=true;
// WebP cannot be read in parts (JPG is refused): the art is placed by its
// measurements, as a full box, and the team checks it before printing.
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
a.lendo=0; a.leitura={inicio:Date.now(), p:0}; pintaArtes();
let mostrado=0;
const lido=await previaPngGrande(a.f, 1200, p=>{
const pct=Math.floor(p*100);
a.leitura.p=p;
if(pct-mostrado>=1){ mostrado=pct; a.lendo=pct; pintaProgressoArte(a); }
}, a.px/300*2.54).catch(()=>null);
const cv=lido&&lido.cv;
if(lido&&lido.mapa) guardaMapaDaArte(a, lido.mapa);
a.lendo=null;
if(cv && artes.includes(a)){ a.src=cv.toDataURL('image/webp',0.9); a.miniSrc=miniatura(cv); a.fotoSrc=miniatura(cv,480,720); }
else if(!cv) a.decodeError=true;
return a;
}).catch(()=>{ a.decodeError=true; return a; });
}
return carregarImagem(a.f).then(async img=>{
if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height; a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720);
// Read at its own pixels while the customer sets the width.
a.lendoArte=true;
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})
.finally(()=>{ a.lendoArte=false; if(artes.includes(a)) pintaArtes(); });
}
else a.decodeError=true;
return a;
});
}
// Item 4 (Dropstar, 30/10/2026): each loose artwork is checked like a sheet,
// at its own pixels: dots under 2 mm, and its thinnest stroke (item 9). Read
// once; the sizes in mm and the stroke at 300 DPI follow the width the
// customer asks for, so they are worked out again when it changes.
function guardaMapaDaArte(a,m){
a.mapa=m; a.anCm=null;
// The stroke in the art's own pixels: the map was read as if at 300 DPI.
a.tracoPx=analisarMapa(m).traco;
}
function analiseDaArte(a){
if(!a.mapa || !(a.cm>0)) return null;
if(a.anCm!==a.cm){
const m=a.mapa; m.larguraCm=a.cm; m.pxPorCm=m.wPx/a.cm;
a.an=analisarMapa(m); a.anCm=a.cm;
}
return a.an;
}
// The art's thinnest stroke at the width asked for, in pixels at 300 DPI.
function tracoDaArte(a){
if(!a.tracoPx || !(a.cm>0)) return null;
const px=Math.max(1,Math.round(a.tracoPx.px*300/dpiDe(a)));
return {px, classe:px<=4?'C1':px<=19?'C2':'C3', largos:a.tracoPx.largos, finos:a.tracoPx.finos,
proofYFraction:a.tracoPx.proofYFraction};
}
// A metragem sai do arquivo, nunca do peso em bytes.
// imagem → proporção da imagem aplicada à largura do filme
// PDF → página única lida pelo PDF.js, com boxes, rotação e UserUnit
// TIFF, PSD, AI, CDR → o navegador não abre; o cliente informa o comprimento