"""Números per machine, month by month (Fase 2, front 1, part b). From what the room enters on each machine's sheet (app/machine_log.py) and what the board already knows it printed, per machine and calendar month (America/Sao_Paulo): Produção printed metres (machine_log rule: imp -> rev, film metres, PROOF_SHEET_CM per proof item); hours running = the union of the time its orders spent in Imprimindo, clipped to the month (two orders printing together count once); metres per hour = printed / hours running; hours stopped = the "stop" events' minutes, in total and by reason (the note, as typed). Consumo metres per film roll = printed / rolls entered in the month; ink litres per 100 m, per colour = litres entered / printed * 100; powder grams per 100 m = kg entered * 1000 / printed * 100. Refills stand for what was used: an entry replaces what ran out. Custo supplies per metre and parts per metre = their cost entered in the month / printed; total per metre = the sum. Resultado contribution = what the orders it printed in the month sold (their items' total_cents, not freight or treatment; no proof or test order) minus its supplies and parts of the month. Also accumulated since installation (installed_on, else log_since). ROI accumulated contribution / (price + parts since installation), in %, and months to pay back = (price + parts since installation - accumulated contribution) / the average monthly contribution since installation (None when that average is not positive or the price is unknown). Every ratio is None when its divisor is zero or unknown: no number is better than a made-up one. """ from datetime import datetime, time from decimal import Decimal, ROUND_HALF_UP from zoneinfo import ZoneInfo from .machine_log import NOT_UNDONE, SUPPLIES SAO_PAULO = ZoneInfo('America/Sao_Paulo') # The five inks Números lists, in the order the sheet knows them. INK_ITEMS = tuple(item for item in SUPPLIES if item.startswith('ink_')) # Average month, for the monthly contribution since installation. _MONTH_SECONDS = Decimal('30.4375') * 86400 # Below a quarter of an hour in Imprimindo the pace is noise: an order moved # through in seconds made a machine show 110671,5 m/h (16/11). No pace then. MIN_PACE_HOURS = 0.25 def pace(metres, hours): """Metres per hour, one decimal; None below MIN_PACE_HOURS of printing.""" if not hours or float(hours) < MIN_PACE_HOURS: return None return round(float(metres) / float(hours), 1) def month_bounds(month): """'2026-11' (None: the current month, local) -> (first day, first day of the next month) as timezone-aware datetimes at 00:00 America/Sao_Paulo. A malformed month is ValueError.""" now = datetime.now(SAO_PAULO) if month is None: year, number = now.year, now.month else: try: parsed = datetime.strptime(month, '%Y-%m') except (TypeError, ValueError): raise ValueError('month must be YYYY-MM') from None # strptime accepts a single digit; the board always sends two. if month != f'{parsed.year:04d}-{parsed.month:02d}': raise ValueError('month must be YYYY-MM') year, number = parsed.year, parsed.month start = datetime(year, number, 1, tzinfo=SAO_PAULO) if number == 12: end = datetime(year + 1, 1, 1, tzinfo=SAO_PAULO) else: end = datetime(year, number + 1, 1, tzinfo=SAO_PAULO) return start, end def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=None, inks=None, powder=None, price_cents=None, contribution_cents=0, installed_parts_cents=0, months=None): """Every Números ratio from raw totals, so they are tested without a database. A zero or unknown divisor gives None; cents are whole.""" printed = Decimal(str(printed or 0)) def per_metre(cents): if printed == 0: return None return int((Decimal(cents) / printed).quantize(Decimal('1'), rounding=ROUND_HALF_UP)) result = { 'metres_per_hour': pace(printed, hours_running), 'metres_per_roll': round(float(printed / Decimal(str(rolls))), 1) if rolls else None, 'ink_per_100m': { item: (None if quantity is None or not printed else round(float(Decimal(str(quantity)) / printed * 100), 1)) for item, quantity in (inks or {}).items()}, 'powder_g_per_100m': (round(float(Decimal(str(powder)) * 1000 / printed * 100), 1) if powder is not None and printed else None), 'supplies_per_metre_cents': per_metre(supplies_cents), 'parts_per_metre_cents': per_metre(parts_cents), 'total_per_metre_cents': per_metre(Decimal(supplies_cents) + Decimal(parts_cents)), 'roi_pct': None, 'payback_months': None, } # Without a price there is no investment to measure the return against. invested = None if price_cents is None else Decimal(price_cents) + Decimal(installed_parts_cents) if invested: result['roi_pct'] = round(float(Decimal(contribution_cents) * 100 / invested), 1) if price_cents is not None and months and months > 0: average = Decimal(contribution_cents) / Decimal(str(months)) if average > 0: result['payback_months'] = round( float((invested - Decimal(contribution_cents)) / average), 1) return result def _printed_orders(c, machine_id, start, end): """The orders that left Imprimindo for Revisão on the machine in the period, with what is needed to count film and what they sold.""" return c.execute(f'''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE} AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall() def _film(snapshot, items=None): """The film printed for one order (machine_log's rule), as Decimal; on a reprint only the `items` that went again.""" from .proof import PROOF_SHEET_CM snapshot = snapshot or {} proof = bool(snapshot.get('proof_of')) total = Decimal(0) for index, item in enumerate(snapshot.get('items') or []): if items is not None and index not in items: continue if proof: total += PROOF_SHEET_CM else: value = item.get('metres') if value is None: value = item.get('billed_metres') total += Decimal(str(value or 0)) return total def _sold(row): """What the order's items sold; proof cards, tests and cancelled orders are not sales (as REAL_ORDER in the board).""" if (row['parent_id'] is not None or row['cancelled_at'] is not None or (row['payment'] or {}).get('provider') == 'teste'): return 0 return sum(int(item.get('total_cents') or 0) for item in (row['snapshot'] or {}).get('items') or []) def printed_between(c, machine_id, start, end): """Film metres the machine printed in [start, end), as Decimal.""" return sum((_film(row['snapshot'], row.get('items')) for row in _printed_orders(c, machine_id, start, end)), Decimal(0)) def _union_hours(spans, start, end): """The hours the spans (start, end) cover inside [start, end); time shared by several orders is counted once.""" clipped = [] for at, until in spans: first, last = max(at, start), min(until, end) if last > first: clipped.append((first, last)) seconds, reached = 0.0, None for at, until in sorted(clipped): if reached is None or at >= reached: seconds += (until - at).total_seconds() reached = until elif until > reached: seconds += (until - reached).total_seconds() reached = until return round(seconds / 3600, 1) def machine_month(c, machine, start, end): """One machine's figures for [start, end): {'printed_metres', 'hours_running', 'metres_per_hour', 'stopped_hours', 'stops': [{'reason', 'hours'}], 'metres_per_roll', 'ink_per_100m': {item: litres}, 'powder_g_per_100m', 'supplies_cents', 'parts_cents', 'supplies_per_metre_cents', 'parts_per_metre_cents', 'total_per_metre_cents', 'sold_cents', 'contribution_cents'}. `machine` is its row from dtf_local.machines.""" mid = machine['id'] rows = _printed_orders(c, mid, start, end) printed = sum((_film(row['snapshot'], row.get('items')) for row in rows), Decimal(0)) sold = sum((_sold(row) for row in rows), 0) ids = [row['id'] for row in rows] spans = c.execute('''WITH events AS ( SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m WHERE m.order_id=ANY(%s)), spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events) SELECT at, until FROM spans WHERE state='imp' AND until IS NOT NULL''', (ids,)).fetchall() if ids else [] hours = _union_hours([(row['at'], row['until']) for row in spans], start, end) supplies = c.execute('''SELECT item, COALESCE(sum(quantity),0) AS quantity, COALESCE(sum(cost_cents),0) AS cents FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='supply' AND created_at>=%s AND created_at<%s GROUP BY item''', (mid, start, end)).fetchall() quantities = {row['item']: row['quantity'] for row in supplies} supplies_cents = int(sum((row['cents'] for row in supplies), 0)) parts_cents = int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='part' AND created_at>=%s AND created_at<%s''', (mid, start, end)).fetchone()['cents']) stops = c.execute('''SELECT note, COALESCE(sum(stop_minutes),0) AS minutes FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='event' AND item='stop' AND created_at>=%s AND created_at<%s GROUP BY note ORDER BY minutes DESC, note''', (mid, start, end)).fetchall() stop_list = [{'reason': row['note'] or '', 'hours': round(float(row['minutes']) / 60, 1)} for row in stops if row['minutes']] stopped = round(sum(float(row['minutes']) for row in stops) / 60, 1) values = ratios(printed, hours_running=hours, supplies_cents=supplies_cents, parts_cents=parts_cents, rolls=quantities.get('film'), inks={item: quantities.get(item) for item in INK_ITEMS}, powder=quantities.get('powder')) return { 'printed_metres': round(float(printed), 2), 'hours_running': hours, 'metres_per_hour': values['metres_per_hour'], 'stopped_hours': stopped, 'stops': stop_list, 'metres_per_roll': values['metres_per_roll'], 'ink_per_100m': values['ink_per_100m'], 'powder_g_per_100m': values['powder_g_per_100m'], 'supplies_cents': supplies_cents, 'parts_cents': parts_cents, 'supplies_per_metre_cents': values['supplies_per_metre_cents'], 'parts_per_metre_cents': values['parts_per_metre_cents'], 'total_per_metre_cents': values['total_per_metre_cents'], 'sold_cents': sold, 'contribution_cents': sold - supplies_cents - parts_cents, } def since_installation(c, machine, until): """{'from': date, 'contribution_cents', 'parts_cents', 'months': float, 'roi_pct': float|None, 'payback_months': float|None} from installed_on (else log_since) to `until`.""" mid = machine['id'] if machine['installed_on'] is not None: from_date = machine['installed_on'] start = datetime.combine(from_date, time.min, tzinfo=SAO_PAULO) else: start = machine['log_since'] or datetime.now(SAO_PAULO) from_date = start.astimezone(SAO_PAULO).date() sold = sum((_sold(row) for row in _printed_orders(c, mid, start, until)), 0) cents = lambda kind: int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents FROM dtf_local.machine_entries WHERE machine_id=%s AND kind=%s AND created_at>=%s AND created_at<%s''', (mid, kind, start, until)).fetchone()['cents']) supplies_cents, parts_cents = cents('supply'), cents('part') contribution = sold - supplies_cents - parts_cents seconds = (until - start).total_seconds() months = round(float(Decimal(str(seconds)) / _MONTH_SECONDS), 1) if seconds > 0 else 0.0 values = ratios(0, price_cents=machine['price_cents'], contribution_cents=contribution, installed_parts_cents=parts_cents, months=months) return {'from': from_date, 'contribution_cents': contribution, 'parts_cents': parts_cents, 'months': months, 'roi_pct': values['roi_pct'], 'payback_months': values['payback_months']} def report(c, month=None): """{'month': '2026-11', 'machines': [{'id', 'name', 'price_cents', 'installed_on', 'month': machine_month(...), 'total': since_installation(...)}]} for every machine (active or not) that has entries or printed in the month, plus every active one.""" start, end = month_bounds(month) until = min(datetime.now(SAO_PAULO), end) machines = c.execute('''SELECT id, name, price_cents, installed_on, log_since, active FROM dtf_local.machines ORDER BY created_at, name''').fetchall() entered = {str(row['machine_id']) for row in c.execute( '''SELECT DISTINCT machine_id FROM dtf_local.machine_entries WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()} printed = {str(row['machine_id']) for row in c.execute( f'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE} AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()} result = [] for machine in machines: key = str(machine['id']) if not (machine['active'] or key in entered or key in printed): continue result.append({'id': key, 'name': machine['name'], 'price_cents': machine['price_cents'], 'installed_on': machine['installed_on'], 'month': machine_month(c, machine, start, end), 'total': since_installation(c, machine, until)}) return {'month': start.strftime('%Y-%m'), 'machines': result}