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

@@ -224,7 +224,7 @@ class LocalS3Storage:
raise
self.client.create_bucket(Bucket=self.bucket)
self.client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration={
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': ''},
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': 'originals/'},
'Expiration': {'Days': 30}, 'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 1}}]})
def health(self):

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

View File

@@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware
from .core import db
from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
from .api import artwork, customer, health, operator, orders, payments, quotes, uploads, users
from .api import artwork, customer, health, operator, orders, payments, quotes, site_videos, uploads, users
@asynccontextmanager
@@ -45,5 +45,5 @@ async def safe_headers(request, call_next):
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users):
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos):
app.include_router(module.router)

View File

@@ -29,6 +29,7 @@ from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
from psycopg.types.json import Jsonb
from PIL import Image
from .core.auth import audit
from .core.db import connect
@@ -68,7 +69,7 @@ def queue(c, order_id, items, only_missing=False):
def claim(c):
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p
JOIN dtf_local.orders o ON o.id=p.order_id
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
@@ -120,13 +121,32 @@ def render_one(storage):
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
job['claim_token'] = token
item = job['snapshot']['items'][job['item_index']]
source_ids = [UUID(u) for u in item['uploads']]
# A format such as CDR needs a human to prepare the full-size final on
# the parent. The child still generates its own 15 cm proof from that PNG.
if job['parent_id']:
source = c.execute('''SELECT u.id FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND f.kind='final' AND f.active
AND u.purged_at IS NULL AND u.expires_at>now()
ORDER BY f.created_at DESC LIMIT 1''',
(job['parent_id'], item['proof_parent_item_index'])).fetchone()
if source:
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
elif job['snapshot'].get('treatment'):
job['wait_for_treatment'] = True
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
([UUID(u) for u in item['uploads']],)).fetchall()
(source_ids,)).fetchall()
# Every generated file shares its order's artwork retention deadline.
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
([UUID(u) for u in item['uploads']],)).fetchone()['e']
(source_ids,)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads}
if job.get('wait_for_treatment'):
finish(job, 'manual', {'reason': 'Tratamento pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
return True
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
'monte a folha a partir do original'})
@@ -249,6 +269,22 @@ def produce(storage, job, item, uploads):
local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name'])
if job.get('proof_fallback'):
with Image.open(files[0][0]) as final:
width_px, height_px = final.size
width_cm = float(Decimal(width_px) * Decimal('2.54') / Decimal(300))
height_cm = float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
original_height = float(item['production']['height_cm'])
fraction = float(item.get('proof_y_fraction') or 0)
source = {'kind': 'sheet', 'width_cm': width_cm, 'length_cm': height_cm,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}
item = {**item, 'proof_y_fraction': min(1, fraction * original_height / height_cm),
'production': {'version': 3, 'film_width_cm': width_cm,
'height_cm': height_cm, 'sources': [source],
'placements': [{'source_index': 0, 'copy_index': 0,
'x_cm': 0, 'y_cm': 0, 'width_cm': width_cm,
'length_cm': height_cm, 'rotation_degrees': 0,
'mirrored': False}]}}
proof_of = job['snapshot'].get('proof_of')
# The child owns its final file; the class names its proof.
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of

View File

@@ -1,7 +1,7 @@
"""The print proof (Dropstar, 2026-10-21).
An order above 10 m prints a proof before the rest, checked by the print room
without stopping the order. Dropstar's rule (2026-10-23): up to 30 cm, from
without stopping the order. Dropstar's current rule: up to 15 cm, from
the part with the thinnest lines, a piece of each different artwork, at most
three proofs per order, never billed. On an order above 10 m the customer
may also ask for a proof at checkout (below 10 m there is none, Dropstar
@@ -89,6 +89,15 @@ def waiting(c, order):
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
def manual_source_needed(c, order):
"""A proof child cannot decode an original; prepare the full parent PNG first."""
if order.get('parent_id') or order['state'] != 'rec':
return False
child = open_child(c, order['id'])
return bool(child and c.execute('''SELECT 1 FROM dtf_local.print_files
WHERE order_id=%s AND status='manual' LIMIT 1''', (child['id'],)).fetchone())
def require_unlocked(c, order):
"""A parent cannot enter production or have its final changed before the proof answer."""
if waiting(c, order):

View File

@@ -67,21 +67,23 @@ def report(order, uploads):
else:
lines.append(f'{lead}Formato detectado: {_ext(final).upper() or "desconhecido"}')
exts = {_ext(name) for name in names}
if exts & {'pdf', 'ai'}:
lines.append(f'{lead}PDF → PNG 300 DPI')
elif exts & MANUAL:
lines.append(f'{lead}{"/".join(sorted(exts & MANUAL)).upper()} com texto vivo → conferência manual')
row = generated.get(index)
ready = bool(row and row.get('status') == 'ready')
if row and row.get('status') == 'manual':
lines.append(f'{lead}Arquivo exige preparo manual')
dpi = item.get('source_dpi')
if dpi:
lines.append(f'{lead}Veio em {dpi} DPI, ampliado para 300' if dpi < 300 else f'{lead}Resolução {dpi} DPI')
lines.append(f'{lead}Fundo conferido na sala (arquivo manual)' if exts & MANUAL
else f'{lead}Fundo transparente')
lines.append(f'{lead}Resolução detectada: {dpi} DPI')
if ready:
detail = row.get('detail') or {}
if exts & {'pdf', 'ai'} and detail.get('format') == 'png':
lines.append(f'{lead}PDF → PNG {detail.get("dpi", 300)} DPI')
elif detail.get('format'):
lines.append(f'{lead}Arquivo final em {detail["format"].upper()} {detail.get("dpi", 300)} DPI')
dots = int(item.get('residue_accepted') or 0)
if dots:
lines.append(f'{lead}{dots} ponto{"s" if dots > 1 else ""} < 2 mm — cliente aceitou' +
_hora(item.get('residue_accepted_at')))
else:
lines.append(f'{lead}0 pontos de recorte')
production = item.get('production') or {}
placements = production.get('placements') or []
if item.get('mode') in ('avulsa', 'uv'):
@@ -100,7 +102,6 @@ def report(order, uploads):
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1')
else:
lines.append(f'{lead}Aviso de traço fino não disparou')
row = generated.get(index)
if row:
detail = row.get('detail') or {}
parts = detail.get('parts') or []
@@ -108,9 +109,7 @@ def report(order, uploads):
sizes = [Decimal(str(p.get('to_cm', 0))) - Decimal(str(p.get('from_cm', 0))) for p in parts]
lines.append(f'{lead}{_m(billed)} m → {len(parts)} partes (' +
' + '.join(_m(size) for size in sizes) + ')')
elif detail.get('format'):
lines.append(f'{lead}Arquivo final em {detail["format"].upper()} {detail.get("dpi", 300)} DPI')
if row.get('finished_at') and row.get('created_at'):
if ready and row.get('finished_at') and row.get('created_at'):
seconds = (row['finished_at'] - row['created_at']).total_seconds()
lines.append(f'{lead}Prumo levou {max(1, round(seconds))} s')
return lines
@@ -123,7 +122,7 @@ def customer_summary(items):
lead = f'Item {index + 1}: ' if len(items) > 1 else ''
dpi = item.get('source_dpi')
if dpi and dpi < 300:
lines.append(f'{lead}Sua arte veio em {dpi} DPI e foi ampliada para 300.')
lines.append(f'{lead}Sua arte foi medida em {dpi} DPI. O arquivo de impressão será preparado em 300 DPI após o pagamento.')
dots = int(item.get('residue_accepted') or 0)
if dots:
lines.append(f'{lead}Há {dots} pontinho{"s" if dots > 1 else ""} solto{"s" if dots > 1 else ""} '

View File

@@ -325,6 +325,20 @@ CREATE TABLE IF NOT EXISTS dtf_local.stage_limits (
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Videos are uploaded by Gestão; the Site reads only enabled, scanned files.
CREATE TABLE IF NOT EXISTS dtf_local.site_videos (
id text PRIMARY KEY CHECK (id IN ('subindo','nota','png','avulsas','retirada','sala')),
upload_id uuid REFERENCES dtf_local.uploads(id),
captions_id uuid REFERENCES dtf_local.uploads(id),
video_key text,
captions_key text,
product text CHECK (product IN ('file','avulsa','uvfile','uv')),
enabled boolean NOT NULL DEFAULT false,
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS video_key text;
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS captions_key text;
INSERT INTO dtf_local.stage_limits(state,hours,responsible) VALUES
('rec',2,'Designer'), ('tra',6,'Operador'), ('imp',4,'Operador'),
('rev',2,'Revisor'), ('fin',72,'Atendimento')

View File

@@ -9,7 +9,7 @@ server {
add_header Referrer-Policy no-referrer always;
add_header X-Frame-Options DENY always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
location = /health { access_log off; return 200 'ok'; }
location /api/ {
limit_req zone=api_limit burst=100 nodelay;

View File

@@ -1 +1 @@
{"Rules":[{"ID":"local-artwork-retention","Status":"Enabled","Filter":{"Prefix":""},"Expiration":{"Days":30},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}
{"Rules":[{"ID":"local-artwork-retention","Status":"Enabled","Filter":{"Prefix":"originals/"},"Expiration":{"Days":30},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}

View File

@@ -2,6 +2,6 @@
"Version": "2012-10-17",
"Statement": [
{"Effect":"Allow","Action":["s3:ListBucket","s3:ListBucketMultipartUploads","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::dtf-local-artwork"]},
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::dtf-local-artwork/originals/*"]}
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::dtf-local-artwork/originals/*","arn:aws:s3:::dtf-local-artwork/videos/*"]}
]
}

View File

@@ -116,8 +116,19 @@ try{
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:1100,deviceScaleFactor:1,mobile:false});
await call('Page.navigate',{url:`http://127.0.0.1:${server.address().port}/`});
await waitFor(()=>evaluate(`typeof sel==='function' && typeof pintaEntrega==='function'`),'Site scripts');
assert.equal(await evaluate(`document.querySelectorAll('#videosGrid .videoCard').length`),6);
assert.equal(await evaluate(`document.querySelector('#videosGrid').textContent.includes('Subindo a arte pelo celular')`),true);
await evaluate('window.siteVideosReady');
assert.equal(await evaluate(`document.querySelectorAll('#videosGrid .videoCard').length`),0);
assert.equal(await evaluate(`document.querySelector('#videos').hidden`),true);
await evaluate(`VIDEOS[0].src='/preview.mp4';videosSection()`);
await evaluate(`document.querySelector('#videosGrid .videoCard').focus()`);
await click('#videosGrid .videoCard');
assert.deepEqual(await evaluate(`({dialog:document.querySelector('.videoModal').getAttribute('role'),
focus:document.activeElement.className,open:!document.querySelector('.videoModal').hidden})`),
{dialog:'dialog',focus:'vmClose',open:true});
await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
assert.equal(await evaluate(`document.querySelector('.videoModal').hidden &&
document.activeElement.classList.contains('videoCard')`),true);
await evaluate(`VIDEOS[0].src=null;videosSection()`);
// Observe the actual engine, without replacing its placement or rendering.
await evaluate(`(()=>{
const original=encaixar;
@@ -172,6 +183,19 @@ try{
return [(await medir(...linhas(2))).px,(await medir(...linhas(5))).px,(await medir(...linhas(6))).px,
(await medir(...linhas(20))).classe,(await medir(...linhas(20),...ciscos)).classe];})()`),[2,5,6,'C3','C3']);
await click('[data-modo="file"]');
// A ready sheet with two source files stores the finest stroke's position
// on the combined film, not its position within the second file.
assert.deepEqual(await evaluate(`(()=>{
const old=folhas,oldLayout=montagemLayout;
folhas=[{an:{traco:{px:9,classe:'C2',proofYFraction:0.2}}},
{an:{traco:{px:3,classe:'C1',proofYFraction:0.5}}}];
montagemLayout=null;
try{return tracoDoItem(null,{height_cm:100,placements:[
{source_index:0,y_cm:0,length_cm:50,rotation_degrees:0},
{source_index:1,y_cm:50,length_cm:50,rotation_degrees:0}]});}
finally{folhas=old;montagemLayout=oldLayout;}
})()`),{strokePx:3,strokeClass:'C1',strokeChoice:null,
proofSourceIndex:1,proofYFraction:0.75});
// Opening a product paints on the next frame; on a busy runner the check
// must wait for it rather than race it.
await waitFor(()=>evaluate(`!$('tipoEnvio').hidden`),'by-metre product open');

View File

@@ -165,6 +165,13 @@ try{
await waitFor(()=>kanban.eval('!document.getElementById("app").hidden'),'Kanban sign-in');
assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null);
assert.equal(await kanban.eval('document.getElementById("password").value'),'');
await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'),
'six video slots in Gestão');
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),12);
await mkdir('output/local',{recursive:true});
await kanban.eval('document.getElementById("site-videos-panel").scrollIntoView()');
await kanban.screenshot('output/local/kanban-videos.png');
await kanban.click('[data-tab="quotes"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#quote-filters button").length===2'),'quote filters');
await kanban.eval('document.querySelectorAll("#quote-filters button")[1].click()');

View File

@@ -171,15 +171,15 @@ def run():
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']
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'average_hours': 2.0}, day['stages']
assert day['stages']['rec']['average_hours'] == 1.0, day['stages']
# Half an hour of it waiting for the customer does not count (D-38).
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.contact_waits(order_id, started_at, ended_at)
VALUES(%s, %s::timestamptz, %s::timestamptz)''', (order_id, f'{alone} 09:15-03', f'{alone} 09:45-03'))
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra']['median_hours'] == 1.5, day['stages']
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
assert day['stages']['tra']['average_hours'] == 1.5, day['stages']
assert day['stages']['rec']['average_hours'] == 1.0, day['stages']
# The company's name from the registry: on the board, and found by the search.
from app import cnpj as registry

View File

@@ -304,6 +304,29 @@ def run():
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it')
# A CDR cannot be decoded by the worker. The designer prepares the full
# parent PNG, then the worker automatically cuts the child's proof from it.
manual_source = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='MANUAL-PROOF.cdr')
manual_parent = paid_order(client, loose_item(manual_source, copies=1))
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
(manual_parent['id'],))
manual_child = client.call('/operator/orders/' + manual_parent['id'] + '/proof-card', {}, operator=True)
wait_print(client, manual_child['id'], 'manual')
retry = client.call('/operator/orders/' + manual_child['id'] + '/print-files', {}, operator=True, expected=409)
assert 'pedido pai' in retry['detail'], retry
prepared = upload_bytes(client, artwork(), name='MANUAL-PROOF-FINAL.png', order_id=manual_parent['id'])
client.call('/operator/orders/' + manual_parent['id'] + '/final-files',
{'version': manual_parent['version'],
'files': [{'item_index': 0, 'upload_id': prepared}],
'note': 'PNG completo para a prova'}, operator=True)
client.call('/operator/orders/' + manual_child['id'] + '/print-files', {}, operator=True)
wait_print(client, manual_child['id'], 'ready')
proof_card = next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == manual_child['id'])
assert proof_card['final_items'] == [0], proof_card
print('PASS: manual parent PNG produces the child proof automatically')
# A customer cannot see or reuse another order's generated file.
other = Client()
other.call('/session')

74
tests/site_video_test.py Normal file
View File

@@ -0,0 +1,74 @@
"""Published site videos retain their file and expose same-origin captions.
Run against the local stack with an internal S3 public endpoint:
SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.site_video_test
"""
from urllib.request import Request, urlopen
from app.core import db
from app.runtime import storage
from tests.smoke_test import BASE, Client, with_host, wait_scan
VIDEO = b'\x00\x00\x00\x18ftypisom\x00\x00\x00\x00isomiso2'
CAPTIONS = b'WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nTeste de legenda.\n'
def upload(operator, name, content):
start = operator.call('/operator/site-videos/uploads', {'name': name, 'size': len(content)})
uid = start['id']
url = operator.call(f'/operator/uploads/{uid}/parts/1', {})['url']
with urlopen(Request(url, data=content, method='PUT'), timeout=30) as response:
assert response.status == 200
operator.call(f'/operator/uploads/{uid}/complete', {})
wait_scan(operator, uid, operator=True)
return uid
def run():
client = Client()
client.call('/session')
with db.connect() as c:
assert not c.execute("SELECT 1 FROM dtf_local.site_videos WHERE id='sala'").fetchone(), \
'The isolated test catalog entry is already configured'
ids = []
keys = []
try:
client.call('/operator/site-videos/sala', {'enabled': True}, expected=401)
operator = client.operator_client or Client()
# Client.call(operator=True) signs in and forwards to its own client.
client.call('/operator/site-videos', operator=True)
operator = client.operator_client
video = upload(operator, 'LOCAL-VIDEO.mp4', VIDEO)
captions = upload(operator, 'LOCAL-VIDEO.vtt', CAPTIONS)
ids = [video, captions]
operator.call('/operator/site-videos/sala', {'upload_id': video,
'captions_id': captions, 'product': 'file', 'enabled': True})
published = client.call('/site/videos')['videos']
entry = next(row for row in published if row['id'] == 'sala')
assert entry['product'] == 'file'
assert entry['captions'] == '/api/site/videos/sala/captions'
with urlopen(entry['src'], timeout=30) as response:
assert response.read() == VIDEO
with urlopen(Request(BASE + entry['captions'], headers=with_host()), timeout=30) as response:
assert response.headers['Content-Type'].startswith('text/vtt')
assert response.read() == CAPTIONS
operator.call('/operator/site-videos/sala', {'upload_id': video,
'captions_id': captions, 'product': 'file', 'enabled': False})
assert not any(row['id'] == 'sala' for row in client.call('/site/videos')['videos'])
print('PASS: Gestão publishes a scanned video, signed media and same-origin VTT; hiding removes it from the Site')
finally:
with db.connect() as c:
row = c.execute("DELETE FROM dtf_local.site_videos WHERE id='sala' RETURNING video_key,captions_key").fetchone()
if row:
keys.extend(key for key in row.values() if key)
if ids:
sources = c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s) RETURNING object_key',
(ids,)).fetchall()
keys.extend(row['object_key'] for row in sources)
for key in keys:
storage.client.delete_object(Bucket=storage.bucket, Key=key)
if __name__ == '__main__':
run()

View File

@@ -17,7 +17,7 @@ class PrumoReportTests(unittest.TestCase):
}
started = datetime(2026, 11, 5, 14, 0, tzinfo=timezone.utc)
return {'snapshot': {'items': [item]}, 'print_files': [{
'item_index': 0, 'created_at': started, 'finished_at': started + timedelta(seconds=41),
'item_index': 0, 'status': 'ready', 'created_at': started, 'finished_at': started + timedelta(seconds=41),
'detail': {'format': 'png', 'dpi': 300, 'parts': [
{'from_cm': '0', 'to_cm': '15'}, {'from_cm': '15', 'to_cm': '16'}]},
}]}
@@ -27,7 +27,7 @@ class PrumoReportTests(unittest.TestCase):
text = '\n'.join(lines)
self.assertIn('Chegou CDR, era PDF por dentro', text)
self.assertIn('PDF → PNG 300 DPI', text)
self.assertIn('Veio em 96 DPI, ampliado para 300', text)
self.assertIn('Resolução detectada: 96 DPI', text)
self.assertIn('3 pontos < 2 mm — cliente aceitou', text)
self.assertIn('2 artes, 1 girada', text)
self.assertIn('Menor traço 6 px → C2', text)
@@ -42,6 +42,17 @@ class PrumoReportTests(unittest.TestCase):
self.assertIn('3 pontinhos', text)
self.assertIn('C2', text)
self.assertIn('C1', text)
self.assertIn('será preparado', text)
self.assertNotIn('foi ampliada', text)
def test_unfinished_job_does_not_claim_a_conversion_or_background_check(self):
order = self.order()
order['print_files'] = [{'item_index': 0, 'status': 'manual', 'detail': {}}]
lines = report(order, {'u1': {'name': 'arte.pdf', 'original_name': 'arte.cdr'}})
text = '\n'.join(lines)
self.assertIn('Arquivo exige preparo manual', text)
self.assertNotIn('PDF → PNG', text)
self.assertNotIn('Fundo transparente', text)
if __name__ == '__main__':

View File

@@ -15,7 +15,7 @@ class SpeedFiguresTests(unittest.TestCase):
rows = {row['key']: row for row in speed_figures(site, generation, card)}
self.assertEqual(rows['page']['average'], 1.5)
self.assertEqual(rows['page']['p95'], 3.0)
self.assertEqual(rows['upload']['unit'], 'MB/s')
self.assertEqual(rows['upload']['unit'], 's/MB')
self.assertEqual(rows['analysis']['average'], 12.0)
self.assertEqual(rows['montage']['p95'], 9.0)
self.assertEqual(rows['print']['average'], 90)

View File

@@ -0,0 +1,38 @@
"""A paid treatment needs a designer-prepared final before the print queue.
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.treatment_gate_test
"""
from app.core import db
from tests.print_file_test import artwork, loose_item, paid_order, wait_print
from tests.smoke_test import Client, upload_bytes
def run():
client = Client()
client.call('/session')
original = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-ORIGINAL.png')
order = paid_order(client, loose_item(original, copies=1))
_, generated = wait_print(client, order['id'], 'ready')
# The local price is normally zero. Mark this paid fixture as having bought
# treatment to exercise the production gate, not the checkout price rule.
with db.connect() as c:
c.execute("""UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{treatment}',
'{"cents":990,"hours":24}'::jsonb) WHERE id=%s""", (order['id'],))
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': generated['upload_id']}],
'note': 'Gerado pelo Prumo'}, operator=True)
blocked = client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True, expected=409)
assert 'Tratamento pago' in blocked['detail'], blocked
prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id'])
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}],
'note': 'PNG tratado pelo designer'}, operator=True)
client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True)
print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue')
if __name__ == '__main__':
run()

View File

@@ -447,7 +447,7 @@
}
if (quote.status==='pending_review') {
message((await ready).environment==='local'
? 'Arquivos enviados. No Kanban, confira metragem e nota e aprove a cotação '+draftId.slice(0,8)+'.'
? 'Arquivos enviados. No Kanban, confira a metragem e os arquivos e aprove a cotação '+draftId.slice(0,8)+'.'
: 'Arquivos enviados. Nossa equipe está conferindo a cotação '+draftId.slice(0,8)+'; o valor final aparece aqui em seguida.');
} else if (quote.status==='approved') {
if ((await ready).payment_provider === 'mercadopago') {
@@ -526,7 +526,7 @@
titulo.insertAdjacentHTML('afterbegin', icone('okCirculo'));
box.append(titulo,
node('p','Recebemos seu pedido e ele já está na produção. Você acompanha cada etapa em Meus pedidos.'),
node('p','O Prumo está preparando o arquivo de impressão. Em geral leva até 1 min por 10 m; o card aparece em Meus pedidos quando fica pronto.'));
node('p','Seu pedido já aparece em Meus pedidos. O Prumo está preparando o arquivo de impressão; você pode acompanhar o andamento por lá.'));
button('Ver meus pedidos',()=>location.assign('/conta/pedidos?order='+quote.order.id),box);
actions.append(box);
}

View File

@@ -717,7 +717,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<span class="chip2">Franca · SP · envio em até 24 h</span>
</div>
<h1>A gente encaixa sua folha e você paga <em>menos metro</em></h1>
<p>Mande a arte, veja a nota e a folha montada antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.</p>
<p>Mande a arte, confira a folha montada e veja o preço antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.</p>
<div class="hero2-cta">
<a href="/#envio" class="btn-laranja">Enviar minha arte <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></a>
<span>Sem cadastro · preço em segundos</span>
@@ -736,7 +736,7 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
<div class="hf-num">
<div><span>Metragem</span><b>0,60 m</b></div>
<div><span>Nota da arte</span><b class="verde">92</b></div>
<div><span>Conferência</span><b class="verde">Inclusa</b></div>
<div><span>Preço do metro</span><b class="laranja" data-preco="file">R$ 19,90</b></div>
</div>
</div>
@@ -745,7 +745,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<section class="etapas2"><div class="w">
<div><span>1</span><div><b>Envie a arte</b><p>PNG ou PDF, conforme o produto. Sem cadastro.</p></div></div>
<div><span>2</span><div><b>Veja nota e montagem</b><p>A folha e o preço aparecem na hora.</p></div></div>
<div><span>2</span><div><b>Confira a montagem</b><p>A folha e o preço aparecem na hora.</p></div></div>
<div><span>3</span><div><b>Pague na hora</b><p>Cartão de crédito ou PIX, na própria página.</p></div></div>
<div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
</div></section>
@@ -776,7 +776,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cards-cab">
<div><div class="et">Escolha o produto</div>
<h2>Qual é o seu caso?</h2></div>
<p>Preço único por produto. A nota da arte aparece na tela para você entender o seu arquivo; ela não muda o preço.</p>
<p>Preço único por produto. Você confere a resolução e a montagem antes de pagar.</p>
</div>
<div class="escolha">
<button class="ec f" data-modo="file">
@@ -864,14 +864,13 @@ h2 em{font-style:normal;color:var(--laranja)}
<details>
<summary>Dicas para o seu arquivo</summary>
<ul>
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a nota máxima</li>
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a resolução ideal</li>
<li class="s"><b>O tamanho manda mais que o arquivo.</b> A mesma arte passa
em 20 cm e não passa em 40. Reduzir um pouco costuma subir a nota</li>
em 20 cm e não passa em 40. Reduzir um pouco costuma melhorar a resolução</li>
<li class="s"><b>Larguras parecidas rendem mais.</b> Se as suas artes têm
medidas próximas, cabem mais por fileira e a folha encolhe</li>
</ul>
<p class="obs2">A nota não muda o preço do metro: ela serve para você
entender o seu arquivo.</p>
<p class="obs2">A resolução não muda o preço do metro; ela mostra se o arquivo pode sair nítido.</p>
</details>
<details>
@@ -893,8 +892,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
para nós — e sai serrilhado no filme do mesmo jeito</li>
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
cada imagem dentro da folha, uma por uma. Se a sua arte é boa, é onde a nota
aparece com mais precisão</li>
cada imagem dentro da folha, uma por uma. É onde a conferência
de resolução fica mais precisa</li>
<li class="a"><b>PDF grande.</b> Sem UserUnit, a página passa do limite de 508 cm
do formato; divida a folha ou mande PNG. Envie um PDF de uma página por folha.</li>
<li class="a"><b>TIFF, PSD, AI e CDR</b> a gente aceita, mas ninguém consegue
@@ -1036,7 +1035,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cp"><label>WhatsApp <span class="obr" aria-hidden="true">*</span></label>
<input id="fZap" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="15" placeholder="(16) 99999-9999">
<span class="err" id="eZap"></span></div>
<div class="cp larga"><label>E-mail para a nota <span class="obr" aria-hidden="true">*</span></label>
<div class="cp larga"><label>E-mail para o pedido <span class="obr" aria-hidden="true">*</span></label>
<input id="fMail" aria-required="true" autocomplete="off" type="email" placeholder="voce@empresa.com.br">
<span class="err" id="eMail"></span></div>
</div>
@@ -1093,7 +1092,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<h4>Prova antes de imprimir</h4>
<label class="provaOp"><input type="checkbox" id="fProva">
<span><b>Quero aprovar uma prova antes de imprimir</b>
Imprimimos até 30 cm da sua folha e mandamos a foto pelo WhatsApp. O resto só é impresso
Imprimimos até 15 cm por classe de contração e mandamos a foto pelo WhatsApp. O resto só é impresso
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
</div>
@@ -1148,7 +1147,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="info2-preco">
<div class="et">Preço</div>
<h2>Preço único por produto</h2>
<p>A nota da arte aparece na tela antes de você pagar, para você entender o seu arquivo. Ela não muda o preço. Preço do metro:</p>
<p>O preço por metro depende do produto. Você confere a arte e a montagem antes de pagar:</p>
<table>
<thead><tr><th scope="col">Produto</th><th scope="col">Têxtil 57 cm</th><th scope="col">UV 27 cm</th></tr></thead>
<tbody>

View File

@@ -611,6 +611,15 @@ label.fopt{cursor:pointer;user-select:none}
/* Pages (redesign, steps 5 to 7): Pagamentos, Números, Integrações and
Usuários, made of panels with a head and a table or a list. */
.page:not([hidden]){padding:24px 28px 40px;display:flex;flex-direction:column;gap:20px;animation:fadeUp .35s cubic-bezier(.2,.8,.2,1) both}
.siteVideoList{display:flex;flex-direction:column;padding:0 18px 18px}
.siteVideoRow{display:flex;flex-direction:column;gap:12px;padding:18px 0;border-top:1px solid var(--ln)}
.siteVideoHeading{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.siteVideoHeading b{font-size:14px}
.siteVideoFields{display:flex;align-items:end;gap:12px;flex-wrap:wrap}
.siteVideoField{display:flex;flex-direction:column;gap:6px;min-width:175px;font-size:12px;color:var(--tx2)}
.siteVideoField input,.siteVideoField select{max-width:240px;min-height:38px;color:var(--tx);background:var(--sf);border:1px solid var(--ln2);border-radius:8px;padding:6px}
.siteVideoToggle{display:flex;align-items:center;gap:7px;min-height:38px;font-size:13px}
.siteVideoError{width:100%;margin:0;color:var(--bad);font-size:12px}
.page>*{flex-shrink:0}
.pagetools{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.panel{background:var(--sf);border:1px solid var(--ln);border-radius:12px}

View File

@@ -141,9 +141,9 @@
<table class="table"><tbody id="stats-rework-printers"></tbody></table>
<h3>Aguardando autorização</h3><ul class="plainlist" id="stats-rework-pending"></ul></details></section>
<section class="panel clip s6"><div class="phead"><h2>Tempo em cada etapa</h2><span class="hint tip-l" tabindex="0" data-tip="Tempo mediano por pedido: quem voltou para a etapa soma cada passagem. O tempo em Aguardando contato não conta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span><button class="btn right" id="edit-stage-limits" type="button" hidden>Editar tempos</button></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Mediana</th><th scope="col" class="r">Aceitável</th><th scope="col" class="r">Estouros</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table></section>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">Aceitável</th><th scope="col" class="r">Estouros</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table></section>
</div>
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (MB/s), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section>
<section id="tab-users" class="page" hidden>
@@ -164,6 +164,11 @@
</section>
<section id="tab-integrations" class="page" hidden>
<div class="panel" id="integrations"></div>
<section class="panel clip" id="site-videos-panel" hidden>
<div class="phead"><h2>Vídeos do Site</h2></div>
<p class="phint">Envie MP4 ou WebM e legenda VTT. Escolha o produto para o vídeo flutuante e publique quando estiver pronto.</p>
<div id="site-videos-list" class="siteVideoList"></div>
</section>
<section class="panel clip" id="event-log">
<div class="phead"><h2>Envios ao Tiny</h2><div class="pfilters" id="event-filters"></div></div>
<div class="scrollbox log"><table class="table"><thead><tr><th scope="col">Quando</th><th scope="col">Pedido</th><th scope="col">Evento</th><th scope="col">Resultado</th></tr></thead><tbody id="events"></tbody></table></div>

View File

@@ -684,7 +684,7 @@ const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
// The room marks "Prova OK" once it is checked; without it, no Finalizado.
const PROOF_ABOVE_METRES=10;
const PROOF_RULE='Até 30 cm, do trecho de traço mais fino, um pedaço de cada arte diferente; no máximo 3 provas por pedido, sem cobrança.';
const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.';
const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES;
const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent;
// The proof card (app/proof.py): the order's own card waits outside the queue
@@ -1549,6 +1549,12 @@ function contractionList(order){
return box;
}
function approveParts(order,main=true){
if(order.snapshot.treatment){
const approve=button('Enviar arte tratada',()=>treatDialog(order),'btn lg'+(main?' pri':''));
approve.dataset.treat='';
return {text:'Tratamento pago: o designer precisa enviar o PNG tratado de cada item antes da fila.',
files:null,approve,extra:[]};
}
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
const files=node('div',undefined,'files');
if(all)ready.forEach((r,i)=>r.files.forEach((f,k)=>files.append(fileRow(f.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source]+
@@ -1576,7 +1582,10 @@ function nextBox(order){
const moveBtn=(to,label,className='btn pri lg')=>{const b=button(label||'Mover para '+board.states[to],()=>move(order,to),className);b.dataset.move=to;return b;};
if(waitingProof(order)){
title='Aguardando prova do #'+order.proof_card.number;
note('O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.');
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
note(manual?'O Prumo não abriu o original. Prepare o PNG completo deste pedido; a prova será gerada automaticamente a partir dele.'
:'O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.');
if(manual&&may('produce'))main.push(button('Preparar arquivo para a prova',()=>finalDialog(order,readyFinals(order)),'btn pri lg'));
return composeNext(title,body,main,more);
}
// A proof card in Revisão waits for its answer (Dropstar, 2026-11-03).
@@ -1614,13 +1623,23 @@ function nextBox(order){
}
if(st==='rec'&&order.proof_parent){
title=finalDone(order)?'Conferir a prova':'Gerando a prova';
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
const manual=(order.print_files||[]).some(r=>r.status==='manual');
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual
?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.'
:'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg'));
if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg'));
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
more.push(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn lg'));
return composeNext(title,body,main,more);
}
if(st==='rec'||st==='cor'){
if(st==='rec'&&order.snapshot.treatment&&!treatmentDone(order)&&finalDone(order)){
title='Enviar a arte tratada';
note('O tratamento foi pago. Envie o PNG tratado de cada item antes de colocar o pedido na fila.');
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
return composeNext(title,body,main,more);
}
if(!finalDone(order)&&trans.includes('tra')){
if(st==='rec')title='Aprovar o arquivo final';
// The designer approves every file (D-16); the others see it waiting.
@@ -1750,6 +1769,7 @@ function pickupDialog(order){
const isPickup=order=>order.snapshot.freight?.service==='pickup';
// ---- Final files: the file each item is printed from, approved by an operator.
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index));
const FINAL_SOURCE={correction:'correção do cliente',generated:'arquivo gerado',original:'original'};
const FINAL_TITLE={correction:'Correção do cliente',generated:'Gerado pelo sistema',original:'Original do cliente'};
// What the system generated for an item: one PNG, or the parts of a film
@@ -1917,11 +1937,13 @@ function treatDialog(order){
const file=row.input.files[0];
if(file)return {file};
const kept=(order.finals||[]).filter(f=>f.item_index===index).map(f=>f.upload_id);
return {ids:kept.length?kept:ready[index]?[ready[index].upload_id]:[]};
const treated=order.treated?.items?.includes(index);
return {ids:order.snapshot.treatment&&!treated?[]:
kept.length?kept:ready[index]?ready[index].files.map(f=>f.upload_id):[]};
});
if(!plan.some(p=>p.file))throw new Error('Escolha o arquivo tratado.');
const empty=plan.findIndex(p=>!p.file&&!p.ids.length);
if(empty>=0)throw new Error('O item '+(empty+1)+' ainda não tem arquivo: suba a arte tratada dele também.');
if(empty>=0)throw new Error('O item '+(empty+1)+' ainda não tem arte tratada: envie o PNG dele também.');
const refs=[];
for(const [index,p] of plan.entries()){
if(!p.file){refs.push(...p.ids.map(upload_id=>({item_index:index,upload_id})));continue;}
@@ -2621,15 +2643,15 @@ async function loadStats(){
// Orders; when some came back to the stage, how many times it was entered.
const passed=st?plural(st.orders,'pedido','pedidos')+(st.passages>st.orders?', '+st.passages+' passagens':''):'nenhum';
name.append(node('span',passed,'sub'));
tr.append(name,node('td',st?duration(st.median_hours):'—','r strong'),
tr.append(name,node('td',st?duration(st.average_hours):'—','r strong'),
node('td',limit?duration(limit.hours):'—','r'),
node('td',late.count?String(late.count)+(late.today?' · '+late.today+' hoje':''):'—','r'),
node('td',now?plural(now.orders,'pedido','pedidos')+', o mais antigo há '+duration(now.oldest_hours):'nenhum','muted'));
return tr;}));
// Speed (item 0.12): average and p95 of what the customer feels.
const secs=v=>v==null?'—':v<60?Math.max(1,Math.round(v))+' s':Math.round(v/60)+' min';
const speedFmt=s=>s.unit==='MB/s'
? (v=>v==null?'—':v.toFixed(1).replace('.',',')+' MB/s')
const speedFmt=s=>s.unit==='s/MB'
? (v=>v==null?'—':v.toFixed(1).replace('.',',')+' s/MB')
: (v=>s.unit==='s'?secs(v):String(v));
$('stats-speed').replaceChildren(...(data.speed||[]).map(s=>{
const tr=node('tr'),fmt=speedFmt(s);
@@ -3208,7 +3230,53 @@ function renderEvents(){
// Integrações: the print room's folder for whoever produces, what is on and off
// for the managers, and the buttons, details and the Tiny log for the superadmin.
const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();};
const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();if(may('manage'))await loadSiteVideos();};
async function loadSiteVideos(){
const host=$('site-videos-list'),panel=$('site-videos-panel');
panel.hidden=!may('manage');
if(panel.hidden)return;
const data=await api('/site-videos');
host.replaceChildren(...data.videos.map(video=>{
const row=node('div',undefined,'siteVideoRow');
const heading=node('div',undefined,'siteVideoHeading');
heading.append(node('b',video.title),node('span',video.enabled?'Publicado':'Rascunho','pill'+(video.enabled?' ok':'')));
const videoInput=node('input');videoInput.type='file';videoInput.accept='.mp4,.webm,video/mp4,video/webm';
const captionsInput=node('input');captionsInput.type='file';captionsInput.accept='.vtt,text/vtt';
const videoLabel=node('label',undefined,'siteVideoField');
videoLabel.append(node('span','Vídeo · '+(video.video_name||'nenhum arquivo')),videoInput);
const captionsLabel=node('label',undefined,'siteVideoField');
captionsLabel.append(node('span','Legenda · '+(video.captions_name||'nenhuma legenda')),captionsInput);
const product=node('select');product.setAttribute('aria-label','Produto do vídeo '+video.title);
for(const [value,title] of [['','Só na categoria DTF'],['file','Arquivo por metro'],
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']]){
const option=node('option',title);option.value=value;product.append(option);
}
product.value=video.product||'';
const productLabel=node('label',undefined,'siteVideoField');productLabel.append(node('span','Vídeo flutuante'),product);
const enabled=node('input');enabled.type='checkbox';enabled.checked=video.enabled;
const publish=node('label',undefined,'siteVideoToggle');publish.append(enabled,node('span','Publicado no Site'));
const errorMessage=node('p',undefined,'siteVideoError');errorMessage.setAttribute('role','alert');
const save=button('Salvar vídeo',async()=>{
save.disabled=true;
errorMessage.textContent='';
try{
let uploadId=video.upload_id,captionsId=video.captions_id;
if(videoInput.files[0])uploadId=await dtfUpload(videoInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
product:product.value||null,enabled:enabled.checked});
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
await loadSiteVideos();
}catch(error){errorMessage.textContent=error.message;save.disabled=false;}
},'btn');
const fields=node('div',undefined,'siteVideoFields');
fields.append(videoLabel,captionsLabel,productLabel,publish,save,errorMessage);
row.append(heading,fields);return row;
}));
}
// A row with only its name, state and summary, for whoever may not change it.
const integRow=o=>may('integrations')?integration(o):integration({name:o.name,state:o.state,tone:o.tone,summary:o.summary});
let mpCheck=null;

View File

@@ -147,7 +147,7 @@ function carrinho(){
// The residue dots the customer accepted printing (Dropstar, 2026-10-29).
residueAccepted:residuosAceitos(),
// The thinnest stroke and its contraction class (item 9), for the room.
...tracoDoItem(),
...tracoDoItem(null,layout),
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m'};
pintaPedido();
previa();

View File

@@ -555,8 +555,8 @@ function pintaFolha(){
'<span class="progT">'+textoProgresso(x)+'</span>'
: x.semAnalise
? '<div class="progF"><b>Não conseguimos conferir esta folha.</b> '+escapeHTML(x.semAnalise)+
'. Seguimos sem a nota, e a conferência é feita na mão. Se quiser a nota, exporte a mesma '+
'folha em <b>PNG</b>, que a conferência é bem mais leve.</div>'
'. A conferência será feita na sala. Para conferir a resolução aqui, exporte a mesma '+
'folha em <b>PNG</b>.</div>'
: '';
// A small thumbnail made once: the list is rebuilt on every change, and the
// full preview of a file up to 150 MB would be re-parsed each time.

View File

@@ -66,7 +66,7 @@ function tracoDoItem(lista,layout){
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
return {strokePx:fino.traco.px, strokeClass:fino.traco.classe, strokeChoice:avisado?'measured':null,
proofSourceIndex:fino.index,
proofYFraction:fracaoNoFilme(lista?layout:montagemLayout,fino.index,fino.traco.proofYFraction||0)};
proofYFraction:fracaoNoFilme(layout||montagemLayout,fino.index,fino.traco.proofYFraction||0)};
}
// Fecha a medida da conferência quando não há mais arquivo sendo lido (0.12).
function marcaTempos(){
@@ -109,7 +109,7 @@ function avaliar(){
const ausentes=folhas.filter(f=>!f.an);
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
mostraNota([
['av','Sem nota · '+exts+' sem análise completa',
['av','Conferência manual · '+exts+' sem análise completa',
ausentes.length+' de '+folhas.length+' folha(s) precisam de conferência manual'],
['fix','Alguém abre seu arquivo','a conferência é feita na mão, na sala']
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
@@ -154,7 +154,7 @@ function avaliar(){
n1(larguraFilme())+' cm. Reduza a medida solicitada antes de continuar.'};
const sem=artes.filter(a=>!a.cm).length;
if(sem) return {pronto:false, falta:'Informe a largura de '+sem+' arte'+(sem>1?'s':'')+
' para ver a nota e o preço.'};
' para ver a conferência e o preço.'};
// Item 4: a dot under 2 mm in a loose artwork holds the order like on a
// sheet, until the customer erases it or accepts printing that artwork so.
const lendoArte=artes.find(a=>a.lendoArte);
@@ -171,7 +171,7 @@ function avaliar(){
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
mostraNota([
['ok','Montagem por nossa conta','5 mm garantidos'],
[cls(pior),'Pior arte em '+pior+'%',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
[cls(pior),'Resolução das artes',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
],media,artes.length+' arte'+(artes.length>1?'s':''),
'folha montada por nós · '+fmtM(metros)+' m');
return {pronto:true};
@@ -189,7 +189,7 @@ function agendaAvaliacao(){
if(!el) return;
if(r.pronto){
el.className='aoVivo pronto';
el.innerHTML='<span class="pt2"></span><span><b>Nota e preço calculados.</b> '+
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço calculados.</b> '+
'Confira abaixo e feche o pedido.</span>';
}else{
el.className='aoVivo';

View File

@@ -71,16 +71,18 @@ section+section{border-top:0}
.videoCard span{font-size:14.5px;line-height:1.4;color:var(--fraco)}
.videoCard em{margin-top:auto;font-style:normal;font-size:12.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--laranja-escuro)}
.videoCard[data-soon="1"]{cursor:default;opacity:.72}
.videoFloat{position:fixed;right:22px;bottom:22px;z-index:70;width:min(280px,calc(100vw - 32px));border-radius:14px;overflow:hidden;background:var(--preto);box-shadow:0 14px 40px rgba(3,6,11,.35)}
.videoCard[data-soon="1"]:hover{border-color:var(--linha)}
.videoFloat{position:fixed;right:max(22px,env(safe-area-inset-right));bottom:max(22px,env(safe-area-inset-bottom));z-index:70;width:min(280px,calc(100vw - 32px));border-radius:14px;overflow:hidden;background:var(--preto);box-shadow:0 14px 40px rgba(3,6,11,.35)}
.videoFloat video{display:block;width:100%;height:auto;aspect-ratio:16/9;background:#000}
.videoFloat .vfClose{position:absolute;top:8px;right:8px;width:30px;height:30px;border:0;border-radius:999px;background:rgba(0,0,0,.62);color:#fff;font-size:18px;line-height:1;cursor:pointer}
.videoFloat .vfClose{position:absolute;top:8px;right:8px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.62);color:#fff;font-size:20px;line-height:1;cursor:pointer}
.videoFloat .vfLabel{padding:8px 12px;color:#fff;font-size:13px;line-height:1.3}
.videoFloat .vfLabel b{display:block;font-family:"Inter",sans-serif;font-size:14px}
.videoModal{position:fixed;inset:0;z-index:120;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(3,6,11,.78)}
.videoAberto{overflow:hidden}
.videoModal{position:fixed;inset:0;z-index:120;display:flex;align-items:center;justify-content:center;padding:max(24px,env(safe-area-inset-top)) max(24px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));background:rgba(3,6,11,.78)}
.videoModal[hidden]{display:none}
.videoModal .vmBox{position:relative;width:min(920px,100%);border-radius:16px;overflow:hidden;background:#000}
.videoModal video{display:block;width:100%;height:auto;max-height:82vh;background:#000}
.videoModal .vmClose{position:absolute;top:10px;right:10px;width:34px;height:34px;border:0;border-radius:999px;background:rgba(0,0,0,.65);color:#fff;font-size:20px;cursor:pointer}
.videoModal .vmClose{position:absolute;top:10px;right:10px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.65);color:#fff;font-size:22px;cursor:pointer}
@media(max-width:900px){.videosGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:620px){.videosGrid{grid-template-columns:1fr}.videos2{padding:36px 0}}

View File

@@ -1,9 +1,4 @@
/* Site DTF — vídeos da categoria DTF e o vídeo flutuante por produto (frente 4).
O espaço e o player ficam prontos agora; os seis arquivos entram quando a
Dropstar gravar. Para publicar um vídeo, coloque o MP4/WebM em web/videos/
e preencha `src` (e, se houver, `captions`) abaixo. `product` liga o vídeo
ao modo do produto: file, avulsa, uvfile ou uv. */
/* Site DTF — the public catalog is filled by videos published in Gestão. */
const VIDEOS = [
{id: 'subindo', title: 'Subindo a arte pelo celular',
desc: 'Do primeiro toque ao preço, sem instalar nada.', product: null,
@@ -32,6 +27,7 @@ function videoElement(video, {controls = false} = {}) {
el.playsInline = true;
el.preload = 'metadata';
if (controls) el.controls = true;
if (controls) el.tabIndex = 0;
if (video.captions) {
const track = document.createElement('track');
track.kind = 'captions';
@@ -44,54 +40,68 @@ function videoElement(video, {controls = false} = {}) {
return el;
}
// The category strip: six cards. A card without a file says it is being made
// instead of opening a broken player.
(function videosSection() {
// The category shows only videos with a published file.
function videosSection() {
const grid = document.getElementById('videosGrid');
if (!grid) return;
for (const video of VIDEOS) {
const published=VIDEOS.filter(video=>video.src);
document.getElementById('videos').hidden=!published.length;
grid.replaceChildren();
for (const video of published) {
const card = document.createElement('button');
card.type = 'button';
card.className = 'videoCard';
card.dataset.video = video.id;
if (!video.src) card.dataset.soon = '1';
const play = document.createElement('span');
play.className = 'vcPlay';
play.textContent = video.src ? '▶' : '…';
play.textContent = '▶';
const title = document.createElement('b');
title.textContent = video.title;
const desc = document.createElement('span');
desc.textContent = video.desc;
const note = document.createElement('em');
note.textContent = video.src ? 'Assistir · 30 s' : 'Em produção';
note.textContent = 'Assistir · 30 s';
card.append(play, title, desc, note);
if (!video.src) {
card.setAttribute('aria-disabled', 'true');
} else {
card.addEventListener('click', () => openVideo(video));
}
card.addEventListener('click', () => openVideo(video, card));
grid.append(card);
}
})();
}
videosSection();
// The category player, opened from a card.
let videoModal = null;
function openVideo(video) {
let videoReturnFocus = null;
function openVideo(video, trigger=document.activeElement) {
videoReturnFocus = trigger;
if (!videoModal) {
videoModal = document.createElement('div');
videoModal.className = 'videoModal';
videoModal.setAttribute('role', 'dialog');
videoModal.setAttribute('aria-modal', 'true');
videoModal.setAttribute('aria-label', 'Vídeo: '+video.title);
videoModal.hidden = true;
videoModal.innerHTML = '<div class="vmBox"><button type="button" class="vmClose" aria-label="Fechar vídeo">×</button></div>';
videoModal.addEventListener('click', event => {
if (event.target === videoModal || event.target.closest('.vmClose')) closeVideo();
});
videoModal.addEventListener('keydown', event => {
if (event.key === 'Escape') { event.preventDefault(); closeVideo(); return; }
if (event.key !== 'Tab') return;
const focusable = [...videoModal.querySelectorAll('button,video[controls]')];
const first=focusable[0], last=focusable[focusable.length-1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
});
document.body.append(videoModal);
}
const box = videoModal.querySelector('.vmBox');
box.querySelectorAll('video').forEach(el => el.remove());
const player = videoElement(video, {controls: true});
player.addEventListener('timeupdate', () => { if (player.currentTime >= 30) player.pause(); });
box.append(player);
videoModal.hidden = false;
videoModal.setAttribute('aria-label', 'Vídeo: '+video.title);
videoModal.querySelector('.vmClose').focus();
player.play().catch(() => {});
document.documentElement.classList.add('videoAberto');
}
@@ -100,6 +110,8 @@ function closeVideo() {
videoModal.querySelectorAll('video').forEach(el => { el.pause(); el.removeAttribute('src'); el.load(); });
videoModal.hidden = true;
document.documentElement.classList.remove('videoAberto');
videoReturnFocus?.focus();
videoReturnFocus = null;
}
// A floating, muted 30 s video on each product page. It only appears when the
@@ -136,7 +148,7 @@ function syncFloatingVideo() {
const title = document.createElement('b');
title.textContent = video.title;
const desc = document.createElement('span');
desc.textContent = 'Mudo · com legenda · 30 s';
desc.textContent = video.captions ? 'Mudo · com legenda · 30 s' : 'Mudo · 30 s';
label.append(title, desc);
floating.append(player, close, label);
document.body.append(floating);
@@ -145,3 +157,11 @@ function syncFloatingVideo() {
addEventListener('dtf-page-changed', syncFloatingVideo);
syncFloatingVideo();
window.siteVideosReady=fetch('/api/site/videos').then(response=>response.ok?response.json():null).then(data=>{
for(const published of data?.videos||[]){
const video=VIDEOS.find(item=>item.id===published.id);
if(video){video.src=published.src;video.captions=published.captions;video.product=published.product;}
}
videosSection();
syncFloatingVideo();
}).catch(()=>{});