diff --git a/app/api/operator.py b/app/api/operator.py index 946dcee..8cb49d8 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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} diff --git a/app/api/users.py b/app/api/users.py index a6a8916..5ea9c8c 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -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} diff --git a/app/machines.py b/app/machines.py new file mode 100644 index 0000000..ca92dbb --- /dev/null +++ b/app/machines.py @@ -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 diff --git a/app/payments.py b/app/payments.py index 33dc0c5..def5038 100644 --- a/app/payments.py +++ b/app/payments.py @@ -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) diff --git a/app/schema.sql b/app/schema.sql index a9fbcb9..e892bcd 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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, diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 6dcb1e3..d6d283e 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -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. diff --git a/tests/users_test.py b/tests/users_test.py index b051408..2a42ce9 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -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,)) diff --git a/web/kanban.css b/web/kanban.css index 535e9c8..cd5d121 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -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} diff --git a/web/kanban.html b/web/kanban.html index 8a69b3d..e9f2779 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -91,9 +91,8 @@ Gestão: tudo, menos usuários. Operador: move pedidos e aprova arquivos. Vendedor: só consulta.

NomePerfilMáquinasÚltimo acesso

Máquinas

-

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.

-
MáquinaProdutosSituação
+

Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.

+