"""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 os 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, observability from ..core import db from ..core.auth import (CAPABILITIES, audit, can, has, machine_bound, machine_question, may_move, may_reorder, password_hash, password_matches, roles_of, signed_in) from ..core.models import StrictModel from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS router = APIRouter() class TinySeller(StrictModel): id: int = Field(gt=0) name: str = Field(min_length=1, max_length=120) ASSIGNABLE = Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao'] 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) # The main profile, and every other one the user has (Marcus, 2026-11-26): # what they may do is the sum. role: ASSIGNABLE roles: list[ASSIGNABLE] = Field(default_factory=list, max_length=8) 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) # The Tiny seller this user is (app/tiny.py list_sellers): a Venda they # assemble reaches Tiny with it. None: no seller. tiny_seller: TinySeller | None = None @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 def profiles(self): """The main profile first, then the others, each once.""" return [self.role] + [r for r in dict.fromkeys(self.roles) if r != self.role] 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) # Orders at once in Imprimindo and files in its hot folder (app/machines.py); # None keeps what it has, or machines.DEFAULT_PLACES for a new one. places: int | None = Field(default=None, ge=1, le=machines.MAX_PLACES) # 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 MachinePlaces(StrictModel): places: int = Field(ge=1, le=machines.MAX_PLACES) 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, roles = account['role'], roles_of(account) moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(roles, a, b)] moves += [[a, b] for a, b in BACK.items() if may_move(roles, a, b, back=True)] return {'email': account['email'], 'name': account['name'], 'role': role, 'roles': list(roles), # Public by design: the Kanban browser initialises Sentry with these. 'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(), 'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT, 'sentry_release': observability.release() or '', # The machine this session is on, and whether to ask (item 12). 'machine': account['machine'], 'machine_question': machine_question(account), 'machine_answered': account['machine_answered'], 'can': sorted(cap for cap in CAPABILITIES if has(account, cap)), 'moves': moves, 'reorder': [state for state in STATES if may_reorder(roles, state)], # The moves only the Operador profile allows: kept to the session's machine. 'machine_moves': [[a, b] for a, b in moves if machine_bound(account, a, b, back=BACK.get(a) == b)]} 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(account) 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.roles,o.active,o.last_login_at,o.created_at, o.tiny_seller_id,o.tiny_seller_name, 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']] row['roles'] = list(roles_of(row)) seller_id, seller_name = row.pop('tiny_seller_id'), row.pop('tiny_seller_name') row['tiny_seller'] = {'id': seller_id, 'name': seller_name} if seller_id else None 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.') seller = body.tiny_seller c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles,active,tiny_seller_id,tiny_seller_name) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password), body.role, body.profiles(), body.active, seller and seller.id, seller and seller.name)) audit('operator_created', operator=user, account=body.email, role='/'.join(body.profiles())) 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 roles = list(roles_of(row)) if row['role'] == 'superadmin' else body.profiles() if str(row['id']) == str(me_['id']) and (not body.active or role != row['role'] or roles != list(roles_of(row))): 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.') seller = body.tiny_seller c.execute('''UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,roles=%s,active=%s,tiny_seller_id=%s, tiny_seller_name=%s WHERE id=%s''', (body.name.strip(), body.email, role, roles, body.active, seller and seller.id, seller and seller.name, 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='/'.join(roles), 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,places) VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres, body.places or machines.DEFAULT_PLACES)) 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, places=COALESCE(%s,places) WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres, body.places, 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}/places') def machine_places(mid: UUID, body: MachinePlaces, user=Depends(can('manage'))): """How many orders the machine takes in Imprimindo, and files in its hot folder: Admin and Gestão set it from the machine's sheet (Marcus, 2026-11-17). Orders already there stay; the next waits for a place.""" with db.connect() as c: row = c.execute('UPDATE dtf_local.machines SET places=%s WHERE id=%s RETURNING name', (body.places, mid)).fetchone() if not row: raise HTTPException(404, 'Máquina não encontrada.') audit('machine_places', operator=user, machine=row['name'], places=body.places) 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}