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

View File

@@ -165,6 +165,10 @@ ADMINS = ('superadmin', 'admin')
COORDINATION = ('gestao',)
MANAGERS = ADMINS + COORDINATION
RELEASERS = ('revisor', 'admin', 'superadmin')
# Who is asked "Em qual máquina você está?" after signing in (Dropstar, 2026-10-30):
# the operator must answer; Gestão and the administrators may say they are on
# none. The other profiles are never asked.
MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'optional'}
MOVERS = MANAGERS + tuple(MOVES)
@@ -194,14 +198,17 @@ 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 FROM dtf_local.operator_sessions s
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
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
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
if row:
row['machines'] = [str(r['machine_id']) for r in c.execute(
'SELECT machine_id FROM dtf_local.operator_machines WHERE operator_id=%s', (row['id'],)).fetchall()]
if not row:
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
# The machine this session works on (item 12), or None.
machine_id, machine_name = row.pop('machine_id'), row.pop('machine_name')
row['machine'] = {'id': str(machine_id), 'name': machine_name} if machine_id else None
row['session'] = digest
request.state.operator = row
return row

View File

@@ -94,9 +94,13 @@ def rows(c, with_operators=False):
load = loads(c)
operators = {}
if with_operators:
for r in c.execute('''SELECT om.machine_id, o.id, o.name, o.email FROM dtf_local.operator_machines om
JOIN dtf_local.operators o ON o.id=om.operator_id ORDER BY o.name, o.email''').fetchall():
operators.setdefault(str(r['machine_id']), []).append({'id': str(r['id']), 'name': r['name'] or r['email']})
# Who is on it now: the open sessions that chose it (item 12).
for r in c.execute('''SELECT DISTINCT ON (s.machine_id, o.id) s.machine_id, o.id, o.name, o.email, s.machine_at
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
WHERE s.machine_id IS NOT NULL AND s.expires_at>now()
ORDER BY s.machine_id, o.id, s.machine_at''').fetchall():
operators.setdefault(str(r['machine_id']), []).append(
{'id': str(r['id']), 'name': r['name'] or r['email'], 'since': r['machine_at']})
result = []
for m in machines:
key = str(m['id'])

View File

@@ -414,3 +414,15 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL;
-- The machine a session works on (Dropstar's third round, item 12, 2026-10-30):
-- chosen after signing in, per session, so one person may be on two machines,
-- one per computer. machine_answered: the question was answered, "Não estou em
-- máquina" included. The links Usuários showed before (operator_machines)
-- are no longer read.
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
-- Thales · máquina2".
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;

View File

@@ -116,7 +116,7 @@ def run():
admin.call(path, {}, expected=403)
admin.call('/operator/events', expected=403)
admin.call('/operator/users', {'name': 'Op', 'email': emails['operador'], 'role': 'operador',
'password': PASSWORD, 'machines': [uv]})
'password': PASSWORD})
admin.call('/operator/users', {'name': 'Vendas', 'email': emails['vendedor'], 'role': 'vendedor',
'password': PASSWORD})
admin.call('/operator/users', {'name': 'Again', 'email': emails['vendedor'], 'role': 'vendedor',
@@ -145,26 +145,45 @@ def run():
# On the UV machine of this test, whatever the others carry.
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
# The operator of the UV machine sees only its orders and prints them:
# Arte conferida to Imprimindo to Revisão, nothing else (Dropstar, 2026-10-23).
# The operator prints: Arte conferida to Imprimindo to Revisão, nothing
# else (Dropstar, 2026-10-23). After signing in they say which machine
# they are on, and must (item 12, 2026-10-30); they see the whole board.
op = signed_in(emails['operador'])
seen = {o['id'] for o in op.call('/operator/board')['orders']}
assert str(uv_o) in seen and str(textil_o) not in seen, seen
assert sorted(op.call('/operator/me')['moves']) == [['imp', 'rev'], ['imp', 'tra'], ['rev', 'imp'], ['tra', 'imp']]
me = op.call('/operator/me')
assert (me['machine_question'], me['machine_answered'], me['machine']) == ('required', False, None), me
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in op.call('/operator/board')['orders']}
assert sorted(me['moves']) == [['imp', 'rev'], ['imp', 'tra'], ['rev', 'imp'], ['tra', 'imp']]
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,))
op.call(f'/operator/orders/{uv_o}/move', {'state': 'rev', 'version': 0, 'reason': ''}, expected=409)
op.call('/operator/me/machine', {'machine_id': None}, expected=422)
op.call('/operator/me/machine', {'machine_id': uv})
assert op.call('/operator/me')['machine'] == {'id': uv, 'name': f'UV {tag}'}
op.call(f'/operator/orders/{uv_o}/move', {'state': 'cor', 'version': 0, 'reason': 'borrou'}, expected=403)
printed = op.call(f'/operator/orders/{uv_o}/move', {'state': 'rev', 'version': 0, 'reason': ''})
# The history names the machine with the person.
last = op.call(f'/operator/orders/{uv_o}/history')[-1]
assert (last['operator'], last['machine']) == (emails['operador'], f'UV {tag}'), last
refused = op.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''},
expected=403)
assert refused['detail'] == 'Só o Revisor manda o pedido para Finalizado.', refused
op.call(f'/operator/orders/{uv_o}/cancel', {'note': 'não pode'}, expected=403)
op.call('/operator/users', expected=403)
op.call('/operator/payment-events', expected=403)
# Sent to the UV machine by hand, the Têxtil order appears for them.
su.call(f'/operator/orders/{textil_o}/machine', {'machine_id': uv}, operator=True)
assert str(textil_o) in {o['id'] for o in op.call('/operator/board')['orders']}
# Another machine's card shows, but only who is on that machine moves it,
# and the operator does not send orders to machines.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (textil_o,))
refused = op.call(f'/operator/orders/{textil_o}/move', {'state': 'rev', 'version': 0, 'reason': ''}, expected=403)
assert 'outra máquina' in refused['detail'], refused
op.call(f'/operator/orders/{textil_o}/machine', {'machine_id': uv}, expected=403)
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (textil_o,))
# Gestão and the administrators may be on no machine; the others are never asked.
assert admin.call('/operator/me')['machine_question'] == 'optional'
admin.call('/operator/me/machine', {'machine_id': None})
assert admin.call('/operator/me')['machine_answered'] and admin.call('/operator/me')['machine'] is None
# The seller reads and changes nothing.
seller = signed_in(emails['vendedor'])
@@ -305,15 +324,14 @@ def run():
seller.call('/operator/me/password', {'current': 'oito-888', 'new': 'outra-senha-de-teste'})
signed_in(emails['vendedor'], 'outra-senha-de-teste').call('/operator/me')
# A second Têxtil machine, its operators ticked on the machine itself: only
# operators are linked, the seller is not.
op_id, seller_id = users[emails['operador']]['id'], users[emails['vendedor']]['id']
textil2 = admin.call('/operator/machines', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'operators': [op_id, seller_id]})['id']
# A second Têxtil machine. Who is on each machine is who chose it after
# signing in: Usuários only shows it (item 12).
op_id = users[emails['operador']]['id']
textil2 = admin.call('/operator/machines', {'name': f'Têxtil B {tag}', 'products': ['textil']})['id']
machines.append(textil2)
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
assert set(next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines']) == {uv, textil2}
assert listed[textil2]['operators'] == [] and [o['id'] for o in listed[uv]['operators']] == [op_id], listed[uv]
assert next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines'] == [uv]
# The next order goes to the one with fewer metres open.
target = expected_machine(su, 'textil')
with db.connect() as c:
@@ -422,6 +440,37 @@ def run():
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
(None, 'imprimindo', 'ripando')
# Pulled by an operator, a queued card becomes their machine's, whatever
# machine it had (item 12); a machine that does not print its product
# does not take it. Someone already on a machine is a warning, not a refusal.
free = admin.call('/operator/machines', {'name': f'Livre {tag}', 'products': ['textil']})['id']
machines.append(free)
with db.connect() as c:
queued = [order_fixture(c, owner, 'file') for _ in range(2)]
made.extend(queued)
for _, oid in queued:
upload = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
(upload, owner, f'test/{upload}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
(textil, oid))
taken_id, other_id = (str(oid) for _, oid in queued)
wrong = op.call(f'/operator/orders/{other_id}/move', {'state': 'imp', 'version': 0, 'reason': ''}, expected=409)
assert wrong['detail'] == f'A UV {tag} não imprime este produto.', wrong
op.call('/operator/me/machine', {'machine_id': free})
taken = op.call(f'/operator/orders/{taken_id}/move', {'state': 'imp', 'version': 0, 'reason': ''})
assert str(taken['machine_id']) == free and taken['machine_chosen'], taken
assert op.call(f'/operator/orders/{taken_id}/history')[-1]['machine'] == f'Livre {tag}'
warned = admin.call('/operator/me/machine', {'machine_id': free}, expected=409)
assert warned['detail'] == f'Livre {tag} já tem Op ligado.', warned
admin.call('/operator/me/machine', {'machine_id': free, 'confirm': True})
on_free = next(m for m in admin.call('/operator/machines')['machines'] if m['id'] == free)['operators']
assert {o['name'] for o in on_free} == {'Op', 'Marcus'}, on_free
designer.call('/operator/me/machine', {'machine_id': free}, expected=403)
# Switched off, a machine gives its automatic orders to another one.
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))

View File

@@ -75,6 +75,16 @@ input[type=file]{font-size:14px;color:var(--muted);max-width:100%}
.tinydot:empty{display:none}
/* .morewrap pushes the panel's menu right; here the search box already does. */
.morewrap.account{margin-left:0}
/* The session's machine (item 12): green when on one; a click changes it. */
.mymachine{flex-shrink:0;display:inline-flex;align-items:center;gap:6px;height:36px;padding:0 12px;border:1px solid var(--line2);border-radius:8px;background:transparent;color:var(--muted);font:inherit;font-size:13.5px;font-weight:700;cursor:pointer;white-space:nowrap}
.mymachine.on{border-color:var(--ok);color:var(--ok);background:rgba(111,209,156,.08)}
.mymachine[hidden]{display:none}
.card.mine{border-color:var(--ok);box-shadow:inset 0 0 0 1px var(--ok)}
.col-head .slot-row.mine{margin:0 -6px;padding:3px 6px;border:1px solid var(--ok);border-radius:8px}
.machine-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin:14px 0}
.machine-choice{display:flex;flex-direction:column;align-items:flex-start;gap:3px;padding:14px;border:1px solid var(--line2);border-radius:10px;background:var(--card2);color:var(--tx);font:inherit;text-align:left;cursor:pointer}
.machine-choice b{font-size:15px}
.machine-choice:hover,.machine-choice.on{border-color:var(--ok)}
.account .btn{min-width:38px;padding:0 10px;font-weight:800;letter-spacing:.02em}
.account .menu{min-width:240px}
.menu-head{display:flex;flex-direction:column;gap:2px;padding:8px 10px 10px;border-bottom:1px solid var(--line2);margin-bottom:4px}

View File

@@ -41,6 +41,7 @@
<option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option>
</select>
</div>
<button class="mymachine" id="my-machine" type="button" hidden></button>
<div class="morewrap account">
<button class="btn ghost" id="account" type="button" aria-haspopup="menu" aria-label="Minha conta"><span id="initials">·</span></button>
<div class="menu" id="account-menu" role="menu" hidden>
@@ -116,10 +117,10 @@
<div class="pagehead"><h1>Usuários</h1><button class="btn primary" id="new-user" type="button">Novo usuário</button></div>
<p class="faint stats-note">Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página.
Gestão: tudo, menos usuários; no quadro só puxa para trás, com motivo (Correção ou voltar uma etapa). Designer: vê todos os pedidos, aprova e recusa o arquivo final, pede correção.
Operador: ligado a uma máquina, vê só os pedidos dela; imprime e passa para a Revisão. Revisor: confere a folha impressa e libera para Finalizado; o Administrador também pode liberar.
Operador: escolhe a máquina ao entrar; vê o quadro todo, puxa da fila para a máquina dele, imprime e passa para a Revisão, e só move os cards da máquina dele. Revisor: confere a folha impressa e libera para Finalizado; o Administrador também pode liberar.
Vendedor: só consulta. Financeiro: vê o quadro, Pagamentos, Números e Cotações e cancela pedido, com o motivo; não move card nem mexe em arquivo.
Retrabalho: a Gestão abre, com a causa; o Administrador autoriza.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquinas</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquina agora</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
<p class="faint stats-note">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
<div class="mtiles" id="machines-list"></div>

View File

@@ -48,6 +48,12 @@ const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão'
// server's own list (app/core/auth.py MOVES), never worked out here.
const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to);
const mayReorder=state=>!!ME?.reorder?.includes(state);
// The session's machine (item 12). An operator pulls any card from the queue,
// which becomes their machine's, and moves only their machine's cards; the
// 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);
// Which tabs each capability opens.
// Vendedor and Financeiro consult Cotações and Números without acting there.
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
@@ -550,7 +556,7 @@ let seenOrders=null, seenPending=null, unseen=0;
async function load(quiet=false){
try{
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
board=absorb(loaded);ME=me;applyRole();
board=absorb(loaded);ME=me;applyRole();paintMyMachine();
noticeNew(quiet);
const known=new Set(board.orders.map(o=>o.id));
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
@@ -558,6 +564,7 @@ async function load(quiet=false){
$('login').hidden=true;$('app').hidden=false;
if(!quiet)say('Atualizado às '+new Date().toLocaleTimeString('pt-BR')+tinyNotice,false,tinyNotice?6000:2500);
render();
askMachine();
syncFolder();
}catch(e){
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
@@ -631,8 +638,8 @@ const PRINTING={imprimindo:['Imprimindo','ok','Já ripou, está rodando'],
// machines with nothing printing share one line. An operator who works on
// some machines sees those.
function printingRoom(){
const cap=board.printing_cap, mine=ME?.role==='operador'&&ME.machines?.length?ME.machines:null;
const list=(board.machines||[]).filter(m=>(m.active||m.states.imp)&&(!mine||mine.includes(m.id)));
const cap=board.printing_cap;
const list=(board.machines||[]).filter(m=>m.active||m.states.imp);
if(!list.length)return null;
const room=node('div',undefined,'slots'), free=[];
for(const m of list){
@@ -640,7 +647,7 @@ function printingRoom(){
.sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1));
const n=Math.max(m.states.imp||0,here.length);
if(!n){free.push(m.name);continue;}
const row=node('div',undefined,'slot-row');
const row=node('div',undefined,'slot-row'+(myMachine()?.id===m.id?' mine':''));
row.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':' · '+(cap-n)+' vaga');
// The places go under the name when the column is too narrow for both.
const places=node('div',undefined,'slot-places');
@@ -802,8 +809,9 @@ function renderBoard(){
const isTest=order=>order.payment?.provider==='teste';
function card(order){
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;
c.draggable=!order.cancelled_at&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
c.draggable=!order.cancelled_at&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
if(order.id===openOrder)c.classList.add('open');
if(isMine(order)&&order.state!=='fin'&&!order.cancelled_at)c.classList.add('mine');
const s=order.snapshot;
const top=node('div',undefined,'row');
top.append(node('span','#'+order.number,'num'),originTag(order),...(isTest(order)?[node('span','TESTE','tag-teste')]:[]),node('span',ago(order.updated_at),'age'));
@@ -1038,14 +1046,15 @@ function moves(order){
if(may('print')){const actions=node('div',undefined,'stepactions');
const b=button('Prova OK',()=>proofOk(order),'btn primary');b.dataset.proof='';actions.append(b);text.append(actions);}
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
}else if(mayMove(order.state,next)){
}else if(mayMove(order.state,next)&&mayAct(order)){
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
}
}
if(!row.children.length&&!step)row.append(node('span',order.state==='fin'?'Pedido concluído.'
:!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.'
:order.state==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.','muted'));
// Undo a mistaken move: one stage back, internal reason, no customer message.
const previous=mayMove(order.state,board.back?.[order.state])?board.back?.[order.state]:null;
const previous=mayMove(order.state,board.back?.[order.state])&&mayAct(order)?board.back?.[order.state]:null;
const sub=node('div',undefined,'subactions');
const backForm=node('form',undefined,'reason');backForm.hidden=true;forms.push(backForm);
if(previous){
@@ -1444,7 +1453,8 @@ function historySection(order,rows,section){
if(reason)text.append(node('span',' · '+reason,'muted'));
li.append(text,node('small',when(at)));return li;
};
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),r.operator,r.created_at,r.reason));
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
r.operator+(r.machine?' · '+r.machine:''),r.created_at,r.reason));
list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
paidOutside(order)?ORIGINS[order.origin]+' · pago fora do site ('+PAID_OUTSIDE[order.payment.method]+') · registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
order.created_at,paidOutside(order)?order.payment.note:''));
@@ -1453,11 +1463,53 @@ function historySection(order,rows,section){
// ---- Machines and users ----------------------------------------------------
// "Em qual máquina você está?" (Dropstar's third round, item 12): after signing
// in, required for the operator, and for Gestão and the administrators with
// "Não estou em máquina". Per session: one person on two computers runs two
// machines. Someone else already on the machine is a warning, not a refusal.
let askingMachine=false;
function askMachine(again=false){
if(!ME?.machine_question||askingMachine||(ME.machine_answered&&!again))return;
askingMachine=true;
const required=ME.machine_question==='required';
const back=node('div',undefined,'modal');const box=node('div',undefined,'modal-box');
const close=()=>{back.remove();askingMachine=false;};
box.append(node('h2','Em qual máquina você está?'),
node('p','O que você puxar para Imprimindo vai para ela, e o histórico grava a máquina com o seu nome.','faint'));
const choose=async(id,confirm=false)=>{
try{await api('/me/machine',{machine_id:id,confirm});close();await load(true);}
catch(e){if(e.status===409&&!confirm&&window.confirm(e.message+' Continuar mesmo assim?'))return choose(id,true);say(e.message,true);}};
const list=node('div',undefined,'machine-choices');
for(const m of (board.machines||[]).filter(m=>m.active)){
const b=node('button',undefined,'machine-choice'+(myMachine()?.id===m.id?' on':''));b.type='button';
b.append(node('b',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e '),'faint'));
b.onclick=()=>choose(m.id);list.append(b);
}
if(!list.children.length)list.append(node('p','Nenhuma máquina ativa. Peça ao Administrador para cadastrar em Usuários › Máquinas.','faint'));
const row=node('div',undefined,'modal-actions');
if(!required)row.append(button('Não estou em máquina',()=>choose(null),'btn ghost'));
if(again&&ME.machine_answered)row.append(button('Cancelar',close,'btn ghost'));
if(required&&!ME.machine_answered)row.append(button('Sair',()=>$('logout').click(),'btn ghost'));
box.append(list,...(row.children.length?[row]:[]));
back.append(box);document.body.append(back);
}
// The machine beside the account button: green, and a click changes it.
function paintMyMachine(){
const pill=$('my-machine');
pill.hidden=!ME?.machine_question;
if(pill.hidden)return;
pill.replaceChildren(icon(ICON_PRINTER),myMachine()?myMachine().name:'Sem máquina');
pill.classList.toggle('on',!!myMachine());
pill.title=myMachine()?'Você está na '+myMachine().name+'. Clique para trocar.':'Você não está em máquina. Clique para escolher.';
}
$('my-machine').onclick=()=>askMachine(true);
// The order's machine: chosen, or the first that prints its product.
function machineCard(order){
const box=node('div',undefined,'fcard');box.append(node('p','Máquina','eyebrow'));
const current=order.machine;
if(!may('print')||!board.machines?.length){
// The operator's orders go to the machine that pulls them (item 12).
if(!may('print')||ME?.role==='operador'||!board.machines?.length){
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'));return box;
}
const select=node('select',undefined,'machine-select');select.setAttribute('aria-label','Máquina do pedido');
@@ -1499,7 +1551,7 @@ function renderUsers(){
const rows=users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email,'faint block'));
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—'));
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):'—');
const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint');
const actions=node('td',undefined,'actions');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
@@ -1533,7 +1585,8 @@ function machineTile(m){
tile.append(head,node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','meta'),
...(m.active||m.open_orders?[bar,used]:[]),
node('span',stages||'Nenhum pedido em aberto','meta'),
node('span',m.operators.length?'Operadores: '+m.operators.map(o=>o.name).join(', '):'Nenhum operador ligado','meta'),actions);
node('span',m.operators.length?'Ligados agora: '+m.operators.map(o=>o.name+(o.since?' (desde '+new Date(o.since).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'})+')':'')).join(', ')
:'Ninguém ligado agora','meta'),actions);
return tile;
}
// One dialog for creating and editing, for users and machines alike.
@@ -1560,13 +1613,9 @@ function userForm(u){
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'8 caracteres ou mais';
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
const picks=pills(usersData.machines.map(m=>[m.id,m.name]),u?.machines||[]);
const machinesField=group('Máquinas',picks);
const syncMachines=()=>{machinesField.hidden=role.value!=='operador'||!usersData.machines.length;};role.onchange=syncMachines;syncMachines();
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
field(editing?'Nova senha':'Senha inicial',pass),activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
machines:role.value==='operador'?picks.values():[],
password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
@@ -1578,15 +1627,12 @@ function machineForm(m){
const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal';
limit.placeholder='Sem limite';limit.value=m?.limit_metres??'';
const unit=node('div',undefined,'unit');unit.append(limit,node('span','metros em aberto','faint'));
const operators=usersData.users.filter(u=>u.role==='operador');
const crew=pills(operators.map(u=>[u.id,u.name||u.email]),(m?.operators||[]).map(o=>o.id));
const active=node('input');active.type='checkbox';active.checked=m?m.active:true;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativa (recebe pedidos)');
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),group('Imprime',products),field('Limite',unit),
group('Operadores',operators.length?crew:node('span','Nenhum operador cadastrado.','faint')),activeLabel],async()=>{
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),group('Imprime',products),field('Limite',unit),activeLabel],async()=>{
if(!products.values().length)throw new Error('Marque o que a máquina imprime.');
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(),
limit_metres:limit.value?Number(limit.value):null,operators:crew.values()});
limit_metres:limit.value?Number(limit.value):null});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
});
}