feat: Kanban profiles, a Usuários page, and machines that route orders

Every operator could do everything, and accounts were made from the
console. Each account now has a profile, checked by the server on every
action: Administrador (everything, plus users and machines), Gestão
(everything but users), Operador (moves cards and handles artwork) and
Vendedor (reads orders, quotes and Números, changes nothing). The
superadmin is the system's own account, set from the console and kept by
the account OPERATOR_EMAIL seeds; administrators cannot change it, and
nobody can delete, disable or demote themselves.

The Usuários tab creates, edits, disables and deletes users with a first
password (there is no e-mail yet), and registers machines with the
products each prints. An order goes to the first active machine that
prints its product, or to the one chosen in its panel; an operator tied
to machines sees and downloads only their orders. Everyone changes their
own password in the account menu, which now holds the name and Sair too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-07 15:00:00 -03:00
parent 6c2dcc77b0
commit c75c40ff28
12 changed files with 719 additions and 66 deletions

View File

@@ -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}"