feat: acceptable time per stage with late cards and alerts (front 11)
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 4m24s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
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 4m24s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
Gestão edits the hours and the responsible for each column. A card past the limit turns yellow, twice the limit red, and the board lists it under Atrasados. Números compares the real median with the limit and counts the passages that exceeded it in the period and today.
This commit is contained in:
@@ -105,6 +105,8 @@ def backup_now(user=Depends(can('integrations'))):
|
||||
@router.get('/api/operator/board')
|
||||
def board(user=Depends(operator)):
|
||||
with db.connect() as c:
|
||||
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
|
||||
for row in c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()}
|
||||
# Everything still in progress, however old: an operator must never lose a
|
||||
# card they can act on. Finished orders are terminal and only accumulate,
|
||||
# so the board carries a recent window of them and reports the true total.
|
||||
@@ -131,6 +133,7 @@ def board(user=Depends(operator)):
|
||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
||||
orders = with_print_files(c, active + finished)
|
||||
assign_late(c, orders, limits)
|
||||
# A paid notification that did not become an order is money received
|
||||
# for nothing the factory will make. The board carries the count; the
|
||||
# Pagamentos tab pages through them until someone records a resolution.
|
||||
@@ -148,7 +151,45 @@ def board(user=Depends(operator)):
|
||||
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.PRINTING_CAP,
|
||||
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes),
|
||||
'pending_total': pending_total, 'approved_total': approved_total}
|
||||
'pending_total': pending_total, 'approved_total': approved_total,
|
||||
'stage_limits': limits}
|
||||
|
||||
|
||||
class StageLimit(StrictModel):
|
||||
state: Literal['rec', 'tra', 'imp', 'rev', 'fin']
|
||||
hours: Decimal = Field(gt=0, le=10000)
|
||||
responsible: str = Field(default='', max_length=80)
|
||||
|
||||
|
||||
class StageLimits(StrictModel):
|
||||
limits: list[StageLimit] = Field(min_length=1, max_length=5)
|
||||
|
||||
|
||||
@router.get('/api/operator/stage-limits')
|
||||
def get_stage_limits(user=Depends(operator)):
|
||||
with db.connect() as c:
|
||||
rows = c.execute('''SELECT state,hours,responsible,updated_by,updated_at
|
||||
FROM dtf_local.stage_limits ORDER BY array_position(ARRAY['rec','tra','imp','rev','fin'],state)''').fetchall()
|
||||
return {'limits': [{'state': row['state'], 'hours': float(row['hours']),
|
||||
'responsible': row['responsible'], 'updated_by': row['updated_by'],
|
||||
'updated_at': row['updated_at']} for row in rows]}
|
||||
|
||||
|
||||
@router.post('/api/operator/stage-limits')
|
||||
def set_stage_limits(body: StageLimits, user=Depends(can('manage'))):
|
||||
seen = set()
|
||||
with db.connect() as c:
|
||||
for limit in body.limits:
|
||||
if limit.state in seen:
|
||||
raise HTTPException(422, 'Cada etapa aparece uma vez.')
|
||||
seen.add(limit.state)
|
||||
c.execute('''INSERT INTO dtf_local.stage_limits(state,hours,responsible,updated_by,updated_at)
|
||||
VALUES(%s,%s,%s,%s,now())
|
||||
ON CONFLICT (state) DO UPDATE SET hours=EXCLUDED.hours,responsible=EXCLUDED.responsible,
|
||||
updated_by=EXCLUDED.updated_by,updated_at=now()''',
|
||||
(limit.state, limit.hours, limit.responsible.strip(), user))
|
||||
audit('stage_limits_changed', operator=user, states=','.join(sorted(seen)))
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def uploads_of(rows):
|
||||
@@ -192,6 +233,35 @@ TREATED = """f.kind='final'
|
||||
AND k.kind='correction')"""
|
||||
|
||||
|
||||
def assign_late(c, orders, limits):
|
||||
"""How long each card has been in its stage, and whether it passed the
|
||||
limit Gestão set (front 11). A finished card with pickup is not late."""
|
||||
ids = [order['id'] for order in orders]
|
||||
if not ids:
|
||||
return
|
||||
entered = {}
|
||||
for row in c.execute('''SELECT order_id,to_state,created_at FROM dtf_local.movements
|
||||
WHERE order_id=ANY(%s) AND NOT back ORDER BY created_at''', (ids,)).fetchall():
|
||||
entered[(str(row['order_id']), row['to_state'])] = row['created_at']
|
||||
now = datetime.now(timezone.utc)
|
||||
for order in orders:
|
||||
if order.get('cancelled_at'):
|
||||
continue
|
||||
limit = limits.get(order['state'])
|
||||
if not limit or (order['state'] == 'fin' and order.get('picked_up_at')):
|
||||
continue
|
||||
since = entered.get((str(order['id']), order['state']))
|
||||
if not since and order['state'] == 'fin':
|
||||
since = order.get('finished_at')
|
||||
since = since or order['created_at']
|
||||
hours = max(0.0, (now - since).total_seconds() / 3600)
|
||||
limit_hours = float(limit['hours'])
|
||||
order['state_hours'] = round(hours, 2)
|
||||
order['limit_hours'] = limit_hours
|
||||
order['limit_by'] = limit['responsible']
|
||||
order['late'] = 'bad' if hours >= limit_hours * 2 else 'warn' if hours >= limit_hours else None
|
||||
|
||||
|
||||
def assign_machines(c, orders):
|
||||
"""Each machine, its pull attribution, and its printing place."""
|
||||
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
|
||||
@@ -1310,6 +1380,9 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
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),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
|
||||
@@ -1344,6 +1417,12 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
(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.
|
||||
late_rows = c.execute(f'''SELECT state,
|
||||
extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')} AS seconds,
|
||||
(until AT TIME ZONE 'America/Sao_Paulo')::date AS day
|
||||
FROM ({spans}) s WHERE 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.
|
||||
@@ -1423,6 +1502,14 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY 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 limit and row['seconds'] > limit['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)
|
||||
@@ -1441,6 +1528,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
'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'])},
|
||||
'stage_limits': limits, 'late': late,
|
||||
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
||||
'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},
|
||||
|
||||
Reference in New Issue
Block a user