feat: a user may have more than one profile, and may do what any of them may (Marcus, 2026-11-26)
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 8m1s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m32s

operators.roles holds every profile, the main one first; permissions, moves,
the column order and the machine question are the sum. The operator's machine
rules apply only to the moves Operador alone allows, so an Operador who is also
Revisor releases any sheet (D-29 does not block, Marcus). Usuários gets
"Outros perfis" chips next to the main profile.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-26 10:57:20 -03:00
parent a88e7a3288
commit 4c6e2aac4a
16 changed files with 234 additions and 62 deletions

View File

@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from .. import machine_log, machine_stats
from ..core import db
from ..core.auth import audit, can, operator
from ..core.auth import audit, can, operator, operator_only, roles_of
from ..core.models import MachineEntry, MachineSheet
router = APIRouter()
@@ -25,7 +25,7 @@ def machine_row(c, mid):
def own_machine(request, mid):
"""An operator enters only on the machine of their session; management, anywhere."""
account = request.state.operator
if account['role'] != 'operador':
if not operator_only(account, 'print'):
return
session_machine = account['machine']
if not session_machine or str(session_machine['id']) != str(mid):
@@ -127,7 +127,7 @@ def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'
@router.get('/api/operator/stats/machines')
def machine_stats_month(request: Request, month: str | None = None, user=Depends(operator)):
"""Números per machine, month by month (Fase 2, front 1b)."""
if request.state.operator['role'] not in STATS_ROLES:
if not set(roles_of(request.state.operator)) & set(STATS_ROLES):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
try:
start, _ = machine_stats.month_bounds(month)

View File

@@ -11,7 +11,8 @@ from psycopg.types.json import Jsonb
from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews
from ...cart_pricing import needs_designer
from ...core import db
from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator
from ...core.auth import (MOVERS, audit, can, machine_bound, may_move, may_reorder, operator, operator_only,
reorder_machine_bound, roles_of)
from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart
from ...payments import release_files
from ...printjobs import queue as queue_print_files, requeue as requeue_print_files
@@ -89,7 +90,7 @@ class MachineChoice(StrictModel):
@router.post('/api/operator/orders/{uid}/machine')
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
"""Exceptional manual choice before printing; the operator's pull is final."""
if request.state.operator['role'] == 'operador':
if operator_only(request.state.operator, 'print'):
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
with db.connect() as c:
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
@@ -379,10 +380,10 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if not may_reorder(request.state.operator['role'], row['state']):
if not may_reorder(roles_of(request.state.operator), row['state']):
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
mine = request.state.operator['machine']
if (request.state.operator['role'] == 'operador' and row['state'] != 'tra'
if (reorder_machine_bound(request.state.operator, row['state']) and row['state'] != 'tra'
and (not mine or str(row['machine_id'] or '') != mine['id'])):
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
keys = {}
@@ -406,7 +407,7 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
@router.post('/api/operator/orders/{uid}/move')
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
if request.state.operator['role'] not in MOVERS:
if not set(roles_of(request.state.operator)) & set(MOVERS):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
@@ -422,7 +423,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
back = BACK.get(row['state']) == body.state
if body.state not in TRANSITIONS[row['state']] and not back:
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
if not may_move(request.state.operator['role'], row['state'], body.state, back):
if not may_move(roles_of(request.state.operator), row['state'], body.state, back):
raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back
else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.")
if body.state == 'cor' and not body.reason.strip():
@@ -434,7 +435,9 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
account = request.state.operator
session_machine = account['machine']
pulling = row['state'] == 'tra' and body.state == 'imp'
if account['role'] == 'operador':
# The operator's machine rules, when only the Operador profile allows the move.
bound = machine_bound(account, row['state'], body.state, back)
if bound:
if not session_machine:
raise HTTPException(409, 'Escolha a máquina em que você está.')
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
@@ -443,7 +446,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
if not chosen:
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
if account['role'] == 'operador' and str(chosen) != session_machine['id']:
if bound and str(chosen) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
if not target or not target['active']:

View File

@@ -10,7 +10,7 @@ from psycopg.types.json import Jsonb
from .. import payments, quote_review
from ..core import db
from ..core.auth import audit, can
from ..core.auth import audit, can, roles_of
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
StampSizeTable, UploadStart)
from ..runtime import operator_identity
@@ -117,8 +117,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
customer, origin atendimento, invoiced and sent to Tiny), at the Site's
table price. A Venda is picked up, travels with a clothing order or ships
with the Site's freight; approve quotes the freight again."""
role = request.state.operator['role']
if body.kind not in MONTADOR_KINDS.get(role, set()):
kinds = set().union(*(MONTADOR_KINDS.get(r, set()) for r in roles_of(request.state.operator)))
if body.kind not in kinds:
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
with db.connect() as c:
if body.kind == 'interno':

View File

@@ -16,8 +16,8 @@ from pydantic import Field, field_validator
from .. import machines, mail, observability
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.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
@@ -28,11 +28,17 @@ class TinySeller(StrictModel):
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)
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
# 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
@@ -50,6 +56,10 @@ class UserIn(StrictModel):
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)
@@ -80,19 +90,22 @@ def me(request: Request):
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,
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.get(role),
'machine': account['machine'], 'machine_question': machine_question(account),
'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)]}
'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):
@@ -109,7 +122,7 @@ def choose_session_machine(body: MachineAnswer, request: Request):
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'])
question = machine_question(account)
if not question:
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
with db.connect() as c:
@@ -148,7 +161,7 @@ def change_password(body: PasswordChange, request: Request):
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,
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.
@@ -159,6 +172,7 @@ def user_rows(c):
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
@@ -189,10 +203,11 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
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,active,tiny_seller_id,tiny_seller_name)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active, seller and seller.id, seller and seller.name))
audit('operator_created', operator=user, account=body.email, role=body.role)
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)}
@@ -203,14 +218,15 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
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']):
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,active=%s,tiny_seller_id=%s,
tiny_seller_name=%s WHERE id=%s''', (body.name.strip(), body.email, role, body.active,
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))
@@ -219,7 +235,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,))
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
audit('operator_updated', operator=user, account=body.email, role='/'.join(roles), active=body.active,
password_reset=bool(body.password))
return {'ok': True}