feat: a Números tab with the production numbers the board already records

Every paid order and every move is recorded, but nobody could see the
totals. The new tab shows, for the last 7, 30 or 90 days: paid orders,
metres sold, money received, the average ticket, how many orders needed a
correction, and the median time from payment to Finalizado. A column per
day charts the metres sold (with a table under it), and a table gives each
stage's median time and what waits in it now, with the oldest order.
Test and cancelled orders stay out.

The header now has five tabs: the search box narrows first, the refresh
picker keeps its width, and the operator's e-mail moves to Sair's tooltip
on narrower screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-05 12:01:03 -03:00
parent f567e6da89
commit 1b445f0459
5 changed files with 183 additions and 10 deletions

View File

@@ -624,6 +624,63 @@ def thumbnail(uid: UUID, user=Depends(operator)):
return Response(bytes(row['data']), media_type=row['mime'],
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'"
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
@router.get('/api/operator/stats')
def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(operator)):
"""Production numbers from what the board already records: orders paid in
the period, how long each stage holds an order, and what is waiting now."""
# From the start of the first local day of the period.
since = ("o.created_at >= (((now() AT TIME ZONE 'America/Sao_Paulo')::date - make_interval(days => %s - 1))"
" AT TIME ZONE 'America/Sao_Paulo')")
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
with db.connect() as c:
total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents,
COALESCE(sum({metres}),0) AS metres,
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
AND m.to_state='cor' AND NOT m.back)) AS corrected
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone()
daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders,
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}
GROUP BY 1''', (days,)).fetchall()}
# Each order's stages as spans: from entering a stage to the next move.
spans = f'''WITH events AS (
SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}
UNION ALL
SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {since})
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
stages = c.execute(f'''SELECT state, count(*) AS orders,
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM until-at)) / 3600 AS median_hours
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', (days, days)).fetchall()
lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
f.at - o.created_at)) / 3600 AS median_hours FROM dtf_local.orders o
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 f.at IS NOT NULL
WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone()
# What waits now, however old, and since when in its stage.
waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE(
(SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state),
o.created_at))) / 3600 AS oldest_hours
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
today = datetime.now(timezone(timedelta(hours=-3))).date()
series = []
for offset in range(days - 1, -1, -1):
day = today - timedelta(days=offset)
row = daily.get(day)
series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0,
'metres': float(row['metres']) if row else 0.0})
hours = lambda value: round(float(value), 1) if value is not None else None
return {'days': days, 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
'corrected': total['corrected'], 'daily': series,
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
'stages': {row['state']: {'orders': row['orders'], 'median_hours': hours(row['median_hours'])} for row in stages},
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}}
@router.get('/api/operator/queue/finals')
def queue_finals(user=Depends(operator)):
"""The approved final files of every order in the print queue, in queue