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

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost. # one a developer exercises on localhost.
- name: API and workflow regressions - name: API and workflow regressions
run: | 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" echo "--- $suite"
$COMPOSE exec -T \ $COMPOSE exec -T \
-e SITE_BASE_URL=http://site \ -e SITE_BASE_URL=http://site \

View File

@@ -9,7 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException
from ..core import db from ..core import db
from ..artwork import submit_files from ..artwork import submit_files
from ..core.auth import operator from ..core.auth import can, operator
from ..core.models import ArtworkSubmission, UploadStart from ..core.models import ArtworkSubmission, UploadStart
from ..runtime import file_rows, operator_identity from ..runtime import file_rows, operator_identity
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status 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 = APIRouter()
@router.post('/api/operator/orders/{oid}/uploads') @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: with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone() row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not row: raise HTTPException(404, 'Order not found') 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)) return upload_status(uid,session_id=operator_identity(user))
@router.post('/api/operator/uploads/{uid}/parts/{number}') @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)) return part_url(uid,number,session_id=operator_identity(user))
@router.post('/api/operator/uploads/{uid}/complete') @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)) return complete_upload(uid,session_id=operator_identity(user))
@router.delete('/api/operator/uploads/{uid}') @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)) return cancel_upload(uid,session_id=operator_identity(user))
@router.get('/api/operator/orders/{oid}/files') @router.get('/api/operator/orders/{oid}/files')
@@ -46,7 +46,7 @@ def operator_files(oid: UUID, user=Depends(operator)):
return file_rows(c,oid) return file_rows(c,oid)
@router.post('/api/operator/orders/{oid}/final-files') @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: with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone() order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
if not order: raise HTTPException(404, 'Order not found') if not order: raise HTTPException(404, 'Order not found')

View File

@@ -11,7 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
from ..core import db 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) login_failed, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
from ..printjobs import queue as queue_print_files from ..printjobs import queue as queue_print_files
@@ -89,7 +89,7 @@ def backup_status(c):
@router.get('/api/operator/board') @router.get('/api/operator/board')
def board(user=Depends(operator)): def board(request: Request, user=Depends(operator)):
with db.connect() as c: with db.connect() as c:
# Everything still in progress, however old: an operator must never lose a # Everything still in progress, however old: an operator must never lose a
# card they can act on. Finished orders are terminal and only accumulate, # 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 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 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'] 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 # A paid notification that did not become an order is money received
# for nothing the factory will make. The board carries the count; the # for nothing the factory will make. The board carries the count; the
# Pagamentos tab pages through them until someone records a resolution. # 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}, 'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN, 'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total, '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), 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes), 'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total} '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'""" 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): def with_print_files(c, orders):
"""Each order with its generated print files, the items whose final file is """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.""" 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['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')} order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
for row in fixes if row['order_id'] == order['id']] for row in fixes if row['order_id'] == order['id']]
return orders return assign_machines(c, orders)
def cursor_pair(first, second): def cursor_pair(first, second):
@@ -195,7 +224,7 @@ def cursor_pair(first, second):
@router.get('/api/operator/orders/finished') @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)): limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
"""Older finished orders, newest first, beyond the board's recent window.""" """Older finished orders, newest first, beyond the board's recent window."""
paged = cursor_pair(before_created_at, before_id) 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 '') + ''' ''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY created_at DESC,id DESC LIMIT %s''', ORDER BY created_at DESC,id DESC LIMIT %s''',
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall() ((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), return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
'names': company_names(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') @router.get('/api/operator/payment-events')
def payment_events(state: Literal['open','resolved','all'] = 'open', def payment_events(state: Literal['open','resolved','all'] = 'open',
offset: int = Query(default=0, ge=0), 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.""" """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] where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state]
with db.connect() as c: with db.connect() as c:
@@ -230,7 +259,7 @@ def events(provider: Literal['tiny','whatsapp'] | None = None,
status: Literal['delivered','queued','failing'] | None = None, status: Literal['delivered','queued','failing'] | None = None,
event: Literal['payment_approved','production_started','correction_needed','ready'] | 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), 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.""" """The integration send log, newest first, filtered, by page with a total."""
clauses, params = [], [] clauses, params = [], []
if provider: if provider:
@@ -324,7 +353,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
@router.get('/api/operator/search') @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, """One search over orders (any stage) and unpaid quotes: customer e-mail,
CNPJ or WhatsApp, the delivery recipient, or the order number.""" CNPJ or WhatsApp, the delivery recipient, or the order number."""
match, params = customer_match('snapshot', q) 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 LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match} WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall() 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] quotes = [quote_view(c, row) for row in rows]
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes), return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes)} 'names': company_names(c, orders, quotes)}
@router.post('/api/operator/quotes/{uid}/approve') @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: with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone() row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row: 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) return quote_review.approve(c, row, body.items, user)
@router.post('/api/operator/quotes/{uid}/test-order') @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, """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 files and print flow in production. Marked TEST on the board, never sent
to Tiny or WhatsApp, and audited.""" 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') @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 """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 keep their normal expiry; a payment that still arrives for it is refused
and listed under Pagamentos.""" and listed under Pagamentos."""
@@ -397,7 +426,7 @@ def discard_quote(uid: UUID, user=Depends(operator)):
@router.post('/api/operator/orders/{uid}/delete') @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 """Deletes a test order, or a paid order already cancelled, with its
history and files' records. A paid order in progress must be cancelled 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 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') @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 """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.""" is refunded here (that is done at the provider) and Tiny is not told."""
with db.connect() as c: with db.connect() as c:
@@ -436,6 +465,24 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(operator)):
return {'ok': True} 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): class QueuePlace(StrictModel):
"""Where a dragged card lands: between two orders of its column, either """Where a dragged card lands: between two orders of its column, either
of them absent at the top or the bottom.""" 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') @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, """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 halfway between the orders it was dropped between. It neither changes the
order's stage nor counts as activity (the stalled clock keeps running).""" 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') @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: with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row: if not row:
@@ -524,7 +571,7 @@ def move(uid: UUID, body: Move, user=Depends(operator)):
return changed return changed
@router.post('/api/operator/orders/{uid}/print-files') @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, """Queue generation again for items that failed or went to manual preparation,
and for orders paid before the generator existed.""" and for orders paid before the generator existed."""
with db.connect() as c: 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() 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') @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: with db.connect() as c:
row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s 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''', 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()} **tiny.TinyAuth().status()}
@router.post('/api/operator/tiny/connect') @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.""" """Start the one-time authorisation of this system in the client's Tiny."""
if not tiny.configured(): if not tiny.configured():
raise HTTPException(503, 'Tiny application is not 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)} return {'url': tiny.TinyAuth().authorize_url(user)}
@router.post('/api/operator/tiny/test') @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.""" """Read one order and one contact from Tiny. Creates nothing."""
if not tiny.configured(): if not tiny.configured():
raise HTTPException(503, 'Tiny application is not 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} return {'ok': all(v == 'ok' for v in results.values()), 'results': results}
@router.post('/api/operator/mercadopago/check') @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.""" """The Mercado Pago account behind the configured token; reads only."""
if payment.name != 'mercadopago': if payment.name != 'mercadopago':
raise HTTPException(409, 'Mercado Pago não está configurado') 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') @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 """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 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 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 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} 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() 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() files, names = [], set()
for row in rows: for row in rows:
prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}" prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}"

210
app/api/users.py Normal file
View 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}

View File

@@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware
from .core import db from .core import db
from .core.auth import audit, client_ip from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage 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 @asynccontextmanager
@@ -45,5 +45,5 @@ async def safe_headers(request, call_next):
# Order is not significant: no two routers declare the same path. # 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) app.include_router(module.router)

View File

@@ -114,13 +114,47 @@ def login_failed(email):
"""Count a failed sign-in (or registration attempt) against the account.""" """Count a failed sign-in (or registration attempt) against the account."""
rate_limit('auth-account', email, 1_000_000) 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', '') token = request.cookies.get('dtf_operator', '')
if not token or len(token)>128: if not token or len(token)>128:
raise HTTPException(401, 'Entre no Kanban.') raise HTTPException(401, 'Entre no Kanban.')
digest = hashlib.sha256(token.encode()).hexdigest() digest = hashlib.sha256(token.encode()).hexdigest()
with connect() as c: 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: if not row:
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.') 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')

View File

@@ -7,11 +7,15 @@ existing deployment keeps working unchanged.
Administered from the API container, the same way the schema is: Administered from the API container, the same way the schema is:
python -m local.operators list python -m app.operators list
python -m local.operators add maria@example.com --name "Maria" python -m app.operators add maria@example.com --name "Maria" [--role admin]
python -m local.operators password maria@example.com python -m app.operators role maria@example.com superadmin
python -m local.operators disable maria@example.com python -m app.operators password maria@example.com
python -m local.operators enable 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 Passwords are read from the terminal, never from an argument, so they do not
reach shell history or the process list. reach shell history or the process list.
@@ -21,7 +25,7 @@ import os
import sys import sys
from uuid import uuid4 from uuid import uuid4
from .core.auth import password_hash from .core.auth import ROLES, password_hash
from .core.db import connect from .core.db import connect
MIN_PASSWORD = 12 MIN_PASSWORD = 12
@@ -40,9 +44,11 @@ def seed_from_environment(cursor):
existing = cursor.execute( existing = cursor.execute(
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone() 'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
if existing: 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 return None
cursor.execute( 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))) (uuid4(), email, 'Operador', password_hash(password)))
return email return email
@@ -56,14 +62,26 @@ def _ask_password(email):
return first return first
def add(email, name=''): def add(email, name='', role='admin'):
email = email.strip().lower() email = email.strip().lower()
if role not in ROLES:
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
with connect() as c: with connect() as c:
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone(): if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
raise SystemExit(f'{email} already exists. Use "password" or "enable".') 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)', 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)))) (uuid4(), email, name, password_hash(_ask_password(email)), role))
print(f'Added {email}.') 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): def password(email):
@@ -93,7 +111,7 @@ def set_active(email, active):
def listing(): def listing():
with connect() as c: 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() ORDER BY email''').fetchall()
if not rows: if not rows:
print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run' print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run'
@@ -102,7 +120,7 @@ def listing():
for row in rows: for row in rows:
seen = row['last_login_at'].strftime('%Y-%m-%d %H:%M') if row['last_login_at'] else 'never' 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' 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): def main(argv):
@@ -116,7 +134,12 @@ def main(argv):
email = rest[0] email = rest[0]
if command == 'add': if command == 'add':
name = rest[rest.index('--name') + 1] if '--name' in rest else '' 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 <email> <role>')
return set_role(email, rest[1])
if command == 'password': if command == 'password':
return password(email) return password(email)
if command == 'disable': if command == 'disable':

View File

@@ -233,3 +233,26 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
cnpj text PRIMARY KEY, legal_name text, trade_name text, cnpj text PRIMARY KEY, legal_name text, trade_name text,
fetched_at timestamptz, failed_at timestamptz 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)
);

124
tests/users_test.py Normal file
View File

@@ -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()

View File

@@ -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{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::before{content:"";width:8px;height:8px;border-radius:999px;background:var(--dot,#5B6168)}
.tinydot:empty{display:none} .tinydot:empty{display:none}
.who{font-size:14px;color:var(--muted);white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis} .account{margin-left:0}
/* With five tabs, the operator's e-mail is the first thing to give way; it stays on Sair's tooltip. */ .account .btn{min-width:38px;padding:0 10px;font-weight:800;letter-spacing:.02em}
@media (max-width:1560px){.who{display:none}} .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{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:empty,#login-status:empty{display:none}
#status.error{border-color:var(--bad-line);color:var(--bad)} #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 .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{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)} .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)}

View File

@@ -22,6 +22,7 @@
<button type="button" data-tab="payments" aria-selected="false">Pagamentos <span class="badge warn" id="badge-payments"></span></button> <button type="button" data-tab="payments" aria-selected="false">Pagamentos <span class="badge warn" id="badge-payments"></span></button>
<button type="button" data-tab="stats" aria-selected="false">Números</button> <button type="button" data-tab="stats" aria-selected="false">Números</button>
<button type="button" data-tab="integrations" aria-selected="false">Integrações</button> <button type="button" data-tab="integrations" aria-selected="false">Integrações</button>
<button type="button" data-tab="users" aria-selected="false" hidden>Usuários</button>
</nav> </nav>
<div class="searchbox"> <div class="searchbox">
<label class="search"> <label class="search">
@@ -32,7 +33,7 @@
<div id="search-results" class="results" role="listbox" aria-label="Resultados da busca" hidden></div> <div id="search-results" class="results" role="listbox" aria-label="Resultados da busca" hidden></div>
</div> </div>
<span id="tiny" class="tinydot"></span> <span id="tiny" class="tinydot"></span>
<span id="who" class="who"></span>
<div class="refresh"> <div class="refresh">
<button class="btn ghost" id="refresh" type="button"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"></path><path d="M21 3v6h-6"></path></svg>Atualizar</button> <button class="btn ghost" id="refresh" type="button"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"></path><path d="M21 3v6h-6"></path></svg>Atualizar</button>
<select id="refresh-every" aria-label="Atualizar sozinho a cada"> <select id="refresh-every" aria-label="Atualizar sozinho a cada">
@@ -40,7 +41,14 @@
<option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option> <option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option>
</select> </select>
</div> </div>
<button class="btn ghost" id="logout" type="button">Sair</button> <div class="morewrap account">
<button class="btn ghost" id="account" type="button" aria-haspopup="menu" aria-label="Minha conta"><span id="initials">·</span></button>
<div class="menu" id="account-menu" role="menu" hidden>
<div class="menu-head"><b id="who"></b><span id="who-role"></span></div>
<button class="menuitem" id="my-password" type="button">Minha senha</button>
<button class="menuitem" id="logout" type="button">Sair</button>
</div>
</div>
</header> </header>
<p id="status" role="status"></p> <p id="status" role="status"></p>
<main> <main>
@@ -77,6 +85,16 @@
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table> <table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>
</section> </section>
</section> </section>
<section id="tab-users" class="page" hidden>
<div class="pagehead"><h1>Usuários</h1><button class="btn primary" id="new-user" type="button">Novo usuário</button></div>
<p class="faint stats-note">Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página.
Gestão: tudo, menos usuários. Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquinas</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
<p class="faint stats-note">Cada pedido vai para a primeira máquina ativa que imprime o produto dele; no pedido dá para escolher outra.
Um operador ligado a máquinas vê só os pedidos delas.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Produtos</th><th scope="col">Situação</th><th scope="col"></th></tr></thead><tbody id="machines-list"></tbody></table></section>
</section>
<section id="tab-integrations" class="page" hidden> <section id="tab-integrations" class="page" hidden>
<h1>Integrações</h1> <h1>Integrações</h1>
<section><div class="grid4" id="integrations"></div></section> <section><div class="grid4" id="integrations"></div></section>

View File

@@ -33,6 +33,17 @@ let quoteKind='pending', pickedQuote=null;
let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=null; let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=null;
// Uploads that have an artwork picture (the customer's browser made it). Every // Uploads that have an artwork picture (the customer's browser made it). Every
// list the API returns says which, so only pictures that exist are asked for. // list the API returns says which, so only pictures that exist are asked for.
// The signed-in operator and what their profile allows (app/core/auth.py).
let ME=null;
const may=cap=>!!ME?.can?.includes(cap);
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',operador:'Operador',vendedor:'Vendedor'};
// Which tabs each capability opens.
const TAB_NEEDS={quotes:o=>may('manage')||ME?.role==='vendedor',payments:()=>may('manage'),
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage'),users:()=>may('users')};
function applyRole(){
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
}
const THUMBS=new Set(); const THUMBS=new Set();
// Company names by CNPJ, from the public registry (app/cnpj.py). // Company names by CNPJ, from the public registry (app/cnpj.py).
const NAMES=new Map(); const NAMES=new Map();
@@ -83,6 +94,7 @@ const ICON_OK=['M5 12l4 4 10-10'], ICON_WARN=['M12 8v5M12 17h.01','circle 12 12
const ICON_TRUCK=['M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2','M15 18H9', const ICON_TRUCK=['M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2','M15 18H9',
'M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14','circle 17 18 2','circle 7 18 2']; 'M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14','circle 17 18 2','circle 7 18 2'];
const ICON_PIN=['M20 10c0 4.99-5.54 10.19-7.4 11.8a1 1 0 0 1-1.2 0C9.54 20.19 4 14.99 4 10a8 8 0 0 1 16 0','circle 12 10 3']; const ICON_PIN=['M20 10c0 4.99-5.54 10.19-7.4 11.8a1 1 0 0 1-1.2 0C9.54 20.19 4 14.99 4 10a8 8 0 0 1 16 0','circle 12 10 3'];
const ICON_PRINTER=['M6 9V2h12v7','M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2','M6 14h12v8H6z'];
const ICON_DOWNLOAD=['M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4','m7 10 5 5 5-5','M12 15V3']; const ICON_DOWNLOAD=['M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4','m7 10 5 5 5-5','M12 15V3'];
const ICON_CHAT=['M7.9 20A9 9 0 1 0 4 16.1L2 22Z']; const ICON_CHAT=['M7.9 20A9 9 0 1 0 4 16.1L2 22Z'];
const ICON_COPY=['M9 9h12v12H9z','M5 15V5a2 2 0 0 1 2-2h10']; const ICON_COPY=['M9 9h12v12H9z','M5 15V5a2 2 0 0 1 2-2h10'];
@@ -241,7 +253,8 @@ function itemPreview(item){
let seenOrders=null, seenPending=null, unseen=0; let seenOrders=null, seenPending=null, unseen=0;
async function load(quiet=false){ async function load(quiet=false){
try{ try{
board=absorb(await api('/board')); const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
board=absorb(loaded);ME=me;applyRole();
noticeNew(quiet); noticeNew(quiet);
const known=new Set(board.orders.map(o=>o.id)); const known=new Set(board.orders.map(o=>o.id));
board.orders.push(...olderFinished.filter(o=>!known.has(o.id))); board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
@@ -259,18 +272,20 @@ async function load(quiet=false){
function showTab(name){ function showTab(name){
tab=name; tab=name;
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name)); for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
for(const id of ['board','quotes','payments','stats','integrations'])$('tab-'+id).hidden=name!==id; for(const id of ['board','quotes','payments','stats','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents}; const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents,users:loadUsers};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true)); if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
} }
function render(){ function render(){
$('who').textContent=board.operator||'';$('logout').title=board.operator?'Sair ('+board.operator+')':'Sair'; $('who').textContent=ME?(ME.name||ME.email):'';
$('who-role').textContent=ME?(ROLE_NAMES[ME.role]||ME.role)+' · '+ME.email:'';
$('initials').textContent=ME?((ME.name||ME.email).trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()):'·';
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length); $('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):''; $('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):''; $('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
tinyHeader();renderBoard();renderIntegrations(); tinyHeader();renderBoard();renderIntegrations();
// Lists live on their own pages of the API; refresh the one being looked at. // Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents}; const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents,users:loadUsers};
if(lists[tab])lists[tab]().catch(e=>say(e.message,true)); if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();} if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
} }
@@ -333,7 +348,7 @@ function renderBoard(){
line.append(swatch,node('h2',title),node('span',count,'n')); line.append(swatch,node('h2',title),node('span',count,'n'));
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+' no total':'vazio')); const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+' no total':'vazio'));
// The print queue's files, all at once, to import into FlexiPRINT. // The print queue's files, all at once, to import into FlexiPRINT.
if(state==='fil'&&orders.length){ if(state==='fil'&&orders.length&&may('produce')){
const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila'; const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';
sub.append(all); sub.append(all);
} }
@@ -361,7 +376,7 @@ function renderBoard(){
// An operator's test order: no payment, no Tiny, no WhatsApp. // An operator's test order: no payment, no Tiny, no WhatsApp.
const isTest=order=>order.payment?.provider==='teste'; const isTest=order=>order.payment?.provider==='teste';
function card(order){ function card(order){
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at; const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at&&may('produce');
if(order.id===openOrder)c.classList.add('open'); if(order.id===openOrder)c.classList.add('open');
const s=order.snapshot; const s=order.snapshot;
const top=node('div',undefined,'row'); const top=node('div',undefined,'row');
@@ -379,6 +394,7 @@ function card(order){
if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at))); if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
} }
c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination)); c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination));
if(order.machine&&order.state!=='fin'){const m=node('div',undefined,'place machine');m.append(icon(ICON_PRINTER),order.machine.name);c.append(m);}
if(flags.children.length)c.append(flags); if(flags.children.length)c.append(flags);
c.onclick=()=>openPanel(order.id); c.onclick=()=>openPanel(order.id);
c.ondragstart=e=>{ c.ondragstart=e=>{
@@ -489,6 +505,7 @@ function renderPanel(order){
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'Cliente retira na fábrica')); node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'Cliente retira na fábrica'));
if(dest&&s.freight?.total_cents)where.append(node('span','Jadlog · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint')); if(dest&&s.freight?.total_cents)where.append(node('span','Jadlog · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
facts.append(who,where); facts.append(who,where);
if(order.machine||board.machines?.length)facts.append(machineCard(order));
const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow')); const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow'));
const itemsList=node('div');itemsList.style.display='flex';itemsList.style.flexDirection='column';itemsList.style.gap='10px'; const itemsList=node('div');itemsList.style.display='flex';itemsList.style.flexDirection='column';itemsList.style.gap='10px';
s.items.forEach((item,index)=>itemsList.append(itemCard(order,item,index))); s.items.forEach((item,index)=>itemsList.append(itemCard(order,item,index)));
@@ -503,6 +520,12 @@ function renderPanel(order){
} }
function moves(order){ function moves(order){
const box=node('div',undefined,'panel-actions'); const box=node('div',undefined,'panel-actions');
if(!may('produce')){
// Sellers read the order; a correction's notice is theirs to send too.
if(order.state==='cor'&&!order.cancelled_at)box.append(correctionNotice(order));
box.append(node('p',order.cancelled_at?'Pedido cancelado.':'Somente consulta: seu perfil não move pedidos.','muted'));
return box;
}
if(order.cancelled_at){ if(order.cancelled_at){
const note=node('div',undefined,'callout bad'); const note=node('div',undefined,'callout bad');
note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason)); note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason));
@@ -510,7 +533,7 @@ function moves(order){
if(!window.confirm('Excluir o pedido #'+order.number+' de vez? Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.'))return; if(!window.confirm('Excluir o pedido #'+order.number+' de vez? Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.'))return;
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load(); await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load();
},'btn danger');remove.style.alignSelf='flex-start'; },'btn danger');remove.style.alignSelf='flex-start';
box.append(note,remove);return box; box.append(note,...(may('manage')?[remove]:[]));return box;
} }
// In correction, the customer has to be told: a message ready to send on // In correction, the customer has to be told: a message ready to send on
// WhatsApp with the reason and where to send the new file. // WhatsApp with the reason and where to send the new file.
@@ -592,7 +615,7 @@ function moves(order){
more.setAttribute('aria-haspopup','menu'); more.setAttribute('aria-haspopup','menu');
more.onclick=e=>{e.stopPropagation();menu.hidden=!menu.hidden; more.onclick=e=>{e.stopPropagation();menu.hidden=!menu.hidden;
if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;},{once:true});}; if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;},{once:true});};
const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);row.append(wrap); const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);if(may('manage'))row.append(wrap);
const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true; const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true;
const sendFix=node('button','Enviar para correção','btn danger'); const sendFix=node('button','Enviar para correção','btn danger');
reason.append(text,sendFix); reason.append(text,sendFix);
@@ -728,7 +751,7 @@ function itemCard(order,item,index){
else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id))); else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost'))); item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost')); if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
if(!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed')) if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
buttons.append(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn ghost')); buttons.append(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn ghost'));
body.append(buttons); body.append(buttons);
box.append(preview,body);return box; box.append(preview,body);return box;
@@ -746,7 +769,7 @@ function finalsSection(order,revisions,section){
// Approving is the button at the top; this is for replacing an approved // Approving is the button at the top; this is for replacing an approved
// final, or sending one before the art is marked as handled. // final, or sending one before the art is marked as handled.
// Before approval in Arte tratada, the step at the top is the way in. // Before approval in Arte tratada, the step at the top is the way in.
if(!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return; if(!may('produce')||!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
const form=finalForm(order,readyFinals(order).map(()=>null)); const form=finalForm(order,readyFinals(order).map(()=>null));
const open=node('button',finalDone(order)?'Enviar nova versão':'Enviar arquivo final','btn ghost');open.type='button'; const open=node('button',finalDone(order)?'Enviar nova versão':'Enviar arquivo final','btn ghost');open.type='button';
open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();}; open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();};
@@ -765,6 +788,126 @@ function historySection(order,rows,section){
section.replaceChildren(node('p','Histórico','eyebrow'),list); section.replaceChildren(node('p','Histórico','eyebrow'),list);
} }
// ---- Machines and users ----------------------------------------------------
// The order's machine: chosen, or the first that prints its product.
function machineCard(order){
const box=node('div',undefined,'fcard');box.append(node('p','Máquina','eyebrow'));
const current=order.machine;
if(!may('produce')||!board.machines?.length){
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'));return box;
}
const select=node('select',undefined,'machine-select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Automática'+(current&&!current.chosen?' ('+current.name+')':''));auto.value='';select.append(auto);
for(const m of board.machines.filter(m=>m.active||m.id===current?.id)){
const o=node('option',m.name);o.value=m.id;select.append(o);
}
select.value=current?.chosen?current.id:'';
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'Máquina automática pelo produto.');await load();}
catch(e){say(e.message,true);}};
box.append(select,node('span',current?.chosen?'Escolhida para este pedido.':'Pelo produto do pedido.','faint'));
return box;
}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
let usersData=null;
async function loadUsers(){
usersData=await api('/users');
renderUsers();
}
function renderUsers(){
const {users,machines}=usersData;
const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
const rows=users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email,'faint block'));
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—'));
const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint');
const actions=node('td',undefined,'actions');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
if(editable)actions.append(button('Editar',()=>userForm(u),'btn ghost small'));
if(editable&&u.email!==ME.email)actions.append(button('Excluir',async()=>{
if(!window.confirm('Excluir o usuário '+(u.name||u.email)+'? Ele perde o acesso na hora. O histórico dos pedidos continua com o e-mail dele.'))return;
await api('/users/'+u.id+'/delete',{});say('Usuário excluído.');await loadUsers();},'btn ghost small danger-text'));
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':' · desativado')),machinesTd,seen,actions);return tr;
});
$('users-list').replaceChildren(...rows);
$('machines-list').replaceChildren(...(machines.length?machines.map(m=>{
const tr=node('tr');if(!m.active)tr.classList.add('off');
const actions=node('td',undefined,'actions');
actions.append(button('Editar',()=>machineForm(m),'btn ghost small'),button('Excluir',async()=>{
if(!window.confirm('Excluir a máquina '+m.name+'? Os pedidos dela voltam para a escolha automática.'))return;
await api('/machines/'+m.id+'/delete',{});say('Máquina excluída.');await loadUsers();await load();},'btn ghost small danger-text'));
tr.append(node('td',m.name),node('td',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto'),
node('td',m.active?'Ativa':'Desativada'),actions);return tr;
}):[(()=>{const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada. Sem máquinas, todos os pedidos aparecem para todos.','faint');td.colSpan=4;tr.append(td);return tr;})()]));
}
// One dialog for creating and editing, for users and machines alike.
function dialog(title,fields,onsave){
const back=node('div',undefined,'modal');const form=node('form',undefined,'modal-box');
form.append(node('h2',title),...fields);
const row=node('div',undefined,'modal-actions');
const cancel=node('button','Cancelar','btn ghost');cancel.type='button';cancel.onclick=()=>back.remove();
const save=node('button','Salvar','btn primary');row.append(cancel,save);form.append(row);
form.onsubmit=async e=>{e.preventDefault();save.disabled=true;try{await onsave();back.remove();}catch(err){say(err.message,true);save.disabled=false;}};
back.onclick=e=>{if(e.target===back)back.remove();};
back.append(form);document.body.append(back);form.querySelector('input,select')?.focus();
}
function field(label,input){const l=node('label',undefined,'mfield');l.append(label,input);return l;}
function userForm(u){
const editing=!!u;
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';
const role=node('select');
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','operador','vendedor'];
for(const r of roles){const o=node('option',ROLE_NAMES[r]);o.value=r;role.append(o);}
role.value=u?.role||'operador';role.disabled=u?.role==='superadmin'||u?.email===ME.email;
const pass=node('input');pass.type='password';pass.minLength=12;pass.maxLength=128;pass.autocomplete='new-password';
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'12 caracteres ou mais';
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
const boxes=usersData.machines.map(m=>{const c=node('input');c.type='checkbox';c.value=m.id;c.checked=!!u?.machines.includes(m.id);
const l=node('label',undefined,'check');l.append(c,m.name);return l;});
const machinesField=node('div',undefined,'mfield');
machinesField.append('Máquinas (só para operadores; nenhuma = todas)',...(boxes.length?boxes:[node('span','Nenhuma máquina cadastrada.','faint')]));
const syncMachines=()=>{machinesField.hidden=role.value!=='operador';};role.onchange=syncMachines;syncMachines();
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
machines:role.value==='operador'?boxes.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value):[],
password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
});
}
function machineForm(m){
const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';
const prods=['textil','uv'].map(p=>{const c=node('input');c.type='checkbox';c.value=p;c.checked=!!m?.products.includes(p);
const l=node('label',undefined,'check');l.append(c,'Imprime '+PRODUCT_LABEL[p]);return l;});
const active=node('input');active.type='checkbox';active.checked=m?m.active:true;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativa (recebe pedidos)');
const prodField=node('div',undefined,'mfield');prodField.append('Produtos',...prods);
dialog(m?'Editar máquina':'Nova máquina',[field('Nome',name),prodField,activeLabel],async()=>{
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,
products:prods.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value)});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
});
}
function passwordForm(){
const current=node('input');current.type='password';current.required=true;current.autocomplete='current-password';
const next=node('input');next.type='password';next.required=true;next.minLength=12;next.autocomplete='new-password';
const again=node('input');again.type='password';again.required=true;again.minLength=12;again.autocomplete='new-password';
dialog('Minha senha',[field('Senha atual',current),field('Nova senha (12 caracteres ou mais)',next),field('Repita a nova senha',again)],async()=>{
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
});
}
$('my-password').onclick=()=>{$('account-menu').hidden=true;passwordForm();};
$('account').onclick=e=>{e.stopPropagation();const m=$('account-menu');m.hidden=!m.hidden;
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;},{once:true});};
$('new-user').onclick=()=>userForm(null);
$('new-machine').onclick=()=>machineForm(null);
// ---- Numbers ------------------------------------------------------------- // ---- Numbers -------------------------------------------------------------
let statsDays=30; let statsDays=30;
@@ -947,7 +1090,7 @@ function review(quote){
content.append(sums); content.append(sums);
} }
card.append(head,content); card.append(head,content);
if(quote.status==='approved'){ if(quote.status==='approved'&&may('manage')){
foot.append(discardButton(quote)); foot.append(discardButton(quote));
// Tries the whole production flow without a payment. // Tries the whole production flow without a payment.
foot.append(button('Criar pedido de teste',async()=>{ foot.append(button('Criar pedido de teste',async()=>{
@@ -959,6 +1102,10 @@ function review(quote){
} }
return card; return card;
} }
if(!may('manage')){
quote.draft.items.forEach(item=>content.append(quoteItem(item,null)));
card.append(head,content);return card;
}
const form=node('form');form.style.display='contents'; const form=node('form');form.style.display='contents';
const edits=quote.draft.items.map(item=>{const fields={};content.append(quoteItem(item,fields)); const edits=quote.draft.items.map(item=>{const fields={};content.append(quoteItem(item,fields));
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});}); return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});