Files
dtf-system/app/prumo.py
Cauê Faleiros a712c69aca
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 5m44s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m22s
fix: align proof, treatment, metrics and site videos with PDF
2026-11-06 15:27:48 -03:00

137 lines
6.3 KiB
Python

"""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}
row = generated.get(index)
ready = bool(row and row.get('status') == 'ready')
if row and row.get('status') == 'manual':
lines.append(f'{lead}Arquivo exige preparo manual')
dpi = item.get('source_dpi')
if dpi:
lines.append(f'{lead}Resolução detectada: {dpi} DPI')
if ready:
detail = row.get('detail') or {}
if exts & {'pdf', 'ai'} and detail.get('format') == 'png':
lines.append(f'{lead}PDF → PNG {detail.get("dpi", 300)} DPI')
elif detail.get('format'):
lines.append(f'{lead}Arquivo final em {detail["format"].upper()} {detail.get("dpi", 300)} DPI')
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')))
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')
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) + ')')
if ready and 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 foi medida em {dpi} DPI. O arquivo de impressão será preparado em 300 DPI após o pagamento.')
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