feat: every order is born with its origin, shown, filtered and counted (Dropstar's rules D-21 and D-35)
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m21s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m1s

Orders carry site, dropflow or atendimento, required and with no default,
limited to the three. The Site's orders are marked site where they are
created; older orders became site. The Kanban shows the origin on each card
and in the order panel, filters by it, and Numeros has a Por origem table:
orders, metres, money and time from payment to Finalizado per way in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-27 11:39:08 -03:00
parent bba55a83f3
commit 0319039328
13 changed files with 98 additions and 19 deletions

View File

@@ -795,6 +795,8 @@ def thumbnail(uid: UUID, user=Depends(operator)):
# 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'"
# 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"
@@ -881,6 +883,16 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
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']
# Each way in apart (D-21): what came from where, and how long it took
# from payment to Finalizado, Aguardando contato left out as above.
origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders,
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres,
count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours
FROM dtf_local.orders o
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
series = []
for offset in range((end - start).days + 1):
day = start + timedelta(days=offset)
@@ -892,6 +904,12 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
'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]},
'origins': [{'origin': name, 'orders': origins[name]['orders'] if name in origins else 0,
'cents': int(origins[name]['cents']) if name in origins else 0,
'metres': float(origins[name]['metres']) if name in origins else 0.0,
'finished': origins[name]['finished'] if name in origins else 0,
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
for name in ORIGINS],
'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

@@ -92,7 +92,8 @@ def create_order(c, quote, payment):
require_clean(upload_row(c, UUID(upload_id), quote['owner']))
order = c.execute(
'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *',
'''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site') RETURNING *''',
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone()
# Paid: the files are kept for the order's retention, counted from upload.
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)

View File

@@ -372,3 +372,14 @@ CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_
INSERT INTO dtf_local.contact_waits(order_id, started_at)
SELECT o.id, o.contact_since FROM dtf_local.orders o
WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contact_waits w WHERE w.order_id=o.id);
-- Every card is born with its origin (Dropstar's rules D-21 and D-35,
-- 2026-10-26): site, dropflow (the montador's batches) or atendimento (an
-- order the team enters). No order without one, and no default: a default
-- would become the origin of almost everything, so each way in names its own.
-- The orders from before this column all came from the Site.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));

View File

@@ -462,9 +462,24 @@ Still to do (2026-10-26):
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): every
order's origin and a manual order entry in the Kanban (D-21, D-35; also how
orders paid with credit come in), and the rework register (D-02 to D-04).
- Every order has an origin (Dropstar's rules D-21 and D-35, 2026-10-26):
`site`, `dropflow` or `atendimento`, in dtf_local.orders.origin, required
and without a default (a default would become the origin of almost
everything, the document says), limited to the three by a check. The Site's
orders are marked `site` where they are created (app/payments.py); the
orders from before the column became `site`. The Kanban shows it on every
card and in the order panel, filters by it (Origem), and Números has a "Por
origem" table: orders, metres, money received and the median time from
payment to Finalizado for each way in, Aguardando contato left out.
- Still open from the internal rules (docs received 2026-10-26): the manual
order entry in the Kanban, where the origin must be chosen (D-35; also how
orders paid with credit come in, and the Dropflow batches until their API),
the Tiny revenue category for Dropflow orders (not DTF SITE; its name and
the origin value must be the same word, the document says), and the rework
register (D-02 to D-04: four causes, falha de impressão, perfil de cor,
erro de tratamento and erro de pedido; opened and classified by Mayana,
authorized by Thales or Alexandre, locked once opened; bad art the customer
approved does not count; goal 0,4% per cause, 1,6% in all).
Done 2026-10-27: the folders catch up on what passed while the Kanban
computer was off, time in "Aguardando contato" no longer counts in Números'
time figures (D-38; each wait is kept in dtf_local.contact_waits, from mark

View File

@@ -11,6 +11,7 @@ from urllib.request import Request
from uuid import uuid4
import httpx
import psycopg
from psycopg.types.json import Jsonb
from app.core import db
@@ -81,8 +82,8 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved)
VALUES(%s,%s,%s,%s,%s,%s)''', (qid, owner, uuid4(), 'kanban-fixture', Jsonb(content),
Jsonb(accepted) if accepted else None))
number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment)
VALUES(%s,%s,%s,%s,%s) RETURNING number''',
number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''',
(order_id, paid, owner, Jsonb({**draft(item('file')), 'total_cents': 1490}),
Jsonb({'provider': 'teste', 'id': f'kanban-{tag}'}))).fetchone()['number']
@@ -126,6 +127,20 @@ def run():
assert (after['orders'], after['cents']) == (before['orders'] + 1, before['cents'] + 1490), (before, after)
assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1
assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1
# Each way in apart (D-21), all three listed even when empty.
assert [o['origin'] for o in after['origins']] == ['site', 'dropflow', 'atendimento']
site = lambda stats: next(o for o in stats['origins'] if o['origin'] == 'site')
assert (site(after)['orders'], site(after)['cents']) == (site(before)['orders'] + 1, site(before)['cents'] + 1490)
# No order without an origin, and only the three (D-21, D-35).
for origin in (None, 'whatsapp'):
try:
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,'{}','{}',%s)''', (uuid4(), approved, owner, origin))
except (psycopg.errors.NotNullViolation, psycopg.errors.CheckViolation):
pass
else:
raise AssertionError(f'an order with origin {origin!r} was accepted')
client.call('/operator/stats?days=3', operator=True, expected=422)
# Or two dates: the same week asked as a range gives the same numbers.
week = client.call(f"/operator/stats?start={after['start']}&end={after['end']}", operator=True)

View File

@@ -17,7 +17,7 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
(order, quote, owner, Jsonb({'items': [], 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
live = c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''',
@@ -52,8 +52,8 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment)
VALUES(%s,%s,%s,%s,%s) RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
Jsonb({'provider': 'teste'}))).fetchone()['number']
assert first == 1, first
c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,))

View File

@@ -27,7 +27,7 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''',
(qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved)))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)''',
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')''',
(paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'})))
listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}),
operator=True)['quotes']}
@@ -94,8 +94,8 @@ def run():
# Dragged within its column: first paid first, unless moved; moving on resets it.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at)
VALUES(%s,%s,%s,%s,%s,now())''', (newer_order, newer_quote, owner, Jsonb(approved),
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at,origin)
VALUES(%s,%s,%s,%s,%s,now(),'site')''', (newer_order, newer_quote, owner, Jsonb(approved),
Jsonb({'provider': 'teste', 'id': 't'})))
client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True)
with db.connect() as c:
@@ -129,8 +129,8 @@ def run():
'total_cents': 1490}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}),
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason,origin)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,'site')''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}),
'now()' if cancelled else None, 'x' if cancelled else None,
'teste' if cancelled else None))
place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True)

View File

@@ -44,7 +44,7 @@ def run():
items = [{'mode': 'file', 'uploads': [str(image), str(drawing)]}]
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
VALUES(%s,%s,%s,'backfill-fixture',%s)''', (quote, owner, uuid4(), Jsonb({'items': items})))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
(order, quote, owner, Jsonb({'items': items, 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
lines = []
assert backfill_thumbnails.main([], out=lines.append, storage=storage) == 0

View File

@@ -34,7 +34,7 @@ def order_fixture(c, owner, mode, metres='1', printed=None):
'items': [item], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
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())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
(order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': str(order)})))
return quote, order

View File

@@ -12,6 +12,8 @@ def run():
q=customer.call('/quotes',{'request_key':str(uuid4()),'customer':profile,'items':[item],'freight':{'service':'pickup'}})
approved_quote(customer,q,[item])
order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id']
# A Site order is born marked as one (Dropstar's rule D-21).
assert next(o for o in customer.call('/operator/board',operator=True)['orders'] if o['id']==oid)['origin']=='site'
before=list(customer.jar)[0].value
password='local-test-password-'+uuid4().hex
register(customer,profile,password)

View File

@@ -129,6 +129,7 @@ main{padding:0 24px 24px}
.card .num{font-size:14.5px;font-weight:800}
.card .age{margin-left:auto;font-size:13.5px;color:var(--faint)}
.card .cust{font-size:14px;font-weight:600;color:var(--tx);width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.origin{font-size:12px;font-weight:700;padding:1px 7px;border-radius:6px;border:1px solid var(--line3);color:var(--muted)}
.tag-teste{font-size:12.5px;font-weight:800;letter-spacing:.04em;padding:2px 7px;border-radius:6px;background:var(--warn);color:#1a1300}
.late{font-size:13.5px;color:#F06A5B;font-weight:600}

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>Por origem</h2>
<p class="faint stats-hint">Por onde o pedido entrou: o Site, os lotes do Dropflow ou a equipe, em Atendimento. O tempo vai do pagamento ao Finalizado, sem o tempo em Aguardando contato.</p>
<table class="log"><thead><tr><th scope="col">Origem</th><th scope="col">Pedidos</th><th scope="col">Metros</th><th scope="col">Recebido</th><th scope="col">Do pagamento ao Finalizado</th></tr></thead><tbody id="stats-origins"></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>

View File

@@ -33,7 +33,7 @@ function outcomeText(outcome){
let board=null;
let tab='board', openOrder=null, openToken=0;
const boardFilter={product:'',machine:'',delivery:'',status:''};
const boardFilter={product:'',machine:'',delivery:'',origin:'',status:''};
// Layout versions the server takes (app/core/models.py PRODUCTION_VERSIONS).
const LAYOUT_VERSIONS=[2,3];
let quoteKind='pending', pickedQuote=null;
@@ -598,7 +598,14 @@ async function proofOk(order){
}
// 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".
// Where an order came from (Dropstar's rule D-21): every card says it.
const ORIGINS={site:'Site',dropflow:'Dropflow',atendimento:'Atendimento'};
const ORIGIN_NOTE='Origem do pedido';
const originTag=order=>{const t=node('span',ORIGINS[order.origin]||order.origin,'origin');t.title=ORIGIN_NOTE;return t;};
const FILTER_TESTS={
site:o=>o.origin==='site',
dropflow:o=>o.origin==='dropflow',
atendimento:o=>o.origin==='atendimento',
textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'),
uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'),
entrega:o=>!!o.snapshot.destination,
@@ -622,6 +629,7 @@ function filterKinds(){
const kinds=[
{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:'origin',label:'Origem',all:'Todas',options:Object.entries(ORIGINS)},
{key:'status',label:'Situação',all:'Todos',options:[['parados','Parados há mais de '+LATE_HOURS+' h','Parados'],
['contato','Aguardando contato'],['prova','Prova a conferir'],['manual','Preparar à mão'],['cancelados','Cancelados']]}];
// A machine, when there is more than one to tell apart.
@@ -732,7 +740,7 @@ function card(order){
if(order.id===openOrder)c.classList.add('open');
const s=order.snapshot;
const top=node('div',undefined,'row');
top.append(node('span','#'+order.number,'num'),...(isTest(order)?[node('span','TESTE','tag-teste')]:[]),node('span',ago(order.updated_at),'age'));
top.append(node('span','#'+order.number,'num'),originTag(order),...(isTest(order)?[node('span','TESTE','tag-teste')]:[]),node('span',ago(order.updated_at),'age'));
const meta=node('div',undefined,'meta');
meta.append(gradePill(lowestGrade(s.items)),productBadge(s.items),
node('b',metres(s.items.reduce((t,i)=>t+Number(i.billed_metres),0)),'mtr'));
@@ -844,7 +852,7 @@ function renderPanel(order){
code.append('Pedido DTF-'+order.number,copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
const theirs=node('span',' · cliente: '+orderCode(order.id),'faint');theirs.title='O código que o cliente vê';code.append(theirs);
code.title='O código que o cliente vê';
row.append(node('span','#'+order.number,'num'),stage,...(test?[test]:[]),code,close);
row.append(node('span','#'+order.number,'num'),stage,originTag(order),...(test?[test]:[]),code,close);
// What was paid and when, and whether it is stuck: the first things asked of an order.
const paid=node('div',undefined,'paidline');
paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at):' pago em '+when(order.created_at));
@@ -1424,6 +1432,11 @@ async function loadStats(){
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);
// Each way in apart (D-21): its orders, metres, money and time to Finalizado.
$('stats-origins').replaceChildren(...data.origins.map(o=>{const tr=node('tr');
tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders)),node('td',metres(o.metres)),node('td',money(o.cents)),
node('td',o.finished?duration(o.median_hours)+' · '+o.finished+(o.finished>1?' finalizados':' finalizado'):'—'));
if(!o.orders)tr.classList.add('off');return tr;}));
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]);