feat: the machine is chosen at sign-in, per session (Dropstar's third round, item 12)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
After signing in, the Kanban asks "Em qual máquina você está?": required
for the operator, optional for Gestão and Administrador ("Não estou em
máquina"), never for the other profiles. The session keeps it until it
ends or is changed from the header, where the machine shows in green;
one person on two computers runs two machines. Someone else already on
the machine is a warning, not a refusal.
Operators see the whole board (no more per-machine filter). From Arte
conferida they pull any card, which becomes their machine's (a machine
that does not print its product refuses it); they move only their
machine's cards, and the others show without drag or buttons. Their
cards and their machine's row in Imprimindo are outlined in green. The
history records the machine with the person: "Imprimindo · Thales ·
máquina2". Usuários shows who is on each machine now, read-only; the old
operator/machine assignment is no longer read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,7 +15,8 @@ from pydantic import Field, field_validator
|
||||
|
||||
from .. import machines, mail
|
||||
from ..core import db
|
||||
from ..core.auth import CAPABILITIES, audit, can, may_move, may_reorder, password_hash, password_matches, signed_in
|
||||
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
||||
password_matches, signed_in)
|
||||
from ..core.models import StrictModel
|
||||
from ..runtime import BACK, STATES, TRANSITIONS
|
||||
|
||||
@@ -28,6 +29,8 @@ class UserIn(StrictModel):
|
||||
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro']
|
||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||
active: bool = True
|
||||
# No longer used: an operator's machine is the one chosen after signing in
|
||||
# (item 12). Kept so a page loaded before still saves.
|
||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||
|
||||
@field_validator('email')
|
||||
@@ -45,7 +48,8 @@ class MachineIn(StrictModel):
|
||||
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)
|
||||
# The operators who work on it; None leaves them as they are.
|
||||
# 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)
|
||||
|
||||
|
||||
@@ -64,11 +68,52 @@ def me(request: Request):
|
||||
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,
|
||||
'machines': account['machines'],
|
||||
# The machine this session is on, and whether to ask (item 12).
|
||||
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
|
||||
'machine_answered': account['machine_answered'],
|
||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
||||
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
||||
|
||||
|
||||
class MachineAnswer(StrictModel):
|
||||
# None: "Não estou em máquina", for the profiles that may say so.
|
||||
machine_id: UUID | None = None
|
||||
# Taken while someone else is on it: a shift change, not a mistake.
|
||||
confirm: bool = False
|
||||
|
||||
|
||||
@router.post('/api/operator/me/machine')
|
||||
def choose_session_machine(body: MachineAnswer, request: Request):
|
||||
"""The machine this session works on (Dropstar's third round, item 12):
|
||||
the operator's pulls go to it, and the history names it. Per session, so a
|
||||
person runs two machines from two computers. Someone else already on it is
|
||||
a warning, not a refusal: shifts overlap for a few minutes."""
|
||||
account = signed_in(request)
|
||||
question = MACHINE_QUESTION.get(account['role'])
|
||||
if not question:
|
||||
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
|
||||
with db.connect() as c:
|
||||
name = None
|
||||
if body.machine_id is None:
|
||||
if question == 'required':
|
||||
raise HTTPException(422, 'Escolha a máquina em que você está.')
|
||||
else:
|
||||
row = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s AND active', (body.machine_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Máquina não encontrada ou desligada.')
|
||||
name = row['name']
|
||||
others = [r['who'] for r in c.execute('''SELECT DISTINCT COALESCE(NULLIF(o.name,''), o.email) AS who
|
||||
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
WHERE s.machine_id=%s AND s.expires_at>now() AND s.username<>%s ORDER BY 1''',
|
||||
(body.machine_id, account['email'])).fetchall()]
|
||||
if others and not body.confirm:
|
||||
raise HTTPException(409, f"{name} já tem {' e '.join(others)} ligado.")
|
||||
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=%s, machine_at=CASE WHEN %s THEN now() END,
|
||||
machine_answered=true WHERE token_hash=%s''', (body.machine_id, name is not None, account['session']))
|
||||
audit('operator_machine_chosen', operator=account['email'], machine=name or '')
|
||||
return {'machine': {'id': str(body.machine_id), 'name': name} if name else None}
|
||||
|
||||
|
||||
@router.post('/api/operator/me/password')
|
||||
def change_password(body: PasswordChange, request: Request):
|
||||
account = signed_in(request)
|
||||
@@ -82,9 +127,11 @@ 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,
|
||||
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
|
||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
|
||||
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines
|
||||
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']]
|
||||
@@ -107,20 +154,6 @@ def target(c, uid, request):
|
||||
return row
|
||||
|
||||
|
||||
def set_machines(c, uid, chosen, role):
|
||||
"""An operator's machines. Only operators have them: they limit what an
|
||||
operator sees, and every other profile sees every order."""
|
||||
if role != 'operador':
|
||||
chosen = []
|
||||
known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)',
|
||||
([str(m) for m in chosen],)).fetchall()}
|
||||
if len(known) != len(set(map(str, chosen))):
|
||||
raise HTTPException(422, 'Uma das máquinas escolhidas não existe mais.')
|
||||
c.execute('DELETE FROM dtf_local.operator_machines WHERE operator_id=%s', (uid,))
|
||||
for machine in known:
|
||||
c.execute('INSERT INTO dtf_local.operator_machines(operator_id,machine_id) VALUES(%s,%s)', (uid, machine))
|
||||
|
||||
|
||||
@router.post('/api/operator/users')
|
||||
def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
if not body.password:
|
||||
@@ -132,7 +165,6 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active))
|
||||
set_machines(c, uid, body.machines, body.role)
|
||||
audit('operator_created', operator=user, account=body.email, role=body.role)
|
||||
return {'id': str(uid)}
|
||||
|
||||
@@ -158,7 +190,6 @@ 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,))
|
||||
set_machines(c, uid, body.machines, role)
|
||||
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
|
||||
password_reset=bool(body.password))
|
||||
return {'ok': True}
|
||||
@@ -177,14 +208,10 @@ def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def set_operators(c, mid, operators):
|
||||
"""The machine's operators, from its own form. Other profiles are ignored."""
|
||||
if operators is None:
|
||||
return
|
||||
ids = [str(o) for o in operators]
|
||||
c.execute('DELETE FROM dtf_local.operator_machines WHERE machine_id=%s', (mid,))
|
||||
c.execute("""INSERT INTO dtf_local.operator_machines(operator_id,machine_id)
|
||||
SELECT id,%s FROM dtf_local.operators WHERE id=ANY(%s::uuid[]) AND role='operador'""", (mid, ids))
|
||||
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')
|
||||
@@ -201,7 +228,6 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
||||
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
||||
set_operators(c, mid, body.operators)
|
||||
machines.route(c)
|
||||
audit('machine_created', operator=user, machine=body.name)
|
||||
return {'id': str(mid)}
|
||||
@@ -217,7 +243,8 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
|
||||
body.limit_metres, mid)).fetchone():
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
set_operators(c, mid, body.operators)
|
||||
if not body.active:
|
||||
release_sessions(c, mid)
|
||||
machines.route(c)
|
||||
audit('machine_updated', operator=user, machine=body.name)
|
||||
return {'ok': True}
|
||||
@@ -227,6 +254,7 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||
"""Its orders go back to the automatic choice; its operators lose it."""
|
||||
with db.connect() as c:
|
||||
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.')
|
||||
|
||||
Reference in New Issue
Block a user