Files
dtf-system/app/machines.py
Cauê Faleiros aaa6090642
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s
feat: places per machine, drops on Imprimindo go to your machine, a Venda carries its seller to Tiny (DTF-WEB-V)
Marcus, 2026-11-17:
- Each machine has its own places (machines.places, 1 to 6, three to
  start): orders at once in Imprimindo and files at once in its hot
  folder. Admin sets it in the machine dialog; Admin and Gestão in the
  machine sheet's Dados da máquina. A third order shows as "Na vez".
- Whoever is signed in on a machine drops a card anywhere in Imprimindo
  and it goes to that machine; without one, the lane under the pointer.
- Each Kanban user may name their Tiny seller (Usuários, read from
  Tiny's own list); a montador Venda reaches Tiny with the seller of who
  assembled it. Every other order still sends no seller.
- A folder download that never reached storage (a network drop) waits
  for the next pass as a warning and is reported only if it keeps
  failing (Sentry DTF-WEB-V).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 14:18:19 -03:00

91 lines
4.5 KiB
Python

"""The print machines, their load and the 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')
# Orders at most in Imprimindo per machine, and files in its hot folder at
# once: dtf_local.machines.places, set per machine by Admin and Gestão
# (Marcus, 2026-11-17). It was two for all (Dropstar, 2026-10-29): one
# printing, the next ripped by FlexiPRINT meanwhile; three keeps one more
# waiting in the folder. A new machine starts with DEFAULT_PLACES.
DEFAULT_PLACES = 3
MAX_PLACES = 6
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, places 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,
'places': m['places'],
'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):
"""(name, places) when the machine already has its places' worth of
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, places 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'], machine['places']) if machine and printing >= machine['places'] 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, 'aguardando'
for those after that, waiting in the hot folder."""
return {row['id']: {1: 'imprimindo', 2: 'ripando'}.get(row['place'], 'aguardando') 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()}