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}

View File

@@ -207,9 +207,19 @@ MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'opti
MOVERS = MANAGERS + tuple(MOVES)
def _profiles(role):
"""One profile or several: a user with more than one profile may do what
any of them may (Marcus, 2026-11-26: operador/revisor, gestor/operador)."""
return (role,) if isinstance(role, str) else tuple(role)
def may_move(role, from_state, to_state, back=False):
"""Whether this profile may move a card; `back` is the step back that
undoes the move to_state -> from_state."""
"""Whether this profile (or any of these) may move a card; `back` is the
step back that undoes the move to_state -> from_state."""
return any(_may_move(r, from_state, to_state, back) for r in _profiles(role))
def _may_move(role, from_state, to_state, back):
if back:
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
if to_state == 'fin':
@@ -222,7 +232,44 @@ def may_move(role, from_state, to_state, back=False):
def may_reorder(role, state):
"""Changing a card's place in its column, the order it is worked in: for
whoever takes cards forward out of it."""
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
return any(r in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(r, ()))
for r in _profiles(role))
def roles_of(account):
"""Every profile of a signed-in user, the main one first. Rows written
before profiles became a list have only `role`."""
return tuple(account.get('roles') or ()) or (account['role'],)
def has(account, capability):
return any(r in CAPABILITIES[capability] for r in roles_of(account))
def machine_bound(account, from_state, to_state, back=False):
"""Whether only the Operador profile allows this move, so the operator's
machine rules apply to it: an operator who is also Revisor releases any
machine's sheet, as a Revisor does."""
roles = roles_of(account)
return 'operador' in roles and not may_move([r for r in roles if r != 'operador'], from_state, to_state, back)
def reorder_machine_bound(account, state):
roles = roles_of(account)
return 'operador' in roles and not may_reorder([r for r in roles if r != 'operador'], state)
def operator_only(account, capability):
"""Whether this capability comes to the user only through Operador."""
roles = roles_of(account)
return 'operador' in roles and not any(r in CAPABILITIES[capability] for r in roles if r != 'operador')
def machine_question(account):
""""Em qual máquina você está?": optional for management, required for an
operator who is nothing more, never for the others."""
answers = {MACHINE_QUESTION.get(r) for r in roles_of(account)}
return 'optional' if 'optional' in answers else 'required' if 'required' in answers else None
def signed_in(request: Request):
@@ -233,7 +280,7 @@ def signed_in(request: Request):
raise HTTPException(401, 'Entre no Kanban.')
digest = hashlib.sha256(token.encode()).hexdigest()
with connect() as c:
row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
row = c.execute('''SELECT o.id,o.email,o.name,o.role,o.roles,s.machine_answered,m.id AS machine_id,m.name AS machine_name
FROM dtf_local.operator_sessions s
JOIN dtf_local.operators o ON o.email=s.username AND o.active
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
@@ -258,7 +305,7 @@ def can(capability):
returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if account['role'] not in CAPABILITIES[capability]:
if not has(account, capability):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check
@@ -269,7 +316,7 @@ def can_any(*capabilities):
and returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities):
if not any(has(account, capability) for capability in capabilities):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check

View File

@@ -0,0 +1,13 @@
-- More than one profile per user (Marcus, 2026-11-26: operador/revisor,
-- gestor/operador/revisor): what a user may do is the sum of their profiles.
-- `role` stays the main one, shown first and kept for superadmin; `roles`
-- holds every profile, the main one included.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS roles text[] NOT NULL DEFAULT '{}';
UPDATE dtf_local.operators SET roles=ARRAY[role] WHERE cardinality(roles)=0;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_roles'
AND conrelid='dtf_local.operators'::regclass) THEN
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_roles
CHECK (roles <@ ARRAY['superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']::text[]);
END IF;
END $$;

View File

@@ -45,10 +45,10 @@ def seed_from_environment(cursor):
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
if existing:
# The configured account is the system's own: it stays superadmin.
cursor.execute("UPDATE dtf_local.operators SET role='superadmin' WHERE email=%s", (email,))
cursor.execute("UPDATE dtf_local.operators SET role='superadmin',roles=ARRAY['superadmin'] WHERE email=%s", (email,))
return None
cursor.execute(
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,'superadmin')",
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles) VALUES(%s,%s,%s,%s,'superadmin',ARRAY['superadmin'])",
(uuid4(), email, 'Operador', password_hash(password)))
return email
@@ -69,8 +69,8 @@ def add(email, name='', role='admin'):
with connect() as c:
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
raise SystemExit(f'{email} already exists. Use "password" or "enable".')
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,%s)',
(uuid4(), email, name, password_hash(_ask_password(email)), role))
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles) VALUES(%s,%s,%s,%s,%s,%s)',
(uuid4(), email, name, password_hash(_ask_password(email)), role, [role]))
print(f'Added {email} as {role}.')
@@ -79,7 +79,8 @@ def set_role(email, role):
if role not in ROLES:
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
with connect() as c:
if not c.execute('UPDATE dtf_local.operators SET role=%s WHERE email=%s RETURNING id', (role, email)).fetchone():
if not c.execute('UPDATE dtf_local.operators SET role=%s,roles=%s WHERE email=%s RETURNING id',
(role, [role], email)).fetchone():
raise SystemExit(f'{email} does not exist.')
print(f'{email} is now {role}.')