"""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, MACHINE_QUESTION, 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', 'financeiro'] password: str | None = Field(default=None, min_length=8, max_length=128) active: bool = True # No longer used: an operator's machine is the one chosen after signing in # (item 12). Kept so a page loaded before still saves. 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) # No longer used (item 12): who is on a machine is who chose it after # signing in. Kept so a page loaded before still saves. 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, # The machine this session is on, and whether to ask (item 12). 'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role), 'machine_answered': account['machine_answered'], '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)]} class MachineAnswer(StrictModel): # None: "Não estou em máquina", for the profiles that may say so. machine_id: UUID | None = None # Taken while someone else is on it: a shift change, not a mistake. confirm: bool = False @router.post('/api/operator/me/machine') def choose_session_machine(body: MachineAnswer, request: Request): """The machine this session works on (Dropstar's third round, item 12): the operator's pulls go to it, and the history names it. Per session, so a person runs two machines from two computers. Someone else already on it is a warning, not a refusal: shifts overlap for a few minutes.""" account = signed_in(request) question = MACHINE_QUESTION.get(account['role']) if not question: raise HTTPException(403, 'Seu perfil não trabalha em máquina.') with db.connect() as c: name = None if body.machine_id is None: if question == 'required': raise HTTPException(422, 'Escolha a máquina em que você está.') else: row = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s AND active', (body.machine_id,)).fetchone() if not row: raise HTTPException(404, 'Máquina não encontrada ou desligada.') name = row['name'] others = [r['who'] for r in c.execute('''SELECT DISTINCT COALESCE(NULLIF(o.name,''), o.email) AS who FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active WHERE s.machine_id=%s AND s.expires_at>now() AND s.username<>%s ORDER BY 1''', (body.machine_id, account['email'])).fetchall()] if others and not body.confirm: raise HTTPException(409, f"{name} já tem {' e '.join(others)} ligado.") c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=%s, machine_at=CASE WHEN %s THEN now() END, machine_answered=true WHERE token_hash=%s''', (body.machine_id, name is not None, account['session'])) audit('operator_machine_chosen', operator=account['email'], machine=name or '') return {'machine': {'id': str(body.machine_id), 'name': name} if name else None} @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): """Every account, with the machines its open sessions are on now (item 12).""" rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at, COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines, -- The last use of any open session: "Ativo agora" in Usuários. (SELECT max(x.seen_at) FROM dtf_local.operator_sessions x WHERE x.username=o.email AND x.expires_at>now()) AS seen_at FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL 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 @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)) 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,)) 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 release_sessions(c, mid): """Whoever was on a machine switched off or deleted is asked again.""" c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=NULL, machine_at=NULL, machine_answered=false WHERE machine_id=%s''', (mid,)) @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)) 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.') if not body.active: release_sessions(c, mid) 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 lose that machine; its operators lose the session choice.""" with db.connect() as c: if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1", (mid,)).fetchone(): raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.') release_sessions(c, mid) 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} @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}