diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 26f2f99..bcda13b 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -86,7 +86,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - 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 run: | diff --git a/app/api/artwork.py b/app/api/artwork.py index 4b6ed31..82a4152 100644 --- a/app/api/artwork.py +++ b/app/api/artwork.py @@ -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}') diff --git a/app/api/operator.py b/app/api/operator.py index 31d403f..70beb39 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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, diff --git a/app/api/users.py b/app/api/users.py index 697957a..4a864d2 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -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') diff --git a/app/artwork.py b/app/artwork.py index 330a756..9542bbb 100644 --- a/app/artwork.py +++ b/app/artwork.py @@ -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): diff --git a/app/core/auth.py b/app/core/auth.py index a98d7a2..b9b892b 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -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 diff --git a/app/core/models.py b/app/core/models.py index d5cb175..3b8deda 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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) diff --git a/app/machines.py b/app/machines.py index ca92dbb..19f63de 100644 --- a/app/machines.py +++ b/app/machines.py @@ -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 diff --git a/app/runtime.py b/app/runtime.py index 973b240..376330e 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -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(): diff --git a/app/schema.sql b/app/schema.sql index d2a9dc5..336c60b 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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; diff --git a/app/tiny.py b/app/tiny.py index 046ef96..c1b1ceb 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -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): diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 45cf0f4..4885fe1 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -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, 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 -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 replaced by another final, are removed from the 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 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 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 @@ -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 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 -(artwork stages only, every order, no machine, queue or cancelling; -DESIGNER_STATES 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 +(artwork stages only, every order, no machine, queue or cancelling; MOVES +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 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 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 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): - The DTF number in Tiny's `numeroPedidoEcommerce`: sent since 2026-10-26, next to the purchase order `numeroOrdemCompra` (which the resend check 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 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 - app/tiny.py is still DUPLICADO DROP), their flow image (removing Fila de - impressão, a Revisão column and a Revisor profile, the only one to move to - Finalizado; Tiny statuses per stage), the internal rules document (D-16 to - D-23), and the montador spec. Their three server folders moved on card moves - need a written decision: the Kanban in the room's browser can do it; a - program on their server is the factory agent left out of this scope. + app/tiny.py is still DUPLICADO DROP), the internal rules document (D-16 to + D-23), and the montador spec (and which "histórico" Marcus means for its + orders). Their three server folders moved on card moves need a written + decision: the Kanban in the room's browser can do it; a 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 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 approved quotes expire after 24 hours. A customer confirms the server total 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. Local mock integration receipts are visible in the Kanban. - The customer portal at `/portal.html` supports local registration/login, diff --git a/ops/demo_customer.py b/ops/demo_customer.py index dbb2e88..463306d 100644 --- a/ops/demo_customer.py +++ b/ops/demo_customer.py @@ -51,14 +51,14 @@ def main(): approved_quote(client, quote, [item]) orders.append(client.call('/orders/dev-paid', {'quote_id': quote['id']})) # 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'], - 3: ['tra', 'fil'], 4: ['tra'], 5: ['cor']} + stages = {0: ['tra', 'imp', 'rev', 'fin'], 1: ['tra', 'imp', 'rev', 'fin'], 2: ['tra', 'imp', 'rev'], + 3: ['tra', 'imp'], 4: ['tra'], 5: ['cor']} for index, path in stages.items(): order = orders[index] version = order['version'] for state in path: - if state == 'fil': - # The print queue takes approved final files, as on the Kanban. + if state == 'tra': + # 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']) version = client.call('/operator/orders/' + order['id'] + '/final-files', {'version': version, 'files': [{'item_index': 0, 'upload_id': final}], diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 9b28e4d..cc1ff29 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -204,13 +204,14 @@ try{ await kanban.click('[data-tab="board"]'); await kanban.click(`[data-card="${oid}"]`); 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']]){ - if(state==='fil'){ + // Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado. + 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, // not a move the server would refuse. The CDR has no ready file, so // the button opens the upload form there. 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 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'); @@ -218,7 +219,7 @@ try{ 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.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. const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1'; 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 kanban.click(`[data-order="${oid}"] [data-move="${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. 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); @@ -247,11 +248,11 @@ try{ } } // 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 kanban.click(`[data-order="${oid}"] [data-back="imp"]`); + await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="rev"]')`),'back button'); + await kanban.click(`[data-order="${oid}"] [data-back="rev"]`); 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 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 kanban.click(`[data-order="${oid}"] [data-move="fin"]`); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again'); diff --git a/tests/kanban_test.py b/tests/kanban_test.py index 99f30de..4a82868 100644 --- a/tests/kanban_test.py +++ b/tests/kanban_test.py @@ -138,7 +138,7 @@ def run(): assert isinstance(after['machines'], list) # An order sent back counts once per stage; its passages are counted apart. 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) 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) @@ -151,7 +151,7 @@ def run(): 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('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) 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) diff --git a/tests/payment_test.py b/tests/payment_test.py index c1b0b18..9b1500d 100644 --- a/tests/payment_test.py +++ b/tests/payment_test.py @@ -152,6 +152,11 @@ def run(): assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id'] 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',): moved = tester.call('/operator/orders/' + order['id'] + '/move', {'state': state, 'version': version}, operator=True) version = moved['version'] diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 511b200..8c1df6b 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -110,9 +110,9 @@ def run(): {'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], 'note': 'Generated print file checked'}, operator=True) version = result['version'] - for state in ('tra', 'fil'): - client.call('/operator/orders/' + oid + '/move', {'state': state, 'version': version}, operator=True) - version += 1 + # Arte conferida is the print queue (2026-10-23). + client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True) + version += 1 # Once queued for printing, the final set can no longer change. client.call('/operator/orders/' + oid + '/final-files', {'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 290048b..2e2994e 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -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':'cor','version':0},operator=True,expected=422) version=0 - for state in ('cor','rec','tra','fil','imp','fin'): - if state=='fil': - client.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409) + # Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado. + for state in ('cor','rec','tra','imp','rev','fin'): + 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)] result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True) version=result['version'] @@ -249,10 +251,10 @@ def run(): # 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 # 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':'tra','version':version},operator=True,expected=409) - back=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version,'reason':'Movido por engano'},operator=True) - assert back['state']=='imp';version+=1 + client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version},operator=True,expected=422) + client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409) + back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True) + assert back['state']=='rev';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) assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back'] diff --git a/tests/test_moves.py b/tests/test_moves.py new file mode 100644 index 0000000..069dd33 --- /dev/null +++ b/tests/test_moves.py @@ -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() diff --git a/tests/test_tiny.py b/tests/test_tiny.py index dd24531..c163df7 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -302,15 +302,15 @@ class TinyStatusTests(FakeTinyCase): self.assertEqual(self.puts(), []) @mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'}) - def test_ready_delivery_order_waits_for_freight(self): - self.tiny.deliver('k1', PAID) - self.calls.clear() - ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order']}) - self.assertEqual(ready['status'], 'not-applicable') - self.assertEqual(self.calls, []) + def test_a_finished_delivery_order_is_ready_too(self): + # Dropstar's flow, 2026-10-23: Finalizado is "Pronto para envio" for every order. + sale = self.tiny.deliver('k1', PAID) + ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order'], 'tiny_id': sale['tiny_id']}) + self.assertEqual((ready['status'], ready['situacao']), ('status-updated', 'Pronto para envio')) + self.assertEqual(self.orders[0]['situacao'], 7) @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) started = {**READY, 'event': 'production_started', 'order': PAID['order'], 'tiny_id': sale['tiny_id']} moved = self.tiny.deliver('k2', started) diff --git a/tests/users_test.py b/tests/users_test.py index 93f9a00..1f308f4 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -71,7 +71,7 @@ def run(): su = Client() su.call('/session') assert su.call('/operator/me', operator=True)['role'] == 'superadmin' - emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer')} + emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer', 'revisor')} owner = uuid4() machines, made = [], [] try: @@ -123,11 +123,20 @@ def run(): # On the UV machine of this test, whatever the others carry. 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']) seen = {o['id'] for o in op.call('/operator/board')['orders']} assert str(uv_o) in seen and str(textil_o) not in seen, seen - op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}) + 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('/operator/users', 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}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403) 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. admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer', 'password': PASSWORD, 'machines': [uv]}) @@ -152,8 +173,17 @@ def run(): 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']} 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': ''}) - designer.call(f'/operator/orders/{textil_o}/move', {'state': 'fil', 'version': moved['version'], 'reason': ''}, + # A correction and back; Arte conferida only with the final approved. + 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) designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'], 'reason': 'arte trocada'}) @@ -167,7 +197,7 @@ def run(): with db.connect() as c: long_q, long_o = order_fixture(c, owner, 'file', metres='12') 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'] su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True, expected=409) @@ -181,7 +211,7 @@ def run(): with db.connect() as c: short_q, short_o = order_fixture(c, owner, 'file', metres='10') 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'] 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. diff --git a/tests/workflow_test.py b/tests/workflow_test.py index 3019b34..720573d 100644 --- a/tests/workflow_test.py +++ b/tests/workflow_test.py @@ -49,8 +49,9 @@ def run(): 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'] - version=move('tra',0) - customer.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409) + # Arte conferida is the print queue (2026-10-23): it takes approved finals only. + 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) customer.call('/uploads/'+final_id,expected=404) 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') 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) - version=move('fil',version) + version=move('tra',version) # The print queue's files come named after their order, straight from storage. 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'] @@ -81,8 +82,7 @@ def run(): 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 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':'fil','version':version},operator=True,expected=409) + customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409) # 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'] 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) 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'] - 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) assert detail['state']=='fin' assert sum(f['active'] and f['kind']=='final' for f in detail['files'])==1 diff --git a/web/kanban.css b/web/kanban.css index 3f3d320..2ed426c 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -4,7 +4,7 @@ --line:#262A2F;--line2:#2A2F35;--line3:#3A4047; --tx:#ECE9E4;--tx2:#D5D2CC;--muted:#A3A9B0;--faint:#8B929A; --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; } *{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.over{color:var(--bad);font-weight:600} .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} diff --git a/web/kanban.html b/web/kanban.html index 9a77b28..27ad249 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -21,7 +21,7 @@ - +