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

@@ -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. '+