fix: align proof, treatment, metrics and site videos with PDF
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 5m44s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m22s

This commit is contained in:
Cauê Faleiros
2026-11-06 15:27:48 -03:00
parent f4cd1842ca
commit a712c69aca
30 changed files with 631 additions and 110 deletions

View File

@@ -241,7 +241,7 @@ def assign_late(c, orders, limits):
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():
WHERE order_id=ANY(%s) ORDER BY created_at,id''', (ids,)).fetchall():
entered[(str(row['order_id']), row['to_state'])] = row['created_at']
now = datetime.now(timezone.utc)
for order in orders:
@@ -894,7 +894,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
# que o Prumo gerou entram como finais, e o pai segue para a fila.
# Itens que ainda dependem de preparo manual continuam em Arte
# recebida, com o botão de final disponível.
if parent['state'] == 'rec':
if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'):
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f
@@ -907,8 +907,12 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
(uuid4(), parent['id'], row['upload_id'], row['item_index'],
f'Aprovado pela prova do #{card["number"]}'))
ready = parent['state'] == 'rec' and all(c.execute('''SELECT 1 FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active AND item_index=%s LIMIT 1''', (parent['id'], i)).fetchone()
treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else ''
ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK}
{treatment_clause} LIMIT 1''', (parent['id'], i)).fetchone()
for i in range(len(parent['snapshot']['items'])))
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(),
state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id']))
@@ -1172,6 +1176,13 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
if row['snapshot'].get('treatment') and not row['parent_id']:
treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.')
# Two at most per machine in Imprimindo (app/machines.py).
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
@@ -1237,6 +1248,16 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
raise HTTPException(409, 'Print files are generated only before the order is queued')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
raise HTTPException(409, 'A customer correction replaced the original artwork; prepare the final file by hand')
if row['parent_id']:
manual = c.execute("SELECT item_index FROM dtf_local.print_files WHERE order_id=%s AND status='manual'",
(uid,)).fetchall()
for stuck in manual:
original_index = row['snapshot']['items'][stuck['item_index']]['proof_parent_item_index']
prepared = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE order_id=%s
AND item_index=%s AND kind='final' AND active LIMIT 1''',
(row['parent_id'], original_index)).fetchone()
if not prepared:
raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.')
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
audit('print_file_requeued', order=str(uid), operator=user)
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()
@@ -1407,7 +1428,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
# 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
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
@@ -1473,16 +1494,16 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
(o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within})
SELECT
percentile_cont(0.5) WITHIN GROUP (ORDER BY page_ms) AS page_avg,
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,
percentile_cont(0.5) WITHIN GROUP (ORDER BY (upload_bytes/1048576.0)/(upload_ms/1000.0))
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_bytes/1048576.0)/(upload_ms/1000.0))
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,
percentile_cont(0.5) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_avg,
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,
percentile_cont(0.5) WITHIN GROUP (ORDER BY montage_ms) AS montage_avg,
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 (
@@ -1492,9 +1513,9 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
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 percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s,
SELECT avg(seconds) AS avg_s,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n,
percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
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,
@@ -1504,7 +1525,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
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 percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s,
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()
@@ -1535,14 +1556,14 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
'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},
'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)}
def speed_figures(site, generation, card):
"""Números' speed block: average and p95, in seconds except upload (MB/s)."""
"""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,
@@ -1550,7 +1571,7 @@ def speed_figures(site, generation, card):
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': 'MB/s',
{'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)},