"""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', 'imp', 'cor') # Stages an automatic order may still move from: not once it is printing. MOVABLE = ('rec', 'tra', 'cor') # One routing at a time, so two at once cannot both pick the same "least loaded". LOCK = 7_041_901 # 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 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 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()}