From 7fc091a1bd36bc4573098597a03ea1e6e49a3f83 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Cau=C3=AA=20Faleiros?=
Date: Mon, 30 Nov 2026 11:11:21 -0300
Subject: [PATCH] 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
---
.gitea/workflows/deploy.yml | 2 +-
app/core/models.py | 4 ++++
app/prumo.py | 21 +++++++++++++++++++++
tests/test_prumo.py | 24 ++++++++++++++++++++++++
tests/test_saved_size.py | 26 ++++++++++++++++++++++++++
web/site-cart.js | 3 ++-
web/site-pdf.js | 32 +++++++++++++++++++++++++++++++-
web/site-upload.js | 13 ++++++++++++-
8 files changed, 121 insertions(+), 4 deletions(-)
create mode 100644 tests/test_saved_size.py
diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml
index cb91db2..ed4f7d3 100644
--- a/.gitea/workflows/deploy.yml
+++ b/.gitea/workflows/deploy.yml
@@ -101,7 +101,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- 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
run: |
diff --git a/app/core/models.py b/app/core/models.py
index 4609cb6..9c159f6 100644
--- a/app/core/models.py
+++ b/app/core/models.py
@@ -132,6 +132,10 @@ class ProductionSource(StrictModel):
# 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_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):
source_index: int = Field(ge=0, le=199, strict=True)
diff --git a/app/prumo.py b/app/prumo.py
index 5da2c3c..658abe7 100644
--- a/app/prumo.py
+++ b/app/prumo.py
@@ -103,6 +103,27 @@ def report(order, uploads):
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
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).
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 [])
diff --git a/tests/test_prumo.py b/tests/test_prumo.py
index 8f538d3..a45f4fc 100644
--- a/tests/test_prumo.py
+++ b/tests/test_prumo.py
@@ -37,6 +37,30 @@ class PrumoReportTests(unittest.TestCase):
self.assertIn('Prumo levou 41 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):
order = self.order()
del order['print_files'][0]['claimed_at']
diff --git a/tests/test_saved_size.py b/tests/test_saved_size.py
new file mode 100644
index 0000000..8dbbcb5
--- /dev/null
+++ b/tests/test_saved_size.py
@@ -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()
diff --git a/web/site-cart.js b/web/site-cart.js
index 3fc6204..cc519f3 100644
--- a/web/site-cart.js
+++ b/web/site-cart.js
@@ -282,7 +282,8 @@ function pintaPedido(){
// 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),
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(){
const cob=cobrarMontagem();
const extra=folhaManual()? TAXA_MANUAL : 0;
diff --git a/web/site-pdf.js b/web/site-pdf.js
index 9d03a65..b4a638d 100644
--- a/web/site-pdf.js
+++ b/web/site-pdf.js
@@ -192,6 +192,30 @@ async function dimensoesImagem(file){
}
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
// 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
@@ -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.
';
const mini = a.miniSrc ? '
' : ''+escapeHTML(extDe(a.f.name))+'';
const sub = a.cm>0 && (a.src||a.semPrevia) ? (a.q>1? a.q+' × ' : '')+''+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm' : '';
+ // 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()
+ ? ''
+ : '';
return ''+
'
'+mini+'
'+
'
'+escapeHTML(a.f.name)+''+(a===recemChegada?'
nova':'')+
@@ -769,7 +799,7 @@ function pintaArtes(){
'
'+
(espelhavel() ? '
' : '')+''+
(sub? '
'+sub+'
' : '')+
- '
'+(TAMANHOS[larguraFilme()]||[]).map(t=>'
'+
'
'+
'
';
diff --git a/web/site-upload.js b/web/site-upload.js
index a1080a9..e2b6b18 100644
--- a/web/site-upload.js
+++ b/web/site-upload.js
@@ -296,6 +296,11 @@ function medir(a){
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;
+ 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
// measurements, as a full box, and the team checks it before printing.
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; });
}
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.
a.lendoArte=true;
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})