"""Each machine's sheet: supplies, parts, events, counters and alerts (Fase 2, front 1, part a; the Números block per machine is part b). The room enters what goes into a machine with one click on its card: a supply (film roll, ink by colour, powder) with its quantity and lot cost, a part (cap, damper, head, wiper, other) with its cost and serial, or an event (cleaned, aligned the head, a stop with its reason and minutes). The Kanban already knows what each machine printed; with what goes in, it knows what it uses. Alerts appear on the machine's computer between one file and the next, never in the middle: when someone on that machine pulls the next card into Imprimindo. They are marked done (which records the event) or postponed once, which lets exactly one more card through. clean CLEAN_EVERY_METRES printed since the last "clean" event. align ALIGN_AFTER_FILM_METRES printed since the last film change (a supply entry of "film") with no "align" event after it. supply a supply whose estimated stock is at or below the machine's minimum: the one Gestão typed, or Dropstar's default for that supply (1 roll of film, 1 L of each ink, 5 kg of powder). The supply estimate assumes each entry refills what was used since the one before: the use per metre is the quantity entered over the metres printed in that interval, averaged over the last SUPPLY_INTERVALS intervals; the stock is the average refill minus that use times the metres printed since the last entry. Fewer than two entries, no estimate. "Printed" is what left Imprimindo for Revisão on the machine (orders.machine_id, the movement imp -> rev not back): the film metres of the items (COALESCE(metres, billed_metres)), and for a proof card the length of each proof sheet (film_metres). """ from datetime import datetime, timezone from decimal import Decimal CLEAN_EVERY_METRES = Decimal('10') ALIGN_AFTER_FILM_METRES = Decimal('20') SUPPLY_INTERVALS = 3 # item -> (Portuguese label, unit shown). Supplies are counted in rolls, # litres and kilograms; Números shows ink per 100 m and powder in grams. SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'), 'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'), 'powder': ('Poliamida', 'kg')} # Dropstar's fixed minimums (2026-11-10): a machine with no minimum typed uses # these. Units match the supplies: rolls, litres and kilograms. DEFAULT_MINIMUMS = {'film': Decimal('1'), 'ink_c': Decimal('1'), 'ink_m': Decimal('1'), 'ink_y': Decimal('1'), 'ink_k': Decimal('1'), 'ink_w': Decimal('1'), 'powder': Decimal('5')} PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'} EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'} # A cycle with no resetting event still needs a value the snooze row can key on. _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) def one_decimal(value): """One decimal place with the Brazilian comma, as the alert lines show it.""" return f'{Decimal(str(value)):.1f}'.replace('.', ',') # A pass to Revisão undone at once (a mistaken move, back to Imprimindo): # the pass after the undo counts the film, so this one must not, or the # machine's metres count it twice. `m` is the pass in dtf_local.movements. NOT_UNDONE = """NOT EXISTS (SELECT 1 FROM dtf_local.movements u WHERE u.order_id=m.order_id AND u.back AND u.from_state='rev' AND u.to_state='imp' AND u.id=(SELECT min(n.id) FROM dtf_local.movements n WHERE n.order_id=m.order_id AND n.id>m.id))""" # Each proof sheet's stretches of film, {item index: [[top, bottom], ...]}, # from its print file (app/printpng.py); `o` is the order. PROOF_WINDOWS = """(SELECT jsonb_object_agg(p.item_index::text, p.detail->'proof_windows') FROM dtf_local.print_files p WHERE p.order_id=o.id AND p.detail ? 'proof_windows') AS windows""" def film_metres(snapshot, items=None, windows=None): """The film one pass to Revisão printed, in metres, as Decimal: each item's metres, on a reprint only the `items` that went again (#105). A proof card's item is its sheet: the finest stroke's window and the colour samples with the clear film between them, up to 30 cm (Marcus, 2026-11-26), from `windows` ({item index: [[top, bottom], ...]} in cm); PROOF_SHEET_CM for a sheet made before the samples.""" from .printpng import PROOF_GAP_CM 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: stretches = (windows or {}).get(str(index)) or [] cm = (sum((Decimal(str(b)) - Decimal(str(a)) for a, b in stretches), Decimal(0)) + PROOF_GAP_CM * (len(stretches) - 1)) if stretches else PROOF_SHEET_CM total += cm / 100 else: value = item.get('metres') if value is None: value = item.get('billed_metres') total += Decimal(str(value or 0)) return total def printed_since(c, machine_id, since): """Film metres the machine printed after `since` (None: ever), as Decimal.""" rows = c.execute(f'''SELECT o.snapshot, m.items, {PROOF_WINDOWS} 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 (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''', (machine_id, since, since)).fetchall() return sum((film_metres(row['snapshot'], row.get('items'), row.get('windows')) for row in rows), Decimal(0)) def _last_entry(c, machine_id, kind, item): return c.execute('''SELECT * FROM dtf_local.machine_entries WHERE machine_id=%s AND kind=%s AND item=%s ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, kind, item)).fetchone() def counters(c, machine_id): """{'clean': {'metres': Decimal, 'since': datetime|None}, 'film': {'metres': Decimal, 'since': datetime|None, 'aligned': bool}}""" clean = _last_entry(c, machine_id, 'event', 'clean') film = _last_entry(c, machine_id, 'supply', 'film') clean_since = clean['created_at'] if clean else None # No cleaning on record yet: count from when the sheet started, or every # machine would ask for one on the day this went live. start = c.execute('SELECT log_since FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone() film_since = film['created_at'] if film else None aligned = False if film: aligned = c.execute('''SELECT 1 FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='event' AND item='align' AND created_at>=%s LIMIT 1''', (machine_id, film_since)).fetchone() is not None return {'clean': {'metres': printed_since(c, machine_id, clean_since or (start or {}).get('log_since')), 'since': clean_since}, 'film': {'metres': printed_since(c, machine_id, film_since or (start or {}).get('log_since')), 'since': film_since, 'aligned': aligned}} def estimate(entries, metres_between, metres_since_last, minimum=None): """The supply estimate from simple lists, so it is tested without a database. `entries` are the quantities entered, oldest first; `metres_between[i]` is the film printed between entry i and entry i+1; `metres_since_last` is the film printed since the last entry. None with fewer than two entries or when no interval had film printed (nothing to divide by). """ quantities = [Decimal(str(value)) for value in entries] if len(quantities) < 2: return None uses, refills = [], [] for quantity, metres in list(zip(quantities[1:], metres_between))[-SUPPLY_INTERVALS:]: metres = Decimal(str(metres)) if metres <= 0: continue uses.append(quantity / metres) refills.append(quantity) if not uses: return None per_metre = sum(uses, Decimal(0)) / len(uses) refill = sum(refills, Decimal(0)) / len(refills) stock = refill - per_metre * Decimal(str(metres_since_last)) return {'per_metre': per_metre, 'stock': stock, 'metres_left': stock / per_metre, 'minimum': minimum} def minimum_for(minimums, item): """The minimum typed for the machine, or Dropstar's default for that supply.""" return minimums.get(item, DEFAULT_MINIMUMS.get(item)) def supply_low(value): """Whether an estimate is at or below the machine's minimum (typed or default).""" return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum'] def supply_estimates(c, machine_id): """{item: {'per_metre': Decimal, 'stock': Decimal, 'metres_left': Decimal, 'minimum': Decimal|None}} for the supplies with an estimate (see module doc).""" minimums = {row['item']: row['minimum'] for row in c.execute( 'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (machine_id,)).fetchall()} result = {} for item in SUPPLIES: # Only the entries the estimate uses: the board asks for it on every refresh. rows = c.execute('''SELECT quantity, created_at FROM (SELECT quantity, created_at, id FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='supply' AND item=%s ORDER BY created_at DESC, id DESC LIMIT %s) last ORDER BY created_at, id''', (machine_id, item, SUPPLY_INTERVALS + 1)).fetchall() if len(rows) < 2: continue printed = [printed_since(c, machine_id, row['created_at']) for row in rows] between = [printed[index - 1] - printed[index] for index in range(1, len(printed))] value = estimate([row['quantity'] for row in rows], between, printed[-1], minimum_for(minimums, item)) if value is not None: result[item] = value return result def alerts(c, machine_id): """The alerts due on this machine now, each {'key': 'clean' | 'align' | 'supply:', 'text': Portuguese line, 'cycle_from': datetime|None, 'snoozable': bool, 'blocking': bool}. blocking is False when it was postponed this cycle and no card was pulled on the machine since. Texts, with metres in one decimal and a comma: clean ": 10,4 m desde a última limpeza — limpe antes do próximo arquivo" align ": 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo" supply "