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

@@ -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}