feat: residue and a solid background stop a ready sheet before payment
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 4m10s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped

Dropstar's items 2 and 3 (2026-10-21): both were warnings the customer
could pay past; now one dot is enough to stop the order.

- every pixel is read (images in strips at 1:1, large PNGs while they
  stream, PDFs rendered in strips at about 0,2 mm): the old check shrank
  the image first and could miss a small dot, or sampled every n-th pixel
- a residue is ink under 2 mm on both sides, measured from where the ink
  starts and ends in each cell: the same dot gets the same verdict wherever
  it falls on the grid, from 0,5 to 4 mm (his acceptance test)
- a solid background is under 1,5 % of transparent pixels; a JPG sheet
  always has one
- the sheet says how many dots there are, circles them on the preview, and
  asks to erase them and send again; the order waits for the check to end
- the page no longer offers JPG for a ready sheet

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-22 16:37:46 -03:00
parent fe7bf4ef07
commit e3c31e43e5
8 changed files with 258 additions and 71 deletions

View File

@@ -349,7 +349,11 @@ two orders spent in Imprimindo together counts once; a stage's median is per
order, the sum of its passages. Layout version 3 (web/site-packing.js): rows
with exact sizes, 5 mm margins top and bottom and between rows, and across
the width 5 mm or the space left shared out equally (1,5 mm at least); the
shape packing is used only when it saves 1 cm or more. Waiting on
shape packing is used only when it saves 1 cm or more. A ready sheet with a
residue (ink under 2 mm on both sides, measured in pixels from the ink map in
web/site-sheet.js) or without transparency (under 1,5 % of transparent
pixels; every JPG) cannot be paid for; the preview circles each dot. PDFs
over 150 MB and CDR/AI/PSD/TIFF are not checked. Waiting on
Dropstar: the Tiny category/seller/tag conflict, residue and opaque background
blocking, the print-file footer, the packing margins, the DTF terms, the
manual-file value, the proof print, and mirroring.

View File

@@ -133,12 +133,15 @@ try{
if(drop)$('zona').dispatchEvent(new DragEvent('drop',{dataTransfer:dt,bubbles:true,cancelable:true}));
else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));}
};
// A genuine mounted sheet spans the film width with printable resolution.
window.sendSheet=async()=>{
// A genuine mounted sheet spans the film width with printable resolution,
// on a transparent background; or with a solid one, or a residue dot.
window.sendSheet=async({fundo=false,ponto=false}={})=>{
const cm=larguraFilme(), px=Math.ceil(cm/2.54*150);
const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6);
const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);
const ctx=c.getContext('2d');
if(fundo){ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);}
ctx.fillStyle='#222';ctx.fillRect(40,40,px/4,px/4);
if(ponto)ctx.fillRect(Math.round(px*0.8),Math.round(c.height/2),4,4);
const blob=await new Promise(r=>c.toBlob(r,'image/png'));
const dt=new DataTransfer();dt.items.add(new File([blob],'folha-montada.png',{type:'image/png'}));
$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));
@@ -273,6 +276,39 @@ try{
assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1);
await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`);
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===TABELA[modo]`),'mixed analyzed and manual sheets use table pricing');
// Residue and a solid background stop the order before payment (Dropstar,
// 2026-10-21). A residue is ink under 2 mm on both sides, measured in real
// millimetres: the same dot, wherever it falls on the 1 mm grid, gets the
// same verdict, from 0,5 to 4 mm.
assert.deepEqual(await evaluate(`(async()=>{
const medir=async(mm,dx,dy)=>{const c=document.createElement('canvas');c.width=5700;c.height=600;
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);
const lado=Math.round(mm*10);ctx.fillRect(4000+dx,300+dy,lado,lado);
return analisarMapa(await mapaDaImagem(c,57)).residuos;};
const out={};
for(const mm of [0.5,1.5,1.9,2.1,4])out[mm]=[await medir(mm,0,0),await medir(mm,5,0),await medir(mm,0,5),await medir(mm,5,5)];
return out;})()`),
{'0.5':[1,1,1,1],'1.5':[1,1,1,1],'1.9':[1,1,1,1],'2.1':[0,0,0,0],'4':[0,0,0,0]});
// A large PNG is read as a stream; every pixel goes into the same ink map.
assert.deepEqual(await evaluate(`(async()=>{
const c=document.createElement('canvas');c.width=5700;c.height=600;
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);ctx.fillRect(4005,305,12,12);
const blob=await new Promise(r=>c.toBlob(r,'image/png'));
const lido=await previaPngGrande(new File([blob],'folha.png'),600,null,57);
const a=analisarMapa(lido.mapa), b=analisarMapa(await mapaDaImagem(c,57));
return {stream:[a.residuos,a.artes,a.fundoChapado,a.pontos[0].mm],direct:[b.residuos,b.artes,b.fundoChapado,b.pontos[0].mm]};})()`),
{stream:[1,1,false,1.2],direct:[1,1,false,1.2]});
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendSheet({ponto:true})');
await waitFor(()=>evaluate(`folhas.length===1 && folhas[0].pct==null && folhas[0].an?.residuos===1`),'residue found');
await waitFor(()=>evaluate(`$('aoVivo').textContent.includes('ponto de recorte') && itemAtual===null`),'residue stops the order');
assert.equal(await evaluate(`$('lista').textContent.includes('Sobrou 1 ponto de recorte na sua folha')`),true);
await waitFor(()=>evaluate(`folhas[0].previewSrc.startsWith('data:image/webp')`),'residue circled on the preview');
await evaluate(`folhas=[];pintaFolha()`);
await evaluate('sendSheet({fundo:true})');
await waitFor(()=>evaluate(`folhas[0]?.an?.fundoChapado===true && itemAtual===null && $('aoVivo').textContent.includes('fundo transparente')`),'solid background stops the order');
assert.equal(await evaluate(`$('lista').textContent.includes('O fundo da sua folha não é transparente')`),true);
await evaluate(`folhas=[];pintaFolha()`);
// An image too small to span the film is refused, never silently repriced.
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendImage()');
@@ -296,6 +332,10 @@ try{
assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2'});
const rendered=await evaluate(`rasterizarPdf(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))},50.8,25.4).then(r=>({ok:!!r.tela,error:r.erro||null}))`);
assert.deepEqual(rendered,{ok:true,error:null});
// A PDF sheet gets the same ink map, rendered in strips: a blank page is all transparent.
const mapped=await evaluate(`rasterizarPdf(${pdfFile(pdfData())},25.4,12.7,true).then(r=>{const a=analisarMapa(r.mapa);
return {fundo:a.fundoChapado,residuos:a.residuos,largura:r.mapa.wPx}})`);
assert.deepEqual(mapped,{fundo:false,residuos:0,largura:1270});
const multi=await evaluate(`medirFolha(${pdfFile(pdfData({pages:2}))})`);
assert.equal(multi.rejected,true);assert.match(multi.reason,/2 páginas/);
const beyondSpec=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 20000 720]'}))})`);
@@ -368,6 +408,6 @@ try{
console.log('Supplied image:',JSON.stringify(layout));
}
assert.deepEqual(errors,[]);
console.log('PASS: JPG/PNG upload and drop, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, UV, stale renders, strict inline CSP.');
console.log('PASS: JPG/PNG upload and drop, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, stale renders, strict inline CSP.');
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;}
finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));}

View File

@@ -879,8 +879,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<details>
<summary>Manda em PNG e sai na hora</summary>
<ul>
<li class="s"><b>PNG ou JPG</b> com fundo transparente entram direto, sem passar
por ninguém, e não têm limite de comprimento. Só que a gente lê a resolução
<li class="s"><b>PNG</b> com fundo transparente entra direto, sem passar
por ninguém, e não tem limite de comprimento. Só que a gente lê a resolução
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
para nós — e sai serrilhado no filme do mesmo jeito</li>
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
@@ -891,6 +891,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<li class="a"><b>TIFF, PSD, AI e CDR</b> a gente aceita, mas ninguém consegue
conferir sozinho: alguém abre na mão, sai mais devagar e o metro vai pela
tabela, sem desconto de nota</li>
<li class="a"><b>Folha em JPG não passa:</b> JPG não tem fundo transparente, e o
branco do fundo sai no filme. Exporte a folha em PNG ou PDF</li>
<li class="a">Em <b>artes avulsas</b> só PNG e JPG: a montagem precisa
enxergar a sua arte para encaixar pela forma</li>
</ul>
@@ -900,9 +902,11 @@ h2 em{font-style:normal;color:var(--laranja)}
<summary>O que só você resolve</summary>
<ul>
<li class="n"><b>Fundo branco ou colorido.</b> Precisa ser transparente de
verdade — branco parecendo transparente sai branco no filme</li>
verdade — branco parecendo transparente sai branco no filme. Sem isso, o site
não deixa pagar</li>
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
resíduo e imprime. Não existe pequeno demais</li>
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
e só deixa pagar depois que você apagar</li>
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
saem duplicadas</li>
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai

View File

@@ -35,12 +35,12 @@ const fmt=b=>b<1048576?(b/1024).toFixed(0)+' KB'
// ── modos
const MODOS={
file: {tit:'Arquivo por metro', lg:'DTF têxtil · 57 cm', larg:57, multi:true, folha:true,
zt:'Arraste sua folha montada aqui', zs:'PNG, JPG ou PDF · 57 cm de largura'},
zt:'Arraste sua folha montada aqui', zs:'PNG ou PDF com fundo transparente · 57 cm de largura'},
avulsa:{tit:'Artes avulsas', lg:'DTF têxtil · 57 cm', larg:57, multi:true,
zt:'Arraste suas artes aqui',
zs:'PNG ou JPG com fundo transparente · informe a largura de cada uma'},
uvfile:{tit:'Arquivo por metro · UV', lg:'Adesivo UV · 28,5 cm', larg:28.5, multi:true, folha:true,
zt:'Arraste sua folha de UV aqui', zs:'PNG, JPG ou PDF · 28,5 cm de largura'},
zt:'Arraste sua folha de UV aqui', zs:'PNG ou PDF com fundo transparente · 28,5 cm de largura'},
uv: {tit:'Artes avulsas · UV', lg:'Adesivo UV · 28,5 cm', larg:28.5, multi:true,
zt:'Arraste suas artes de UV',
zs:'PNG ou JPG com fundo transparente · informe a largura de cada arte'}

View File

@@ -85,11 +85,14 @@ function resumoDpi(lista){
}
// Rasteriza a primeira página a 1 mm por pixel e devolve a tela para a análise
async function rasterizarPdf(file, larguraCm, alturaCm){
// The page drawn small for the preview and, with comMapa, again in strips at
// about 0,2 mm per pixel for the ink map the residue check measures.
const PDF_PX_POR_CM=50, PDF_MAPA_PX=30e6;
async function rasterizarPdf(file, larguraCm, alturaCm, comMapa){
const lib=await carregarPdfJs();
if(!lib) return {erro:'não foi possível carregar o leitor de PDF'};
// Decide after the worker check; the old timeout always used 30 seconds.
const espera=temWorker===false ? 90000 : 30000;
const espera=(temWorker===false ? 90000 : 30000)*(comMapa ? 2 : 1);
const folga=temWorker===false ? 2.2 : 1;
let loading=null, doc=null, rendering=null, expired=false, timer=null;
const trabalho=(async()=>{
@@ -117,7 +120,28 @@ async function rasterizarPdf(file, larguraCm, alturaCm){
let dpis=[];
try{ dpis=dpiDasImagens(page,ops); }catch(e){}
const r=resumoDpi(dpis);
return {tela:cv, dpi:r? r.ponderado:null, res:r};
let mapa=null;
if(comMapa){
const altura=alturaCm||larguraCm*vp1.height/vp1.width;
const pxPorCm=Math.min(PDF_PX_POR_CM, Math.sqrt(PDF_MAPA_PX/(larguraCm*altura)));
const vpM=page.getViewport({scale:pxPorCm*larguraCm/vp1.width});
const W=Math.max(1,Math.round(vpM.width)), H=Math.max(1,Math.round(vpM.height));
mapa=novoMapa(W,H,larguraCm);
const faixa=Math.max(1,Math.min(H,Math.floor(4e6/W)));
const cvM=document.createElement('canvas'); cvM.width=W; cvM.height=faixa;
const ctxM=cvM.getContext('2d',{willReadFrequently:true});
for(let topo=0;topo<H;topo+=faixa){
const n=Math.min(faixa,H-topo);
ctxM.clearRect(0,0,W,faixa);
rendering=page.render({canvasContext:ctxM, viewport:vpM, transform:[1,0,0,1,0,-topo],
background:'rgba(0,0,0,0)'});
await rendering.promise;
if(expired) return null;
const d=ctxM.getImageData(0,0,W,n).data;
for(let k=0;k<n;k++) mapaLinha(mapa,topo+k,d,k*W*4+3,4);
}
}
return {tela:cv, dpi:r? r.ponderado:null, res:r, mapa};
}catch(e){
if(expired) return null;
return {erro:(e&&e.message)||'erro ao abrir o PDF', semWorker:temWorker===false};
@@ -170,10 +194,11 @@ async function dimensoesImagem(file){
}
// A small copy of a large PNG, read as a stream: the file is inflated in
// pieces and only every n-th pixel of every n-th row is kept, so memory stays
// at a few MB whatever the file's size. It is the preview, and what the sheet
// check (pieces, gaps, background) reads. 8- and 16-bit greyscale, RGB,
// palette and alpha; interlaced files return null.
async function previaPngGrande(file, larguraAlvo, progresso){
// at a few MB whatever the file's size. It is the preview. Given the sheet's
// width in cm (mapaCm), every pixel also goes into the ink map the sheet check
// reads, and it returns {cv, mapa}. 8- and 16-bit greyscale, RGB, palette and
// alpha; interlaced files return null.
async function previaPngGrande(file, larguraAlvo, progresso, mapaCm){
const leitor=file.stream().getReader();
let pedacos=[], guardado=0, lidos=0, fim=false;
// A queue of the file's pieces: take() never copies more than it returns.
@@ -234,6 +259,18 @@ async function previaPngGrande(file, larguraAlvo, progresso){
const cw=Math.ceil(w/passo), ch=Math.ceil(h/passo);
const cv=document.createElement('canvas'); cv.width=cw; cv.height=ch;
const ctx=cv.getContext('2d'), img=ctx.createImageData(cw,1), px=img.data;
// The ink map reads each pixel's alpha: from the row itself when the file has
// an alpha channel, else from the palette or the transparent colour.
const mapa=mapaCm ? novoMapa(w,h,mapaCm) : null;
const alfaLinha=mapa && ![4,6].includes(tipo) ? new Uint8Array(w).fill(255) : null;
const alfaDaLinha=()=>{
if(tipo===3){ for(let x=0;x<w;x++){ const q=atual[x]; alfaLinha[x]=trns&&q<trns.length?trns[q]:255; } }
else if(trns && tipo===0){ for(let x=0,i=0;x<w;x++,i+=bpp)
alfaLinha[x]=atual[i]===trns[2-b] && (b===1||atual[i+1]===trns[1]) ? 0 : 255; }
else if(trns && tipo===2){ for(let x=0,i=0;x<w;x++,i+=bpp){ let igual=true;
for(let k=0;k<3&&igual;k++) igual=atual[i+k*b]===trns[k*2+2-b] && (b===1||atual[i+k*b+1]===trns[k*2+1]);
alfaLinha[x]=igual?0:255; } }
};
// Each row is gathered whole (filter byte + data), then unfiltered in one
// tight loop for its filter type.
let ant=new Uint8Array(linha), atual=new Uint8Array(linha), y=0;
@@ -261,6 +298,11 @@ async function previaPngGrande(file, larguraAlvo, progresso){
cheio=0;
// Every row is unfiltered: Up, Average and Paeth read the previous one.
desfiltra();
if(mapa){
if(tipo===6) mapaLinha(mapa,y,atual,3*b,bpp);
else if(tipo===4) mapaLinha(mapa,y,atual,b,bpp);
else{ alfaDaLinha(); mapaLinha(mapa,y,alfaLinha,0,1); }
}
if(y%passo===0 && y/passo<ch){
for(let xx=0,k=0;xx<w;xx+=passo,k+=4){
const i=xx*bpp;
@@ -277,7 +319,8 @@ async function previaPngGrande(file, larguraAlvo, progresso){
}
await alimenta.catch(()=>{});
leitor.cancel().catch(()=>{});
return y>=h ? cv : null;
if(y<h) return null;
return mapa ? {cv, mapa} : cv;
}
// Large PDFs are read in ranges, never loaded whole into memory.
async function fontePdf(lib, file){
@@ -366,6 +409,26 @@ function miniatura(fonte, maxW=104, maxH=192){
cv.getContext('2d').drawImage(fonte,0,0,cv.width,cv.height);
return cv.toDataURL('image/webp',0.8);
}
// The preview with a red circle around each residue dot and its size, so the
// customer finds what to erase: on the screen they are invisible.
async function previaMarcada(src, pontos){
const img=await new Promise(res=>{ const im=new Image(); im.onload=()=>res(im); im.onerror=()=>res(null); im.src=src; });
if(!img) return src;
const s=Math.min(1,1200/img.naturalWidth), cv=document.createElement('canvas');
cv.width=Math.max(1,Math.round(img.naturalWidth*s)); cv.height=Math.max(1,Math.round(img.naturalHeight*s));
const ctx=cv.getContext('2d');
ctx.drawImage(img,0,0,cv.width,cv.height);
const r=Math.max(9,cv.width*0.014);
ctx.lineWidth=Math.max(2,r/4); ctx.strokeStyle='#E0301E'; ctx.font='700 '+Math.round(r*1.1)+'px Inter, sans-serif';
for(const p of pontos){
const x=p.x*cv.width, y=p.y*cv.height;
ctx.beginPath(); ctx.arc(x,y,r,0,2*Math.PI); ctx.stroke();
const t=n1(p.mm)+' mm', tw=ctx.measureText(t).width, tx=Math.min(x+r+4,cv.width-tw-4);
ctx.fillStyle='rgba(255,255,255,.9)'; ctx.fillRect(tx-3,y-r*0.7,tw+6,r*1.4);
ctx.fillStyle='#E0301E'; ctx.fillText(t,tx,y+r*0.4);
}
return cv.toDataURL('image/webp',0.9);
}
// Moves one sheet's progress bar in place: repainting the whole list and the
// preview on every step made "Sua folha" flicker while a large file was read.
function pintaProgressoFolha(x){
@@ -381,17 +444,27 @@ function chipsDaFolha(a){
const dpi = a.vetor ? chip('ok','Arte vetorial')
: chip(a.dpi>=DPI_AVISA?'ok':a.dpi>=DPI_RECUSA?'av':'er', a.dpi+' DPI');
if(a.grande) return dpi+chip('nt','Peças, resíduos e fundo: a equipe confere');
return dpi+
(a.fundoChapado? chip('er','Fundo chapado') : chip('ok','Fundo transparente'))+
// Sem transparência a folha inteira é uma peça só: não há resíduo a contar.
if(a.fundoChapado) return dpi+chip('er','Fundo chapado');
return dpi+chip('ok','Fundo transparente')+
(a.residuos? chip('er',a.residuos+' resíduo'+(a.residuos>1?'s':'')) : chip('ok','Sem resíduos'))+
(a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos grátis') : chip('ok','Peças separadas'));
}
function avisosDaFolha(a){
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema".
function avisosDaFolha(a,nome){
if(a.grande) return '';
return (a.fundoChapado? '<p class="avisoF"><b>O fundo não é transparente.</b> '+
'Branco parecendo transparente sai branco no filme. Exporte com fundo transparente.</p>' : '')+
(a.residuos? '<p class="avisoF"><b>'+a.residuos+' pontinho'+(a.residuos>1?'s soltos serão impressos':' solto será impresso')+
'.</b> A impressora imprime qualquer resíduo de recorte. Apague no arquivo e envie de novo.</p>' : '');
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+
'no filme. Exporte a folha em PNG ou PDF, com fundo transparente, e envie de novo.</p>'
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> O que parece branco na tela sai '+
'branco no filme. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
if(!a.residuos) return '';
const n=a.residuos, varios=n>1;
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+'</p>';
}
function detalhesDaFolha(a,i,aberto){
const linhas = a.grande
@@ -423,7 +496,7 @@ function pintaFolha(){
if(lido){
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
(a? '<ul class="chips">'+chipsDaFolha(a)+'</ul>'+avisosDaFolha(a)+detalhesDaFolha(a,i,x.detAberto) : '')+
(a? '<ul class="chips">'+chipsDaFolha(a)+'</ul>'+avisosDaFolha(a,x.f.name)+detalhesDaFolha(a,i,x.detAberto) : '')+
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
'Ele abre certo só em quem o gerou — aqui vai precisar de tratamento. '+

View File

@@ -3,6 +3,9 @@
Loaded as classic scripts in the order listed there: they share one global
scope and run top to bottom, exactly as the original did. */
// ── enviar
// Folha que a impressora estragaria: com resíduo de recorte ou sem fundo
// transparente. Só vale para o que o navegador conferiu.
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || x.an.residuos));
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
// para a fila dizer em texto em vez de travar num botão.
function avaliar(){
@@ -16,6 +19,15 @@ function avaliar(){
const semMedida=folhas.filter(x=>!(x.m>0)).length;
if(semMedida) return {pronto:false, falta:'Informe o comprimento de '+semMedida+
' folha'+(semMedida>1?'s':'')+'.'};
// Resíduo e fundo chapado barram antes do pagamento, com um ponto só
// (Dropstar, 21/10/2026): então o pedido espera a conferência terminar.
const lendo=folhas.find(x=>x.pct!=null);
if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'…'};
const barrada=folhas.find(folhaBarrada);
if(barrada) return {pronto:false, falta:barrada.an.fundoChapado
? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.'
: barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+
' de recorte. Apague e envie de novo.'};
metros=folhaTotalM();
reencaixado=false;
const ans=folhas.map(x=>x.an).filter(Boolean);

View File

@@ -3,7 +3,7 @@
Loaded as classic scripts in the order listed there: they share one global
scope and run top to bottom, exactly as the original did. */
// ── Análise real da folha: lê o canal alfa, separa cada ilha de arte e mede.
// Grade de 1 mm. Só roda em arquivo que o navegador abre; PDF precisa do servidor.
// A grade de 1 mm agrupa a tinta; a medida de cada ilha sai dos pixels.
const MM=0.1; // grade fina: 1 mm
const CELULAS_MAX=1200000; // teto de custo da análise
// Folha grande vira grade mais grossa. Sem isso, 57 x 480 cm dá 2,7 milhões de
@@ -46,39 +46,75 @@ function grupos(bits,cw,ch){
return {marca,n};
}
// ── Mapa de tinta: cada pixel da folha lido, nenhum pulado.
// Regra da Dropstar (21/10/2026): resíduo é uma ilha de tinta menor que 2 mm
// nos dois lados, e um ponto só já barra o pedido. Reduzir a imagem antes de
// olhar perde ponto pequeno, e medir pela grade erra até uma célula: o mesmo
// ponto de 1,5 mm saía resíduo ou arte conforme caía na grade. Aqui a grade só
// agrupa; cada célula guarda onde a tinta começa e termina, em pixels, e cada
// ilha é medida por esses extremos, em milímetros reais.
const ALFA_TINTA=10; // acima disto o pixel leva tinta (e branco de base)
function novoMapa(wPx,hPx,larguraCm){
const pxPorCm=wPx/larguraCm, passo=passoDe(larguraCm,hPx/pxPorCm), pxCel=passo*pxPorCm;
const cw=Math.max(1,Math.ceil(wPx/pxCel)), ch=Math.max(1,Math.ceil(hPx/pxCel)), n=cw*ch;
const colDe=new Uint32Array(wPx);
for(let x=0;x<wPx;x++) colDe[x]=Math.min(cw-1,Math.floor(x/pxCel));
return {wPx,hPx,larguraCm,pxPorCm,passo,pxCel,cw,ch,colDe,bits:new Uint8Array(n),
x0:new Uint32Array(n),x1:new Uint32Array(n),y0:new Uint32Array(n),y1:new Uint32Array(n),tinta:0};
}
// A linha y da folha: o alfa de cada pixel em alfa[inicio + x*de].
function mapaLinha(m,y,alfa,inicio,de){
const base=Math.min(m.ch-1,Math.floor(y/m.pxCel))*m.cw;
const {bits,x0,x1,y0,y1,colDe}=m;
let tinta=0;
for(let x=0,i=inicio;x<m.wPx;x++,i+=de){
if(alfa[i]<=ALFA_TINTA) continue;
tinta++;
const c=base+colDe[x];
if(!bits[c]){ bits[c]=1; x0[c]=x1[c]=x; y0[c]=y1[c]=y; }
else{ if(x<x0[c]) x0[c]=x; else if(x>x1[c]) x1[c]=x; y1[c]=y; }
}
m.tinta+=tinta;
}
// Uma imagem que o navegador abre, lida em faixas no tamanho real (1:1).
async function mapaDaImagem(img,larguraCm){
const w=img.naturalWidth||img.width, h=img.naturalHeight||img.height;
const m=novoMapa(w,h,larguraCm);
const faixa=Math.max(1,Math.min(h,Math.floor(4e6/w)));
const cv=document.createElement('canvas'); cv.width=w; cv.height=faixa;
const ctx=cv.getContext('2d',{willReadFrequently:true});
ctx.imageSmoothingEnabled=false;
for(let topo=0;topo<h;topo+=faixa){
const n=Math.min(faixa,h-topo);
ctx.clearRect(0,0,w,faixa);
ctx.drawImage(img,0,topo,w,n,0,0,w,n);
const d=ctx.getImageData(0,0,w,n).data;
for(let r=0;r<n;r++) mapaLinha(m,topo+r,d,r*w*4+3,4);
await new Promise(r=>setTimeout(r)); // a página não congela
}
return m;
}
// ── O que a folha permite medir, e só isso.
// Peça = pixels a menos de 2 mm entre si · letras de uma palavra ficam juntas.
// Peça = tinta a menos de 2 mm entre si · letras de uma palavra ficam juntas.
// Encostadas = peças que só se unem quando a folga chega a 6 mm.
const R_PECA=1, R_PERTO=2; // peça: 2 mm · aviso de encostadas: 4 mm
function analisarFolha(img, larguraCm){
const alturaCmEst=larguraCm*img.height/img.width;
const passo=passoDe(larguraCm, alturaCmEst);
const cw=Math.max(8,Math.round(larguraCm/passo));
const ch=Math.max(8,Math.round(cw*img.height/img.width));
const cv=document.createElement('canvas'); cv.width=cw; cv.height=ch;
const ctx=cv.getContext('2d',{willReadFrequently:true});
ctx.clearRect(0,0,cw,ch); ctx.drawImage(img,0,0,cw,ch);
const d=ctx.getImageData(0,0,cw,ch).data;
const bits=new Uint8Array(cw*ch);
let opacos=0;
for(let i=0,j=3;i<bits.length;i++,j+=4) if(d[j]>10){ bits[i]=1; opacos++; }
// peças: agrupa pela distância real entre pixels
const RESIDUO_MM=2;
function analisarMapa(m){
const {cw,ch,bits}=m;
const gp=grupos(inchar(bits,cw,ch,R_PECA), cw, ch);
const caixas=[];
for(let p=0;p<bits.length;p++){
if(!bits[p]) continue;
const id=gp.marca[p]; if(id<0) continue;
const x=p%cw, y=(p/cw)|0;
const c=caixas[id] || (caixas[id]={x0:x,x1:x,y0:y,y1:y,area:0,id});
if(x<c.x0)c.x0=x; if(x>c.x1)c.x1=x; if(y<c.y0)c.y0=y; if(y>c.y1)c.y1=y;
c.area++;
const c=caixas[id] || (caixas[id]={x0:m.x0[p],x1:m.x1[p],y0:m.y0[p],y1:m.y1[p],id});
if(m.x0[p]<c.x0)c.x0=m.x0[p]; if(m.x1[p]>c.x1)c.x1=m.x1[p];
if(m.y0[p]<c.y0)c.y0=m.y0[p]; if(m.y1[p]>c.y1)c.y1=m.y1[p];
}
const pecasTodas=caixas.filter(Boolean);
const limRes=Math.max(1, Math.round(0.2/passo)); // 2 mm na grade em uso
const residuos=pecasTodas.filter(o=>(o.x1-o.x0)<limRes && (o.y1-o.y0)<limRes);
const artes=pecasTodas.filter(o=>!((o.x1-o.x0)<limRes && (o.y1-o.y0)<limRes));
const mm=px=>px/m.pxPorCm*10;
const ilhas=caixas.filter(Boolean).map(c=>({...c, wMm:mm(c.x1-c.x0+1), hMm:mm(c.y1-c.y0+1)}));
const residuos=ilhas.filter(c=>c.wMm<RESIDUO_MM && c.hMm<RESIDUO_MM);
const deResiduo=new Set(residuos.map(c=>c.id));
// encostadas: peças diferentes que se unem quando a folga chega a 6 mm
const gper=grupos(inchar(bits,cw,ch,R_PERTO), cw, ch);
@@ -86,22 +122,27 @@ function analisarFolha(img, larguraCm){
for(let p=0;p<bits.length;p++){
if(!bits[p]) continue;
const a=gp.marca[p], b=gper.marca[p];
if(a<0||b<0) continue;
if(a<0||b<0||deResiduo.has(a)) continue;
if(!porPerto.has(b)) porPerto.set(b,new Set());
porPerto.get(b).add(a);
}
let encostadas=0;
porPerto.forEach(set=>{ if(set.size>1) encostadas+=set.size; });
const total=m.wPx*m.hPx;
return {
dpi: Math.round(img.width/(larguraCm/2.54)),
artes: artes.length,
dpi: Math.round(m.wPx/(m.larguraCm/2.54)),
artes: ilhas.length-residuos.length,
residuos: residuos.length,
// Onde está cada ponto, em fração da folha: os círculos da prévia.
pontos: residuos.map(c=>({x:(c.x0+c.x1+1)/2/m.wPx, y:(c.y0+c.y1+1)/2/m.hPx,
mm:+Math.max(c.wMm,c.hMm).toFixed(1)})),
encostadas,
fundoChapado: opacos/(cw*ch) > 0.985,
aproveitamento: Math.max(1,Math.min(100,Math.round(opacos/(cw*ch)*100))),
alturaCm: ch*passo,
grade: +(passo*10).toFixed(1) // mm por célula analisada
// Sem transparência: o que parece branco na tela sai branco no filme.
fundoChapado: (total-m.tinta)/total < 0.015,
aproveitamento: Math.max(1,Math.min(100,Math.round(m.tinta/total*100))),
alturaCm: m.hPx/m.pxPorCm,
grade: +(m.passo*10).toFixed(1) // mm por célula que agrupa
};
}

View File

@@ -28,6 +28,12 @@ Z.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){I.click();e.pr
if(ev==='drop') sel([...e.dataTransfer.files]);
}));
I.addEventListener('change',()=>sel([...I.files]));
// 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(); }
}
function sel(fs){
if(!fs.length) return;
// Pixels cannot tell a loose artwork from a finished sheet, so the customer
@@ -64,6 +70,8 @@ function sel(fs){
// 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;
@@ -71,36 +79,41 @@ function sel(fs){
const pct=60+Math.floor(p*38);
x.leitura.p=p;
if(pct-mostrado>=1){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
}).then(cv=>{
if(cv && folhas.includes(x)){
}, md.larg).then(lido=>{
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=analisarFolha(cv, md.larg);
const an=analisarMapa(lido.mapa);
x.an={...an, dpi:md.dpiFolha, fonteDpi:'arquivo', grande:false};
}catch(e){}
}
}).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); });
}).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); });
}else if(md && RENDERIZA.test(x.f.name)){
carregarImagem(x.f).then(img=>{
if(img){ x.previewSrc=img.src; x.miniSrc=miniatura(img); x.fotoSrc=miniatura(img,480,720); try{ x.an=analisarFolha(img, md.larg); if(x.an) x.an.fonteDpi='arquivo'; }
catch(e){} }
x.pct=null; pintaFolha();
carregarImagem(x.f).then(async img=>{
if(img){
x.previewSrc=img.src; x.miniSrc=miniatura(img); x.fotoSrc=miniatura(img,480,720);
x.pct=80; pintaFolha();
try{ x.an={...analisarMapa(await mapaDaImagem(img, md.larg)), fonteDpi:'arquivo'}; }catch(e){}
}
x.pct=null; pintaFolha(); marcaResiduos(x);
});
}else if(md && /\.pdf$/i.test(x.f.name) && x.f.size>GRANDE_BYTES){
x.semAnalise='PDF grande: a resolução das imagens de dentro é conferida pela equipe';
x.pct=null; pintaFolha();
}else if(md && /\.pdf$/i.test(x.f.name)){
x.pct=70; pintaFolha();
rasterizarPdf(x.f, md.larg, md.alt).then(r=>{
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
if(r && r.erro){
x.semAnalise = r.erro + (r.semWorker
? ' · este navegador não deixa o leitor rodar em segundo plano'
: '');
}
if(r && r.tela){
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=analisarFolha(r.tela, md.larg);
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;
@@ -108,7 +121,7 @@ function sel(fs){
x.an.res = r.res || null;
}catch(e){}
}
x.pct=null; pintaFolha();
x.pct=null; pintaFolha(); marcaResiduos(x);
});
}else{ x.pct=null; pintaFolha(); }
});