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,

View File

@@ -328,6 +328,15 @@ details and the Tiny log there (`integrations` capability, app/core/auth.py).
Admins and gestão see each integration's state and summary; anyone who
produces also gets the folder's row with its buttons.
Machines (2026-10-20, app/machines.py): each order keeps one machine, either
chosen in the order panel or given on arrival: the active machine of its
product with the fewest metres open (rec, tra, fil, imp, cor), preferring
those below their optional limit in metres, else the least loaded anyway (the
Usuários page shows it over the limit). A machine switched off, deleted or no
longer printing the product hands its automatic orders, not yet printing, to
that choice again. Only operators are linked to machines (from the user or
the machine form); a linked operator sees only those machines' orders.
### Active localhost milestone (2026-09-15)
The current implementation target is localhost before any production connection.

View File

@@ -3,10 +3,12 @@
Run inside the API container: python -m tests.users_test
"""
import secrets
from decimal import Decimal
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import machines as routing
from app.core import db
from tests.smoke_test import Client
@@ -20,14 +22,54 @@ def signed_in(email, password=PASSWORD):
return client
def order_fixture(c, owner, mode, metres='1'):
"""A paid order straight in the database, as the payment would leave it."""
quote, order = uuid4(), uuid4()
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
'items': [{'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': 1490,
'uploads': []}], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
(order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': str(order)})))
return quote, order
def expected_machine(su, product, metres=1.0):
"""What app/machines.py should pick now: the active machine of the product
with the fewest metres open, among those with room, else among all."""
# Listed in the order they were registered: min() keeps the first of equals, as the routing does.
rows = [m for m in su.call('/operator/machines', operator=True)['machines'] if m['active'] and product in m['products']]
room = [m for m in rows if m['limit_metres'] is None or m['open_metres'] + metres <= m['limit_metres']]
return min(room or rows, key=lambda m: m['open_metres'])['id']
def picking():
"""The choice itself: room first, then the fewest metres, then the first registered."""
textil = {'snapshot': {'items': [{'mode': 'file', 'billed_metres': '1'}]}}
uv = {'snapshot': {'items': [{'mode': 'uvfile', 'billed_metres': '1'}]}}
a = {'id': 'a', 'products': ['textil'], 'active': True, 'limit_metres': Decimal('2')}
b = {'id': 'b', 'products': ['textil'], 'active': True, 'limit_metres': None}
off = {'id': 'off', 'products': ['textil'], 'active': False, 'limit_metres': None}
assert routing.pick([a, b], {}, textil)['id'] == 'a'
assert routing.pick([off, a, b], {'a': Decimal('0.5')}, textil)['id'] == 'b'
# Full: the one with room takes it, even with more metres open.
assert routing.pick([a, b], {'a': Decimal('1.5'), 'b': Decimal('9')}, textil)['id'] == 'b'
# All full: the least loaded anyway.
b_full = {**b, 'limit_metres': Decimal('3')}
assert routing.pick([a, b_full], {'a': Decimal('5'), 'b': Decimal('4')}, textil)['id'] == 'b'
assert routing.pick([a, b], {}, uv) is None
def run():
picking()
tag = secrets.token_hex(3)
su = Client()
su.call('/session')
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor')}
owner, textil_q, uv_q, textil_o, uv_o = uuid4(), uuid4(), uuid4(), uuid4(), uuid4()
machines = []
owner = uuid4()
machines, made = [], []
try:
# Machines, then an administrator who creates the rest of the team.
textil = su.call('/operator/machines', {'name': f'Têxtil {tag}', 'products': ['textil']}, operator=True)['id']
@@ -63,18 +105,19 @@ def run():
expected=409)
admin.call(f"/operator/users/{mine['id']}/delete", {}, expected=409)
# Two paid orders: Têxtil goes to the Têxtil machine, UV to the UV one.
# Orders other suites left open get their machines first; then each paid
# order goes to the machine of its product with the fewest metres open.
su.call('/operator/board', operator=True)
want = {'textil': expected_machine(su, 'textil'), 'uv': expected_machine(su, 'uv')}
with db.connect() as c:
for quote, order, mode in ((textil_q, textil_o, 'file'), (uv_q, uv_o, 'uvfile')):
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
'items': [{'mode': mode, 'grade': 100, 'billed_metres': '1', 'unit_cents': 1490,
'uploads': []}], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
(order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': tag})))
textil_q, textil_o = order_fixture(c, owner, 'file')
uv_q, uv_o = order_fixture(c, owner, 'uvfile')
made += [(textil_q, textil_o), (uv_q, uv_o)]
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(textil_o)]['machine']['id'] == textil and board[str(uv_o)]['machine']['id'] == uv
assert board[str(textil_o)]['machine']['id'] == want['textil'] and not board[str(textil_o)]['machine']['chosen']
assert board[str(uv_o)]['machine']['id'] == want['uv'] and not board[str(uv_o)]['machine']['chosen']
# On the UV machine of this test, whatever the others carry.
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
# The operator of the UV machine sees only its orders, moves them, and nothing more.
op = signed_in(emails['operador'])
@@ -106,6 +149,55 @@ def run():
seller.call('/operator/me/password', {'current': 'oito-888', 'new': 'outra-senha-de-teste'})
signed_in(emails['vendedor'], 'outra-senha-de-teste').call('/operator/me')
# A second Têxtil machine, its operators ticked on the machine itself: only
# operators are linked, the seller is not.
op_id, seller_id = users[emails['operador']]['id'], users[emails['vendedor']]['id']
textil2 = admin.call('/operator/machines', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'operators': [op_id, seller_id]})['id']
machines.append(textil2)
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
assert set(next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines']) == {uv, textil2}
# The next order goes to the one with fewer metres open.
target = expected_machine(su, 'textil')
with db.connect() as c:
made.append(order_fixture(c, owner, 'file'))
second = str(made[-1][1])
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] == target
# Chosen by hand, the order stays there; back to automatic, it is routed again.
su.call(f'/operator/orders/{second}/machine', {'machine_id': textil2}, operator=True)
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
assert listed[textil2]['open_orders'] >= 1 and listed[textil2]['states'].get('rec', 0) >= 1
# A limit: once full, the next order goes to a machine with room.
open_now = listed[textil2]['open_metres']
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'limit_metres': round(open_now + 0.5, 1)})
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
assert listed[textil2]['limit_metres'] == round(open_now + 0.5, 1)
# Left out, the operators stay as they were.
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
target = expected_machine(su, 'textil')
assert target != textil2
with db.connect() as c:
made.append(order_fixture(c, owner, 'file'))
third = str(made[-1][1])
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[third]['machine']['id'] == target
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'limit_metres': 0}, expected=422)
su.call(f'/operator/orders/{second}/machine', {'machine_id': None}, operator=True)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert not board[second]['machine']['chosen']
# Switched off, a machine gives its automatic orders to another one.
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'], 'active': False})
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] not in (None, textil2)
# Disabled, the operator is out at once; deleted, the account is gone.
op_row = users[emails['operador']]
admin.call(f"/operator/users/{op_row['id']}", {'name': 'Op', 'email': emails['operador'], 'role': 'operador',
@@ -117,17 +209,18 @@ def run():
su.call(f'/operator/machines/{uv}/delete', {}, operator=True)
machines.remove(uv)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(textil_o)]['machine']['id'] == textil
back = board[str(textil_o)]['machine']
assert back and back['id'] != uv and not back['chosen']
print('PASS: profiles limit actions, admins manage users but not the superadmin or themselves, '
'machines route orders and limit what their operators see')
'machines take orders by load and limit, keep a choice, and limit what their operators see')
finally:
with db.connect() as c:
for oid in (textil_o, uv_o):
for _, oid in made:
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{oid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([textil_q, uv_q],))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([q for q, _ in made],))
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.machines WHERE id=ANY(%s::uuid[])', (machines,))

View File

@@ -466,6 +466,31 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
.danger-text{color:var(--bad)}
.machine-select{height:36px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px}
.card .machine{color:var(--accent-tx)}
.chip.over{border-color:var(--bad-line);color:var(--bad)}
/* Chips that are checkboxes: products, machines, operators. */
.pills{display:flex;flex-wrap:wrap;gap:8px}
.pill{position:relative;display:inline-flex;align-items:center;height:34px;padding:0 12px;border-radius:8px;border:1px solid var(--line2);color:var(--muted);font-size:14px;font-weight:600;cursor:pointer;user-select:none}
.pill input{position:absolute;opacity:0;width:1px;height:1px;margin:0}
.pill:has(input:checked){border-color:var(--accent);background:rgba(255,139,43,.12);color:var(--accent-tx)}
.pill:has(input:focus-visible){outline:2px solid var(--accent);outline-offset:2px}
.unit{display:flex;align-items:center;gap:10px}
.unit input{flex:1;min-width:0}
.unit span{font-weight:500}
/* Machines: one card each, with the metres open against its limit. */
.mtiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(280px,100%),1fr));gap:12px}
.mtile{display:flex;flex-direction:column;gap:8px;padding:16px 18px;border:1px solid var(--line2);border-radius:12px;background:var(--card)}
.mtile.off{opacity:.6}
.mtile-head{display:flex;align-items:center;gap:10px}
.mtile-head b{font-size:15.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.mtile-head .integ-state{margin-left:auto}
.mtile .meta{font-size:13.5px;color:var(--muted)}
.mbar{height:8px;border-radius:999px;background:var(--line2);overflow:hidden;margin-top:4px}
.mbar span{display:block;height:100%;border-radius:inherit;background:var(--ok)}
.mbar.full span{background:var(--warn)}
.mbar.over span{background:var(--bad)}
.mload{display:flex;justify-content:space-between;gap:8px;font-size:13.5px;color:var(--tx2)}
.mload.over{color:var(--bad);font-weight:600}
.mtile-actions{display:flex;justify-content:flex-end;gap:6px;margin-top:4px}
/* Fila de impressão's tools: Baixar. */
.coltools{display:flex;gap:6px;flex-shrink:0}

View File

@@ -91,9 +91,8 @@
Gestão: tudo, menos usuários. Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquinas</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
<p class="faint stats-note">Cada pedido vai para a primeira máquina ativa que imprime o produto dele; no pedido dá para escolher outra.
Um operador ligado a máquinas vê só os pedidos delas.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Produtos</th><th scope="col">Situação</th><th scope="col"></th></tr></thead><tbody id="machines-list"></tbody></table></section>
<p class="faint stats-note">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
<div class="mtiles" id="machines-list"></div>
</section>
<section id="tab-integrations" class="page" hidden>
<h1>Integrações</h1>

View File

@@ -557,6 +557,7 @@ function matchesFilter(order,key){
if(key==='cancelados')return !!order.cancelled_at;
if(order.cancelled_at)return false;
const modes=order.snapshot.items.map(i=>i.mode);
if(key.startsWith('m:'))return order.machine?.id===key.slice(2);
if(key==='textil')return modes.some(m=>m==='file'||m==='avulsa');
if(key==='uv')return modes.some(m=>m==='uvfile'||m==='uv');
if(key==='entrega')return !!order.snapshot.destination;
@@ -573,10 +574,16 @@ function renderBoard(){
['parados','Parados'],['contato','Aguardando contato'],['manual','Preparar à mão'],['cancelados','Cancelados']];
// Each chip says how many orders in progress it would show.
const inProgress=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at);
// One chip per machine, when there is more than one to tell apart.
const machineChips=(board.machines||[]).filter(m=>m.active||m.open_orders);
if(machineChips.length>1)filters.splice(3,0,...machineChips.map(m=>['m:'+m.id,m.name]));
if(!filters.some(([key])=>key===filter))filter='all';
$('filters').replaceChildren(...filters.map(([key,label])=>{
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(filter===key));
b.append(node('span',String((key==='cancelados'?board.orders:inProgress).filter(o=>matchesFilter(o,key)).length),'chip-n'));
if(key==='parados')b.title='Sem mudar de etapa há mais de '+LATE_HOURS+' h';
if(key.startsWith('m:')){const m=board.machines.find(x=>'m:'+x.id===key);b.title=machineLoad(m);
if(m.limit_metres&&m.open_metres>m.limit_metres)b.classList.add('over');}
b.onclick=()=>{filter=key;renderBoard();};return b;}));
const active=board.orders.filter(o=>['rec','tra','fil','imp'].includes(o.state));
const queued=active.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
@@ -1076,16 +1083,31 @@ function machineCard(order){
}
const select=node('select',undefined,'machine-select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Automática'+(current&&!current.chosen?' ('+current.name+')':''));auto.value='';select.append(auto);
for(const m of board.machines.filter(m=>m.active||m.id===current?.id)){
const o=node('option',m.name);o.value=m.id;select.append(o);
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
const o=node('option',m.name+' · '+machineLoad(m));o.value=m.id;select.append(o);
}
select.value=current?.chosen?current.id:'';
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'Máquina automática pelo produto.');await load();}
catch(e){say(e.message,true);}};
box.append(select,node('span',current?.chosen?'Escolhida para este pedido.':'Pelo produto do pedido.','faint'));
box.append(select,node('span',current?.chosen?'Escolhida para este pedido.':current?'Escolhida automaticamente quando o pedido chegou.':'Nenhuma máquina imprime este produto.','faint'));
return box;
}
// "120,00 m de 300,00 m" or "120,00 m em aberto".
function machineLoad(m){
return m.limit_metres?metres(m.open_metres)+' de '+metres(m.limit_metres):metres(m.open_metres)+' em aberto';
}
// Checkboxes drawn as chips; .values() is what is ticked.
function pills(options,selected){
const box=node('div',undefined,'pills');
const inputs=options.map(([value,label])=>{const c=node('input');c.type='checkbox';c.value=value;c.checked=selected.includes(value);
const pill=node('label',undefined,'pill');pill.append(c,node('span',label));box.append(pill);return c;});
box.values=()=>inputs.filter(c=>c.checked).map(c=>c.value);
return box;
}
// A dialog field that is a group (chips, a list) rather than one input.
function group(label,...content){const g=node('div',undefined,'mfield');g.append(node('span',label),...content);return g;}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
let usersData=null;
async function loadUsers(){
@@ -1109,15 +1131,31 @@ function renderUsers(){
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':' · desativado')),machinesTd,seen,actions);return tr;
});
$('users-list').replaceChildren(...rows);
$('machines-list').replaceChildren(...(machines.length?machines.map(m=>{
const tr=node('tr');if(!m.active)tr.classList.add('off');
const actions=node('td',undefined,'actions');
actions.append(button('Editar',()=>machineForm(m),'btn ghost small'),button('Excluir',async()=>{
if(!window.confirm('Excluir a máquina '+m.name+'? Os pedidos dela voltam para a escolha automática.'))return;
await api('/machines/'+m.id+'/delete',{});say('Máquina excluída.');await loadUsers();await load();},'btn ghost small danger-text'));
tr.append(node('td',m.name),node('td',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto'),
node('td',m.active?'Ativa':'Desativada'),actions);return tr;
}):[(()=>{const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada. Sem máquinas, todos os pedidos aparecem para todos.','faint');td.colSpan=4;tr.append(td);return tr;})()]));
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
:[node('p','Nenhuma máquina cadastrada.','faint')]));
}
const OPEN_STAGES=['rec','tra','fil','imp','cor'];
function machineTile(m){
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
const head=node('div',undefined,'mtile-head');
const state=node('span',m.active?'Ativa':'Desativada','integ-state');state.style.setProperty('--c',m.active?'var(--ok)':'var(--faint)');
head.append(node('b',m.name),state);
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
const full=!over&&!!m.limit_metres&&m.open_metres>=m.limit_metres;
const bar=node('div',undefined,'mbar'+(over?' over':full?' full':''));const fill=node('span');
fill.style.width=(m.limit_metres?Math.min(100,m.open_metres/m.limit_metres*100):0)+'%';bar.append(fill);
const used=node('div',undefined,'mload'+(over?' over':''));
used.append(node('span',machineLoad(m)),node('span',over?'acima do limite':full?'no limite':m.limit_metres?'':'sem limite'));
const stages=OPEN_STAGES.filter(s=>m.states[s]).map(s=>(board?.states?.[s]||s)+' '+m.states[s]).join(' · ');
const actions=node('div',undefined,'mtile-actions');
actions.append(button('Editar',()=>machineForm(m),'btn ghost small'),button('Excluir',async()=>{
if(!window.confirm('Excluir a máquina '+m.name+'? Os pedidos dela vão para outra máquina do produto.'))return;
await api('/machines/'+m.id+'/delete',{});say('Máquina excluída.');await loadUsers();await load();},'btn ghost small danger-text'));
tile.append(head,node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','meta'),
...(m.active||m.open_orders?[bar,used]:[]),
node('span',stages||'Nenhum pedido em aberto','meta'),
node('span',m.operators.length?'Operadores: '+m.operators.map(o=>o.name).join(', '):'Nenhum operador ligado','meta'),actions);
return tile;
}
// One dialog for creating and editing, for users and machines alike.
function dialog(title,fields,onsave){
@@ -1143,15 +1181,13 @@ function userForm(u){
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'8 caracteres ou mais';
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
const boxes=usersData.machines.map(m=>{const c=node('input');c.type='checkbox';c.value=m.id;c.checked=!!u?.machines.includes(m.id);
const l=node('label',undefined,'check');l.append(c,m.name);return l;});
const machinesField=node('div',undefined,'mfield');
machinesField.append('Máquinas (só para operadores; nenhuma = todas)',...(boxes.length?boxes:[node('span','Nenhuma máquina cadastrada.','faint')]));
const syncMachines=()=>{machinesField.hidden=role.value!=='operador';};role.onchange=syncMachines;syncMachines();
const picks=pills(usersData.machines.map(m=>[m.id,m.name]),u?.machines||[]);
const machinesField=group('Máquinas',picks);
const syncMachines=()=>{machinesField.hidden=role.value!=='operador'||!usersData.machines.length;};role.onchange=syncMachines;syncMachines();
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
machines:role.value==='operador'?boxes.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value):[],
machines:role.value==='operador'?picks.values():[],
password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
@@ -1159,14 +1195,19 @@ function userForm(u){
}
function machineForm(m){
const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';
const prods=['textil','uv'].map(p=>{const c=node('input');c.type='checkbox';c.value=p;c.checked=!!m?.products.includes(p);
const l=node('label',undefined,'check');l.append(c,'Imprime '+PRODUCT_LABEL[p]);return l;});
const products=pills([['textil','Têxtil'],['uv','UV']],m?.products||[]);
const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal';
limit.placeholder='Sem limite';limit.value=m?.limit_metres??'';
const unit=node('div',undefined,'unit');unit.append(limit,node('span','metros em aberto','faint'));
const operators=usersData.users.filter(u=>u.role==='operador');
const crew=pills(operators.map(u=>[u.id,u.name||u.email]),(m?.operators||[]).map(o=>o.id));
const active=node('input');active.type='checkbox';active.checked=m?m.active:true;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativa (recebe pedidos)');
const prodField=node('div',undefined,'mfield');prodField.append('Produtos',...prods);
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),prodField,activeLabel],async()=>{
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,
products:prods.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value)});
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),group('Imprime',products),field('Limite',unit),
group('Operadores',operators.length?crew:node('span','Nenhum operador cadastrado.','faint')),activeLabel],async()=>{
if(!products.values().length)throw new Error('Marque o que a máquina imprime.');
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(),
limit_metres:limit.value?Number(limit.value):null,operators:crew.values()});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
});
}