Files
dtf-system/app/machines.py
Cauê Faleiros 29518795a5
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m20s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m11s
feat: each machine's sheet, counters and alerts (front 1a)
The machine's name in Imprimindo (and "Ficha" in Usuários › Máquinas)
opens its sheet: metres since the last cleaning and since the last film
change, each supply's estimate, pending alerts and the entries. The room
enters supplies (film, ink by colour, powder; a supply without cost
takes the last one), parts (cap, damper, head, wiper, other) and events
(cleaning, head alignment, a stop with reason and minutes). Gestão types
the price, installation date and supply minimums.

Alerts appear when someone pulls the next card onto the machine, never
mid-print: 10 m since the last cleaning, 20 m after a film change
without aligning the head, and a supply at its minimum. Marked done it
records the event; postponed once it lets one more card through. The
server refuses the pull otherwise. Counters start when the sheet went
live (machines.log_since), not from everything printed before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:19:31 -03:00

86 lines
4.2 KiB
Python

"""The print machines, their load and the two printing places on each one."""
from decimal import Decimal
from . import machine_log
# Not finished: the work still ahead of a machine.
OPEN = ('rec', 'tra', 'imp', 'cor')
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
# make the RIP choke; two mean the next sheet is ready when one ends.
PRINTING_CAP = 2
def product_family(order):
"""Têxtil or UV, by the order's first item: what a machine prints."""
items = (order.get('snapshot') or {}).get('items') or [{}]
return 'uv' if items[0].get('mode') in ('uvfile', 'uv') else 'textil'
def order_metres(order):
return sum((Decimal(str(i.get('billed_metres') or 0)) for i in (order.get('snapshot') or {}).get('items') or []),
Decimal(0))
def loads(c):
"""Per machine id: metres and orders still open, and orders per stage."""
result = {}
for row in c.execute('''SELECT machine_id, state, snapshot FROM dtf_local.orders
WHERE machine_id IS NOT NULL AND cancelled_at IS NULL AND state=ANY(%s)''', (list(OPEN),)).fetchall():
load = result.setdefault(str(row['machine_id']), {'metres': Decimal(0), 'orders': 0, 'states': {}})
load['metres'] += order_metres(row)
load['orders'] += 1
load['states'][row['state']] = load['states'].get(row['state'], 0) + 1
return result
def rows(c, with_operators=False):
"""Every machine with its load, for the Kanban."""
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
ORDER BY created_at, name''').fetchall()
load = loads(c)
operators = {}
if with_operators:
# Who is on it now: the open sessions that chose it (item 12).
for r in c.execute('''SELECT DISTINCT ON (s.machine_id, o.id) s.machine_id, o.id, o.name, o.email, s.machine_at
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
WHERE s.machine_id IS NOT NULL AND s.expires_at>now()
ORDER BY s.machine_id, o.id, s.machine_at''').fetchall():
operators.setdefault(str(r['machine_id']), []).append(
{'id': str(r['id']), 'name': r['name'] or r['email'], 'since': r['machine_at']})
result = []
for m in machines:
key = str(m['id'])
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'],
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
'alerts': machine_log.alerts(c, m['id'])}
if with_operators:
row['operators'] = operators.get(key, [])
result.append(row)
return result
def full(c, machine_id, order_id):
"""The machine's name when it already has PRINTING_CAP other orders in
Imprimindo, so this one cannot join them; None when it has room. The
machine's row is locked, so two pulls at once cannot both take the last
place."""
if machine_id is None:
return None
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
return machine['name'] if machine and printing >= PRINTING_CAP else None
def printing_slots(c):
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
machine (ripped, running), 'ripando' for the one after it."""
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
WHERE order_id=o.id AND to_state='imp') m
WHERE o.state='imp' AND o.cancelled_at IS NULL AND o.machine_id IS NOT NULL''').fetchall()}