feat: a PNG that records 200 DPI or more offers its own size, Manter, and the Prumo says if it was kept (Rodada 5, A1)

The Site reads the pHYs chunk of a loose art; at 200 DPI or more the
size in the file is the default width and a Manter button sits before
the table sizes (also when the art is turned 90 degrees). The source
carries saved_width_cm and saved_dpi, used only by the Prumo report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 11:11:21 -03:00
parent 7e33e6fb1d
commit 7fc091a1bd
8 changed files with 121 additions and 4 deletions

View File

@@ -101,7 +101,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health tests.test_saved_size -v
- name: Runtime and retention regressions - name: Runtime and retention regressions
run: | run: |

View File

@@ -132,6 +132,10 @@ class ProductionSource(StrictModel):
# and printed; the file itself is length_cm plus both trims long. # and printed; the file itself is length_cm plus both trims long.
trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000) trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000) trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
# The size the PNG itself recorded (item A1, round 5), only for the Prumo
# report; nothing on the server prices or packs by it.
saved_width_cm: Decimal | None = Field(default=None, gt=0, le=10000)
saved_dpi: int | None = Field(default=None, ge=1, le=10000, strict=True)
class ProductionPlacement(StrictModel): class ProductionPlacement(StrictModel):
source_index: int = Field(ge=0, le=199, strict=True) source_index: int = Field(ge=0, le=199, strict=True)

View File

@@ -103,6 +103,27 @@ def report(order, uploads):
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, ' lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), ' f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
f'altura {_cm(production.get("height_cm"))} cm') f'altura {_cm(production.get("height_cm"))} cm')
# The size the PNG said it had (item A1, round 5): whether the
# customer kept it or changed it.
for k, source in enumerate(production.get('sources') or []):
saved = source.get('saved_width_cm')
if not saved:
continue
width = Decimal(str(source.get('width_cm')))
length = Decimal(str(source.get('length_cm')))
# Turned 90°, the art's own width runs along the film.
if source.get('rotation_degrees') == 90:
width, length = length, width
saved_w = Decimal(str(saved))
altura = saved_w * length / width if width else Decimal(0)
dpi = source.get('saved_dpi')
if abs(width - saved_w) < Decimal('0.05'):
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), mantido')
else:
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), '
f'alterado pelo cliente para {_cm(width)} cm')
# The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18). # The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18).
trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0)) trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0))
for s in production.get('sources') or []) for s in production.get('sources') or [])

View File

@@ -37,6 +37,30 @@ class PrumoReportTests(unittest.TestCase):
self.assertIn('Prumo levou 41 s', text) self.assertIn('Prumo levou 41 s', text)
self.assertNotIn('Prumo levou 341 s', text) self.assertNotIn('Prumo levou 341 s', text)
def test_saved_png_size_says_whether_the_customer_kept_it(self):
order = self.order()
item = order['snapshot']['items'][0]
item['production']['sources'] = [
{'width_cm': '28.0', 'length_cm': '35.2',
'saved_width_cm': '28.0', 'saved_dpi': 300},
{'width_cm': '20', 'length_cm': '25',
'saved_width_cm': '15', 'saved_dpi': 240},
]
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
self.assertIn('Arte 2: tamanho lido do arquivo 15,0 × 18,8 cm (240 DPI), '
'alterado pelo cliente para 20,0 cm', text)
# Turned 90°: the art's own width is the length along the film.
item['production']['sources'] = [
{'width_cm': '35.2', 'length_cm': '28.0', 'rotation_degrees': 90,
'saved_width_cm': '28.0', 'saved_dpi': 300}]
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
def test_without_a_saved_png_size_no_line_is_added(self):
text = '\n'.join(report(self.order(), {'u1': {'name': 'arte.pdf'}}))
self.assertNotIn('tamanho lido do arquivo', text)
def test_without_a_claim_time_the_generation_line_is_hidden(self): def test_without_a_claim_time_the_generation_line_is_hidden(self):
order = self.order() order = self.order()
del order['print_files'][0]['claimed_at'] del order['print_files'][0]['claimed_at']

26
tests/test_saved_size.py Normal file
View File

@@ -0,0 +1,26 @@
"""The PNG's own size on an artwork source (item A1, round 5)."""
import unittest
from uuid import uuid4
try:
from pydantic import ValidationError
from app.core.models import ProductionSource
except ImportError:
# The validate job runs this file on the host, without the runtime image's
# dependencies; the runtime suites exercise the model there.
ProductionSource = ValidationError = None
class ProductionSourceSavedSizeTests(unittest.TestCase):
@unittest.skipUnless(ProductionSource, 'pydantic is only in the runtime image')
def test_saved_size_is_optional_and_saved_dpi_must_be_positive(self):
base = {'upload_id': str(uuid4()), 'kind': 'artwork', 'width_cm': '28.0',
'length_cm': '35.2', 'copies': 1, 'measurement': 'file'}
ProductionSource.model_validate(base)
ProductionSource.model_validate({**base, 'saved_width_cm': '28.0', 'saved_dpi': 300})
with self.assertRaises(ValidationError):
ProductionSource.model_validate({**base, 'saved_width_cm': '28.0', 'saved_dpi': 0})
if __name__ == '__main__':
unittest.main()

View File

@@ -282,7 +282,8 @@ function pintaPedido(){
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro. // A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4), const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp, copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'}); measurement:(x.src||x.semPrevia)?'file':'customer',
...(x.cmSalvo?{saved_width_cm:x.cmSalvo,saved_dpi:x.dpiSalvo}:{})});
function carrinho(){ function carrinho(){
const cob=cobrarMontagem(); const cob=cobrarMontagem();
const extra=folhaManual()? TAXA_MANUAL : 0; const extra=folhaManual()? TAXA_MANUAL : 0;

View File

@@ -192,6 +192,30 @@ async function dimensoesImagem(file){
} }
return null; return null;
} }
// The PNG may record its own resolution in the pHYs chunk. A loose art that
// says 200 DPI or more has a real size in pixels ÷ DPI, offered as "Manter";
// below 200 DPI, or without the chunk, it says nothing. Never throws.
async function dpiSalvoPng(file){
try{
if(!file || !(file.size>0)) return null;
const b=new Uint8Array(await file.slice(0,Math.min(file.size,4*1048576)).arrayBuffer());
if(!(b.length>=8 && b[0]===0x89 && b[1]===0x50 && b[2]===0x4E && b[3]===0x47)) return null;
const u32=i=>((b[i]<<24)>>>0)+(b[i+1]<<16)+(b[i+2]<<8)+b[i+3];
let i=8;
while(i+12<=b.length){
const len=u32(i), tipo=String.fromCharCode(...b.slice(i+4,i+8));
if(tipo==='pHYs'){
if(len<9 || i+8+len>b.length) return null;
const ppmX=u32(i+8), ppmY=u32(i+12), unidade=b[i+16];
if(unidade===1 && ppmX>0 && ppmX===ppmY) return Math.round(ppmX*0.0254);
return null;
}
if(tipo==='IDAT' || tipo==='IEND') return null;
i+=12+len;
}
return null;
}catch(e){ return null; }
}
// A small copy of a large PNG, read as a stream: the file is inflated in // 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 // 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. Given the sheet's // at a few MB whatever the file's size. It is the preview. Given the sheet's
@@ -748,6 +772,12 @@ function pintaArtes(){
'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>'; 'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>';
const mini = a.miniSrc ? '<img src="'+escapeHTML(a.miniSrc)+'" alt="">' : '<span>'+escapeHTML(extDe(a.f.name))+'</span>'; const mini = a.miniSrc ? '<img src="'+escapeHTML(a.miniSrc)+'" alt="">' : '<span>'+escapeHTML(extDe(a.f.name))+'</span>';
const sub = a.cm>0 && (a.src||a.semPrevia) ? (a.q>1? a.q+' × ' : '')+'<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>' : ''; const sub = a.cm>0 && (a.src||a.semPrevia) ? (a.q>1? a.q+' × ' : '')+'<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>' : '';
// Girada, a largura na folha é a altura salva no arquivo.
const salvo = a.cmSalvo ? Math.round((a.giro? a.cmSalvo*(a.prop||1) : a.cmSalvo)*10)/10 : 0;
const manter = salvo && salvo<=larguraFilme()
? '<button class="tm'+(Math.abs(a.cm-salvo)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+salvo+'">'+
'Manter '+n1(salvo)+' × '+n1(salvo*propDe(a))+' cm</button>'
: '';
return '<div class="rep art2'+(a===recemChegada?' nova':'')+'" data-arte="'+i+'">'+ return '<div class="rep art2'+(a===recemChegada?' nova':'')+'" data-arte="'+i+'">'+
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+ '<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
'<div class="l1"><b>'+escapeHTML(a.f.name)+'</b>'+(a===recemChegada?'<em class="novaT">nova</em>':'')+ '<div class="l1"><b>'+escapeHTML(a.f.name)+'</b>'+(a===recemChegada?'<em class="novaT">nova</em>':'')+
@@ -769,7 +799,7 @@ function pintaArtes(){
'<button class="gr'+(a.giro?' on':'')+'" data-giro="'+i+'" title="Girar 90°" aria-label="Girar 90°">'+icone('girar')+'</button>'+ '<button class="gr'+(a.giro?' on':'')+'" data-giro="'+i+'" title="Girar 90°" aria-label="Girar 90°">'+icone('girar')+'</button>'+
(espelhavel() ? '<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button>' : '')+'</span>'+ (espelhavel() ? '<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button>' : '')+'</span>'+
(sub? '<div class="conta">'+sub+'</div>' : '')+ (sub? '<div class="conta">'+sub+'</div>' : '')+
'<div class="atalhos">'+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+ '<div class="atalhos">'+manter+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+
(Math.abs(a.cm-t)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+t+'">'+n1(t)+' cm</button>').join('')+'</div>'+ (Math.abs(a.cm-t)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+t+'">'+n1(t)+' cm</button>').join('')+'</div>'+
'</div>'+ '</div>'+
'</div>'; '</div>';

View File

@@ -296,6 +296,11 @@ function medir(a){
return dimensoesImagem(a.f).then(async d=>{ return dimensoesImagem(a.f).then(async d=>{
if(!d || !(d.w>0) || !(d.h>0)){ a.decodeError=true; return a; } 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; a.px=d.w; a.py=d.h; a.prop=d.h/d.w; a.grande=true;
a.dpiSalvo=await dpiSalvoPng(a.f);
if(a.dpiSalvo>=200){
a.cmSalvo=Math.round(a.px/a.dpiSalvo*2.54*10)/10;
if(a.cmSalvo>=1 && a.cmSalvo<=larguraFilme() && !a.cm) a.cm=a.cmSalvo;
}
// WebP cannot be read in parts (JPG is refused): the art is placed by its // 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. // measurements, as a full box, and the team checks it before printing.
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; } if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
@@ -315,7 +320,13 @@ function medir(a){
}).catch(()=>{ a.decodeError=true; return a; }); }).catch(()=>{ a.decodeError=true; return a; });
} }
return carregarImagem(a.f).then(async img=>{ 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); if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height;
a.dpiSalvo=await dpiSalvoPng(a.f);
if(a.dpiSalvo>=200){
a.cmSalvo=Math.round(a.px/a.dpiSalvo*2.54*10)/10;
if(a.cmSalvo>=1 && a.cmSalvo<=larguraFilme() && !a.cm) a.cm=a.cmSalvo;
}
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. // Read at its own pixels while the customer sets the width.
a.lendoArte=true; a.lendoArte=true;
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{}) mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})