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 <noreply@anthropic.com>
This commit is contained in:
213
app/api/saved_sheets.py
Normal file
213
app/api/saved_sheets.py
Normal file
@@ -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}
|
||||||
@@ -18,7 +18,7 @@ from . import observability
|
|||||||
from .core import db
|
from .core import db
|
||||||
from .core.auth import audit, client_ip
|
from .core.auth import audit, client_ip
|
||||||
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
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')
|
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.
|
# 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)
|
app.include_router(module.router)
|
||||||
|
|||||||
15
app/migrations/202611301700_saved-sheets.sql
Normal file
15
app/migrations/202611301700_saved-sheets.sql
Normal file
@@ -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);
|
||||||
@@ -54,7 +54,7 @@ server {
|
|||||||
try_files /index.html =404;
|
try_files /index.html =404;
|
||||||
}
|
}
|
||||||
# The customer's area: one page, which shows the right part for each address.
|
# 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;
|
expires -1;
|
||||||
try_files /portal.html =404;
|
try_files /portal.html =404;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ server {
|
|||||||
try_files /index.html =404;
|
try_files /index.html =404;
|
||||||
}
|
}
|
||||||
# The customer's area: one page, which shows the right part for each address.
|
# 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;
|
try_files /portal.html =404;
|
||||||
}
|
}
|
||||||
location ~ ^/termos/?$ {
|
location ~ ^/termos/?$ {
|
||||||
|
|||||||
113
tests/saved_sheets_test.py
Normal file
113
tests/saved_sheets_test.py
Normal file
@@ -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()
|
||||||
@@ -141,6 +141,21 @@ button:disabled{opacity:.6;cursor:default}
|
|||||||
.correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical}
|
.correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical}
|
||||||
.correcaoForm .bPri{margin-top:14px;align-self:flex-start}
|
.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){
|
@media (max-width:820px){
|
||||||
.area{grid-template-columns:1fr;gap:16px}
|
.area{grid-template-columns:1fr;gap:16px}
|
||||||
.lateral{position:static;flex-direction:row;flex-wrap:wrap}
|
.lateral{position:static;flex-direction:row;flex-wrap:wrap}
|
||||||
|
|||||||
@@ -107,6 +107,7 @@
|
|||||||
<nav class="lateral" aria-label="Minha conta">
|
<nav class="lateral" aria-label="Minha conta">
|
||||||
<a href="/conta" data-view="geral" data-conta>Visão geral</a>
|
<a href="/conta" data-view="geral" data-conta>Visão geral</a>
|
||||||
<a href="/conta/pedidos" data-view="pedidos">Pedidos</a>
|
<a href="/conta/pedidos" data-view="pedidos">Pedidos</a>
|
||||||
|
<a href="/conta/folhas" data-view="folhas" data-conta>Minhas folhas</a>
|
||||||
<a href="/conta/dados" data-view="dados" data-conta>Dados da conta</a>
|
<a href="/conta/dados" data-view="dados" data-conta>Dados da conta</a>
|
||||||
<a href="/conta/entrar" data-view="entrar" id="navEntrar">Entrar</a>
|
<a href="/conta/entrar" data-view="entrar" id="navEntrar">Entrar</a>
|
||||||
<button type="button" id="logout" hidden>Sair</button>
|
<button type="button" id="logout" hidden>Sair</button>
|
||||||
@@ -140,6 +141,11 @@
|
|||||||
<div class="paginas" id="paginas"></div>
|
<div class="paginas" id="paginas"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="vista" id="vFolhas" hidden aria-labelledby="tFolhas">
|
||||||
|
<h1 id="tFolhas">Minhas folhas</h1>
|
||||||
|
<div class="lista" id="sheets"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="vista" id="vDados" hidden aria-labelledby="tDados">
|
<section class="vista" id="vDados" hidden aria-labelledby="tDados">
|
||||||
<h1 id="tDados">Dados da conta</h1>
|
<h1 id="tDados">Dados da conta</h1>
|
||||||
<form class="bloco" id="fPerfil">
|
<form class="bloco" id="fPerfil">
|
||||||
|
|||||||
@@ -28,7 +28,8 @@ function icone(nome){
|
|||||||
return span.firstChild;
|
return span.firstChild;
|
||||||
}
|
}
|
||||||
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
||||||
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas',
|
||||||
|
premium:'DTF Têxtil Premium · folha montada'};
|
||||||
// Artes avulsas que o Site separou por traço (item 17): uma folha por item.
|
// Artes avulsas que o Site separou por traço (item 17): uma folha por item.
|
||||||
const nomeItem=item=>(PRODUTO[item.mode]||item.mode)+(item.split?' · folha '+item.split.part+' de '+item.split.of:'');
|
const nomeItem=item=>(PRODUTO[item.mode]||item.mode)+(item.split?' · folha '+item.split.part+' de '+item.split.of:'');
|
||||||
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
|
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
|
||||||
@@ -50,6 +51,7 @@ function vista(){
|
|||||||
if(p==='/conta/entrar') return 'entrar';
|
if(p==='/conta/entrar') return 'entrar';
|
||||||
if(p==='/conta/redefinir') return 'redefinir';
|
if(p==='/conta/redefinir') return 'redefinir';
|
||||||
if(p==='/conta/dados') return 'dados';
|
if(p==='/conta/dados') return 'dados';
|
||||||
|
if(p==='/conta/folhas') return 'folhas';
|
||||||
if(p==='/conta') return 'geral';
|
if(p==='/conta') return 'geral';
|
||||||
return 'pedidos'; // /conta/pedidos, and the old /portal.html
|
return 'pedidos'; // /conta/pedidos, and the old /portal.html
|
||||||
}
|
}
|
||||||
@@ -64,20 +66,22 @@ document.addEventListener('click',event=>{
|
|||||||
async function mostra(){
|
async function mostra(){
|
||||||
aviso('');
|
aviso('');
|
||||||
const v=vista(), proximo=new URLSearchParams(location.search).get('next');
|
const v=vista(), proximo=new URLSearchParams(location.search).get('next');
|
||||||
// Overview and details are the account's; orders also work for a guest.
|
// Overview, details and saved sheets are the account's; orders also work for a guest.
|
||||||
if((v==='geral'||v==='dados')&&!conta){history.replaceState({},'','/conta/entrar?next='+encodeURIComponent(location.pathname));return mostra();}
|
if((v==='geral'||v==='dados'||v==='folhas')&&!conta){history.replaceState({},'','/conta/entrar?next='+encodeURIComponent(location.pathname));return mostra();}
|
||||||
if(v==='entrar'&&conta){history.replaceState({},'',proximo&&/^\/conta(\/[a-z]+)?$/.test(proximo)?proximo:'/conta');return mostra();}
|
if(v==='entrar'&&conta){history.replaceState({},'',proximo&&/^\/conta(\/[a-z]+)?$/.test(proximo)?proximo:'/conta');return mostra();}
|
||||||
$('auth').hidden=v!=='entrar';
|
$('auth').hidden=v!=='entrar';
|
||||||
$('redefinir').hidden=v!=='redefinir';
|
$('redefinir').hidden=v!=='redefinir';
|
||||||
$('area').hidden=v==='entrar'||v==='redefinir';
|
$('area').hidden=v==='entrar'||v==='redefinir';
|
||||||
if(v==='redefinir'&&!resetToken)aviso('Este link está incompleto. Peça outro em “Esqueci minha senha”.',true);
|
if(v==='redefinir'&&!resetToken)aviso('Este link está incompleto. Peça outro em “Esqueci minha senha”.',true);
|
||||||
$('vGeral').hidden=v!=='geral';$('vPedidos').hidden=v!=='pedidos';$('vDados').hidden=v!=='dados';
|
$('vGeral').hidden=v!=='geral';$('vPedidos').hidden=v!=='pedidos';$('vDados').hidden=v!=='dados';
|
||||||
|
$('vFolhas').hidden=v!=='folhas';
|
||||||
for(const a of document.querySelectorAll('.lateral a'))a.classList.toggle('on',a.dataset.view===v);
|
for(const a of document.querySelectorAll('.lateral a'))a.classList.toggle('on',a.dataset.view===v);
|
||||||
for(const a of document.querySelectorAll('.lateral [data-conta]'))a.hidden=!conta;
|
for(const a of document.querySelectorAll('.lateral [data-conta]'))a.hidden=!conta;
|
||||||
$('navEntrar').hidden=!!conta;$('logout').hidden=!conta;
|
$('navEntrar').hidden=!!conta;$('logout').hidden=!conta;
|
||||||
document.title=({entrar:'Entrar',redefinir:'Criar nova senha',geral:'Minha conta',pedidos:'Pedidos',dados:'Dados da conta'})[v]+' · DTF Dropstar';
|
document.title=({entrar:'Entrar',redefinir:'Criar nova senha',geral:'Minha conta',pedidos:'Pedidos',folhas:'Minhas folhas',dados:'Dados da conta'})[v]+' · DTF Dropstar';
|
||||||
if(v==='geral')await geral();
|
if(v==='geral')await geral();
|
||||||
else if(v==='pedidos')await pedidos();
|
else if(v==='pedidos')await pedidos();
|
||||||
|
else if(v==='folhas')await folhas();
|
||||||
else if(v==='dados')dados();
|
else if(v==='dados')dados();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,6 +303,85 @@ async function geral(){
|
|||||||
else{const v=node('div',null,'vazio');v.append(node('p','Seu primeiro pedido aparece aqui.'));const a=node('a','Enviar uma arte','bPri');a.href='/#envio';v.append(a);ultimo.append(v);}
|
else{const v=node('div',null,'vazio');v.append(node('p','Seu primeiro pedido aparece aqui.'));const a=node('a','Enviar uma arte','bPri');a.href='/#envio';v.append(a);ultimo.append(v);}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Saved sheets (Minhas folhas) ----------------------------------------
|
||||||
|
|
||||||
|
const FOLHA_PAGINA={file:'/arquivo-por-metro',avulsa:'/artes-avulsas',uvfile:'/uv-arquivo-por-metro',
|
||||||
|
uv:'/uv-artes-avulsas',premium:'/arquivo-por-metro'};
|
||||||
|
const FOLHA_MAX=300*1024*1024;
|
||||||
|
const ddmm=d=>new Date(d).toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
|
||||||
|
async function excluirFolha(id){
|
||||||
|
const r=await fetch('/api/account/sheets/'+encodeURIComponent(id),{method:'DELETE'});
|
||||||
|
const d=await r.json();
|
||||||
|
if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Não foi possível excluir a folha.');error.status=r.status;throw error;}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
async function guardarNoCarrinho(item){
|
||||||
|
const database=await new Promise((resolve,reject)=>{const req=indexedDB.open('dtf-local-cart',1);req.onupgradeneeded=()=>req.result.createObjectStore('cart');req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);});
|
||||||
|
try{
|
||||||
|
await new Promise((resolve,reject)=>{
|
||||||
|
const tx=database.transaction('cart','readwrite'),store=tx.objectStore('cart');
|
||||||
|
const req=store.get(scope);
|
||||||
|
req.onsuccess=()=>{
|
||||||
|
const saved=req.result;
|
||||||
|
const items=Array.isArray(saved?.items)?saved.items:[];
|
||||||
|
store.put({items:[...items,item],expires:Date.now()+86400000},scope);
|
||||||
|
};
|
||||||
|
tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);
|
||||||
|
});
|
||||||
|
}finally{database.close();}
|
||||||
|
}
|
||||||
|
function folhaCartao(f){
|
||||||
|
const card=node('article',null,'folhaCard');
|
||||||
|
const pic=node('div',null,'folhaPic');
|
||||||
|
if(f.picture){const img=node('img');img.alt='Miniatura da folha '+f.name;img.loading='lazy';img.src=f.picture;pic.append(img);}
|
||||||
|
else pic.append(node('div',null,'semFoto'));
|
||||||
|
const body=node('div',null,'folhaBody');
|
||||||
|
body.append(node('h2',f.name,'folhaNome'),node('p',PRODUTO[f.mode]||f.mode,'folhaProduto'),
|
||||||
|
node('p',metros(f.metres),'folhaMetros'));
|
||||||
|
const validade=f.available?'Arquivos até '+ddmm(f.files_until)
|
||||||
|
:(f.files_until?'Arquivos vencidos em '+ddmm(f.files_until)+'. Envie de novo para pedir.'
|
||||||
|
:'Arquivos vencidos. Envie de novo para pedir.');
|
||||||
|
body.append(node('p',validade,'folhaValidade'+(f.available?'':' vencida')));
|
||||||
|
card.append(pic,body);
|
||||||
|
const acoes=node('div',null,'folhaAcoes');
|
||||||
|
if(f.available){
|
||||||
|
acoes.append(button('Pedir de novo',async()=>{
|
||||||
|
const sheet=await api('/account/sheets/'+encodeURIComponent(f.id)+'/use',{});
|
||||||
|
await guardarNoCarrinho(sheet.item);
|
||||||
|
location.assign('/carrinho');
|
||||||
|
},'bPri bMini'));
|
||||||
|
if(Number(f.total_size)<=FOLHA_MAX){
|
||||||
|
acoes.append(button('Editar',()=>location.assign(FOLHA_PAGINA[f.mode]+'?folha='+encodeURIComponent(f.id)),'bSec'));
|
||||||
|
}else{
|
||||||
|
const grande=node('button','Grande demais para editar aqui. Use Pedir de novo.','bSec folhaGrande');
|
||||||
|
grande.type='button';grande.disabled=true;acoes.append(grande);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acoes.append(button('Excluir',async()=>{
|
||||||
|
if(!confirm('Excluir a folha “'+f.name+'”?'))return;
|
||||||
|
await excluirFolha(f.id);
|
||||||
|
await folhas();
|
||||||
|
},'bSec'));
|
||||||
|
card.append(acoes);
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
async function folhas(){
|
||||||
|
const lista=$('sheets');lista.replaceChildren();
|
||||||
|
const carregando=node('div',null,'vazio');carregando.append(node('p','Carregando…','nota2'));lista.append(carregando);
|
||||||
|
let data;
|
||||||
|
try{data=await api('/account/sheets');}
|
||||||
|
catch(error){lista.replaceChildren();aviso(error.message,true);return;}
|
||||||
|
lista.replaceChildren();
|
||||||
|
if(!data.sheets.length){
|
||||||
|
const vazio=node('div',null,'vazio');
|
||||||
|
vazio.append(node('p','Nenhuma folha salva. No carrinho, use Salvar em Minhas folhas.'));
|
||||||
|
lista.append(vazio);return;
|
||||||
|
}
|
||||||
|
const grade=node('div',null,'folhas');
|
||||||
|
for(const f of data.sheets)grade.append(folhaCartao(f));
|
||||||
|
lista.append(grade);
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Account details -----------------------------------------------------
|
// ---- Account details -----------------------------------------------------
|
||||||
|
|
||||||
const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']];
|
const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']];
|
||||||
|
|||||||
Reference in New Issue
Block a user