diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 5956799..af7ec52 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/customer.py b/app/api/customer.py index 17fb8ad..8342520 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -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)): diff --git a/app/api/operator.py b/app/api/operator.py index 8e675c1..6eae8b3 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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') diff --git a/app/api/reviews.py b/app/api/reviews.py new file mode 100644 index 0000000..7209989 --- /dev/null +++ b/app/api/reviews.py @@ -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'} diff --git a/app/app.py b/app/app.py index 921a90a..fd7b2af 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, 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) diff --git a/app/core/auth.py b/app/core/auth.py index d011d7c..032b297 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -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 diff --git a/app/reviews.py b/app/reviews.py new file mode 100644 index 0000000..c699416 --- /dev/null +++ b/app/reviews.py @@ -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--revisao-., 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 diff --git a/app/schema.sql b/app/schema.sql index ec787de..d2c31fb 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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--revisao-, 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); diff --git a/ops/launch_reset.py b/ops/launch_reset.py index 8fd8fc3..7ad9767 100644 --- a/ops/launch_reset.py +++ b/ops/launch_reset.py @@ -37,6 +37,7 @@ TABLES = [ # in an order the foreign keys allow ('order_files', 'arquivos finais e correções'), ('print_files', 'arquivos de impressão gerados'), ('outbox', 'envios ao Tiny e avisos'), + ('order_reviews', 'fotos e vídeos de revisão'), ('orders', 'pedidos'), ('payment_intents', 'tentativas de pagamento'), ('payment_events', 'avisos de pagamento'), diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index f847829..e1d5460 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -250,6 +250,24 @@ try{ await waitFor(async()=>(await savedFiles('1. Arte recebida')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Arte recebida',45000); assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.startsWith(early)),false); } + if(state==='fin'){ + // Above 1 m Finalizado needs the review photo (app/reviews.py). Take one + // with a canvas in the page and send it as the Revisor's dialog does. + const metres=await kanban.eval(`board.orders.find(o=>o.id==='${oid}').snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)`); + if(metres>1){ + await kanban.eval(`(async()=>{ + const order=board.orders.find(o=>o.id==='${oid}'); + const canvas=document.createElement('canvas');canvas.width=2000;canvas.height=1500; + const ctx=canvas.getContext('2d');ctx.fillStyle='#c04030';ctx.fillRect(0,0,2000,1500); + const blob=await new Promise(ok=>canvas.toBlob(ok,'image/jpeg',0.9)); + const file=new File([blob],'revisao.jpg',{type:'image/jpeg'}); + const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/reviews/uploads',scope:'operator:review:'+order.id+':browser',progress:()=>{}}); + await api('/orders/'+order.id+'/reviews',{upload_id:uid}); + await load(); + })()`); + await waitFor(()=>kanban.eval(`(board.orders.find(o=>o.id==='${oid}').reviews||[]).some(r=>r.kind==='photo')`),'review photo attached'); + } + } await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title); await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state); @@ -296,7 +314,7 @@ try{ await kanban.eval('syncFolder(true)'); await waitFor(async()=>!(await folders()).includes('3. Finalizado'),'old Finalizado folder removed',30000); const tree=await folders(); - for(const name of ['1. Arte recebida','2. Arte conferida','3. Imprimindo','4. Revisão','5. Finalizado','Recibos']) + for(const name of ['1. Arte recebida','2. Arte conferida','3. Imprimindo','4. Revisão','5. Finalizado','Recibos','Revisões']) assert.ok(tree.includes(name),name+' missing from '+tree.join(', ')); } } diff --git a/tests/review_media_test.py b/tests/review_media_test.py new file mode 100644 index 0000000..d5de77d --- /dev/null +++ b/tests/review_media_test.py @@ -0,0 +1,123 @@ +"""The review photo or video attached to an order in Revisão (Fase 2, front 2). + +Run against the local stack: +SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.review_media_test +""" +from io import BytesIO +from urllib.request import Request, urlopen +from uuid import uuid4 + +from PIL import Image + +from tests.smoke_test import (Client, approved_quote, final_png_bytes, item_spec, review_photo, + upload_bytes, wait_scan) + + +def jpeg(width, height): + out = BytesIO() + Image.new('RGB', (width, height), (190, 60, 50)).save(out, 'JPEG', quality=80) + return out.getvalue() + + +def run(): + customer = Client() + customer.call('/session') + original = upload_bytes(customer, b'LOCAL REVIEW ORIGINAL') + item = item_spec('file', '1.01', 0, original) + profile = {'cnpj': '11222333000181', 'zap': '11999999999', + 'mail': 'review-' + uuid4().hex[:8] + '@example.test'} + quote = customer.call('/quotes', {'request_key': str(uuid4()), 'customer': profile, + 'items': [item], 'freight': {'service': 'pickup'}}) + approved_quote(customer, quote, [item]) + order = customer.call('/orders/dev-paid', {'quote_id': quote['id']}) + oid, number = order['id'], order['number'] + + final = upload_bytes(customer, final_png_bytes('review final'), name='LOCAL-REVIEW-FINAL.png', order_id=oid) + version = customer.call('/operator/orders/' + oid + '/final-files', + {'version': 0, 'note': 'Conferido', + 'files': [{'item_index': 0, 'upload_id': final}]}, operator=True)['version'] + + machine = None + + def move(state, version): + nonlocal machine + body = {'state': state, 'version': version, 'reason': ''} + if state == 'imp': + if machine is None: + machine = customer.call('/operator/machines', + {'name': 'Review ' + uuid4().hex[:6], 'products': ['textil']}, + operator=True)['id'] + body['machine_id'] = machine + return customer.call('/operator/orders/' + oid + '/move', body, operator=True)['version'] + + for state in ('tra', 'imp', 'rev'): + version = move(state, version) + + def upload_raw(name, content): + start = customer.call('/operator/orders/' + oid + '/reviews/uploads', + {'name': name, 'size': len(content)}, operator=True) + uid = start['id'] + url = customer.call('/operator/uploads/' + uid + '/parts/1', {}, operator=True)['url'] + with urlopen(Request(url, data=content, method='PUT'), timeout=30) as response: + assert response.status == 200 + customer.call('/operator/uploads/' + uid + '/complete', {}, operator=True) + wait_scan(customer, uid, operator=True) + return uid + + def add_raw(uid, expected=200): + return customer.call('/operator/orders/' + oid + '/reviews', {'upload_id': uid}, + operator=True, expected=expected) + + # Above 1 m without a photo the order does not reach Finalizado. + customer.call('/operator/orders/' + oid + '/move', {'state': 'fin', 'version': version}, + operator=True, expected=409) + + # A photo below 1600 px on the longer side is refused. + small = upload_raw('LOCAL-SMALL.jpg', jpeg(800, 600)) + add_raw(small, expected=422) + + # The extension must match the content: a PNG named .jpg is refused. + fake = upload_raw('LOCAL-FAKE.jpg', final_png_bytes('fake')) + add_raw(fake, expected=422) + + # A real 2000x1500 JPEG becomes DTF--revisao-1.jpg. + row = review_photo(customer, oid) + assert row['seq'] == 1 and row['kind'] == 'photo', row + assert row['name'] == 'DTF-%d-revisao-1.jpg' % number, row + + board = customer.call('/operator/board', operator=True) + saved = next(o for o in board['orders'] if o['id'] == oid) + assert [(r['seq'], r['kind'], r['name']) for r in saved['reviews']] == [(1, 'photo', row['name'])], saved['reviews'] + + folder = customer.call('/operator/queue/folder', {'early': True}, operator=True) + entry = next(r for r in folder['reviews'] if r['upload_id'] == row['upload_id']) + assert entry['name'] == row['name'] and entry['order'] == oid and entry['number'] == number, entry + + # The customer sees no photo while the order is still in Revisão. + assert customer.call('/customer/orders/' + oid)['reviews'] == [] + + # A second review can be removed only while the order is in Revisão. + second = review_photo(customer, oid) + assert second['seq'] == 2, second + customer.call('/operator/orders/' + oid + '/reviews/' + str(second['id']) + '/remove', {}, + operator=True) + + # With the photo the order finishes, and the customer then sees it. + version = move('fin', version) + detail = customer.call('/customer/orders/' + oid) + assert detail['state'] == 'fin' + assert [(r['id'], r['name']) for r in detail['reviews']] == [(row['id'], row['name'])], detail['reviews'] + view = customer.call('/customer/orders/' + oid + '/reviews/' + str(row['id']) + '/view') + assert view['kind'] == 'photo' and view['name'] == row['name'] + with urlopen(view['url'], timeout=30) as response: + assert Image.open(BytesIO(response.read())).size == (2000, 1500) + + # Once Finalizado, a review can no longer be removed. + customer.call('/operator/orders/' + oid + '/reviews/' + str(row['id']) + '/remove', {}, + operator=True, expected=409) + + print('PASS: review photo upload, signature and size checks, the 1 m rule, the folder and the customer view') + + +if __name__ == '__main__': + run() diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 1ad46b2..19b6994 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -105,6 +105,26 @@ def upload_bytes(client, content, name='LOCAL-TEST.cdr', order_id=None, expected wait_scan(client,uid,operator,expected_scan) return uid +def review_photo(client, order_id): + """A 2000x1500 JPEG attached as the order's review photo, in Revisão. + + The same transport site_video_test uses: start the operator upload, PUT the + single part, complete it, wait for the scan, then POST the review.""" + from io import BytesIO + from PIL import Image + out=BytesIO() + Image.new('RGB',(2000,1500),(200,80,40)).save(out,'JPEG',quality=85) + content=out.getvalue() + start=client.call('/operator/orders/'+order_id+'/reviews/uploads', + {'name':'revisao.jpg','size':len(content)},operator=True) + uid=start['id'] + url=client.call('/operator/uploads/'+uid+'/parts/1',{},operator=True)['url'] + with urlopen(Request(url,data=content,method='PUT'),timeout=30) as response: + assert response.status==200 + client.call('/operator/uploads/'+uid+'/complete',{},operator=True) + wait_scan(client,uid,operator=True) + return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True) + def item_spec(mode, metres, grade, uid): film_width=27 if mode in ('uvfile','uv') else 57 length_cm=float(metres)*100 @@ -304,6 +324,8 @@ def run(): if machine is None: machine=client.call('/operator/machines',{'name':'Smoke '+uuid4().hex[:6],'products':['textil']},operator=True)['id'] body['machine_id']=machine + # Above 1 m Finalizado needs the review photo (app/reviews.py). + if state=='fin':review_photo(client,oid) moved=client.call('/operator/orders/'+oid+'/move',body,operator=True) version+=1;assert moved['version']==version client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409) @@ -315,6 +337,7 @@ def run(): client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409) back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True) assert back['state']=='rev';version+=1 + review_photo(client,oid) client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1 history=client.call('/operator/orders/'+oid+'/history',operator=True) assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back'] diff --git a/tests/users_test.py b/tests/users_test.py index 78284c0..5ee59a6 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -11,7 +11,7 @@ from psycopg.types.json import Jsonb from app import payments, proof from app.core import db -from tests.smoke_test import BASE, Client, with_host +from tests.smoke_test import BASE, Client, with_host, review_photo PASSWORD = 'senha-de-teste-123' @@ -203,7 +203,7 @@ def run(): 'password': PASSWORD}) reviewer = signed_in(emails['revisor']) me = reviewer.call('/operator/me') - assert me['can'] == ['deliver', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me + assert me['can'] == ['deliver', 'inspect', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403) assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''})['state'] == 'fin' @@ -274,6 +274,8 @@ def run(): version = su.call(f'/operator/orders/{long_o}/proof', {}, operator=True)['version'] board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']} assert board[str(long_o)]['proof_ok_at'] and board[str(long_o)]['proof_ok_by'] + # Above 1 m Finalizado also needs the review photo (app/reviews.py). + review_photo(su, str(long_o)) su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True) # Up to 10 m, nothing to wait for. with db.connect() as c: @@ -281,6 +283,8 @@ def run(): made.append((short_q, short_o)) c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (short_o,)) version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(short_o))['version'] + # 10 m is above the 1 m review photo rule just the same. + review_photo(su, str(short_o)) su.call(f'/operator/orders/{short_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True) # Asked for at checkout: the paid order arrives waiting for the customer's word. with db.connect() as c: diff --git a/tests/workflow_test.py b/tests/workflow_test.py index 59e4a03..97a52d3 100644 --- a/tests/workflow_test.py +++ b/tests/workflow_test.py @@ -2,7 +2,7 @@ import os from uuid import uuid4 from urllib.request import urlopen -from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register, final_png_bytes +from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register, final_png_bytes, review_photo def run(): customer=Client();other=Client();customer.call('/session');other.call('/session') @@ -111,7 +111,10 @@ def run(): assert treated()=={'items':[0],'by':operator_email}, treated() stats=customer.call('/operator/stats?days=7',operator=True)['treated'] assert stats['orders']>=1 and any(t['orders']>=1 for t in stats['by']), stats - for state in ('tra','imp','rev','fin'):version=move(state,version) + for state in ('tra','imp','rev','fin'): + # Above 1 m Finalizado needs the review photo (app/reviews.py). + if state=='fin':review_photo(customer,oid) + version=move(state,version) # In the queue the finals stay as approved. customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Too late'},operator=True,expected=409) detail=other.call('/customer/orders/'+oid) diff --git a/web/kanban.css b/web/kanban.css index c280dd1..dd4b6a8 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -273,6 +273,21 @@ main{padding:0} .card:focus-visible,.mini:focus-visible{outline:2px solid var(--acc);outline-offset:2px} .card-open{display:inline-flex;align-items:center;justify-content:center;gap:5px;align-self:flex-start;min-height:28px;padding:4px 8px;border:1px solid var(--ln2);border-radius:7px;background:var(--sf3);color:var(--tx);font:inherit;font-size:11px;font-weight:600;cursor:pointer} .card-open:hover,.card-open:focus-visible{border-color:var(--acc);color:var(--acc)} +.card-open-row{display:flex;flex-wrap:wrap;gap:6px} +/* A review photo or video: live camera, the preview, and the order's list. */ +.reviewcam{width:100%;aspect-ratio:16/9;object-fit:contain;background:var(--bg);border:1px solid var(--ln2);border-radius:10px;display:block} +.reviewpreview{width:100%;aspect-ratio:16/9;background:var(--bg);border:1px solid var(--ln2);border-radius:10px;overflow:hidden;display:flex;align-items:center;justify-content:center} +.reviewpreview img,.reviewpreview video{width:100%;height:100%;object-fit:contain;display:block} +.reviewcontrols{display:flex;flex-wrap:wrap;align-items:center;gap:8px} +.reviewcontrols label.btn{cursor:pointer} +.reviewtime{font-size:12px;color:var(--tx3);font-variant-numeric:tabular-nums} +.reviewmsg{flex:1;min-width:0;margin:0;font-size:13px;color:var(--tx2)} +.reviewmsg.bad{color:var(--bad)} +.reviewlist{display:flex;flex-direction:column;max-height:220px;overflow:auto;border-top:1px solid var(--ln)} +.reviewsec{padding-top:22px;border-top:1px solid var(--ln)} +.reviewrow{display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid var(--ln)} +.reviewopen{flex:1;min-width:0;padding:5px 2px;border:0;background:none;color:var(--tx);font:inherit;font-size:13px;text-align:left;cursor:pointer} +.reviewopen:hover,.reviewopen:focus-visible{color:var(--acc)} .ctop{display:grid;grid-template-columns:56px minmax(0,1fr);gap:12px;align-items:center} .thumb{width:56px;height:56px;border-radius:8px;padding:4px;border:0;box-shadow:inset 0 0 0 1px var(--ln);background:repeating-conic-gradient(var(--chka) 0 25%,var(--chkb) 0 50%) 0 0/8px 8px} .thumb img{transition:transform .5s cubic-bezier(.2,.8,.2,1)} diff --git a/web/kanban.js b/web/kanban.js index a2b48bc..d49d15d 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -142,6 +142,7 @@ const IC={ logout:'M8 3.25H3.75v13.5H8 M12 6.5l3.5 3.5-3.5 3.5 M15.5 10H7.5', printer:'M5.75 7.5V3h8.5v4.5 M5.75 14H3V7.5h14V14h-2.75 M5.75 11.25h8.5v5.75h-8.5z', eye:'M2.5 10s2.75-5.25 7.5-5.25S17.5 10 17.5 10s-2.75 5.25-7.5 5.25S2.5 10 2.5 10z '+C(10,10,2.25), + camera:'M2.75 6.5h3.25l1.25-2.5h5.5l1.25 2.5h3.25v9.5H2.75z '+C(10,11.25,2.75), edit:'M12.5 4l3.5 3.5L7.5 16H4v-3.5z M10.5 6l3.5 3.5', user:C(10,6.25,3.25)+' M3.75 17c.6-3.2 3.1-5 6.25-5s5.65 1.8 6.25 5', link:'M8.5 6.5H6a3.25 3.25 0 0 0 0 6.5h2.5 M11.5 6.5H14a3.25 3.25 0 0 1 0 6.5h-2.5 M7 9.75h6', @@ -262,6 +263,8 @@ const OLD_FOLDERS=['3. Finalizado']; const KEEP_FINISHED_DAYS=30; // The pickup receipts (item 14): the counter's print queue watches this one. const RECEIPTS_FOLDER='Recibos'; +// The review photos and videos (front 2), written once and never removed. +const REVIEWS_FOLDER='Revisões'; const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null, saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null}; @@ -324,7 +327,7 @@ function folderCard(){ : integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as pastas do fluxo pedem o Chrome ou o Edge.', actions:[act('Ligar',()=>setDownloads(true))],details:how}); }else if(!h){ - row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos nas pastas do fluxo, de 1. Arte recebida a 5. Finalizado, e o recibo de cada retirada em Recibos.', + row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos nas pastas do fluxo, de 1. Arte recebida a 5. Finalizado, o recibo de cada retirada em Recibos e as fotos da revisão em Revisões.', actions:[act('Escolher pasta',chooseFolder)], details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as pastas do fluxo e move o arquivo conforme o card anda. '+ 'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]}); @@ -338,7 +341,7 @@ function folderCard(){ ['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'], node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em '+STAGE_FOLDERS.rec+', passa para '+STAGE_FOLDERS.tra+' quando o card vai para lá '+ 'e fica lá enquanto imprime, vai para '+STAGE_FOLDERS.rev+' com o card e para '+STAGE_FOLDERS.fin+' quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'), - node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada.'), + node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada. As fotos da revisão vão para '+REVIEWS_FOLDER+' e não saem de lá.'), node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+ 'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+ 'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')], @@ -399,7 +402,7 @@ async function writeWhole(dir,name,source){ } const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true}); // The flow's folders exist from the moment the main one is chosen, empty or not. -const makeStageFolders=()=>Promise.all([...new Set([...Object.values(STAGE_FOLDERS),PRINTING_FOLDER,RECEIPTS_FOLDER])].map(stageDir)); +const makeStageFolders=()=>Promise.all([...new Set([...Object.values(STAGE_FOLDERS),PRINTING_FOLDER,RECEIPTS_FOLDER,REVIEWS_FOLDER])].map(stageDir)); // Remove a saved file from its folder; one already gone (someone took it) is fine. async function removeSaved(rec){ const dir=await stageDir(rec.folder); @@ -463,13 +466,13 @@ async function syncFolder(force=false){ const stages=FOLDER.mode==='folder'; const follows=stages?['rec','tra','imp','rev','fin','cor']:['tra']; const sig=board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at) - .map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(','); + .map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')+':'+(o.reviews?.length||0)).join(','); if(!force&&sig===FOLDER.lastSig)return; FOLDER.busy=true; try{ if(stages)await makeStageFolders(); - const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[]; - const {files,states,receipts=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null}); + const held=stages?[...new Set([...FOLDER.saved.values()].filter(r=>!r.review).map(r=>r.order).filter(Boolean))].slice(-1000):[]; + const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null}); // By file: an item over 15 m is several parts (item 13), each its own file. const wanted=new Map(files.map(f=>[f.upload_id,f])); const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; @@ -526,11 +529,26 @@ async function syncFolder(force=false){ await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res.body);printed++; }catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;} } + // The review photos and videos, once each, into Revisões/. They are never + // removed from there: the folder is the room's evidence of the check. + let reviewSaved=0; + if(stages)for(const review of reviews){ + const key='review:'+review.upload_id; + if(FOLDER.saved.has(key))continue; + FOLDER.status='Salvando revisão: '+review.name;paintFolder(); + const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view'); + const res=await fetch(view.url,{referrerPolicy:'no-referrer'}); + if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').'); + await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res.body); + FOLDER.saved.set(key,{order:review.order,name:review.name,review:true}); + FOLDER.last=new Date();await keepSaved();reviewSaved++; + } FOLDER.lastSig=sig;FOLDER.error=''; FOLDER.status=''; if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.'); if(hot)say('Gravados '+hot+' arquivo(s) na hot folder da máquina.'); if(printed)say(printed+' recibo(s) de retirada salvos em '+RECEIPTS_FOLDER+'.'); + if(reviewSaved)say(reviewSaved+' foto(s)/vídeo(s) de revisão salvos em '+REVIEWS_FOLDER+'.'); if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.'); if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.'); }catch(e){ @@ -1234,7 +1252,7 @@ function stageLimitsDialog(){ fields.push(field(STAGE_LABELS[state]+' (horas)',hours,state==='fin'?'Use 72 para 3 dias.':'')); fields.push(field('Responsável por '+STAGE_LABELS[state].toLowerCase(),who)); } - formDialog('Tempos aceitáveis por etapa',{host:$('drawer'),width:640,fields, + formDialog('Tempos aceitáveis por etapa',{host:dialogHost(),width:640,fields, note:'Amarelo ao passar do limite; vermelho no dobro.', onsave:async()=>{ const limits=Object.entries(inputs).map(([state,{hours,who}])=>({ @@ -1346,6 +1364,10 @@ $('filter-open').onclick=()=>phoneFilters(); // The panel's tab stays while the same order is open. let panelTab='order'; +// A dialog sits over the order's panel when it is open, and over the page +// when it is not: opened from a card's face or the board, inside the closed +// drawer it would be invisible. +const dialogHost=()=>$('drawer').hidden?document.body:$('drawer'); function openPanel(id){if(id!==openOrder)panelTab='order';openOrder=id;const order=board.orders.find(o=>o.id===id);$('drawer').hidden=false;renderPanel(order);renderBoard();} function closePanel(){ for(const m of [...MODALS])if(m.host===$('drawer'))m.close(); @@ -1687,9 +1709,18 @@ function nextBox(order){ :'Pedido acima de 10 m: imprima a prova, confira e marque Prova OK antes de rodar o resto.')+' '+PROOF_RULE); const p=proofBtn('btn pri lg');if(p)main.push(p); }else{ - title='Conferir a folha impressa'; - note('Confira cores, recorte e a folha inteira contra o arquivo.'); - if(can('fin'))main.push(moveBtn('fin','Liberar para Finalizado'));else cannot(); + // Above 1 m the photo is required to finish (app/reviews.py): the main + // button takes it instead of releasing the order. + const hasPhoto=(order.reviews||[]).some(review=>review.kind==='photo'); + if(!order.proof_parent&&orderMetres(order)>1&&!hasPhoto){ + title='Tire a foto da revisão'; + note('Pedido acima de 1 m: tire a foto da revisão antes de finalizar.'); + if(may('inspect'))main.push(button('Revisar',()=>reviewDialog(order),'btn pri lg'));else cannot(); + }else{ + title='Conferir a folha impressa'; + note('Confira cores, recorte e a folha inteira contra o arquivo.'); + if(can('fin'))main.push(moveBtn('fin','Liberar para Finalizado'));else cannot(); + } } fixBtn(); }else if(st==='fin'){ @@ -1856,8 +1887,169 @@ function checkButton(order,className='btn'){ function cardOpenAction(order){ const action=button('Abrir arquivo',()=>openCheck(order),'card-open'); action.prepend(svgIcon(IC.eye||IC.file,'i s')); + // In Revisão the Revisor also has the photo/video on the card's face, beside + // the file. The click is stopped by button(), as on "Abrir arquivo". + if(order.state==='rev'&&!order.cancelled_at&&may('inspect')){ + const review=button('Revisar',()=>reviewDialog(order),'card-open'); + review.prepend(svgIcon(IC.camera,'i s')); + const row=node('span',undefined,'card-open-row');row.append(action,review); + return row; + } return action; } +// "Revisar" (Fase 2, front 2): the sheet's photo or a video of up to 30 s, +// taken here with the computer's or the phone's camera, or a file already +// recorded. The server names it DTF--revisao- and keeps it 180 days. +const REVIEW_VIDEO_MAX=30; +const reviewClock=s=>Math.floor(s/60)+':'+String(s%60).padStart(2,'0'); +function reviewDialog(order){ + const host=dialogHost(); + const video=node('video');video.className='reviewcam';video.muted=true;video.playsInline=true;video.autoplay=true; + video.setAttribute('aria-label','Pré-visualização da câmera'); + const timer=node('span','0:00 / 0:30','reviewtime');timer.setAttribute('aria-live','polite'); + const controls=node('div',undefined,'reviewcontrols'); + const photoBtn=node('button','Tirar foto','btn pri');photoBtn.type='button';photoBtn.setAttribute('aria-label','Tirar foto');photoBtn.setAttribute('autofocus',''); + const videoBtn=node('button','Gravar vídeo','btn');videoBtn.type='button';videoBtn.setAttribute('aria-label','Gravar vídeo'); + const input=node('input');input.type='file';input.className='vh'; + input.accept='image/jpeg,image/png,image/webp,video/mp4,video/webm,video/quicktime'; + const fileLabel=node('label',undefined,'btn');fileLabel.tabIndex=0; + fileLabel.append(svgIcon(IC.upload,'i m'),'Enviar arquivo',input); + const preview=node('div',undefined,'reviewpreview');preview.hidden=true; + const status=node('p','','reviewmsg');status.setAttribute('role','status');status.setAttribute('aria-live','polite'); + const save=node('button','Salvar revisão','btn pri');save.type='button';save.disabled=true; + const cancel=node('button','Cancelar','btn ghost right');cancel.type='button'; + controls.append(photoBtn,videoBtn,fileLabel); + let stream=null,recorder=null,recordTimer=null,chunks=[],ready=null,objectUrl=null,closed=false,recording=false,recordStart=0; + const fail=text=>{status.textContent=text;status.classList.add('bad');}; + const clear=()=>{status.textContent='';status.classList.remove('bad');}; + const endStream=()=>{ + if(recordTimer){clearInterval(recordTimer);recordTimer=null;} + if(stream){stream.getTracks().forEach(track=>track.stop());stream=null;} + }; + const cleanup=()=>{ + closed=true; + if(recorder&&recorder.state!=='inactive'){try{recorder.stop();}catch(_){}} + endStream(); + if(objectUrl){URL.revokeObjectURL(objectUrl);objectUrl=null;} + }; + function showReady(file,kind){ + ready={file,kind}; + endStream(); + video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true; + if(objectUrl)URL.revokeObjectURL(objectUrl); + objectUrl=URL.createObjectURL(file); + preview.replaceChildren(); + if(kind==='video'){ + const shot=node('video');shot.controls=true;shot.playsInline=true;shot.src=objectUrl; + shot.setAttribute('aria-label','Pré-visualização do vídeo gravado');preview.append(shot); + }else{ + const shot=node('img');shot.src=objectUrl;shot.alt='Pré-visualização da foto';preview.append(shot); + } + preview.hidden=false;save.disabled=false;clear();save.focus(); + } + function checkDuration(file){ + return new Promise((resolve,reject)=>{ + const probe=document.createElement('video');probe.preload='metadata'; + const url=URL.createObjectURL(file); + probe.onloadedmetadata=()=>{ + const seconds=probe.duration;URL.revokeObjectURL(url); + if(Number.isFinite(seconds)&&seconds>REVIEW_VIDEO_MAX+0.2) + reject(new Error('O vídeo tem mais de 30 segundos. Grave um de até 30 s ou envie outro menor.')); + else resolve(); + }; + probe.onerror=()=>{URL.revokeObjectURL(url);resolve();}; + probe.src=url; + }); + } + function stopRecording(){if(recorder&&recorder.state!=='inactive')recorder.stop();} + photoBtn.onclick=()=>{ + clear(); + const width=video.videoWidth,height=video.videoHeight; + if(!width||!height){fail('A câmera ainda não está pronta. Espere um instante.');return;} + const canvas=document.createElement('canvas');canvas.width=width;canvas.height=height; + canvas.getContext('2d').drawImage(video,0,0,width,height); + canvas.toBlob(blob=>{ + if(!blob){fail('Não foi possível tirar a foto.');return;} + showReady(new File([blob],'revisao.jpg',{type:'image/jpeg'}),'photo'); + },'image/jpeg',0.9); + }; + videoBtn.onclick=()=>{ + clear(); + if(recording){stopRecording();return;} + if(!stream){fail('A câmera não está disponível. Envie um arquivo.');return;} + const options=['video/mp4','video/webm;codecs=vp9','video/webm']; + const mime=(window.MediaRecorder&&options.find(type=>MediaRecorder.isTypeSupported(type)))||''; + try{recorder=new MediaRecorder(stream,mime?{mimeType:mime}:undefined);} + catch(_){fail('Este navegador não grava vídeo. Envie um arquivo.');return;} + const type=recorder.mimeType||mime||'video/webm'; + chunks=[];recording=true;recordStart=Date.now(); + recorder.ondataavailable=event=>{if(event.data&&event.data.size)chunks.push(event.data);}; + recorder.onstop=()=>{ + recording=false;videoBtn.textContent='Gravar vídeo'; + if(recordTimer){clearInterval(recordTimer);recordTimer=null;} + if(closed)return; + const blob=new Blob(chunks,{type});chunks=[]; + if(!blob.size){fail('Não foi possível gravar o vídeo.');return;} + showReady(new File([blob],'revisao.'+(type.includes('mp4')?'mp4':'webm'),{type}),'video'); + }; + recorder.start();videoBtn.textContent='Parar'; + const paint=()=>{ + const elapsed=Math.min(REVIEW_VIDEO_MAX,Math.floor((Date.now()-recordStart)/1000)); + timer.textContent=reviewClock(elapsed)+' / '+reviewClock(REVIEW_VIDEO_MAX); + if(elapsed>=REVIEW_VIDEO_MAX)stopRecording(); + }; + paint();recordTimer=setInterval(paint,250); + }; + input.onchange=async()=>{ + const file=input.files[0];if(!file)return; + clear(); + const name=file.name.toLowerCase(); + const isVideo=file.type.startsWith('video/')||/\.(mp4|webm|mov)$/.test(name); + const isPhoto=file.type.startsWith('image/')||/\.(jpe?g|png|webp)$/.test(name); + if(!isVideo&&!isPhoto){input.value='';fail('Escolha uma foto JPG, PNG ou WebP, ou um vídeo MP4, WebM ou MOV.');return;} + if(isVideo){ + try{await checkDuration(file);}catch(error){input.value='';fail(error.message);return;} + if(closed)return; + showReady(file,'video'); + }else showReady(file,'photo'); + }; + fileLabel.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();input.click();}}; + cancel.onclick=()=>m.close(); + save.onclick=async()=>{ + if(!ready)return; + save.disabled=true;clear();status.textContent='Enviando '+ready.file.name+'…'; + try{ + const uid=await dtfUpload(ready.file,{api,startPath:'/orders/'+order.id+'/reviews/uploads', + scope:'operator:review:'+order.id,progress:text=>{if(!closed)status.textContent=text;}}); + if(closed)return; + await api('/orders/'+order.id+'/reviews',{upload_id:uid}); + m.close(); + say('Revisão salva no pedido #'+order.number+'.'); + await load(); + }catch(error){ + if(closed)return; + fail(error.message);save.disabled=false; + } + }; + const m=modal('Revisão do #'+order.number,{host,width:640, + text:'Tire uma foto ou grave um vídeo de até 30 s da folha impressa, ou envie um arquivo.', + body:[video,controls,timer,preview],foot:[status,cancel,save],onclose:cleanup}); + (async()=>{ + try{ + if(!navigator.mediaDevices?.getUserMedia)throw new Error('sem câmera'); + stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'environment', + width:{ideal:1920},height:{ideal:1080}},audio:false}); + if(closed){endStream();return;} + video.srcObject=stream; + await video.play().catch(()=>{}); + photoBtn.focus(); + }catch(_){ + endStream();video.hidden=true;photoBtn.hidden=true;videoBtn.hidden=true;timer.hidden=true; + fail('Câmera indisponível neste computador. Envie um arquivo.'); + fileLabel.focus(); + } + })(); +} async function openCheck(order){ const {files}=await api('/orders/'+order.id+'/view'); if(!files.length){say('Ainda não há arquivo para abrir.',true);return;} @@ -1962,12 +2154,49 @@ function treatDialog(order){ paint(); })(); } +// The reviews recorded on the order: what was checked, when and by whom. A +// photo opens in the viewer; a video cannot, so it opens in a new tab. In +// Revisão a reviewer may remove one. +function reviewSection(order){ + if(!order.reviews?.length)return null; + const box=node('section',undefined,'reviewsec');box.setAttribute('aria-label','Revisões'); + const info=node('div',undefined,'iinfo'); + info.append(node('span','Revisões','lbl'),node('h3',plural(order.reviews.length,'revisão','revisões'))); + const list=node('div',undefined,'reviewlist'); + for(const review of order.reviews){ + const row=node('div',undefined,'reviewrow'); + const open=node('button',undefined,'reviewopen');open.type='button'; + open.append(node('span','Revisão · '+(review.kind==='video'?'vídeo':'foto')+' · '+ + when(review.created_at)+' · '+review.created_by)); + open.onclick=async()=>{ + try{ + const view=await api('/orders/'+order.id+'/reviews/'+review.id+'/view'); + if(review.kind==='photo'&&window.openViewer)openViewer([{name:view.name,picture:view.url}],{title:'Revisão #'+order.number}); + else{const link=node('a');link.href=view.url;link.target='_blank';link.rel='noopener noreferrer';link.click();} + }catch(error){say(error.message,true);} + }; + row.append(open); + if(order.state==='rev'&&may('inspect')){ + const remove=node('button','Remover','btn quiet');remove.type='button'; + remove.onclick=async()=>{ + if(!await ask('Remover esta revisão?','Ela some do pedido e o arquivo deixa de ficar guardado.','Remover revisão',{tone:'red',host:$('drawer')}))return; + await api('/orders/'+order.id+'/reviews/'+review.id+'/remove',{}); + say('Revisão removida do pedido #'+order.number+'.');await load(); + }; + row.append(remove); + } + list.append(row); + } + info.append(list);box.append(info); + return box; +} // Pedido: the items, then who, where and on which machine, then any rework. function orderView(order){ const view=node('div',undefined,'tview'); const s=order.snapshot; s.items.forEach((item,index)=>view.append(itemCard(order,item,index))); view.append(orderFacts(order)); + const reviews=reviewSection(order);if(reviews)view.append(reviews); if(order.reworks?.length)view.append(reworkSection(order)); return view; } @@ -2326,7 +2555,7 @@ function avatar(u,className='ava'){ // "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py). const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro']; const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNN'],['Pedir correção','YYYNNNN'],['Puxar da fila e imprimir','YNNYNNN'], - ['Liberar para Finalizado','YNNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'], + ['Liberar para Finalizado','YNNNYNN'],['Foto da revisão','YYNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'], ['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNV'],['Pedido pago fora do site','YYNNNNN'],['Prova OK ou reprovada','YYNNNYN'],['Cancelar pedido','YYNNNNY'], ['Abrir retrabalho','NYNNNNN'],['Autorizar retrabalho','YNNNNNN'],['Usuários e máquinas','YNNNNNN']]; let usersData=null; diff --git a/web/portal.css b/web/portal.css index 4f67888..b72df2a 100644 --- a/web/portal.css +++ b/web/portal.css @@ -134,6 +134,8 @@ button:disabled{opacity:.6;cursor:default} .arquivo>div{flex:1;min-width:0;display:flex;flex-direction:column} .arquivo b{overflow-wrap:anywhere;font-size:15px} .arquivo span{font-size:14px;color:var(--fraco)} +.fotoPed{display:flex;flex-direction:column;align-items:flex-start;gap:10px;margin-bottom:14px} +.fotoPed img{display:block;max-width:100%;height:auto;border:1px solid var(--linha);border-radius:var(--raio2)} .correcaoForm{display:flex;flex-direction:column;padding:16px;border-radius:var(--raio2);background:var(--cinza)} .correcaoForm label{margin:10px 0 5px;font-size:14px;font-weight:600;color:var(--texto2)} .correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical} diff --git a/web/portal.js b/web/portal.js index 7e7161c..f36e2a0 100644 --- a/web/portal.js +++ b/web/portal.js @@ -246,6 +246,18 @@ async function details(id,container,criado){ } container.append(arq); } + if(order.state==='fin'&&order.reviews?.length){ + const sec=node('div',null,'secao fotoPedSec');sec.append(node('h4','Foto do seu pedido')); + for(const review of order.reviews){ + const view=await api('/customer/orders/'+id+'/reviews/'+review.id+'/view'); + const row=node('div',null,'fotoPed'); + const img=node('img');img.alt='Foto da folha impressa do pedido #'+order.number; + img.loading='lazy';img.src=view.url; + const link=node('a','Baixar foto','bSec');link.href=view.url;link.download=view.name;link.target='_blank';link.rel='noopener noreferrer'; + row.append(img,link);sec.append(row); + } + container.append(sec); + } if(order.state==='cor'){ const form=node('form',null,'secao correcaoForm');form.append(node('h4','Enviar arte corrigida')); const inputs=order.snapshot.items.map((item,index)=>{