diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 1bfbff0..0d080b8 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -101,7 +101,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v - name: Runtime and retention regressions run: | diff --git a/app/api/machine_log.py b/app/api/machine_log.py index 3bad147..5dea33d 100644 --- a/app/api/machine_log.py +++ b/app/api/machine_log.py @@ -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) diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index 1307403..745c456 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -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']: diff --git a/app/api/stamps.py b/app/api/stamps.py index 25a9205..b5914f6 100644 --- a/app/api/stamps.py +++ b/app/api/stamps.py @@ -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': diff --git a/app/api/users.py b/app/api/users.py index e2ad5ac..f15ff5b 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -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} diff --git a/app/core/auth.py b/app/core/auth.py index 0b92064..5de8958 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -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 diff --git a/app/migrations/202611261200_operator-roles.sql b/app/migrations/202611261200_operator-roles.sql new file mode 100644 index 0000000..0f59c45 --- /dev/null +++ b/app/migrations/202611261200_operator-roles.sql @@ -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 $$; diff --git a/app/operators.py b/app/operators.py index 364e691..6417b78 100644 --- a/app/operators.py +++ b/app/operators.py @@ -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}.') diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index c261573..4a4b421 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -372,6 +372,14 @@ try{ await waitFor(()=>kanban.eval(`document.querySelector('#users-list').children.length>0 && document.querySelector('#roles-matrix').children.length>0 && document.querySelector('#machines-list').children.length>0`),'Usuários tab, people, roles and machines'); + // More than one profile (Marcus, 2026-11-26): the form offers the others as chips. + await kanban.eval('userForm()'); + await waitFor(()=>kanban.eval(`[...document.querySelectorAll('.fld > span')].some(s=>s.textContent==='Outros perfis') + && document.querySelectorAll('.fopts .fopt').length>=8`),'user form with other profiles'); + await kanban.eval(`document.querySelector('.fopts .fopt').click()`); + assert.equal(await kanban.eval(`document.querySelector('.fopts .fopt').getAttribute('aria-pressed')`),'true'); + await kanban.eval(`[...document.querySelectorAll('.modal .dfoot button')].find(b=>b.textContent==='Cancelar').click()`); + await waitFor(()=>kanban.eval(`!document.querySelector('.modal')`),'user form closed'); // Pagamentos and Integrações live in their own file now: both lists still render. await kanban.click('[data-tab="payments"]'); await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab'); diff --git a/tests/test_profiles.py b/tests/test_profiles.py new file mode 100644 index 0000000..c1148e8 --- /dev/null +++ b/tests/test_profiles.py @@ -0,0 +1,53 @@ +"""Users with more than one profile (Marcus, 2026-11-26): what they may do is +the sum of their profiles, and an operator's machine rules apply only to the +moves that come from Operador. + +Run from the repository root: python3 -m unittest tests.test_profiles -v. +""" +import unittest + +from app.core.auth import has, machine_bound, machine_question, may_move, operator_only, roles_of +from tests.test_moves import moves + + +def user(*roles): + return {'role': roles[0], 'roles': list(roles)} + + +class ProfilesTest(unittest.TestCase): + def test_moves_are_the_sum_of_the_profiles(self): + self.assertEqual(moves(['operador', 'revisor']), moves('operador') | moves('revisor')) + # Gestão and Operador: the coordination's pulls back, and the operator's moves forward. + self.assertEqual(moves(['gestao', 'operador']), moves('gestao') | moves('operador')) + self.assertTrue(may_move(['gestao', 'operador'], 'tra', 'imp')) + self.assertFalse(may_move('gestao', 'tra', 'imp')) + + def test_operador_and_revisor_release_what_they_printed(self): + # D-29 does not block a user with both profiles (Marcus, 2026-11-26). + self.assertTrue(may_move(['operador', 'revisor'], 'rev', 'fin')) + + def test_the_machine_rules_follow_the_profile_that_allows_the_move(self): + both = user('operador', 'revisor') + self.assertTrue(machine_bound(both, 'tra', 'imp')) + self.assertTrue(machine_bound(both, 'imp', 'rev')) + self.assertFalse(machine_bound(both, 'rev', 'fin')) # as a Revisor, any machine + self.assertFalse(machine_bound(user('gestao', 'operador'), 'imp', 'cor')) + self.assertTrue(machine_bound(user('operador'), 'imp', 'rev')) + self.assertFalse(machine_bound(user('admin'), 'tra', 'imp')) + + def test_capabilities_and_the_machine_question(self): + both = user('operador', 'revisor') + self.assertTrue(has(both, 'inspect') and has(both, 'print')) + self.assertTrue(operator_only(both, 'print')) + self.assertFalse(operator_only(user('gestao', 'operador'), 'print')) + self.assertEqual(machine_question(user('operador')), 'required') + self.assertEqual(machine_question(both), 'required') + self.assertEqual(machine_question(user('gestao', 'operador', 'revisor')), 'optional') + self.assertIsNone(machine_question(user('revisor'))) + + def test_a_row_from_before_the_list_has_its_one_profile(self): + self.assertEqual(roles_of({'role': 'designer', 'roles': []}), ('designer',)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/users_test.py b/tests/users_test.py index d5f3dcb..2198fea 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -231,6 +231,19 @@ def run(): reviewer.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=409) shown = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o)) assert (shown['picked_up_by'], shown['picked_up_photo']) == (emails['revisor'], photo) and shown['picked_up_at'], shown + # More than one profile (Marcus, 2026-11-26): Revisor and Operador sum + # their moves; the operator's machine rules keep only to Operador's. + row = next(u for u in admin.call('/operator/users')['users'] if u['email'] == emails['revisor']) + admin.call(f"/operator/users/{row['id']}", {'name': 'Confere', 'email': emails['revisor'], 'role': 'revisor', + 'roles': ['operador', 'revisor']}) + assert next(u for u in admin.call('/operator/users')['users'] + if u['email'] == emails['revisor'])['roles'] == ['revisor', 'operador'] + both = reviewer.call('/operator/me') + assert both['roles'] == ['revisor', 'operador'] and both['machine_question'] == 'required', both + assert ['tra', 'imp'] in both['moves'] and ['rev', 'fin'] in both['moves'] and 'print' in both['can'], both + assert ['tra', 'imp'] in both['machine_moves'] and ['rev', 'fin'] not in both['machine_moves'], both + admin.call(f"/operator/users/{row['id']}", {'name': 'Confere', 'email': emails['revisor'], 'role': 'revisor'}) + assert reviewer.call('/operator/me')['roles'] == ['revisor'] # The designer: every order, whatever its machine; the artwork stages only. admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer', diff --git a/web/kanban-board.js b/web/kanban-board.js index d4352a2..03b636d 100644 --- a/web/kanban-board.js +++ b/web/kanban-board.js @@ -587,7 +587,7 @@ function phoneMenu(){ const go=fn=>async()=>{m.close();await fn();}; const who=node('div',undefined,'who sheetwho'),words=node('span'); const ava=node('span',initialsOf(ME.name||ME.email),'ava');ava.append(node('i',undefined,'pres on')); - words.append(node('b',ME.name||ME.email),node('span',(ROLE_NAMES[ME.role]||ME.role)+(myMachine()?', na '+myMachine().name:''),'sub')); + words.append(node('b',ME.name||ME.email),node('span',rolesLabel(myRoles())+(myMachine()?', na '+myMachine().name:''),'sub')); who.append(ava,words); // Seções: the tabs that do not fit the bottom bar (canvas Ph2), with the // rail's own icon and name; then the account. diff --git a/web/kanban-montador.js b/web/kanban-montador.js index ca229f0..f7fba97 100644 --- a/web/kanban-montador.js +++ b/web/kanban-montador.js @@ -26,7 +26,9 @@ const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size'). // Interno orders, the Vendedor only Venda, and Gestão and the administrators // both. An Interno order uses the fixed internal customer; a Venda one is // picked from Tiny. -const montarKindNames=()=>ME?.role==='expedicao'?['interno']:ME?.role==='vendedor'?['venda']:['interno','venda']; +// The kinds of each profile, summed (app/api/stamps.py MONTADOR_KINDS). +const montarKindNames=()=>['interno','venda'].filter(kind=>myRoles().some(r=> + r==='expedicao'?kind==='interno':r==='vendedor'?kind==='venda':['superadmin','admin','gestao'].includes(r))); const montarInternalField=key=>String(MONTAR.internal?.[key]||''); const montarInternalReady=()=>!!MONTAR.internal&&['name','cnpj','zap','mail'].every(key=>montarInternalField(key).trim()); function montarPaintKind(){ diff --git a/web/kanban-order.js b/web/kanban-order.js index 4b2e114..d165bde 100644 --- a/web/kanban-order.js +++ b/web/kanban-order.js @@ -1016,7 +1016,7 @@ function phoneFacts(order){ row('Entrega',specialDelivery(s)||(dest?dest.city+'/'+dest.state:'Retirada em Franca')); row('Máquina',order.machine?.name||'Nenhuma');row('Código','DTF-'+order.number+', cliente '+orderCode(order.id)); // Choosing the machine stays where it is allowed. - if(may('print')&&ME?.role!=='operador'&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);} + if(may('print')&&!printOnlyAsOperator()&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);} return box; } function orderFacts(order){ diff --git a/web/kanban-users.js b/web/kanban-users.js index 05510c2..bc154b6 100644 --- a/web/kanban-users.js +++ b/web/kanban-users.js @@ -86,7 +86,7 @@ function machineCard(order){ const pulled=order.machine_pulled; const detail=pulled?'Puxada por '+pulled.by+' em '+when(pulled.at):current?'Escolhida para este pedido':'Definida quando alguém puxar o card'; // The operator's orders go to the machine that pulls them (item 12). - if(!may('print')||ME?.role==='operador'||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){ + if(!may('print')||printOnlyAsOperator()||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){ box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail)); return box; } @@ -193,7 +193,7 @@ function renderUsers(){ else machine.append(node('span','Sem máquina','muted')); const open=node('td',undefined,'r'); if(editable){open.append(iconButton(IC.right,'Editar '+(u.name||u.email),()=>userForm(u),'btn sq ghost'));tr.classList.add('click');tr.onclick=()=>userForm(u);} - tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':', desativado')),machine, + tr.append(who,node('td',rolesLabel(u.roles||[u.role])+(u.active?'':', desativado')),machine, node('td',u.last_login_at?ago(u.last_login_at):'nunca entrou','muted'),open); return tr; })); @@ -202,7 +202,7 @@ function renderUsers(){ const editable=u.role!=='superadmin'||ME.role==='superadmin'; const row=node('button',undefined,'mli');row.type='button';row.disabled=!editable;if(editable)row.onclick=()=>userForm(u); const words=node('span',undefined,'grow'),sub=node('span',undefined,'sub mcell'); - sub.append(ROLE_NAMES[u.role]+(u.active?'':', desativado')); + sub.append(rolesLabel(u.roles||[u.role])+(u.active?'':', desativado')); if(u.machines.length){sub.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));} words.append(node('b',u.name||u.email),sub); row.append(avatar(u),words,svgIcon(IC.right,'i m'));return row;})); @@ -258,6 +258,10 @@ function userForm(u){ const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador', {label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email}); const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint); + // More than one profile (Marcus, 2026-11-26): the person may do what any of them may. + const others=pills(roles.filter(r=>r!=='superadmin').map(r=>[r,ROLE_NAMES[r]]),(u?.roles||[]).filter(r=>r!==u?.role)); + if(u?.role==='superadmin'||u?.email===ME.email)others.querySelectorAll('button').forEach(b=>b.disabled=true); + const othersField=group('Outros perfis',others,node('small','Some as permissões de mais perfis, por exemplo Operador e Revisor.')); const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password'; pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter a atual':'8 caracteres ou mais'; const active=node('input');active.checked=u?u.active:true;active.disabled=u?.email===ME.email; @@ -284,10 +288,11 @@ function userForm(u){ } const m=formDialog(editing?u.name||u.email:'Novo usuário',{width:560,left,lead:editing?avatar(u,'bigava'):null, text:editing?PRESENCE[presence(u)].split(':')[0]+', último acesso '+(u.last_login_at?when(u.last_login_at):'nunca'):'A pessoa entra com o e-mail e esta senha, e troca a senha em Minha conta.', - fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),field('Vendedor no Tiny',seller,sellerNote),checkbox('Ativo: pode entrar no sistema',active)], + fields:[row,roleField,othersField,field(editing?'Nova senha':'Senha inicial',pass),field('Vendedor no Tiny',seller,sellerNote),checkbox('Ativo: pode entrar no sistema',active)], label:editing?'Salvar':'Criar usuário',onsave:async()=>{ const picked=seller.value?{id:Number(seller.value),name:seller.selectedOptions[0].textContent.replace(/ \(não está mais no Tiny\)$/,'')}:null; - const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null,tiny_seller:picked}; + const main=role.value()==='superadmin'?'admin':role.value(); + const body={name:name.value,email:email.value,role:main,roles:others.values().filter(r=>r!==main),active:active.checked,password:pass.value||null,tiny_seller:picked}; // An e-mail already in use is said in the form, not an error (Sentry DTF-WEB-1D). await api(editing?'/users/'+u.id:'/users',body,{expected:[409]}); say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers(); @@ -355,7 +360,7 @@ async function openMachineSheet(machineId, tab='situacao'){ catch(e){say(e.message,true);return;} const machine=data.machine; const machineState=(board.machines||[]).find(row=>row.id===machine.id)||null; - const launch=may('print')&&(ME?.role!=='operador'||myMachine()?.id===machine.id); + const launch=may('print')&&(!printOnlyAsOperator()||myMachine()?.id===machine.id); const manage=may('manage'); let sheetModal=null; let activeTab=tab; @@ -594,7 +599,7 @@ function machineAlertDialog(order,machineId,alert){ return new Promise(resolve=>{ let decided=false; const machine=(board.machines||[]).find(row=>row.id===machineId); - const allowed=ME?.role!=='operador'||myMachine()?.id===machineId; + const allowed=!printOnlyAsOperator()||myMachine()?.id===machineId; const made=node('button','Marcar como feito','btn pri');made.type='button'; const later=node('button','Adiar uma vez','btn');later.type='button'; const back=node('button','Voltar','btn ghost right');back.type='button'; @@ -660,7 +665,7 @@ function choosePullMachine(order){ // always go to the machine of their session (DTF-WEB-4). async function pullTo(order, machineId){ let target; - if(ME?.role==='operador'){ + if(machineBound('tra','imp')){ const mine=myMachine(); if(!mine){askMachine(true);return;} // Guidance, not an error: the pull goes to the session's machine (Sentry DTF-WEB-1A). @@ -718,13 +723,13 @@ function accountForm(){ const next=node('input');next.type='password';next.required=true;next.minLength=8;next.autocomplete='new-password'; const again=node('input');again.type='password';again.required=true;again.minLength=8;again.autocomplete='new-password'; const dl=node('dl',undefined,'dl'); - for(const [k,v] of [['E-mail',ME.email],['Perfil',ROLE_NAMES[ME.role]||ME.role],...(ME.machine_question?[['Máquina agora',myMachine()?.name||'Nenhuma']]:[])]){ + for(const [k,v] of [['E-mail',ME.email],['Perfil',rolesLabel(myRoles())],...(ME.machine_question?[['Máquina agora',myMachine()?.name||'Nenhuma']]:[])]){ const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);} const sect=node('div',undefined,'sect'); const row=node('div',undefined,'frow');row.append(field('Nova senha',next,'8 caracteres ou mais'),field('Repita a nova senha',again)); sect.append(node('b','Trocar a senha'),field('Senha atual',current),row); formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'), - text:ROLE_NAMES[ME.role]+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect], + text:rolesLabel(myRoles())+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect], note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave:async()=>{ if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.'); await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.'); diff --git a/web/kanban.js b/web/kanban.js index dde7302..275284e 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -54,10 +54,21 @@ const mayReorder=state=>!!ME?.reorder?.includes(state); // others show, without drag or buttons. const myMachine=()=>ME?.machine||null; const isMine=order=>!!myMachine()&&order.machine?.id===myMachine().id; -const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order); +// Every profile of the user, the main one first (Marcus, 2026-11-26): what +// they may do is the sum of them. +const myRoles=()=>ME?.roles?.length?ME.roles:ME?[ME.role]:[]; +const hasRole=r=>myRoles().includes(r); +const rolesLabel=roles=>roles.map(r=>ROLE_NAMES[r]||r).join(' / '); +// The moves only the Operador profile allows this user: they keep to the +// session's machine. An operator who is also Revisor releases any sheet. +const machineBound=(a,b)=>(ME?.machine_moves||[]).some(([c,d])=>c===a&&d===b); +// Printing comes to this user only through Operador: no choosing the machine by hand. +const printOnlyAsOperator=()=>hasRole('operador')&&!myRoles().some(r=>['superadmin','admin','gestao'].includes(r)); +const mayAct=order=>!hasRole('operador')||order.state==='tra'||isMine(order)|| + (ME?.moves||[]).some(([a,b])=>a===order.state&&!machineBound(a,b)); // Which tabs each capability opens. // Vendedor and Financeiro consult Cotações and Números without acting there. -const consults=()=>['vendedor','financeiro'].includes(ME?.role); +const consults=()=>myRoles().some(r=>['vendedor','financeiro'].includes(r)); const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'), stats:()=>may('manage')||consults(),site:()=>may('manage'), integrations:()=>may('manage')||may('print')||may('label'),users:()=>may('users'),montar:()=>may('assemble')}; @@ -887,7 +898,7 @@ function showTab(name){ } function render(){ $('who').textContent=ME?(ME.name||ME.email):''; - $('who-role').textContent=ME?(ROLE_NAMES[ME.role]||ME.role)+', '+ME.email:''; + $('who-role').textContent=ME?rolesLabel(myRoles())+', '+ME.email:''; $('who-initials').textContent=ME?initialsOf(ME.name||ME.email):''; $('initials').textContent=ME?initialsOf(ME.name||ME.email):'·'; $('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';