feat: Redesenho previews on the server: one at a time, counted, and the stage clock stops while one waits (Rodada 5, D2)

POST /api/operator/orders/{id}/redesign-preview (sent, approved,
rejected), redesign_previews table, previews on every board order, and
assign_late leaves out the time a preview waited for the customer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 11:59:24 -03:00
parent aeb43500a7
commit 45c5493a4c
5 changed files with 149 additions and 2 deletions

View File

@@ -88,7 +88,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test redesign_preview_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

View File

@@ -137,7 +137,15 @@ def assign_late(c, orders, limits):
if not since and order['state'] == 'fin':
since = order.get('finished_at')
since = since or order['created_at']
hours = max(0.0, (now - since).total_seconds() / 3600)
hours = (now - since).total_seconds() / 3600
# A preview waiting for the customer stops the stage clock: the time
# between sending it and its answer is left out (D2).
for preview in order.get('previews') or []:
if preview['sent_at'] < since:
continue
ended = preview['decided_at'] or now
hours -= max(0.0, (ended - preview['sent_at']).total_seconds() / 3600)
hours = max(0.0, hours)
limit_hours = float(limit['hours'])
# Paid designer work gives Art received its extra hours to prepare the
# art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
@@ -207,6 +215,10 @@ def with_print_files(c, orders):
# Why each order was last sent to correction, for the notice to the customer.
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
# A redesign's previews, oldest first: the card shows them and the stage
# clock leaves out the time a preview waited for the customer (D2).
previews = c.execute('''SELECT order_id,number,sent_at,sent_by,decided_at,result,reason,decided_by
FROM dtf_local.redesign_previews WHERE order_id=ANY(%s) ORDER BY order_id,number''', (ids,)).fetchall()
# Where a printing order's files are in its machine's hot folder (item 10).
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
# Orders the machine already printed: a reprint chooses which items go
@@ -252,6 +264,9 @@ def with_print_files(c, orders):
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
for row in fixes if row['order_id'] == order['id']]
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
order['previews'] = [{k: row[k] for k in ('number', 'sent_at', 'sent_by', 'decided_at', 'result',
'reason', 'decided_by')}
for row in previews if row['order_id'] == order['id']]
return assign_machines(c, orders)

View File

@@ -191,6 +191,46 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
return {'ok': True}
class RedesignPreview(StrictModel):
action: Literal['sent', 'approved', 'rejected']
reason: str = Field(default='', max_length=500)
@router.post('/api/operator/orders/{uid}/redesign-preview')
def redesign_preview(uid: UUID, body: RedesignPreview, user=Depends(can('produce'))):
"""A redesign's preview: sent to the customer, then approved or rejected.
One preview waits at a time; the stage clock stops while it waits."""
with db.connect() as c:
row = c.execute('SELECT id,number,snapshot,state,cancelled_at FROM dtf_local.orders WHERE id=%s FOR UPDATE',
(uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
if not (row['snapshot'] or {}).get('redesign'):
raise HTTPException(409, 'Este pedido não tem Ajuste Fino Redesenho.')
if row['cancelled_at'] or row['state'] != 'rec':
raise HTTPException(409, 'A prévia só vale com o pedido em Arte recebida.')
prior = c.execute('''SELECT id,number,decided_at,result FROM dtf_local.redesign_previews
WHERE order_id=%s ORDER BY number''', (uid,)).fetchall()
if body.action == 'sent':
if any(preview['decided_at'] is None for preview in prior):
raise HTTPException(409, 'Já há uma prévia com o cliente.')
if any(preview['result'] == 'approved' for preview in prior):
raise HTTPException(409, 'A prévia já foi aprovada.')
number = max((preview['number'] for preview in prior), default=0) + 1
c.execute('''INSERT INTO dtf_local.redesign_previews(order_id,number,sent_by)
VALUES(%s,%s,%s)''', (uid, number, user))
else:
opened = next((preview for preview in prior if preview['decided_at'] is None), None)
if not opened:
raise HTTPException(409, 'Nenhuma prévia com o cliente.')
reason = ' '.join(body.reason.split()) if body.action == 'rejected' else ''
c.execute('''UPDATE dtf_local.redesign_previews SET decided_at=now(),result=%s,reason=%s,decided_by=%s
WHERE id=%s''', (body.action, reason, user, opened['id']))
number = opened['number']
audit('redesign_preview_' + body.action, order=row['number'], number=number, operator=user)
return {'ok': True}
class ProofAnswer(StrictModel):
result: Literal['ok', 'rejected']
reason: str = Field(default='', max_length=500)

View File

@@ -0,0 +1,15 @@
-- Round 5, D2 (order from 2026-11-16): a redesign's preview, sent to the
-- customer, waiting for approval or rejection. One preview is open at a time.
CREATE TABLE IF NOT EXISTS dtf_local.redesign_previews (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
number int NOT NULL,
sent_at timestamptz NOT NULL DEFAULT now(),
sent_by text NOT NULL,
decided_at timestamptz,
result text CHECK (result IN ('approved','rejected')),
reason text NOT NULL DEFAULT '',
decided_by text,
UNIQUE (order_id, number)
);
CREATE UNIQUE INDEX IF NOT EXISTS redesign_previews_open ON dtf_local.redesign_previews(order_id) WHERE decided_at IS NULL;

View File

@@ -0,0 +1,77 @@
"""A redesign's preview: sent, then approved or rejected, stopping the clock."""
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client
from tests.users_test import order_fixture
def run():
client = Client()
client.call('/session')
owner = uuid4()
quote = order = None
try:
with db.connect() as c:
quote, order = order_fixture(c, owner, 'file')
c.execute("""UPDATE dtf_local.orders SET snapshot = snapshot || %s, state='rec', payment=%s
WHERE id=%s""",
(Jsonb({'redesign': {'arts': 1, 'cents': 1990}}),
Jsonb({'provider': 'mercadopago', 'id': str(order)}), order))
path = f'/operator/orders/{order}/redesign-preview'
# Nothing to approve before a preview was sent.
answer = client.call(path, {'action': 'approved'}, operator=True, expected=409)
assert answer['detail'] == 'Nenhuma prévia com o cliente.', answer
# The first preview opens.
client.call(path, {'action': 'sent'}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == str(order))
assert len(mine['previews']) == 1 and mine['previews'][0]['number'] == 1, mine['previews']
assert mine['previews'][0]['decided_at'] is None, mine['previews']
# Only one preview waits at a time.
answer = client.call(path, {'action': 'sent'}, operator=True, expected=409)
assert answer['detail'] == 'Já há uma prévia com o cliente.', answer
# Rejected with its reason, spaces tidied.
client.call(path, {'action': 'rejected', 'reason': ' motivo teste '}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == str(order))
preview = mine['previews'][0]
assert preview['result'] == 'rejected' and preview['reason'] == 'motivo teste', preview
assert preview['decided_at'] and preview['decided_by'], preview
# A second preview follows.
client.call(path, {'action': 'sent'}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == str(order))
assert [p['number'] for p in mine['previews']] == [1, 2], mine['previews']
assert mine['previews'][1]['decided_at'] is None, mine['previews']
# Three hours in Arte recebida, two of them waiting for the customer:
# the stage clock shows about one.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '3 hours' WHERE id=%s", (order,))
c.execute("""UPDATE dtf_local.redesign_previews SET sent_at=now()-interval '2 hours'
WHERE order_id=%s AND decided_at IS NULL""", (order,))
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == str(order))
assert abs(mine['state_hours'] - 1) < 0.2, mine['state_hours']
# Approved ends the previews; no new one is sent.
client.call(path, {'action': 'approved'}, operator=True)
answer = client.call(path, {'action': 'sent'}, operator=True, expected=409)
assert answer['detail'] == 'A prévia já foi aprovada.', answer
# An order without the redesign has no previews.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot = snapshot - 'redesign' WHERE id=%s", (order,))
answer = client.call(path, {'action': 'sent'}, operator=True, expected=409)
assert answer['detail'] == 'Este pedido não tem Ajuste Fino Redesenho.', answer
print('PASS: a redesign preview opens, closes with a reason, reopens, '
'stops the stage clock and never reopens after approval')
finally:
if order is not None:
with db.connect() as c:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
if __name__ == '__main__':
run()