From 56712356813a531d7a5de16bc63c72fb2e2efab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 30 Nov 2026 16:09:52 -0300 Subject: [PATCH] feat: Minhas folhas on the server and in Minha conta: saved sheets per account with their uploads, 30 days, 50 per account; order again, edit, delete (Rodada 5, B9) Co-Authored-By: Claude Opus 5.5 --- app/api/saved_sheets.py | 213 +++++++++++++++++++ app/app.py | 4 +- app/migrations/202611301700_saved-sheets.sql | 15 ++ deploy/nginx.conf.template | 2 +- infra/nginx.conf.template | 2 +- tests/saved_sheets_test.py | 113 ++++++++++ web/portal.css | 15 ++ web/portal.html | 6 + web/portal.js | 91 +++++++- 9 files changed, 453 insertions(+), 8 deletions(-) create mode 100644 app/api/saved_sheets.py create mode 100644 app/migrations/202611301700_saved-sheets.sql create mode 100644 tests/saved_sheets_test.py diff --git a/app/api/saved_sheets.py b/app/api/saved_sheets.py new file mode 100644 index 0000000..d86cfe5 --- /dev/null +++ b/app/api/saved_sheets.py @@ -0,0 +1,213 @@ +"""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} diff --git a/app/app.py b/app/app.py index 622bdfd..1037ee1 100644 --- a/app/app.py +++ b/app/app.py @@ -18,7 +18,7 @@ from . import observability 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, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users +from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, saved_sheets, site_admin, site_videos, stamps, uploads, users observability.init('api') @@ -82,5 +82,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, site_admin, reviews, machine_log, stamps): +for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps, saved_sheets): app.include_router(module.router) diff --git a/app/migrations/202611301700_saved-sheets.sql b/app/migrations/202611301700_saved-sheets.sql new file mode 100644 index 0000000..9955db4 --- /dev/null +++ b/app/migrations/202611301700_saved-sheets.sql @@ -0,0 +1,15 @@ +-- Rodada 5, B9: a customer with an account keeps a built sheet (a cart item) +-- in Minhas folhas and asks for it again, edits it or deletes it later. +CREATE TABLE IF NOT EXISTS dtf_local.saved_sheets ( + id uuid PRIMARY KEY, + account uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE, + name text NOT NULL, + mode text NOT NULL CHECK (mode IN ('file','avulsa','uvfile','uv','premium')), + metres numeric NOT NULL, + item jsonb NOT NULL, + uploads uuid[] NOT NULL, + picture text, + created_at timestamptz NOT NULL DEFAULT now(), + used_at timestamptz +); +CREATE INDEX IF NOT EXISTS saved_sheets_account ON dtf_local.saved_sheets(account); diff --git a/deploy/nginx.conf.template b/deploy/nginx.conf.template index 301d85e..d6b02cb 100644 --- a/deploy/nginx.conf.template +++ b/deploy/nginx.conf.template @@ -54,7 +54,7 @@ server { try_files /index.html =404; } # The customer's area: one page, which shows the right part for each address. - location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ { + location ~ ^/conta(/(entrar|pedidos|dados|redefinir|folhas))?/?$ { expires -1; try_files /portal.html =404; } diff --git a/infra/nginx.conf.template b/infra/nginx.conf.template index eab6a51..18e60a8 100644 --- a/infra/nginx.conf.template +++ b/infra/nginx.conf.template @@ -24,7 +24,7 @@ server { try_files /index.html =404; } # The customer's area: one page, which shows the right part for each address. - location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ { + location ~ ^/conta(/(entrar|pedidos|dados|redefinir|folhas))?/?$ { try_files /portal.html =404; } location ~ ^/termos/?$ { diff --git a/tests/saved_sheets_test.py b/tests/saved_sheets_test.py new file mode 100644 index 0000000..02d41ad --- /dev/null +++ b/tests/saved_sheets_test.py @@ -0,0 +1,113 @@ +"""Minhas folhas: an account keeps a built sheet and asks for it again. + +Run against the local stack: python3 -m tests.saved_sheets_test +SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.saved_sheets_test +""" +from datetime import datetime, timedelta, timezone +import secrets + +from app.core import db +from tests.smoke_test import Client, register, upload_bytes + +PASSWORD = 'senha-folhas-12345' +CNPJ = '11222333000181' +CONTENT = b'LOCAL SAVED SHEET ARTWORK' + + +def saved_file(uid, name='LOCAL-TEST.cdr'): + return {'upload_id': uid, 'name': name, 'size': len(CONTENT), 'lastModified': 0, + 'type': 'application/octet-stream'} + + +def body(uid, name='Minha folha', mode='file', metres='1.2', picture=None): + item = {'mode': mode, 'metres': metres, 'savedFiles': [saved_file(uid)]} + data = {'name': name, 'mode': mode, 'metres': metres, 'item': item} + if picture is not None: + data['picture'] = picture + return data + + +def run(): + tag = secrets.token_hex(3) + emails = [f'folhas-{tag}@example.test', f'outra-{tag}@example.test'] + client, other = Client(), Client() + try: + # A visitor has no account to keep sheets in. + client.call('/session') + client.call('/account/sheets', expected=401) + + register(client, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': emails[0]}, PASSWORD) + register(other, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': emails[1]}, PASSWORD) + + uid = upload_bytes(client, CONTENT) + picture = 'data:image/png;base64,AAAA' + first = client.call('/account/sheets', body(uid, picture=picture)) + assert first['id'] + + sheets = client.call('/account/sheets')['sheets'] + assert [s['id'] for s in sheets] == [first['id']], sheets + saved = sheets[0] + assert saved['available'] is True and saved['picture'] == picture + assert saved['total_size'] == len(CONTENT) and saved['item']['savedFiles'][0]['upload_id'] == uid + until = datetime.fromisoformat(saved['files_until']) + assert abs((until - (datetime.now(timezone.utc) + timedelta(days=30))).total_seconds()) < 300, saved + + # Another account's upload cannot be saved. + stranger_uid = upload_bytes(other, CONTENT) + refused = client.call('/account/sheets', body(stranger_uid), expected=409) + assert 'não está mais disponível' in refused['detail'], refused + + # A sheet of another account is not found. + second = other.call('/account/sheets', body(stranger_uid, name='Outra folha')) + assert second['id'] + client.call('/account/sheets/' + second['id'], expected=404, method='DELETE') + client.call('/account/sheets/' + second['id'] + '/use', {}, expected=404) + client.call('/account/sheets/' + second['id'] + '/files', {}, expected=404) + + # An upload older than 30 days is no longer available. + old_uid = upload_bytes(client, CONTENT) + old = client.call('/account/sheets', body(old_uid, name='Vencida')) + with db.connect() as c: + c.execute("UPDATE dtf_local.uploads SET created_at=now()-interval '31 days' WHERE id=%s", (old_uid,)) + expired = next(s for s in client.call('/account/sheets')['sheets'] if s['id'] == old['id']) + assert expired['available'] is False, expired + refused = client.call('/account/sheets/' + old['id'] + '/use', {}, expected=409) + assert 'venceram' in refused['detail'], refused + + # At most 50 sheets per account. + created = 2 + while created < 50: + client.call('/account/sheets', body(uid, name=f'Folha {created + 1}')) + created += 1 + full = client.call('/account/sheets', body(uid, name='A 51a'), expected=409) + assert '50 folhas' in full['detail'], full + + # Asking for it again records when and hands back the item. + used = client.call('/account/sheets/' + first['id'] + '/use', {}) + assert used['id'] == first['id'] and used['used_at'] and used['item']['savedFiles'][0]['upload_id'] == uid + assert next(s for s in client.call('/account/sheets')['sheets'] if s['id'] == first['id'])['used_at'] + + # Editing gets a link to each file, in the item's order. + files = client.call('/account/sheets/' + first['id'] + '/files', {})['files'] + assert len(files) == 1 and files[0]['upload_id'] == uid + assert files[0]['name'] == 'LOCAL-TEST.cdr' and files[0]['size'] == len(CONTENT) + assert files[0]['url'].startswith('http'), files + + # Deleted, it leaves the list. + assert client.call('/account/sheets/' + first['id'], method='DELETE') == {'ok': True} + assert first['id'] not in [s['id'] for s in client.call('/account/sheets')['sheets']] + client.call('/account/sheets/' + first['id'], method='DELETE', expected=404) + + print('PASS: saved sheets belong to the account, last 30 days, cap at 50, and come back for ' + 'Pedir de novo or Editar') + finally: + with db.connect() as c: + c.execute('DELETE FROM dtf_local.uploads WHERE owner IN ' + '(SELECT id FROM dtf_local.accounts WHERE email=ANY(%s))', (emails,)) + c.execute('DELETE FROM dtf_local.accounts WHERE email=ANY(%s)', (emails,)) + c.execute('DELETE FROM dtf_local.account_signups WHERE email=ANY(%s)', (emails,)) + c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=ANY(%s)', (emails,)) + + +if __name__ == '__main__': + run() diff --git a/web/portal.css b/web/portal.css index b72df2a..8733a0a 100644 --- a/web/portal.css +++ b/web/portal.css @@ -141,6 +141,21 @@ button:disabled{opacity:.6;cursor:default} .correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical} .correcaoForm .bPri{margin-top:14px;align-self:flex-start} +/* Saved sheets (Minhas folhas). */ +.folhas{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:14px;padding:14px} +.folhaCard{display:flex;flex-direction:column;border:1px solid var(--linha);border-radius:var(--raio2);background:#fff;overflow:hidden} +.folhaPic{aspect-ratio:4/3;background:var(--cinza);border-bottom:1px solid var(--linha)} +.folhaPic img{display:block;width:100%;height:100%;object-fit:cover} +.folhaPic .semFoto{width:100%;height:100%;background:repeating-linear-gradient(135deg,var(--cinza),var(--cinza) 10px,#EDEDED 10px,#EDEDED 20px)} +.folhaBody{display:flex;flex-direction:column;gap:4px;padding:14px 16px 6px} +.folhaNome{font-family:"Inter",sans-serif;font-size:16px;font-weight:800;overflow-wrap:anywhere} +.folhaProduto,.folhaMetros{margin:0;font-size:14px;color:var(--fraco)} +.folhaValidade{margin:6px 0 0;font-size:14px;color:var(--texto2)} +.folhaValidade.vencida{color:#B42318} +.folhaAcoes{display:flex;flex-wrap:wrap;gap:8px;padding:12px 16px 16px;margin-top:auto} +.folhaAcoes .bPri,.folhaAcoes .bSec{height:38px;padding:0 14px;font-size:14.5px} +.folhaAcoes .folhaGrande{max-width:100%;min-height:38px;height:auto;padding:7px 12px;text-align:center;line-height:1.25;white-space:normal} + @media (max-width:820px){ .area{grid-template-columns:1fr;gap:16px} .lateral{position:static;flex-direction:row;flex-wrap:wrap} diff --git a/web/portal.html b/web/portal.html index 97d4a4f..858dbec 100644 --- a/web/portal.html +++ b/web/portal.html @@ -107,6 +107,7 @@