diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 06c4434..e4d0426 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test thumbnail_backfill_test launch_reset_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test thumbnail_backfill_test launch_reset_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/artwork.py b/app/api/artwork.py index 76cd63e..4b6ed31 100644 --- a/app/api/artwork.py +++ b/app/api/artwork.py @@ -9,7 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException from ..core import db from ..artwork import submit_files -from ..core.auth import operator +from ..core.auth import can, operator from ..core.models import ArtworkSubmission, UploadStart from ..runtime import file_rows, operator_identity from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status @@ -17,7 +17,7 @@ from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upl router = APIRouter() @router.post('/api/operator/orders/{oid}/uploads') -def begin_final(oid: UUID, body: UploadStart, user=Depends(operator)): +def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))): with db.connect() as c: row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone() if not row: raise HTTPException(404, 'Order not found') @@ -29,15 +29,15 @@ def final_status(uid: UUID, user=Depends(operator)): return upload_status(uid,session_id=operator_identity(user)) @router.post('/api/operator/uploads/{uid}/parts/{number}') -def final_part(uid: UUID, number: int, user=Depends(operator)): +def final_part(uid: UUID, number: int, user=Depends(can('produce'))): return part_url(uid,number,session_id=operator_identity(user)) @router.post('/api/operator/uploads/{uid}/complete') -def final_complete(uid: UUID, user=Depends(operator)): +def final_complete(uid: UUID, user=Depends(can('produce'))): return complete_upload(uid,session_id=operator_identity(user)) @router.delete('/api/operator/uploads/{uid}') -def final_cancel(uid: UUID, user=Depends(operator)): +def final_cancel(uid: UUID, user=Depends(can('produce'))): return cancel_upload(uid,session_id=operator_identity(user)) @router.get('/api/operator/orders/{oid}/files') @@ -46,7 +46,7 @@ def operator_files(oid: UUID, user=Depends(operator)): return file_rows(c,oid) @router.post('/api/operator/orders/{oid}/final-files') -def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(operator)): +def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))): with db.connect() as c: order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone() if not order: raise HTTPException(404, 'Order not found') diff --git a/app/api/operator.py b/app/api/operator.py index b5019a7..ff9b49d 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -11,7 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from fastapi.responses import RedirectResponse from ..core import db -from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, operator, +from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator, login_failed, password_matches, throttle) from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel from ..printjobs import queue as queue_print_files @@ -89,7 +89,7 @@ def backup_status(c): @router.get('/api/operator/board') -def board(user=Depends(operator)): +def board(request: Request, user=Depends(operator)): with db.connect() as c: # Everything still in progress, however old: an operator must never lose a # card they can act on. Finished orders are terminal and only accumulate, @@ -112,7 +112,7 @@ def board(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 = with_print_files(c, active + list(reversed(finished))) + orders = visible(request, 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. @@ -125,6 +125,8 @@ def board(user=Depends(operator)): 'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup}, 'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN, 'finished_shown': len(finished), 'finished_total': finished_total, + 'machines': [{**m, 'id': str(m['id'])} for m in c.execute( + 'SELECT id,name,products,active FROM dtf_local.machines ORDER BY created_at,name').fetchall()], 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes), 'names': company_names(c, orders, quotes), 'pending_total': pending_total, 'approved_total': approved_total} @@ -162,6 +164,33 @@ def company_names(c, *groups): FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'""" +def product_family(order): + """Têxtil or UV, by the order's first item: what a machine prints.""" + items = (order.get('snapshot') or {}).get('items') or [{}] + return 'uv' if items[0].get('mode') in ('uvfile', 'uv') else 'textil' + + +def assign_machines(c, orders): + """Each order's machine: the one someone chose, or else the first active + machine that prints its product. None while no machine is registered.""" + machines = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY created_at,name').fetchall() + by_id = {str(m['id']): m for m in machines} + for order in orders: + chosen = by_id.get(str(order.get('machine_id') or '')) + machine = chosen or next((m for m in machines if m['active'] and product_family(order) in m['products']), None) + order['machine'] = {'id': str(machine['id']), 'name': machine['name'], 'chosen': bool(chosen)} if machine else None + 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.""" @@ -185,7 +214,7 @@ def with_print_files(c, orders): order['final_items'] = sorted(row['item_index'] for row in finals if row['order_id'] == order['id']) order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')} for row in fixes if row['order_id'] == order['id']] - return orders + return assign_machines(c, orders) def cursor_pair(first, second): @@ -195,7 +224,7 @@ def cursor_pair(first, second): @router.get('/api/operator/orders/finished') -def finished_page(before_created_at: datetime | None = None, before_id: UUID | None = None, +def finished_page(request: Request, 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) @@ -204,7 +233,7 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N ''' + ('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 = with_print_files(c, rows[:limit]) + orders = visible(request, with_print_files(c, rows[:limit])) return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders), 'names': company_names(c, orders)} @@ -212,7 +241,7 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N @router.get('/api/operator/payment-events') def payment_events(state: Literal['open','resolved','all'] = 'open', offset: int = Query(default=0, ge=0), - limit: int = Query(default=20, ge=1, le=100), user=Depends(operator)): + limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))): """Payments that needed a person, newest first: open ones to act on, resolved ones as history.""" where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state] with db.connect() as c: @@ -230,7 +259,7 @@ def events(provider: Literal['tiny','whatsapp'] | None = None, status: Literal['delivered','queued','failing'] | None = None, event: Literal['payment_approved','production_started','correction_needed','ready'] | None = None, order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0), - limit: int = Query(default=20, ge=1, le=100), user=Depends(operator)): + limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))): """The integration send log, newest first, filtered, by page with a total.""" clauses, params = [], [] if provider: @@ -324,7 +353,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime @router.get('/api/operator/search') -def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)): +def search(request: Request, 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) @@ -347,13 +376,13 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)) 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 = with_print_files(c, orders) + orders = visible(request, 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)} @router.post('/api/operator/quotes/{uid}/approve') -def approve(uid: UUID, body: Review, user=Depends(operator)): +def approve(uid: UUID, body: Review, user=Depends(can('manage'))): with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: @@ -361,7 +390,7 @@ def approve(uid: UUID, body: Review, user=Depends(operator)): return quote_review.approve(c, row, body.items, user) @router.post('/api/operator/quotes/{uid}/test-order') -def test_order(uid: UUID, user=Depends(operator)): +def test_order(uid: UUID, user=Depends(can('manage'))): """An order for an approved quote without payment, to try the Kanban, files and print flow in production. Marked TEST on the board, never sent to Tiny or WhatsApp, and audited.""" @@ -379,7 +408,7 @@ def test_order(uid: UUID, user=Depends(operator)): @router.post('/api/operator/quotes/{uid}/discard') -def discard_quote(uid: UUID, user=Depends(operator)): +def discard_quote(uid: UUID, user=Depends(can('manage'))): """An unpaid quote leaves the Kanban and can no longer be paid. Its files keep their normal expiry; a payment that still arrives for it is refused and listed under Pagamentos.""" @@ -397,7 +426,7 @@ def discard_quote(uid: UUID, user=Depends(operator)): @router.post('/api/operator/orders/{uid}/delete') -def delete_order(uid: UUID, user=Depends(operator)): +def delete_order(uid: UUID, user=Depends(can('manage'))): """Deletes a test order, or a paid order already cancelled, with its history and files' records. A paid order in progress must be cancelled first, with its reason. A test order's quote is unpaid again; a cancelled @@ -423,7 +452,7 @@ def delete_order(uid: UUID, user=Depends(operator)): @router.post('/api/operator/orders/{uid}/cancel') -def cancel_order(uid: UUID, body: Resolution, user=Depends(operator)): +def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))): """A paid order leaves the board but keeps its payment and history. Nothing is refunded here (that is done at the provider) and Tiny is not told.""" with db.connect() as c: @@ -436,6 +465,24 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(operator)): return {'ok': True} +class MachineChoice(StrictModel): + machine_id: UUID | None = None + + +@router.post('/api/operator/orders/{uid}/machine') +def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('produce'))): + """Send an order to a machine, or back to the automatic choice (None).""" + 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.') + row = c.execute('UPDATE dtf_local.orders SET machine_id=%s WHERE id=%s RETURNING number', + (body.machine_id, uid)).fetchone() + if not row: + raise HTTPException(404, 'Pedido não encontrado.') + audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user) + return {'ok': True} + + class QueuePlace(StrictModel): """Where a dragged card lands: between two orders of its column, either of them absent at the top or the bottom.""" @@ -447,7 +494,7 @@ QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))' @router.post('/api/operator/orders/{uid}/queue') -def queue_place(uid: UUID, body: QueuePlace, user=Depends(operator)): +def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))): """An order's place in its column: by default its payment time; dragged, halfway between the orders it was dropped between. It neither changes the order's stage nor counts as activity (the stalled clock keeps running).""" @@ -477,7 +524,7 @@ def queue_place(uid: UUID, body: QueuePlace, user=Depends(operator)): @router.post('/api/operator/orders/{uid}/move') -def move(uid: UUID, body: Move, user=Depends(operator)): +def move(uid: UUID, body: Move, user=Depends(can('produce'))): with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: @@ -524,7 +571,7 @@ def move(uid: UUID, body: Move, user=Depends(operator)): return changed @router.post('/api/operator/orders/{uid}/print-files') -def regenerate(uid: UUID, user=Depends(operator)): +def regenerate(uid: UUID, user=Depends(can('produce'))): """Queue generation again for items that failed or went to manual preparation, and for orders paid before the generator existed.""" with db.connect() as c: @@ -540,7 +587,7 @@ def regenerate(uid: UUID, user=Depends(operator)): return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall() @router.post('/api/operator/payment-events/{uid}/resolve') -def resolve_payment(uid: UUID, body: Resolution, user=Depends(operator)): +def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))): with db.connect() as c: row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s WHERE id=%s AND (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') AND resolved_at IS NULL RETURNING id''', @@ -557,7 +604,7 @@ def tiny_status(): **tiny.TinyAuth().status()} @router.post('/api/operator/tiny/connect') -def tiny_connect(user=Depends(operator)): +def tiny_connect(user=Depends(can('manage'))): """Start the one-time authorisation of this system in the client's Tiny.""" if not tiny.configured(): raise HTTPException(503, 'Tiny application is not configured') @@ -565,7 +612,7 @@ def tiny_connect(user=Depends(operator)): return {'url': tiny.TinyAuth().authorize_url(user)} @router.post('/api/operator/tiny/test') -def tiny_test(user=Depends(operator)): +def tiny_test(user=Depends(can('manage'))): """Read one order and one contact from Tiny. Creates nothing.""" if not tiny.configured(): raise HTTPException(503, 'Tiny application is not configured') @@ -577,7 +624,7 @@ def tiny_test(user=Depends(operator)): return {'ok': all(v == 'ok' for v in results.values()), 'results': results} @router.post('/api/operator/mercadopago/check') -def mercadopago_check(user=Depends(operator)): +def mercadopago_check(user=Depends(can('manage'))): """The Mercado Pago account behind the configured token; reads only.""" if payment.name != 'mercadopago': raise HTTPException(409, 'Mercado Pago não está configurado') @@ -694,7 +741,7 @@ def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(o @router.get('/api/operator/queue/finals') -def queue_finals(user=Depends(operator)): +def queue_finals(request: Request, user=Depends(can('produce'))): """The approved final files of every order in the print queue, in queue order, each named after its order so a folder of them stays readable. The browser downloads them straight from storage: a zip of multi-GB sheets @@ -704,6 +751,10 @@ def queue_finals(user=Depends(operator)): JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE o.state='fil' AND o.cancelled_at IS NULL AND {FINAL_OK} ORDER BY COALESCE(o.queue_key, extract(epoch FROM o.created_at)),o.id,f.item_index,f.created_at''').fetchall() + # A machine's operator downloads only that machine's queue. + queued = assign_machines(c, c.execute("SELECT * FROM dtf_local.orders WHERE state='fil' AND cancelled_at IS NULL").fetchall()) + mine = {o['number'] for o in visible(request, queued)} + rows = [row for row in rows if row['number'] in mine] files, names = [], set() for row in rows: prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}" diff --git a/app/api/users.py b/app/api/users.py new file mode 100644 index 0000000..036b717 --- /dev/null +++ b/app/api/users.py @@ -0,0 +1,210 @@ +"""Kanban users and print machines, managed by the administrators. + +There is no e-mail yet, so an administrator creates each account with a +first password and the person changes it in "Minha senha". The superadmin is +the system's own account, set from the console (python -m app.operators); +administrators manage everyone else. Nobody can remove, disable or demote +themselves, so the last administrator cannot lock the team out by accident. +""" +import re +from typing import Literal +from uuid import UUID, uuid4 + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import Field, field_validator + +from ..core import db +from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in +from ..core.models import StrictModel + +router = APIRouter() + +class UserIn(StrictModel): + # The profiles an administrator may give; superadmin only comes from the console. + name: str = Field(min_length=1, max_length=80) + email: str = Field(min_length=3, max_length=254) + role: Literal['admin', 'gestao', 'operador', 'vendedor'] + password: str | None = Field(default=None, min_length=12, max_length=128) + active: bool = True + machines: list[UUID] = Field(default_factory=list, max_length=50) + + @field_validator('email') + @classmethod + def email_valid(cls, value): + value = value.strip().lower() + if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value): + raise ValueError('Informe um e-mail válido.') + return value + + +class MachineIn(StrictModel): + name: str = Field(min_length=1, max_length=60) + products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2) + active: bool = True + + +class PasswordChange(StrictModel): + current: str = Field(min_length=1, max_length=128) + new: str = Field(min_length=12, max_length=128) + + +@router.get('/api/operator/me') +def me(request: Request): + """Who is signed in, and what the Kanban should offer them.""" + account = signed_in(request) + return {'email': account['email'], 'name': account['name'], 'role': account['role'], + 'machines': account['machines'], + 'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)} + + +@router.post('/api/operator/me/password') +def change_password(body: PasswordChange, request: Request): + account = signed_in(request) + with db.connect() as c: + row = c.execute('SELECT password_hash FROM dtf_local.operators WHERE id=%s', (account['id'],)).fetchone() + if not password_matches(body.current, row['password_hash']): + raise HTTPException(403, 'A senha atual não confere.') + c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.new), account['id'])) + audit('operator_password_changed', operator=account['email']) + return {'ok': True} + + +def user_rows(c): + 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 + 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']] + return rows + + +@router.get('/api/operator/users') +def list_users(user=Depends(can('users'))): + with db.connect() as c: + return {'users': user_rows(c), 'machines': machine_rows(c)} + + +def target(c, uid, request): + """The account to change, refusing a superadmin unless one is asking.""" + row = c.execute('SELECT * FROM dtf_local.operators WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Usuário não encontrado.') + if row['role'] == 'superadmin' and request.state.operator['role'] != 'superadmin': + raise HTTPException(403, 'Só o superadmin altera esta conta.') + return row + + +def set_machines(c, uid, machines): + known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)', + ([str(m) for m in machines],)).fetchall()} + if len(known) != len(set(map(str, machines))): + 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: + raise HTTPException(422, 'Defina uma senha inicial com 12 caracteres ou mais.') + uid = uuid4() + with db.connect() as c: + if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone(): + raise HTTPException(409, 'Já existe um usuário com este e-mail.') + 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) + audit('operator_created', operator=user, account=body.email, role=body.role) + return {'id': str(uid)} + + +@router.post('/api/operator/users/{uid}') +def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('users'))): + me_ = request.state.operator + with db.connect() as c: + row = target(c, uid, request) + # A superadmin keeps that profile: the form offers only the assignable ones. + role = row['role'] if row['role'] == 'superadmin' else body.role + if str(row['id']) == str(me_['id']) and (not body.active or role != row['role']): + raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.') + if body.email != row['email'] and c.execute( + 'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone(): + raise HTTPException(409, 'Já existe um usuário com este e-mail.') + c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s', + (body.name.strip(), body.email, role, body.active, uid)) + if body.password: + c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid)) + if body.email != row['email']: + c.execute('UPDATE dtf_local.operator_sessions SET username=%s WHERE username=%s', (body.email, row['email'])) + 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) + audit('operator_updated', operator=user, account=body.email, role=role, active=body.active, + password_reset=bool(body.password)) + return {'ok': True} + + +@router.post('/api/operator/users/{uid}/delete') +def delete_user(uid: UUID, request: Request, user=Depends(can('users'))): + with db.connect() as c: + row = target(c, uid, request) + if str(row['id']) == str(request.state.operator['id']): + raise HTTPException(409, 'Você não pode excluir a sua própria conta.') + c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (row['email'],)) + c.execute('DELETE FROM dtf_local.operators WHERE id=%s', (uid,)) + # The movement history keeps the e-mail of whoever moved each card. + audit('operator_deleted', operator=user, account=row['email']) + return {'ok': True} + + +def machine_rows(c): + rows = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY active DESC, name').fetchall() + for row in rows: + row['id'] = str(row['id']) + return rows + + +@router.get('/api/operator/machines') +def list_machines(user=Depends(can('view'))): + with db.connect() as c: + return {'machines': machine_rows(c)} + + +@router.post('/api/operator/machines') +def create_machine(body: MachineIn, user=Depends(can('users'))): + mid = uuid4() + with db.connect() as c: + if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone(): + raise HTTPException(409, 'Já existe uma máquina com este nome.') + c.execute('INSERT INTO dtf_local.machines(id,name,products,active) VALUES(%s,%s,%s,%s)', + (mid, body.name.strip(), sorted(set(body.products)), body.active)) + audit('machine_created', operator=user, machine=body.name) + return {'id': str(mid)} + + +@router.post('/api/operator/machines/{mid}') +def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))): + with db.connect() as c: + if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s', + (body.name.strip(), mid)).fetchone(): + raise HTTPException(409, 'Já existe uma máquina com este nome.') + if not c.execute('UPDATE dtf_local.machines SET name=%s,products=%s,active=%s WHERE id=%s RETURNING id', + (body.name.strip(), sorted(set(body.products)), body.active, mid)).fetchone(): + raise HTTPException(404, 'Máquina não encontrada.') + audit('machine_updated', operator=user, machine=body.name) + return {'ok': True} + + +@router.post('/api/operator/machines/{mid}/delete') +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: + 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.') + audit('machine_deleted', operator=user, machine=row['name']) + return {'ok': True} diff --git a/app/app.py b/app/app.py index 186b931..5b8a40f 100644 --- a/app/app.py +++ b/app/app.py @@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware from .core import db from .core.auth import audit, client_ip from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage -from .api import artwork, customer, health, operator, orders, payments, quotes, uploads +from .api import artwork, customer, health, operator, orders, payments, quotes, uploads, users @asynccontextmanager @@ -45,5 +45,5 @@ async def safe_headers(request, call_next): # Order is not significant: no two routers declare the same path. -for module in (health, uploads, quotes, orders, payments, operator, customer, artwork): +for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users): app.include_router(module.router) diff --git a/app/core/auth.py b/app/core/auth.py index 1fc9cf6..4c01a31 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -114,13 +114,47 @@ def login_failed(email): """Count a failed sign-in (or registration attempt) against the account.""" rate_limit('auth-account', email, 1_000_000) -def operator(request: Request): +# What each Kanban profile may do. "view" is reading; "produce" moves cards and +# handles artwork; "manage" covers quotes, cancellations, payments and the +# integrations; "users" is the Usuários page. +ROLES = ('superadmin', 'admin', 'gestao', 'operador', 'vendedor') +CAPABILITIES = { + 'view': set(ROLES), + 'produce': {'superadmin', 'admin', 'gestao', 'operador'}, + 'manage': {'superadmin', 'admin', 'gestao'}, + 'users': {'superadmin', 'admin'}, +} + + +def signed_in(request: Request): + """The operator behind this session, active, with the profile read now: a + role changed or an account disabled takes effect on the next request.""" token = request.cookies.get('dtf_operator', '') if not token or len(token)>128: raise HTTPException(401, 'Entre no Kanban.') digest = hashlib.sha256(token.encode()).hexdigest() with connect() as c: - row = c.execute('SELECT username FROM dtf_local.operator_sessions WHERE token_hash=%s AND expires_at>now()', (digest,)).fetchone() + row = c.execute('''SELECT o.id,o.email,o.name,o.role FROM dtf_local.operator_sessions s + JOIN dtf_local.operators o ON o.email=s.username AND o.active + 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.') - return row['username'] + request.state.operator = row + return row + + +def can(capability): + """A dependency that lets through the profiles allowed to do this, and + returns the operator's e-mail, as the routes record it.""" + def check(request: Request): + account = signed_in(request) + if account['role'] not in CAPABILITIES[capability]: + raise HTTPException(403, 'Seu perfil não permite esta ação.') + return account['email'] + return check + + +operator = can('view') diff --git a/app/operators.py b/app/operators.py index 110c549..e0e79b6 100644 --- a/app/operators.py +++ b/app/operators.py @@ -7,11 +7,15 @@ existing deployment keeps working unchanged. Administered from the API container, the same way the schema is: - python -m local.operators list - python -m local.operators add maria@example.com --name "Maria" - python -m local.operators password maria@example.com - python -m local.operators disable maria@example.com - python -m local.operators enable maria@example.com + python -m app.operators list + python -m app.operators add maria@example.com --name "Maria" [--role admin] + python -m app.operators role maria@example.com superadmin + python -m app.operators password maria@example.com + python -m app.operators disable maria@example.com + python -m app.operators enable maria@example.com + +The superadmin is the system's own account and is only set here; the +administrators manage everyone else on the Kanban's Usuários page. Passwords are read from the terminal, never from an argument, so they do not reach shell history or the process list. @@ -21,7 +25,7 @@ import os import sys from uuid import uuid4 -from .core.auth import password_hash +from .core.auth import ROLES, password_hash from .core.db import connect MIN_PASSWORD = 12 @@ -40,9 +44,11 @@ def seed_from_environment(cursor): existing = cursor.execute( 'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone() if existing: + # The configured account is the system's own: it stays superadmin. + cursor.execute("UPDATE dtf_local.operators SET role='superadmin' WHERE email=%s", (email,)) return None cursor.execute( - 'INSERT INTO dtf_local.operators(id,email,name,password_hash) VALUES(%s,%s,%s,%s)', + "INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,'superadmin')", (uuid4(), email, 'Operador', password_hash(password))) return email @@ -56,14 +62,26 @@ def _ask_password(email): return first -def add(email, name=''): +def add(email, name='', role='admin'): email = email.strip().lower() + if role not in ROLES: + raise SystemExit('Role must be one of: ' + ', '.join(ROLES)) with connect() as c: if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone(): raise SystemExit(f'{email} already exists. Use "password" or "enable".') - c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash) VALUES(%s,%s,%s,%s)', - (uuid4(), email, name, password_hash(_ask_password(email)))) - print(f'Added {email}.') + c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,%s)', + (uuid4(), email, name, password_hash(_ask_password(email)), role)) + print(f'Added {email} as {role}.') + + +def set_role(email, role): + email = email.strip().lower() + if role not in ROLES: + raise SystemExit('Role must be one of: ' + ', '.join(ROLES)) + with connect() as c: + if not c.execute('UPDATE dtf_local.operators SET role=%s WHERE email=%s RETURNING id', (role, email)).fetchone(): + raise SystemExit(f'{email} does not exist.') + print(f'{email} is now {role}.') def password(email): @@ -93,7 +111,7 @@ def set_active(email, active): def listing(): with connect() as c: - rows = c.execute('''SELECT email,name,active,last_login_at FROM dtf_local.operators + rows = c.execute('''SELECT email,name,role,active,last_login_at FROM dtf_local.operators ORDER BY email''').fetchall() if not rows: print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run' @@ -102,7 +120,7 @@ def listing(): for row in rows: seen = row['last_login_at'].strftime('%Y-%m-%d %H:%M') if row['last_login_at'] else 'never' state = 'active ' if row['active'] else 'DISABLED' - print(f"{state} {row['email']:<34} {row['name'][:20]:<20} last login {seen}") + print(f"{state} {row['email']:<34} {row['name'][:20]:<20} {row['role']:<10} last login {seen}") def main(argv): @@ -116,7 +134,12 @@ def main(argv): email = rest[0] if command == 'add': name = rest[rest.index('--name') + 1] if '--name' in rest else '' - return add(email, name) + role = rest[rest.index('--role') + 1] if '--role' in rest else 'admin' + return add(email, name, role) + if command == 'role': + if len(rest) < 2: + raise SystemExit('usage: python -m app.operators role ') + return set_role(email, rest[1]) if command == 'password': return password(email) if command == 'disable': diff --git a/app/schema.sql b/app/schema.sql index e2eeb1a..2ef6fbf 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -233,3 +233,26 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names ( cnpj text PRIMARY KEY, legal_name text, trade_name text, fetched_at timestamptz, failed_at timestamptz ); + +-- Who may do what on the Kanban. superadmin is the system's own account (set +-- from the console); administrators manage users and machines; gestão runs +-- the business; operadores produce; vendedores only read. +ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin'; +DO $$ BEGIN + ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role + CHECK (role IN ('superadmin','admin','gestao','operador','vendedor')); +EXCEPTION WHEN duplicate_object THEN NULL; END $$; +-- The print machines, and which products each prints. An order goes to the +-- first active machine that prints its product unless someone chooses one. +CREATE TABLE IF NOT EXISTS dtf_local.machines ( + id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}', + active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now() +); +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL; +-- The machines an operator works on; none means every machine. +CREATE TABLE IF NOT EXISTS dtf_local.operator_machines ( + operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE, + machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE, + PRIMARY KEY (operator_id, machine_id) +); + diff --git a/tests/users_test.py b/tests/users_test.py new file mode 100644 index 0000000..627c9a5 --- /dev/null +++ b/tests/users_test.py @@ -0,0 +1,124 @@ +"""Kanban profiles, users and machines: who may do what, and who sees which orders. + +Run inside the API container: python -m tests.users_test +""" +import secrets +from uuid import uuid4 + +from psycopg.types.json import Jsonb + +from app.core import db +from tests.smoke_test import Client + +PASSWORD = 'senha-de-teste-123' + + +def signed_in(email, password=PASSWORD): + client = Client() + client.call('/session') + client.call('/operator/login', {'email': email, 'password': password}) + return client + + +def run(): + tag = secrets.token_hex(3) + su = Client() + su.call('/session') + assert su.call('/operator/me', operator=True)['role'] == 'superadmin' + emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor')} + owner, textil_q, uv_q, textil_o, uv_o = uuid4(), uuid4(), uuid4(), uuid4(), uuid4() + machines = [] + try: + # Machines, then an administrator who creates the rest of the team. + textil = su.call('/operator/machines', {'name': f'Têxtil {tag}', 'products': ['textil']}, operator=True)['id'] + uv = su.call('/operator/machines', {'name': f'UV {tag}', 'products': ['uv']}, operator=True)['id'] + machines += [textil, uv] + su.call('/operator/machines', {'name': f'uv {tag}', 'products': []}, operator=True, expected=409) + su.call('/operator/users', {'name': 'Marcus', 'email': emails['admin'], 'role': 'admin', 'password': PASSWORD}, + operator=True) + # Superadmin is never given through the page. + su.call('/operator/users', {'name': 'X', 'email': f'x-{tag}@example.test', 'role': 'superadmin', + 'password': PASSWORD}, operator=True, expected=422) + admin = signed_in(emails['admin']) + admin.call('/operator/users', {'name': 'Op', 'email': emails['operador'], 'role': 'operador', + 'password': PASSWORD, 'machines': [uv]}) + admin.call('/operator/users', {'name': 'Vendas', 'email': emails['vendedor'], 'role': 'vendedor', + 'password': PASSWORD}) + admin.call('/operator/users', {'name': 'Again', 'email': emails['vendedor'], 'role': 'vendedor', + 'password': PASSWORD}, expected=409) + users = {u['email']: u for u in admin.call('/operator/users')['users']} + superadmin = next(u for u in users.values() if u['role'] == 'superadmin') + mine = users[emails['admin']] + # An administrator cannot touch the superadmin, nor demote, disable or delete themselves. + admin.call(f"/operator/users/{superadmin['id']}", {'name': 'x', 'email': superadmin['email'], + 'role': 'admin'}, expected=403) + admin.call(f"/operator/users/{mine['id']}", {'name': 'Marcus', 'email': emails['admin'], 'role': 'gestao'}, + expected=409) + admin.call(f"/operator/users/{mine['id']}/delete", {}, expected=409) + + # Two paid orders: Têxtil goes to the Têxtil machine, UV to the UV one. + with db.connect() as c: + for quote, order, mode in ((textil_q, textil_o, 'file'), (uv_q, uv_o, 'uvfile')): + content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'}, + 'items': [{'mode': mode, 'grade': 100, 'billed_metres': '1', 'unit_cents': 1490, + 'uploads': []}], 'freight': {'service': 'pickup'}, 'total_cents': 1490} + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) + VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content))) + c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)', + (order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': tag}))) + board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']} + assert board[str(textil_o)]['machine']['id'] == textil and board[str(uv_o)]['machine']['id'] == uv + + # The operator of the UV machine sees only its orders, moves them, and nothing more. + 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 + op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}) + 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']} + + # The seller reads and changes nothing. + seller = signed_in(emails['vendedor']) + assert {str(uv_o), str(textil_o)} <= {o['id'] for o in seller.call('/operator/board')['orders']} + seller.call('/operator/stats?days=7') + seller.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 1, 'reason': ''}, expected=403) + seller.call(f'/operator/quotes/{uv_q}/discard', {}, expected=403) + seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403) + assert seller.call('/operator/me')['can'] == ['view'] + # Their own password: the current one is asked for. + seller.call('/operator/me/password', {'current': 'errada', 'new': 'outra-senha-de-teste'}, expected=403) + seller.call('/operator/me/password', {'current': PASSWORD, 'new': 'outra-senha-de-teste'}) + signed_in(emails['vendedor'], 'outra-senha-de-teste').call('/operator/me') + + # Disabled, the operator is out at once; deleted, the account is gone. + op_row = users[emails['operador']] + admin.call(f"/operator/users/{op_row['id']}", {'name': 'Op', 'email': emails['operador'], 'role': 'operador', + 'active': False, 'machines': [uv]}) + op.call('/operator/board', expected=401) + admin.call(f"/operator/users/{op_row['id']}/delete", {}) + assert emails['operador'] not in {u['email'] for u in admin.call('/operator/users')['users']} + # A deleted machine sends its orders back to the automatic choice. + su.call(f'/operator/machines/{uv}/delete', {}, operator=True) + machines.remove(uv) + board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']} + assert board[str(textil_o)]['machine']['id'] == textil + print('PASS: profiles limit actions, admins manage users but not the superadmin or themselves, ' + 'machines route orders and limit what their operators see') + finally: + with db.connect() as c: + for oid in (textil_o, uv_o): + c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,)) + c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,)) + c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{oid}:%',)) + c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([textil_q, uv_q],)) + c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',)) + c.execute('DELETE FROM dtf_local.machines WHERE id=ANY(%s::uuid[])', (machines,)) + + +if __name__ == '__main__': + run() diff --git a/web/kanban.css b/web/kanban.css index d76b1b3..ca2e42a 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -73,9 +73,12 @@ input[type=file]{font-size:14px;color:var(--muted);max-width:100%} .tinydot{display:flex;align-items:center;gap:8px;font-size:14px;color:var(--muted);white-space:nowrap} .tinydot::before{content:"";width:8px;height:8px;border-radius:999px;background:var(--dot,#5B6168)} .tinydot:empty{display:none} -.who{font-size:14px;color:var(--muted);white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis} -/* With five tabs, the operator's e-mail is the first thing to give way; it stays on Sair's tooltip. */ -@media (max-width:1560px){.who{display:none}} +.account{margin-left:0} +.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} +.menu-head b{font-size:14.5px} +.menu-head span{font-size:12.5px;color:var(--faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #status{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:20;margin:0;max-width:min(640px,calc(100vw - 32px));padding:10px 16px;border-radius:10px;border:1px solid var(--line3);background:#1E2226;color:var(--tx);font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.45)} #status:empty,#login-status:empty{display:none} #status.error{border-color:var(--bad-line);color:var(--bad)} @@ -422,3 +425,23 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom} .refresh .btn{border:0;border-radius:0;display:inline-flex;align-items:center;gap:6px} .refresh select{width:88px;height:36px;padding:0 24px 0 10px;border:0;border-left:1px solid var(--line2);background:transparent;color:var(--muted);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer} .refresh select option{background:var(--card);color:var(--tx)} + +/* Usuários: dialogs for users and machines, and the tables. */ +.modal{position:fixed;inset:0;z-index:50;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;padding:16px} +.modal-box{width:min(460px,100%);max-height:calc(100vh - 32px);overflow:auto;display:flex;flex-direction:column;gap:14px;padding:22px; + border-radius:14px;border:1px solid var(--line3);background:var(--panel)} +.modal-box h2{margin:0;font-size:18px} +.mfield{display:flex;flex-direction:column;gap:6px;font-size:13.5px;font-weight:600;color:var(--muted)} +.mfield input:not([type=checkbox]),.mfield select{height:40px;padding:0 12px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px;font-weight:500} +.mfield .check{font-weight:500} +.modal-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:4px} +#tab-users .pagehead h2{margin:0} +#tab-users .pagehead .btn{margin-left:auto} +#tab-users td.actions{text-align:right;white-space:nowrap} +#tab-users td.actions .btn+.btn{margin-left:6px} +#tab-users tr.off td{opacity:.55} +.faint.block{display:block;font-size:13px} +.danger-text{color:var(--bad)} +.machine-select{height:36px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px} +.card .machine{color:var(--accent-tx)} + diff --git a/web/kanban.html b/web/kanban.html index f786a5b..00e03cd 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -22,6 +22,7 @@ + - +
- +

@@ -77,6 +85,16 @@
EtapaTempo medianoPedidos que passaramAgora
+