Files
dtf-system/app/machines.py
Cauê Faleiros 53c6234feb
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 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 59s
feat: machines share the work by metres open, with an optional limit, their load on show and operators set from the machine
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:13 -03:00

107 lines
5.2 KiB
Python

"""The print machines: which one each order goes to, and how loaded each is.
An order gets its machine once, and keeps it: someone's choice in the order
panel, or else the active machine that prints its product with the fewest
metres still open, among those below their limit (or, all of them full, the
least loaded anyway; the machine then shows it is over its limit). A machine
switched off, deleted or no longer printing the product gives its automatic
orders back to that choice, unless they are already printing.
"""
from decimal import Decimal
# Not finished: the work still ahead of a machine.
OPEN = ('rec', 'tra', 'fil', 'imp', 'cor')
# Stages an automatic order may still move from: not once it is printing.
MOVABLE = ('rec', 'tra', 'fil', 'cor')
# One routing at a time, so two at once cannot both pick the same "least loaded".
LOCK = 7_041_901
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 pick(machines, load, order):
"""The machine for one order, or None when none prints its product."""
family, metres = product_family(order), order_metres(order)
able = [m for m in machines if m['active'] and family in m['products']]
if not able:
return None
used = lambda m: load.get(str(m['id']), Decimal(0))
room = [m for m in able if m['limit_metres'] is None or used(m) + metres <= m['limit_metres']]
# min() keeps the first of equals: the machine registered first.
return min(room or able, key=used)
def route(c):
"""Give every open order without a machine its automatic one."""
# A choice whose machine was deleted is no choice any more.
c.execute('UPDATE dtf_local.orders SET machine_chosen=false WHERE machine_id IS NULL AND machine_chosen')
# Automatic orders on a machine that can no longer take them, before printing.
c.execute('''UPDATE dtf_local.orders o SET machine_id=NULL FROM dtf_local.machines m
WHERE o.machine_id=m.id AND NOT o.machine_chosen AND o.state=ANY(%s) AND o.cancelled_at IS NULL
AND (NOT m.active OR NOT ((CASE WHEN o.snapshot->'items'->0->>'mode' IN ('uv','uvfile')
THEN 'uv' ELSE 'textil' END)=ANY(m.products)))''', (list(MOVABLE),))
waiting = c.execute('''SELECT id, snapshot FROM dtf_local.orders
WHERE machine_id IS NULL AND cancelled_at IS NULL AND state=ANY(%s)
ORDER BY created_at, number''', (list(OPEN),)).fetchall()
if not waiting:
return 0
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
machines = c.execute('''SELECT id, products, active, limit_metres FROM dtf_local.machines
ORDER BY created_at, name''').fetchall()
load = {k: v['metres'] for k, v in loads(c).items()}
routed = 0
for order in waiting:
machine = pick(machines, load, order)
if machine is None:
continue
if c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false
WHERE id=%s AND machine_id IS NULL RETURNING id''', (machine['id'], order['id'])).fetchone():
key = str(machine['id'])
load[key] = load.get(key, Decimal(0)) + order_metres(order)
routed += 1
return routed
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:
for r in c.execute('''SELECT om.machine_id, o.id, o.name, o.email FROM dtf_local.operator_machines om
JOIN dtf_local.operators o ON o.id=om.operator_id ORDER BY o.name, o.email''').fetchall():
operators.setdefault(str(r['machine_id']), []).append({'id': str(r['id']), 'name': r['name'] or r['email']})
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']}
if with_operators:
row['operators'] = operators.get(key, [])
result.append(row)
return result