feat: "Arte tratada" flags the orders whose final the team prepared, counted in Números
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 58s

Dropstar's internal rules (2026-10-26) asked how to tell art that arrived
ready from art the designer had to fix, and Marcus agreed on 2026-10-27 to
mark it automatically, for the designer's productivity.

- an order whose approved final is not the customer's art (not the file the
  system generated from it, not one of their originals, not a correction
  they sent) shows "Arte tratada" on its card and in the order, with who
  approved it
- Números counts the period's treated orders, the share of all orders, and
  how many each person approved
- the Kanban's cancel text: the money stays as the customer's credit, in
  Dropstar's financial control (rule D-15), no longer a refund
- Números' machine table shows the orders waiting in Arte conferida again;
  it still looked for the old print queue

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-27 10:01:35 -03:00
parent f77de40b7f
commit 35e64d77d7
6 changed files with 72 additions and 4 deletions

View File

@@ -175,6 +175,15 @@ def company_names(c, *groups):
# An item's final counts while its file is still there and scanned clean: the
# same rule that lets an order into the print queue.
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the
# customer's own artwork. It is neither the file the system generated from
# their art, nor one of their originals, nor a correction they sent. `f` is
# the final in dtf_local.order_files, `o` its order.
TREATED = """f.kind='final'
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
AND k.kind='correction')"""
def assign_machines(c, orders):
@@ -211,6 +220,10 @@ def with_print_files(c, orders):
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
# The items whose approved final someone prepared, and who approved it.
treated = c.execute(f'''SELECT f.order_id,f.item_index,f.created_by FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id WHERE f.order_id=ANY(%s) AND f.active AND {TREATED}
ORDER BY f.item_index''', (ids,)).fetchall()
# 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()}
@@ -218,6 +231,8 @@ def with_print_files(c, orders):
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']]
order['final_items'] = sorted(row['item_index'] for row in finals if row['order_id'] == order['id'])
mine = [row for row in treated if row['order_id'] == order['id']]
order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
for row in fixes if row['order_id'] == order['id']]
return assign_machines(c, orders)
@@ -843,6 +858,15 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
o.created_at))) / 3600 AS oldest_hours
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
printed = machine_output(c, start, end)
# Arte tratada, for the designer's productivity: orders of the period
# whose final someone prepared, by who approved it (any version).
treated = c.execute(f'''SELECT COALESCE(op.name, f.created_by) AS who, count(DISTINCT f.order_id) AS orders
FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id
LEFT JOIN dtf_local.operators op ON op.email=f.created_by
WHERE {REAL_ORDER} AND {within} AND {TREATED} GROUP BY 1 ORDER BY 2 DESC, 1''', period).fetchall()
treated_orders = c.execute(f'''SELECT count(DISTINCT f.order_id) AS n FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id WHERE {REAL_ORDER} AND {within} AND {TREATED}''',
period).fetchone()['n']
series = []
for offset in range((end - start).days + 1):
day = start + timedelta(days=offset)
@@ -853,6 +877,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(),
'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
'corrected': total['corrected'], 'daily': series,
'treated': {'orders': treated_orders, 'by': [{'who': row['who'], 'orders': row['orders']} for row in treated]},
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
'median_hours': hours(row['median_hours'])} for row in stages},

View File

@@ -437,8 +437,21 @@ Still to do (2026-10-26):
- 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 internal rules document (D-16 to D-23). Settled
on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py),
- Done 2026-10-27, from Dropstar's answers on their internal rules: "Arte
tratada", an order whose approved final is not the customer's art (not the
file generated from it, not an original, not a correction they sent), is
flagged on the card and in the order, and Números counts those orders by who
approved the final, for the designer's productivity; a cancelled order's
money stays as the customer's credit in their financial control (D-15, the
Kanban's cancel text says so, nothing on the Site); the Kanban keeps
deleting Finalizado files after 30 days; the footer gets the white spot.
- Still open from the internal rules (docs received 2026-10-26): file type by
its first bytes (D-13), every order's origin and a manual order entry in
the Kanban (D-21, D-35; also how orders paid with credit come in), the
rework register (D-02 to D-04), Aguardando contato time out of the time
figures (D-38), and the folders fetching what passed while the Kanban
computer was off.
- Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py),
the white spot also under the print PDF's footer (nothing to change here),
and the montador's order format (customer, files, product, the batch with
the customer's ERP sale numbers, labels or pickup) with a record of each

View File

@@ -110,6 +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']
# The file the system generated from the customer's art is not "Arte tratada".
board = client.call('/operator/board', operator=True)['orders']
assert next(o for o in board if o['id'] == oid)['treated'] is None
# Arte conferida is the print queue (2026-10-23).
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
version += 1

View File

@@ -1,4 +1,5 @@
"""Customer identity, correction and final-file trust boundaries against local stack."""
import os
from uuid import uuid4
from urllib.request import urlopen
from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register
@@ -57,6 +58,10 @@ def run():
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
customer.call('/operator/orders/'+oid+'/final-files',body,expected=401)
version=customer.call('/operator/orders/'+oid+'/final-files',body,operator=True)['version']
# A final the team uploaded is not the customer's art: "Arte tratada" (2026-10-27).
treated=lambda:next(o for o in customer.call('/operator/board',operator=True)['orders'] if o['id']==oid)['treated']
operator_email=os.environ.get('OPERATOR_EMAIL','operator@example.test')
assert treated()=={'items':[0],'by':operator_email}, treated()
detail=customer.call('/customer/orders/'+oid)
final=detail['files'][0]
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
@@ -87,9 +92,14 @@ def run():
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)
assert any(f['kind']=='final' and f['active'] and f['upload_id']==correction_id for f in files)
# The customer's own correction approved as it is: not treated.
assert treated() is None, treated()
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']
assert treated()=={'items':[0],'by':operator_email}, treated()
stats=customer.call('/operator/stats?days=7',operator=True)['treated']
assert stats['orders']>=1 and any(t['orders']>=1 for t in stats['by']), stats
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)

View File

@@ -94,6 +94,9 @@
Metros por hora: sobre o tempo em Imprimindo; pedidos imprimindo juntos na mesma máquina contam esse tempo uma vez.</p>
<table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Impresso</th><th scope="col">Metros por hora</th><th scope="col">Último finalizado</th><th scope="col">Agora</th></tr></thead><tbody id="stats-machines"></tbody></table>
</section>
<section class="statbox"><h2>Artes tratadas</h2>
<p class="faint stats-hint">Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou. Por quem aprovou o arquivo.</p>
<table class="log"><thead><tr><th scope="col">Quem aprovou</th><th scope="col">Pedidos</th></tr></thead><tbody id="stats-treated"></tbody></table></section>
<section class="statbox"><h2>Tempo em cada etapa</h2>
<p class="faint stats-hint">Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem.</p>
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>

View File

@@ -577,6 +577,7 @@ 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 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);
const MIRROR_NOTE='O cliente espelhou a arte: confira antes de imprimir';
@@ -737,6 +738,8 @@ function card(order){
? 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: prova antes do resto'));
}
// Arte tratada (Dropstar, 2026-10-27): the final is not the customer's art, someone prepared it.
if(!order.cancelled_at&&order.treated)flags.append(badge('Arte tratada','info',TREATED_NOTE+' Aprovado por '+order.treated.by+'.'));
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);}
if(flags.children.length)c.append(flags);
@@ -987,7 +990,7 @@ function moves(order){
b.onclick=()=>{menu.hidden=true;toggle(cancelForm);};menu.append(b);
const why=node('input');why.placeholder='Motivo do cancelamento';why.setAttribute('aria-label','Motivo do cancelamento');why.required=true;why.minLength=3;why.maxLength=1000;
const go=node('button','Cancelar pedido #'+order.number,'btn danger');
cancelForm.append(node('span','O pedido sai do quadro e fica em "Cancelados", com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago, e o pedido no Tiny se cancela lá.','muted'),why,go);
cancelForm.append(node('span','O pedido sai do quadro e fica em "Cancelados", com o pagamento e o histórico. O valor fica como crédito do cliente, no controle financeiro, e o pedido no Tiny se cancela lá.','muted'),why,go);
cancelForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;
try{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}
catch(error){say(error.message,true);go.disabled=false;}};
@@ -1144,6 +1147,11 @@ function itemCard(order,item,index){
status.append(icon(done?ICON_OK:ICON_WARN),node('span',done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn'));
body.append(status);
}
if(order.treated?.items.includes(index)){
const treated=node('div',undefined,'file');
treated.append(icon(ICON_OK),node('span','Arte tratada: '+TREATED_NOTE.charAt(0).toLowerCase()+TREATED_NOTE.slice(1)+' Aprovado por '+order.treated.by+'.'));
body.append(treated);
}
const buttons=node('div',undefined,'buttons');
if(fix&&!fix.expired)buttons.append(downloadButton('Correção',download(fix.upload_id)));
else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
@@ -1385,11 +1393,12 @@ async function loadStats(){
kpi('Recebido',money(data.cents),'com frete'),
kpi('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'),
kpi('Pedidos com correção',String(data.corrected),data.orders?pct+'% dos pedidos':null),
kpi('Artes tratadas',String(data.treated.orders),data.orders?Math.round(100*data.treated.orders/data.orders)+'% dos pedidos':null),
kpi('Do pagamento ao Finalizado',duration(data.lead.median_hours),data.lead.orders?'mediana de '+data.lead.orders+' pedidos':'nenhum finalizado'));
statsChart($('stats-chart'),data.daily);
const machineRows=data.machines.map(m=>{
const tr=node('tr');if(!m.active)tr.classList.add('off');
const now=[m.now.imp?m.now.imp+' imprimindo':'',m.now.fil?m.now.fil+' na fila':''].filter(Boolean).join(' · ');
const now=[m.now.imp?m.now.imp+' imprimindo':'',m.now.tra?m.now.tra+' na fila':''].filter(Boolean).join(' · ');
tr.append(node('td',m.name+(m.active?'':' · desativada')),
node('td',m.orders?metres(m.metres)+' · '+m.orders+(m.orders>1?' pedidos':' pedido'):'nada'),
node('td',m.metres_per_hour!=null?String(m.metres_per_hour).replace('.',',')+' m/h':'—'),
@@ -1398,6 +1407,11 @@ async function loadStats(){
return tr;});
if(!machineRows.length){const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada.','faint');td.colSpan=5;tr.append(td);machineRows.push(tr);}
$('stats-machines').replaceChildren(...machineRows);
// Who prepared the finals of the period's orders, for the designer's productivity.
const treatedRows=data.treated.by.map(t=>{const tr=node('tr');
tr.append(node('td',t.who),node('td',t.orders+(t.orders>1?' pedidos':' pedido')));return tr;});
if(!treatedRows.length){const tr=node('tr');const td=node('td','Nenhuma arte tratada no período.','faint');td.colSpan=2;tr.append(td);treatedRows.push(tr);}
$('stats-treated').replaceChildren(...treatedRows);
const rows=['rec','tra','imp','cor','rev'].map(state=>{
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
name.append(sw,board.states[state]);