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

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:
Cauê Faleiros
2026-10-26 12:45:57 -03:00
parent 93cb289940
commit b6f20733fa
26 changed files with 344 additions and 166 deletions

View File

@@ -21,7 +21,7 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not row: raise HTTPException(404, 'Order not found')
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))
@router.get('/api/operator/uploads/{uid}')

View File

@@ -12,8 +12,8 @@ from fastapi.responses import RedirectResponse
from pydantic import Field
from ..core import db
from ..core.auth import (COOKIE_SECURE, DESIGNER_STATES, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator,
login_failed, password_matches, throttle)
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
from ..printjobs import file_prefix, queue as queue_print_files
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}
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):
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')
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,
halfway between the orders it was dropped between. It neither changes the
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()
if not row:
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 = {}
for side in ('after', 'before'):
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')
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:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
@@ -623,19 +619,22 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
raise HTTPException(409, 'Pedido cancelado.')
if body.state == row['state']:
return row
designer_only(request, row['state'], body.state)
back = BACK.get(row['state']) == body.state
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]}.")
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():
raise HTTPException(422, 'Informe o motivo da correção.')
if back and not body.reason.strip():
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
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']))):
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']:
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
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)',
(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()
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):
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction
# 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,
'customer_path': f'/portal.html?order={uid}'}
# 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_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,
'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]
if 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')
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
downloads them straight from storage: a zip of multi-GB sheets would go
through the server."""
"""The approved final files of every order in the print queue (Arte
conferida). The browser downloads them straight from storage: a zip of
multi-GB sheets would go through the server."""
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.
if not auto:
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
nothing when the order was deleted, so their files can be removed."""
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)',
(body.held,)).fetchall() if body.held else []
return {'files': files,

View File

@@ -15,8 +15,9 @@ from pydantic import Field, field_validator
from .. import machines, mail
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 ..runtime import BACK, STATES, TRANSITIONS
router = APIRouter()
@@ -24,7 +25,7 @@ class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80)
email: str = Field(min_length=3, max_length=254)
role: Literal['admin', 'gestao', 'designer', 'operador', 'vendedor']
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor']
password: str | None = Field(default=None, min_length=8, max_length=128)
active: bool = True
machines: list[UUID] = Field(default_factory=list, max_length=50)
@@ -55,11 +56,17 @@ class PasswordChange(StrictModel):
@router.get('/api/operator/me')
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)
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'],
'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')