Under each art the Prumo warns about, the customer can choose Ajuste Fino or Ajuste Fino Redesenho (vectorize or redraw, per art, +48 h, no batch price). It is a disabled product until Gestão prices it in the Site tab; the server charges it per chosen art, Tiny gets a DTFIMP.AJF.RED line and two more business days, the card shows 'Redesenho · N artes' and the designer gate applies. The preview loop is slice R2. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
361 lines
24 KiB
Python
361 lines
24 KiB
Python
"""Números: the production figures and the SQL helpers they share."""
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from decimal import Decimal
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
|
|
from ... import machines, payments, unpaid
|
|
from ...cart_pricing import designer_hours
|
|
from ...core import db
|
|
from ...core.auth import operator
|
|
from .common import ORIGINS, REAL_ORDER, TREATED, person
|
|
from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT
|
|
|
|
router = APIRouter()
|
|
|
|
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
|
# A montador "Interno" or "faturado" order records the table price, not money
|
|
# received (Marcus, 2026-11-10): the cash figures leave it out and Números
|
|
# shows it in its own block.
|
|
NOT_CASH = ('COALESCE(o.payment->>\'method\',\'\') NOT IN '
|
|
f"('{payments.INTERNAL_METHOD}','{payments.INVOICED_METHOD}')")
|
|
|
|
|
|
def waited(order, start, end):
|
|
"""SQL: the seconds `order` spent in "Aguardando contato" between `start`
|
|
and `end`. Dropstar's rule D-38: that wait has no deadline and does not
|
|
count in the time figures."""
|
|
return f'''COALESCE((SELECT sum(extract(epoch FROM least({end}, COALESCE(w.ended_at, now()))
|
|
- greatest({start}, w.started_at))) FROM dtf_local.contact_waits w
|
|
WHERE w.order_id={order} AND w.started_at<{end} AND COALESCE(w.ended_at, now())>{start}), 0)'''
|
|
|
|
|
|
# Longest period one request may cover: a year and a day, for a year against the last.
|
|
STATS_MAX_DAYS = 366
|
|
|
|
|
|
def stats_period(days, start, end):
|
|
"""The local days a request covers: the last `days`, or start to end."""
|
|
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
|
if start is None and end is None:
|
|
days = days or 30
|
|
return today - timedelta(days=days - 1), today
|
|
if start is None or end is None:
|
|
raise HTTPException(422, 'Informe a data inicial e a final.')
|
|
if start > end:
|
|
raise HTTPException(422, 'A data inicial é depois da final.')
|
|
if (end - start).days + 1 > STATS_MAX_DAYS:
|
|
raise HTTPException(422, f'O período vai até {STATS_MAX_DAYS} dias.')
|
|
return start, end
|
|
|
|
|
|
@router.get('/api/operator/stats')
|
|
def production_stats(days: int | None = Query(default=None, ge=7, le=365), start: date | None = None,
|
|
end: date | None = None, user=Depends(operator)):
|
|
"""Production numbers from what the board already records: orders paid in
|
|
the period, how long each stage holds an order, what each machine printed,
|
|
and what is waiting now. The period is the last `days`, or start to end."""
|
|
start, end = stats_period(days, start, end)
|
|
period = (start, end)
|
|
within = f"{LOCAL_DAY} BETWEEN %s AND %s"
|
|
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
|
|
with db.connect() as c:
|
|
limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()
|
|
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
|
|
for row in limit_rows}
|
|
total = c.execute(f'''SELECT count(*) AS orders,
|
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),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 {within}''', period).fetchone()
|
|
# Approved quotes of the period nobody paid (front 9).
|
|
unpaid_figures = unpaid.figures(c, start, end)
|
|
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 {within}
|
|
GROUP BY 1''', period).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 {within}
|
|
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 {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,
|
|
# 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,
|
|
avg(seconds) / 3600 AS average_hours
|
|
FROM (SELECT id, state, count(*) AS passages,
|
|
sum(extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')}) 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) - {waited('o.id', 'o.created_at', 'f.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 {within}''', period).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()
|
|
# Passages past each stage's acceptable time (front 11), in the
|
|
# selected period and today.
|
|
# Each passage carries whether its order paid for treatment, which only
|
|
# Art received counts (front 5).
|
|
late_rows = c.execute(f'''SELECT s.state,
|
|
extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds,
|
|
(s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day,
|
|
o.snapshot->'treatment' AS treatment, o.snapshot->'redesign' AS redesign
|
|
FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''',
|
|
period + period).fetchall()
|
|
printed = machine_output(c, start, end)
|
|
# Rework of the period (D-02 to D-04): the authorized ones, by the day
|
|
# they were opened, over the film the machines printed in it.
|
|
not_test = "COALESCE(o.payment->>'provider','') <> 'teste'"
|
|
opened = "(r.opened_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s"
|
|
redone = {row['cause']: row for row in c.execute(f'''SELECT r.cause, sum(r.metres) AS metres,
|
|
count(DISTINCT r.order_id) AS orders FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
|
WHERE r.authorized AND {not_test} AND {opened} GROUP BY r.cause''', period).fetchall()}
|
|
# The house's rework enters the pay of who printed it (D-02).
|
|
by_printer = c.execute(f'''SELECT COALESCE({person('r.printed_by')}, 'Sem registro') AS who,
|
|
sum(r.metres) AS metres FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
|
WHERE r.authorized AND r.cause<>%s AND {not_test} AND {opened} GROUP BY 1 ORDER BY 2 DESC''',
|
|
(CUSTOMER_CAUSE,) + period).fetchall()
|
|
undecided = c.execute(f'''SELECT r.id, r.order_id, o.number, r.cause, r.metres, r.opened_at,
|
|
{person('r.opened_by')} AS opened_name FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
|
WHERE r.decided_at IS NULL AND {not_test} ORDER BY r.opened_at''').fetchall()
|
|
# 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']
|
|
# 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) FILTER (WHERE {NOT_CASH}),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()}
|
|
# The table price of the montador's Interno and Venda orders, counted
|
|
# apart from the money received above (front 7a.3).
|
|
price_table = {row['method']: row for row in c.execute(f'''SELECT o.payment->>'method' AS method,
|
|
count(*) AS orders, COALESCE(sum({metres}),0) AS metres,
|
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents
|
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
|
AND o.payment->>'method' IN (%s,%s) GROUP BY 1''',
|
|
period + (payments.INTERNAL_METHOD, payments.INVOICED_METHOD)).fetchall()}
|
|
# Coupons used by the period's paid orders (front 8.3): what each code
|
|
# brought in orders, billed metres, discount and money received.
|
|
coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id,
|
|
o.snapshot->'coupon'->>'code' AS code, count(*) AS orders,
|
|
COALESCE(sum({metres}),0) AS metres,
|
|
COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents,
|
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents
|
|
FROM dtf_local.orders o
|
|
WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL
|
|
GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall()
|
|
# Speed (item 0.12): the browser's marks on the way to a quote, the
|
|
# Prumo's print generation and the time from payment event to card.
|
|
site_speed = c.execute(f'''WITH samples AS (
|
|
SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms,
|
|
(o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms,
|
|
(o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes,
|
|
(o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms,
|
|
(o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms
|
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within})
|
|
SELECT
|
|
avg(page_ms) AS page_avg,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n,
|
|
avg((upload_ms/1000.0)/(upload_bytes/1048576.0))
|
|
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_ms/1000.0)/(upload_bytes/1048576.0))
|
|
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95,
|
|
count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n,
|
|
avg(analysis_ms) AS analysis_avg,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n,
|
|
avg(montage_ms) AS montage_avg,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n
|
|
FROM samples''', period).fetchone()
|
|
print_speed = c.execute(f'''WITH samples AS (
|
|
SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds,
|
|
COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric,
|
|
(o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres
|
|
FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id
|
|
WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL
|
|
AND p.item_index < jsonb_array_length(o.snapshot->'items'))
|
|
SELECT avg(seconds) AS avg_s,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n,
|
|
avg(seconds/NULLIF(metres/10,0))
|
|
FILTER (WHERE metres>0) AS per10_avg,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
|
|
FILTER (WHERE metres>0) AS per10_p95,
|
|
count(*) FILTER (WHERE metres>0) AS per10_n
|
|
FROM samples''', period).fetchone()
|
|
card_speed = c.execute(f'''WITH samples AS (
|
|
SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds
|
|
FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text
|
|
WHERE {REAL_ORDER} AND {within} GROUP BY o.id)
|
|
SELECT avg(seconds) AS avg_s,
|
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n
|
|
FROM samples WHERE seconds >= 0''', period).fetchone()
|
|
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
|
late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')}
|
|
for row in late_rows:
|
|
limit = limits.get(row['state'])
|
|
if not limit:
|
|
continue
|
|
hours = float(limit['hours'])
|
|
if row['state'] == 'rec':
|
|
hours += designer_hours({'treatment': row.get('treatment'), 'redesign': row.get('redesign')})
|
|
if row['seconds'] > hours * 3600:
|
|
late[row['state']]['count'] += 1
|
|
if row['day'] == today:
|
|
late[row['state']]['today'] += 1
|
|
series = []
|
|
for offset in range((end - start).days + 1):
|
|
day = start + 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': 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]},
|
|
'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],
|
|
'unpaid': unpaid_figures,
|
|
'price_table': [{'method': method,
|
|
'orders': price_table[method]['orders'] if method in price_table else 0,
|
|
'metres': float(price_table[method]['metres']) if method in price_table else 0.0,
|
|
'cents': int(price_table[method]['cents']) if method in price_table else 0}
|
|
for method in (payments.INVOICED_METHOD, payments.INTERNAL_METHOD)],
|
|
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
|
'stage_limits': limits, 'late': late,
|
|
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
|
'average_hours': hours(row['average_hours'])} for row in stages},
|
|
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
|
|
'speed': speed_figures(site_speed, print_speed, card_speed),
|
|
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided),
|
|
'coupons': [{'id': row['id'], 'code': row['code'], 'orders': row['orders'],
|
|
'metres': float(row['metres']), 'discount_cents': int(row['discount_cents']),
|
|
'cents': int(row['cents'])} for row in coupons_used]}
|
|
|
|
|
|
def speed_figures(site, generation, card):
|
|
"""Números' speed block: average and slow-case p95, in seconds per unit."""
|
|
def pair(avg, p95, n, scale=1):
|
|
return {'average': round(float(avg)/scale, 2) if avg is not None else None,
|
|
'p95': round(float(p95)/scale, 2) if p95 is not None else None,
|
|
'samples': int(n or 0)}
|
|
return [
|
|
{'key': 'page', 'label': 'Abrir o montador', 'unit': 's',
|
|
**pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)},
|
|
{'key': 'upload', 'label': 'Subir o arquivo', 'unit': 's/MB',
|
|
**pair(site['upload_avg'], site['upload_p95'], site['upload_n'])},
|
|
{'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's',
|
|
**pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)},
|
|
{'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's',
|
|
**pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)},
|
|
{'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's',
|
|
**pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])},
|
|
{'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's',
|
|
**pair(card['avg_s'], card['p95_s'], card['n'])},
|
|
]
|
|
|
|
|
|
def rework_figures(printed, redone, by_printer, undecided):
|
|
"""Números' rework: per cause, the metres redone over the film printed,
|
|
against the goal; the house's total against four times it."""
|
|
film = Decimal(str(sum(m['metres'] for m in printed)))
|
|
share = lambda metres: float(round(100 * metres / film, 2)) if film else None
|
|
causes = []
|
|
for cause in HOUSE_CAUSES + (CUSTOMER_CAUSE,):
|
|
row = redone.get(cause)
|
|
metres = Decimal(row['metres']) if row else Decimal(0)
|
|
causes.append({'cause': cause, 'metres': float(metres), 'orders': row['orders'] if row else 0,
|
|
'percent': share(metres)})
|
|
house = sum(Decimal(str(c['metres'])) for c in causes if c['cause'] != CUSTOMER_CAUSE)
|
|
return {'film_metres': float(film), 'goal_percent': float(REWORK_GOAL_PERCENT),
|
|
'house': {'metres': float(house), 'percent': share(house),
|
|
'goal_percent': float(REWORK_GOAL_PERCENT * len(HOUSE_CAUSES))},
|
|
'causes': causes,
|
|
'by_printer': [{'who': row['who'], 'metres': float(row['metres'])} for row in by_printer],
|
|
'pending': [{'id': row['id'], 'order_id': str(row['order_id']), 'number': row['number'],
|
|
'cause': row['cause'], 'metres': float(row['metres']), 'opened_at': row['opened_at'].isoformat(),
|
|
'opened_by': row['opened_name']} for row in undecided]}
|
|
|
|
|
|
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.
|
|
|
|
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
|
|
WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL
|
|
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 = {}
|
|
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, 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 = 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),
|
|
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
|
|
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
|
|
'now': {state: m['states'].get(state, 0) for state in ('tra', 'imp')}})
|
|
loose = [row for row in done if row['machine_id'] is None]
|
|
if loose:
|
|
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
|
|
'metres': float(sum(row['metres'] for row in loose)), 'printing_hours': None,
|
|
'metres_per_hour': None, 'last_finished': None, 'now': {}})
|
|
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
|