feat: a ready sheet prints at its real size, centred on the film, with the customer's confirmation (Marcus, 2026-12-02)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m43s

Replaces 7111995 (only 57,0 cm entered; a whole order of 56,5-56,9 cm
sheets was refused, DTF-WEB-2C). Marcus's rules, for Arquivo por metro,
Premium (57 cm) and UV (27 cm):
1. A known width up to the film (PNG recording 200 DPI or more, or a PDF
   page) enters at its real size, centred, billed by its real height.
2. Narrower: his warning before the cart, confirmation required
   (Imprimir no tamanho real / Enviar outro arquivo); recorded in the
   Prumo report ("cliente confirmou folha de 35,8 cm no tamanho real") and
   shown in the cart and payment summaries.
3. Wider than the film: refused with his message.
4. Unknown width: taken as the film's, DPI from the pixels; 200 or more
   with a confirmation, under 200 refused with the artes avulsas hint.
Within 0,1 cm of the film counts as the film. The server checks it all
again at checkout (sheet_width_issue, centred placement, size_confirmed).

Also ops.stretched_sheets: the ready-sheet orders since 16/10 laid out
wider than their real width (number, real width, factor), for Marcus.
Contract: output/revisao/contrato-folha-real.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-12-02 09:51:38 -03:00
parent 7af6c9797d
commit 41126a42fd
22 changed files with 634 additions and 153 deletions

View File

@@ -102,7 +102,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_storage_steady 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
run: $COMPOSE exec -T api python -m unittest tests.test_storage_steady tests.test_stretched_sheets 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: |

View File

@@ -37,6 +37,8 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
item['residue_accepted_at'] = accepted_at
if item.get('stroke_choice'):
item['stroke_choice_at'] = accepted_at
if any(s.get('size_confirmed') for s in (item.get('production') or {}).get('sources') or []):
item['size_confirmed_at'] = accepted_at
reason = quote_review.review_reason(draft)
with db.connect() as c:
rows = {}

View File

@@ -136,6 +136,11 @@ class ProductionSource(StrictModel):
# 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)
# The customer confirmed this ready sheet's size in the Site's dialog: a
# known width narrower than the film printed at its real size, or an
# unknown width taken as the film's (Marcus, 2026-12-02,
# output/revisao/contrato-folha-real.md). The checkout requires it.
size_confirmed: bool = False
class ProductionPlacement(StrictModel):
source_index: int = Field(ge=0, le=199, strict=True)
@@ -291,7 +296,9 @@ class Item(StrictModel):
raise ValueError('Production placement changes the source size')
if placement.x_cm+placement.width_cm>film_width+tolerance or placement.y_cm+placement.length_cm>self.production.height_cm+tolerance:
raise ValueError('Production placement is outside the film')
if is_sheet and (placement.x_cm or auto_rotation):
# A ready sheet prints at its real size, centred on the film
# (Marcus, 2026-12-02; output/revisao/contrato-folha-real.md).
if is_sheet and (auto_rotation or abs(placement.x_cm - (film_width - placement.width_cm) / 2) > tolerance):
raise ValueError('Finished sheets must retain their original orientation')
if placed != expected:
raise ValueError('Production layout does not cover every source copy')

View File

@@ -324,15 +324,15 @@ def proportion_issue(files, items, rows):
return None
# A ready sheet in the 57 cm textile products must be 57 cm wide where its real
# width is known (Marcus, 2026-12-01: a pop-up on upload and refused, narrower
# or wider). Known means a PNG whose pHYs records TRUSTED_DPI or more (the A1
# threshold, rodada 5) or a PDF page; anything else keeps the v0 rule (the
# image stretched to the film). output/revisao/contrato-largura-folha.md;
# the Site has the same numbers (web/site-config.js LARGURA_EXATA).
EXACT_SHEET_WIDTH_CM = {'file': 57.0, 'premium': 57.0}
# A ready sheet prints at its real size, centred on the film (Marcus,
# 2026-12-02, output/revisao/contrato-folha-real.md). Its width is known for a
# PNG whose pHYs records TRUSTED_DPI or more (the A1 threshold, rodada 5) and
# for a PDF page; otherwise it is taken as the film's, and its DPI is the
# pixels over that width. The Site has the same numbers (web/site-config.js).
SHEET_FILM_CM = {'file': 57.0, 'premium': 57.0, 'uvfile': 27.0}
SHEET_WIDTH_TOLERANCE_CM = 0.1
TRUSTED_DPI = 200
SHEET_MIN_DPI = 200
def png_saved_dpi(head):
@@ -363,45 +363,72 @@ def png_saved_dpi(head):
def sheet_width_issue(files, items, rows):
"""Why a cart cannot be approved: a ready sheet of a 57 cm textile item
(EXACT_SHEET_WIDTH_CM) whose real width is off by more than
SHEET_WIDTH_TOLERANCE_CM, or None. A PNG's real width is its pixels ÷ its
pHYs DPI × 2.54 when that DPI is TRUSTED_DPI or more; a PDF's is the
source's width_cm (the page the Site measured). Anything else passes."""
"""Why a cart cannot be approved, or None, for each ready sheet of an item
in SHEET_FILM_CM (contrato-folha-real.md, Server V1–V5): a known width
wider than the film, a source width_cm other than the known width (a
stretched sheet), a narrower known width or an unknown one without
size_confirmed, or an unknown width whose effective DPI is under
SHEET_MIN_DPI. measurement 'customer' sources pass."""
def cm(value):
return f'{value:.1f}'.replace('.', ',')
def film_text(value):
return f'{value:.0f}' if value == int(value) else cm(value)
for index, item in enumerate(items, 1):
mode = item.get('mode')
if mode not in EXACT_SHEET_WIDTH_CM:
if mode not in SHEET_FILM_CM:
continue
expected = EXACT_SHEET_WIDTH_CM[mode]
expected_text = f'{expected:g}'
film = SHEET_FILM_CM[mode]
for number, source in enumerate(item['production']['sources'], 1):
if source.get('kind') != 'sheet':
if source.get('kind') != 'sheet' or source.get('measurement') != 'file':
continue
row = rows.get(str(source['upload_id']))
if not row:
continue
name = row['name'].lower()
width = float(source['width_cm'])
confirmed = bool(source.get('size_confirmed'))
if name.endswith('.pdf'):
cm = float(source['width_cm'])
dpi = None
real = width
elif name.endswith('.png'):
dpi = png_saved_dpi(files.head(row))
if dpi is None or dpi < TRUSTED_DPI:
continue
size = image_size(files.head(row))
if not size or not all(size):
continue
cm = size[0] / dpi * 2.54
if dpi is not None and dpi >= TRUSTED_DPI:
size = image_size(files.head(row))
if not size or not all(size):
continue
real = size[0] / dpi * 2.54
else:
real = None
elif name.endswith('.webp'):
real = None
else:
continue
if abs(cm - expected) <= SHEET_WIDTH_TOLERANCE_CM:
if real is not None:
if real > film + SHEET_WIDTH_TOLERANCE_CM:
return (f'Item {index}: a folha {number} tem {cm(real)} cm e não cabe em '
f'{film_text(film)} cm. Reduza no seu programa ou envie as artes separadas.')
if abs(width - real) > SHEET_WIDTH_TOLERANCE_CM:
return (f'Item {index}: a folha {number} foi montada com {cm(width)} cm, mas tem '
f'{cm(real)} cm. Monte o pedido de novo.')
if real < film - SHEET_WIDTH_TOLERANCE_CM and not confirmed:
return (f'Item {index}: confirme a folha {number} de {cm(real)} cm no tamanho real '
'antes de pagar.')
continue
cm_text = f'{cm:.1f}'.replace('.', ',')
if dpi is None:
return (f'Item {index}: a folha {number} tem {cm_text} cm de largura. '
f'A folha montada precisa ter {expected_text} cm.')
return (f'Item {index}: a folha {number} tem {cm_text} cm de largura ({dpi} DPI). '
f'A folha montada precisa ter {expected_text} cm.')
size = image_size(files.head(row))
if not size or not all(size):
continue
# Unknown width: the sheet is taken as the film's (rule 4).
if abs(width - film) > SHEET_WIDTH_TOLERANCE_CM:
return (f'Item {index}: a folha {number} foi montada com {cm(width)} cm, mas tem '
f'{film_text(film)} cm. Monte o pedido de novo.')
effective = js_round(size[0] / (film / 2.54))
if effective < SHEET_MIN_DPI:
return (f'Item {index}: a folha {number} tem {effective} DPI em {film_text(film)} cm, '
f'abaixo do mínimo de {SHEET_MIN_DPI}. Se a sua folha não tem '
f'{film_text(film)} cm, suba as artes como artes avulsas.')
if not confirmed:
return (f'Item {index}: confirme a folha {number} de {film_text(film)} cm antes de pagar.')
return None

View File

@@ -106,6 +106,14 @@ def report(order, uploads):
lines.append(f'{lead}{dots} ponto{"s" if dots > 1 else ""} < 2 mm — cliente aceitou' +
_hora(item.get('residue_accepted_at')))
production = item.get('production') or {}
film = production.get('film_width_cm')
if item.get('mode') in ('file', 'premium', 'uvfile') and film is not None:
film = Decimal(str(film))
for k, source in enumerate(production.get('sources') or [], 1):
width = Decimal(str(source.get('width_cm')))
if source.get('size_confirmed') and width < film - Decimal('0.1'):
lines.append(f'{lead}Folha {k}: cliente confirmou folha de {_cm(width)} cm no tamanho real' +
_hora(item.get('size_confirmed_at')))
placements = production.get('placements') or []
if item.get('mode') in ('avulsa', 'uv'):
rotated = sum(1 for p in placements if p.get('rotation_degrees') in (90, 270))

88
ops/stretched_sheets.py Normal file
View File

@@ -0,0 +1,88 @@
"""The ready-sheet orders whose sheet was stretched to the film (Marcus, 2026-12-02).
Until the real-size rule (output/revisao/contrato-folha-real.md) the Site
stretched every ready-sheet image to the film's width. A PNG that records its
own DPI (200 or more, the A1 threshold) tells its real width, so an order
whose sheet was laid out wider than that was printed bigger. Run once from
the API's console:
python -m ops.stretched_sheets since 2026-10-16
python -m ops.stretched_sheets --desde 2026-11-01
Read only. For each paid order (tests and cancelled ones left out) it prints
the order number, the sheet's real width, the width it was laid out at and
the factor. A sheet whose file is already gone (30 days after upload) or that
records no DPI cannot be measured, and is listed apart.
"""
import argparse
from datetime import date
from app import payments
from app.core import db
from app.grade_check import Files, TRUSTED_DPI, image_size, png_saved_dpi
SHEET_MODES = ('file', 'premium', 'uvfile')
TOLERANCE_CM = 0.1
def sheets(order):
"""(item number, source number, source) for each measured ready sheet."""
for i, item in enumerate((order['snapshot'] or {}).get('items') or [], 1):
if item.get('mode') not in SHEET_MODES:
continue
for n, source in enumerate((item.get('production') or {}).get('sources') or [], 1):
if source.get('kind') == 'sheet' and source.get('measurement') == 'file':
yield i, n, source
def main(argv=None, out=print, storage=None, connect=db.connect):
parser = argparse.ArgumentParser(prog='python -m ops.stretched_sheets')
parser.add_argument('--desde', type=date.fromisoformat, default=date(2026, 10, 16))
args = parser.parse_args(argv)
if storage is None:
from app.runtime import storage
files = Files(storage)
stretched, unknown = [], []
with connect() as c:
orders = c.execute('''SELECT id, number, snapshot, payment, created_at FROM dtf_local.orders
WHERE created_at >= %s AND cancelled_at IS NULL AND parent_id IS NULL ORDER BY number''',
(args.desde,)).fetchall()
for order in orders:
if payments.is_test(order):
continue
for i, n, source in sheets(order):
row = c.execute('SELECT name, object_key, purged_at FROM dtf_local.uploads WHERE id=%s',
(source['upload_id'],)).fetchone()
label = f"#{order['number']} item {i} folha {n}"
if not row or not row['name'].lower().endswith('.png'):
continue # a PDF was always laid out at its page's width
if row['purged_at']:
unknown.append(f"{label} ({row['name']}): arquivo já apagado")
continue
try:
head = files.head(row)
except Exception as exc: # noqa: BLE001 - one unreadable file must not stop the list
unknown.append(f"{label} ({row['name']}): não foi possível ler ({type(exc).__name__})")
continue
dpi, size = png_saved_dpi(head), image_size(head)
if not size or dpi is None or dpi < TRUSTED_DPI:
unknown.append(f"{label} ({row['name']}): o arquivo não grava o DPI")
continue
real = size[0] / dpi * 2.54
placed = float(source['width_cm'])
if abs(placed - real) > TOLERANCE_CM:
stretched.append((order['number'], label, row['name'], real, placed, placed / real))
comma = lambda v, places: f'{v:.{places}f}'.replace('.', ',')
out(f'Pedidos de folha pronta desde {args.desde:%d/%m/%Y} montados com outra largura: {len(stretched)}')
for _, label, name, real, placed, factor in stretched:
out(f'{label}: {name} · largura real {comma(real, 1)} cm · montada com {comma(placed, 1)} cm · '
f'fator {comma(factor, 2)}')
if unknown:
out(f'Sem como medir: {len(unknown)}')
for line in unknown:
out(line)
return stretched, unknown
if __name__ == '__main__':
main()

View File

@@ -162,15 +162,36 @@ try{
else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));}
};
// A genuine mounted sheet spans the film width with printable resolution,
// on a transparent background; or with a solid one, or a residue dot.
// on a transparent background; or with a solid one, or a residue dot. The
// pHYs chunk makes its real width known, as a sheet exported at 300 DPI.
window.comDpi=async(blob,ppm=11811)=>{
const b=new Uint8Array(await blob.arrayBuffer());
const crc=c=>{let x=0xffffffff;for(const v of c){x^=v;for(let k=0;k<8;k++)x=x&1?0xedb88320^(x>>>1):x>>>1;}return (x^0xffffffff)>>>0;};
let i=8;
while(i+8<=b.length){
const len=((b[i]<<24)>>>0)+(b[i+1]<<16)+(b[i+2]<<8)+b[i+3];
const tipo=String.fromCharCode(...b.slice(i+4,i+8));
if(tipo==='IDAT'){
const ch=new Uint8Array(21), dv=new DataView(ch.buffer);
dv.setUint32(0,9);ch.set([0x70,0x48,0x59,0x73],4);
dv.setUint32(8,ppm);dv.setUint32(12,ppm);ch[16]=1;
dv.setUint32(17,crc(ch.subarray(4,17)));
const out=new Uint8Array(b.length+21);
out.set(b.subarray(0,i),0);out.set(ch,i);out.set(b.subarray(i),i+21);
return new Blob([out],{type:'image/png'});
}
i+=12+len;
}
return blob;
};
window.sendSheet=async({fundo=false,ponto=false}={})=>{
const cm=larguraFilme(), px=Math.ceil(cm/2.54*150);
const cm=larguraFilme(), px=Math.ceil(cm/2.54*300);
const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6);
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 blob=await window.comDpi(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}));
};
@@ -223,8 +244,9 @@ try{
'files beyond the 4 GB upload limit are rejected before browser analysis');
// A PNG above the browser's ~32k-pixel height limit cannot be checked here:
// it is refused with a clear message instead of being accepted as 0 DPI.
await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
await evaluate(`(()=>{const h=new Uint8Array(54);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24);
v.setUint32(33,9);h.set([0x70,0x48,0x59,0x73],37);v.setUint32(41,11811);v.setUint32(45,11811);h[49]=1;
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].measurementError`),'tall sheet refused');
assert.equal(await evaluate(`folhas[0].measurementError.includes('PNG alto')`),true);
@@ -232,34 +254,83 @@ try{
// A ready textile sheet whose real width is known (PNG pHYs >= 200 DPI, or a
// PDF page) must be 57 cm wide: otherwise it leaves the list and a dialog
// names it. A hand-made PNG header with a pHYs chunk, read by its header.
await evaluate(`window.pngLargura=async(w,ppm)=>{
const b=new Uint8Array(54);b.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A]);
await evaluate(`window.pngLargura=async(w,ppm,h=10339,nome='folha-larga.png')=>{
const comDpi=ppm!=null, b=new Uint8Array(comDpi?54:33);
b.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A]);
const v=new DataView(b.buffer);
v.setUint32(8,13);b.set([0x49,0x48,0x44,0x52],12);
v.setUint32(16,w);v.setUint32(20,10339);b.set([8,6,0,0,0],24);
v.setUint32(33,9);b.set([0x70,0x48,0x59,0x73],37);
v.setUint32(41,ppm);v.setUint32(45,ppm);b[49]=1;
const f=new File([b],'folha-larga.png',{type:'image/png'});
v.setUint32(16,w);v.setUint32(20,h);b.set([8,6,0,0,0],24);
if(comDpi){v.setUint32(33,9);b.set([0x70,0x48,0x59,0x73],37);
v.setUint32(41,ppm);v.setUint32(45,ppm);b[49]=1;}
const f=new File([b],nome,{type:'image/png'});
Object.defineProperty(f,'size',{value:900*1048576});
return sel([f]);}`);
// S1/S2: 35,8 cm at 300 DPI enters at its real size and asks for confirmation.
await evaluate(`pngLargura(4227,11811)`);
await waitFor(()=>evaluate(`folhas.length===0 && $('larguraDlg').open`),'wrong-width sheet opens dialog');
await waitFor(()=>evaluate(`folhas.length===1 && $('tamanhoDlg').open`),'narrow sheet opens the size dialog');
assert.equal(await evaluate(`$('tamanhoTit').textContent`),'folha-larga.png');
const tamanhoTxt=await evaluate(`$('tamanhoTxt').textContent`);
assert.match(tamanhoTxt,/35,8 cm/);
assert.match(tamanhoTxt,/0,88 m/);
assert.match(tamanhoTxt,/R\$ 21,90\/m/);
assert.equal(await evaluate(`$('tamanhoOk').textContent`),'Imprimir no tamanho real');
// While unconfirmed, "Adicionar ao carrinho" says so and adds nothing.
assert.deepEqual(await evaluate(`(()=>{const antes=pedido.length;$('qOk').disabled=false;$('qOk').click();
return {added:pedido.length-antes,msg:$('qmsg').textContent.includes('Confirme o tamanho')};})()`),
{added:0,msg:true});
await click('#tamanhoOk');
await waitFor(()=>evaluate(`!$('tamanhoDlg').open && folhas[0]?.confirmado===true`),'narrow sheet confirmed');
assert.ok(Math.abs(await evaluate(`folhas[0].med.larg`)-35.79)<0.02);
assert.equal(await evaluate(`$('larguraDlg').open`),false);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.size_confirmed===true`),
'confirmed size goes to the cart source');
await evaluate(`folhas=[];pintaFolha()`);
// S3: "Enviar outro arquivo" takes the sheet out of the list.
await evaluate(`pngLargura(4227,11811)`);
await waitFor(()=>evaluate(`folhas.length===1 && $('tamanhoDlg').open`),'narrow sheet opens again');
await click('#tamanhoOutro');
await waitFor(()=>evaluate(`folhas.length===0 && !$('tamanhoDlg').open`),'send another removes the sheet');
// S6: 61,0 cm does not fit the film: it leaves and the width dialog names it.
await evaluate(`pngLargura(7200,11811,10339,'folha-larga.png')`);
await waitFor(()=>evaluate(`folhas.length===0 && $('larguraDlg').open`),'too-wide sheet opens the width dialog');
assert.deepEqual(await evaluate(`({itens:$('larguraLista').children.length,
texto:$('larguraLista').textContent})`),
{itens:1,texto:'folha-larga.png: 35,8 cm (300 DPI)'});
texto:$('larguraLista').textContent,titulo:$('larguraTit').textContent})`),
{itens:1,texto:'folha-larga.png: tem 61,0 cm e não cabe em 57 cm.',
titulo:'A folha não cabe no filme de 57 cm'});
await click('#larguraOk');
await waitFor(()=>evaluate(`!$('larguraDlg').open && $('larguraLista').children.length===0`),
'width dialog closes and clears the list');
// 6732 px at 300 DPI is 57 cm within tolerance: accepted as today.
// S5: 6732 px at 300 DPI is 57 cm within tolerance: no dialog, real width.
await evaluate(`pngLargura(6732,11811)`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].med`),'57 cm sheet accepted');
assert.equal(await evaluate(`$('larguraDlg').open`),false);
assert.equal(await evaluate(`folhas[0].med.larg`),57);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].med && !$('tamanhoDlg').open && !$('larguraDlg').open`),
'57 cm sheet accepted');
assert.ok(Math.abs(await evaluate(`folhas[0].med.larg`)-56.998)<0.01);
assert.equal(await evaluate(`!!folhas[0].confirmado`),false);
await evaluate(`folhas=[];pintaFolha()`);
// Under 200 DPI the file says nothing about its real width: today's rule.
await evaluate(`pngLargura(4227,3780)`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].med`),'low-DPI sheet follows today rule');
assert.equal(await evaluate(`$('larguraDlg').open`),false);
// S7: without pHYs the width is unknown, so it assumes the film and asks.
await evaluate(`pngLargura(6732,null,10339,'folha-sem-dpi.png')`);
await waitFor(()=>evaluate(`folhas.length===1 && $('tamanhoDlg').open`),'unknown width opens the size dialog');
assert.equal(await evaluate(`$('tamanhoTit').textContent`),'folha-sem-dpi.png');
assert.match(await evaluate(`$('tamanhoTxt').textContent`),
/57 cm de largura e 87,5 cm de altura \(300 DPI\)/);
await click('#tamanhoOk');
await waitFor(()=>evaluate(`folhas[0]?.confirmado===true && !$('tamanhoDlg').open`),'unknown width confirmed');
await evaluate(`folhas=[];pintaFolha()`);
// S8: unknown width with less than 200 DPI is refused by resolution.
await evaluate(`pngLargura(2154,null,10339,'folha-baixa.png')`);
await waitFor(()=>evaluate(`folhas.length===0 && $('avisoTipo').textContent.includes('abaixo do mínimo de 200')`),
'unknown width under 200 DPI is refused');
assert.match(await evaluate(`$('avisoTipo').textContent`),/artes avulsas/);
// S13: several sheets needing a dialog are answered one at a time, in order.
await evaluate(`pngLargura(4227,11811,10339,'folha-a.png')`);
await waitFor(()=>evaluate(`$('tamanhoDlg').open && $('tamanhoTit').textContent==='folha-a.png'`),'first sheet in order');
await evaluate(`pngLargura(4300,11811,10339,'folha-b.png')`);
await waitFor(()=>evaluate(`folhas.length===2`),'second sheet queued');
await click('#tamanhoOk');
await waitFor(()=>evaluate(`$('tamanhoDlg').open && $('tamanhoTit').textContent==='folha-b.png'`),'second sheet next');
await click('#tamanhoOk');
await waitFor(()=>evaluate(`!$('tamanhoDlg').open && folhas.length===2 && folhas.every(x=>x.confirmado)`),
'each sheet answered on its own');
await evaluate(`folhas=[];pintaFolha()`);
await evaluate(`pickTipo('avulsa')`);
assert.equal(await evaluate('modo'),'avulsa');
@@ -458,11 +529,9 @@ try{
// Parsed geometry honors inherited MediaBox, CropBox, rotation and UserUnit.
// Extra pages and unreadable PDFs must never fall through to manual pricing.
const pdfFile=(data,name='sheet.pdf')=>`new File([Uint8Array.from(atob(${data}),c=>c.charCodeAt(0))],${JSON.stringify(name)},{type:'application/pdf'})`;
// Geometry alone: measured under UV, where the 57 cm rule does not apply.
const rotated=await evaluate(`(async()=>{const m=modo;modo='uvfile';
try{return await medirFolha(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))});}
finally{modo=m;}})()`);
assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2'});
// A 50,8 cm page on the 57 cm film: real size, asking for confirmation.
const rotated=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))})`);
assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2',confirmar:'estreita'});
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.
@@ -475,13 +544,17 @@ try{
assert.equal(beyondSpec.rejected,true);assert.match(beyondSpec.reason,/508 cm/);
const broken=await evaluate(`medirFolha(new File(['broken'],'broken.pdf',{type:'application/pdf'}))`);
assert.equal(broken.rejected,true);
// A PDF page is a known real width too: 30 cm is refused, 57 cm is accepted.
// A PDF page is a known real width too: 30 cm enters narrow with confirmation,
// 57 cm enters as the film, and 60 cm does not fit.
const pdfWide=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 850.394 360]'}))})`);
assert.equal(!!pdfWide.larguraErrada,true);
assert.ok(Math.abs(pdfWide.larguraErrada.cm-30)<0.01);
assert.equal(pdfWide.larguraErrada.dpi,null);
assert.equal(pdfWide.confirmar,'estreita');
assert.ok(Math.abs(pdfWide.larg-30)<0.01);
const pdfTooWide=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 1700.787 360]'}))})`);
assert.equal(!!pdfTooWide.largaDemais,true);
assert.ok(Math.abs(pdfTooWide.largaDemais.cm-60)<0.01);
const pdfOk=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 1615.748 360]'}))})`);
assert.ok(Math.abs(pdfOk.larg-57)<0.01);
assert.equal(pdfOk.confirmar,undefined);
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate(`sel([${pdfFile(pdfData({pages:2}),'two-pages.pdf')}])`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].measurementError`),'multipage PDF refusal');

View File

@@ -11,6 +11,17 @@ from psycopg.types.json import Jsonb
from app.core import db
from tests.print_file_test import artwork
def uv_sheet():
"""A UV ready sheet 27 x 13,5 cm at 300 DPI, inked inside a margin."""
import io
from PIL import Image, ImageDraw
image = Image.new('RGBA', (3189, 1595), (0, 0, 0, 0))
ImageDraw.Draw(image).rectangle([40, 40, 3149, 1555], fill=(220, 30, 60, 255))
out = io.BytesIO()
image.save(out, 'PNG', dpi=(300, 300))
return out.getvalue()
from tests.smoke_test import Client, item_spec, upload_bytes
@@ -36,9 +47,13 @@ def run():
early_id = None
order_id = None
upload_id = None
sheet_id = None
try:
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
sheet = {**item_spec('uvfile', '1', 0, upload_id, aspect=2),
# The UV ready sheet is its own 27 cm file at 300 DPI: the art above is
# 13,5 cm, and laid out at 27 cm it would be a stretched sheet.
sheet_id = upload_bytes(client, uv_sheet(), name=f'LOCAL-COUPON-SHEET-{tag}.png')
sheet = {**item_spec('uvfile', '1', 0, sheet_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
# The sheet is the customer's own file, not one someone opens by hand.
sheet['production']['sources'][0]['measurement'] = 'file'
@@ -155,8 +170,9 @@ def run():
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (early_id,))
if coupon_id:
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
if upload_id:
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (upload_id,))
for uid in (upload_id, sheet_id):
if uid:
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (uid,))
if __name__ == '__main__':

View File

@@ -243,58 +243,98 @@ class ProportionTests(unittest.TestCase):
class SheetWidthTests(unittest.TestCase):
"""A 57 cm ready sheet must really be 57 cm wide where the file tells
(contrato-largura-folha.md), or the cart is refused."""
"""A ready sheet prints at its real size, centred on the film
(contrato-folha-real.md, Server V1–V5)."""
def cart(self, mode, name, width_cm=57):
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': width_cm}
def cart(self, mode, name, width_cm=57, **source):
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': width_cm,
'measurement': 'file', **source}
return [{'mode': mode, 'production': {'sources': [source]}}], {name: {'name': name}}
def test_a_narrow_png_is_refused(self):
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png')
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('35,8 cm', issue)
self.assertIn('300 DPI', issue)
def test_an_unknown_sheet_is_laid_out_at_the_film_width(self):
# Rule 4: no DPI recorded, the sheet is taken as 57 cm; another width is a stretched layout.
files = FakeFiles({'sheet.png': encoded('PNG', (6732, 100))})
items, rows = self.cart('file', 'sheet.png', width_cm=40, size_confirmed=True)
self.assertIn('foi montada com 40,0 cm, mas tem 57 cm', grade_check.sheet_width_issue(files, items, rows))
def test_a_wide_png_is_refused(self):
def test_a_narrow_known_sheet_asks_for_confirmation(self):
# V3: 4227 px at 300 DPI is 35,8 cm, below the 57 cm film.
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png', width_cm=35.79)
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('confirme a folha 1 de 35,8 cm no tamanho real', issue)
def test_a_confirmed_narrow_sheet_passes(self):
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png', width_cm=35.79, size_confirmed=True)
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
def test_a_stretched_sheet_must_be_mounted_again(self):
# V2: the source says 57 cm, the file measures 35,8 cm.
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png', width_cm=57)
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('foi montada com 57,0 cm, mas tem 35,8 cm', issue)
def test_a_sheet_wider_than_the_film_is_refused(self):
# V1: 7200 px at 300 DPI is 61,0 cm.
files = FakeFiles({'sheet.png': encoded('PNG', (7200, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png')
self.assertIn('61,0 cm', grade_check.sheet_width_issue(files, items, rows))
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('61,0 cm', issue)
self.assertIn('não cabe', issue)
def test_sheet_width_rounding_boundaries(self):
for width_px, refused in ((6732, False), (6721, False), (6720, True)):
files = FakeFiles({'sheet.png': encoded('PNG', (width_px, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png')
issue = grade_check.sheet_width_issue(files, items, rows)
if refused:
self.assertIn('56,9 cm', issue)
else:
self.assertIsNone(issue, width_px)
def test_a_sheet_within_tolerance_of_the_film_passes(self):
# 6732 px at 300 DPI is 56,998 cm: within 0,1 cm of the film, no dialog.
files = FakeFiles({'sheet.png': encoded('PNG', (6732, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png', width_cm=56.998)
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
def test_png_under_trusted_dpi_passes(self):
for options in ({}, {'dpi': (96, 96)}, {'dpi': (150, 150)}):
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), **options)})
items, rows = self.cart('file', 'sheet.png')
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows), options)
def test_an_unknown_width_is_taken_as_the_film(self):
# V5: no pHYs, 6732 px over 57 cm is 300 effective DPI.
files = FakeFiles({'sheet.png': encoded('PNG', (6732, 100))})
items, rows = self.cart('file', 'sheet.png')
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('confirme a folha 1 de 57 cm antes de pagar', issue)
items, rows = self.cart('file', 'sheet.png', size_confirmed=True)
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
def test_only_the_57_cm_modes_are_checked(self):
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('premium', 'sheet.png')
self.assertIn('35,8 cm', grade_check.sheet_width_issue(files, items, rows))
for mode in ('uvfile', 'avulsa'):
items, rows = self.cart(mode, 'sheet.png')
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows), mode)
def test_an_unknown_width_under_the_minimum_dpi_is_refused(self):
# V4: 2154 px over 57 cm is 96 effective DPI.
files = FakeFiles({'sheet.png': encoded('PNG', (2154, 100))})
items, rows = self.cart('file', 'sheet.png')
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('96 DPI em 57 cm', issue)
def test_a_pdf_width_is_checked(self):
def test_uv_uses_the_27_cm_film(self):
# 2362 px at 300 DPI is 20,0 cm on the 27 cm UV film.
files = FakeFiles({'sheet.png': encoded('PNG', (2362, 100), dpi=(300, 300))})
items, rows = self.cart('uvfile', 'sheet.png', width_cm=20)
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('confirme a folha 1 de 20,0 cm no tamanho real', issue)
def test_a_narrow_pdf_asks_for_confirmation(self):
files = FakeFiles({})
items, rows = self.cart('file', 'sheet.pdf', width_cm=30)
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('30,0 cm', issue)
self.assertNotIn('DPI', issue)
for width_cm in (57, '56.95'):
items, rows = self.cart('file', 'sheet.pdf', width_cm=width_cm)
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows), width_cm)
self.assertIn('confirme a folha 1 de 30,0 cm no tamanho real', issue)
def test_a_pdf_wider_than_the_film_is_refused(self):
files = FakeFiles({})
items, rows = self.cart('file', 'sheet.pdf', width_cm=60)
issue = grade_check.sheet_width_issue(files, items, rows)
self.assertIn('não cabe', issue)
self.assertIn('60,0 cm', issue)
def test_customer_measured_sheets_pass(self):
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('file', 'sheet.png', width_cm=35.79, measurement='customer')
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
def test_loose_art_is_not_checked(self):
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
items, rows = self.cart('avulsa', 'sheet.png', width_cm=35.79)
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
def test_png_saved_dpi(self):
head = encoded('PNG', (4227, 100), dpi=(300, 300))

View File

@@ -105,6 +105,20 @@ class PrumoReportTests(unittest.TestCase):
self.assertIn('Formatos detectados: PDF, PNG', mixed)
self.assertIn('Chegou CDR, era PDF por dentro', mixed)
def test_a_confirmed_narrow_sheet_is_reported(self):
order = self.order()
item = order['snapshot']['items'][0]
item['mode'] = 'file'
item['size_confirmed_at'] = '2026-11-05T17:32:00+00:00'
item['production']['film_width_cm'] = 57
item['production']['sources'] = [
{'width_cm': '35.79', 'length_cm': '40', 'size_confirmed': True},
{'width_cm': '57', 'length_cm': '30', 'size_confirmed': True},
]
text = '\n'.join(report(order, {'u1': {'name': 'folha.png'}}))
self.assertIn('Folha 1: cliente confirmou folha de 35,8 cm no tamanho real às 14:32', text)
self.assertNotIn('Folha 2: cliente confirmou', text)
def test_customer_summary_is_plain_language(self):
lines = customer_summary(self.order()['snapshot']['items'])
text = ' '.join(lines)

View File

@@ -39,6 +39,31 @@ class SheetGapTests(unittest.TestCase):
self.assertEqual(str(caught.exception), SHEET_GAP_CHANGED)
class CentredSheetTests(unittest.TestCase):
"""A narrower ready sheet prints at its real size, centred on the film
(Marcus, 2026-12-02, contrato-folha-real.md V7)."""
def narrow_sheet(self, x_cm):
upload = str(uuid4())
width, film, length = 35.79, 57, 20
return Item.model_validate({
'mode': 'file', 'metres': str(length / 100), 'grade': 100, 'uploads': [upload],
'quality_status': 'ok', 'quality_acknowledged': False,
'production': {'version': 3, 'film_width_cm': film, 'height_cm': length,
'sources': [{'upload_id': upload, 'kind': 'sheet', 'width_cm': width,
'length_cm': length, 'copies': 1, 'measurement': 'file'}],
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': x_cm,
'y_cm': 0, 'width_cm': width, 'length_cm': length,
'rotation_degrees': 0, 'mirrored': False}]}})
def test_a_narrow_sheet_is_centred(self):
self.narrow_sheet((57 - 35.79) / 2)
def test_a_narrow_sheet_away_from_the_centre_is_refused(self):
with self.assertRaises(ValueError):
self.narrow_sheet(0)
def loose(xs_ys):
upload = str(uuid4())
placements = [{'source_index': 0, 'copy_index': i, 'x_cm': x, 'y_cm': y, 'width_cm': 20, 'length_cm': 10,

View File

@@ -0,0 +1,83 @@
"""ops.stretched_sheets lists the ready sheets laid out wider than they are."""
import io
import unittest
from contextlib import contextmanager
from PIL import Image
from ops import stretched_sheets
def png(width, dpi=None):
out = io.BytesIO()
Image.new('RGBA', (width, 10)).save(out, 'PNG', **({'dpi': (dpi, dpi)} if dpi else {}))
return out.getvalue()
class Storage:
bucket = 'b'
def __init__(self, blobs):
self.blobs = blobs
self.client = self
def get_object(self, Bucket, Key, Range):
return {'Body': io.BytesIO(self.blobs[Key])}
class Result:
def __init__(self, rows):
self.rows = rows
def fetchall(self):
return self.rows
def fetchone(self):
return self.rows[0] if self.rows else None
class Connection:
def __init__(self, orders, uploads):
self.orders, self.uploads = orders, uploads
def execute(self, sql, params):
if 'FROM dtf_local.orders' in sql:
return Result(self.orders)
return Result([self.uploads[params[0]]] if params[0] in self.uploads else [])
def order(number, mode='file', width=57, upload='u', provider='mercadopago'):
return {'id': number, 'number': number, 'payment': {'provider': provider}, 'created_at': None,
'snapshot': {'items': [{'mode': mode, 'production': {'sources': [
{'upload_id': upload, 'kind': 'sheet' if mode != 'avulsa' else 'artwork',
'measurement': 'file', 'width_cm': width}]}}]}}
class StretchedSheetsTests(unittest.TestCase):
def run_with(self, orders, uploads, blobs):
@contextmanager
def connect():
yield Connection(orders, uploads)
lines = []
stretched, unknown = stretched_sheets.main([], out=lines.append, storage=Storage(blobs), connect=connect)
return stretched, unknown, lines
def test_only_sheets_laid_out_at_another_width_are_listed(self):
uploads = {name: {'name': f'{name}.png', 'object_key': name, 'purged_at': None}
for name in ('narrow', 'right', 'nodpi', 'gone', 'loose', 'test')}
uploads['gone']['purged_at'] = '2026-11-20'
blobs = {'narrow': png(4227, 300), 'right': png(6732, 300), 'nodpi': png(4227),
'loose': png(1000, 300), 'test': png(4227, 300)}
orders = [order(177, upload='narrow'), order(178, upload='right'), order(179, upload='nodpi'),
order(180, upload='gone'), order(181, mode='avulsa', upload='loose'),
order(182, upload='test', provider='teste')]
stretched, unknown, lines = self.run_with(orders, uploads, blobs)
self.assertEqual([row[0] for row in stretched], [177])
self.assertIn('largura real 35,8 cm · montada com 57,0 cm · fator 1,59', '\n'.join(lines))
self.assertEqual(len(unknown), 2)
self.assertTrue(any('#179' in line and 'não grava o DPI' in line for line in unknown))
self.assertTrue(any('#180' in line and 'apagado' in line for line in unknown))
if __name__ == '__main__':
unittest.main()

View File

@@ -48,10 +48,13 @@ def item_with(uploads):
'mode': 'file', 'metres': round(height / 100, 4), 'grade': 100, 'uploads': uploads,
'production': {
'version': 3, 'film_width_cm': 57, 'height_cm': height,
# Measured by the customer (as a CDR's typed length): this test counts
# sheets; the real-size rule (contrato-folha-real.md) is not its business.
'sources': [{'upload_id': uid, 'kind': 'sheet', 'width_cm': 0.5, 'length_cm': 0.25,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'file'} for uid in uploads],
'placements': [{'source_index': index, 'copy_index': 0, 'x_cm': 0,
'measurement': 'customer'} for uid in uploads],
# A sheet narrower than the film is centred on it.
'placements': [{'source_index': index, 'copy_index': 0, 'x_cm': 28.25,
'y_cm': round(index * step, 4), 'width_cm': 0.5, 'length_cm': 0.25,
'rotation_degrees': 0, 'mirrored': False} for index in range(count)]},
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}

View File

@@ -192,16 +192,24 @@
const amount=document.createElement('b'); amount.textContent=value;
row.append(name,amount); return row;
};
const umaCasa = value => Number(value).toFixed(1).replace('.',',');
// The sheets of a split (item 17) are one line, as in the cart.
const linhas=[];
const linhas=[], estreitas=[];
for (const item of approved.items) {
const grupo=item.split && linhas.find(l=>l.split?.group===item.split.group);
if (grupo) { grupo.billed_metres=String(Number(grupo.billed_metres)+Number(item.billed_metres)); grupo.total_cents+=item.total_cents; grupo.folhas++; }
else linhas.push({...item,folhas:1});
const film=item.production?.film_width_cm;
if (film!=null) for (const source of item.production.sources || []) {
if (source.kind==='sheet' && Number(source.width_cm) < Number(film)-0.1)
estreitas.push('Folha de '+umaCasa(source.width_cm)+' cm no tamanho real, '+
'centralizada no filme de '+String(Number(film)).replace('.',',')+' cm');
}
}
const rows = linhas.map(item => linha(
(MODOS[item.mode]?.tit || item.mode)+(item.folhas>1?' · '+item.folhas+' folhas':'')+' · '+
fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
rows.push(...estreitas.map(texto => linha(texto,'')));
const pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,

View File

@@ -972,13 +972,20 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
</dialog>
<dialog class="ampliaDlg mistaDlg" id="larguraDlg" aria-labelledby="larguraTit">
<div class="ampliaCab"><b id="larguraTit">A folha precisa ter 57 cm de largura</b></div>
<div class="ampliaCab"><b id="larguraTit">A folha não cabe no filme de 57 cm</b></div>
<div class="mistaCorpo">
<ul id="larguraLista"></ul>
<p>Ajuste a largura da folha no seu programa para 57 cm e envie de novo.</p>
<p id="larguraTxt">Reduza no seu programa ou envie as artes separadas.</p>
<div class="mistaBot"><button type="button" class="ec-go" id="larguraOk">Entendi</button></div>
</div>
</dialog>
<dialog class="ampliaDlg mistaDlg" id="tamanhoDlg" aria-labelledby="tamanhoTit">
<div class="ampliaCab"><b id="tamanhoTit">Tamanho da folha</b></div>
<div class="mistaCorpo">
<p id="tamanhoTxt"></p>
<div class="mistaBot"><button type="button" class="ec-go" id="tamanhoOk">Confirmar</button><button type="button" id="tamanhoOutro">Enviar outro arquivo</button></div>
</div>
</dialog>
<dialog class="ampliaDlg" id="ampliaDlg" aria-labelledby="ampliaTit">
<div class="ampliaCab"><b id="ampliaTit">Sua folha</b>
<button type="button" id="ampliaFecha" aria-label="Fechar"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button></div>

View File

@@ -213,6 +213,17 @@ function itemParaSalvar(it){
}
return copia;
}
// A folha que entra no tamanho real, centralizada no filme: o resumo diz isso
// uma vez por folha estreita confirmada.
function folhasEstreitas(it){
const p=it.production;
if(!p || p.film_width_cm==null) return [];
const filme=Number(p.film_width_cm);
return (p.sources||[]).filter(s=>s.kind==='sheet' &&
Number(s.width_cm)<filme-0.1).map(s=>
'Folha de '+n1(Number(s.width_cm))+' cm no tamanho real, centralizada no filme de '+
String(filme).replace('.',',')+' cm');
}
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
function pintaPedido(){
const aPagar = itensAPagar();
@@ -242,6 +253,7 @@ function pintaPedido(){
'<span class="miniItem">'+(it.mini ? '<img src="'+escapeHTML(it.mini)+'" alt="">' : '<i>'+escapeHTML(it.ext||'')+'</i>')+
(it.arquivos>1 ? '<em>+'+(it.arquivos-1)+'</em>' : '')+'</span>'+
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span>'+
folhasEstreitas(it).map(l=>'<span>'+l+'</span>').join('')+
(semMargem(it)?'<span class="avisoF">O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.</span>':'')+'</div>'+
'<div class="vl2">'+rs(it.total)+'</div>'+
(window.dtfContaAberta?'<button type="button" class="salvaBt" data-salvai="'+i+'"'+
@@ -353,7 +365,7 @@ function carrinho(){
const sources=(ehFolha()?folhas:artes).map(x=>ehFolha()
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
copies:x.rep||1,rotation_degrees:0,mirrored:false,
measurement:x.med?'file':'customer',
measurement:x.med?'file':'customer',size_confirmed:!!x.confirmado,
// The empty strips cut from the top and the bottom (aplicaCorte).
...(x.corte?{trim_top_cm:x.corte.topo,trim_bottom_cm:x.corte.fim}:{})}
: fonteDaArte(x));
@@ -365,7 +377,8 @@ function carrinho(){
for(let copy_index=0;copy_index<source.copies;copy_index++){
// MARGEM_FOLHA_CM entre uma cópia e a próxima, nunca depois da última.
if(placements.length)y+=MARGEM_FOLHA_CM;
placements.push({source_index,copy_index,x_cm:0,y_cm:+y.toFixed(4),
placements.push({source_index,copy_index,
x_cm:+((larguraFilme()-source.width_cm)/2).toFixed(4),y_cm:+y.toFixed(4),
width_cm:source.width_cm,length_cm:source.length_cm,
rotation_degrees:0,mirrored:false});
y+=source.length_cm;

View File

@@ -114,14 +114,14 @@ const ACEITA={
};
const MEDE=/[.](png|jpe?g|webp|gif|bmp|pdf)$/i;
const DPI_RECUSA=96, DPI_AVISA=200; // régua aprovada pela Dropstar · 05/11/2026
// A folha pronta dos produtos têxteis de 57 cm tem de ter 57 cm de largura
// quando a largura real é conhecida: abre um aviso e não entra (Marcus,
// 01/12). Conhecida é um PNG que grava DPI_TAMANHO_REAL ou mais (o limite do
// A1, rodada 5) ou a página de um PDF; o resto segue a regra da versão 0
// (esticada até o filme). output/revisao/contrato-largura-folha.md.
const LARGURA_EXATA={file:57, premium:57};
// Folha pronta no tamanho real, centralizada no filme (Marcus, 02/12):
// output/revisao/contrato-folha-real.md. A largura é conhecida num PNG que
// grava DPI_TAMANHO_REAL ou mais (o limite do A1) e na página de um PDF; senão
// vale a do filme e o DPI sai dos pixels, com DPI_MINIMO_FOLHA de piso.
// Dentro de LARGURA_TOLERANCIA_CM da largura do filme conta como o filme.
const LARGURA_TOLERANCIA_CM=0.1;
const DPI_TAMANHO_REAL=200;
const DPI_MINIMO_FOLHA=200;
// 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.

View File

@@ -11,6 +11,11 @@
// straight to the cart.
$('qOk').addEventListener('click',()=>{
if($('qOk').disabled) return;
// A folha que pede confirmação de tamanho (Marcus, 02/12) só entra confirmada.
if(ehFolha() && folhas.some(x=>x.med?.confirmar && !x.confirmado)){
qm('Confirme o tamanho da folha antes de adicionar.','var(--vermelho)');
proximaTamanho(); return;
}
if(!$('prev').classList.contains('on')){ adicionaAoCarrinho(); return; }
const ok=$('ciente').classList.contains('on');
qm(ok? '<b>Ressalva aceita.</b> Confira a folha montada abaixo.'

View File

@@ -95,9 +95,9 @@ function recusaFolha(x, md){
folhas=folhas.filter(y=>y!==x);
pintaFolha();
avisoTipo('<b>'+escapeHTML(arquivo.name)+' não é uma folha montada.</b> '+
'Nos '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
' DPI, abaixo do mínimo de '+DPI_RECUSA+'. '+
'Se for uma arte para montarmos, use <b>'+MODOS[destino].tit+'</b>, '+
'Nos '+larguraFilme()+' cm do filme ela teria só '+md.dpiFolha+
' DPI, abaixo do mínimo de '+DPI_MINIMO_FOLHA+'. '+
'Se a sua folha não tem '+larguraFilme()+' cm, suba as artes como <b>'+MODOS[destino].tit+'</b>, '+
'a '+rs(PRECO[destino])+' o metro. '+
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
const botao=$('usarAvulsa');

View File

@@ -360,17 +360,22 @@ function medirFolha(file){
if(/\.png$/.test(nome)){
dimensoesImagem(file).then(async 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.'});
// Folha têxtil de 57 cm: se o PNG diz o DPI real, a largura tem de ser 57.
const exata=LARGURA_EXATA[modo];
if(exata!=null){
const dpi=await dpiSalvoPng(file);
if(dpi>=DPI_TAMANHO_REAL){
const cm=d.w/dpi*2.54;
if(Math.abs(cm-exata)>LARGURA_TOLERANCIA_CM) return res({larguraErrada:{cm, dpi}});
}
const L=larguraFilme(), tol=LARGURA_TOLERANCIA_CM, dpi=await dpiSalvoPng(file);
let measure;
if(dpi>=DPI_TAMANHO_REAL){
// A largura real vem do pHYs; até 0,1 cm além do filme conta como o filme.
const cm=d.w/dpi*2.54;
if(cm>L+tol) return res({largaDemais:{cm}});
// Até 0,1 cm além do filme é o filme: a folha nunca passa da largura dele.
measure={larg:Math.min(cm,L), alt:+(d.h/dpi*2.54).toFixed(1), fonte:'dimensões do arquivo',
dpiFolha:dpi, px:d.w};
if(cm<L-tol) measure.confirmar='estreita';
}else{
// Sem DPI confiável a folha vale o filme inteiro; o DPI sai dos pixels.
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, larguraDesconhecida:true};
if(measure.dpiFolha>=DPI_MINIMO_FOLHA) measure.confirmar='desconhecida';
}
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});
// A PNG the phone cannot open whole (out of memory, a 57 MB sheet on
// 26/11) is read in bands like a large one, never sent to the manual
@@ -382,21 +387,25 @@ function medirFolha(file){
if(RENDERIZA.test(nome) && file.size>GRANDE_BYTES){
dimensoesImagem(file).then(d=>{
if(!d || !(d.w>0) || !(d.h>0)) return res(null);
const L=larguraFilme();
res({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, grande:true});
const L=larguraFilme(), dpiFolha=Math.round(d.w/(L/2.54));
const measure={larg:L, alt:+(d.h/d.w*L).toFixed(1), fonte:'dimensões do arquivo',
dpiFolha, px:d.w, grande:true, larguraDesconhecida:true};
if(dpiFolha>=DPI_MINIMO_FOLHA) measure.confirmar='desconhecida';
res(measure);
}).catch(()=>res(null));
return;
}
if(RENDERIZA.test(nome)){
carregarImagem(file).then(img=>{
if(!img || !img.width) return res(null);
const L=larguraFilme();
const L=larguraFilme(), dpiFolha=Math.round(img.width/(L/2.54));
// Uma imagem só é folha montada se tiver pixel para ocupar a largura do
// filme. Sem esta conferência, qualquer arte pequena vira "folha" e leva
// o preço por metro sem nunca ter sido montada.
res({larg:L, alt:+(img.height/img.width*L).toFixed(1), fonte:'proporção da imagem',
dpiFolha:Math.round(img.width/(L/2.54)), px:img.width});
const measure={larg:L, alt:+(img.height/img.width*L).toFixed(1), fonte:'proporção da imagem',
dpiFolha, px:img.width, larguraDesconhecida:true};
if(dpiFolha>=DPI_MINIMO_FOLHA) measure.confirmar='desconhecida';
res(measure);
});
return;
}
@@ -428,14 +437,14 @@ function medirFolha(file){
const w=vp.width*unit*PT_CM, h=vp.height*unit*PT_CM;
if(!Number.isFinite(w) || !Number.isFinite(h) || w<=0 || h<=0 || h>6000)
return {rejected:true, reason:'Esta página é grande demais. Divida a folha em partes menores.'};
// A página do PDF já diz a largura real: fora de 57 cm, recusa.
const exata=LARGURA_EXATA[modo];
if(exata!=null && Math.abs(w-exata)>LARGURA_TOLERANCIA_CM)
return {larguraErrada:{cm:w, dpi:null}};
// Keep precise geometry for the fit and quote; the UI rounds only
// when displaying dimensions.
return {larg:+w.toFixed(3), alt:+h.toFixed(3),
// A página do PDF já diz a largura real: mais larga que o filme, não entra;
// mais estreita, entra no tamanho real e pede confirmação.
const L=larguraFilme(), tol=LARGURA_TOLERANCIA_CM;
if(w>L+tol) return {largaDemais:{cm:w}};
const medida={larg:+Math.min(w,L).toFixed(3), alt:+h.toFixed(3),
fonte:'página do PDF'+(unit!==1 ? ' · UserUnit '+unit : '')};
if(w<L-tol) medida.confirmar='estreita';
return medida;
}).then(res).catch(()=>res({rejected:true,
reason:'Não conseguimos ler este PDF. Exporte de novo como PDF de uma página ou PNG.'}))
.finally(()=>{ if(doc) doc.destroy().catch(()=>{}); });

View File

@@ -32,7 +32,7 @@ const TEXTO_MISTA={
// avulsa: imprimir assim mesmo (C1), ou trocar o arquivo por dois.
function perguntaMista(){
const dlg=$('mistaDlg');
if(!dlg || dlg.open || $('larguraDlg')?.open) return;
if(!dlg || dlg.open || $('larguraDlg')?.open || $('tamanhoDlg')?.open) return;
const lista=ehFolha()?folhas:artes;
const x=lista.find(y=>!y.mistaVista && mista(tracoDoArquivo(y)));
if(!x) return;

View File

@@ -48,19 +48,65 @@ function recusa(lista){
: '<b>'+exts+' não entra aqui.</b> Artes avulsas só aceitam PNG com '+
'fundo transparente. Para CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
}
// Folha de 57 cm com largura real conhecida e diferente: sai da lista e o
// diálogo junta os arquivos, um por linha, até o cliente fechar.
function recusaLargura(nome, {cm, dpi}){
// Folha mais larga que o filme: sai da lista e o diálogo junta os arquivos,
// um por linha, até o cliente fechar.
function recusaLargura(nome, {cm}){
const dlg=$('larguraDlg'); if(!dlg) return;
const lista=$('larguraLista');
const li=document.createElement('li');
li.textContent=nome+': '+n1(cm)+' cm'+(dpi==null?'':' ('+dpi+' DPI)');
li.textContent=nome+': tem '+n1(cm)+' cm e não cabe em '+larguraFilme()+' cm.';
lista.appendChild(li);
$('larguraTit').textContent='A folha não cabe no filme de '+larguraFilme()+' cm';
const texto=$('larguraTxt');
if(texto) texto.textContent='Reduza no seu programa ou envie as artes separadas.';
const ok=$('larguraOk');
ok.onclick=()=>dlg.close();
dlg.onclose=()=>{ lista.textContent=''; const z=$('zona'); if(z) z.focus(); agendaAvaliacao(); };
if(!dlg.open){ dlg.showModal(); ok.focus(); }
}
// Uma folha por vez, na ordem em que chegaram. Uma folha que já saiu da lista
// (troca de modo, remoção) é pulada; confirmar segue para a próxima.
let filaTamanho=[], tamanhoAtual=null;
function proximaTamanho(){
const dlg=$('tamanhoDlg'); if(!dlg || dlg.open) return;
while(filaTamanho.length && (!folhas.includes(filaTamanho[0]) || !filaTamanho[0].med?.confirmar))
filaTamanho.shift();
const x=filaTamanho.shift();
if(!x || !MODOS[modo] || !ehFolha()){ tamanhoAtual=null; return; }
tamanhoAtual=x;
const md=x.med;
$('tamanhoTit').textContent=x.f.name;
if(md.confirmar==='estreita'){
$('tamanhoTxt').textContent='Sua folha tem '+n1(md.larg)+' cm de largura. '+
'Vamos imprimir no tamanho real, centralizada no filme de '+larguraFilme()+
' cm, e cobrar pela altura: '+fmtM(md.alt/100)+' m. Se quiser aproveitar a largura toda, '+
'remonte a folha com '+larguraFilme()+' cm no seu programa ou envie as artes separadas ('+
rs(PRECO[PAR[modo]]||PRECO[modo])+'/m) que nós encaixamos.';
$('tamanhoOk').textContent='Imprimir no tamanho real';
}else{
$('tamanhoTxt').textContent='Sua folha vai sair com '+larguraFilme()+' cm de largura e '+
n1(md.alt)+' cm de altura ('+md.dpiFolha+' DPI). Confirma?';
$('tamanhoOk').textContent='Confirmar';
}
$('tamanhoOk').className='ec-go';
dlg.showModal();
$('tamanhoOk').focus();
}
function resolveTamanho(acao){
const dlg=$('tamanhoDlg'), x=tamanhoAtual;
if(x && folhas.includes(x)){
if(acao==='confirmar') x.confirmado=true;
else folhas=folhas.filter(y=>y!==x);
pintaFolha();
}
tamanhoAtual=null;
if(dlg && dlg.open) dlg.close();
if(acao==='outro') $('inp').click();
setTimeout(proximaTamanho,0);
}
$('tamanhoDlg')?.addEventListener('cancel',e=>{ e.preventDefault(); resolveTamanho('cancelar'); });
$('tamanhoOk')?.addEventListener('click',()=>resolveTamanho('confirmar'));
$('tamanhoOutro')?.addEventListener('click',()=>resolveTamanho('outro'));
const Z=$('zona'), I=$('inp');
Z.addEventListener('click',()=>I.click());
Z.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){I.click();e.preventDefault();}});
@@ -221,16 +267,23 @@ async function sel(fs){
if(md && md.rejected){
x.measurementError=md.reason; x.pct=null; pintaFolha(); return;
}
if(md && md.larguraErrada){
if(md && md.largaDemais){
if(folhas.includes(x)){
folhas=folhas.filter(y=>y!==x);
pintaFolha();
recusaLargura(x.f.name, md.larguraErrada);
recusaLargura(x.f.name, md.largaDemais);
}
return;
}
if(md && md.dpiFolha!=null && md.dpiFolha<DPI_RECUSA) return recusaFolha(x, md);
x.med=md; if(md) x.m=md.alt/100; x.pct=55; pintaFolha();
if(md && md.larguraDesconhecida && md.dpiFolha<DPI_MINIMO_FOLHA)
return recusaFolha(x, md);
x.med=md; if(md) x.m=md.alt/100; x.pct=55;
if(md && md.confirmar){
x.confirmado=false;
if(!filaTamanho.includes(x)) filaTamanho.push(x);
}
pintaFolha();
if(md && md.confirmar) proximaTamanho();
if(md && md.grande){
// Graded at once from its size in pixels. A PNG is then read as a
// stream into a small copy: the preview, and the sheet check.