Compare commits

..

5 Commits

Author SHA1 Message Date
Cauê Faleiros
3db528a373 feat: UV goes to Tiny as whole metres of DTFIMP.UV.1MT, then DTFIMP.UV.010CM
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 3m12s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 58s
The client registered UV as a metre SKU and a 10 cm SKU. With
TINY_SKU_METRO_<MODE> beside TINY_SKU10_<MODE>, 2,30 m goes as 2 × the
metre SKU and 3 × the 10 cm one, at the price the customer paid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:00:00 -03:00
Cauê Faleiros
44cb6ccc16 feat: credit card payments in up to 3 installments
Dropstar sells in up to 3 installments. The card form offers no more, and
the server refuses a payment asking for more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:00:00 -03:00
Cauê Faleiros
c75c40ff28 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>
2026-10-07 15:00:00 -03:00
Cauê Faleiros
6c2dcc77b0 docs: the Site guide for today's Site, with its source in the repository
The 24/09 guide said files go up to 128 MB (5 GB now), that the team
reviews every quote before payment (the Site approves it), that payment
is PIX or card (credit card or PIX, on a page of its own), that WhatsApp
notices go out at four moments (two do; the team sends the correction
notice), and showed the order number customers no longer see. It lacked
Minha conta, freight by CEP, choosing which cart items to pay and the
refusal messages, and its status page was from week 2. Rebuilt in the
operator guide's format, source in docs/guias/site, new screenshots from
the local stack with fictional customers; imprimir.sh prints both guides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:42:29 -03:00
Cauê Faleiros
5063c152c2 fix: the Site no longer promises a review before payment, notices at every step, or boleto
The home page's steps said "Conferimos a metragem e liberamos o pagamento"
and "Aviso no WhatsApp a cada etapa": carts are now approved by the Site
and paid at once, and WhatsApp notices go out when the payment is approved
and when the order is ready. They read "Pague na hora: cartão de crédito ou
PIX" and "Acompanhe em Minha conta, com aviso no WhatsApp quando ficar
pronto". The footer listed boleto, which the Site does not take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:42:28 -03:00
35 changed files with 1083 additions and 81 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

@@ -190,7 +190,8 @@ class PaymentMethod(StrictModel):
# in the browser; the number never reaches this server. # in the browser; the number never reaches this server.
token: str | None = Field(default=None, max_length=200) token: str | None = Field(default=None, max_length=200)
payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$') payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$')
installments: int = Field(default=1, ge=1, le=12, strict=True) # Up to 3, as Dropstar sells; the card form offers no more.
installments: int = Field(default=1, ge=1, le=3, strict=True)
issuer_id: str | None = Field(default=None, max_length=40) issuer_id: str | None = Field(default=None, max_length=40)
# The cardholder's document from the card form: for a card, the payer is # The cardholder's document from the card form: for a card, the payer is
# the cardholder, not necessarily the company on the invoice. # the cardholder, not necessarily the company on the invoice.

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)
);

View File

@@ -49,10 +49,12 @@ PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT
# the mode's product id. # the mode's product id.
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA', SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'} 'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'}
# Or a single SKU per 10 cm, as the client sells UV ("DTFIMP.UV.010CM"): # Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after
# 2,30 m is 23 of it. # a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm.
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA', STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'} 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'}
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'}
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada', PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
'avulsa': 'DTF Têxtil 57 cm · artes avulsas', 'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
'uvfile': 'DTF UV 28,5 cm · folha montada', 'uvfile': 'DTF UV 28,5 cm · folha montada',
@@ -116,10 +118,15 @@ def step_sku(mode):
return os.environ.get(STEP_SETTINGS[mode], '').strip() return os.environ.get(STEP_SETTINGS[mode], '').strip()
def metre_sku(mode):
"""The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone."""
return os.environ.get(METRE_SETTINGS[mode], '').strip() if step_sku(mode) else ''
def mode_codes(mode): def mode_codes(mode):
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id.""" """Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
if step_sku(mode): if step_sku(mode):
return [step_sku(mode)] return [code for code in (metre_sku(mode), step_sku(mode)) if code]
return sku_codes(sku_prefix(mode)) if sku_prefix(mode) else [] return sku_codes(sku_prefix(mode)) if sku_prefix(mode) else []
@@ -137,10 +144,23 @@ def tenths(item):
return int(steps), int(billed * int(item['unit_cents'])) return int(steps), int(billed * int(item['unit_cents']))
def step_lines(item, code): def step_lines(item, code, metre=''):
"""(code, quantity, cents each) for a single 10 cm SKU, adding up to the """(code, quantity, cents each) for a 10 cm SKU, after whole metres of the
item's total; a rest that does not divide goes on one line of its own.""" metre SKU when there is one, adding up to the item's total; a rest that
does not divide goes on one line of its own."""
steps, total = tenths(item) steps, total = tenths(item)
lines = []
if metre and steps >= 10:
metres, steps = divmod(steps, 10)
unit = int(item['unit_cents'])
lines.append((metre, metres, unit))
total -= metres * unit
if not steps:
return lines
return lines + split_steps(code, steps, total)
def split_steps(code, steps, total):
each, rest = divmod(total, steps) each, rest = divmod(total, steps)
if not rest: if not rest:
return [(code, steps, each)] return [(code, steps, each)]
@@ -354,7 +374,7 @@ def order_payload(payload, contact_id, today=None, product_id=None):
if step or prefix: if step or prefix:
if product_id is None: if product_id is None:
raise TinyError(f"{SKU_SETTINGS[item['mode']]} needs the SKUs looked up in Tiny") raise TinyError(f"{SKU_SETTINGS[item['mode']]} needs the SKUs looked up in Tiny")
lines = step_lines(item, step) if step else sku_lines(item, prefix) lines = step_lines(item, step, metre_sku(item['mode'])) if step else sku_lines(item, prefix)
for index, (code, quantity, cents) in enumerate(lines): for index, (code, quantity, cents) in enumerate(lines):
line = {'produto': {'id': product_id(code)}, 'quantidade': quantity, 'valorUnitario': money(cents)} line = {'produto': {'id': product_id(code)}, 'quantidade': quantity, 'valorUnitario': money(cents)}
if index == 0: if index == 0:

View File

@@ -71,7 +71,9 @@ def conferir(orders, out):
if step: if step:
result = tiny.configured_skus(orders, mode) result = tiny.configured_skus(orders, mode)
ok &= result == 'ok' ok &= result == 'ok'
out(f'{tiny.STEP_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} ({step} a cada 10 cm)') metre = tiny.metre_sku(mode)
out(f'{tiny.STEP_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
f'({metre + " por metro e " if metre else ""}{step} a cada 10 cm)')
continue continue
if prefix: if prefix:
result = tiny.configured_skus(orders, mode) result = tiny.configured_skus(orders, mode)

View File

@@ -66,6 +66,10 @@ x-app: &app
TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-} TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-}
TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-} TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-}
TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-} TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-}
TINY_SKU_METRO_TEXTIL_FOLHA: ${TINY_SKU_METRO_TEXTIL_FOLHA:-}
TINY_SKU_METRO_TEXTIL_AVULSA: ${TINY_SKU_METRO_TEXTIL_AVULSA:-}
TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-}
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-} TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
WHATSAPP_ADAPTER: fake WHATSAPP_ADAPTER: fake
STORAGE_ADAPTER: s3-local STORAGE_ADAPTER: s3-local

View File

@@ -80,6 +80,10 @@ x-app-environment: &app-environment
TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-} TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-}
TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-} TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-}
TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-} TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-}
TINY_SKU_METRO_TEXTIL_FOLHA: ${TINY_SKU_METRO_TEXTIL_FOLHA:-}
TINY_SKU_METRO_TEXTIL_AVULSA: ${TINY_SKU_METRO_TEXTIL_AVULSA:-}
TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-}
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
# The client's "retirar pessoalmente" forma de envio id, on pickup orders. # The client's "retirar pessoalmente" forma de envio id, on pickup orders.
TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-} TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-}
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup # Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup

View File

@@ -316,6 +316,8 @@ TINY_SKU_UV_FOLHA=
TINY_SKU_UV_AVULSA= TINY_SKU_UV_AVULSA=
TINY_SKU10_UV_FOLHA=DTFIMP.UV.010CM # or one SKU per 10 cm: 2,30 m = 23 of it (the client's UV) TINY_SKU10_UV_FOLHA=DTFIMP.UV.010CM # or one SKU per 10 cm: 2,30 m = 23 of it (the client's UV)
TINY_SKU10_UV_AVULSA=DTFIMP.UV.010CM TINY_SKU10_UV_AVULSA=DTFIMP.UV.010CM
TINY_SKU_METRO_UV_FOLHA=DTFIMP.UV.1MT # with a 10 cm SKU: whole metres first (2,30 m = 2 × 1MT + 3 × 010CM)
TINY_SKU_METRO_UV_AVULSA=DTFIMP.UV.1MT
``` ```
With the client ID and secret set, the Kanban header shows **Conectar Tiny**. With the client ID and secret set, the Kanban header shows **Conectar Tiny**.

Binary file not shown.

View File

@@ -6,3 +6,5 @@ cd "$(dirname "$0")"
CHROME=${CHROME:-$(command -v google-chrome-stable || command -v google-chrome || command -v chromium)} CHROME=${CHROME:-$(command -v google-chrome-stable || command -v google-chrome || command -v chromium)}
"$CHROME" --headless --disable-gpu --no-pdf-header-footer --run-all-compositor-stages-before-draw \ "$CHROME" --headless --disable-gpu --no-pdf-header-footer --run-all-compositor-stages-before-draw \
--print-to-pdf="$PWD/../guia-operador-kanban.pdf" "file://$PWD/operador/guia-operador-kanban.html" --print-to-pdf="$PWD/../guia-operador-kanban.pdf" "file://$PWD/operador/guia-operador-kanban.html"
"$CHROME" --headless --disable-gpu --no-pdf-header-footer --run-all-compositor-stages-before-draw \
--print-to-pdf="$PWD/../guia-site-dtf.pdf" "file://$PWD/site/guia-site-dtf.html"

View File

@@ -0,0 +1,285 @@
<!DOCTYPE html>
<!-- Source of docs/guia-site-dtf.pdf. Print with docs/guias/imprimir.sh.
Screenshots in img/ come from the local stack with fictional customers. -->
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<title>Site DTF · Como funciona</title>
<style>
@page { size: A4; margin: 0; }
:root {
--navy: #0B1320; --orange: #F08A24; --ink: #1B2331; --muted: #6B7280;
--line: #D6DCE4; --head: #EAF0F8; --note: #FFF5E8; --note-line: #F4C58E;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body { font-family: 'DejaVu Sans', sans-serif; color: var(--ink); font-size: 9.7pt; line-height: 1.55;
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
.page { width: 210mm; height: 297mm; position: relative; padding: 26mm 18mm 20mm; overflow: hidden;
page-break-after: always; break-after: page; }
.page:last-child { page-break-after: auto; break-after: auto; }
.running { position: absolute; top: 9mm; left: 18mm; right: 18mm; font-size: 7.4pt; color: var(--muted);
border-bottom: 0.6pt solid #E3E7ED; padding-bottom: 2.4mm; }
.folio { position: absolute; bottom: 9mm; right: 18mm; font-size: 7.4pt; color: var(--muted); }
.kicker { color: var(--orange); font-weight: bold; font-size: 7.6pt; letter-spacing: 0.04em; margin: 0 0 1mm; }
h1 { font-size: 20.5pt; line-height: 1.2; margin: 0 0 2mm; color: #101826; }
h1::after { content: ""; display: block; width: 18mm; height: 1.4mm; background: var(--orange); margin-top: 3mm; }
h2 { font-size: 11.5pt; margin: 7mm 0 2.5mm; color: #101826; }
p { margin: 0 0 2.6mm; }
b { font-weight: bold; }
table { width: 100%; border-collapse: collapse; margin: 2mm 0 3mm; font-size: 8.6pt; line-height: 1.45; }
th, td { border: 0.6pt solid var(--line); padding: 2mm 2.4mm; vertical-align: top; text-align: left; }
th { background: var(--head); font-weight: bold; }
td.n { color: var(--orange); font-weight: bold; font-size: 11pt; width: 7mm; text-align: center; }
td.k { font-weight: bold; }
.note { background: var(--note); border: 0.6pt solid var(--note-line); border-radius: 2mm; padding: 3mm 3.6mm;
font-size: 8.6pt; margin: 3mm 0; }
ul { margin: 0 0 3mm; padding-left: 4.5mm; }
ul li { margin-bottom: 1.1mm; }
ul li::marker { color: var(--orange); }
ol { margin: 0 0 3mm; padding-left: 5mm; }
ol li { margin-bottom: 1.3mm; }
ol li::marker { color: var(--orange); font-weight: bold; }
.chip { display: inline-block; border: 0.6pt solid #C9D0DA; background: #F4F6F9; border-radius: 1.2mm;
padding: 0 1.6mm; font-size: 7.6pt; line-height: 1.6; white-space: nowrap; }
.shot { display: block; width: 100%; border-radius: 1.6mm; margin: 2mm 0 1mm; }
.caption { font-size: 7.2pt; color: var(--muted); margin: 0 0 3mm; }
.split { display: flex; gap: 6mm; align-items: flex-start; }
.split > div { flex: 1; }
.split > .side { flex: 0 0 79.5mm; }
.quote { font-style: normal; }
.shot.half { width: 62%; }
.shot.narrow { width: 78%; }
/* Cover */
.cover { background: var(--navy); color: #F3F5F8; padding: 0 18mm; }
.cover .block { position: absolute; left: 18mm; right: 18mm; top: 158mm; }
.cover .kicker { margin-bottom: 4mm; }
.cover .title { font-size: 27pt; font-weight: bold; line-height: 1.25; margin: 0 0 4mm; color: #fff; }
.cover .lead { font-size: 9.6pt; color: #C8CFDA; margin: 0 0 8mm; }
.cover table { font-size: 8pt; margin: 0 0 8mm; }
.cover th, .cover td { border-color: #2A3547; background: transparent; color: #E6EAF0; padding: 3mm 3.6mm; }
.cover th { color: var(--orange); }
.cover .version { font-size: 8pt; color: #A9B2C0; }
</style>
</head>
<body>
<!-- 1 · Capa -->
<section class="page cover">
<div class="block">
<p class="kicker">GUIA DO SITE</p>
<p class="title">Site DTF<br>Como funciona</p>
<p class="lead">Do envio da arte ao pedido pronto: o que o cliente vê e o que acontece em cada etapa.</p>
<table>
<tr><th style="width:50%">Endereço</th><th>Para quem</th></tr>
<tr><td>dtf.agenciacompor.com.br<br>(endereço provisório)</td><td>Equipe Dropstar e atendimento</td></tr>
</table>
<p class="version">Versão de 7 de outubro de 2026</p>
</div>
</section>
<!-- 2 · Jornada -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">VISÃO GERAL</p>
<h1>A jornada do cliente</h1>
<p>O cliente escolhe o produto, envia as artes e vê a nota e o preço na hora, sem cadastro. Fecha o carrinho e paga
em seguida: o Site confere o pedido sozinho.</p>
<table>
<tr><td class="n">1</td><td class="k" style="width:34mm">Escolhe o produto</td>
<td>Quatro opções: DTF Têxtil ou DTF UV, com folha já montada ou artes avulsas.</td></tr>
<tr><td class="n">2</td><td class="k">Monta a folha</td>
<td>Envia as artes, informa tamanho e quantidade e vê a folha, a nota e o total.</td></tr>
<tr><td class="n">3</td><td class="k">Carrinho</td>
<td>Escolhe os itens que vai pagar, informa CNPJ, WhatsApp e e-mail e escolhe retirada ou entrega.</td></tr>
<tr><td class="n">4</td><td class="k">Pagamento</td>
<td>Cartão de crédito ou PIX pelo Mercado Pago, na própria página. Os dados do cartão não passam pelo nosso servidor.</td></tr>
<tr><td class="n">5</td><td class="k">Produção</td>
<td>Com o pagamento aprovado, o pedido aparece no Kanban da equipe.</td></tr>
<tr><td class="n">6</td><td class="k">Acompanhamento</td>
<td>Em <b>Minha conta</b>, pelo código do pedido, e por WhatsApp quando o pagamento é aprovado e quando o pedido fica pronto.</td></tr>
</table>
<img class="shot" src="img/inicio.png" alt="Página inicial do Site DTF">
<p class="caption">Página inicial do Site DTF.</p>
<div class="folio">Página 2</div>
</section>
<!-- 3 · Produtos e preços -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">PRODUTOS E PREÇOS</p>
<h1>Quatro produtos, um preço por nota</h1>
<img class="shot" src="img/produtos.png" alt="Escolha do produto">
<p>O preço do metro depende da <b>nota da arte</b>, calculada pela resolução no tamanho em que vai ser impressa.
Quanto melhor o arquivo, menor o preço.</p>
<table>
<tr><th>Nota da arte</th><th>Têxtil 57 cm<br>folha montada</th><th>Têxtil 57 cm<br>artes avulsas</th><th>UV 28,5 cm<br>folha montada</th><th>UV 28,5 cm<br>artes avulsas</th></tr>
<tr><td>90 a 100</td><td>R$ 14,90</td><td>R$ 24,90</td><td>R$ 69,90</td><td>R$ 83,90</td></tr>
<tr><td>75 a 89</td><td>R$ 16,20</td><td>R$ 26,20</td><td>R$ 73,90</td><td>R$ 87,90</td></tr>
<tr><td>60 a 74</td><td>R$ 17,50</td><td>R$ 27,50</td><td>R$ 77,90</td><td>R$ 91,90</td></tr>
<tr><td>40 a 59</td><td>R$ 18,70</td><td>R$ 28,70</td><td>R$ 81,90</td><td>R$ 95,90</td></tr>
<tr><td>abaixo de 40</td><td>R$ 19,90</td><td>R$ 29,90</td><td>R$ 85,90</td><td>R$ 99,90</td></tr>
</table>
<ul>
<li><b>Artes avulsas</b> incluem a montagem da folha: R$ 10,00 a mais por metro no têxtil e R$ 14,00 no UV, em qualquer nota.</li>
<li>A cobrança é a cada <b>10 cm</b> (uma folha de 2,75 m custa 2,80 m) e o pedido mínimo é de <b>1 metro</b>.</li>
<li>Folhas em CDR, AI, PSD ou TIFF não têm conferência automática: o metro vai pela tabela cheia e a equipe prepara o arquivo à mão.</li>
</ul>
<div class="folio">Página 3</div>
</section>
<!-- 4 · Montar a folha -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">PASSO 1</p>
<h1>Montar a folha</h1>
<img class="shot" src="img/montagem.png" alt="Página de um produto">
<p class="caption">Página de um produto: as artes à esquerda e, à direita, a folha montada ao vivo.</p>
<ul>
<li><b>Enviar as artes</b>: arrastar para a área de envio ou clicar para escolher. Artes avulsas aceitam PNG, JPG ou
WEBP; a folha montada aceita PNG, JPG ou PDF (e CDR, AI, PSD e TIFF pela tabela cheia).</li>
<li><b>Arquivos de até 5 GB</b>. O envio começa assim que a arte entra, com uma barra que mostra quanto tempo falta.
Todo arquivo passa por antivírus (até 2 GB) ou pela conferência do formato (acima disso) antes de chegar à equipe.</li>
<li><b>Tamanho e quantidade</b>: o cliente informa a largura de cada arte na peça e quantas cópias quer. Botões com
medidas comuns agilizam, e cada arte pode ser girada ou espelhada.</li>
<li><b>Dicas na própria arte</b>: se uma arte está pequena para o tamanho pedido, o Site diz até que medida ela sai em
300 DPI. Se uma largura um pouco menor economiza filme, aparece o botão para usar essa medida.</li>
<li><b>Folha já montada / Artes separadas</b>: a opção no topo troca entre enviar a folha pronta e mandar as artes
para a equipe montar, com a diferença de preço à vista.</li>
</ul>
<div class="folio">Página 4</div>
</section>
<!-- 5 · A folha, a nota e o total -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">PASSO 1</p>
<h1>A folha, a nota e o total</h1>
<div class="split">
<div class="side" style="flex-basis:72mm"><img class="shot" src="img/painel.png" alt="Quadro da folha, nota e total"></div>
<div>
<p>O quadro da direita acompanha o cliente enquanto ele monta:</p>
<ul>
<li><b>Montagem ao vivo</b>: como as artes vão ficar no filme de 57 cm, e quanto da folha virou arte. O arquivo de
impressão é gerado com exatamente essa montagem.</li>
<li><b>Preço do metro pela resolução</b>: a escala mostra em que faixa a arte está e quanto custaria em cada uma.</li>
<li><b>Metragem</b> cobrada a cada 10 cm. Quando a folha tem menos de 1 m, o Site mostra quantos centímetros de
artes ainda cabem sem custo.</li>
<li><b>Total</b> do item e quanto o cliente economizou pela resolução.</li>
<li><b>Ressalva de resolução</b>: se alguma arte fica abaixo de 300 DPI, o cliente precisa marcar que leu e quer
imprimir assim. Abaixo de 96 DPI o Site não aceita a arte.</li>
<li><b>Adicionar ao carrinho</b> leva o item para o carrinho; dá para montar outros itens e pagar tudo junto.</li>
</ul>
</div>
</div>
<div class="folio">Página 5</div>
</section>
<!-- 6 · Carrinho -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">PASSO 2</p>
<h1>Carrinho, dados e entrega</h1>
<img class="shot" src="img/carrinho.png" alt="Carrinho com dados e entrega">
<ul>
<li><b>Itens</b>: cada item aparece com a miniatura da arte. O cliente marca quais quer pagar agora; os outros ficam no
carrinho. <b>Remover</b> e <b>Esvaziar carrinho</b> podem ser desfeitos na hora.</li>
<li><b>Seus dados</b>: CNPJ (o mesmo da nota fiscal), WhatsApp e e-mail.</li>
<li><b>Forma de entrega</b>: <b>Retirar em Franca</b> (Av. Major Elias Motta, 1281, Jardim São Luís, de segunda a
sexta, das 7h às 17h) ou <b>Receber em casa</b>. Na entrega, o CEP preenche o endereço e o frete da Jadlog aparece
na hora, com o prazo já contando o dia de produção.</li>
<li><b>Arquivos enviados</b> confirma que as artes já chegaram. Os arquivos de um carrinho não pago ficam guardados
por 2 dias.</li>
</ul>
<div class="folio">Página 6</div>
</section>
<!-- 7 · Pagamento -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">PASSO 3</p>
<h1>Pagamento</h1>
<p>Em <b>Ir para o pagamento</b>, o Site confere o carrinho no servidor (preço, metragem e a nota pelos próprios
arquivos) e libera o pagamento na hora. Só esperam a equipe os pedidos acima de <b>50 m</b> e os que pedem uma nota
que não confere com os arquivos. Depois da aprovação, o cliente tem <b>24 horas</b> para pagar.</p>
<table>
<tr><th style="width:38mm">Forma</th><th>Como funciona</th></tr>
<tr><td class="k">Cartão de crédito</td><td>No formulário seguro do Mercado Pago, dentro da página, em até 12
parcelas. Os dados do cartão não passam pelo nosso servidor.</td></tr>
<tr><td class="k">PIX</td><td>QR Code e código copia e cola na própria página, válidos por 30 minutos, com contagem.
A página confirma sozinha quando o pagamento cai.</td></tr>
</table>
<h2>Quando o cartão é recusado</h2>
<p>O cliente vê o motivo em uma frase e o que fazer, por exemplo:</p>
<ul>
<li>“O cartão não tem limite suficiente para este valor. Use outro cartão ou pague com PIX.”</li>
<li>“O código de segurança (CVV) está incorreto. Confira e tente de novo.”</li>
<li>“O banco precisa autorizar este pagamento. Ligue para o banco emissor e tente de novo, ou use outro cartão.”</li>
</ul>
<h2>Pagamento aprovado</h2>
<p>A página mostra <b>Pagamento confirmado</b> e o botão <b>Ver meus pedidos</b>. O pedido entra na produção e aparece
no Kanban. Para o cliente, o pedido tem um <b>código</b> (ex.: <span class="chip">3F0CB7C2</span>); o número
sequencial fica só com a equipe.</p>
<div class="folio">Página 7</div>
</section>
<!-- 8 · Minha conta -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">ACOMPANHAMENTO</p>
<h1>Minha conta</h1>
<p>O cliente entra com e-mail e senha, ou cria a conta com CNPJ, WhatsApp, e-mail e uma senha de 12 caracteres ou
mais. Quem pagou sem conta vê os pedidos no mesmo navegador, e eles passam para a conta quando ela é criada.</p>
<img class="shot narrow" src="img/conta.png" alt="Visão geral de Minha conta">
<ul>
<li><b>Visão geral</b>: quantos pedidos aguardam pagamento, estão em produção, em correção ou finalizados.</li>
<li><b>Pedidos</b>: a lista com código, produto, metragem, situação e valor, com filtros e busca pelo código. Cada
pedido mostra as etapas e o andamento, com data e hora.</li>
<li><b>Dados da conta</b>: CNPJ, WhatsApp e e-mail, e a troca de senha.</li>
</ul>
<div class="note"><b>Esqueci minha senha</b> ainda leva ao WhatsApp da Dropstar: a recuperação por e-mail entra
quando o servidor de e-mail estiver configurado.</div>
<div class="folio">Página 8</div>
</section>
<!-- 9 · Correção -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">ACOMPANHAMENTO</p>
<h1>Correção e avisos</h1>
<img class="shot" src="img/pedido-correcao.png" alt="Pedido em correção em Minha conta">
<p class="caption">Pedido em correção: o motivo escrito pela equipe e o envio do arquivo corrigido.</p>
<p>Quando a equipe pede uma correção, o pedido aparece em <b>Correção</b> em Minha conta, com o motivo. O cliente envia
a arte corrigida ali mesmo, com uma nota do que mudou, e a equipe segue com o pedido. A equipe avisa o cliente pelo
WhatsApp, com a mensagem pronta no Kanban.</p>
<ul>
<li><b>Avisos automáticos por WhatsApp</b>: pagamento aprovado e pedido pronto para retirada, pelo número e pelas
mensagens que a Dropstar já usa.</li>
<li>As artes ficam guardadas por <b>30 dias</b>. Depois disso, para repetir o pedido, o cliente envia os arquivos de novo.</li>
</ul>
<div class="folio">Página 9</div>
</section>
<!-- 10 · Situação atual -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">SITUAÇÃO ATUAL</p>
<h1>O que já funciona e o que falta para o lançamento</h1>
<table>
<tr><th style="width:44mm">Parte</th><th style="width:36mm">Situação</th><th>Observação</th></tr>
<tr><td class="k">Site: produtos, montagem, nota e preço</td><td>Funcionando</td><td>Tabela e regras comerciais do Site DTF mantidas.</td></tr>
<tr><td class="k">Arquivos de até 5 GB</td><td>Funcionando</td><td>Antivírus até 2 GB; acima disso, conferência do formato.</td></tr>
<tr><td class="k">Frete (receber em casa)</td><td>Funcionando</td><td>Jadlog, com a caixa e o peso informados pela Dropstar.</td></tr>
<tr><td class="k">Pagamento</td><td>Funcionando em teste</td><td>Cartão de crédito e PIX testados com as credenciais de teste; falta ativar as de produção.</td></tr>
<tr><td class="k">Minha conta</td><td>Funcionando</td><td>Pedidos, correção e dados da conta.</td></tr>
<tr><td class="k">Kanban de produção</td><td>Funcionando</td><td>Veja o guia do operador.</td></tr>
<tr><td class="k">Pedido no Tiny e avisos por WhatsApp</td><td>Pronto, falta o teste</td><td>Ativados depois do pedido de teste acompanhado no Tiny.</td></tr>
<tr><td class="k">Recuperação de senha</td><td>Depende do e-mail</td><td>Entra com os dados do servidor de e-mail (SMTP).</td></tr>
<tr><td class="k">Domínio</td><td>Provisório</td><td>dtf.agenciacompor.com.br até a definição do domínio definitivo.</td></tr>
</table>
<div class="folio">Página 10</div>
</section>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

View File

@@ -61,6 +61,9 @@ def run():
# Debit cards are not taken, even sent around the payment page. # Debit cards are not taken, even sent around the payment page.
customer.call('/payments/intent', {'quote_id': quote_id, 'method': { customer.call('/payments/intent', {'quote_id': quote_id, 'method': {
'type': 'card', 'token': 'tok', 'payment_method_id': 'debvisa'}}, expected=422) 'type': 'card', 'token': 'tok', 'payment_method_id': 'debvisa'}}, expected=422)
# At most 3 installments.
customer.call('/payments/intent', {'quote_id': quote_id, 'method': {
'type': 'card', 'token': 'tok', 'payment_method_id': 'visa', 'installments': 4}}, expected=422)
# Starting a PIX twice returns the same one. A card in review blocks every # Starting a PIX twice returns the same one. A card in review blocks every
# further attempt, so one quote can never be charged twice. # further attempt, so one quote can never be charged twice.

View File

@@ -336,6 +336,32 @@ class TinyStepSkuTests(FakeTinyCase):
self.assertIn('DTFIMP.UV.010CM', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada']) self.assertIn('DTFIMP.UV.010CM', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'])
@mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU10_UV_FOLHA': 'DTFIMP.UV.010CM',
'TINY_SKU_METRO_UV_FOLHA': 'DTFIMP.UV.1MT'})
class TinyMetreAndStepSkuTests(FakeTinyCase):
"""UV as the client registered it: DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm."""
def setUp(self):
super().setUp()
self.products['300'] = {'id': 300, 'sku': 'DTFIMP.UV.010CM', 'descricao': 'UV 10 cm', 'situacao': 'A'}
self.products['301'] = {'id': 301, 'sku': 'DTFIMP.UV.1MT', 'descricao': 'UV 1 metro', 'situacao': 'A'}
def test_whole_metres_then_ten_centimetre_steps(self):
self.tiny.deliver('k1', UV)
lines = [(i['produto']['id'], i['quantidade'], i['valorUnitario']) for i in self.orders[0]['itens']]
# 2,30 m at R$ 69,90: 2 × "1 metro" + 3 × "10 cm", R$ 160,77 in all.
self.assertEqual(lines, [(301, 2, 69.9), (300, 3, 6.99)])
self.assertAlmostEqual(sum(q * v for _, q, v in lines), 160.77)
def test_whole_metres_alone_and_the_check(self):
from app.tiny import check, step_lines
self.assertEqual(step_lines({'billed_metres': '2', 'unit_cents': 6990}, 'C', 'M'), [('M', 2, 6990)])
self.assertEqual(check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'], 'ok')
del self.products['301']
self.tiny.skus.clear()
self.assertIn('DTFIMP.UV.1MT', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'])
@mock.patch.dict(os.environ, PRODUCTS) @mock.patch.dict(os.environ, PRODUCTS)
class TinyProbeTests(FakeTinyCase): class TinyProbeTests(FakeTinyCase):
"""The supervised console tool run against the fake Tiny.""" """The supervised console tool run against the fake Tiny."""

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

@@ -574,8 +574,8 @@
const mp=new window.MercadoPago(session.payment_public_key,{locale:'pt-BR'}); const mp=new window.MercadoPago(session.payment_public_key,{locale:'pt-BR'});
cardBrick=await mp.bricks().create('cardPayment','cardPaymentBrick',{ cardBrick=await mp.bricks().create('cardPayment','cardPaymentBrick',{
initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail}}, initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail}},
// Credit cards only: the store does not take debit. // Credit cards only, in up to 3 installments, as Dropstar decided.
customization:{paymentMethods:{maxInstallments:12,types:{excluded:['debit_card']}}, customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}},
// The option above already names the card; the form's own title // The option above already names the card; the form's own title
// ("crédito ou débito") would contradict it. // ("crédito ou débito") would contradict it.
visual:{hideFormTitle:true, visual:{hideFormTitle:true,

View File

@@ -746,8 +746,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<section class="etapas2"><div class="w"> <section class="etapas2"><div class="w">
<div><span>1</span><div><b>Envie a arte</b><p>PNG, JPG ou PDF, conforme o produto. Sem cadastro.</p></div></div> <div><span>1</span><div><b>Envie a arte</b><p>PNG, JPG ou PDF, conforme o produto. Sem cadastro.</p></div></div>
<div><span>2</span><div><b>Veja nota e montagem</b><p>A folha e o preço aparecem na hora.</p></div></div> <div><span>2</span><div><b>Veja nota e montagem</b><p>A folha e o preço aparecem na hora.</p></div></div>
<div><span>3</span><div><b>Confira e pague</b><p>Conferimos a metragem e liberamos o pagamento.</p></div></div> <div><span>3</span><div><b>Pague na hora</b><p>Cartão de crédito ou PIX, na própria página.</p></div></div>
<div><span>4</span><div><b>Acompanhe</b><p>Aviso no WhatsApp a cada etapa.</p></div></div> <div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
</div></section> </div></section>
<!-- ENVIO --> <!-- ENVIO -->
@@ -1158,7 +1158,7 @@ h2 em{font-style:normal;color:var(--laranja)}
</div> </div>
<div class="fbase"> <div class="fbase">
<span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span> <span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span>
<span>Visa · Master · Elo · Amex · Pix · Boleto</span> <span>Cartão de crédito (Visa · Master · Elo · Amex) · PIX</span>
<span>têxtil 57 cm · UV 28,5 cm</span> <span>têxtil 57 cm · UV 28,5 cm</span>
</div> </div>
</div></footer> </div></footer>

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)});});

View File

@@ -156,7 +156,7 @@
</div> </div>
<div class="fbase"> <div class="fbase">
<span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span> <span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span>
<span>Visa · Master · Elo · Amex · Pix · Boleto</span> <span>Cartão de crédito (Visa · Master · Elo · Amex) · PIX</span>
<span>têxtil 57 cm · UV 28,5 cm</span> <span>têxtil 57 cm · UV 28,5 cm</span>
</div> </div>
</div></footer> </div></footer>