diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 01ff561..dc38ef3 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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: | diff --git a/app/api/quotes.py b/app/api/quotes.py index 6b70f29..c4ff38d 100644 --- a/app/api/quotes.py +++ b/app/api/quotes.py @@ -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 = {} diff --git a/app/core/models.py b/app/core/models.py index 70655ad..54bac31 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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') diff --git a/app/grade_check.py b/app/grade_check.py index 505725f..1c7f2d0 100644 --- a/app/grade_check.py +++ b/app/grade_check.py @@ -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 diff --git a/app/prumo.py b/app/prumo.py index 87a97d1..56ee1fa 100644 --- a/app/prumo.py +++ b/app/prumo.py @@ -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)) diff --git a/ops/stretched_sheets.py b/ops/stretched_sheets.py new file mode 100644 index 0000000..6bfe020 --- /dev/null +++ b/ops/stretched_sheets.py @@ -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() diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index 1fe7d08..4149a72 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -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'); diff --git a/tests/coupons_test.py b/tests/coupons_test.py index b669f95..4b5df64 100644 --- a/tests/coupons_test.py +++ b/tests/coupons_test.py @@ -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__': diff --git a/tests/test_grade_check.py b/tests/test_grade_check.py index 6bba95e..c52d38f 100644 --- a/tests/test_grade_check.py +++ b/tests/test_grade_check.py @@ -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)) diff --git a/tests/test_prumo.py b/tests/test_prumo.py index 5293749..627bb1c 100644 --- a/tests/test_prumo.py +++ b/tests/test_prumo.py @@ -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) diff --git a/tests/test_sheet_gap.py b/tests/test_sheet_gap.py index 2e5a947..4aa31d3 100644 --- a/tests/test_sheet_gap.py +++ b/tests/test_sheet_gap.py @@ -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, diff --git a/tests/test_stretched_sheets.py b/tests/test_stretched_sheets.py new file mode 100644 index 0000000..f3624c3 --- /dev/null +++ b/tests/test_stretched_sheets.py @@ -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() diff --git a/tests/upload_limits_test.py b/tests/upload_limits_test.py index 4738ef4..36480d8 100644 --- a/tests/upload_limits_test.py +++ b/tests/upload_limits_test.py @@ -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} diff --git a/web/checkout.js b/web/checkout.js index 58c44ab..520225d 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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, diff --git a/web/index.html b/web/index.html index 3855d96..948a257 100644 --- a/web/index.html +++ b/web/index.html @@ -972,13 +972,20 @@ h2 em{font-style:normal;color:var(--laranja)} -
A folha precisa ter 57 cm de largura
+
A folha não cabe no filme de 57 cm
-

Ajuste a largura da folha no seu programa para 57 cm e envie de novo.

+

Reduza no seu programa ou envie as artes separadas.

+ +
Tamanho da folha
+
+

+
+
+
Sua folha
diff --git a/web/site-cart.js b/web/site-cart.js index 46618c8..3724563 100644 --- a/web/site-cart.js +++ b/web/site-cart.js @@ -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) + '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(){ ''+(it.mini ? '' : ''+escapeHTML(it.ext||'')+'')+ (it.arquivos>1 ? '+'+(it.arquivos-1)+'' : '')+''+ '
'+escapeHTML(it.tit)+''+escapeHTML(it.desc)+''+ + folhasEstreitas(it).map(l=>''+l+'').join('')+ (semMargem(it)?'O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.':'')+'
'+ '
'+rs(it.total)+'
'+ (window.dtfContaAberta?''); const botao=$('usarAvulsa'); diff --git a/web/site-pdf.js b/web/site-pdf.js index 2b4c8eb..25dbe4b 100644 --- a/web/site-pdf.js +++ b/web/site-pdf.js @@ -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=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(wres({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(()=>{}); }); diff --git a/web/site-quality.js b/web/site-quality.js index ec3f5ec..195cc16 100644 --- a/web/site-quality.js +++ b/web/site-quality.js @@ -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; diff --git a/web/site-upload.js b/web/site-upload.js index 66fa2e0..6a83c59 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -48,19 +48,65 @@ function recusa(lista){ : ''+exts+' não entra aqui. Artes avulsas só aceitam PNG com '+ 'fundo transparente. Para CDR, AI ou PSD, exporte em PNG ou use Arquivo por metro.'; } -// 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