All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m24s
The board Dropstar drew on 2026-10-23: Arte recebida, Arte conferida, Imprimindo, Correção, Revisão, Finalizado. - Fila de impressão leaves the board: Arte conferida is the queue. It takes an order only with every item's final approved, keeps the finals as approved, orders its cards for printing and has the room's "Baixar" and the automatic folder. Orders that were in the queue move there once, with a line in their history - Revisão checks the printed sheet, and the new Revisor profile is the only one that sends an order to Finalizado (the superadmin too, for support) - who moves what, from the server (MOVES): the designer the artwork, asking for corrections and bringing the new art back; the operator Arte conferida to Imprimindo to Revisão; admin and gestão everything else, Correção included; a step back belongs to whoever makes the move it undoes - Tiny: Arte conferida is "Preparando envio" and Finalizado "Pronto para envio", for delivery orders too - Prova OK still comes before Finalizado; the customer's portal shows the new steps Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
248 lines
12 KiB
Python
248 lines
12 KiB
Python
"""Kanban users and print machines, managed by the administrators.
|
|
|
|
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 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 machines, mail
|
|
from ..core import db
|
|
from ..core.auth import CAPABILITIES, audit, can, may_move, may_reorder, password_hash, password_matches, signed_in
|
|
from ..core.models import StrictModel
|
|
from ..runtime import BACK, STATES, TRANSITIONS
|
|
|
|
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', 'designer', 'operador', 'revisor', 'vendedor']
|
|
password: str | None = Field(default=None, min_length=8, 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
|
|
# 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):
|
|
current: str = Field(min_length=1, max_length=128)
|
|
new: str = Field(min_length=8, max_length=128)
|
|
|
|
|
|
@router.get('/api/operator/me')
|
|
def me(request: Request):
|
|
"""Who is signed in, and what the Kanban should offer them: the moves
|
|
their profile makes (forward, and the step back) and the columns whose
|
|
order they set."""
|
|
account = signed_in(request)
|
|
role = account['role']
|
|
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
|
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
|
|
return {'email': account['email'], 'name': account['name'], 'role': role,
|
|
'machines': account['machines'],
|
|
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
|
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
|
|
|
|
|
@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': machines.rows(c, with_operators=True)}
|
|
|
|
|
|
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, 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 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:
|
|
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 8 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, body.role)
|
|
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, role)
|
|
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 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': machines.rows(c, with_operators=True)}
|
|
|
|
|
|
@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,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)}
|
|
|
|
|
|
@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,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}
|
|
|
|
|
|
@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.')
|
|
machines.route(c)
|
|
audit('machine_deleted', operator=user, machine=row['name'])
|
|
return {'ok': True}
|
|
|
|
|
|
@router.post('/api/operator/mail/test')
|
|
def test_mail(request: Request, user=Depends(can('integrations'))):
|
|
"""A message to whoever asked, to prove the mail server works."""
|
|
with db.connect() as c:
|
|
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
|
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
|
|
'os e-mails dos clientes.'):
|
|
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
|
audit('mail_test_queued', operator=user)
|
|
return {'ok': True, 'to': user}
|