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:
@@ -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')
|
||||
|
||||
@@ -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}"
|
||||
|
||||
210
app/api/users.py
Normal file
210
app/api/users.py
Normal file
@@ -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}
|
||||
Reference in New Issue
Block a user