Files
dtf-system/app/machine_log.py
Cauê Faleiros b8496b858f
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 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s
feat: a reprint sends only the items chosen to the machine (Marcus, 2026-11-26, #105)
An order the machine already printed, back in Arte conferida, sends again
only the items whose final changed since the machine took them; the panel's
"Vai para a máquina" shows and changes the choice, and the card says
"Reimpressão". The order stays one card. The pass to Revisão keeps the
items printed, so the machine's metres count only those.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 10:00:54 -03:00

266 lines
13 KiB
Python

"""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 PROOF_SHEET_CM per item for a proof card.
"""
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('.', ',')
def printed_since(c, machine_id, since):
"""Film metres the machine printed after `since` (None: ever), as Decimal."""
from .proof import PROOF_SHEET_CM
rows = c.execute('''SELECT o.snapshot, 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 (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
(machine_id, since, since)).fetchall()
total = Decimal(0)
for row in rows:
snapshot = row['snapshot'] or {}
proof = bool(snapshot.get('proof_of'))
for index, item in enumerate(snapshot.get('items') or []):
# A reprint counts only the items that went again (#105).
if row.get('items') is not None and index not in row['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 _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:<item>', '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 "<máquina>: 10,4 m desde a última limpeza — limpe antes do próximo arquivo"
align "<máquina>: 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo"
supply "<label minúsculo> da <máquina> deve acabar em ~3 m" (e.g. "tinta branca da máquina2 deve acabar em ~3,0 m")
"""
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone()
if not machine:
return []
name = machine['name']
counts = counters(c, machine_id)
supplies = supply_estimates(c, machine_id)
result = []
def postponed(key, cycle):
return c.execute('''SELECT snoozed_at FROM dtf_local.machine_snoozes
WHERE machine_id=%s AND alert=%s AND cycle_from=%s''',
(machine_id, key, cycle or _EPOCH)).fetchone()
def pulled_since(moment):
return c.execute('''SELECT 1 FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.to_state='imp' AND NOT m.back AND m.created_at>%s LIMIT 1''',
(machine_id, moment)).fetchone() is not None
def due(key, text, cycle):
snooze = postponed(key, cycle)
blocking = not (snooze and not pulled_since(snooze['snoozed_at']))
result.append({'key': key, 'text': text, 'cycle_from': cycle,
'snoozable': snooze is None, 'blocking': blocking})
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
'— limpe antes do próximo arquivo', counts['clean']['since'])
if (counts['film']['since'] is not None and not counts['film']['aligned']
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
'— alinhe a cabeça antes do próximo', counts['film']['since'])
for item, value in supplies.items():
if not supply_low(value):
continue
last = _last_entry(c, machine_id, 'supply', item)
due('supply:' + item, f"{SUPPLIES[item][0].lower()} da {name} deve acabar em "
f"~{one_decimal(value['metres_left'])} m", last['created_at'] if last else None)
return result
def _field(body, name, default=None):
return body.get(name, default) if isinstance(body, dict) else getattr(body, name, default)
def add_entry(c, machine_id, body, user, from_alert=False):
"""Record one entry. A supply without cost takes the cost of that item's
last entry on the machine. Returns the row."""
kind = _field(body, 'kind')
item = _field(body, 'item')
cost = _field(body, 'cost_cents')
if kind == 'supply' and cost is None:
last = c.execute('''SELECT cost_cents FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind='supply' AND item=%s AND cost_cents IS NOT NULL
ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, item)).fetchone()
if last:
cost = last['cost_cents']
quantity = _field(body, 'quantity') if kind == 'supply' else None
stop_minutes = _field(body, 'stop_minutes') if kind == 'event' and item == 'stop' else None
return c.execute('''INSERT INTO dtf_local.machine_entries
(machine_id,kind,item,quantity,cost_cents,serial,note,stop_minutes,from_alert,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(machine_id, kind, item, quantity, cost if kind in ('supply', 'part') else None,
_field(body, 'serial') if kind == 'part' else None, _field(body, 'note'),
stop_minutes, from_alert, user)).fetchone()
def snooze(c, machine_id, key, user):
"""Postpone an alert once per cycle; a second time in the same cycle is 409."""
from fastapi import HTTPException
current = next((alert for alert in alerts(c, machine_id) if alert['key'] == key), None)
if current is None:
raise HTTPException(409, 'Este aviso não está pendente.')
if not current['snoozable']:
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
row = c.execute('''INSERT INTO dtf_local.machine_snoozes(machine_id,alert,cycle_from,snoozed_by)
VALUES(%s,%s,%s,%s) ON CONFLICT (machine_id,alert,cycle_from) DO NOTHING RETURNING *''',
(machine_id, key, current['cycle_from'] or _EPOCH, user)).fetchone()
if not row:
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
return row