"""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'} # The stroke class in the customer's words, without the internal C1/C2/C3 code. STROKE_SUMMARY = { 'C1': 'Sua arte tem traços muito finos; a impressão foi ajustada para eles.', 'C2': 'Sua arte tem traços médios; a impressão foi ajustada para eles.', 'C3': 'Sua arte tem áreas cheias; a impressão foi ajustada para elas.', } 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()}') # One format line per item, not one per file: the designer reads what # the item is, and only the files that changed are named above. formats = sorted({_ext(name).upper() or 'desconhecido' for name in names}) if len(formats) == 1: count = f' ({len(names)} arquivos)' if len(names) > 1 else '' lines.append(f'{lead}Formato detectado: {formats[0]}{count}') elif formats: lines.append(f'{lead}Formatos detectados: {", ".join(formats)}') 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) + ')') # From the claim, not from the queue: the customer waits for the # generation, not for the file's turn. if ready and row.get('finished_at') and row.get('claimed_at'): seconds = (row['finished_at'] - row['claimed_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') in STROKE_SUMMARY: lines.append(f'{lead}{STROKE_SUMMARY[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