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

@@ -26,7 +26,8 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
if not row: raise HTTPException(404, 'Order not found')
if row['parent_id']:
raise HTTPException(409, 'A prova recebe o PNG final automaticamente.')
proof.require_unlocked(c, row)
if not proof.manual_source_needed(c, row):
proof.require_unlocked(c, row)
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
return begin_upload(body, session_id=operator_identity(user))
@@ -60,5 +61,6 @@ def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))
if not order: raise HTTPException(404, 'Order not found')
if order['parent_id']:
raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.')
proof.require_unlocked(c, order)
if not proof.manual_source_needed(c, order):
proof.require_unlocked(c, order)
return submit_files(c,order,body,operator_identity(user),'final',user)

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)},

160
app/api/site_videos.py Normal file
View File

@@ -0,0 +1,160 @@
"""Six DTF videos, managed by Gestão and published only after virus scanning."""
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import Field
from ..core import db
from ..core.auth import audit, can, operator
from ..core.models import StrictModel
from ..runtime import operator_identity, storage, upload_row
from ..scanning import require_clean
from .uploads import begin_upload
router = APIRouter()
CATALOG = {
'subindo': 'Subindo a arte pelo celular',
'nota': 'O que é a nota da arte — e o que ela não é',
'png': 'Por que PNG com fundo transparente',
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
'retirada': 'Retirada em Franca em 24 h',
'sala': 'A sala às 3 da manhã',
}
VIDEO_MAX = 100 * 1024 * 1024
CAPTIONS_MAX = 1024 * 1024
class VideoUpdate(StrictModel):
upload_id: UUID | None = None
captions_id: UUID | None = None
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
enabled: bool = False
class VideoUploadStart(StrictModel):
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
size: int = Field(gt=0, strict=True)
def _kind(upload):
name = upload['name'].lower()
if name.endswith('.mp4') and upload['size'] <= VIDEO_MAX:
return 'video/mp4', b'ftyp', 4
if name.endswith('.webm') and upload['size'] <= VIDEO_MAX:
return 'video/webm', b'\x1a\x45\xdf\xa3', 0
if name.endswith('.vtt') and upload['size'] <= CAPTIONS_MAX:
return 'text/vtt', b'WEBVTT', 0
raise HTTPException(422, 'Use MP4/WebM de até 100 MB ou legenda VTT de até 1 MB.')
def _checked_upload(c, uid, identity, expected):
upload = upload_row(c, uid, identity, lock=True)
if not upload['complete']:
raise HTTPException(409, 'Espere o envio terminar.')
require_clean(upload)
mime, signature, offset = _kind(upload)
if mime not in expected:
raise HTTPException(422, 'Escolha um vídeo MP4/WebM e uma legenda VTT.')
response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'], Range='bytes=0-31')
head = response['Body'].read()
if not head[offset:].startswith(signature) and not (mime == 'text/vtt' and head.startswith(b'\xef\xbb\xbfWEBVTT')):
raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.')
return upload, mime
@router.post('/api/operator/site-videos/uploads')
def start_video_upload(body: VideoUploadStart, user=Depends(can('manage'))):
_kind({'name': body.name, 'size': body.size})
return begin_upload(body, session_id=operator_identity(user))
@router.get('/api/operator/site-videos')
def manage_videos(user=Depends(operator)):
with db.connect() as c:
rows = {row['id']: row for row in c.execute('''SELECT v.*,
u.name AS video_name, t.name AS captions_name
FROM dtf_local.site_videos v
LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id
LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()}
return {'videos': [dict(id=id, title=title,
product=rows[id]['product'] if id in rows else None,
upload_id=rows[id]['upload_id'] if id in rows else None,
captions_id=rows[id]['captions_id'] if id in rows else None,
video_name=rows[id]['video_name'] if id in rows else None,
captions_name=rows[id]['captions_name'] if id in rows else None,
enabled=rows[id]['enabled'] if id in rows else False)
for id, title in CATALOG.items()]}
@router.post('/api/operator/site-videos/{video_id}')
def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
if video_id not in CATALOG:
raise HTTPException(404, 'Vídeo não encontrado.')
if body.enabled and (not body.upload_id or not body.captions_id):
raise HTTPException(422, 'Envie o vídeo e sua legenda VTT antes de publicar.')
with db.connect() as c:
previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE',
(video_id,)).fetchone() or {}
identity = operator_identity(user)
keys = []
for uid, expected, previous_id, previous_key in (
(body.upload_id, ('video/mp4','video/webm'), previous.get('upload_id'), previous.get('video_key')),
(body.captions_id, ('text/vtt',), previous.get('captions_id'), previous.get('captions_key'))):
if not uid:
keys.append(None)
elif uid == previous_id and previous_key:
keys.append(previous_key)
else:
upload, mime = _checked_upload(c, uid, identity, expected)
key = f'videos/{video_id}/{uid}{".vtt" if mime == "text/vtt" else ".webm" if mime == "video/webm" else ".mp4"}'
storage.client.copy_object(Bucket=storage.bucket,
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
Key=key, ContentType=mime, MetadataDirective='REPLACE')
keys.append(key)
if body.enabled and body.product:
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
(video_id, body.product)).fetchone()
if other:
raise HTTPException(409, 'Já existe um vídeo flutuante ativo para este produto.')
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,enabled,updated_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id,
video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key,
product=EXCLUDED.product,enabled=EXCLUDED.enabled,updated_by=EXCLUDED.updated_by,updated_at=now()''',
(video_id, body.upload_id, body.captions_id, keys[0], keys[1], body.product, body.enabled, user))
ids = [uid for uid in (body.upload_id, body.captions_id) if uid]
if ids:
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,))
audit('site_video_changed', video=video_id, operator=user, enabled=body.enabled)
return {'ok': True}
@router.get('/api/site/videos')
def published_videos():
with db.connect() as c:
rows = c.execute('''SELECT v.id,v.product,v.video_key,v.captions_key,u.name AS video_name
FROM dtf_local.site_videos v
JOIN dtf_local.uploads u ON u.id=v.upload_id
WHERE v.enabled AND v.video_key IS NOT NULL AND v.captions_key IS NOT NULL''').fetchall()
return {'videos': [dict(id=row['id'], product=row['product'],
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
captions=f"/api/site/videos/{row['id']}/captions") for row in rows]}
@router.get('/api/site/videos/{video_id}/captions')
def published_captions(video_id: str):
if video_id not in CATALOG:
raise HTTPException(404, 'Legenda não encontrada.')
with db.connect() as c:
row = c.execute('''SELECT captions_key FROM dtf_local.site_videos
WHERE id=%s AND enabled AND video_key IS NOT NULL AND captions_key IS NOT NULL''',
(video_id,)).fetchone()
if not row:
raise HTTPException(404, 'Legenda não encontrada.')
obj = storage.client.get_object(Bucket=storage.bucket, Key=row['captions_key'])
body = obj['Body'].read(CAPTIONS_MAX + 1)
if len(body) > CAPTIONS_MAX:
raise HTTPException(500, 'Legenda inválida.')
return Response(body, media_type='text/vtt', headers={'Cache-Control': 'public, max-age=300'})