feat: machines share the work by metres open, with an optional limit, their load on show and operators set from the machine
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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-20 10:28:13 -03:00
parent df30046027
commit 53c6234feb
10 changed files with 380 additions and 81 deletions

View File

@@ -16,7 +16,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_
login_failed, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
from ..printjobs import queue as queue_print_files
from .. import cnpj, mail, payments, quote_review
from .. import cnpj, machines, mail, payments, quote_review
from .. import tiny
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
@@ -102,6 +102,8 @@ def backup_now(user=Depends(can('integrations'))):
@router.get('/api/operator/board')
def board(request: Request, user=Depends(operator)):
with db.connect() as c:
# Orders that arrived, or lost their machine, get one before the board is read.
machines.route(c)
# Everything still in progress, however old: an operator must never lose a
# card they can act on. Finished orders are terminal and only accumulate,
# so the board carries a recent window of them and reports the true total.
@@ -137,8 +139,7 @@ def board(request: Request, user=Depends(operator)):
'mail': mail.status(c)},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total,
'machines': [{**m, 'id': str(m['id'])} for m in c.execute(
'SELECT id,name,products,active FROM dtf_local.machines ORDER BY created_at,name').fetchall()],
'machines': machines.rows(c),
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total}
@@ -176,21 +177,14 @@ def company_names(c, *groups):
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
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 assign_machines(c, orders):
"""Each order's machine: the one someone chose, or else the first active
machine that prints its product. None while no machine is registered."""
machines = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY created_at,name').fetchall()
by_id = {str(m['id']): m for m in machines}
"""Each order's machine as stored (app/machines.py gives it): chosen by
someone, or automatic. None while no machine prints its product."""
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
for order in orders:
chosen = by_id.get(str(order.get('machine_id') or ''))
machine = chosen or next((m for m in machines if m['active'] and product_family(order) in m['products']), None)
order['machine'] = {'id': str(machine['id']), 'name': machine['name'], 'chosen': bool(chosen)} if machine else None
key = str(order.get('machine_id') or '')
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
if key in names else None)
return orders
@@ -524,10 +518,11 @@ def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('produce')))
with db.connect() as c:
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
row = c.execute('UPDATE dtf_local.orders SET machine_id=%s WHERE id=%s RETURNING number',
(body.machine_id, uid)).fetchone()
row = c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s RETURNING number',
(body.machine_id, body.machine_id is not None, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
machines.route(c)
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
return {'ok': True}

View File

@@ -6,13 +6,14 @@ administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident.
"""
import re
from decimal import Decimal
from typing import Literal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, field_validator
from .. import mail
from .. import machines, mail
from ..core import db
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
from ..core.models import StrictModel
@@ -41,6 +42,10 @@ class MachineIn(StrictModel):
name: str = Field(min_length=1, max_length=60)
products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2)
active: bool = True
# Metres open before the next order goes to another machine; None is no limit.
limit_metres: Decimal | None = Field(default=None, gt=0, le=99999, decimal_places=1)
# The operators who work on it; None leaves them as they are.
operators: list[UUID] | None = Field(default=None, max_length=200)
class PasswordChange(StrictModel):
@@ -82,7 +87,7 @@ def user_rows(c):
@router.get('/api/operator/users')
def list_users(user=Depends(can('users'))):
with db.connect() as c:
return {'users': user_rows(c), 'machines': machine_rows(c)}
return {'users': user_rows(c), 'machines': machines.rows(c, with_operators=True)}
def target(c, uid, request):
@@ -95,10 +100,14 @@ def target(c, uid, request):
return row
def set_machines(c, uid, machines):
def set_machines(c, uid, chosen, role):
"""An operator's machines. Only operators have them: they limit what an
operator sees, and every other profile sees every order."""
if role != 'operador':
chosen = []
known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)',
([str(m) for m in machines],)).fetchall()}
if len(known) != len(set(map(str, machines))):
([str(m) for m in chosen],)).fetchall()}
if len(known) != len(set(map(str, chosen))):
raise HTTPException(422, 'Uma das máquinas escolhidas não existe mais.')
c.execute('DELETE FROM dtf_local.operator_machines WHERE operator_id=%s', (uid,))
for machine in known:
@@ -116,7 +125,7 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active))
set_machines(c, uid, body.machines)
set_machines(c, uid, body.machines, body.role)
audit('operator_created', operator=user, account=body.email, role=body.role)
return {'id': str(uid)}
@@ -142,7 +151,7 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
if not body.active or body.password:
# Disabled, or given a new password: whoever was signed in signs in again.
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
set_machines(c, uid, body.machines)
set_machines(c, uid, body.machines, role)
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
password_reset=bool(body.password))
return {'ok': True}
@@ -161,17 +170,20 @@ def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
return {'ok': True}
def machine_rows(c):
rows = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY active DESC, name').fetchall()
for row in rows:
row['id'] = str(row['id'])
return rows
def set_operators(c, mid, operators):
"""The machine's operators, from its own form. Other profiles are ignored."""
if operators is None:
return
ids = [str(o) for o in operators]
c.execute('DELETE FROM dtf_local.operator_machines WHERE machine_id=%s', (mid,))
c.execute("""INSERT INTO dtf_local.operator_machines(operator_id,machine_id)
SELECT id,%s FROM dtf_local.operators WHERE id=ANY(%s::uuid[]) AND role='operador'""", (mid, ids))
@router.get('/api/operator/machines')
def list_machines(user=Depends(can('view'))):
with db.connect() as c:
return {'machines': machine_rows(c)}
return {'machines': machines.rows(c, with_operators=True)}
@router.post('/api/operator/machines')
@@ -180,8 +192,10 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('INSERT INTO dtf_local.machines(id,name,products,active) VALUES(%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active))
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
set_operators(c, mid, body.operators)
machines.route(c)
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@@ -192,9 +206,12 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
(body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
if not c.execute('UPDATE dtf_local.machines SET name=%s,products=%s,active=%s WHERE id=%s RETURNING id',
(body.name.strip(), sorted(set(body.products)), body.active, mid)).fetchone():
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, mid)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
set_operators(c, mid, body.operators)
machines.route(c)
audit('machine_updated', operator=user, machine=body.name)
return {'ok': True}
@@ -206,6 +223,7 @@ def delete_machine(mid: UUID, user=Depends(can('users'))):
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
machines.route(c)
audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True}

106
app/machines.py Normal file
View File

@@ -0,0 +1,106 @@
"""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

View File

@@ -16,7 +16,7 @@ from uuid import UUID, uuid4
from psycopg.types.json import Jsonb
from . import mail
from . import machines, mail
from .core.auth import audit
from .printjobs import queue as queue_print_files
from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
@@ -97,6 +97,7 @@ def create_order(c, quote, payment):
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)
WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
queue_print_files(c, order['id'], len(approved['items']))
machines.route(c)
if is_test(order):
return order, True
mail.order_paid(c, order, PUBLIC_ORIGIN)

View File

@@ -253,13 +253,25 @@ DO $$ BEGIN
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','operador','vendedor'));
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
-- The print machines, and which products each prints. An order goes to the
-- first active machine that prints its product unless someone chooses one.
-- The print machines, and which products each prints. An order keeps the
-- machine someone chose (machine_chosen) or the one given automatically: the
-- active machine of its product with the fewest metres open (app/machines.py).
-- limit_metres: the metres open a machine takes before the next order goes to
-- another one; NULL is no limit.
CREATE TABLE IF NOT EXISTS dtf_local.machines (
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS limit_metres numeric(8,1) CHECK (limit_metres > 0);
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_chosen boolean NOT NULL DEFAULT false;
-- Until now only a person's choice was stored.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-chosen-v1') THEN
UPDATE dtf_local.orders SET machine_chosen=true WHERE machine_id IS NOT NULL;
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
END IF;
END $$;
-- The machines an operator works on; none means every machine.
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,