diff --git a/app/api/operator.py b/app/api/operator.py index b0131aa..5cb7aac 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -18,7 +18,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, login_failed, may_move, may_reorder, password_matches, throttle) from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files -from .. import cnpj, hotfolder, machines, mail, payments, proof, quote_review, receipt +from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt from .. import tiny from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, quote_views, storage, upload_row) @@ -215,10 +215,16 @@ def with_print_files(c, orders): approved, and the customer's corrections waiting to be approved as finals.""" ids = [o['id'] for o in orders] generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at, + p.created_at, (p.status='rendering' AND p.claimed_at 1 + for index, item in enumerate(items): + lead = f'Item {index + 1}: ' if multi else '' + names = [] + for uid in item.get('uploads') or []: + row = uploads.get(str(uid)) or {} + original = row.get('original_name') or row.get('name') or '' + final = row.get('name') or original + names.append(final) + if original and final and _ext(original) != _ext(final): + lines.append(f'{lead}Chegou {_ext(original).upper()}, era {_ext(final).upper()} por dentro — tratado como {_ext(final).upper()}') + else: + lines.append(f'{lead}Formato detectado: {_ext(final).upper() or "desconhecido"}') + exts = {_ext(name) for name in names} + if exts & {'pdf', 'ai'}: + lines.append(f'{lead}PDF → PNG 300 DPI') + elif exts & MANUAL: + lines.append(f'{lead}{"/".join(sorted(exts & MANUAL)).upper()} com texto vivo → conferência manual') + dpi = item.get('source_dpi') + if dpi: + lines.append(f'{lead}Veio em {dpi} DPI, ampliado para 300' if dpi < 300 else f'{lead}Resolução {dpi} DPI') + lines.append(f'{lead}Fundo conferido na sala (arquivo manual)' if exts & MANUAL + else f'{lead}Fundo transparente') + dots = int(item.get('residue_accepted') or 0) + if dots: + lines.append(f'{lead}{dots} ponto{"s" if dots > 1 else ""} < 2 mm — cliente aceitou' + + _hora(item.get('residue_accepted_at'))) + else: + lines.append(f'{lead}0 pontos de recorte') + production = item.get('production') or {} + 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)) + lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, ' + f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), ' + f'altura {_cm(production.get("height_cm"))} cm') + billed = item.get('billed_metres') or item.get('metres') + if billed: + lines.append(f'{lead}Cobrado {_m(billed)} m (height_cm {_cm(production.get("height_cm"))})') + if item.get('stroke_px') and item.get('stroke_class'): + lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}') + if item.get('stroke_choice') == 'client_c3': + lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu proteger as áreas chapadas (C3)') + elif item.get('stroke_choice') == 'measured': + lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1') + else: + lines.append(f'{lead}Aviso de traço fino não disparou') + row = generated.get(index) + if row: + detail = row.get('detail') or {} + parts = detail.get('parts') or [] + if len(parts) > 1: + sizes = [Decimal(str(p.get('to_cm', 0))) - Decimal(str(p.get('from_cm', 0))) for p in parts] + lines.append(f'{lead}{_m(billed)} m → {len(parts)} partes (' + + ' + '.join(_m(size) for size in sizes) + ')') + elif detail.get('format'): + lines.append(f'{lead}Arquivo final em {detail["format"].upper()} {detail.get("dpi", 300)} DPI') + if row.get('finished_at') and row.get('created_at'): + seconds = (row['finished_at'] - row['created_at']).total_seconds() + lines.append(f'{lead}Prumo levou {max(1, round(seconds))} s') + return lines + + +def customer_summary(items): + """The same facts in the customer's words, for the summary before paying.""" + lines = [] + for index, item in enumerate(items or []): + lead = f'Item {index + 1}: ' if len(items) > 1 else '' + dpi = item.get('source_dpi') + if dpi and dpi < 300: + lines.append(f'{lead}Sua arte veio em {dpi} DPI e foi ampliada para 300.') + dots = int(item.get('residue_accepted') or 0) + if dots: + lines.append(f'{lead}Há {dots} pontinho{"s" if dots > 1 else ""} solto{"s" if dots > 1 else ""} ' + 'que você aceitou imprimir.') + if item.get('stroke_class'): + lines.append(f'{lead}O traço mais fino foi medido em {item["stroke_class"]}.') + if item.get('stroke_choice') == 'measured': + lines.append(f'{lead}Você escolheu imprimir o traço fino assim mesmo (C1).') + elif item.get('stroke_choice') == 'client_c3': + lines.append(f'{lead}Você escolheu proteger as áreas chapadas (C3).') + return lines diff --git a/app/quote_review.py b/app/quote_review.py index b1192c1..bbf7072 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -87,6 +87,7 @@ def approve(c, row, items, reviewer): if original.get('stroke_choice_at') else {}), **({'proof_y_fraction': original['proof_y_fraction']} if original.get('proof_y_fraction') is not None else {}), + **({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}), **({'split': original['split']} if original.get('split') else {})}) bill_splits(priced) metres = sum(Decimal(i['billed_metres']) for i in priced) diff --git a/app/runtime.py b/app/runtime.py index 7419203..207dcb5 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -32,6 +32,7 @@ if os.environ.get('FREIGHT_ADAPTER') == 'jadlog': from .jadlog import JadlogFreight _carriers.append(JadlogFreight()) from . import correios as _correios +from . import prumo if _correios.configured(): _carriers.append(_correios.CorreiosFreight()) freight = FreightOptions(_carriers or [FakeFreight()]) @@ -132,8 +133,10 @@ def quote_view(c, row, order=None, attempt=None, known=False): from .payment_messages import rejection attempt = {**attempt, 'message': rejection(attempt['status_detail'])} expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24) + items = (row['approved'] or row['draft']).get('items') or [] return {'id': row['id'], 'created_at': row['created_at'], 'draft': row['draft'], 'approved': row['approved'], + 'prumo': prumo.customer_summary(items), 'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired else 'approved' if row['approved'] else 'pending_review', 'auto_approved': row.get('reviewed_by') == 'auto', diff --git a/app/schema.sql b/app/schema.sql index 9cb2d6a..6a4296f 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -80,6 +80,8 @@ CREATE TABLE IF NOT EXISTS dtf_local.security_events ( ); ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz; ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz; +ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS original_name text; +UPDATE dtf_local.uploads SET original_name=name WHERE original_name IS NULL; ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending'; ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text; ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz; diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 21aaf8e..0a6c957 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -208,6 +208,8 @@ try{ assert.equal(await kanban.eval(`!!document.querySelector('[data-card="${oid}"] .card-open')`),true); await kanban.click(`[data-card="${oid}"]`); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel'); + // The Prumo report is on the card before the designer opens the file. + await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] .prumo')`),'Prumo report'); // No machine at payment (Dropstar, 2026-11-05): the pull chooses one. await waitFor(()=>kanban.eval(`board.machines.some(m=>m.active&&m.products.includes('textil'))`),'a textile machine'); const machineId=await kanban.eval(`board.machines.find(m=>m.active&&m.products.includes('textil')).id`); diff --git a/tests/print_file_test.py b/tests/print_file_test.py index e17fae4..21e6a53 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -94,6 +94,7 @@ def run(): order = paid_order(client, loose_item(uid)) order, row = wait_print(client, order['id'], 'ready') assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(1600 / (20 / 2.54)) + assert any('Prumo levou' in line for line in order['prumo']), order['prumo'] # A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm # and the 1,5 cm footer band, outside the billed length. film = download_png(client, row['upload_id']) diff --git a/tests/smoke_test.py b/tests/smoke_test.py index e971993..1ad46b2 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -220,6 +220,7 @@ def run(): assert auto['status']=='approved' seen=client.call('/quotes/'+auto['id']) assert seen['auto_approved'] and seen['review_reason'] is None + assert isinstance(seen.get('prumo'), list) and seen['prumo'], seen.get('prumo') assert seen['approved']['total_cents']==6132+int(os.environ.get('MOCK_FREIGHT_CENTS','1500')) assert client.call('/quotes',small)['status']=='approved' client.call('/operator/quotes/'+auto['id']+'/approve',{'items':small['items']},operator=True,expected=409) diff --git a/tests/test_prumo.py b/tests/test_prumo.py new file mode 100644 index 0000000..de2eca3 --- /dev/null +++ b/tests/test_prumo.py @@ -0,0 +1,48 @@ +"""The Prumo report: only what happened, in the order it happened (front 6).""" +import unittest +from datetime import datetime, timedelta, timezone + +from app.prumo import customer_summary, report + + +class PrumoReportTests(unittest.TestCase): + def order(self): + item = { + 'mode': 'avulsa', 'billed_metres': '1.30', 'metres': '1.30', + 'uploads': ['u1'], 'source_dpi': 96, 'residue_accepted': 3, + 'residue_accepted_at': '2026-11-05T17:32:00+00:00', + 'stroke_px': 6, 'stroke_class': 'C2', 'stroke_choice': 'measured', + 'production': {'height_cm': '130', 'placements': [ + {'rotation_degrees': 0}, {'rotation_degrees': 90}]}, + } + started = datetime(2026, 11, 5, 14, 0, tzinfo=timezone.utc) + return {'snapshot': {'items': [item]}, 'print_files': [{ + 'item_index': 0, 'created_at': started, 'finished_at': started + timedelta(seconds=41), + 'detail': {'format': 'png', 'dpi': 300, 'parts': [ + {'from_cm': '0', 'to_cm': '15'}, {'from_cm': '15', 'to_cm': '16'}]}, + }]} + + def test_card_report_reads_the_decisions(self): + lines = report(self.order(), {'u1': {'name': 'arte.pdf', 'original_name': 'arte.cdr'}}) + text = '\n'.join(lines) + self.assertIn('Chegou CDR, era PDF por dentro', text) + self.assertIn('PDF → PNG 300 DPI', text) + self.assertIn('Veio em 96 DPI, ampliado para 300', text) + self.assertIn('3 pontos < 2 mm — cliente aceitou', text) + self.assertIn('2 artes, 1 girada', text) + self.assertIn('Menor traço 6 px → C2', text) + self.assertIn('cliente escolheu imprimir em C1', text) + self.assertIn('2 partes (15,00 + 1,00)', text) + self.assertIn('Prumo levou 41 s', text) + + def test_customer_summary_is_plain_language(self): + lines = customer_summary(self.order()['snapshot']['items']) + text = ' '.join(lines) + self.assertIn('96 DPI', text) + self.assertIn('3 pontinhos', text) + self.assertIn('C2', text) + self.assertIn('C1', text) + + +if __name__ == '__main__': + unittest.main() diff --git a/web/checkout.js b/web/checkout.js index ff374e3..b458ef3 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -123,7 +123,12 @@ rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo, approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis')); rows.push(linha('Total', rs(approved.total_cents/100), 'tot')); - resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows); + const prumoBox=node('div',null,'prumoResumo'); + if(quote.prumo?.length){ + prumoBox.append(node('b','O que o Prumo fez')); + for(const line of quote.prumo) prumoBox.append(node('span',line)); + } + resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows, ...(quote.prumo?.length?[prumoBox]:[])); } function esqueletoPagamento() { const linhas=['skel skelLinha','skel skelLinha','skel skelLinha curta'].map(c=>node('div',null,c)); diff --git a/web/kanban.css b/web/kanban.css index ed82a8b..b176c3c 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -414,6 +414,9 @@ main{padding:0} .dl dt{font-size:12.5px;color:var(--tx3)} .dl dd{margin:0;font-size:14px;font-weight:550;overflow-wrap:anywhere} .inotes{display:flex;flex-direction:column;gap:7px;margin-top:18px} +.prumo{border:1px solid var(--ln2);border-radius:9px;padding:7px 10px;background:var(--sf3);font-size:12px;color:var(--mut)} +.prumo summary{cursor:pointer;color:var(--tx);font-weight:600} +.prumo p{margin:5px 0 0;line-height:1.35} .inote{display:flex;align-items:flex-start;gap:8px;font-size:13px;color:var(--tx2)} .inote .i{margin-top:2px;color:var(--tx3)} .inote.ok .i{color:var(--mine)} diff --git a/web/kanban.js b/web/kanban.js index 557f455..e434bdc 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -1981,6 +1981,16 @@ function itemCard(order,item,index){ notes.append(itemNote(done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn')); } if(order.treated?.items.includes(index))notes.append(itemNote('Arte tratada: '+TREATED_NOTE.charAt(0).toLowerCase()+TREATED_NOTE.slice(1)+' Aprovado por '+order.treated.by+'.')); + // O que o Prumo fez (front 6): the actions that happened, before the + // designer opens the file. Multi-item orders show each item's own lines. + const multi=order.snapshot.items.length>1, prefix=multi?'Item '+(index+1)+': ':''; + const prumoLines=(order.prumo||[]).filter(line=>!multi||line.startsWith(prefix)||line.startsWith('Prova do')) + .map(line=>line.startsWith(prefix)?line.slice(prefix.length):line); + if(prumoLines.length){ + const block=node('details',undefined,'prumo');block.append(node('summary','O que o Prumo fez')); + prumoLines.forEach(line=>block.append(node('p',line))); + notes.append(block); + } if(notes.children.length)info.append(notes); const links=node('div',undefined,'links'); const dl_=(text,uid)=>{const b=downloadButton(text,download(uid),'btn');return b;}; diff --git a/web/site-v2.css b/web/site-v2.css index 6352078..6032047 100644 --- a/web/site-v2.css +++ b/web/site-v2.css @@ -405,6 +405,9 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te .pagResumo .l span{color:var(--texto2)} .pagResumo .tot{display:flex;justify-content:space-between;align-items:baseline;border-top:1px solid #EFEFEF;margin-top:10px;padding-top:12px} .pagResumo .tot b{font-family:"Inter",sans-serif;font-weight:900;font-size:24px} +.prumoResumo{margin-top:12px;border-top:1px solid #EFEFEF;padding-top:12px;font-size:13px;line-height:1.45;color:var(--texto2)} +.prumoResumo b{display:block;color:var(--texto);font-family:"Inter",sans-serif;font-size:14px;margin-bottom:5px} +.prumoResumo span{display:block;padding:1px 0} .metodos{display:grid;grid-template-columns:1fr;gap:10px;max-width:420px;margin-bottom:20px} .metodo{height:56px;display:flex;align-items:center;gap:12px;padding:0 16px;border:2px solid var(--linha);border-radius:var(--raio2);background:#fff;color:var(--preto);font-family:"Inter",sans-serif;font-weight:700;font-size:16.5px;text-align:left;cursor:pointer} .metodo::before{content:"";width:18px;height:18px;flex-shrink:0;border-radius:50%;border:2px solid #B5B8BD;box-sizing:border-box}