feat: review photo or video in Revisão (front 2)
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 6m4s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m6s

In Revisão the card gets "Revisar": a photo or a video of up to 30 s of
the printed sheet, from the computer's or the phone's camera in the
browser, or a file already recorded. It is attached to the order as
DTF-<n>-revisao-<seq> with when and who, kept 180 days, and copied by
the computers with the order folders to Kanban/Revisões/. A photo needs
1600 px on its longer side. An order above 1 m cannot reach Finalizado
without one. In Finalizado the customer's order page shows the photo.

The Revisor, Gestão and the administrators take it (capability
"inspect"). Dialogs opened from a card's face or the board (Revisar,
Editar tempos) now show over the page when the order panel is closed;
inside the closed panel they were invisible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 11:39:15 -03:00
parent 5aafd9ee91
commit b280e0cfa6
18 changed files with 725 additions and 22 deletions

View File

@@ -501,10 +501,18 @@ def detail(oid: UUID, identity=Depends(owner)):
# only a correction's reason is written for the customer.
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall()
# The review photos only once the order is Finalizado; a video stays
# on the Kanban card (app/reviews.py).
photos = c.execute('''SELECT r.id,u.name,r.created_at FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE r.order_id=%s AND r.kind='photo' ORDER BY r.seq''', (oid,)).fetchall() \
if row['state'] == 'fin' else []
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
'state': row['state'], 'version': row['version'],
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
'files': file_rows(c,oid)}
'files': file_rows(c,oid),
'reviews': [{'id': photo['id'], 'name': photo['name'], 'created_at': photo['created_at']}
for photo in photos]}
@router.post('/api/customer/orders/{oid}/corrections')
def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)):

View File

@@ -18,7 +18,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can,
login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files
from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt, unpaid
from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt, reviews, unpaid
from .. import tiny
from ..payments import release_files
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
@@ -338,8 +338,11 @@ def with_print_files(c, orders):
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
# Every order's review photos and videos, in one query like the print files.
review_rows = reviews.by_order(c, ids)
for order in orders:
order['hot'] = hot.get(order['id'])
order['reviews'] = review_rows.get(str(order['id']), [])
child = children.get(order['id'])
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
@@ -1177,6 +1180,11 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.')
if body.state == 'fin' and not row.get('parent_id') and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
# Above 1 m the review photo is the evidence the sheet was checked; a
# proof card is no sale and skips this (app/reviews.py).
if (body.state == 'fin' and not back and not row.get('parent_id')
and reviews.required(row['snapshot']) and not reviews.has_photo(c, uid)):
raise HTTPException(409, 'Pedido acima de 1 m: tire a foto da revisão antes de finalizar.')
if body.state == 'cor':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
# Who moved it, and on which machine: the one it goes to print on, or
@@ -1856,9 +1864,19 @@ def queue_folder(body: FolderSync, user=Depends(can('print'))):
due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL
AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s)
ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else []
# The review photos and videos to copy into Revisões/ (front 2). Without
# `since`, the last 30 days, so a new computer catches up.
since = body.since or datetime.now(timezone.utc) - timedelta(days=30)
review_rows = c.execute('''SELECT r.id,r.order_id,o.number,r.upload_id,u.name
FROM dtf_local.order_reviews r
JOIN dtf_local.orders o ON o.id=r.order_id
JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE o.cancelled_at IS NULL AND r.created_at>=%s ORDER BY r.created_at,r.id''', (since,)).fetchall()
return {'files': files,
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held},
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due]}
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due],
'reviews': [{'id': r['id'], 'order': str(r['order_id']), 'number': r['number'],
'upload_id': str(r['upload_id']), 'name': r['name']} for r in review_rows]}
@router.get('/api/operator/uploads/{uid}/download')

98
app/api/reviews.py Normal file
View File

@@ -0,0 +1,98 @@
"""Routes of the review photo or video (Fase 2, front 2, app/reviews.py)."""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from .. import reviews
from ..core import db
from ..core.auth import audit, can, operator, owner
from ..core.models import StrictModel
from ..runtime import operator_identity, owned_order, storage, upload_row
from ..scanning import require_clean
from .uploads import begin_upload
router = APIRouter()
class ReviewUploadStart(StrictModel):
"""The same shape as UploadStart, without its artwork-extension rule: a
review carries a photo or a video, not an artwork."""
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
size: int = Field(gt=0, strict=True)
class ReviewAdd(StrictModel):
upload_id: UUID
@router.post('/api/operator/orders/{uid}/reviews/uploads')
def start_review_upload(uid: UUID, body: ReviewUploadStart, user=Depends(can('inspect'))):
reviews.kind_of(body.name, body.size)
return begin_upload(body, session_id=operator_identity(user))
@router.post('/api/operator/orders/{uid}/reviews')
def add_review(uid: UUID, body: ReviewAdd, user=Depends(can('inspect'))):
with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if order.get('cancelled_at'):
raise HTTPException(409, 'Pedido cancelado.')
if order['state'] != 'rev':
raise HTTPException(409, 'A revisão só entra com o pedido em Revisão.')
upload = upload_row(c, body.upload_id, operator_identity(user), lock=True)
if not upload['complete']:
raise HTTPException(409, 'Espere o envio terminar.')
require_clean(upload)
kind, ext, width, height = reviews.check(storage, upload)
row = reviews.attach(c, order, upload, kind, ext, width, height, user)
audit('order_review_added', order=str(uid), review=row['id'], kind=kind, operator=user)
return row
@router.post('/api/operator/orders/{uid}/reviews/{rid}/remove')
def remove_review(uid: UUID, rid: int, user=Depends(can('inspect'))):
with db.connect() as c:
order = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if order['state'] != 'rev':
raise HTTPException(409, 'A revisão só sai com o pedido ainda em Revisão.')
row = c.execute('DELETE FROM dtf_local.order_reviews WHERE id=%s AND order_id=%s RETURNING upload_id',
(rid, uid)).fetchone()
if not row:
raise HTTPException(404, 'Revisão não encontrada.')
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE id=%s', (row['upload_id'],))
audit('order_review_removed', order=str(uid), review=rid, operator=user)
return {'ok': True}
def _mime(name):
return reviews.FORMATS[name.rsplit('.', 1)[-1].lower()][1]
@router.get('/api/operator/orders/{uid}/reviews/{rid}/view')
def view_review(uid: UUID, rid: int, user=Depends(operator)):
with db.connect() as c:
row = c.execute('''SELECT r.kind,u.object_key,u.name FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id WHERE r.id=%s AND r.order_id=%s''',
(rid, uid)).fetchone()
if not row:
raise HTTPException(404, 'Revisão não encontrada.')
return {'url': storage.view(row['object_key'], _mime(row['name'])), 'name': row['name'], 'kind': row['kind']}
@router.get('/api/customer/orders/{oid}/reviews/{rid}/view')
def customer_view_review(oid: UUID, rid: int, identity=Depends(owner)):
with db.connect() as c:
owned_order(c, oid, identity)
row = c.execute('''SELECT u.object_key,u.name FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id
JOIN dtf_local.orders o ON o.id=r.order_id
WHERE r.id=%s AND r.order_id=%s AND o.state='fin' AND r.kind='photo' ''',
(rid, oid)).fetchone()
if not row:
raise HTTPException(404, 'Foto não encontrada.')
return {'url': storage.view(row['object_key'], _mime(row['name'])), 'name': row['name'], 'kind': 'photo'}

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, site_videos, uploads, users
from .api import artwork, customer, health, operator, orders, payments, quotes, reviews, 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, site_videos):
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews):
app.include_router(module.router)

View File

@@ -152,6 +152,9 @@ CAPABILITIES = {
# but the seller, who only views (D-30). It includes everyone who produces,
# and the operator, so an operator upload (artwork.py) takes it for its parts.
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
# The photo or video of the printed sheet in Revisão (Fase 2, front 2): who
# releases to Finalizado, and Gestão, which may stand in for them.
'inspect': {'superadmin', 'admin', 'gestao', 'revisor'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of

131
app/reviews.py Normal file
View File

@@ -0,0 +1,131 @@
"""The review photo or video of the printed sheet (Fase 2, front 2).
In Revisão the card gets "Revisar": the Revisor takes a photo or a short video
(up to 30 s) of the sheet with the computer's or the phone's camera in the
browser, or sends one already recorded. It is attached to the order as
DTF-<n>-revisao-<seq>.<ext>, with when and who (dtf_local.order_reviews), and
the computers with the order folders turned on copy it to Kanban/Revisões/.
An order above 1 m cannot reach Finalizado without a photo; a smaller one may.
Once the order is in Finalizado, the customer's order page shows the photos
(the "ready" notice links to it). Videos stay on the card.
Kept for REVIEW_KEEP_DAYS, longer than artwork: it is the evidence when a
customer says the sheet came out wrong.
"""
from decimal import Decimal
from fastapi import HTTPException
from . import grade_check
from .proof import billed_metres
PHOTO_MIN_PX = 1600 # the longer side; enough to read the footer
VIDEO_MAX_SECONDS = 30 # enforced by the recorder and the file check in the browser
PHOTO_MAX_BYTES = 30 * 1048576
VIDEO_MAX_BYTES = 150 * 1048576
REQUIRED_ABOVE_METRES = Decimal('1')
REVIEW_KEEP_DAYS = 180
FOLDER = 'Revisões'
# Extension -> (kind, MIME). HEIC is left out: browsers cannot show it.
FORMATS = {'jpg': ('photo', 'image/jpeg'), 'jpeg': ('photo', 'image/jpeg'),
'png': ('photo', 'image/png'), 'webp': ('photo', 'image/webp'),
'mp4': ('video', 'video/mp4'), 'webm': ('video', 'video/webm'),
'mov': ('video', 'video/quicktime')}
def file_name(number, seq, ext):
"""DTF-13-revisao-1.jpg: the name in the folder and on the card."""
return f'DTF-{number}-revisao-{seq}.{ext}'
FORMAT_MESSAGE = ('Use foto JPG, PNG ou WebP de até 30 MB, ou vídeo MP4, WebM ou MOV de até 150 MB.')
# What each extension must start with. MP4 and MOV share the ISO container:
# the "ftyp" box sits at byte 4.
SIGNATURES = {'jpg': (b'\xff\xd8\xff', 0), 'jpeg': (b'\xff\xd8\xff', 0),
'png': (b'\x89PNG\r\n\x1a\n', 0),
'webp': (b'WEBP', 8),
'mp4': (b'ftyp', 4), 'mov': (b'ftyp', 4),
'webm': (b'\x1a\x45\xdf\xa3', 0)}
def kind_of(name, size):
"""('photo' | 'video', mime, ext) for an accepted file, or HTTPException 422
with a Portuguese message naming the accepted formats and size limits."""
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
if ext not in FORMATS:
raise HTTPException(422, FORMAT_MESSAGE)
kind, mime = FORMATS[ext]
limit = PHOTO_MAX_BYTES if kind == 'photo' else VIDEO_MAX_BYTES
if size > limit:
raise HTTPException(422, FORMAT_MESSAGE)
return kind, mime, ext
def check(storage, upload):
"""Read the start of the stored file (a Range read, as grade_check.Files.head)
and confirm its signature matches the extension. For a photo, return its
(width, height) and refuse (422) when the longer side is below PHOTO_MIN_PX;
for a video, return (None, None). Returns (kind, ext, width, height)."""
kind, mime, ext = kind_of(upload['name'], upload['size'])
head = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'],
Range=f'bytes=0-{grade_check.HEAD_BYTES - 1}')['Body'].read()
# WebP is a RIFF container with its own form type, like the scanner's check.
if ext == 'webp':
matches = head[:4] == b'RIFF' and head[8:12] == b'WEBP'
else:
signature, offset = SIGNATURES[ext]
matches = head[offset:].startswith(signature)
if not matches:
raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.')
if kind == 'video':
return kind, ext, None, None
size = grade_check.image_size(head)
if not size or not all(size):
raise HTTPException(422, 'Não foi possível ler a foto.')
width, height = size
if max(width, height) < PHOTO_MIN_PX:
raise HTTPException(422, f'A foto precisa ter pelo menos {PHOTO_MIN_PX} px no lado maior para ler o rodapé.')
return kind, ext, width, height
def required(snapshot):
"""Whether finishing this order needs a review photo: billed metres above
REQUIRED_ABOVE_METRES (proof.billed_metres)."""
return billed_metres(snapshot) > REQUIRED_ABOVE_METRES
def has_photo(c, order_id):
return c.execute("SELECT 1 FROM dtf_local.order_reviews WHERE order_id=%s AND kind='photo' LIMIT 1",
(order_id,)).fetchone() is not None
def attach(c, order, upload, kind, ext, width, height, user):
"""Record the review: the next seq for the order, the upload renamed to
file_name(...) and kept REVIEW_KEEP_DAYS from now. Returns the new row."""
# The order's row is the lock: two reviewers adding at once take one seq
# each, never the same one.
c.execute('SELECT id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (order['id'],))
seq = c.execute('SELECT COALESCE(max(seq),0)+1 AS seq FROM dtf_local.order_reviews WHERE order_id=%s',
(order['id'],)).fetchone()['seq']
name = file_name(order['number'], seq, ext)
c.execute("UPDATE dtf_local.uploads SET name=%s, expires_at=now()+make_interval(days => %s) WHERE id=%s",
(name, REVIEW_KEEP_DAYS, upload['id']))
row = c.execute('''INSERT INTO dtf_local.order_reviews(order_id,seq,upload_id,kind,width,height,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(order['id'], seq, upload['id'], kind, width, height, user)).fetchone()
return {**row, 'name': name}
def by_order(c, order_ids):
"""{order_id (str): [ {id, seq, kind, name, width, height, created_by,
created_at}, ... ]} in seq order, for the board."""
if not order_ids:
return {}
rows = c.execute('''SELECT r.id,r.order_id,r.seq,r.kind,r.width,r.height,r.created_by,r.created_at,u.name
FROM dtf_local.order_reviews r JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE r.order_id=ANY(%s) ORDER BY r.order_id,r.seq''', (order_ids,)).fetchall()
out = {}
for row in rows:
out.setdefault(str(row['order_id']), []).append(
{key: row[key] for key in ('id', 'seq', 'kind', 'name', 'width', 'height', 'created_by', 'created_at')})
return out

View File

@@ -531,3 +531,18 @@ ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;
-- The Revisor's photo or short video of the printed sheet (Fase 2, front 2,
-- app/reviews.py): DTF-<n>-revisao-<seq>, the record of when and by whom it
-- was checked. A photo is required to finish an order above 1 m.
CREATE TABLE IF NOT EXISTS dtf_local.order_reviews (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
seq integer NOT NULL CHECK(seq >= 1),
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
kind text NOT NULL CHECK(kind IN ('photo','video')),
width integer, height integer,
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(order_id, seq)
);
CREATE INDEX IF NOT EXISTS order_reviews_order ON dtf_local.order_reviews(order_id);