feat: Prumo tells the card and the customer what it did (front 6)
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 4m41s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s

Every order now carries a short report of the decisions that happened:
original format, conversion, resolution, background, residue, montage,
billed length, contraction, thin-stroke warning, parts and generation time.
The card shows it above the file; the payment summary shows the customer's
version. The upload keeps the original name so a renamed CDR/PDF is told.
This commit is contained in:
Cauê Faleiros
2026-11-06 12:37:08 -03:00
parent 25e4ac541a
commit b10eeead6e
16 changed files with 242 additions and 6 deletions

View File

@@ -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<now()-%s) AS timed_out,
p.claimed_at+%s AS timeout_at,u.name
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items']
for uid in item.get('uploads') or []})
uploads = {row['id']: row for row in c.execute(
'''SELECT id::text AS id,name,original_name FROM dtf_local.uploads WHERE id::text=ANY(%s)''',
(upload_ids,)).fetchall()}
# A film over 15 m is several PNGs, in order (item 13).
parts = c.execute('''SELECT p.order_id,p.item_index,p.part,p.upload_id,u.name FROM dtf_local.print_parts p
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall()
@@ -261,6 +267,7 @@ def with_print_files(c, orders):
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
order['prumo'] = prumo.report(order, uploads)
approved = [row for row in finals if row['order_id'] == order['id']]
order['final_items'] = sorted({row['item_index'] for row in approved})
# The approved finals themselves: "Tratar a arte" keeps those it does not replace.

View File

@@ -14,7 +14,7 @@ from ..core.auth import owner
from ..core.models import QuoteRequest
from ..core.pricing import price
from .. import quote_review
from ..grade_check import Files, mismatch, resolution_issue
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
@@ -59,6 +59,16 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
# longer sets the price): before a cart is approved at checkout, the
# server works it out from the files.
files = Files(storage)
# Record the lowest source resolution for the Prumo report (front 6).
for draft_item, item in zip(draft['items'], body.items):
dpis = []
for source in item.production.sources:
row = rows.get(str(source.upload_id))
dpi = source_dpi(files, row, source.model_dump(mode='json')) if row else None
if dpi:
dpis.append(dpi)
if dpis:
draft_item['source_dpi'] = round(min(dpis))
issue = resolution_issue(files, draft['items'], rows)
if issue:
raise HTTPException(422, issue)

View File

@@ -41,9 +41,9 @@ def begin_upload(body: UploadStart, session_id=Depends(owner)):
audit('upload_quota_rejected')
raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
multipart = storage.begin(key)
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,expires_at)
VALUES(%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
(uid, session_id, body.name, body.size, key, multipart))
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
(uid, session_id, body.name, body.name, body.size, key, multipart))
return {'id': uid, 'part_bytes': PART_BYTES}
@router.get('/api/uploads/{uid}')

View File

@@ -193,6 +193,9 @@ class Item(StrictModel):
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
# The lowest source resolution the server measured, for the Prumo report
# (Dropstar, 05/11). None when the format cannot be measured.
source_dpi: int | None = Field(default=None, ge=0, le=1000000)
split: Split | None = None
@model_validator(mode='after')

137
app/prumo.py Normal file
View File

@@ -0,0 +1,137 @@
"""What the Prumo did to an order, in the order it happened (front 6).
The Site and the browser already make every decision; this module only turns
the fields they left on the order into the short report the designer reads
before opening the file. Nothing here changes an order or a price.
"""
from datetime import datetime
from decimal import Decimal
from zoneinfo import ZoneInfo
LOCAL = ZoneInfo('America/Sao_Paulo')
MANUAL = {'cdr', 'psd', 'psb', 'tif', 'tiff'}
def _ext(name):
return (str(name or '').rsplit('.', 1)[-1] if '.' in str(name or '') else '').lower()
def _m(value):
try:
return f'{Decimal(str(value)):.2f}'.replace('.', ',')
except Exception:
return str(value)
def _cm(value):
try:
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
except Exception:
return str(value)
def _hora(value):
if not value:
return ''
try:
moment = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace('Z', '+00:00'))
return ' às ' + moment.astimezone(LOCAL).strftime('%H:%M')
except Exception:
return ''
def report(order, uploads):
"""One line per action that happened, for the card and the customer.
`uploads` maps an upload id (as text) to a row with `name` and
`original_name`. `order` is the order row with its snapshot and generated
print files.
"""
snapshot = order.get('snapshot') or {}
items = snapshot.get('items') or []
generated = {row.get('item_index'): row for row in (order.get('print_files') or [])}
lines = []
if snapshot.get('proof_of'):
lines.append(f'Prova do pedido #{snapshot["proof_of"]}')
multi = len(items) > 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

View File

@@ -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)

View File

@@ -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',

View File

@@ -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;

View File

@@ -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`);

View File

@@ -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'])

View File

@@ -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)

48
tests/test_prumo.py Normal file
View File

@@ -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()

View File

@@ -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));

View File

@@ -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)}

View File

@@ -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;};

View File

@@ -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}