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

View File

@@ -50,8 +50,9 @@ def correction_owner(c, order, ref, kind):
def submit_files(c, order, body, identity, kind, actor):
if order['version'] != body.version:
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'):
raise HTTPException(409, 'O arquivo final só pode mudar antes da fila de impressão.')
# Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
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':
raise HTTPException(409, 'Este pedido não está esperando correção.')
if len({f.upload_id for f in body.files}) != len(body.files):

View File

@@ -121,9 +121,8 @@ def login_failed(email):
# 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.
# The designer approves and refuses artwork and asks for corrections, on every
# order whatever its machine, and moves cards only among DESIGNER_STATES.
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'vendedor')
DESIGNER_STATES = ('rec', 'tra', 'cor')
# order whatever its machine. Which cards each profile moves is MOVES.
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
@@ -133,6 +132,36 @@ CAPABILITIES = {
'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):
"""The operator behind this session, active, with the profile read now: a

View File

@@ -257,7 +257,7 @@ class PaymentIntent(StrictModel):
method: PaymentMethod
class Move(StrictModel):
state: Literal['rec','tra','fil','imp','cor','fin']
state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000)

View File

@@ -10,9 +10,9 @@ orders back to that choice, unless they are already printing.
from decimal import Decimal
# 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.
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".
LOCK = 7_041_901

View File

@@ -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'))
if not 5242880 <= PART_BYTES <= 67108864:
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'fil': 'Fila de impressão',
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'}
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []}
# Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
# impressão, 'fil', left the board), and Revisão checks the printed sheet
# before Finalizado. After a correction the new art goes back through Arte
# 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
# 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():

View File

@@ -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
-- 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 DROP CONSTRAINT IF EXISTS 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
-- machine someone chose (machine_chosen) or the one given automatically: the
-- 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.
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;
-- 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;

View File

@@ -26,15 +26,18 @@ numero_ecommerce.
Customer notices: the client sends WhatsApp messages from Tiny's order
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
envio (pickup only), Enviado and Entregue. With TINY_STATUS_UPDATES on, the
Kanban moves the Tiny order along with it:
envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves
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)
Imprimindo -> Preparando envio (no notice)
Finalizado, pickup -> Pronto para envio (the pickup notice)
Finalizado, delivery -> unchanged: the team invoices and ships in Tiny
Arte conferida (queue) -> Preparando envio (no notice)
Finalizado -> Pronto para envio (pickup or delivery)
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
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
@@ -759,13 +762,9 @@ class TinyOrders:
return receipt
def ready(self, event_key, payload):
"""A pickup order became ready: "Pronto para envio", which the client's
notices turn into the pickup message. Shipped orders get "Enviada"
once freight exists (1.2)."""
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'}
"""The order reached Finalizado: "Pronto para envio", for pickup and
delivery alike (Dropstar, 2026-10-23). From there the team ships it in
Tiny as any other order."""
return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA))
def move(self, event_key, payload, target, from_situacoes):