diff --git a/app/adapters.py b/app/adapters.py index 4770628..3b5dbcd 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -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): diff --git a/app/api/artwork.py b/app/api/artwork.py index 8a49182..4941a03 100644 --- a/app/api/artwork.py +++ b/app/api/artwork.py @@ -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) diff --git a/app/api/operator.py b/app/api/operator.py index 12bce5b..104b660 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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)}, diff --git a/app/api/site_videos.py b/app/api/site_videos.py new file mode 100644 index 0000000..12fed7f --- /dev/null +++ b/app/api/site_videos.py @@ -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'}) diff --git a/app/app.py b/app/app.py index 5b8a40f..921a90a 100644 --- a/app/app.py +++ b/app/app.py @@ -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) diff --git a/app/printjobs.py b/app/printjobs.py index 1995479..0c16a3e 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -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 diff --git a/app/proof.py b/app/proof.py index 64e6b01..d3bb6be 100644 --- a/app/proof.py +++ b/app/proof.py @@ -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): diff --git a/app/prumo.py b/app/prumo.py index 924c865..9d807d4 100644 --- a/app/prumo.py +++ b/app/prumo.py @@ -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 ""} ' diff --git a/app/schema.sql b/app/schema.sql index 340a6da..b895eb2 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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') diff --git a/infra/nginx.conf.template b/infra/nginx.conf.template index b3cb4ff..190d882 100644 --- a/infra/nginx.conf.template +++ b/infra/nginx.conf.template @@ -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; diff --git a/infra/storage-lifecycle.json b/infra/storage-lifecycle.json index 18427cb..01b3696 100644 --- a/infra/storage-lifecycle.json +++ b/infra/storage-lifecycle.json @@ -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}}]} diff --git a/infra/storage-policy.json b/infra/storage-policy.json index b590f96..2f41dc4 100644 --- a/infra/storage-policy.json +++ b/infra/storage-policy.json @@ -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/*"]} ] } diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index 4e4ec1a..374e622 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -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'); diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index e59c9f4..f847829 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -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()'); diff --git a/tests/kanban_test.py b/tests/kanban_test.py index 4d443e0..8ed39dd 100644 --- a/tests/kanban_test.py +++ b/tests/kanban_test.py @@ -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 diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 21e6a53..a84b2b0 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -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') diff --git a/tests/site_video_test.py b/tests/site_video_test.py new file mode 100644 index 0000000..204cd1e --- /dev/null +++ b/tests/site_video_test.py @@ -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() diff --git a/tests/test_prumo.py b/tests/test_prumo.py index de2eca3..fb7cb9b 100644 --- a/tests/test_prumo.py +++ b/tests/test_prumo.py @@ -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__': diff --git a/tests/test_speed.py b/tests/test_speed.py index fe354b2..0e8d81e 100644 --- a/tests/test_speed.py +++ b/tests/test_speed.py @@ -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) diff --git a/tests/treatment_gate_test.py b/tests/treatment_gate_test.py new file mode 100644 index 0000000..4f34170 --- /dev/null +++ b/tests/treatment_gate_test.py @@ -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() diff --git a/web/checkout.js b/web/checkout.js index c9ad0f3..4d189a3 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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); } diff --git a/web/index.html b/web/index.html index a01db80..2dbfd7c 100644 --- a/web/index.html +++ b/web/index.html @@ -717,7 +717,7 @@ h2 em{font-style:normal;color:var(--laranja)} Franca · SP · envio em até 24 h
Mande a arte, veja a nota e a folha montada antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.
+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.
PNG ou PDF, conforme o produto. Sem cadastro.
A folha e o preço aparecem na hora.
A folha e o preço aparecem na hora.
Cartão de crédito ou PIX, na própria página.
Em Minha conta, com aviso no WhatsApp quando ficar pronto.
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.
+Preço único por produto. Você confere a resolução e a montagem antes de pagar.
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:
+O preço por metro depende do produto. Você confere a arte e a montagem antes de pagar:
| Produto | Têxtil 57 cm | UV 27 cm |
|---|
| Etapa | Mediana | Aceitável | Estouros | Agora |
|---|
| Etapa | Média | Aceitável | Estouros | Agora |
|---|
| Etapa | Média | p95 | Amostras |
|---|
Envie MP4 ou WebM e legenda VTT. Escolha o produto para o vídeo flutuante e publique quando estiver pronto.
+ +| Quando | Pedido | Evento | Resultado |
|---|