feat: the site's third-round corrections on acceptance, DPI and the final file
Residue and thin strokes can be accepted on ready sheets and loose art, with the consent and its time kept on the order. The resolution rule is 96/200 DPI, and a final file must be a transparent 300 DPI PNG. The art score leaves the customer's cart and buy box (Dropstar, 2026-11-05).
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -13,7 +14,7 @@ from ..core.auth import owner
|
||||
from ..core.models import QuoteRequest
|
||||
from ..core.pricing import price
|
||||
from .. import quote_review
|
||||
from ..grade_check import Files, mismatch
|
||||
from ..grade_check import Files, mismatch, resolution_issue
|
||||
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||
from ..scanning import require_clean
|
||||
|
||||
@@ -27,6 +28,12 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
require_delivery_available(body.freight.service)
|
||||
draft = body.model_dump(mode='json', exclude={'request_key'})
|
||||
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||
accepted_at = datetime.now(timezone.utc).isoformat()
|
||||
for item in draft['items']:
|
||||
if item.get('residue_accepted'):
|
||||
item['residue_accepted_at'] = accepted_at
|
||||
if item.get('stroke_choice'):
|
||||
item['stroke_choice_at'] = accepted_at
|
||||
reason = quote_review.review_reason(draft)
|
||||
if reason is not None:
|
||||
# Waits for review: check the delivery now, priced at approval.
|
||||
@@ -51,7 +58,11 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
# The grade came from the browser and is shown with the order (it no
|
||||
# longer sets the price): before a cart is approved at checkout, the
|
||||
# server works it out from the files.
|
||||
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
|
||||
files = Files(storage)
|
||||
issue = resolution_issue(files, draft['items'], rows)
|
||||
if issue:
|
||||
raise HTTPException(422, issue)
|
||||
note = mismatch(files, draft['items'], rows) if reason is None else None
|
||||
reason = reason or note
|
||||
uid = uuid4()
|
||||
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
|
||||
|
||||
@@ -23,7 +23,9 @@ import os
|
||||
import struct
|
||||
import tempfile
|
||||
|
||||
DPI_IDEAL = 300
|
||||
DPI_IDEAL = 200
|
||||
DPI_REFUSE = 96
|
||||
PDF_VECTOR_DPI = 300
|
||||
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
|
||||
# grade them, so neither does this.
|
||||
PDF_MAX_BYTES = 150 * 1048576
|
||||
@@ -123,7 +125,7 @@ def pdf_dpi(path):
|
||||
return None
|
||||
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
||||
if not found:
|
||||
return DPI_IDEAL
|
||||
return PDF_VECTOR_DPI
|
||||
total = sum(area for _, area in found) or 1
|
||||
return js_round(sum(dpi * area for dpi, area in found) / total)
|
||||
|
||||
@@ -178,6 +180,31 @@ def item_grade(files, item, rows):
|
||||
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
|
||||
|
||||
|
||||
def resolution_issue(files, items, rows):
|
||||
"""Refuse sub-96 DPI and require recorded consent for measurable 96–199 DPI.
|
||||
|
||||
Unknown formats remain for manual review; they cannot be treated as a
|
||||
measured zero DPI or silently called high-resolution artwork.
|
||||
"""
|
||||
for index, item in enumerate(items, 1):
|
||||
dpis = []
|
||||
for source in item['production']['sources']:
|
||||
row = rows.get(str(source['upload_id']))
|
||||
dpi = source_dpi(files, row, source) if row else None
|
||||
if dpi is None:
|
||||
dpis = []
|
||||
break
|
||||
dpis.append(dpi)
|
||||
if not dpis:
|
||||
continue
|
||||
lowest = min(dpis)
|
||||
if lowest < DPI_REFUSE:
|
||||
return f'Item {index}: resolução de {js_round(lowest)} DPI abaixo do mínimo de {DPI_REFUSE} DPI.'
|
||||
if lowest < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']):
|
||||
return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.'
|
||||
return None
|
||||
|
||||
|
||||
def mismatch(files, items, rows):
|
||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||
for item in items:
|
||||
|
||||
@@ -78,9 +78,13 @@ def approve(c, row, items, reviewer):
|
||||
'quality_status': original['quality_status'],
|
||||
'quality_acknowledged': original['quality_acknowledged'],
|
||||
'residue_accepted': original.get('residue_accepted', 0),
|
||||
**({'residue_accepted_at': original['residue_accepted_at']}
|
||||
if original.get('residue_accepted_at') else {}),
|
||||
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
|
||||
if original.get('stroke_class') else {}),
|
||||
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
|
||||
**({'stroke_choice_at': original['stroke_choice_at']}
|
||||
if original.get('stroke_choice_at') else {}),
|
||||
**({'split': original['split']} if original.get('split') else {})})
|
||||
bill_splits(priced)
|
||||
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||
|
||||
@@ -62,25 +62,43 @@ class GradeCheckTests(unittest.TestCase):
|
||||
self.assertEqual(grade_check.pdf_dpi(handle.name), 300)
|
||||
|
||||
def test_grades_follow_the_site(self):
|
||||
# 57 cm is 22.44 in: 6059 px is 270 DPI, grade 90; 3366 px is 150 DPI, grade 50.
|
||||
# 57 cm is 22.44 in: the new clean threshold is 200 DPI.
|
||||
files = FakeFiles({'a.png': encoded('PNG', (6059, 100)), 'b.jpg': encoded('JPEG', (3366, 100)),
|
||||
'tall.png': encoded('PNG', (100, 2362)), 'x.cdr': b'CDR'})
|
||||
rows = {n: {'name': n, 'size': 1} for n in files.blobs}
|
||||
# A sheet takes the worst sheet's grade.
|
||||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 90)
|
||||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 50)
|
||||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 100)
|
||||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 75)
|
||||
# Artworks average; a rotated one is measured along its height.
|
||||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 70)
|
||||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 88)
|
||||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('tall.png', 20, 90)]), rows), 100)
|
||||
self.assertIsNone(grade_check.item_grade(files, item('sheet', 0, [('x.cdr', 57, 0)]), rows))
|
||||
# What the cart claims is checked, with a point or two of rounding.
|
||||
claim = lambda g, src: grade_check.mismatch(files, [item('sheet', g, src)], rows)
|
||||
self.assertIsNone(claim(90, [('a.png', 57, 0)]))
|
||||
self.assertIsNone(claim(92, [('a.png', 57, 0)]))
|
||||
self.assertEqual(claim(100, [('a.png', 57, 0)]), 'Nota 100 maior que a do arquivo (90)')
|
||||
self.assertIsNone(claim(100, [('a.png', 57, 0)]))
|
||||
self.assertIsNone(claim(77, [('b.jpg', 57, 0)]))
|
||||
self.assertEqual(claim(100, [('b.jpg', 57, 0)]), 'Nota 100 maior que a do arquivo (75)')
|
||||
self.assertEqual(claim(40, [('x.cdr', 57, 0)]), 'Nota não conferida no servidor')
|
||||
self.assertIsNone(claim(0, [('x.cdr', 57, 0)]))
|
||||
|
||||
def test_resolution_boundaries_and_consent(self):
|
||||
width = lambda dpi: int(dpi * 57 / 2.54) + 1
|
||||
files = FakeFiles({f'{dpi}.png': encoded('PNG', (width(dpi), 20))
|
||||
for dpi in (95, 96, 199, 200, 287, 293)})
|
||||
rows = {name: {'name': name, 'size': 1} for name in files.blobs}
|
||||
def issue(dpi, status='ok', acknowledged=False):
|
||||
spec = item('sheet', 0, [(f'{dpi}.png', 57, 0)])
|
||||
spec.update(quality_status=status, quality_acknowledged=acknowledged)
|
||||
return grade_check.resolution_issue(files, [spec], rows)
|
||||
self.assertIn('abaixo do mínimo', issue(95))
|
||||
self.assertIn('confirme a ressalva', issue(96))
|
||||
self.assertIn('confirme a ressalva', issue(199))
|
||||
self.assertIsNone(issue(96, 'warning', True))
|
||||
self.assertIsNone(issue(199, 'warning', True))
|
||||
for dpi in (200, 287, 293):
|
||||
self.assertIsNone(issue(dpi), dpi)
|
||||
self.assertEqual(grade_check.grade_of(dpi), 100)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -906,7 +906,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
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: o site mostra onde cada um está
|
||||
e só deixa pagar depois que você apagar</li>
|
||||
e pede que você apague ou aceite imprimir assim</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
|
||||
@@ -929,7 +929,6 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="compra" id="compra">
|
||||
<div class="aoVivo" id="aoVivo"></div>
|
||||
<div id="compraVals" hidden>
|
||||
<div class="cLin"><span>Nota da arte</span><b id="cNota">—</b></div>
|
||||
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
|
||||
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
|
||||
<p class="cObs" id="cObs"></p>
|
||||
@@ -971,10 +970,9 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="qh">
|
||||
<div><h3 id="qNome">sua folha</h3>
|
||||
<span style="font-size:14.5px;color:var(--fraco)" id="qSub"></span></div>
|
||||
<div style="text-align:right"><div class="pct" id="pct">—</div>
|
||||
<span style="font-size:13.5px;color:var(--fraco)">qualidade</span></div>
|
||||
<div style="display:none"><div class="pct" id="pct">—</div></div>
|
||||
</div>
|
||||
<div class="qbar"><i id="qbi" style="width:0%"></i></div>
|
||||
<div class="qbar" style="display:none"><i id="qbi" style="width:0%"></i></div>
|
||||
<div class="qitens" id="qitens"></div>
|
||||
<div class="qbts">
|
||||
<button class="qb chama" id="qOk">Seguir para o pedido</button>
|
||||
|
||||
@@ -144,7 +144,7 @@ function carrinho(){
|
||||
residueAccepted:residuosAceitos(),
|
||||
// The thinnest stroke and its contraction class (item 9), for the room.
|
||||
...tracoDoItem(),
|
||||
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m · nota '+nota};
|
||||
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m'};
|
||||
pintaPedido();
|
||||
previa();
|
||||
}
|
||||
|
||||
@@ -9,9 +9,6 @@
|
||||
vals.hidden=!it;
|
||||
add.disabled=!it || !itemPodeEnviar(it);
|
||||
if(!it) return;
|
||||
// One price per product (Dropstar, 2026-10-23): the grade is shown to explain
|
||||
// the file, on its own line, and never changes the metre.
|
||||
$('cNota').textContent = it.nota ? it.nota+'/100' : '—';
|
||||
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
||||
$('cMetro').textContent=rs(it.unit);
|
||||
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
||||
|
||||
@@ -67,7 +67,7 @@ const ACEITA={
|
||||
avulsa: /[.](png|webp)$/i
|
||||
};
|
||||
const MEDE=/[.](png|jpe?g|webp|gif|bmp|pdf)$/i;
|
||||
const DPI_RECUSA=96, DPI_AVISA=300; // régua dos designers · 02/09/2026
|
||||
const DPI_RECUSA=96, DPI_AVISA=200; // régua aprovada pela Dropstar · 05/11/2026
|
||||
// A especificação do PDF limita a página a 14.400 unidades — 200 pol, 508 cm.
|
||||
// Passar disso só é válido com UserUnit (PDF 1.6+), que a maioria dos programas
|
||||
// não escreve: o arquivo sai fora do padrão e só o gerador lê direito.
|
||||
|
||||
@@ -505,7 +505,6 @@ function previa(){
|
||||
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
|
||||
? '5 mm entre as artes e nas bordas'
|
||||
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
|
||||
[nota>=75?'var(--verde)':'var(--laranja)', nota>=75?'✓':'!','Qualidade da folha',motivoNota()],
|
||||
['var(--verde)','✓','Metragem proporcional',
|
||||
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
|
||||
' m · arredondamos só até os 10 cm mais próximos'],
|
||||
|
||||
@@ -333,6 +333,16 @@ async function fontePdf(lib, file){
|
||||
function medirFolha(file){
|
||||
return new Promise(res=>{
|
||||
const nome=(file.name||'').toLowerCase();
|
||||
if(/\.png$/.test(nome)){
|
||||
dimensoesImagem(file).then(d=>{
|
||||
if(!d || !(d.w>0) || !(d.h>0)) return res({rejected:true,reason:'Não foi possível ler as dimensões do PNG. Exporte novamente.'});
|
||||
const L=larguraFilme(), measure={larg:L,alt:+(d.h/d.w*L).toFixed(1),
|
||||
fonte:'dimensões do arquivo',dpiFolha:Math.round(d.w/(L/2.54)),px:d.w};
|
||||
if(d.h>32767 || file.size>GRANDE_BYTES) return res({...measure,grande:true,tall:d.h>32767});
|
||||
carregarImagem(file).then(img=>res(img&&img.width?{...measure,fonte:'proporção da imagem'}:null));
|
||||
}).catch(()=>res({rejected:true,reason:'Não foi possível ler o PNG. Exporte novamente.'}));
|
||||
return;
|
||||
}
|
||||
if(RENDERIZA.test(nome) && file.size>GRANDE_BYTES){
|
||||
dimensoesImagem(file).then(d=>{
|
||||
if(!d || !(d.w>0) || !(d.h>0)) return res(null);
|
||||
@@ -453,9 +463,7 @@ function chipsDaFolha(a,aceito){
|
||||
}
|
||||
// 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". O
|
||||
// resíduo o cliente pode aceitar imprimir (29/10/2026); marcado, o aviso sai
|
||||
// e fica só o aceite. Só na arte avulsa (Dropstar, 03/11/2026): a folha pronta
|
||||
// com resíduo volta, porque o designer não limpa folha fechada.
|
||||
// resíduo o cliente pode aceitar imprimir em ambos os caminhos.
|
||||
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||
if(a.grande) return '';
|
||||
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
|
||||
@@ -466,8 +474,7 @@ function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||
if(!a.residuos) return '';
|
||||
const n=a.residuos, varios=n>1;
|
||||
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
|
||||
'<span>Esta arte tem '+n+(varios?' pontos menores':' ponto menor')+' que 2 mm. Estou ciente e aceito '+
|
||||
'imprimir assim — '+(varios?'eles podem':'ele pode')+' se perder no recorte.</span></label>';
|
||||
'<span>Esses pontos fazem parte da arte. Li e concordo em imprimir assim — eles podem sair no recorte.</span></label>';
|
||||
if(aceitavel && aceito) return aceite;
|
||||
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 '+
|
||||
@@ -505,7 +512,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,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x))+
|
||||
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
|
||||
detalhesDaFolha(a,i,x.detAberto) : '')+
|
||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||
@@ -736,14 +743,9 @@ function resumoArtes(){
|
||||
if(!prontas.length){ r.style.display='none'; return; }
|
||||
const m=montagemCm/100; // a mesma folha que aparece ao lado
|
||||
const cob=montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(m);
|
||||
const notas=prontas.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
|
||||
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
||||
const falta=artes.length-prontas.length;
|
||||
r.style.display='block'; r.className='resumoA on';
|
||||
r.innerHTML='<div class="r"><span>artes com tamanho</span><b>'+prontas.length+' de '+artes.length+'</b></div>'+
|
||||
'<div class="r"><span>qualidade média</span><b style="color:'+
|
||||
(media>=85?'var(--verde)':media>=50?'var(--laranja)':'var(--vermelho)')+'">'+media+'%</b></div>'+
|
||||
(pior<media?'<div class="r"><span>a pior arte</span><b>'+pior+'%</b></div>':'')+
|
||||
(m>0?'<div class="r"><span>'+(montagemFolhas?montagemFolhas.length+' folhas montadas':'folha montada')+'</span><b>'+fmtM(m)+' m</b></div>'+
|
||||
(cob>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cob)+
|
||||
' m'+(cob===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
// transparente. Só vale para o que o navegador conferiu. O resíduo que o
|
||||
// cliente aceita imprimir (Dropstar, 29/10/2026: às vezes os pontos são da
|
||||
// arte) não barra; o fundo chapado barra sempre.
|
||||
// A folha pronta não aceita resíduo (Dropstar, 03/11/2026): só a arte avulsa.
|
||||
const residuoAceito=()=>false;
|
||||
const residuoAceito=x=>!!x.residuoAceito;
|
||||
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x))));
|
||||
// Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item.
|
||||
// the sheet of loose art inherits what each artwork accepted
|
||||
@@ -37,12 +36,11 @@ function perguntaMista(){
|
||||
const lista=ehFolha()?folhas:artes;
|
||||
const x=lista.find(y=>!y.mistaVista && mista(tracoDoArquivo(y)));
|
||||
if(!x) return;
|
||||
x.mistaVista=true;
|
||||
$('mistaTit').textContent=x.f.name;
|
||||
$('mistaTxt').textContent=ehFolha()?TEXTO_MISTA.folha:TEXTO_MISTA.arte;
|
||||
$('mistaSep').onclick=()=>{ dlg.close(); const i=lista.indexOf(x);
|
||||
if(i>=0){ lista.splice(i,1); ehFolha()?pintaFolha():pintaArtes(); } $('inp').click(); };
|
||||
$('mistaSegue').onclick=()=>{ dlg.close(); agendaAvaliacao(); };
|
||||
$('mistaSegue').onclick=()=>{ x.mistaVista=true; dlg.close(); agendaAvaliacao(); };
|
||||
dlg.showModal();
|
||||
}
|
||||
// O traço mais fino do item (item 9, Dropstar 30/10/2026): o menor entre as
|
||||
@@ -50,12 +48,13 @@ function perguntaMista(){
|
||||
// que confere a classe de contração ao aprovar o arquivo final.
|
||||
function tracoDoItem(lista){
|
||||
const arquivos=lista||(ehFolha()?folhas:artes);
|
||||
const medidas=arquivos.map(x=>lista?tracoDaArte(x):tracoDoArquivo(x)).filter(Boolean);
|
||||
const medidas=arquivos.map((x,index)=>({index,traco:lista?tracoDaArte(x):tracoDoArquivo(x)})).filter(x=>x.traco);
|
||||
if(!medidas.length) return {strokePx:null, strokeClass:null, strokeChoice:null};
|
||||
const fino=medidas.reduce((a,b)=>b.px<a.px?b:a);
|
||||
const fino=medidas.reduce((a,b)=>b.traco.px<a.traco.px?b:a);
|
||||
// Avisado do item 16, o cliente quis imprimir assim: fica a medida, C1.
|
||||
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
|
||||
return {strokePx:fino.px, strokeClass:fino.classe, strokeChoice:avisado?'measured':null};
|
||||
return {strokePx:fino.traco.px, strokeClass:fino.traco.classe, strokeChoice:avisado?'measured':null,
|
||||
proofSourceIndex:fino.index, proofYFraction:fino.traco.proofYFraction||0};
|
||||
}
|
||||
// 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.
|
||||
@@ -78,7 +77,7 @@ function avaliar(){
|
||||
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.'};
|
||||
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};
|
||||
metros=folhaTotalM();
|
||||
setTimeout(perguntaMista);
|
||||
reencaixado=false;
|
||||
@@ -145,7 +144,7 @@ function avaliar(){
|
||||
// metragem = altura da folha depois de montada, com os 5 mm entre peças
|
||||
metros=+(montagemCm/100).toFixed(4);
|
||||
if(!(metros>0)) return {pronto:false, falta:'Montando a folha…'};
|
||||
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
|
||||
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/DPI_AVISA*100))));
|
||||
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
||||
mostraNota([
|
||||
['ok','Montagem por nossa conta','5 mm garantidos'],
|
||||
@@ -211,7 +210,7 @@ function ressalvaResolucao(){
|
||||
quantas:r.quantasBaixas, parte:Math.round(r.fracBaixa*100),
|
||||
quantasAviso:r.quantasAviso, parteAviso:Math.round(r.fracAviso*100)} : {};
|
||||
if(x.an.dpi<DPI_RECUSA) recusadas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
|
||||
else if(x.an.dpi<DPI_AVISA || (r&&r.quantasAviso))
|
||||
else if(x.an.dpi<DPI_AVISA)
|
||||
baixas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
|
||||
});
|
||||
geral = folhas.some(x=>x.an) ? Math.max(...folhas.filter(x=>x.an).map(x=>x.an.dpi)) : 300;
|
||||
|
||||
@@ -61,7 +61,7 @@ function novoMapa(wPx,hPx,larguraCm){
|
||||
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,
|
||||
traco:novoTraco(wPx,wPx/(larguraCm/2.54))};
|
||||
traco:novoTraco(wPx,wPx/(larguraCm/2.54),hPx)};
|
||||
}
|
||||
// ── Traço mais fino (Dropstar, 30/10/2026): a contração do Flexi vem dele.
|
||||
// Tinta é alfa acima de 40; a distância de cada pixel de tinta ao fundo sai de
|
||||
@@ -89,13 +89,14 @@ function tintaPerto(t,lim,r,de,ate){
|
||||
// O contexto de cada faixa: as linhas acima e abaixo que ela lê sem medir. Um
|
||||
// cisco (menos de 30 px de tinta a 300 DPI) tem menos linhas que isso, então
|
||||
// a faixa sempre o vê inteiro; o que encosta na borda cortada é traço.
|
||||
function novoTraco(wPx,dpi){
|
||||
function novoTraco(wPx,dpi,hPx){
|
||||
const cisco=Math.ceil(TRACO_CISCO*(dpi/300)**2), ctx=Math.min(120,Math.max(TRACO_D,cisco));
|
||||
const linhas=TRACO_FAIXA+2*ctx;
|
||||
return {w:wPx,dpi,linhas,ctx,cisco,tinta:new Uint8Array(wPx*linhas),dist:new Uint16Array(wPx*linhas),
|
||||
rot:new Int32Array(wPx*linhas),pai:new Int32Array((wPx*linhas>>1)+2),area:new Int32Array((wPx*linhas>>1)+2),
|
||||
prox:new Int32Array(TRACO_FAIXA+2*ctx),
|
||||
n:0,inicio:0,hist:new Float64Array(2*TRACO_D+2),total:0,tintaPx:0,largosPx:0,finosPx:0};
|
||||
n:0,inicio:0,hist:new Float64Array(2*TRACO_D+2),total:0,tintaPx:0,largosPx:0,finosPx:0,
|
||||
hPx,windowRows:Math.max(1,Math.round(dpi/2.54*15)),windows:[]};
|
||||
}
|
||||
// Como a sala mede (Dropstar, 30/10/2026): componentes de tinta com menos de
|
||||
// 30 px não são traço e saem antes da distância. Vizinhos nas oito direções.
|
||||
@@ -183,7 +184,9 @@ function tracoFaixa(t,fim){
|
||||
// conta, na última faixa, ou dois pixels soltos de borda viram o menor
|
||||
// traço de uma arte toda chapada. O comprimento do eixo é cerca de metade
|
||||
// do contorno da região além do limite.
|
||||
if(d>=CAP){ if(at(x-1,y)<CAP||at(x+1,y)<CAP||at(x,y-1)<CAP||at(x,y+1)<CAP){hist[max]+=0.5;t.total+=0.5;} continue; }
|
||||
if(d>=CAP){ if(at(x-1,y)<CAP||at(x+1,y)<CAP||at(x,y-1)<CAP||at(x,y+1)<CAP){
|
||||
const wi=Math.floor((t.inicio+y)/t.windowRows), wh=t.windows[wi]||(t.windows[wi]=new Float64Array(hist.length));
|
||||
hist[max]+=0.5;wh[max]+=0.5;t.total+=0.5;} continue; }
|
||||
// No eixo do traço a distância não é menor que a de nenhum vizinho; perto
|
||||
// de um canto sempre há um vizinho mais fundo, e o canto não conta.
|
||||
let iguais=0, eixo=true;
|
||||
@@ -197,7 +200,8 @@ function tracoFaixa(t,fim){
|
||||
// Largura par: o eixo tem dois pixels, e os iguais passam de dois.
|
||||
const larg=iguais>=4?2*d/10:2*d/10-1;
|
||||
const i=Math.max(1,Math.min(max,Math.round(larg*escala)));
|
||||
hist[i]++;t.total++;
|
||||
const wi=Math.floor((t.inicio+y)/t.windowRows), wh=t.windows[wi]||(t.windows[wi]=new Float64Array(hist.length));
|
||||
hist[i]++;wh[i]++;t.total++;
|
||||
}
|
||||
// As últimas linhas ficam como contexto da próxima faixa.
|
||||
if(!fim){
|
||||
@@ -216,8 +220,18 @@ function tracoFim(t){
|
||||
if(!t.total) return t.lido=null;
|
||||
let soma=0, px=1;
|
||||
for(let i=1;i<t.hist.length;i++){ soma+=t.hist[i]; if(soma>=t.total*0.01){ px=i; break; } }
|
||||
// largos: a parte da tinta em áreas chapadas, de 20 px ou mais (item 16)
|
||||
return t.lido={px, classe:px<=4?'C1':px<=19?'C2':'C3', largos:t.tintaPx?t.largosPx/t.tintaPx:0, finos:t.tintaPx?t.finosPx/t.tintaPx:0};
|
||||
// Choose the 15 cm stretch with the finest 1st-percentile stroke.
|
||||
let best=0, bestPx=Infinity;
|
||||
t.windows.forEach((histogram,index)=>{
|
||||
if(!histogram)return;
|
||||
const count=histogram.reduce((a,b)=>a+b,0);
|
||||
if(count<20)return;
|
||||
let seen=0, width=histogram.length-1;
|
||||
for(let i=1;i<histogram.length;i++){seen+=histogram[i];if(seen>=count*0.01){width=i;break;}}
|
||||
if(width<bestPx){bestPx=width;best=index;}
|
||||
});
|
||||
return t.lido={px, classe:px<=4?'C1':px<=19?'C2':'C3', largos:t.tintaPx?t.largosPx/t.tintaPx:0, finos:t.tintaPx?t.finosPx/t.tintaPx:0,
|
||||
proofYFraction:Math.min(1,best*t.windowRows/t.hPx)};
|
||||
}
|
||||
// A linha y da folha: o alfa de cada pixel em alfa[inicio + x*de].
|
||||
function mapaLinha(m,y,alfa,inicio,de){
|
||||
@@ -306,4 +320,3 @@ function analisarMapa(m){
|
||||
traco: m.traco ? tracoFim(m.traco) : null
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -147,15 +147,27 @@ async function sel(fs){
|
||||
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};
|
||||
}catch(e){}
|
||||
}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(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); });
|
||||
}).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){
|
||||
@@ -267,7 +279,8 @@ function analiseDaArte(a){
|
||||
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};
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user