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
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:
@@ -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
|
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})
|
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'''
|
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.
|
# 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,
|
# and its time in a stage is the sum of its passages. Otherwise an order
|
||||||
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM until-at)) / 3600 AS median_hours
|
# that came back twice reads as three quick passages, not one slow order.
|
||||||
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', period + period).fetchall()
|
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
|
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
|
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
|
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
|
"""What each machine printed in the period: the orders that reached
|
||||||
Finalizado then, on the machine they were on, their metres, the hours they
|
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
|
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."""
|
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)"
|
|
||||||
|
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
|
done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at
|
||||||
FROM dtf_local.orders o
|
FROM dtf_local.orders o
|
||||||
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
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''',
|
WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
|
||||||
(start, end)).fetchall()
|
(start, end)).fetchall()
|
||||||
ids = [row['id'] for row in done]
|
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
|
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)),
|
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)
|
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
|
SELECT id, at, until FROM spans WHERE state='imp' AND until IS NOT NULL''', (ids,)).fetchall() if ids else []:
|
||||||
WHERE state='imp' AND until IS NOT NULL GROUP BY id''', (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
|
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'
|
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()}
|
WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()}
|
||||||
result = []
|
result = []
|
||||||
for m in machines.rows(c):
|
for m in machines.rows(c):
|
||||||
mine = [row for row in done if str(row['machine_id'] or '') == m['id']]
|
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))
|
made = float(sum(row['metres'] for row in mine))
|
||||||
result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine),
|
result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine),
|
||||||
'metres': made, 'printing_hours': round(hours_in, 2),
|
'metres': made, 'printing_hours': round(hours_in, 2),
|
||||||
@@ -881,6 +892,19 @@ def machine_output(c, start, end):
|
|||||||
return result
|
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):
|
def named_files(rows):
|
||||||
"""Each file named after its order and item, so a folder of them stays
|
"""Each file named after its order and item, so a folder of them stays
|
||||||
readable, with a link straight to storage."""
|
readable, with a link straight to storage."""
|
||||||
|
|||||||
@@ -343,7 +343,10 @@ up to 1 GB (MAX_UPLOAD_BYTES, scanned whole by ClamAV); a Designer profile
|
|||||||
(artwork stages only, every order, no machine, queue or cancelling;
|
(artwork stages only, every order, no machine, queue or cancelling;
|
||||||
DESIGNER_STATES in app/core/auth.py, the "print" capability for the room's
|
DESIGNER_STATES in app/core/auth.py, the "print" capability for the room's
|
||||||
side); Números by date range, per machine (metres finished, metres per hour
|
side); Números by date range, per machine (metres finished, metres per hour
|
||||||
in Imprimindo, last finished, now) and orders apart from passages. Waiting on
|
in Imprimindo, last finished, now) and orders apart from passages. A machine's
|
||||||
|
metres are the film printed (item `metres`), never the billed ones, and time
|
||||||
|
two orders spent in Imprimindo together counts once; a stage's median is per
|
||||||
|
order, the sum of its passages. Waiting on
|
||||||
Dropstar: the Tiny category/seller/tag conflict, residue and opaque background
|
Dropstar: the Tiny category/seller/tag conflict, residue and opaque background
|
||||||
blocking, the print-file footer, the packing margins, the DTF terms, the
|
blocking, the print-file footer, the packing margins, the DTF terms, the
|
||||||
manual-file value, the proof print, and mirroring.
|
manual-file value, the proof print, and mirroring.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ Run against the local stack: python3 -m tests.kanban_test
|
|||||||
"""
|
"""
|
||||||
import base64
|
import base64
|
||||||
import secrets
|
import secrets
|
||||||
|
from datetime import date, timedelta
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
from urllib.request import Request
|
from urllib.request import Request
|
||||||
@@ -144,6 +145,18 @@ def run():
|
|||||||
tra_before = after['stages'].get('tra', {'orders': 0, 'passages': 0})
|
tra_before = after['stages'].get('tra', {'orders': 0, 'passages': 0})
|
||||||
assert moved['stages']['tra']['orders'] == tra_before['orders'] + 1, moved['stages']
|
assert moved['stages']['tra']['orders'] == tra_before['orders'] + 1, moved['stages']
|
||||||
assert moved['stages']['tra']['passages'] == tra_before['passages'] + 2, moved['stages']
|
assert moved['stages']['tra']['passages'] == tra_before['passages'] + 2, moved['stages']
|
||||||
|
# Its time in a stage is the sum of its passages: on a day of its own, one
|
||||||
|
# hour in Arte conferida, a correction, and another hour there read as 2 h.
|
||||||
|
alone = (date(2001, 1, 1) + timedelta(days=int(tag, 16) % 3000)).isoformat()
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('UPDATE dtf_local.orders SET created_at=%s::timestamptz WHERE id=%s', (f'{alone} 08:00-03', order_id))
|
||||||
|
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
|
||||||
|
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'fil')), start=9):
|
||||||
|
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
|
VALUES(%s,%s,%s,'kanban-test','',false,%s::timestamptz)''', (order_id, frm, to, f'{alone} {hour}:00-03'))
|
||||||
|
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
|
||||||
|
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'median_hours': 2.0}, day['stages']
|
||||||
|
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
|
||||||
|
|
||||||
# The company's name from the registry: on the board, and found by the search.
|
# The company's name from the registry: on the board, and found by the search.
|
||||||
from app import cnpj as registry
|
from app import cnpj as registry
|
||||||
|
|||||||
@@ -22,12 +22,15 @@ def signed_in(email, password=PASSWORD):
|
|||||||
return client
|
return client
|
||||||
|
|
||||||
|
|
||||||
def order_fixture(c, owner, mode, metres='1'):
|
def order_fixture(c, owner, mode, metres='1', printed=None):
|
||||||
"""A paid order straight in the database, as the payment would leave it."""
|
"""A paid order straight in the database, as the payment would leave it:
|
||||||
|
`metres` billed, `printed` the film the sheet takes, when it differs."""
|
||||||
quote, order = uuid4(), uuid4()
|
quote, order = uuid4(), uuid4()
|
||||||
|
item = {'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': 1490, 'uploads': []}
|
||||||
|
if printed is not None:
|
||||||
|
item['metres'] = printed
|
||||||
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
|
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
|
||||||
'items': [{'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': 1490,
|
'items': [item], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
|
||||||
'uploads': []}], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
|
|
||||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
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)))
|
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) VALUES(%s,%s,%s,%s,%s)',
|
||||||
@@ -209,20 +212,36 @@ def run():
|
|||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
assert not board[second]['machine']['chosen']
|
assert not board[second]['machine']['chosen']
|
||||||
|
|
||||||
# Números per machine: an order printed for half an hour on its machine, then finished.
|
# Números per machine: an order printed for half an hour on its machine, then
|
||||||
|
# finished. It counts the film printed (0,40 m), not the metre billed.
|
||||||
before = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
|
before = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
# A real payment: Números leaves test orders out.
|
# A real payment: Números leaves test orders out.
|
||||||
c.execute('UPDATE dtf_local.orders SET payment=%s WHERE id=%s',
|
c.execute('''UPDATE dtf_local.orders SET payment=%s,
|
||||||
|
snapshot=jsonb_set(snapshot, '{items,0,metres}', '"0.40"') WHERE id=%s''',
|
||||||
(Jsonb({'provider': 'mercadopago', 'id': f'users-{tag}'}), third))
|
(Jsonb({'provider': 'mercadopago', 'id': f'users-{tag}'}), third))
|
||||||
for frm, to, at in (('rec', 'imp', "now()-interval '30 minutes'"), ('imp', 'fin', 'now()')):
|
for frm, to, at in (('rec', 'imp', "now()-interval '30 minutes'"), ('imp', 'fin', 'now()')):
|
||||||
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to))
|
VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to))
|
||||||
after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
|
after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
|
||||||
assert after[target]['orders'] == before[target]['orders'] + 1
|
assert after[target]['orders'] == before[target]['orders'] + 1
|
||||||
assert after[target]['metres'] == before[target]['metres'] + 1.0
|
assert round(after[target]['metres'] - before[target]['metres'], 2) == 0.4, (before[target], after[target])
|
||||||
assert after[target]['last_finished'] and after[target]['metres_per_hour'] is not None
|
assert after[target]['last_finished'] and after[target]['metres_per_hour'] is not None
|
||||||
assert after[target]['printing_hours'] >= before[target]['printing_hours'] + 0.49
|
assert after[target]['printing_hours'] >= before[target]['printing_hours'] + 0.49
|
||||||
|
# Two orders printing at once on one machine: the half hour they share counts
|
||||||
|
# once, so the machine did 1,50 m in 0,5 h, not in 1 h.
|
||||||
|
with db.connect() as c:
|
||||||
|
together = [order_fixture(c, owner, 'file', printed=printed) for printed in ('0.60', '0.90')]
|
||||||
|
made.extend(together)
|
||||||
|
for _, oid in together:
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET payment=%s, state='fin', machine_id=%s, machine_chosen=true
|
||||||
|
WHERE id=%s''', (Jsonb({'provider': 'mercadopago', 'id': f'users-{tag}-{oid}'}), textil2, oid))
|
||||||
|
for frm, to, at in (('rec', 'imp', "now()-interval '30 minutes'"), ('imp', 'fin', 'now()')):
|
||||||
|
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
|
VALUES(%s,%s,%s,'users-test','',false,{at})''', (oid, frm, to))
|
||||||
|
shared = next(m for m in su.call('/operator/stats?days=7', operator=True)['machines'] if m['id'] == textil2)
|
||||||
|
assert (shared['orders'], shared['metres'], shared['printing_hours'], shared['metres_per_hour']) == \
|
||||||
|
(2, 1.5, 0.5, 3.0), shared
|
||||||
|
|
||||||
# Switched off, a machine gives its automatic orders to another one.
|
# Switched off, a machine gives its automatic orders to another one.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
|||||||
@@ -82,10 +82,12 @@
|
|||||||
<div class="kpis" id="stats-kpis"></div>
|
<div class="kpis" id="stats-kpis"></div>
|
||||||
<section class="statbox"><h2>Metros por dia</h2><div class="chart" id="stats-chart"></div></section>
|
<section class="statbox"><h2>Metros por dia</h2><div class="chart" id="stats-chart"></div></section>
|
||||||
<section class="statbox"><h2>Por máquina</h2>
|
<section class="statbox"><h2>Por máquina</h2>
|
||||||
<p class="faint stats-hint">Pedidos que chegaram a Finalizado no período, na máquina em que estavam. Metros por hora: o tempo que ficaram em Imprimindo.</p>
|
<p class="faint stats-hint">Pedidos que chegaram a Finalizado no período, na máquina em que estavam. Impresso: o filme da folha, não o metro cobrado.
|
||||||
|
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>
|
<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>
|
||||||
<section class="statbox"><h2>Tempo em cada etapa</h2>
|
<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>
|
<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>
|
||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
Reference in New Issue
Block a user