diff --git a/app/api/operator.py b/app/api/operator.py index fa5a7b8..4dca8f3 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -111,9 +111,10 @@ def board(user=Depends(operator)): # card they can act on. Finished orders are terminal and only accumulate, # so the board carries a recent window of them and reports the true total. active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall() - finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s", - (BOARD_FINISHED_LIMIT,)).fetchall() - finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n'] + # A proof card that got its answer is done with (app/proof.py). + finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL + ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall() + finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n'] pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE} @@ -238,8 +239,19 @@ def with_print_files(c, orders): FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (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']) + # Each parent's latest proof card, and each card's parent (app/proof.py). + children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state, + proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders + WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()} + parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)', + ([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()} for order in orders: order['hot'] = hot.get(order['id']) + child = children.get(order['id']) + order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result', + 'proof_decided_at', 'proof_decided_by', 'proof_reason')} + parent = parents.get(order.get('parent_id')) + order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']} order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None order['print_files'] = [row for row in generated if row['order_id'] == order['id']] approved = [row for row in finals if row['order_id'] == order['id']] @@ -271,7 +283,7 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N """Older finished orders, newest first, beyond the board's recent window.""" paged = cursor_pair(before_created_at, before_id) with db.connect() as c: - rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' + rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL ''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + ''' ORDER BY created_at DESC,id DESC LIMIT %s''', ((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall() @@ -436,7 +448,8 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)) params.append(code + '%') quote_match, quote_params = customer_match('q.draft', q) with db.connect() as c: - orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql} + # Real orders: a proof card is found through its order (app/proof.py). + orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL ORDER BY created_at DESC LIMIT 8''', params).fetchall() rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id @@ -603,8 +616,10 @@ def delete_order(uid: UUID, user=Depends(can('manage'))): UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''', (uid, uid, uid)).fetchall()} candidates = produced - originals if test else produced | originals + # Its proof cards (app/proof.py) go with it. + cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()] for table in ('movements', 'order_files', 'print_files'): - c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,)) + c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,)) c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,)) if not test: @@ -744,10 +759,78 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))): return {'ok': True} +class ProofAnswer(StrictModel): + result: Literal['ok', 'rejected'] + reason: str = Field(default='', max_length=500) + + +@router.post('/api/operator/orders/{uid}/proof-answer') +def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))): + """The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK + puts its order in the queue; Prova reprovada, with its reason, sends the + order back to Arte recebida. Either way the card closes.""" + reason = ' '.join(body.reason.split()) + if body.result == 'rejected' and len(reason) < 3: + raise HTTPException(422, 'Diga por que a prova foi reprovada.') + with db.connect() as c: + card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not card or not card.get('parent_id'): + raise HTTPException(404, 'Card de prova não encontrado.') + if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev': + raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.') + parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone() + c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s, + proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''', + (body.result, user, reason or None, uid)) + label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label)) + if body.result == 'ok': + # The order enters the queue: Arte conferida, if its finals are approved. + ready = parent['state'] == 'rec' and all(c.execute('''SELECT 1 FROM dtf_local.order_files + WHERE order_id=%s AND kind='final' AND active AND item_index=%s LIMIT 1''', (parent['id'], i)).fetchone() + for i in range(len(parent['snapshot']['items']))) + c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(), + state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id'])) + if ready: + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user)) + elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']: + # Back to Arte recebida with the reason; its final is approved again. + c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],)) + c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL, + version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],)) + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label)) + audit('order_proof_answered', order=parent['number'], result=body.result, operator=user) + return {'ok': True} + + +@router.post('/api/operator/orders/{uid}/proof-card') +def new_proof_card(uid: UUID, user=Depends(can('produce'))): + """A new proof card for an order whose proof was rejected, or that has + none yet (an order from before the cards).""" + with db.connect() as c: + row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not row or row.get('parent_id'): + raise HTTPException(404, 'Pedido não encontrado.') + if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid): + raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.') + child = proof.create_child(c, row) + if not child: + raise HTTPException(409, 'Este pedido não leva prova.') + machines.route(c) + audit('order_proof_card', order=row['number'], operator=user) + return {'ok': True, 'id': child['id'], 'number': child['number']} + + @router.post('/api/operator/orders/{uid}/proof') def proof_ok(uid: UUID, user=Depends(can('print'))): - """The print room checked the proof: the order may reach Finalizado.""" + """An order from before the proof cards: the print room checked the + proof, and the order may reach Finalizado.""" with db.connect() as c: + if proof.open_child(c, uid): + raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.') row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1 WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone() if not row: @@ -968,7 +1051,13 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): # Two at most per machine in Imprimindo (app/machines.py). if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)): raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') - if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']: + # A proof card ends with its answer, not in Finalizado; its order waits + # for that answer outside the queue (app/proof.py). + if row.get('parent_id') and body.state == 'fin': + raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.') + if body.state == 'imp' and proof.waiting(c, row): + raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.') + if body.state == 'fin' and not row.get('parent_id') 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': c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,)) @@ -1124,7 +1213,8 @@ def thumbnail(uid: UUID, user=Depends(operator)): headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'}) # Real work only: an operator's test order and a cancelled one are not production. -REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'" +# A proof card (app/proof.py) is no sale either. +REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL" # Where orders come from (D-21), in the order Números lists them. ORIGINS = ('site', 'dropflow', 'atendimento') LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" diff --git a/app/core/auth.py b/app/core/auth.py index c108c79..d011d7c 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -145,6 +145,9 @@ CAPABILITIES = { # file. Resolving a payment stays with "manage". 'payments': {'superadmin', 'admin', 'gestao', 'financeiro'}, 'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'}, + # Prova OK or reprovada, on the proof card only (Dropstar, 2026-11-03): the + # seller, who otherwise only views, Gestão and the administrators. + 'proof': {'superadmin', 'admin', 'gestao', 'vendedor'}, # "Retirado" at the counter (Dropstar's third round, item 14): everyone # but the seller, who only views (D-30). It includes everyone who produces, # and the operator, so an operator upload (artwork.py) takes it for its parts. diff --git a/app/payments.py b/app/payments.py index cc3ca91..a2ccc9c 100644 --- a/app/payments.py +++ b/app/payments.py @@ -63,9 +63,10 @@ OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit') def in_tiny(order): - """Whether the order goes to Tiny: every order but a test. A Dropflow - order goes in its own revenue category (app/tiny.py, CATEGORIES).""" - return not is_test(order) + """Whether the order goes to Tiny: every order but a test or a proof card + (app/proof.py), which is no sale. A Dropflow order goes in its own revenue + category (app/tiny.py, CATEGORIES).""" + return not is_test(order) and not order.get('parent_id') # How long a file is kept while nothing has been paid for it. A cart's files @@ -118,6 +119,8 @@ def create_order(c, quote, payment, origin): order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone() c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],)) + # An order with a proof gets its proof card (app/proof.py). + proof.create_child(c, order) machines.route(c) if is_test(order): return order, True diff --git a/app/printjobs.py b/app/printjobs.py index 7da457d..226004f 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -32,6 +32,7 @@ from .core.auth import audit from .core.db import connect from .printfile import Unsupported from .printpng import render +from .proof import PROOF_SHEET_CM from .tiny import purchase_order LOCAL = ZoneInfo('America/Sao_Paulo') @@ -159,6 +160,10 @@ def footer(job, item): count = len(job['snapshot']['items']) day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y') billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',') + proof_of = job['snapshot'].get('proof_of') + if proof_of: + return ' · '.join(['DROPSTAR', f'Prova do pedido {purchase_order(proof_of)}', + f'Item {job["item_index"] + 1}/{count}', day]) fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}', f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m'] # A mirrored artwork (UV only) is named on the sheet, for the room to see @@ -185,8 +190,12 @@ def produce(storage, job, item, uploads): local = os.path.join(scratch, f'source-{index}') storage.fetch(uploads[upload_id]['object_key'], local) files[index] = (local, uploads[upload_id]['name']) - parts, detail = render(item, files, output, file_prefix(job['number'], job['item_index']), - footer=footer(job, item), tiles=True) + proof_of = job['snapshot'].get('proof_of') + # A proof card's file: the first 30 cm, DTF-N-item-1-prova.png (app/proof.py). + prefix = (file_prefix(proof_of, job['item_index']) + '-prova' if proof_of + else file_prefix(job['number'], job['item_index'])) + parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True, + limit_cm=PROOF_SHEET_CM if proof_of else None) except BaseException: shutil.rmtree(output, ignore_errors=True) raise diff --git a/app/printpng.py b/app/printpng.py index 2edaac3..9041ea7 100644 --- a/app/printpng.py +++ b/app/printpng.py @@ -425,7 +425,7 @@ def footer_band(text, width): # ---- The file --------------------------------------------------------------- -def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False): +def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None): """Write the PNG part(s) of one approved order item into `out_dir`. `files` maps each source index to (local path, original name). With @@ -443,7 +443,9 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False) width = px(production['film_width_cm']) pieces = sorted((Piece(placement, sources[placement['source_index']]) for placement in production['placements']), key=lambda piece: piece.y) - cuts = part_cuts(production, part_cm) + # A proof sheet is the film's first `limit_cm` (app/proof.py). + cuts = ([Decimal(0), min(Decimal(str(production['height_cm'])), Decimal(str(limit_cm)))] if limit_cm + else part_cuts(production, part_cm)) count = len(cuts) - 1 parts, manifests = [], [] for number in range(count): diff --git a/app/proof.py b/app/proof.py index 3ef3b45..23b6ab6 100644 --- a/app/proof.py +++ b/app/proof.py @@ -11,6 +11,9 @@ marks "Prova OK" once the proof is checked, and without it the order does not reach Finalizado. """ from decimal import Decimal +from uuid import NAMESPACE_URL, uuid4, uuid5 + +from psycopg.types.json import Jsonb PROOF_ABOVE_METRES = Decimal('10') CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp ' @@ -24,3 +27,50 @@ def billed_metres(snapshot): def needs_proof(snapshot): """Whether the order prints a proof first: asked for, or above 10 m.""" return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES + + +# ---- The proof card (Dropstar's third round, 2026-10-30 and 2026-11-03) ----- +# +# An order with a proof becomes a parent and a child. The child, the card +# "Prova", is an order of its own (orders.parent_id) with a pre-built proof +# sheet of up to 30 cm, DTF-N-item-1-prova.png, and follows the normal flow up +# to Revisão. The parent waits outside the queue, "Aguardando prova". On the +# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and +# the parent enters the queue; or Prova reprovada, with its reason, and the +# parent goes back to Arte recebida and the child closes. The child is no +# sale: it is not in Tiny, Números, the customer's account or their e-mails. +PROOF_SHEET_CM = Decimal('30') +# Three proofs at most per order, one per item (Dropstar, 2026-10-23). +MAX_PROOFS = 3 +PROVIDER = 'prova' + + +def proof_identity(order_id): + return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}') + + +def create_child(c, parent): + """The parent's proof card, in Arte recebida, its proof sheets queued to be + generated. Returns it, or None when the order needs no proof.""" + if parent.get('parent_id') or not needs_proof(parent['snapshot']): + return None + from .printjobs import queue + snapshot = {**parent['snapshot'], 'items': parent['snapshot']['items'][:MAX_PROOFS], + 'proof_of': parent['number']} + child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen) + VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''', + (uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}), + parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone() + queue(c, child['id'], len(snapshot['items'])) + return child + + +def open_child(c, parent_id): + """The parent's proof card still waiting for its answer, if any.""" + return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL + AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone() + + +def waiting(c, order): + """Whether the order waits for its proof: it has a proof card without an OK.""" + return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id'])) diff --git a/app/schema.sql b/app/schema.sql index 19bc48c..493ffbe 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -456,6 +456,32 @@ ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answere -- The contraction class chosen per item (item 9), keyed by item index, with -- who chose it and when; the measured class stays in the order's snapshot. ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb; + +-- The proof card (Dropstar, 2026-10-30, app/proof.py): an order of its own, +-- child of the order it proves, with no quote of its own; its answer, Prova OK +-- or reprovada with its reason, by whom and when. +ALTER TABLE dtf_local.orders ALTER COLUMN quote_id DROP NOT NULL; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES dtf_local.orders(id) ON DELETE CASCADE; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_result text CHECK (proof_result IN ('ok','rejected')); +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_at timestamptz; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_by text; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_reason text; +CREATE INDEX IF NOT EXISTS orders_parent ON dtf_local.orders(parent_id) WHERE parent_id IS NOT NULL; +-- An order's own rows go with it, so deleting an order takes its proof cards +-- and theirs too. Done once: a constraint already cascading is left alone. +DO $$ +DECLARE r record; +BEGIN + FOR r IN SELECT c.conname, c.conrelid::regclass AS tbl FROM pg_constraint c + WHERE c.contype='f' AND c.confrelid='dtf_local.orders'::regclass AND c.confdeltype<>'c' + AND c.conrelid IN ('dtf_local.movements'::regclass, 'dtf_local.order_files'::regclass, + 'dtf_local.print_files'::regclass) + LOOP + EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', r.tbl, r.conname); + EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I FOREIGN KEY (order_id) REFERENCES dtf_local.orders(id) ON DELETE CASCADE', + r.tbl, r.conname); + END LOOP; +END $$; -- When the session was last used (Usuários: who is on the system now). ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz; -- The machine of whoever moved a card, as it was named then: "Imprimindo · diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 00118e4..b7d2f2a 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -15,6 +15,7 @@ from uuid import uuid4 from PIL import Image +from app.core import db from tests.payment_test import deliver from tests.smoke_test import Client, approved_quote as approval, upload_bytes @@ -204,6 +205,56 @@ def run(): assert red[3] == 255 and red[0] > 200 and red[1] < 60, red print('PASS: PDF artwork drawn into the PNG print file at 300 DPI') + # The proof card (Dropstar, 2026-10-30 and 2026-11-03): an order above + # 10 m gets a child card "Prova"; the order waits outside the queue until + # the card in Revisão gets its answer. + # Artwork the generator refuses at once, so no 10 m file is drawn. + unread = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='LOCAL-PROOF-TEST.cdr') + long = loose_item(unread, copies=1) + long['metres'] = '10.5' + long['production'] = {**long['production'], 'height_cm': 1050, + 'placements': [{**long['production']['placements'][0], 'y_cm': 1040}]} + parent = paid_order(client, long) + board = client.call('/operator/board', operator=True)['orders'] + mine = next(o for o in board if o['id'] == parent['id']) + card = next(o for o in board if o['id'] == mine['proof_card']['id']) + assert card['proof_parent']['number'] == parent['number'] and card['state'] == 'rec', card + assert card['snapshot']['proof_of'] == parent['number'] and card['payment'] == {'provider': 'prova'} + with db.connect() as c: + assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key LIKE %s', (card['id'] + '%',)).fetchone() + c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],)) + final = upload_bytes(client, b'LOCAL PROOF FINAL FIXTURE', order_id=parent['id']) + version = client.call('/operator/orders/' + parent['id'] + '/final-files', + {'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}], + 'note': 'Local proof test final'}, operator=True)['version'] + version = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'tra', 'version': version}, + operator=True)['version'] + held = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'imp', 'version': version}, + operator=True, expected=409) + assert 'Aguardando prova' in held['detail'], held + client.call('/operator/orders/' + card['id'] + '/move', {'state': 'fin', 'version': card['version']}, + operator=True, expected=409) + # Reprovada needs its reason; the order goes back to Arte recebida. + client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'rejected', 'reason': 'x'}, + operator=True, expected=422) + client.call('/operator/orders/' + card['id'] + '/proof-answer', + {'result': 'rejected', 'reason': 'Cor do fundo errada'}, operator=True) + client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True, expected=409) + board = client.call('/operator/board', operator=True)['orders'] + mine = next(o for o in board if o['id'] == parent['id']) + assert mine['state'] == 'rec' and mine['proof_card']['proof_result'] == 'rejected', mine['proof_card'] + assert mine['proof_card']['proof_reason'] == 'Cor do fundo errada' + assert not [o for o in board if o['id'] == card['id']], 'an answered proof card leaves the board' + # A new card, and Prova OK lets the order into the queue. + again = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True) + client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True, expected=409) + with db.connect() as c: + c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (again['id'],)) + client.call('/operator/orders/' + again['id'] + '/proof-answer', {'result': 'ok'}, operator=True) + mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id']) + assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine + print('PASS: an order with a proof waits for its proof card, which is answered OK or rejected in Revisão') + # A customer cannot see or reuse another order's generated file. other = Client() other.call('/session') diff --git a/tests/smoke_test.py b/tests/smoke_test.py index d288145..76c29fb 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -272,10 +272,17 @@ def run(): 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'] - if state=='fin': - # Above 10 m the proof comes first: no Finalizado before Prova OK (app/proof.py). - client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True,expected=409) - version=client.call('/operator/orders/'+oid+'/proof',{},operator=True)['version'] + if state=='imp': + # Above 10 m the proof comes first (app/proof.py): the order waits + # outside the queue for Prova OK on its proof card in Revisão. + held=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409) + assert 'Aguardando prova' in held['detail'], held + card=next(o for o in client.call('/operator/board',operator=True)['orders'] if o['id']==oid)['proof_card'] + from app.core import db + with db.connect() as c: + c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s",(card['id'],)) + client.call('/operator/orders/'+card['id']+'/proof-answer',{'result':'ok'},operator=True) + version+=1 moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True) version+=1;assert moved['version']==version client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409) diff --git a/tests/users_test.py b/tests/users_test.py index 89da3b4..a231115 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -199,7 +199,8 @@ 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) # The seller only views the board (D-30): no order registered by hand either. - assert seller.call('/operator/me')['can'] == ['view'] + # The seller only views, but answers a proof card (Dropstar, 2026-11-03). + assert seller.call('/operator/me')['can'] == ['proof', 'view'] seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) # Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and # Cotações, and cancels an order with its reason; moves nothing. diff --git a/web/kanban.js b/web/kanban.js index c0e81d8..2eced2f 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -686,7 +686,21 @@ const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since); const PROOF_ABOVE_METRES=10; const PROOF_RULE='Até 30 cm, do trecho de traço mais fino, um pedaço de cada arte diferente; no máximo 3 provas por pedido, sem cobrança.'; const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES; -const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at; +const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent; +// The proof card (app/proof.py): the order's own card waits outside the queue +// for its answer; an order from before the cards has none. +const waitingProof=order=>!!order.proof_card&&!order.proof_card.proof_result&&!order.proof_ok_at; +const proofRejected=order=>order.proof_card?.proof_result==='rejected'&&!order.proof_ok_at; +async function proofAnswer(order,result,reason=''){ + await api('/orders/'+order.id+'/proof-answer',{result,reason});await load(); + say(result==='ok'?'Prova OK: o pedido #'+order.proof_parent.number+' entra na fila.':'Prova reprovada: o pedido #'+order.proof_parent.number+' voltou para Arte recebida.'); +} +function proofReject(order){ + const reason=node('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=3; + formDialog('Prova reprovada',{host:$('drawer'),label:'Reprovar a prova',tone:'red', + text:'O pedido #'+order.proof_parent.number+' volta para Arte recebida com o motivo, e este card de prova encerra.', + fields:[field('Motivo',reason)],onsave:async()=>{await proofAnswer(order,'rejected',reason.value);}}); +} const TREATED_NOTE='O arquivo final foi preparado pela equipe, não é a arte que o cliente mandou.'; // Mirrored by the customer (UV only, web/site-pdf.js): the room checks it before printing. const mirroredItem=item=>!!item.production?.sources?.some(source=>source.mirrored); @@ -942,7 +956,8 @@ function markLane(column,id){ // A card's place in the print queue, among the orders of its product (a // textile machine pulls the next textile order). const uvOrder=o=>o.snapshot.items.some(i=>i.mode.startsWith('uv')); -const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)).indexOf(order)+1; +// An order waiting for its proof is not in the queue yet (app/proof.py). +const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)&&!waitingProof(o)).indexOf(order)+1; // An operator's test order: no payment, no Tiny. const isTest=order=>order.payment?.provider==='teste'; const shortAgo=value=>ago(value).replace(/^há /,''); @@ -952,6 +967,9 @@ const shortAgo=value=>ago(value).replace(/^há /,''); function nextStep(order,place){ if(order.cancelled_at)return ['Cancelado','wait']; if(order.state==='cor')return ['Esperando o cliente','wait']; + // The proof card waits for its answer; its order, outside the queue, for that. + if(order.proof_parent&&order.state==='rev')return ['Responder a prova','act']; + if(order.state==='tra'&&waitingProof(order))return ['Aguardando prova','wait']; if(order.state==='rev')return ['Conferir a folha','act']; if(order.state==='imp')return partsStep(order)||(order.printing?PRINTING[order.printing].slice(0,2):['Na máquina','wait']); if(order.state==='tra'){ @@ -979,7 +997,10 @@ function cardFlags(order){ if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]); if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]); if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]); - if(live&&proofPending(order))out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']); + if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]); + if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]); + if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]); + if(live&&proofPending(order)&&!order.proof_card)out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']); if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']); const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0); if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]); @@ -1308,7 +1329,10 @@ function renderPanel(order){ // What was paid and when, where it came from, and the codes: DTF-23 is the // room's, in the file names, the footer and Tiny; the customer knows the other. const sub=node('div',undefined,'dsub'); - const paid=node('span');paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at): + const paid=node('span'); + // A proof card is no sale (app/proof.py): it says whose proof it is. + if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at)); + else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at): paidOutside(order)?' pago fora do site ('+PAID_OUTSIDE[order.payment.method]+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at)); const code=node('span',undefined,'chip'); code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido')); @@ -1494,6 +1518,15 @@ function nextBox(order){ const note=text=>body.push(node('p',text,'nnote')); const can=to=>mayMove(st,to)&&mayAct(order); const moveBtn=(to,label,className='btn pri lg')=>{const b=button(label||'Mover para '+board.states[to],()=>move(order,to),className);b.dataset.move=to;return b;}; + // A proof card in Revisão waits for its answer (Dropstar, 2026-11-03). + if(order.proof_parent&&st==='rev'){ + title='Responder a prova'; + note('Prova do pedido #'+order.proof_parent.number+'. Com a prova impressa conferida'+(order.snapshot.proof?' e o aceite do cliente':'')+', responda aqui.'); + if(may('proof')){main.push(button('Prova OK',()=>proofAnswer(order,'ok'),'btn pri lg')); + more.push(button('Prova reprovada',()=>proofReject(order),'btn quiet lg'));} + else note('Quem responde é o Vendedor, a Gestão ou o Administrador.'); + return composeNext(title,body,main,more); + } const readOnly=!may('produce')&&!ME?.moves?.length; const fixed=(order.corrections||[]).length>0; if(st==='cor'){ @@ -1509,10 +1542,15 @@ function nextBox(order){ } const fixBtn=()=>{if(!trans.includes('cor')||!can('cor'))return; const b=node('button','Pedir correção','btn quiet lg');b.type='button';b.dataset.move='cor';b.onclick=()=>correctionDialog(order);more.push(b);}; - const proofBtn=(className='btn lg')=>{if(!proofPending(order)||!may('print'))return null; + const proofBtn=(className='btn lg')=>{if(!proofPending(order)||order.proof_card||!may('print'))return null; const b=button('Prova OK',()=>proofOk(order),className);b.dataset.proof='';b.title='A prova foi impressa e conferida';return b;}; const cannot=()=>note(!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.' :st==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.'); + // The proof was rejected: its reason, and a new proof card when the art is fixed. + if(st==='rec'&&proofRejected(order)){ + const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p); + if(may('produce'))more.push(button('Nova prova',async()=>{await api('/orders/'+order.id+'/proof-card',{});await load();say('Nova prova criada.');},'btn lg')); + } if(st==='rec'||st==='cor'){ if(!finalDone(order)&&trans.includes('tra')){ if(st==='rec')title='Aprovar o arquivo final'; @@ -1537,6 +1575,10 @@ function nextBox(order){ if(can(to))(to==='tra'&&finalDone(order)?main:more).push(moveBtn(to,null,to==='tra'&&finalDone(order)?'btn pri lg':'btn lg')); } if(st==='rec')fixBtn(); + }else if(st==='tra'&&waitingProof(order)){ + title='Aguardando prova'; + note('O pedido entra na fila com Prova OK no card da prova #'+order.proof_card.number+'.'); + fixBtn(); }else if(st==='tra'){ title='Puxar para a máquina'; note(order.machine?'Vai para a '+order.machine.name+'. O arquivo final já está aprovado.':'O arquivo final já está aprovado.'); @@ -2155,7 +2197,7 @@ function avatar(u,className='ava'){ const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro']; const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNN'],['Pedir correção','YYYNNNN'],['Puxar da fila e imprimir','YNNYNNN'], ['Liberar para Finalizado','YNNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'], - ['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNV'],['Pedido pago fora do site','YYNNNNN'],['Cancelar pedido','YYNNNNY'], + ['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNV'],['Pedido pago fora do site','YYNNNNN'],['Prova OK ou reprovada','YYNNNYN'],['Cancelar pedido','YYNNNNY'], ['Abrir retrabalho','NYNNNNN'],['Autorizar retrabalho','YNNNNNN'],['Usuários e máquinas','YNNNNNN']]; let usersData=null; async function loadUsers(){