fix: Números measures what Dropstar asked: machines by film printed, stages by order
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m7s

- a machine's metres are the film printed, not the metres billed, which round
  up to one metre and made small orders look like fast printing
- orders in Imprimindo together on one machine count that time once
- a stage's median time is per order, the sum of its passages, so rework
  reads as one slow order instead of quick passages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-22 15:25:08 -03:00
parent 80975b9424
commit 3ae453f47a
5 changed files with 80 additions and 19 deletions

View File

@@ -809,10 +809,14 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
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 {within})
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
# Orders, not passages: an order sent back counts once, its passages apart.
stages = c.execute(f'''SELECT state, count(DISTINCT id) AS orders, count(*) AS passages,
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''', period + period).fetchall()
# Orders, not passages: an order sent back counts once, its passages apart,
# and its time in a stage is the sum of its passages. Otherwise an order
# that came back twice reads as three quick passages, not one slow order.
stages = c.execute(f'''SELECT state, count(*) AS orders, sum(passages)::int AS passages,
percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) / 3600 AS median_hours
FROM (SELECT id, state, count(*) AS passages, sum(extract(epoch FROM until-at)) AS seconds
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY id, state) per_order
GROUP BY state''', period + period).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
@@ -845,8 +849,14 @@ def machine_output(c, start, end):
"""What each machine printed in the period: the orders that reached
Finalizado then, on the machine they were on, their metres, the hours they
spent in Imprimindo (so metres per hour is the machine's real pace, as the
room moves the cards), when it last finished one, and what it has now."""
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
room moves the cards), when it last finished one, and what it has now.
The metres are the film printed, not the metres billed: billing rounds up
to 10 cm and to one metre at least, and a 0,40 m order printed as 1 m would
make the machine look faster than it is. Orders in Imprimindo on the same
machine at the same time share that time: it counts once."""
metres = ("(SELECT COALESCE(sum(COALESCE(i->>'metres', i->>'billed_metres')::numeric),0)"
" FROM jsonb_array_elements(o.snapshot->'items') i)")
done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at
FROM dtf_local.orders o
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
@@ -854,19 +864,20 @@ def machine_output(c, start, end):
WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
(start, end)).fetchall()
ids = [row['id'] for row in done]
printing = {row['id']: float(row['hours']) for row in c.execute('''WITH events AS (
printing = {}
for row in c.execute('''WITH events AS (
SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m
WHERE m.order_id=ANY(%s)),
spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events)
SELECT id, sum(extract(epoch FROM until-at)) / 3600 AS hours FROM spans
WHERE state='imp' AND until IS NOT NULL GROUP BY id''', (ids,)).fetchall()} if ids else {}
SELECT id, at, until FROM spans WHERE state='imp' AND until IS NOT NULL''', (ids,)).fetchall() if ids else []:
printing.setdefault(row['id'], []).append((row['at'], row['until']))
last = {str(row['machine_id']): row['at'] for row in c.execute(f'''SELECT o.machine_id, max(m.created_at) AS at
FROM dtf_local.orders o JOIN dtf_local.movements m ON m.order_id=o.id AND m.to_state='fin'
WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()}
result = []
for m in machines.rows(c):
mine = [row for row in done if str(row['machine_id'] or '') == m['id']]
hours_in = sum(printing.get(row['id'], 0.0) for row in mine)
hours_in = busy_hours([span for row in mine for span in printing.get(row['id'], [])])
made = float(sum(row['metres'] for row in mine))
result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine),
'metres': made, 'printing_hours': round(hours_in, 2),
@@ -881,6 +892,19 @@ def machine_output(c, start, end):
return result
def busy_hours(spans):
"""The hours the spans (start, end) cover, time shared by several counted once."""
seconds, reached = 0.0, None
for at, until in sorted(spans):
if reached is None or at >= reached:
seconds += (until - at).total_seconds()
reached = until
elif until > reached:
seconds += (until - reached).total_seconds()
reached = until
return seconds / 3600
def named_files(rows):
"""Each file named after its order and item, so a folder of them stays
readable, with a link straight to storage."""