feat: Dropstar's new flow: Arte conferida is the queue, Revisão and the Revisor
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m24s
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m24s
The board Dropstar drew on 2026-10-23: Arte recebida, Arte conferida, Imprimindo, Correção, Revisão, Finalizado. - Fila de impressão leaves the board: Arte conferida is the queue. It takes an order only with every item's final approved, keeps the finals as approved, orders its cards for printing and has the room's "Baixar" and the automatic folder. Orders that were in the queue move there once, with a line in their history - Revisão checks the printed sheet, and the new Revisor profile is the only one that sends an order to Finalizado (the superadmin too, for support) - who moves what, from the server (MOVES): the designer the artwork, asking for corrections and bringing the new art back; the operator Arte conferida to Imprimindo to Revisão; admin and gestão everything else, Correção included; a step back belongs to whoever makes the move it undoes - Tiny: Arte conferida is "Preparando envio" and Finalizado "Pronto para envio", for delivery orders too - Prova OK still comes before Finalizado; the customer's portal shows the new steps Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -86,7 +86,7 @@ jobs:
|
|||||||
# the generator's geometry. The provider suites use a fake transport: they
|
# the generator's geometry. The provider suites use a fake transport: they
|
||||||
# prove the documented contract, not the integration.
|
# prove the documented contract, not the integration.
|
||||||
- name: Print-file geometry and provider adapters
|
- name: Print-file geometry and provider adapters
|
||||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v
|
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v
|
||||||
|
|
||||||
- name: Runtime and retention regressions
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ 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')
|
||||||
if row['state'] not in ('rec','tra','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
||||||
return begin_upload(body, session_id=operator_identity(user))
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
@router.get('/api/operator/uploads/{uid}')
|
@router.get('/api/operator/uploads/{uid}')
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ from fastapi.responses import RedirectResponse
|
|||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import (COOKIE_SECURE, DESIGNER_STATES, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator,
|
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
|
||||||
login_failed, password_matches, throttle)
|
login_failed, may_move, may_reorder, password_matches, throttle)
|
||||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
||||||
from ..printjobs import file_prefix, queue as queue_print_files
|
from ..printjobs import file_prefix, queue as queue_print_files
|
||||||
from .. import cnpj, machines, mail, payments, proof, quote_review
|
from .. import cnpj, machines, mail, payments, proof, quote_review
|
||||||
@@ -508,13 +508,6 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
|||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
def designer_only(request, *states):
|
|
||||||
"""A designer works on the artwork stages only: Arte recebida, Arte
|
|
||||||
conferida and Correção. The queue onwards is the print room's."""
|
|
||||||
if request.state.operator['role'] == 'designer' and not set(states) <= set(DESIGNER_STATES):
|
|
||||||
raise HTTPException(403, 'O perfil Designer move pedidos só entre Arte recebida, Arte conferida e Correção.')
|
|
||||||
|
|
||||||
|
|
||||||
class MachineChoice(StrictModel):
|
class MachineChoice(StrictModel):
|
||||||
machine_id: UUID | None = None
|
machine_id: UUID | None = None
|
||||||
|
|
||||||
@@ -581,7 +574,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, request: Request, user=Depends(can('produce'))):
|
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(operator)):
|
||||||
"""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)."""
|
||||||
@@ -591,7 +584,8 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(can(
|
|||||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Order not found')
|
raise HTTPException(404, 'Order not found')
|
||||||
designer_only(request, row['state'])
|
if not may_reorder(request.state.operator['role'], row['state']):
|
||||||
|
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
|
||||||
keys = {}
|
keys = {}
|
||||||
for side in ('after', 'before'):
|
for side in ('after', 'before'):
|
||||||
other = getattr(body, side)
|
other = getattr(body, side)
|
||||||
@@ -612,7 +606,9 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(can(
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/orders/{uid}/move')
|
@router.post('/api/operator/orders/{uid}/move')
|
||||||
def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
|
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||||
|
if request.state.operator['role'] not in MOVERS:
|
||||||
|
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||||
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:
|
||||||
@@ -623,19 +619,22 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
|
|||||||
raise HTTPException(409, 'Pedido cancelado.')
|
raise HTTPException(409, 'Pedido cancelado.')
|
||||||
if body.state == row['state']:
|
if body.state == row['state']:
|
||||||
return row
|
return row
|
||||||
designer_only(request, row['state'], body.state)
|
|
||||||
back = BACK.get(row['state']) == body.state
|
back = BACK.get(row['state']) == body.state
|
||||||
if body.state not in TRANSITIONS[row['state']] and not back:
|
if body.state not in TRANSITIONS[row['state']] and not back:
|
||||||
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
|
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||||
|
if not may_move(request.state.operator['role'], row['state'], body.state, back):
|
||||||
|
raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back
|
||||||
|
else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||||
if body.state == 'cor' and not body.reason.strip():
|
if body.state == 'cor' and not body.reason.strip():
|
||||||
raise HTTPException(422, 'Informe o motivo da correção.')
|
raise HTTPException(422, 'Informe o motivo da correção.')
|
||||||
if back and not body.reason.strip():
|
if back and not body.reason.strip():
|
||||||
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
||||||
if body.state in ('fil','imp'):
|
# Arte conferida is the queue: what enters it has its final files approved.
|
||||||
|
if body.state in ('tra','imp'):
|
||||||
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
||||||
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
|
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
|
||||||
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
|
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
|
||||||
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de colocar na fila.')
|
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
|
||||||
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
|
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
|
||||||
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
|
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
|
||||||
if body.state == 'cor':
|
if body.state == 'cor':
|
||||||
@@ -643,12 +642,14 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
|
|||||||
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
|
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
|
||||||
(uid,row['state'],body.state,user,body.reason,back))
|
(uid,row['state'],body.state,user,body.reason,back))
|
||||||
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
|
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
|
||||||
events = {'imp':'production_started','cor':'correction_needed','fin':'ready'}
|
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
||||||
|
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
||||||
|
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
||||||
if body.state in events and not back and not payments.is_test(row):
|
if body.state in events and not back and not payments.is_test(row):
|
||||||
# "Production started" and "ready" reach the customer once per order,
|
# "Production started" and "ready" reach the customer once per order,
|
||||||
# even if a mistaken move is undone and made again. Each correction
|
# even if a mistaken move is undone and made again. Each correction
|
||||||
# is a new request, so it keeps one message per movement.
|
# is a new request, so it keeps one message per movement.
|
||||||
once = body.state in ('imp','fin')
|
once = body.state in ('tra','fin')
|
||||||
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
|
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
|
||||||
'customer_path': f'/portal.html?order={uid}'}
|
'customer_path': f'/portal.html?order={uid}'}
|
||||||
# Tiny needs the order (customer, pickup or delivery) and, once the
|
# Tiny needs the order (customer, pickup or delivery) and, once the
|
||||||
@@ -897,7 +898,7 @@ def machine_output(c, start, end):
|
|||||||
'metres': made, 'printing_hours': round(hours_in, 2),
|
'metres': made, 'printing_hours': round(hours_in, 2),
|
||||||
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
|
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
|
||||||
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
|
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
|
||||||
'now': {state: m['states'].get(state, 0) for state in ('fil', 'imp')}})
|
'now': {state: m['states'].get(state, 0) for state in ('tra', 'imp')}})
|
||||||
loose = [row for row in done if row['machine_id'] is None]
|
loose = [row for row in done if row['machine_id'] is None]
|
||||||
if loose:
|
if loose:
|
||||||
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
|
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
|
||||||
@@ -973,11 +974,11 @@ def print_ready(c, request, states):
|
|||||||
|
|
||||||
@router.get('/api/operator/queue/finals')
|
@router.get('/api/operator/queue/finals')
|
||||||
def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))):
|
def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))):
|
||||||
"""The approved final files of every order in the print queue. The browser
|
"""The approved final files of every order in the print queue (Arte
|
||||||
downloads them straight from storage: a zip of multi-GB sheets would go
|
conferida). The browser downloads them straight from storage: a zip of
|
||||||
through the server."""
|
multi-GB sheets would go through the server."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
files = named_files(print_ready(c, request, ('fil',)))
|
files = named_files(print_ready(c, request, ('tra',)))
|
||||||
# The automatic folder asks whenever the queue changes; only a person's download is logged.
|
# The automatic folder asks whenever the queue changes; only a person's download is logged.
|
||||||
if not auto:
|
if not auto:
|
||||||
audit('queue_finals_downloaded', operator=user, files=len(files))
|
audit('queue_finals_downloaded', operator=user, files=len(files))
|
||||||
@@ -997,7 +998,7 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print')))
|
|||||||
for the orders the folder already holds files of: a stage, 'cancelled', or
|
for the orders the folder already holds files of: a stage, 'cancelled', or
|
||||||
nothing when the order was deleted, so their files can be removed."""
|
nothing when the order was deleted, so their files can be removed."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
files = named_files(print_ready(c, request, ('rec', 'tra', 'fil') if body.early else ('fil',)))
|
files = named_files(print_ready(c, request, ('rec', 'tra') if body.early else ('tra',)))
|
||||||
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||||
(body.held,)).fetchall() if body.held else []
|
(body.held,)).fetchall() if body.held else []
|
||||||
return {'files': files,
|
return {'files': files,
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ from pydantic import Field, field_validator
|
|||||||
|
|
||||||
from .. import machines, mail
|
from .. import machines, mail
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
|
from ..core.auth import CAPABILITIES, audit, can, may_move, may_reorder, password_hash, password_matches, signed_in
|
||||||
from ..core.models import StrictModel
|
from ..core.models import StrictModel
|
||||||
|
from ..runtime import BACK, STATES, TRANSITIONS
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@@ -24,7 +25,7 @@ class UserIn(StrictModel):
|
|||||||
# The profiles an administrator may give; superadmin only comes from the console.
|
# The profiles an administrator may give; superadmin only comes from the console.
|
||||||
name: str = Field(min_length=1, max_length=80)
|
name: str = Field(min_length=1, max_length=80)
|
||||||
email: str = Field(min_length=3, max_length=254)
|
email: str = Field(min_length=3, max_length=254)
|
||||||
role: Literal['admin', 'gestao', 'designer', 'operador', 'vendedor']
|
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor']
|
||||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||||
active: bool = True
|
active: bool = True
|
||||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||||
@@ -55,11 +56,17 @@ class PasswordChange(StrictModel):
|
|||||||
|
|
||||||
@router.get('/api/operator/me')
|
@router.get('/api/operator/me')
|
||||||
def me(request: Request):
|
def me(request: Request):
|
||||||
"""Who is signed in, and what the Kanban should offer them."""
|
"""Who is signed in, and what the Kanban should offer them: the moves
|
||||||
|
their profile makes (forward, and the step back) and the columns whose
|
||||||
|
order they set."""
|
||||||
account = signed_in(request)
|
account = signed_in(request)
|
||||||
return {'email': account['email'], 'name': account['name'], 'role': account['role'],
|
role = account['role']
|
||||||
|
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
||||||
|
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
|
||||||
|
return {'email': account['email'], 'name': account['name'], 'role': role,
|
||||||
'machines': account['machines'],
|
'machines': account['machines'],
|
||||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)}
|
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
||||||
|
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/me/password')
|
@router.post('/api/operator/me/password')
|
||||||
|
|||||||
@@ -50,8 +50,9 @@ def correction_owner(c, order, ref, kind):
|
|||||||
def submit_files(c, order, body, identity, kind, actor):
|
def submit_files(c, order, body, identity, kind, actor):
|
||||||
if order['version'] != body.version:
|
if order['version'] != body.version:
|
||||||
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
|
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
|
||||||
if kind == 'final' and order['state'] not in ('rec','tra','cor'):
|
# Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
|
||||||
raise HTTPException(409, 'O arquivo final só pode mudar antes da fila de impressão.')
|
if kind == 'final' and order['state'] not in ('rec','cor'):
|
||||||
|
raise HTTPException(409, 'O arquivo final só muda antes de Arte conferida, a fila. Volte o pedido para Arte recebida para trocar.')
|
||||||
if kind == 'correction' and order['state'] != 'cor':
|
if kind == 'correction' and order['state'] != 'cor':
|
||||||
raise HTTPException(409, 'Este pedido não está esperando correção.')
|
raise HTTPException(409, 'Este pedido não está esperando correção.')
|
||||||
if len({f.upload_id for f in body.files}) != len(body.files):
|
if len({f.upload_id for f in body.files}) != len(body.files):
|
||||||
|
|||||||
@@ -121,9 +121,8 @@ def login_failed(email):
|
|||||||
# Integrações but the print room's folder (connecting Tiny, the checks, the
|
# Integrações but the print room's folder (connecting Tiny, the checks, the
|
||||||
# backup, the Tiny log): the others see there only what is on and off.
|
# backup, the Tiny log): the others see there only what is on and off.
|
||||||
# The designer approves and refuses artwork and asks for corrections, on every
|
# The designer approves and refuses artwork and asks for corrections, on every
|
||||||
# order whatever its machine, and moves cards only among DESIGNER_STATES.
|
# order whatever its machine. Which cards each profile moves is MOVES.
|
||||||
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'vendedor')
|
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor')
|
||||||
DESIGNER_STATES = ('rec', 'tra', 'cor')
|
|
||||||
CAPABILITIES = {
|
CAPABILITIES = {
|
||||||
'view': set(ROLES),
|
'view': set(ROLES),
|
||||||
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
||||||
@@ -133,6 +132,36 @@ CAPABILITIES = {
|
|||||||
'integrations': {'superadmin'},
|
'integrations': {'superadmin'},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Who moves which card (Dropstar's flow, 2026-10-23): the designer the
|
||||||
|
# artwork, the operator the printing, and only the Revisor (and we, the
|
||||||
|
# superadmin, for support) to Finalizado, so nobody releases their own print.
|
||||||
|
# Admin and Gestão make every other move, Correção included. A step back
|
||||||
|
# undoes a mistaken move: open to whoever may make the move it undoes.
|
||||||
|
MOVES = {
|
||||||
|
'designer': {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')},
|
||||||
|
'operador': {('tra', 'imp'), ('imp', 'rev')},
|
||||||
|
'revisor': {('rev', 'fin')},
|
||||||
|
}
|
||||||
|
MANAGERS = ('superadmin', 'admin', 'gestao')
|
||||||
|
RELEASERS = ('revisor', 'superadmin')
|
||||||
|
MOVERS = MANAGERS + tuple(MOVES)
|
||||||
|
|
||||||
|
|
||||||
|
def may_move(role, from_state, to_state, back=False):
|
||||||
|
"""Whether this profile may move a card; `back` is the step back that
|
||||||
|
undoes the move to_state -> from_state."""
|
||||||
|
if back:
|
||||||
|
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
|
||||||
|
if to_state == 'fin':
|
||||||
|
return role in RELEASERS
|
||||||
|
return role in MANAGERS or (from_state, to_state) in MOVES.get(role, ())
|
||||||
|
|
||||||
|
|
||||||
|
def may_reorder(role, state):
|
||||||
|
"""Changing a card's place in its column, the order it is worked in: for
|
||||||
|
whoever takes cards forward out of it."""
|
||||||
|
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
|
||||||
|
|
||||||
|
|
||||||
def signed_in(request: Request):
|
def signed_in(request: Request):
|
||||||
"""The operator behind this session, active, with the profile read now: a
|
"""The operator behind this session, active, with the profile read now: a
|
||||||
|
|||||||
@@ -257,7 +257,7 @@ class PaymentIntent(StrictModel):
|
|||||||
method: PaymentMethod
|
method: PaymentMethod
|
||||||
|
|
||||||
class Move(StrictModel):
|
class Move(StrictModel):
|
||||||
state: Literal['rec','tra','fil','imp','cor','fin']
|
state: Literal['rec','tra','imp','cor','rev','fin']
|
||||||
version: int = Field(ge=0)
|
version: int = Field(ge=0)
|
||||||
reason: str = Field(default='', max_length=1000)
|
reason: str = Field(default='', max_length=1000)
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ orders back to that choice, unless they are already printing.
|
|||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
# Not finished: the work still ahead of a machine.
|
# Not finished: the work still ahead of a machine.
|
||||||
OPEN = ('rec', 'tra', 'fil', 'imp', 'cor')
|
OPEN = ('rec', 'tra', 'imp', 'cor')
|
||||||
# Stages an automatic order may still move from: not once it is printing.
|
# Stages an automatic order may still move from: not once it is printing.
|
||||||
MOVABLE = ('rec', 'tra', 'fil', 'cor')
|
MOVABLE = ('rec', 'tra', 'cor')
|
||||||
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
||||||
LOCK = 7_041_901
|
LOCK = 7_041_901
|
||||||
|
|
||||||
|
|||||||
@@ -51,13 +51,18 @@ BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
|
|||||||
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
|
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
|
||||||
if not 5242880 <= PART_BYTES <= 67108864:
|
if not 5242880 <= PART_BYTES <= 67108864:
|
||||||
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
|
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
|
||||||
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'fil': 'Fila de impressão',
|
# Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
|
||||||
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'}
|
# impressão, 'fil', left the board), and Revisão checks the printed sheet
|
||||||
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
|
# before Finalizado. After a correction the new art goes back through Arte
|
||||||
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []}
|
# recebida or Arte conferida; Gestão may also take it straight to Revisão.
|
||||||
|
# Who may make each move is app/core/auth.py's MOVES.
|
||||||
|
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'imp': 'Imprimindo',
|
||||||
|
'cor': 'Correção', 'rev': 'Revisão', 'fin': 'Finalizado'}
|
||||||
|
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['imp','cor'], 'imp': ['rev','cor'],
|
||||||
|
'rev': ['fin','cor'], 'cor': ['rec','tra','rev'], 'fin': []}
|
||||||
# Undoing a move made by mistake: one stage back, with an internal reason. It
|
# Undoing a move made by mistake: one stage back, with an internal reason. It
|
||||||
# is not a correction: the customer is not told and approved finals stay.
|
# is not a correction: the customer is not told and approved finals stay.
|
||||||
BACK = {'tra': 'rec', 'fil': 'tra', 'imp': 'fil', 'fin': 'imp'}
|
BACK = {'tra': 'rec', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'}
|
||||||
|
|
||||||
|
|
||||||
def real_delivery():
|
def real_delivery():
|
||||||
|
|||||||
@@ -247,11 +247,13 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
|
|||||||
|
|
||||||
-- Who may do what on the Kanban. superadmin is the system's own account (set
|
-- 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
|
-- from the console); administrators manage users and machines; gestão runs
|
||||||
-- the business; designers approve artwork; operadores produce; vendedores only read.
|
-- the business; designers approve artwork; operadores print; revisores check
|
||||||
|
-- the printed sheet and are the only ones to release it to Finalizado;
|
||||||
|
-- vendedores only read.
|
||||||
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
||||||
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
||||||
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||||
CHECK (role IN ('superadmin','admin','gestao','designer','operador','vendedor'));
|
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor'));
|
||||||
-- The print machines, and which products each prints. An order keeps the
|
-- The print machines, and which products each prints. An order keeps the
|
||||||
-- machine someone chose (machine_chosen) or the one given automatically: the
|
-- machine someone chose (machine_chosen) or the one given automatically: the
|
||||||
-- active machine of its product with the fewest metres open (app/machines.py).
|
-- active machine of its product with the fewest metres open (app/machines.py).
|
||||||
@@ -349,3 +351,10 @@ ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
|||||||
-- Finalizado.
|
-- Finalizado.
|
||||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_at timestamptz;
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_at timestamptz;
|
||||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_by text;
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_by text;
|
||||||
|
|
||||||
|
-- Fila de impressão left the board (Dropstar, 2026-10-23): Arte conferida is
|
||||||
|
-- the queue. An order still in it moves there once, with a line in its history.
|
||||||
|
WITH moved AS (UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
||||||
|
WHERE state='fil' RETURNING id)
|
||||||
|
INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||||
|
SELECT id,'fil','tra','sistema','A Fila de impressão saiu do quadro: Arte conferida é a fila.' FROM moved;
|
||||||
|
|||||||
23
app/tiny.py
23
app/tiny.py
@@ -26,15 +26,18 @@ numero_ecommerce.
|
|||||||
|
|
||||||
Customer notices: the client sends WhatsApp messages from Tiny's order
|
Customer notices: the client sends WhatsApp messages from Tiny's order
|
||||||
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
|
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
|
||||||
envio (pickup only), Enviado and Entregue. With TINY_STATUS_UPDATES on, the
|
envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves
|
||||||
Kanban moves the Tiny order along with it:
|
the Tiny order along with it (Dropstar's flow, 2026-10-23: two changes of
|
||||||
|
situação, none for Imprimindo, Correção or Revisão):
|
||||||
|
|
||||||
paid (Arte recebida) -> Aprovada (the "approved" notice)
|
paid (Arte recebida) -> Aprovada (the "approved" notice)
|
||||||
Imprimindo -> Preparando envio (no notice)
|
Arte conferida (queue) -> Preparando envio (no notice)
|
||||||
Finalizado, pickup -> Pronto para envio (the pickup notice)
|
Finalizado -> Pronto para envio (pickup or delivery)
|
||||||
Finalizado, delivery -> unchanged: the team invoices and ships in Tiny
|
|
||||||
cancelled -> Cancelada (no notice)
|
cancelled -> Cancelada (no notice)
|
||||||
|
|
||||||
|
After Pronto para envio the order goes on in Tiny like any other: Enviada,
|
||||||
|
Entregue.
|
||||||
|
|
||||||
An order someone already moved further in Tiny is never moved back, and an
|
An order someone already moved further in Tiny is never moved back, and an
|
||||||
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
|
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
|
||||||
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
||||||
@@ -759,13 +762,9 @@ class TinyOrders:
|
|||||||
return receipt
|
return receipt
|
||||||
|
|
||||||
def ready(self, event_key, payload):
|
def ready(self, event_key, payload):
|
||||||
"""A pickup order became ready: "Pronto para envio", which the client's
|
"""The order reached Finalizado: "Pronto para envio", for pickup and
|
||||||
notices turn into the pickup message. Shipped orders get "Enviada"
|
delivery alike (Dropstar, 2026-10-23). From there the team ships it in
|
||||||
once freight exists (1.2)."""
|
Tiny as any other order."""
|
||||||
base = {'provider': 'tiny', 'event_key': event_key}
|
|
||||||
order = payload.get('order') or {}
|
|
||||||
if (order.get('freight') or {}).get('service') != 'pickup':
|
|
||||||
return {**base, 'status': 'not-applicable', 'event': 'ready'}
|
|
||||||
return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA))
|
return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA))
|
||||||
|
|
||||||
def move(self, event_key, payload, target, from_situacoes):
|
def move(self, event_key, payload, target, from_situacoes):
|
||||||
|
|||||||
@@ -340,7 +340,8 @@ The Kanban, open on the print room's computer, saves the files to a folder
|
|||||||
chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer,
|
chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer,
|
||||||
it downloads as soon as the order arrives in Arte recebida (the default since
|
it downloads as soon as the order arrives in Arte recebida (the default since
|
||||||
2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when
|
2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when
|
||||||
the order enters the queue; or only when the order enters the print queue.
|
the order enters the queue (Arte conferida since 2026-10-26); or only when the
|
||||||
|
order enters the queue.
|
||||||
Files of orders cancelled, deleted or sent back for correction, and files
|
Files of orders cancelled, deleted or sent back for correction, and files
|
||||||
replaced by another final, are removed from the folder
|
replaced by another final, are removed from the folder
|
||||||
(`POST /api/operator/queue/folder`).
|
(`POST /api/operator/queue/folder`).
|
||||||
@@ -352,7 +353,7 @@ produces also gets the folder's row with its buttons.
|
|||||||
|
|
||||||
Machines (2026-10-20, app/machines.py): each order keeps one machine, either
|
Machines (2026-10-20, app/machines.py): each order keeps one machine, either
|
||||||
chosen in the order panel or given on arrival: the active machine of its
|
chosen in the order panel or given on arrival: the active machine of its
|
||||||
product with the fewest metres open (rec, tra, fil, imp, cor), preferring
|
product with the fewest metres open (rec, tra, imp, cor), preferring
|
||||||
those below their optional limit in metres, else the least loaded anyway (the
|
those below their optional limit in metres, else the least loaded anyway (the
|
||||||
Usuários page shows it over the limit). A machine switched off, deleted or no
|
Usuários page shows it over the limit). A machine switched off, deleted or no
|
||||||
longer printing the product hands its automatic orders, not yet printing, to
|
longer printing the product hands its automatic orders, not yet printing, to
|
||||||
@@ -362,9 +363,8 @@ the machine form); a linked operator sees only those machines' orders.
|
|||||||
Dropstar's corrections of 2026-10-21 already done: the home example priced as
|
Dropstar's corrections of 2026-10-21 already done: the home example priced as
|
||||||
a ready sheet; opening hours 7h to 18h with "send your art any time"; uploads
|
a ready sheet; opening hours 7h to 18h with "send your art any time"; uploads
|
||||||
up to 1 GB (MAX_UPLOAD_BYTES, scanned whole by ClamAV); a Designer profile
|
up to 1 GB (MAX_UPLOAD_BYTES, scanned whole by ClamAV); a Designer profile
|
||||||
(artwork stages only, every order, no machine, queue or cancelling;
|
(artwork stages only, every order, no machine, queue or cancelling; MOVES
|
||||||
DESIGNER_STATES in app/core/auth.py, the "print" capability for the room's
|
in app/core/auth.py, the "print" capability for the room's side); Números by date range, per machine (metres finished, metres per hour
|
||||||
side); Números by date range, per machine (metres finished, metres per hour
|
|
||||||
in Imprimindo, last finished, now) and orders apart from passages. A machine's
|
in Imprimindo, last finished, now) and orders apart from passages. A machine's
|
||||||
metres are the film printed (item `metres`), never the billed ones, and time
|
metres are the film printed (item `metres`), never the billed ones, and time
|
||||||
two orders spent in Imprimindo together counts once; a stage's median is per
|
two orders spent in Imprimindo together counts once; a stage's median is per
|
||||||
@@ -397,19 +397,42 @@ settled in writing.
|
|||||||
Done on 2026-10-26: the single price per product Dropstar asked for on
|
Done on 2026-10-26: the single price per product Dropstar asked for on
|
||||||
2026-10-23 (see Commercial rules), on the Site and the server.
|
2026-10-23 (see Commercial rules), on the Site and the server.
|
||||||
|
|
||||||
|
Dropstar's flow of 2026-10-23, in the code since 2026-10-26 (app/runtime.py,
|
||||||
|
app/core/auth.py): the board is Arte recebida, Arte conferida, Imprimindo,
|
||||||
|
Correção, Revisão, Finalizado. Fila de impressão left: Arte conferida is the
|
||||||
|
queue, entered only with every item's final file approved, kept as approved
|
||||||
|
there (to change one, the order goes back to Arte recebida), with its card
|
||||||
|
order as the print order and "Baixar" for the room; orders that were in the
|
||||||
|
queue were moved to Arte conferida with a line in their history. Who moves
|
||||||
|
what (MOVES): the Designer Arte recebida to Arte conferida, asks for
|
||||||
|
corrections and brings the new art back to Arte recebida or Arte conferida;
|
||||||
|
the Operador Arte conferida to Imprimindo to Revisão; only the Revisor (and
|
||||||
|
the superadmin, for support) Revisão to Finalizado, so nobody releases their
|
||||||
|
own print; Admin and Gestão every other move, including Imprimindo or
|
||||||
|
Revisão to Correção and Correção straight to Revisão. A step back belongs to
|
||||||
|
whoever makes the move it undoes, and to Admin and Gestão. Tiny: Arte
|
||||||
|
conferida sets "Preparando envio" and Finalizado "Pronto para envio", for
|
||||||
|
delivery orders too; nothing for Imprimindo, Correção or Revisão. Prova OK
|
||||||
|
still comes before Finalizado. The customer's portal shows the same steps.
|
||||||
|
|
||||||
Still to do (2026-10-26):
|
Still to do (2026-10-26):
|
||||||
- The DTF number in Tiny's `numeroPedidoEcommerce`: sent since 2026-10-26,
|
- The DTF number in Tiny's `numeroPedidoEcommerce`: sent since 2026-10-26,
|
||||||
next to the purchase order `numeroOrdemCompra` (which the resend check
|
next to the purchase order `numeroOrdemCompra` (which the resend check
|
||||||
searches), with no channel unless `TINY_ECOMMERCE_ID` is set; Tiny's v3 API
|
searches), with no channel unless `TINY_ECOMMERCE_ID` is set; Tiny's v3 API
|
||||||
cannot list channels or take one by name. Confirm at the supervised Tiny
|
cannot list channels or take one by name. Confirm at the supervised Tiny
|
||||||
test order: the probe reads the number back and fails if Tiny dropped it.
|
test order: the probe reads the number back and fails if Tiny dropped it.
|
||||||
|
- Before TINY_STATUS_UPDATES goes on: Finalizado now sets "Pronto para
|
||||||
|
envio" on delivery orders too, so the client's n8n must not send them the
|
||||||
|
pickup message it sends on that situação.
|
||||||
|
- Dropstar creates the Revisor users right after the redeploy that brings the
|
||||||
|
new flow (the profile exists only from then): until then orders wait in
|
||||||
|
Revisão, and only the superadmin can release them.
|
||||||
- Waiting on Dropstar: the DTF SITE category's numeric id (CATEGORY in
|
- Waiting on Dropstar: the DTF SITE category's numeric id (CATEGORY in
|
||||||
app/tiny.py is still DUPLICADO DROP), their flow image (removing Fila de
|
app/tiny.py is still DUPLICADO DROP), the internal rules document (D-16 to
|
||||||
impressão, a Revisão column and a Revisor profile, the only one to move to
|
D-23), and the montador spec (and which "histórico" Marcus means for its
|
||||||
Finalizado; Tiny statuses per stage), the internal rules document (D-16 to
|
orders). Their three server folders moved on card moves need a written
|
||||||
D-23), and the montador spec. Their three server folders moved on card moves
|
decision: the Kanban in the room's browser can do it; a program on their
|
||||||
need a written decision: the Kanban in the room's browser can do it; a
|
server is the factory agent left out of this scope.
|
||||||
program on their server is the factory agent left out of this scope.
|
|
||||||
- Anchor-customer orders from the montador: after the launch; the team's idea
|
- Anchor-customer orders from the montador: after the launch; the team's idea
|
||||||
is that Graphs handles that side and sends the orders to this Kanban.
|
is that Graphs handles that side and sends the orders to this Kanban.
|
||||||
|
|
||||||
@@ -440,7 +463,7 @@ as references and are not imported or started by Compose.
|
|||||||
one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable
|
one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable
|
||||||
approved quotes expire after 24 hours. A customer confirms the server total
|
approved quotes expire after 24 hours. A customer confirms the server total
|
||||||
on the Site to create one idempotent local paid order.
|
on the Site to create one idempotent local paid order.
|
||||||
- Paid orders use `rec`, `tra`, `fil`, `imp`, `cor`, `fin`, with allowed transitions,
|
- Paid orders use `rec`, `tra`, `imp`, `cor`, `rev`, `fin` (`fil` until 2026-10-26), with allowed transitions,
|
||||||
operator authentication, concurrency checks, and durable movement history.
|
operator authentication, concurrency checks, and durable movement history.
|
||||||
Local mock integration receipts are visible in the Kanban.
|
Local mock integration receipts are visible in the Kanban.
|
||||||
- The customer portal at `/portal.html` supports local registration/login,
|
- The customer portal at `/portal.html` supports local registration/login,
|
||||||
|
|||||||
@@ -51,14 +51,14 @@ def main():
|
|||||||
approved_quote(client, quote, [item])
|
approved_quote(client, quote, [item])
|
||||||
orders.append(client.call('/orders/dev-paid', {'quote_id': quote['id']}))
|
orders.append(client.call('/orders/dev-paid', {'quote_id': quote['id']}))
|
||||||
# Spread them over the production stages, one waiting for a correction.
|
# Spread them over the production stages, one waiting for a correction.
|
||||||
stages = {0: ['tra', 'fil', 'imp', 'fin'], 1: ['tra', 'fil', 'imp', 'fin'], 2: ['tra', 'fil', 'imp'],
|
stages = {0: ['tra', 'imp', 'rev', 'fin'], 1: ['tra', 'imp', 'rev', 'fin'], 2: ['tra', 'imp', 'rev'],
|
||||||
3: ['tra', 'fil'], 4: ['tra'], 5: ['cor']}
|
3: ['tra', 'imp'], 4: ['tra'], 5: ['cor']}
|
||||||
for index, path in stages.items():
|
for index, path in stages.items():
|
||||||
order = orders[index]
|
order = orders[index]
|
||||||
version = order['version']
|
version = order['version']
|
||||||
for state in path:
|
for state in path:
|
||||||
if state == 'fil':
|
if state == 'tra':
|
||||||
# The print queue takes approved final files, as on the Kanban.
|
# Arte conferida, the print queue, takes approved final files, as on the Kanban.
|
||||||
final = upload_bytes(client, b'DEMO FINAL %d' % index, order_id=order['id'])
|
final = upload_bytes(client, b'DEMO FINAL %d' % index, order_id=order['id'])
|
||||||
version = client.call('/operator/orders/' + order['id'] + '/final-files',
|
version = client.call('/operator/orders/' + order['id'] + '/final-files',
|
||||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}],
|
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}],
|
||||||
|
|||||||
@@ -204,13 +204,14 @@ try{
|
|||||||
await kanban.click('[data-tab="board"]');
|
await kanban.click('[data-tab="board"]');
|
||||||
await kanban.click(`[data-card="${oid}"]`);
|
await kanban.click(`[data-card="${oid}"]`);
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
||||||
for(const [title,state] of [['Arte conferida','tra'],['Fila de impressão','fil'],['Imprimindo','imp'],['Finalizado','fin']]){
|
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
|
||||||
if(state==='fil'){
|
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
|
||||||
|
if(state==='tra'){
|
||||||
// Without an approved final, the next step at the top is approving it,
|
// Without an approved final, the next step at the top is approving it,
|
||||||
// not a move the server would refuse. The CDR has no ready file, so
|
// not a move the server would refuse. The CDR has no ready file, so
|
||||||
// the button opens the upload form there.
|
// the button opens the upload form there.
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button');
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button');
|
||||||
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fil"]')`),false);
|
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="tra"]')`),false);
|
||||||
await kanban.click(`[data-order="${oid}"] [data-approve]`);
|
await kanban.click(`[data-order="${oid}"] [data-approve]`);
|
||||||
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
|
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
|
||||||
const doc=await kanban.call('DOM.getDocument');
|
const doc=await kanban.call('DOM.getDocument');
|
||||||
@@ -218,7 +219,7 @@ try{
|
|||||||
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
|
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
|
||||||
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
||||||
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===2`),'final file approval');
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
|
||||||
// Approved before the queue: already on this computer, in Recebidos.
|
// Approved before the queue: already on this computer, in Recebidos.
|
||||||
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||||
await kanban.eval('syncFolder(true)');
|
await kanban.eval('syncFolder(true)');
|
||||||
@@ -228,7 +229,7 @@ try{
|
|||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
||||||
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
||||||
if(state==='fil'){
|
if(state==='tra'){
|
||||||
// Entering the queue saves its final file there, whole and named after the order.
|
// Entering the queue saves its final file there, whole and named after the order.
|
||||||
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||||
await waitFor(async()=>(await savedFiles()).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file saved in the folder',45000);
|
await waitFor(async()=>(await savedFiles()).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file saved in the folder',45000);
|
||||||
@@ -247,11 +248,11 @@ try{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Undo a mistaken move from the panel: one stage back with an internal reason.
|
// Undo a mistaken move from the panel: one stage back with an internal reason.
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="imp"]')`),'back button');
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="rev"]')`),'back button');
|
||||||
await kanban.click(`[data-order="${oid}"] [data-back="imp"]`);
|
await kanban.click(`[data-order="${oid}"] [data-back="rev"]`);
|
||||||
await kanban.fill(`[data-order="${oid}"] form.reason input`,'Movido por engano (teste)');
|
await kanban.fill(`[data-order="${oid}"] form.reason input`,'Movido por engano (teste)');
|
||||||
await kanban.eval(`document.querySelector('[data-order="${oid}"] form.reason input').closest('form').requestSubmit()`);
|
await kanban.eval(`document.querySelector('[data-order="${oid}"] form.reason input').closest('form').requestSubmit()`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='imp'`),'undo to Imprimindo');
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='rev'`),'undo to Revisão');
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fin"]')`),'move to Finalizado again');
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fin"]')`),'move to Finalizado again');
|
||||||
await kanban.click(`[data-order="${oid}"] [data-move="fin"]`);
|
await kanban.click(`[data-order="${oid}"] [data-move="fin"]`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again');
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again');
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ def run():
|
|||||||
assert isinstance(after['machines'], list)
|
assert isinstance(after['machines'], list)
|
||||||
# An order sent back counts once per stage; its passages are counted apart.
|
# An order sent back counts once per stage; its passages are counted apart.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'fil'))):
|
for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp'))):
|
||||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
VALUES(%s,%s,%s,'kanban-test','',false,now()+%s*interval '1 second')''', (order_id, frm, to, step + 1))
|
VALUES(%s,%s,%s,'kanban-test','',false,now()+%s*interval '1 second')''', (order_id, frm, to, step + 1))
|
||||||
moved = client.call('/operator/stats?days=7', operator=True)
|
moved = client.call('/operator/stats?days=7', operator=True)
|
||||||
@@ -151,7 +151,7 @@ def run():
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute('UPDATE dtf_local.orders SET created_at=%s::timestamptz WHERE id=%s', (f'{alone} 08:00-03', order_id))
|
c.execute('UPDATE dtf_local.orders SET created_at=%s::timestamptz WHERE id=%s', (f'{alone} 08:00-03', order_id))
|
||||||
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
|
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
|
||||||
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'fil')), start=9):
|
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp')), start=9):
|
||||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
VALUES(%s,%s,%s,'kanban-test','',false,%s::timestamptz)''', (order_id, frm, to, f'{alone} {hour}:00-03'))
|
VALUES(%s,%s,%s,'kanban-test','',false,%s::timestamptz)''', (order_id, frm, to, f'{alone} {hour}:00-03'))
|
||||||
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
|
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
|
||||||
|
|||||||
@@ -152,6 +152,11 @@ def run():
|
|||||||
assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order
|
assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order
|
||||||
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
|
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
|
||||||
version = order['version']
|
version = order['version']
|
||||||
|
# Arte conferida, the print queue, takes the order once its final is approved.
|
||||||
|
final = upload_bytes(tester, b'TEST ORDER FINAL', order_id=order['id'])
|
||||||
|
version = tester.call('/operator/orders/' + order['id'] + '/final-files',
|
||||||
|
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}], 'note': 'Teste'},
|
||||||
|
operator=True)['version']
|
||||||
for state in ('tra',):
|
for state in ('tra',):
|
||||||
moved = tester.call('/operator/orders/' + order['id'] + '/move', {'state': state, 'version': version}, operator=True)
|
moved = tester.call('/operator/orders/' + order['id'] + '/move', {'state': state, 'version': version}, operator=True)
|
||||||
version = moved['version']
|
version = moved['version']
|
||||||
|
|||||||
@@ -110,9 +110,9 @@ def run():
|
|||||||
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
||||||
'note': 'Generated print file checked'}, operator=True)
|
'note': 'Generated print file checked'}, operator=True)
|
||||||
version = result['version']
|
version = result['version']
|
||||||
for state in ('tra', 'fil'):
|
# Arte conferida is the print queue (2026-10-23).
|
||||||
client.call('/operator/orders/' + oid + '/move', {'state': state, 'version': version}, operator=True)
|
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
|
||||||
version += 1
|
version += 1
|
||||||
# Once queued for printing, the final set can no longer change.
|
# Once queued for printing, the final set can no longer change.
|
||||||
client.call('/operator/orders/' + oid + '/final-files',
|
client.call('/operator/orders/' + oid + '/final-files',
|
||||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
||||||
|
|||||||
@@ -232,9 +232,11 @@ def run():
|
|||||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
|
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=422)
|
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=422)
|
||||||
version=0
|
version=0
|
||||||
for state in ('cor','rec','tra','fil','imp','fin'):
|
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
|
||||||
if state=='fil':
|
for state in ('cor','rec','tra','imp','rev','fin'):
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
if state=='tra':
|
||||||
|
# The queue takes approved final files only.
|
||||||
|
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||||
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
|
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
|
||||||
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
||||||
version=result['version']
|
version=result['version']
|
||||||
@@ -249,10 +251,10 @@ def run():
|
|||||||
# A mistaken move can be undone one stage at a time, with an internal
|
# A mistaken move can be undone one stage at a time, with an internal
|
||||||
# reason. The customer is not told again: going back and forward once more
|
# reason. The customer is not told again: going back and forward once more
|
||||||
# adds no messages (the outbox count below stays 4).
|
# adds no messages (the outbox count below stays 4).
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=422)
|
client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version},operator=True,expected=422)
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
|
||||||
back=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version,'reason':'Movido por engano'},operator=True)
|
back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True)
|
||||||
assert back['state']=='imp';version+=1
|
assert back['state']=='rev';version+=1
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1
|
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1
|
||||||
history=client.call('/operator/orders/'+oid+'/history',operator=True)
|
history=client.call('/operator/orders/'+oid+'/history',operator=True)
|
||||||
assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back']
|
assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back']
|
||||||
|
|||||||
50
tests/test_moves.py
Normal file
50
tests/test_moves.py
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from app.core.auth import ROLES, may_move, may_reorder
|
||||||
|
from app.runtime import BACK, STATES, TRANSITIONS
|
||||||
|
|
||||||
|
|
||||||
|
def moves(role):
|
||||||
|
return {(a, b) for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)}
|
||||||
|
|
||||||
|
|
||||||
|
class MovesTest(unittest.TestCase):
|
||||||
|
def test_the_board(self):
|
||||||
|
# Fila de impressão left: Arte conferida is the queue; Revisão before Finalizado.
|
||||||
|
self.assertEqual(list(STATES), ['rec', 'tra', 'imp', 'cor', 'rev', 'fin'])
|
||||||
|
self.assertEqual(BACK, {'tra': 'rec', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'})
|
||||||
|
self.assertIn('revisor', ROLES)
|
||||||
|
|
||||||
|
def test_each_profile_moves_its_part(self):
|
||||||
|
self.assertEqual(moves('designer'), {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')})
|
||||||
|
self.assertEqual(moves('operador'), {('tra', 'imp'), ('imp', 'rev')})
|
||||||
|
self.assertEqual(moves('revisor'), {('rev', 'fin')})
|
||||||
|
self.assertEqual(moves('vendedor'), set())
|
||||||
|
# Gestão sends to Correção and brings back, straight to Revisão too.
|
||||||
|
for pair in (('imp', 'cor'), ('cor', 'rev'), ('rev', 'cor'), ('tra', 'imp'), ('rec', 'tra')):
|
||||||
|
self.assertTrue(may_move('gestao', *pair), pair)
|
||||||
|
|
||||||
|
def test_only_the_revisor_releases_to_finalizado(self):
|
||||||
|
for role in ROLES:
|
||||||
|
self.assertEqual(may_move(role, 'rev', 'fin'), role in ('revisor', 'superadmin'), role)
|
||||||
|
|
||||||
|
def test_a_step_back_belongs_to_whoever_makes_the_move_it_undoes(self):
|
||||||
|
self.assertTrue(may_move('operador', 'rev', 'imp', back=True))
|
||||||
|
self.assertTrue(may_move('operador', 'imp', 'tra', back=True))
|
||||||
|
self.assertFalse(may_move('operador', 'tra', 'rec', back=True))
|
||||||
|
self.assertTrue(may_move('designer', 'tra', 'rec', back=True))
|
||||||
|
self.assertTrue(may_move('revisor', 'fin', 'rev', back=True))
|
||||||
|
self.assertTrue(may_move('gestao', 'fin', 'rev', back=True))
|
||||||
|
self.assertFalse(may_move('vendedor', 'tra', 'rec', back=True))
|
||||||
|
|
||||||
|
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
|
||||||
|
self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp'])
|
||||||
|
self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor'])
|
||||||
|
self.assertEqual([s for s in STATES if may_reorder('revisor', s)], ['rev'])
|
||||||
|
self.assertEqual([s for s in STATES if may_reorder('vendedor', s)], [])
|
||||||
|
self.assertTrue(all(may_reorder('gestao', s) for s in STATES))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -302,15 +302,15 @@ class TinyStatusTests(FakeTinyCase):
|
|||||||
self.assertEqual(self.puts(), [])
|
self.assertEqual(self.puts(), [])
|
||||||
|
|
||||||
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
|
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
|
||||||
def test_ready_delivery_order_waits_for_freight(self):
|
def test_a_finished_delivery_order_is_ready_too(self):
|
||||||
self.tiny.deliver('k1', PAID)
|
# Dropstar's flow, 2026-10-23: Finalizado is "Pronto para envio" for every order.
|
||||||
self.calls.clear()
|
sale = self.tiny.deliver('k1', PAID)
|
||||||
ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order']})
|
ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order'], 'tiny_id': sale['tiny_id']})
|
||||||
self.assertEqual(ready['status'], 'not-applicable')
|
self.assertEqual((ready['status'], ready['situacao']), ('status-updated', 'Pronto para envio'))
|
||||||
self.assertEqual(self.calls, [])
|
self.assertEqual(self.orders[0]['situacao'], 7)
|
||||||
|
|
||||||
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
|
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
|
||||||
def test_printing_is_preparando_envio_but_never_moves_an_invoiced_order_back(self):
|
def test_the_queue_is_preparando_envio_but_never_moves_an_invoiced_order_back(self):
|
||||||
sale = self.tiny.deliver('k1', PAID)
|
sale = self.tiny.deliver('k1', PAID)
|
||||||
started = {**READY, 'event': 'production_started', 'order': PAID['order'], 'tiny_id': sale['tiny_id']}
|
started = {**READY, 'event': 'production_started', 'order': PAID['order'], 'tiny_id': sale['tiny_id']}
|
||||||
moved = self.tiny.deliver('k2', started)
|
moved = self.tiny.deliver('k2', started)
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ def run():
|
|||||||
su = Client()
|
su = Client()
|
||||||
su.call('/session')
|
su.call('/session')
|
||||||
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
||||||
emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer')}
|
emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer', 'revisor')}
|
||||||
owner = uuid4()
|
owner = uuid4()
|
||||||
machines, made = [], []
|
machines, made = [], []
|
||||||
try:
|
try:
|
||||||
@@ -123,11 +123,20 @@ def run():
|
|||||||
# On the UV machine of this test, whatever the others carry.
|
# On the UV machine of this test, whatever the others carry.
|
||||||
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
|
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
|
||||||
|
|
||||||
# The operator of the UV machine sees only its orders, moves them, and nothing more.
|
# The operator of the UV machine sees only its orders and prints them:
|
||||||
|
# Arte conferida to Imprimindo to Revisão, nothing else (Dropstar, 2026-10-23).
|
||||||
op = signed_in(emails['operador'])
|
op = signed_in(emails['operador'])
|
||||||
seen = {o['id'] for o in op.call('/operator/board')['orders']}
|
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
|
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': ''})
|
assert sorted(op.call('/operator/me')['moves']) == [['imp', 'rev'], ['imp', 'tra'], ['rev', 'imp'], ['tra', 'imp']]
|
||||||
|
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,))
|
||||||
|
op.call(f'/operator/orders/{uv_o}/move', {'state': 'cor', 'version': 0, 'reason': 'borrou'}, expected=403)
|
||||||
|
printed = op.call(f'/operator/orders/{uv_o}/move', {'state': 'rev', 'version': 0, 'reason': ''})
|
||||||
|
refused = op.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''},
|
||||||
|
expected=403)
|
||||||
|
assert refused['detail'] == 'Só o Revisor manda o pedido para Finalizado.', refused
|
||||||
op.call(f'/operator/orders/{uv_o}/cancel', {'note': 'não pode'}, expected=403)
|
op.call(f'/operator/orders/{uv_o}/cancel', {'note': 'não pode'}, expected=403)
|
||||||
op.call('/operator/users', expected=403)
|
op.call('/operator/users', expected=403)
|
||||||
op.call('/operator/payment-events', expected=403)
|
op.call('/operator/payment-events', expected=403)
|
||||||
@@ -144,6 +153,18 @@ def run():
|
|||||||
seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
|
seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
|
||||||
seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403)
|
seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403)
|
||||||
assert seller.call('/operator/me')['can'] == ['view']
|
assert seller.call('/operator/me')['can'] == ['view']
|
||||||
|
# Only the Revisor releases to Finalizado: not even the administrator.
|
||||||
|
admin.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''},
|
||||||
|
expected=403)
|
||||||
|
admin.call('/operator/users', {'name': 'Confere', 'email': emails['revisor'], 'role': 'revisor',
|
||||||
|
'password': PASSWORD})
|
||||||
|
reviewer = signed_in(emails['revisor'])
|
||||||
|
me = reviewer.call('/operator/me')
|
||||||
|
assert me['can'] == ['view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
|
||||||
|
reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
|
||||||
|
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
|
||||||
|
'reason': ''})['state'] == 'fin'
|
||||||
|
|
||||||
# The designer: every order, whatever its machine; the artwork stages only.
|
# The designer: every order, whatever its machine; the artwork stages only.
|
||||||
admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer',
|
admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer',
|
||||||
'password': PASSWORD, 'machines': [uv]})
|
'password': PASSWORD, 'machines': [uv]})
|
||||||
@@ -152,8 +173,17 @@ def run():
|
|||||||
assert set(designer.call('/operator/me')['can']) == {'view', 'produce'}
|
assert set(designer.call('/operator/me')['can']) == {'view', 'produce'}
|
||||||
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']}
|
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']}
|
||||||
version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version']
|
version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version']
|
||||||
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': version, 'reason': ''})
|
# A correction and back; Arte conferida only with the final approved.
|
||||||
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'fil', 'version': moved['version'], 'reason': ''},
|
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'cor', 'version': version,
|
||||||
|
'reason': 'fundo branco'})
|
||||||
|
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
|
||||||
|
'reason': ''})
|
||||||
|
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': moved['version'], 'reason': ''},
|
||||||
|
expected=409)
|
||||||
|
# In the queue the card is the print room's; the designer only takes it back.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (textil_o,))
|
||||||
|
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'imp', 'version': moved['version'], 'reason': ''},
|
||||||
expected=403)
|
expected=403)
|
||||||
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
|
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
|
||||||
'reason': 'arte trocada'})
|
'reason': 'arte trocada'})
|
||||||
@@ -167,7 +197,7 @@ def run():
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
long_q, long_o = order_fixture(c, owner, 'file', metres='12')
|
long_q, long_o = order_fixture(c, owner, 'file', metres='12')
|
||||||
made.append((long_q, long_o))
|
made.append((long_q, long_o))
|
||||||
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (long_o,))
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (long_o,))
|
||||||
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(long_o))['version']
|
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(long_o))['version']
|
||||||
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''},
|
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''},
|
||||||
operator=True, expected=409)
|
operator=True, expected=409)
|
||||||
@@ -181,7 +211,7 @@ def run():
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
short_q, short_o = order_fixture(c, owner, 'file', metres='10')
|
short_q, short_o = order_fixture(c, owner, 'file', metres='10')
|
||||||
made.append((short_q, short_o))
|
made.append((short_q, short_o))
|
||||||
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (short_o,))
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (short_o,))
|
||||||
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(short_o))['version']
|
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(short_o))['version']
|
||||||
su.call(f'/operator/orders/{short_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
|
su.call(f'/operator/orders/{short_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
|
||||||
# Asked for at checkout: the paid order arrives waiting for the customer's word.
|
# Asked for at checkout: the paid order arrives waiting for the customer's word.
|
||||||
|
|||||||
@@ -49,8 +49,9 @@ def run():
|
|||||||
|
|
||||||
def move(state,version):
|
def move(state,version):
|
||||||
return customer.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''},operator=True)['version']
|
return customer.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''},operator=True)['version']
|
||||||
version=move('tra',0)
|
# Arte conferida is the print queue (2026-10-23): it takes approved finals only.
|
||||||
customer.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
version=0
|
||||||
|
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||||
final_id=upload_bytes(customer,b'LOCAL FINAL VERSION ONE',order_id=oid)
|
final_id=upload_bytes(customer,b'LOCAL FINAL VERSION ONE',order_id=oid)
|
||||||
customer.call('/uploads/'+final_id,expected=404)
|
customer.call('/uploads/'+final_id,expected=404)
|
||||||
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
|
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
|
||||||
@@ -61,7 +62,7 @@ def run():
|
|||||||
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
|
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
|
||||||
assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE'
|
assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE'
|
||||||
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||||
version=move('fil',version)
|
version=move('tra',version)
|
||||||
# The print queue's files come named after their order, straight from storage.
|
# The print queue's files come named after their order, straight from storage.
|
||||||
queued=customer.call('/operator/queue/finals',operator=True)['files']
|
queued=customer.call('/operator/queue/finals',operator=True)['files']
|
||||||
mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE']
|
mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE']
|
||||||
@@ -81,8 +82,7 @@ def run():
|
|||||||
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
||||||
assert any(f['kind']=='correction' and f['active'] and f['upload_id']==correction_id for f in files)
|
assert any(f['kind']=='correction' and f['active'] and f['upload_id']==correction_id for f in files)
|
||||||
assert not any(f['kind']=='final' and f['active'] for f in files), 'new correction kept a stale final active'
|
assert not any(f['kind']=='final' and f['active'] for f in files), 'new correction kept a stale final active'
|
||||||
version=move('tra',version)
|
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||||
customer.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
|
||||||
# The correction itself can be approved as the final of the item it corrects.
|
# The correction itself can be approved as the final of the item it corrects.
|
||||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Correction is print-ready'},operator=True)['version']
|
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Correction is print-ready'},operator=True)['version']
|
||||||
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
||||||
@@ -90,7 +90,9 @@ def run():
|
|||||||
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
|
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
|
||||||
new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid)
|
new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid)
|
||||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
|
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
|
||||||
for state in ('fil','imp','fin'):version=move(state,version)
|
for state in ('tra','imp','rev','fin'):version=move(state,version)
|
||||||
|
# In the queue the finals stay as approved.
|
||||||
|
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Too late'},operator=True,expected=409)
|
||||||
detail=other.call('/customer/orders/'+oid)
|
detail=other.call('/customer/orders/'+oid)
|
||||||
assert detail['state']=='fin'
|
assert detail['state']=='fin'
|
||||||
assert sum(f['active'] and f['kind']=='final' for f in detail['files'])==1
|
assert sum(f['active'] and f['kind']=='final' for f in detail['files'])==1
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
--line:#262A2F;--line2:#2A2F35;--line3:#3A4047;
|
--line:#262A2F;--line2:#2A2F35;--line3:#3A4047;
|
||||||
--tx:#ECE9E4;--tx2:#D5D2CC;--muted:#A3A9B0;--faint:#8B929A;
|
--tx:#ECE9E4;--tx2:#D5D2CC;--muted:#A3A9B0;--faint:#8B929A;
|
||||||
--accent:#FF8B2B;--accent-tx:#FFB575;--ok:#6FD19C;--warn:#F2B33D;--bad:#F4968B;--bad-line:#5A3530;
|
--accent:#FF8B2B;--accent-tx:#FFB575;--ok:#6FD19C;--warn:#F2B33D;--bad:#F4968B;--bad-line:#5A3530;
|
||||||
--rec:#2BB6D9;--tra:#E0508F;--fil:#E9C23A;--imp:#D9D6D0;--cor:#F06A5B;--fin:#3FB97A;
|
--rec:#2BB6D9;--tra:#E0508F;--fil:#E9C23A;--imp:#D9D6D0;--cor:#F06A5B;--rev:#8E6BDE;--fin:#3FB97A;
|
||||||
--mono:Manrope,system-ui,sans-serif;
|
--mono:Manrope,system-ui,sans-serif;
|
||||||
}
|
}
|
||||||
*{box-sizing:border-box}
|
*{box-sizing:border-box}
|
||||||
@@ -513,6 +513,6 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
|
|||||||
.mload{display:flex;justify-content:space-between;gap:8px;font-size:13.5px;color:var(--tx2)}
|
.mload{display:flex;justify-content:space-between;gap:8px;font-size:13.5px;color:var(--tx2)}
|
||||||
.mload.over{color:var(--bad);font-weight:600}
|
.mload.over{color:var(--bad);font-weight:600}
|
||||||
.mtile-actions{display:flex;justify-content:flex-end;gap:6px;margin-top:4px}
|
.mtile-actions{display:flex;justify-content:flex-end;gap:6px;margin-top:4px}
|
||||||
/* Fila de impressão's tools: Baixar. */
|
/* The queue's tools (Arte conferida): Baixar. */
|
||||||
.coltools{display:flex;gap:6px;flex-shrink:0}
|
.coltools{display:flex;gap:6px;flex-shrink:0}
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
<button type="button" data-tab="quotes" aria-selected="false">Cotações <span class="badge" id="badge-quotes"></span></button>
|
<button type="button" data-tab="quotes" aria-selected="false">Cotações <span class="badge" id="badge-quotes"></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="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 <span class="badge warn" id="badge-integrations" title="A pasta da Fila de impressão precisa de atenção"></span></button>
|
<button type="button" data-tab="integrations" aria-selected="false">Integrações <span class="badge warn" id="badge-integrations" title="A pasta da fila precisa de atenção"></span></button>
|
||||||
<button type="button" data-tab="users" aria-selected="false" hidden>Usuários</button>
|
<button type="button" data-tab="users" aria-selected="false" hidden>Usuários</button>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="searchbox">
|
<div class="searchbox">
|
||||||
@@ -102,8 +102,9 @@
|
|||||||
<section id="tab-users" class="page" hidden>
|
<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>
|
<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.
|
<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. Designer: aprova arquivos e pede correção, em Arte recebida, Arte conferida e Correção.
|
Gestão: tudo, menos usuários; manda o pedido para Correção e traz de volta. Designer: vê todos os pedidos, aprova e recusa o arquivo final, pede correção.
|
||||||
Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
|
Operador: ligado a uma máquina, vê só os pedidos dela; imprime e passa para a Revisão. Revisor: confere a folha impressa e libera; é o único que manda para Finalizado.
|
||||||
|
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>
|
<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>
|
<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 máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
|
<p class="faint stats-note">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
|
||||||
|
|||||||
106
web/kanban.js
106
web/kanban.js
@@ -5,8 +5,12 @@ const $ = id=>document.getElementById(id);
|
|||||||
// Remove credentials saved by older local builds. Only HttpOnly sessions now.
|
// Remove credentials saved by older local builds. Only HttpOnly sessions now.
|
||||||
sessionStorage.removeItem('dtf-operator');
|
sessionStorage.removeItem('dtf-operator');
|
||||||
|
|
||||||
const STAGE_COLORS={rec:'var(--rec)',tra:'var(--tra)',fil:'var(--fil)',imp:'var(--imp)',cor:'var(--cor)',fin:'var(--fin)'};
|
// Dropstar's flow (2026-10-23): Arte conferida is the print queue and Revisão
|
||||||
const FLOW=['rec','tra','fil','imp','fin'];
|
// checks the printed sheet. 'fil' (Fila de impressão) is only in older history.
|
||||||
|
const STAGE_COLORS={rec:'var(--rec)',tra:'var(--tra)',fil:'var(--fil)',imp:'var(--imp)',cor:'var(--cor)',rev:'var(--rev)',fin:'var(--fin)'};
|
||||||
|
const FLOW=['rec','tra','imp','rev','fin'];
|
||||||
|
const FORMER_STATES={fil:'Fila de impressão'};
|
||||||
|
const stateName=s=>board.states[s]||FORMER_STATES[s]||s;
|
||||||
const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
||||||
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'};
|
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'};
|
||||||
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'};
|
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'};
|
||||||
@@ -39,10 +43,11 @@ let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=nul
|
|||||||
// The signed-in operator and what their profile allows (app/core/auth.py).
|
// The signed-in operator and what their profile allows (app/core/auth.py).
|
||||||
let ME=null;
|
let ME=null;
|
||||||
const may=cap=>!!ME?.can?.includes(cap);
|
const may=cap=>!!ME?.can?.includes(cap);
|
||||||
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',vendedor:'Vendedor'};
|
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor'};
|
||||||
// The designer moves cards only among the artwork stages; the queue onwards is the print room's (app/core/auth.py).
|
// Which moves this profile makes, and which columns' order it sets: the
|
||||||
const DESIGNER_STATES=['rec','tra','cor'];
|
// server's own list (app/core/auth.py MOVES), never worked out here.
|
||||||
const mayMove=(from,to)=>may('produce')&&(ME?.role!=='designer'||DESIGNER_STATES.includes(from)&&DESIGNER_STATES.includes(to));
|
const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to);
|
||||||
|
const mayReorder=state=>!!ME?.reorder?.includes(state);
|
||||||
// Which tabs each capability opens.
|
// Which tabs each capability opens.
|
||||||
const TAB_NEEDS={quotes:o=>may('manage')||ME?.role==='vendedor',payments:()=>may('manage'),
|
const TAB_NEEDS={quotes:o=>may('manage')||ME?.role==='vendedor',payments:()=>may('manage'),
|
||||||
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage')||may('print'),users:()=>may('users')};
|
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage')||may('print'),users:()=>may('users')};
|
||||||
@@ -202,8 +207,8 @@ function download(uid){return async()=>{
|
|||||||
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
||||||
};}
|
};}
|
||||||
// ---- Automatic folder ------------------------------------------------------
|
// ---- Automatic folder ------------------------------------------------------
|
||||||
// The print queue's files, saved by this browser as orders enter Fila de
|
// The print queue's files, saved by this browser as orders enter Arte
|
||||||
// impressão, while the Kanban is open. It is switched on in Integrações, on
|
// conferida (the queue since 2026-10-23), while the Kanban is open. It is switched on in Integrações, on
|
||||||
// the print room's computer: the folder belongs to that browser, not to the
|
// the print room's computer: the folder belongs to that browser, not to the
|
||||||
// account. Chrome and Edge write into a folder the operator chose
|
// account. Chrome and Edge write into a folder the operator chose
|
||||||
// (FlexiPRINT's, or the internal server's share), remembered, with one click
|
// (FlexiPRINT's, or the internal server's share), remembered, with one click
|
||||||
@@ -219,8 +224,9 @@ const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>
|
|||||||
const BRAVE_FLAG='brave://flags/#file-system-access-api';
|
const BRAVE_FLAG='brave://flags/#file-system-access-api';
|
||||||
// `when`: download as soon as the order arrives in Arte recebida ('rec', the
|
// `when`: download as soon as the order arrives in Arte recebida ('rec', the
|
||||||
// default), into a "Recebidos" folder inside the chosen one; the file moves up
|
// default), into a "Recebidos" folder inside the chosen one; the file moves up
|
||||||
// when the order enters the queue; or only at the queue ('fil'). Only a chosen folder can do that: Firefox
|
// when the order enters the queue; or only at the queue ('tra'; computers set
|
||||||
// downloads cannot be moved or removed afterwards.
|
// before 2026-10-23 kept 'fil', read the same). Only a chosen folder can do
|
||||||
|
// that: Firefox downloads cannot be moved or removed afterwards.
|
||||||
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
|
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
|
||||||
brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'rec',
|
brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'rec',
|
||||||
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
|
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
|
||||||
@@ -242,7 +248,7 @@ async function restoreFolder(){
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(FOLDER.mode!=='folder')return;
|
if(FOLDER.mode!=='folder')return;
|
||||||
try{FOLDER.when=await kv.get('folder-when')==='fil'?'fil':'rec';
|
try{FOLDER.when=['tra','fil'].includes(await kv.get('folder-when'))?'tra':'rec';
|
||||||
FOLDER.handle=await kv.get('folder')||null;
|
FOLDER.handle=await kv.get('folder')||null;
|
||||||
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
|
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
|
||||||
FOLDER.saved=await loadSaved();
|
FOLDER.saved=await loadSaved();
|
||||||
@@ -253,7 +259,7 @@ async function restoreFolder(){
|
|||||||
// row says what is happening; the how-to and the secondary buttons are under
|
// row says what is happening; the how-to and the secondary buttons are under
|
||||||
// "Detalhes".
|
// "Detalhes".
|
||||||
function folderCard(){
|
function folderCard(){
|
||||||
const name='Pasta da Fila de impressão', h=FOLDER.handle;
|
const name='Pasta da fila (Arte conferida)', h=FOLDER.handle;
|
||||||
const act=(text,fn)=>button(text,fn,'btn small');
|
const act=(text,fn)=>button(text,fn,'btn small');
|
||||||
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
|
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
|
||||||
const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;};
|
const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;};
|
||||||
@@ -286,7 +292,7 @@ function folderCard(){
|
|||||||
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||||
}else{
|
}else{
|
||||||
const when=node('select',undefined,'machine-select');when.setAttribute('aria-label','Quando baixar');
|
const when=node('select',undefined,'machine-select');when.setAttribute('aria-label','Quando baixar');
|
||||||
for(const [value,text] of [['rec','Baixar em Arte recebida'],['fil','Baixar na Fila de impressão']]){
|
for(const [value,text] of [['rec','Baixar em Arte recebida'],['tra','Baixar em Arte conferida']]){
|
||||||
const o=node('option',text);o.value=value;o.selected=FOLDER.when===value;when.append(o);}
|
const o=node('option',text);o.value=value;o.selected=FOLDER.when===value;when.append(o);}
|
||||||
when.onchange=()=>setWhen(when.value);
|
when.onchange=()=>setWhen(when.value);
|
||||||
row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
||||||
@@ -294,8 +300,8 @@ function folderCard(){
|
|||||||
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
||||||
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
|
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
|
||||||
node('p',FOLDER.when==='rec'
|
node('p',FOLDER.when==='rec'
|
||||||
?'Em Arte recebida: o arquivo do pedido é baixado em “'+h.name+'/'+RECEIVED+'” assim que o pedido chega, e passa para “'+h.name+'” quando entra na Fila de impressão.'
|
?'Em Arte recebida: o arquivo do pedido é baixado em “'+h.name+'/'+RECEIVED+'” assim que o pedido chega, e passa para “'+h.name+'” quando entra em Arte conferida, a fila.'
|
||||||
:'Na Fila de impressão: o arquivo é baixado em “'+h.name+'” quando o pedido entra na Fila de impressão.'),
|
:'Em Arte conferida: o arquivo é baixado em “'+h.name+'” quando o pedido entra em Arte conferida, a fila.'),
|
||||||
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai. '+
|
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai. '+
|
||||||
'Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')],
|
'Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')],
|
||||||
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||||
@@ -340,7 +346,7 @@ async function setDownloads(on){
|
|||||||
async function setWhen(when){
|
async function setWhen(when){
|
||||||
FOLDER.when=when;FOLDER.lastSig=null;
|
FOLDER.when=when;FOLDER.lastSig=null;
|
||||||
await kv.set('folder-when',when).catch(()=>{});
|
await kv.set('folder-when',when).catch(()=>{});
|
||||||
paintFolder();say(when==='rec'?'Os arquivos vão ser baixados assim que o pedido chegar, em “'+RECEIVED+'”.':'Os arquivos vão ser baixados quando o pedido entrar na Fila.');
|
paintFolder();say(when==='rec'?'Os arquivos vão ser baixados assim que o pedido chegar, em “'+RECEIVED+'”.':'Os arquivos vão ser baixados quando o pedido entrar em Arte conferida.');
|
||||||
syncFolder(true);
|
syncFolder(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,7 +390,7 @@ async function moveToQueue(rec){
|
|||||||
// own timer always asks, since another computer may have moved the order.
|
// own timer always asks, since another computer may have moved the order.
|
||||||
async function syncFolder(force=false){
|
async function syncFolder(force=false){
|
||||||
if(!folderActive()||FOLDER.busy||!board||!may('print'))return;
|
if(!folderActive()||FOLDER.busy||!board||!may('print'))return;
|
||||||
const follows=early()?['rec','tra','cor','fil']:['fil'];
|
const follows=early()?['rec','tra','cor']:['tra'];
|
||||||
const sig=FOLDER.when+'|'+board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at)
|
const sig=FOLDER.when+'|'+board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at)
|
||||||
.map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(',');
|
.map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(',');
|
||||||
if(!force&&sig===FOLDER.lastSig)return;
|
if(!force&&sig===FOLDER.lastSig)return;
|
||||||
@@ -399,13 +405,13 @@ async function syncFolder(force=false){
|
|||||||
if(tidy)for(const [uid,rec] of [...FOLDER.saved]){
|
if(tidy)for(const [uid,rec] of [...FOLDER.saved]){
|
||||||
if(!rec.order||rec.place==='done')continue;
|
if(!rec.order||rec.place==='done')continue;
|
||||||
const state=states[rec.order];
|
const state=states[rec.order];
|
||||||
if(state==='imp'||state==='fin'){rec.place='done';continue;}
|
if(state==='imp'||state==='rev'||state==='fin'){rec.place='done';continue;}
|
||||||
const now=wanted.get(rec.order+':'+rec.item);
|
const now=wanted.get(rec.order+':'+rec.item);
|
||||||
const expected=state==='fil'||early()&&(state==='rec'||state==='tra');
|
const expected=state==='tra'||early()&&state==='rec';
|
||||||
if(state&&state!=='cancelled'&&state!=='cor'&&!(expected&&(!now||now.upload_id!==uid)))continue;
|
if(state&&state!=='cancelled'&&state!=='cor'&&!(expected&&(!now||now.upload_id!==uid)))continue;
|
||||||
await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();
|
await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();
|
||||||
}
|
}
|
||||||
const pending=files.filter(f=>{const r=FOLDER.saved.get(f.upload_id);return !r||r.place==='early'&&f.state==='fil';});
|
const pending=files.filter(f=>{const r=FOLDER.saved.get(f.upload_id);return !r||r.place==='early'&&f.state==='tra';});
|
||||||
for(const [i,file] of pending.entries()){
|
for(const [i,file] of pending.entries()){
|
||||||
const rec=FOLDER.saved.get(file.upload_id);
|
const rec=FOLDER.saved.get(file.upload_id);
|
||||||
const up=!!rec&&await moveToQueue(rec);
|
const up=!!rec&&await moveToQueue(rec);
|
||||||
@@ -419,11 +425,11 @@ async function syncFolder(force=false){
|
|||||||
}else{
|
}else{
|
||||||
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
|
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
|
||||||
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
|
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
|
||||||
await writeWhole(file.state==='fil'?FOLDER.handle:await received(),file.name,r.body);
|
await writeWhole(file.state==='tra'?FOLDER.handle:await received(),file.name,r.body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name,
|
FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name,
|
||||||
place:file.state==='fil'||FOLDER.mode!=='folder'?'queue':'early'});
|
place:file.state==='tra'||FOLDER.mode!=='folder'?'queue':'early'});
|
||||||
FOLDER.last=new Date();await keepSaved();
|
FOLDER.last=new Date();await keepSaved();
|
||||||
}
|
}
|
||||||
FOLDER.lastSig=sig;FOLDER.error='';
|
FOLDER.lastSig=sig;FOLDER.error='';
|
||||||
@@ -544,7 +550,7 @@ function render(){
|
|||||||
// ---- Production board ----------------------------------------------------
|
// ---- Production board ----------------------------------------------------
|
||||||
|
|
||||||
function printState(order){
|
function printState(order){
|
||||||
if(order.state==='fil'||order.state==='imp')return {text:'Final aprovado',tone:'ok'};
|
if(order.state==='imp'||order.state==='rev')return {text:'Final aprovado',tone:'ok'};
|
||||||
if(order.state==='fin')return {text:'Concluído',tone:'ok'};
|
if(order.state==='fin')return {text:'Concluído',tone:'ok'};
|
||||||
if(order.state==='cor')return {text:'Aguardando o cliente',tone:''};
|
if(order.state==='cor')return {text:'Aguardando o cliente',tone:''};
|
||||||
if(finalDone(order))return {text:'Final aprovado',tone:'ok'};
|
if(finalDone(order))return {text:'Final aprovado',tone:'ok'};
|
||||||
@@ -557,7 +563,7 @@ function printState(order){
|
|||||||
return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'};
|
return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'};
|
||||||
return {text:'Sem arquivo gerado',tone:'warn'};
|
return {text:'Sem arquivo gerado',tone:'warn'};
|
||||||
}
|
}
|
||||||
const stalled=order=>['rec','tra','fil','imp'].includes(order.state)&&Date.now()-new Date(order.updated_at)>LATE_HOURS*3600000;
|
const stalled=order=>['rec','tra','imp','rev'].includes(order.state)&&Date.now()-new Date(order.updated_at)>LATE_HOURS*3600000;
|
||||||
// "Aguardando contato": a word with the customer is needed before printing.
|
// "Aguardando contato": a word with the customer is needed before printing.
|
||||||
// A mark on the card, not a stage; a finished order no longer needs it.
|
// A mark on the card, not a stage; a finished order no longer needs it.
|
||||||
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
|
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
|
||||||
@@ -658,7 +664,7 @@ function renderFilters(){
|
|||||||
}
|
}
|
||||||
function renderBoard(){
|
function renderBoard(){
|
||||||
renderFilters();
|
renderFilters();
|
||||||
const active=board.orders.filter(o=>['rec','tra','fil','imp'].includes(o.state));
|
const active=board.orders.filter(o=>['rec','tra','imp'].includes(o.state));
|
||||||
const queued=active.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
|
const queued=active.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
|
||||||
$('board-summary').textContent=metres(queued)+' em produção';
|
$('board-summary').textContent=metres(queued)+' em produção';
|
||||||
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
|
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
|
||||||
@@ -672,8 +678,8 @@ function renderBoard(){
|
|||||||
// Finished orders are a recent window, not the whole history: say so.
|
// Finished orders are a recent window, not the whole history: say so.
|
||||||
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
|
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
|
||||||
line.append(swatch,node('h2',title),node('span',count,'n'));
|
line.append(swatch,node('h2',title),node('span',count,'n'));
|
||||||
// The print queue's tools need the room: there it says only the metres.
|
// The print queue (Arte conferida) has the room's tools: there it says only the metres.
|
||||||
const tools=state==='fil'&&may('print');
|
const tools=state==='tra'&&may('print');
|
||||||
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+(tools?'':' no total'):'vazio'));
|
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+(tools?'':' 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(tools){
|
if(tools){
|
||||||
@@ -688,7 +694,7 @@ function renderBoard(){
|
|||||||
// Dragging only goes forward to the next stage. Going back or asking for a
|
// Dragging only goes forward to the next stage. Going back or asking for a
|
||||||
// correction needs a reason, so those happen in the order panel.
|
// correction needs a reason, so those happen in the order panel.
|
||||||
column.ondragover=e=>{
|
column.ondragover=e=>{
|
||||||
if(dragging?.state===state&&state!=='fin'&&mayMove(state,state)){e.preventDefault();markDrop(column,e.clientY);return;}
|
if(dragging?.state===state&&state!=='fin'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;}
|
||||||
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');};
|
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');};
|
||||||
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');clearDrop();}};
|
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');clearDrop();}};
|
||||||
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
|
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
|
||||||
@@ -705,7 +711,8 @@ function renderBoard(){
|
|||||||
// An operator's test order: no payment, no Tiny.
|
// An operator's test order: no payment, no Tiny.
|
||||||
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&&mayMove(order.state,order.state);
|
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;
|
||||||
|
c.draggable=!order.cancelled_at&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
|
||||||
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');
|
||||||
@@ -736,7 +743,9 @@ function card(order){
|
|||||||
e.dataTransfer.setData('text/plain',order.id);
|
e.dataTransfer.setData('text/plain',order.id);
|
||||||
const forward=board.transitions[order.state].filter(s=>s!=='cor'&&mayMove(order.state,s));
|
const forward=board.transitions[order.state].filter(s=>s!=='cor'&&mayMove(order.state,s));
|
||||||
for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state));
|
for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state));
|
||||||
say((forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou ')+', ou ':'')+'arraste para cima ou para baixo para mudar a prioridade',false,60000);
|
const moves=forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou '):'';
|
||||||
|
const priority=mayReorder(order.state)?'arraste para cima ou para baixo para mudar a prioridade':'';
|
||||||
|
say(moves&&priority?moves+', ou '+priority:moves||priority,false,60000);
|
||||||
};
|
};
|
||||||
c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');};
|
c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');};
|
||||||
return c;
|
return c;
|
||||||
@@ -858,8 +867,9 @@ 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. The
|
||||||
// Sellers read the order; a correction's notice is theirs to send too.
|
// Revisor handles no artwork but releases to Finalizado, so gets the moves.
|
||||||
|
if(!may('produce')&&!ME?.moves?.length){
|
||||||
if(order.state==='cor'&&!order.cancelled_at)box.append(correctionNotice(order));
|
if(order.state==='cor'&&!order.cancelled_at)box.append(correctionNotice(order));
|
||||||
if(waitingContact(order))box.append(contactNotice(order,false));
|
if(waitingContact(order))box.append(contactNotice(order,false));
|
||||||
box.append(node('p',order.cancelled_at?'Pedido cancelado.':'Somente consulta: seu perfil não move pedidos.','muted'));
|
box.append(node('p',order.cancelled_at?'Pedido cancelado.':'Somente consulta: seu perfil não move pedidos.','muted'));
|
||||||
@@ -890,9 +900,9 @@ function moves(order){
|
|||||||
if(!mayMove(order.state,next))continue;
|
if(!mayMove(order.state,next))continue;
|
||||||
const b=node('button','Pedir correção','btn danger');b.type='button';b.dataset.move='cor';
|
const b=node('button','Pedir correção','btn danger');b.type='button';b.dataset.move='cor';
|
||||||
b.onclick=()=>toggle(reason);row.append(b);
|
b.onclick=()=>toggle(reason);row.append(b);
|
||||||
}else if(next==='fil'&&!finalDone(order)){
|
}else if(next==='tra'&&!finalDone(order)){
|
||||||
// The queue needs an approved final: approving it is the next step,
|
// Arte conferida is the queue and needs an approved final: approving it
|
||||||
// shown first, with the file that would be printed.
|
// is the next step, shown first, with the file that would be printed.
|
||||||
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
||||||
const upload=finalForm(order,all?ready.map(()=>null):ready);forms.unshift(upload);
|
const upload=finalForm(order,all?ready.map(()=>null):ready);forms.unshift(upload);
|
||||||
const text=node('div');text.append(node('b','Próximo passo: aprovar o arquivo final'));
|
const text=node('div');text.append(node('b','Próximo passo: aprovar o arquivo final'));
|
||||||
@@ -927,7 +937,8 @@ function moves(order){
|
|||||||
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
|
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(!row.children.length)row.append(node('span',order.state==='fin'?'Pedido concluído.':'Daqui em diante, com a produção.','muted'));
|
if(!row.children.length&&!step)row.append(node('span',order.state==='fin'?'Pedido concluído.'
|
||||||
|
:order.state==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.','muted'));
|
||||||
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
||||||
const previous=mayMove(order.state,board.back?.[order.state])?board.back?.[order.state]:null;
|
const previous=mayMove(order.state,board.back?.[order.state])?board.back?.[order.state]:null;
|
||||||
const sub=node('div',undefined,'subactions');
|
const sub=node('div',undefined,'subactions');
|
||||||
@@ -940,14 +951,14 @@ function moves(order){
|
|||||||
backForm.append(why,go);
|
backForm.append(why,go);
|
||||||
backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}};
|
backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}};
|
||||||
}
|
}
|
||||||
// The proof may be checked before Imprimindo, while the order waits in the queue.
|
// The proof is checked by the room, in the queue (Arte conferida) or while printing.
|
||||||
if(order.state==='fil'&&proofPending(order)&&may('print')){
|
if(['tra','imp'].includes(order.state)&&proofPending(order)&&may('print')){
|
||||||
const b=button('✓ Prova OK',()=>proofOk(order),'linkbtn');b.title='A prova foi impressa e conferida';sub.append(b);
|
const b=button('✓ Prova OK',()=>proofOk(order),'linkbtn');b.title='A prova foi impressa e conferida';sub.append(b);
|
||||||
}
|
}
|
||||||
// Waiting for a word with the customer: shown on top with "Contato feito";
|
// Waiting for a word with the customer: shown on top with "Contato feito";
|
||||||
// otherwise marked from here, with what has to be agreed.
|
// otherwise marked from here, with what has to be agreed.
|
||||||
const contactForm=node('form',undefined,'reason');contactForm.hidden=true;forms.push(contactForm);
|
const contactForm=node('form',undefined,'reason');contactForm.hidden=true;forms.push(contactForm);
|
||||||
if(order.state!=='fin'&&!waitingContact(order)){
|
if(order.state!=='fin'&&!waitingContact(order)&&may('produce')){
|
||||||
const b=node('button','☎ Aguardando contato','linkbtn');b.type='button';b.dataset.contact='';
|
const b=node('button','☎ Aguardando contato','linkbtn');b.type='button';b.dataset.contact='';
|
||||||
b.title='Marcar que é preciso falar com o cliente antes de imprimir';b.onclick=()=>toggle(contactForm);sub.append(b);
|
b.title='Marcar que é preciso falar com o cliente antes de imprimir';b.onclick=()=>toggle(contactForm);sub.append(b);
|
||||||
const what=node('input');what.placeholder='O que precisa ser combinado com o cliente';what.setAttribute('aria-label','O que precisa ser combinado');
|
const what=node('input');what.placeholder='O que precisa ser combinado com o cliente';what.setAttribute('aria-label','O que precisa ser combinado');
|
||||||
@@ -987,7 +998,7 @@ function moves(order){
|
|||||||
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);
|
||||||
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
|
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
|
||||||
const contactNow=waitingContact(order)?contactNotice(order,true):null;
|
const contactNow=waitingContact(order)?contactNotice(order,may('produce')):null;
|
||||||
box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
||||||
}
|
}
|
||||||
function contactNotice(order,canClear){
|
function contactNotice(order,canClear){
|
||||||
@@ -1044,7 +1055,7 @@ async function approveReady(order,ready){
|
|||||||
ready.map((r,i)=>(many?'Item '+(i+1)+': ':'')+r.label).join('\n')))return;
|
ready.map((r,i)=>(many?'Item '+(i+1)+': ':'')+r.label).join('\n')))return;
|
||||||
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
||||||
await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note});
|
await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note});
|
||||||
await load();say(mayMove(order.state,'fil')?'Arquivo final aprovado. Agora é só mover para a fila.':'Arquivo final aprovado. A produção coloca na fila.');
|
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
|
||||||
}
|
}
|
||||||
// The form for a file the operator prepared, or to pick per item; ready
|
// The form for a file the operator prepared, or to pick per item; ready
|
||||||
// files come ticked.
|
// files come ticked.
|
||||||
@@ -1152,8 +1163,9 @@ function finalsSection(order,revisions,section){
|
|||||||
if(!revisions.length)section.append(node('p','Nenhum arquivo final ainda.','faint'));
|
if(!revisions.length)section.append(node('p','Nenhum arquivo final ainda.','faint'));
|
||||||
// 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 conferida, the step at the top is the way in.
|
// Before approval, the step at the top (on the way to Arte conferida) is the way in.
|
||||||
if(!may('produce')||!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
|
// In Arte conferida, the queue, the finals stay as approved: to change one, the order goes back to Arte recebida.
|
||||||
|
if(!may('produce')||!['rec','cor'].includes(order.state)||!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();};
|
||||||
@@ -1167,7 +1179,7 @@ function historySection(order,rows,section){
|
|||||||
if(reason)text.append(node('span',' · '+reason,'muted'));
|
if(reason)text.append(node('span',' · '+reason,'muted'));
|
||||||
li.append(text,node('small',when(at)));return li;
|
li.append(text,node('small',when(at)));return li;
|
||||||
};
|
};
|
||||||
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+board.states[r.to_state]:board.states[r.to_state],r.operator,r.created_at,r.reason));
|
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),r.operator,r.created_at,r.reason));
|
||||||
list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':'Site',order.created_at,''));
|
list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':'Site',order.created_at,''));
|
||||||
section.replaceChildren(node('p','Histórico','eyebrow'),list);
|
section.replaceChildren(node('p','Histórico','eyebrow'),list);
|
||||||
}
|
}
|
||||||
@@ -1234,7 +1246,7 @@ function renderUsers(){
|
|||||||
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
|
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
|
||||||
:[node('p','Nenhuma máquina cadastrada.','faint')]));
|
:[node('p','Nenhuma máquina cadastrada.','faint')]));
|
||||||
}
|
}
|
||||||
const OPEN_STAGES=['rec','tra','fil','imp','cor'];
|
const OPEN_STAGES=['rec','tra','imp','cor'];
|
||||||
function machineTile(m){
|
function machineTile(m){
|
||||||
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
|
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
|
||||||
const head=node('div',undefined,'mtile-head');
|
const head=node('div',undefined,'mtile-head');
|
||||||
@@ -1274,7 +1286,7 @@ function userForm(u){
|
|||||||
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';
|
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 email=node('input');email.type='email';email.required=true;email.value=u?.email||'';
|
||||||
const role=node('select');
|
const role=node('select');
|
||||||
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','vendedor'];
|
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor'];
|
||||||
for(const r of roles){const o=node('option',ROLE_NAMES[r]);o.value=r;role.append(o);}
|
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;
|
role.value=u?.role||'operador';role.disabled=u?.role==='superadmin'||u?.email===ME.email;
|
||||||
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
|
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
|
||||||
@@ -1383,7 +1395,7 @@ async function loadStats(){
|
|||||||
return tr;});
|
return tr;});
|
||||||
if(!machineRows.length){const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada.','faint');td.colSpan=5;tr.append(td);machineRows.push(tr);}
|
if(!machineRows.length){const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada.','faint');td.colSpan=5;tr.append(td);machineRows.push(tr);}
|
||||||
$('stats-machines').replaceChildren(...machineRows);
|
$('stats-machines').replaceChildren(...machineRows);
|
||||||
const rows=['rec','tra','fil','imp','cor'].map(state=>{
|
const rows=['rec','tra','imp','cor','rev'].map(state=>{
|
||||||
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
|
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
|
||||||
name.append(sw,board.states[state]);
|
name.append(sw,board.states[state]);
|
||||||
const st=data.stages[state], now=data.waiting[state];
|
const st=data.stages[state], now=data.waiting[state];
|
||||||
|
|||||||
@@ -29,7 +29,8 @@ function icone(nome){
|
|||||||
}
|
}
|
||||||
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
||||||
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
||||||
const TRILHA=['rec','tra','fil','imp','fin'];
|
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
|
||||||
|
const TRILHA=['rec','tra','imp','rev','fin'];
|
||||||
const TAMANHO=10;
|
const TAMANHO=10;
|
||||||
let scope,states={},environment='',conta=null;
|
let scope,states={},environment='',conta=null;
|
||||||
let filtro={status:'all',code:'',days:0,page:1};
|
let filtro={status:'all',code:'',days:0,page:1};
|
||||||
|
|||||||
Reference in New Issue
Block a user