"""Minhas folhas: a customer with an account keeps a built cart item and asks for it again, edits it or deletes it later (Rodada 5, B9). The item is stored as the Site sent it, with the local files already replaced by the uploads they came from. Only the uploads it names are checked: they must belong to the account, arrived complete and still be within the 30 days an upload is kept (app/runtime.py upload_row). """ import json import mimetypes import re from datetime import datetime, timedelta, timezone from decimal import Decimal from typing import Literal from uuid import UUID, uuid4 from fastapi import APIRouter, Depends, HTTPException from pydantic import Field, field_validator from psycopg.types.json import Jsonb from ..core import db from ..core.auth import audit, owner from ..core.models import StrictModel from ..runtime import storage from .customer import account_row router = APIRouter() LIMIT = 50 ITEM_BYTES = 256 * 1024 KEEP_DAYS = 30 EXPIRED = 'Os arquivos desta folha venceram. Envie de novo para pedir.' UNAVAILABLE = 'Algum arquivo desta folha não está mais disponível. Envie de novo antes de salvar.' NO_FILES = 'A folha precisa ter os arquivos enviados.' PICTURE = re.compile(r'^data:image/(?:webp|png|jpeg);base64,') class SavedSheet(StrictModel): name: str = Field(min_length=1, max_length=80) mode: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] metres: Decimal = Field(gt=0, le=1000) item: dict picture: str | None = Field(default=None, max_length=300000) @field_validator('picture') @classmethod def picture_is_data_url(cls, value): if value is not None and not PICTURE.match(value): raise ValueError('Invalid picture') return value def saved_files(item): """The `savedFiles` lists of an item, in order: the item's and each part's.""" for group in [item.get('savedFiles')] + [part.get('savedFiles') for part in item.get('partes') or [] if isinstance(part, dict)]: if group is not None: yield group def upload_ids(item): """The uploads an item names, in the order they appear, without duplicates.""" ids = [] for group in saved_files(item): if not isinstance(group, list): raise HTTPException(422, NO_FILES) for file in group: if not isinstance(file, dict) or not file.get('upload_id'): raise HTTPException(422, NO_FILES) try: ids.append(UUID(str(file['upload_id']))) except ValueError: raise HTTPException(422, NO_FILES) if not ids: raise HTTPException(422, NO_FILES) if len(ids) > 200: raise HTTPException(422, 'Esta folha tem mais de 200 arquivos.') if len(set(ids)) != len(ids): raise HTTPException(422, 'Esta folha tem arquivos repetidos.') return ids def file_types(item): """upload_id -> the MIME type the Site recorded for it, when it did.""" types = {} for group in saved_files(item): for file in group or []: if isinstance(file, dict) and file.get('upload_id') and isinstance(file.get('type'), str) and file['type']: types[str(file['upload_id'])] = file['type'] return types def uploads_of(c, ids): if not ids: return [] return c.execute('SELECT id,owner,name,size,object_key,complete,purged_at,expires_at,created_at ' 'FROM dtf_local.uploads WHERE id=ANY(%s)', (ids,)).fetchall() def sheet_view(c, row): """The stored sheet with what the page needs to show it: whether every file still exists and is within its 30 days, when the first one ends, and the total size.""" ids = list(row['uploads']) rows = uploads_of(c, ids) by_id = {upload['id']: upload for upload in rows} files = [by_id[uid] for uid in ids if uid in by_id] now = datetime.now(timezone.utc) cutoff = now - timedelta(days=KEEP_DAYS) available = len(files) == len(ids) and all( upload['complete'] and not upload['purged_at'] and upload['expires_at'] > now and upload['created_at'] >= cutoff for upload in files) until = min((upload['created_at'] for upload in files), default=None) return {'id': row['id'], 'name': row['name'], 'mode': row['mode'], 'metres': row['metres'], 'picture': row['picture'], 'created_at': row['created_at'], 'used_at': row['used_at'], 'files_until': until + timedelta(days=KEEP_DAYS) if until else None, 'available': available, 'total_size': sum(upload['size'] for upload in files), 'item': row['item']} def owned_sheet(c, sid, identity, lock=False): row = c.execute('SELECT * FROM dtf_local.saved_sheets WHERE id=%s AND account=%s' + (' FOR UPDATE' if lock else ''), (sid, identity)).fetchone() if not row: raise HTTPException(404, 'Folha não encontrada.') return row def require_available(c, row): view = sheet_view(c, row) if not view['available']: raise HTTPException(409, EXPIRED) return view def touch(c, row): return c.execute('UPDATE dtf_local.saved_sheets SET used_at=now() WHERE id=%s RETURNING *', (row['id'],)).fetchone() @router.post('/api/account/sheets') def save_sheet(body: SavedSheet, identity=Depends(owner)): size = len(json.dumps(body.item, ensure_ascii=False, separators=(',', ':')).encode()) if size > ITEM_BYTES: raise HTTPException(422, 'Esta folha é grande demais para salvar.') ids = upload_ids(body.item) with db.connect() as c: account_row(c, identity, lock=True) rows = uploads_of(c, ids) cutoff = datetime.now(timezone.utc) - timedelta(days=KEEP_DAYS) if len(rows) != len(ids) or any(upload['owner'] != identity or not upload['complete'] or upload['purged_at'] or upload['created_at'] < cutoff for upload in rows): raise HTTPException(409, UNAVAILABLE) used = c.execute('SELECT count(*) AS n FROM dtf_local.saved_sheets WHERE account=%s', (identity,)).fetchone()['n'] if used >= LIMIT: raise HTTPException(409, 'Você já tem 50 folhas salvas. Exclua uma antes.') c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at + interval '30 days') " 'WHERE id=ANY(%s) AND purged_at IS NULL', (ids,)) sid = uuid4() c.execute('''INSERT INTO dtf_local.saved_sheets(id,account,name,mode,metres,item,uploads,picture) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (sid, identity, body.name, body.mode, body.metres, Jsonb(body.item), ids, body.picture)) audit('saved_sheet_created', account=str(identity), sheet=str(sid), files=len(ids), c=c) return {'id': sid} @router.get('/api/account/sheets') def list_sheets(identity=Depends(owner)): with db.connect() as c: account_row(c, identity) rows = c.execute('SELECT * FROM dtf_local.saved_sheets WHERE account=%s ORDER BY created_at DESC', (identity,)).fetchall() return {'sheets': [sheet_view(c, row) for row in rows]} @router.delete('/api/account/sheets/{sid}') def delete_sheet(sid: UUID, identity=Depends(owner)): with db.connect() as c: account_row(c, identity) owned_sheet(c, sid, identity, lock=True) c.execute('DELETE FROM dtf_local.saved_sheets WHERE id=%s', (sid,)) audit('saved_sheet_deleted', account=str(identity), sheet=str(sid)) return {'ok': True} @router.post('/api/account/sheets/{sid}/use') def use_sheet(sid: UUID, identity=Depends(owner)): with db.connect() as c: account_row(c, identity) row = owned_sheet(c, sid, identity, lock=True) require_available(c, row) row = touch(c, row) return sheet_view(c, row) @router.post('/api/account/sheets/{sid}/files') def sheet_files(sid: UUID, identity=Depends(owner)): with db.connect() as c: account_row(c, identity) row = owned_sheet(c, sid, identity, lock=True) require_available(c, row) rows = {upload['id']: upload for upload in uploads_of(c, list(row['uploads']))} types = file_types(row['item']) files = [] for uid in row['uploads']: upload = rows[uid] content_type = types.get(str(uid)) or mimetypes.guess_type(upload['name'])[0] or 'application/octet-stream' files.append({'upload_id': upload['id'], 'name': upload['name'], 'size': upload['size'], 'url': storage.view(upload['object_key'], content_type)}) touch(c, row) return {'files': files}