diff --git a/app/api/operator.py b/app/api/operator.py index 71e462f..4cb74da 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -16,7 +16,7 @@ from ..core.auth import (COOKIE_SECURE, DESIGNER_STATES, DUMMY_PASSWORD_HASH, au login_failed, password_matches, throttle) from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel from ..printjobs import queue as queue_print_files -from .. import cnpj, machines, mail, payments, quote_review +from .. import cnpj, machines, mail, payments, proof, quote_review from .. import tiny from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, TRANSITIONS, payment, enqueue, freight, quote_view, storage) @@ -558,6 +558,18 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))): return {'ok': True} +@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.""" + with db.connect() as c: + 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: + raise HTTPException(404, 'Pedido não encontrado.') + audit('order_proof_ok', order=row['number'], operator=user) + return {'ok': True, 'version': row['version']} + + class QueuePlace(StrictModel): """Where a dragged card lands: between two orders of its column, either of them absent at the top or the bottom.""" @@ -624,6 +636,8 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))): 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.') + if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']: + raise HTTPException(409, 'Falta a prova: confira os 20 cm impressos 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,)) c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)', diff --git a/app/core/models.py b/app/core/models.py index eab2fc8..d5cb175 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -207,6 +207,8 @@ class QuoteRequest(StrictModel): items: list[Item] = Field(min_length=1, max_length=30) freight: Freight destination: Destination | None = None + # "Quero aprovar uma prova antes de imprimir": the order waits for the customer. + proof: bool = False @model_validator(mode='after') def destination_matches_freight(self): diff --git a/app/payments.py b/app/payments.py index 97d7419..81bc07b 100644 --- a/app/payments.py +++ b/app/payments.py @@ -16,7 +16,7 @@ from uuid import UUID, uuid4 from psycopg.types.json import Jsonb -from . import machines, mail +from . import machines, mail, proof from .core.auth import audit from .core.models import PRODUCTION_VERSIONS from .printjobs import queue as queue_print_files @@ -98,6 +98,10 @@ def create_order(c, quote, payment): c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval) WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved))) queue_print_files(c, order['id'], len(approved['items'])) + if approved.get('proof'): + # The customer asked for a proof: the order waits for their word. + 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() machines.route(c) if is_test(order): return order, True diff --git a/app/proof.py b/app/proof.py new file mode 100644 index 0000000..999c71e --- /dev/null +++ b/app/proof.py @@ -0,0 +1,23 @@ +"""The print proof (Dropstar, 2026-10-21). + +An order above 10 m prints 20 cm of proof before the rest, checked by the +print room without stopping the order. A customer may also ask for a proof at +checkout, for any length: that order waits for them, marked "Aguardando +contato", until they approve the photo sent by WhatsApp. Either way the room +marks "Prova OK" once the proof is checked, and without it the order does not +reach Finalizado. The proof is not billed (to be confirmed by Dropstar). +""" +from decimal import Decimal + +PROOF_ABOVE_METRES = Decimal('10') +CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp ' + 'e espere o aceite.') + + +def billed_metres(snapshot): + return sum((Decimal(str(item.get('billed_metres') or 0)) for item in snapshot.get('items') or []), Decimal(0)) + + +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 diff --git a/app/quote_review.py b/app/quote_review.py index 3473f59..da30f7c 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -86,6 +86,7 @@ def approve(c, row, items, reviewer): raise HTTPException(422, str(exc)) approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight, 'destination': draft.get('destination'), + **({'proof': True} if draft.get('proof') else {}), 'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']} c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s', (Jsonb(approved), reviewer, row['id'])) diff --git a/app/schema.sql b/app/schema.sql index a5a3e8c..d2a9dc5 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -342,3 +342,10 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check CHECK(kind IN ('reset','code','account','notice','order','alert','test')); + +-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose +-- customer asked for a proof at checkout, prints 20 cm first; the room marks +-- "Prova OK" once it is checked, and without it the order does not reach +-- 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; diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 566aa99..8d4292d 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -357,7 +357,10 @@ over 150 MB and CDR/AI/PSD/TIFF are not checked. The generated print PDF ends in a 1,5 cm footer band below the layout, outside the billed length: "DROPSTAR · Pedido DTF- · Item 1/2 · date · billed metres" in black Helvetica (the logo waits for Dropstar's file). An original used whole as its -own print file (over 300 MB) has no footer. Waiting on +own print file (over 300 MB) has no footer. The print proof (app/proof.py): +an order above 10 m, or one whose customer ticked "quero aprovar uma prova" at +checkout (that one arrives marked Aguardando contato), cannot reach Finalizado +before the print room marks Prova OK; the proof is not billed. Waiting on Dropstar: the Tiny category/seller/tag conflict, residue and opaque background blocking, the print-file footer, the packing margins, the DTF terms, the manual-file value, the proof print, and mirroring. diff --git a/tests/users_test.py b/tests/users_test.py index 8483145..93f9a00 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -9,6 +9,7 @@ from uuid import uuid4 from psycopg.types.json import Jsonb from app import machines as routing +from app import payments, proof from app.core import db from tests.smoke_test import Client @@ -161,6 +162,41 @@ def run(): designer.call('/operator/queue/finals', expected=403) designer.call('/operator/users', expected=403) + # The print proof (Dropstar, 2026-10-21): above 10 m, no Finalizado before + # "Prova OK", which the print room marks and the designer cannot. + 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,)) + 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) + designer.call(f'/operator/orders/{long_o}/proof', {}, expected=403) + seller.call(f'/operator/orders/{long_o}/proof', {}, expected=403) + version = su.call(f'/operator/orders/{long_o}/proof', {}, operator=True)['version'] + board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']} + assert board[str(long_o)]['proof_ok_at'] and board[str(long_o)]['proof_ok_by'] + su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True) + # Up to 10 m, nothing to wait for. + 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,)) + 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. + with db.connect() as c: + asked = uuid4() + content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'}, + 'items': [{'mode': 'file', 'grade': 100, 'billed_metres': '1', 'unit_cents': 1490, 'uploads': []}], + 'freight': {'service': 'pickup'}, 'total_cents': 1490, 'proof': True} + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) + VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (asked, owner, uuid4(), Jsonb(content), Jsonb(content))) + quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (asked,)).fetchone() + order, created = payments.create_order(c, quote, {'provider': 'teste', 'id': f'proof-{tag}'}) + made.append((asked, order['id'])) + assert created and order['contact_since'] and order['contact_note'] == proof.CUSTOMER_NOTE, order + # Their own password: the current one is asked for. seller.call('/operator/me/password', {'current': 'errada', 'new': 'outra-senha-de-teste'}, expected=403) # Eight characters or more. diff --git a/web/checkout.js b/web/checkout.js index 40b753f..18bfa41 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -324,6 +324,8 @@ const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}}; const destination = destinoApi(); if (destination) content.destination = destination; + // "Quero aprovar uma prova antes de imprimir": the order waits for the customer. + if ($('fProva')?.checked) content.proof = true; if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.'); const serialized = JSON.stringify(content); if (!requestKey || serialized !== requestBody) { diff --git a/web/index.html b/web/index.html index 632de58..a1b3767 100644 --- a/web/index.html +++ b/web/index.html @@ -1078,6 +1078,14 @@ h2 em{font-style:normal;color:var(--laranja)} + +
+

Prova antes de imprimir

+ +