feat: the print proof: Prova OK before Finalizado, and a proof the customer can ask for
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 56s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped

Dropstar's items 15 and 16 (2026-10-21).

- an order above 10 m prints 20 cm of proof first; the room checks it and
  marks "Prova OK", without stopping the order, and without that mark the
  order cannot reach Finalizado
- at checkout, "Quero aprovar uma prova antes de imprimir", for any length:
  the paid order arrives marked "Aguardando contato" with what to do, and
  waits for the customer's word on the photo sent by WhatsApp
- the card shows Prova / Prova OK, the panel gives the next step, and
  "Prova a conferir" is a board filter; the designer cannot mark it
- the proof is not billed, as Dropstar leans; rounds and which part of the
  sheet wait for their answer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-22 17:21:26 -03:00
parent f6bdbe006e
commit 1dc8cf1efb
12 changed files with 132 additions and 4 deletions

View File

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

View File

@@ -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):

View File

@@ -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

23
app/proof.py Normal file
View File

@@ -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

View File

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

View File

@@ -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;

View File

@@ -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-<Kanban number> · 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.

View File

@@ -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.

View File

@@ -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) {

View File

@@ -1078,6 +1078,14 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
</div>
</div>
<div class="cxE">
<h4>Prova antes de imprimir</h4>
<label class="provaOp"><input type="checkbox" id="fProva">
<span><b>Quero aprovar uma prova antes de imprimir</b>
Imprimimos um trecho da sua folha e mandamos a foto pelo WhatsApp. O resto só é impresso
depois do seu ok, então o pedido espera a sua resposta.</span></label>
</div>
</div>
<aside class="resumo">

View File

@@ -558,6 +558,14 @@ const stalled=order=>['rec','tra','fil','imp'].includes(order.state)&&Date.now()
// A mark on the card, not a stage; a finished order no longer needs it.
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
// The room marks "Prova OK" once it is checked; without it, no Finalizado.
const PROOF_ABOVE_METRES=10;
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;
async function proofOk(order){
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
}
// The board's filters: one choice per kind, and the kinds combine (Têxtil on
// máquina2, waiting for contact). An empty choice is "all".
const FILTER_TESTS={
@@ -567,6 +575,7 @@ const FILTER_TESTS={
retirada:o=>!o.snapshot.destination,
parados:stalled,
contato:waitingContact,
prova:proofPending,
manual:o=>['rec','tra'].includes(o.state)&&!finalDone(o)&&(o.print_files||[]).some(r=>
(r.status==='manual'||r.status==='failed')&&!(o.corrections||[]).some(f=>f.item_index===r.item_index)),
};
@@ -584,7 +593,7 @@ function filterKinds(){
{key:'product',label:'Produto',all:'Todos',options:[['textil','Têxtil'],['uv','UV']]},
{key:'delivery',label:'Envio',all:'Entrega e retirada',options:[['entrega','Entrega'],['retirada','Retirada']]},
{key:'status',label:'Situação',all:'Todos',options:[['parados','Parados há mais de '+LATE_HOURS+' h','Parados'],
['contato','Aguardando contato'],['manual','Preparar à mão'],['cancelados','Cancelados']]}];
['contato','Aguardando contato'],['prova','Prova a conferir'],['manual','Preparar à mão'],['cancelados','Cancelados']]}];
// A machine, when there is more than one to tell apart.
const machines=(board.machines||[]).filter(m=>m.active||m.open_orders);
if(machines.length>1)kinds.splice(1,0,{key:'machine',label:'Máquina',all:'Todas',options:machines.map(m=>
@@ -705,6 +714,9 @@ function card(order){
if(s.items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva','warn','O cliente aceitou a ressalva de resolução'));
if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
if(waitingContact(order))flags.append(badge('☎ Aguardando contato','warn',order.contact_note+' · '+contactWho(order)));
if(needsProof(order))flags.append(order.proof_ok_at
? badge('✓ Prova OK','ok','Conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at))
: badge('Prova','warn',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: 20 cm de prova antes do resto'));
}
c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination));
if(order.machine&&order.state!=='fin'){const m=node('div',undefined,'place machine');m.append(icon(ICON_PRINTER),order.machine.name);c.append(m);}
@@ -889,6 +901,15 @@ function moves(order){
upload.append(cancel);sync=()=>{actions.hidden=!upload.hidden;};
text.append(actions,upload);
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
}else if(next==='fin'&&proofPending(order)){
// Finalizado waits for the proof: printing it and checking it is the next step.
const text=node('div');text.append(node('b','Próximo passo: conferir a prova'),
node('span',order.snapshot.proof
?'O cliente pediu uma prova: mande a foto pelo WhatsApp e, com o aceite dele, marque Prova OK.'
:'Pedido acima de 10 m: imprima 20 cm, confira e marque Prova OK antes de rodar o resto.'));
if(may('print')){const actions=node('div',undefined,'stepactions');
const b=button('Prova OK',()=>proofOk(order),'btn primary');b.dataset.proof='';actions.append(b);text.append(actions);}
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
}else if(mayMove(order.state,next)){
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
}
@@ -906,6 +927,10 @@ function moves(order){
backForm.append(why,go);
backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}};
}
// The proof may be checked before Imprimindo, while the order waits in the queue.
if(order.state==='fil'&&proofPending(order)&&may('print')){
const b=button('✓ Prova OK',()=>proofOk(order),'linkbtn');b.title='A prova foi impressa e conferida';sub.append(b);
}
// Waiting for a word with the customer: shown on top with "Contato feito";
// otherwise marked from here, with what has to be agreed.
const contactForm=node('form',undefined,'reason');contactForm.hidden=true;forms.push(contactForm);

View File

@@ -323,6 +323,9 @@ section+section{border-top:0}
.carr h3{font-size:24px;font-weight:800;letter-spacing:-.02em}
.cxE{border-radius:var(--raio);border-color:var(--linha)}
.cxE h4,.resumo h4{font-family:"Inter",sans-serif;font-weight:800;font-size:18px}
.provaOp{display:flex;gap:10px;align-items:flex-start;cursor:pointer;font-size:15px;line-height:1.5;color:var(--fraco)}
.provaOp input{margin-top:3px;width:17px;height:17px;flex:none;accent-color:var(--laranja)}
.provaOp b{display:block;color:var(--preto);font-weight:700}
.cp input,.cepL input{height:46px;border-radius:var(--raio2)}
.cp input:focus,.cepL input:focus{border-color:var(--laranja2);box-shadow:0 0 0 3px rgba(255,168,26,.18)}
.opE{border-radius:12px}