diff --git a/app/api/operator.py b/app/api/operator.py index 762a43e..43c994d 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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)', diff --git a/app/api/users.py b/app/api/users.py index 90eef74..6f0c4db 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -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.') diff --git a/app/core/auth.py b/app/core/auth.py index 0b9b180..0726568 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -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 diff --git a/app/machines.py b/app/machines.py index b6534d1..a9dcb8d 100644 --- a/app/machines.py +++ b/app/machines.py @@ -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']) diff --git a/app/schema.sql b/app/schema.sql index e26a6d3..68cfeed 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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; diff --git a/tests/users_test.py b/tests/users_test.py index c421f7b..ed92e7b 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -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)) diff --git a/web/kanban.css b/web/kanban.css index fc29217..b5d04d2 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -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} diff --git a/web/kanban.html b/web/kanban.html index 339b296..9a3222e 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -41,6 +41,7 @@ +