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

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:
Cauê Faleiros
2026-10-30 13:18:24 -03:00
parent 8c053596b7
commit db877c52e6
9 changed files with 288 additions and 113 deletions

View File

@@ -102,7 +102,7 @@ def backup_now(user=Depends(can('integrations'))):
@router.get('/api/operator/board')
def board(request: Request, user=Depends(operator)):
def board(user=Depends(operator)):
with db.connect() as c:
# Orders that arrived, or lost their machine, get one before the board is read.
machines.route(c)
@@ -127,7 +127,7 @@ def board(request: Request, user=Depends(operator)):
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
orders = visible(request, with_print_files(c, active + list(reversed(finished))))
orders = with_print_files(c, active + list(reversed(finished)))
# A paid notification that did not become an order is money received
# for nothing the factory will make. The board carries the count; the
# Pagamentos tab pages through them until someone records a resolution.
@@ -202,15 +202,6 @@ def assign_machines(c, orders):
return orders
def visible(request, orders):
"""An operator who works on some machines sees only their orders."""
account = request.state.operator
if account['role'] != 'operador' or not account['machines']:
return orders
mine = set(account['machines'])
return [o for o in orders if o.get('machine') and o['machine']['id'] in mine]
def with_print_files(c, orders):
"""Each order with its generated print files, the items whose final file is
approved, and the customer's corrections waiting to be approved as finals."""
@@ -264,7 +255,7 @@ def cursor_pair(first, second):
@router.get('/api/operator/orders/finished')
def finished_page(request: Request, before_created_at: datetime | None = None, before_id: UUID | None = None,
def finished_page(before_created_at: datetime | None = None, before_id: UUID | None = None,
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
"""Older finished orders, newest first, beyond the board's recent window."""
paged = cursor_pair(before_created_at, before_id)
@@ -273,7 +264,7 @@ def finished_page(request: Request, before_created_at: datetime | None = None, b
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY created_at DESC,id DESC LIMIT %s''',
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
orders = visible(request, with_print_files(c, rows[:limit]))
orders = with_print_files(c, rows[:limit])
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
'names': company_names(c, orders)}
@@ -393,7 +384,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
@router.get('/api/operator/search')
def search(request: Request, q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
"""One search over orders (any stage) and unpaid quotes: customer e-mail,
CNPJ or WhatsApp, the delivery recipient, or the order number."""
match, params = customer_match('snapshot', q)
@@ -416,7 +407,7 @@ def search(request: Request, q: str = Query(min_length=2, max_length=100), user=
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
orders = visible(request, with_print_files(c, orders))
orders = with_print_files(c, orders)
quotes = [quote_view(c, row) for row in rows]
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes)}
@@ -636,8 +627,11 @@ class MachineChoice(StrictModel):
@router.post('/api/operator/orders/{uid}/machine')
def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('print'))):
"""Send an order to a machine, or back to the automatic choice (None)."""
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
"""Send an order to a machine, or back to the automatic choice (None).
Not the operator: their pull makes an order their machine's (item 12)."""
if request.state.operator['role'] == 'operador':
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
with db.connect() as c:
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
@@ -812,11 +806,15 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
if not body.after and not body.before:
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
row = c.execute('SELECT state, machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
if not may_reorder(request.state.operator['role'], 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'
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 = {}
for side in ('after', 'before'):
other = getattr(body, side)
@@ -860,6 +858,25 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(422, 'Informe o motivo da correção.')
if back and not body.reason.strip():
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
# The machine of this session (item 12): pulling a card from the queue
# makes it that machine's ("a máquina real do card é a que puxou"); an
# operator pulls any card but moves only their machine's.
account = request.state.operator
session_machine = account['machine']
pulling = row['state'] == 'tra' and body.state == 'imp'
if account['role'] == 'operador':
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']:
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
if pulling and session_machine and (account['role'] == 'operador' or not row['machine_chosen']):
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
if machines.product_family(row) in (prints or {}).get('products', []):
row['machine_id'] = session_machine['id']
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s',
(session_machine['id'], uid))
elif account['role'] == 'operador':
raise HTTPException(409, f"A {session_machine['name']} não imprime este produto.")
# Arte conferida is the queue: what enters it has its final files approved.
if body.state in ('tra','imp'):
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
@@ -873,8 +890,14 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
if body.state == 'cor':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
(uid,row['state'],body.state,user,body.reason,back))
# Who moved it, and on which machine: the one it goes to print on, or
# else the mover's.
machine_name = (session_machine or {}).get('name')
if body.state == 'imp' and row['machine_id']:
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
(row['machine_id'],)).fetchone() or {}).get('name')
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
# A pickup reaching Finalizado has its receipt due (item 14), once.
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL,
@@ -1258,12 +1281,11 @@ def named_files(rows):
return files
def print_ready(c, request, states, only=None, paid_after=None):
def print_ready(c, states, only=None, paid_after=None):
"""The file to print for each item of the orders in these stages, in queue
order: the approved final, or before approval the generated print file
(unless the customer has sent a correction since). `only` narrows it to
these orders, `paid_after` to the orders paid since then. An operator who
works on some machines gets only those machines' orders."""
these orders, `paid_after` to the orders paid since then."""
ids = None if only is None else list(only)
rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name,
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position
@@ -1284,32 +1306,28 @@ def print_ready(c, request, states, only=None, paid_after=None):
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
ORDER BY position,order_id,item_index''',
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
# Only the orders that have a file, for their machines: not every order in the stages.
staged = assign_machines(c, c.execute('SELECT * FROM dtf_local.orders WHERE id=ANY(%s)',
(list({row['order_id'] for row in rows}),)).fetchall())
mine = {o['id'] for o in visible(request, staged)}
return [row for row in rows if row['order_id'] in mine]
return rows
@router.get('/api/operator/orders/{uid}/folder-files')
def folder_files(uid: UUID, request: Request, user=Depends(can('produce'))):
def folder_files(uid: UUID, user=Depends(can('produce'))):
"""What each item's file is called in the order's stage folder, as the
automatic folders save it: "Tratar a arte" shows where to open it."""
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
files = named_files(print_ready(c, request, (row['state'],), only=[uid]))
files = named_files(print_ready(c, (row['state'],), only=[uid]))
return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]}
@router.get('/api/operator/queue/finals')
def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))):
def queue_finals(auto: bool = False, user=Depends(can('print'))):
"""The approved final files of every order in the print queue (Arte
conferida). The browser downloads them straight from storage: a zip of
multi-GB sheets would go through the server."""
with db.connect() as c:
files = named_files(print_ready(c, request, ('tra',)))
files = named_files(print_ready(c, ('tra',)))
# The automatic folder asks whenever the queue changes; only a person's download is logged.
if not auto:
audit('queue_finals_downloaded', operator=user, files=len(files))
@@ -1325,7 +1343,7 @@ class FolderSync(StrictModel):
@router.post('/api/operator/queue/folder')
def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))):
def queue_folder(body: FolderSync, user=Depends(can('print'))):
"""What the Kanban's automatic folders should hold. `early` is Dropstar's
stage folders (2026-10-26): the files of orders in Arte recebida and Arte
conferida, and, for the orders the folders already hold, their files while
@@ -1338,12 +1356,12 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print')))
folders hold files of: a stage, 'cancelled', or nothing when the order was
deleted, so their files can be removed."""
with db.connect() as c:
rows = print_ready(c, request, ('rec', 'tra') if body.early else ('tra',))
rows = print_ready(c, ('rec', 'tra') if body.early else ('tra',))
if body.early and body.held:
rows += print_ready(c, request, ('imp', 'rev', 'fin'), only=body.held)
rows += print_ready(c, ('imp', 'rev', 'fin'), only=body.held)
if body.early and body.since:
seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows}
rows += [r for r in print_ready(c, request, ('imp', 'rev', 'fin'), paid_after=body.since)
rows += [r for r in print_ready(c, ('imp', 'rev', 'fin'), paid_after=body.since)
if (r['order_id'], r['item_index'], r['upload_id']) not in seen]
files = named_files(rows)
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',

View File

@@ -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.')