Every operator could do everything, and accounts were made from the console. Each account now has a profile, checked by the server on every action: Administrador (everything, plus users and machines), Gestão (everything but users), Operador (moves cards and handles artwork) and Vendedor (reads orders, quotes and Números, changes nothing). The superadmin is the system's own account, set from the console and kept by the account OPERATOR_EMAIL seeds; administrators cannot change it, and nobody can delete, disable or demote themselves. The Usuários tab creates, edits, disables and deletes users with a first password (there is no e-mail yet), and registers machines with the products each prints. An order goes to the first active machine that prints its product, or to the one chosen in its panel; an operator tied to machines sees and downloads only their orders. Everyone changes their own password in the account menu, which now holds the name and Sair too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
211 lines
9.9 KiB
Python
211 lines
9.9 KiB
Python
"""Kanban users and print machines, managed by the administrators.
|
|
|
|
There is no e-mail yet, so an administrator creates each account with a
|
|
first password and the person changes it in "Minha senha". The superadmin is
|
|
the system's own account, set from the console (python -m app.operators);
|
|
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 typing import Literal
|
|
from uuid import UUID, uuid4
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
from pydantic import Field, field_validator
|
|
|
|
from ..core import db
|
|
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
|
|
from ..core.models import StrictModel
|
|
|
|
router = APIRouter()
|
|
|
|
class UserIn(StrictModel):
|
|
# The profiles an administrator may give; superadmin only comes from the console.
|
|
name: str = Field(min_length=1, max_length=80)
|
|
email: str = Field(min_length=3, max_length=254)
|
|
role: Literal['admin', 'gestao', 'operador', 'vendedor']
|
|
password: str | None = Field(default=None, min_length=12, max_length=128)
|
|
active: bool = True
|
|
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
|
|
|
@field_validator('email')
|
|
@classmethod
|
|
def email_valid(cls, value):
|
|
value = value.strip().lower()
|
|
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
|
|
raise ValueError('Informe um e-mail válido.')
|
|
return value
|
|
|
|
|
|
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
|
|
|
|
|
|
class PasswordChange(StrictModel):
|
|
current: str = Field(min_length=1, max_length=128)
|
|
new: str = Field(min_length=12, max_length=128)
|
|
|
|
|
|
@router.get('/api/operator/me')
|
|
def me(request: Request):
|
|
"""Who is signed in, and what the Kanban should offer them."""
|
|
account = signed_in(request)
|
|
return {'email': account['email'], 'name': account['name'], 'role': account['role'],
|
|
'machines': account['machines'],
|
|
'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)}
|
|
|
|
|
|
@router.post('/api/operator/me/password')
|
|
def change_password(body: PasswordChange, request: Request):
|
|
account = signed_in(request)
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT password_hash FROM dtf_local.operators WHERE id=%s', (account['id'],)).fetchone()
|
|
if not password_matches(body.current, row['password_hash']):
|
|
raise HTTPException(403, 'A senha atual não confere.')
|
|
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.new), account['id']))
|
|
audit('operator_password_changed', operator=account['email'])
|
|
return {'ok': True}
|
|
|
|
|
|
def user_rows(c):
|
|
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
|
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
|
|
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
|
|
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
|
for row in rows:
|
|
row['machines'] = [str(m) for m in row['machines']]
|
|
return rows
|
|
|
|
|
|
@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)}
|
|
|
|
|
|
def target(c, uid, request):
|
|
"""The account to change, refusing a superadmin unless one is asking."""
|
|
row = c.execute('SELECT * FROM dtf_local.operators WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Usuário não encontrado.')
|
|
if row['role'] == 'superadmin' and request.state.operator['role'] != 'superadmin':
|
|
raise HTTPException(403, 'Só o superadmin altera esta conta.')
|
|
return row
|
|
|
|
|
|
def set_machines(c, uid, machines):
|
|
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))):
|
|
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:
|
|
c.execute('INSERT INTO dtf_local.operator_machines(operator_id,machine_id) VALUES(%s,%s)', (uid, machine))
|
|
|
|
|
|
@router.post('/api/operator/users')
|
|
def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
|
if not body.password:
|
|
raise HTTPException(422, 'Defina uma senha inicial com 12 caracteres ou mais.')
|
|
uid = uuid4()
|
|
with db.connect() as c:
|
|
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
|
|
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
|
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)
|
|
audit('operator_created', operator=user, account=body.email, role=body.role)
|
|
return {'id': str(uid)}
|
|
|
|
|
|
@router.post('/api/operator/users/{uid}')
|
|
def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('users'))):
|
|
me_ = request.state.operator
|
|
with db.connect() as c:
|
|
row = target(c, uid, request)
|
|
# A superadmin keeps that profile: the form offers only the assignable ones.
|
|
role = row['role'] if row['role'] == 'superadmin' else body.role
|
|
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role']):
|
|
raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.')
|
|
if body.email != row['email'] and c.execute(
|
|
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
|
|
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
|
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
|
|
(body.name.strip(), body.email, role, body.active, uid))
|
|
if body.password:
|
|
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
|
if body.email != row['email']:
|
|
c.execute('UPDATE dtf_local.operator_sessions SET username=%s WHERE username=%s', (body.email, row['email']))
|
|
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)
|
|
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
|
|
password_reset=bool(body.password))
|
|
return {'ok': True}
|
|
|
|
|
|
@router.post('/api/operator/users/{uid}/delete')
|
|
def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
|
|
with db.connect() as c:
|
|
row = target(c, uid, request)
|
|
if str(row['id']) == str(request.state.operator['id']):
|
|
raise HTTPException(409, 'Você não pode excluir a sua própria conta.')
|
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (row['email'],))
|
|
c.execute('DELETE FROM dtf_local.operators WHERE id=%s', (uid,))
|
|
# The movement history keeps the e-mail of whoever moved each card.
|
|
audit('operator_deleted', operator=user, account=row['email'])
|
|
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
|
|
|
|
|
|
@router.get('/api/operator/machines')
|
|
def list_machines(user=Depends(can('view'))):
|
|
with db.connect() as c:
|
|
return {'machines': machine_rows(c)}
|
|
|
|
|
|
@router.post('/api/operator/machines')
|
|
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
|
mid = uuid4()
|
|
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))
|
|
audit('machine_created', operator=user, machine=body.name)
|
|
return {'id': str(mid)}
|
|
|
|
|
|
@router.post('/api/operator/machines/{mid}')
|
|
def update_machine(mid: UUID, 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) 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():
|
|
raise HTTPException(404, 'Máquina não encontrada.')
|
|
audit('machine_updated', operator=user, machine=body.name)
|
|
return {'ok': True}
|
|
|
|
|
|
@router.post('/api/operator/machines/{mid}/delete')
|
|
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
|
"""Its orders go back to the automatic choice; its operators lose it."""
|
|
with db.connect() as c:
|
|
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.')
|
|
audit('machine_deleted', operator=user, machine=row['name'])
|
|
return {'ok': True}
|