"""Customer accounts, their orders, and the corrections they submit.""" from datetime import datetime, timedelta, timezone from uuid import UUID, uuid4 from typing import Literal from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from psycopg.errors import UniqueViolation from psycopg.types.json import Jsonb from ..core import db from ..artwork import submit_files from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash, password_matches, session_row, throttle, transfer_guest) from ..core.models import ArtworkSubmission, EmailChange, Login, PasswordChange, ProfileUpdate, Register from ..runtime import STATES, file_rows, owned_order, storage from ..scanning import require_clean router = APIRouter() def current(request): try: return session_row(request) except HTTPException: return None @router.post('/api/account/register') def register(body: Register, request: Request, response: Response): email = body.customer.mail.strip().lower() throttle(email, request) # Registration attempts keep counting against the email, as before. login_failed(email) previous = current(request) encoded = password_hash(body.password) identity = uuid4() profile = body.customer.model_dump() profile['mail'] = email try: with db.connect() as c: if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone(): raise HTTPException(409, 'Sign out before registering another account') c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile))) if previous: transfer_guest(c, previous, identity) new_session(c, response, identity) except UniqueViolation: raise HTTPException(409, 'An account already exists; sign in') audit('account_registered', account=str(identity)) return {'customer': profile} @router.post('/api/account/login') def login(body: Login, request: Request, response: Response): email = body.email.strip().lower() throttle(email, request) with db.connect() as c: account = c.execute('SELECT * FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone() # Comparable password work even when the email is absent. stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH matches = password_matches(body.password, stored) if not account or not matches: login_failed(email) audit('customer_login_failed', ip=client_ip(request)) raise HTTPException(401, 'E-mail ou senha inválidos.') previous = current(request) with db.connect() as c: if not stored.startswith('scrypt-v2$'): c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.password),account['id'])) if previous: transfer_guest(c, previous, account['id']) c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],)) new_session(c, response, account['id']) audit('customer_login_success', account=str(account['id'])) return {'customer': account['profile']} @router.post('/api/account/logout') def logout(request: Request, response: Response): previous = current(request) if previous: with db.connect() as c: c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],)) response.delete_cookie('dtf_session', httponly=True, samesite='strict') response.headers['Clear-Site-Data'] = '"storage"' audit('customer_logout') return {'ok': True} @router.get('/api/account/me') def me(identity=Depends(owner)): with db.connect() as c: row = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone() return {'customer': row['profile'] if row else None} def account_row(c, identity, lock=False): row = c.execute('SELECT * FROM dtf_local.accounts WHERE id=%s' + (' FOR UPDATE' if lock else ''), (identity,)).fetchone() if not row: raise HTTPException(401, 'Entre na sua conta.') return row @router.post('/api/account/profile') def update_profile(body: ProfileUpdate, identity=Depends(owner)): """WhatsApp and the saved delivery address. The CNPJ is the account's and does not change; the e-mail is the login and changes on its own route.""" with db.connect() as c: row = account_row(c, identity, lock=True) profile = {**row['profile'], 'zap': body.zap, 'address': body.address.model_dump() if body.address else None} c.execute('UPDATE dtf_local.accounts SET profile=%s WHERE id=%s', (Jsonb(profile), identity)) audit('account_profile_updated', account=str(identity)) return {'customer': profile} @router.post('/api/account/email') def change_email(body: EmailChange, request: Request, identity=Depends(owner)): with db.connect() as c: row = account_row(c, identity) throttle(row['email'], request) if not password_matches(body.password, row['password_hash']): login_failed(row['email']) raise HTTPException(401, 'Senha incorreta.') profile = {**row['profile'], 'mail': body.email} try: with db.connect() as c: c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (body.email, Jsonb(profile), identity)) except UniqueViolation: raise HTTPException(409, 'Este e-mail já é de outra conta.') audit('account_email_changed', account=str(identity)) return {'customer': profile} @router.post('/api/account/password') def change_password(body: PasswordChange, request: Request, identity=Depends(owner)): with db.connect() as c: row = account_row(c, identity) throttle(row['email'], request) if not password_matches(body.current, row['password_hash']): login_failed(row['email']) raise HTTPException(401, 'Senha atual incorreta.') session = current(request) with db.connect() as c: c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.new), identity)) # Other devices signed in with the old password are signed out. c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s AND id<>%s', (identity, session['id'])) audit('account_password_changed', account=str(identity)) return {'ok': True} # The order list's groups, as the customer filters them. GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'} ENTRIES = '''WITH live_quote AS ( -- The cart waiting for payment: the newest unpaid quote whose files still -- exist. An older one was replaced when the cart changed, and one whose -- files are gone can no longer be paid. SELECT q.id, q.created_at, q.approved FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE q.owner=%(me)s AND o.id IS NULL AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i CROSS JOIN LATERAL jsonb_array_elements_text(i->'uploads') u(uid) JOIN dtf_local.uploads up ON up.id=u.uid::uuid WHERE up.purged_at IS NOT NULL OR up.expires_at<=now()) ORDER BY q.created_at DESC LIMIT 1 ), entries AS ( SELECT 'order' AS kind, o.id, o.number, o.state, CASE WHEN o.state='fin' THEN 'fin' WHEN o.state='cor' THEN 'cor' ELSE 'prod' END AS grp, (o.snapshot->>'total_cents')::bigint AS total_cents, o.created_at, o.snapshot->'items' AS items FROM dtf_local.orders o WHERE o.owner=%(me)s UNION ALL SELECT 'quote', q.id, NULL, CASE WHEN q.approved IS NULL THEN 'review' ELSE 'pay' END, 'pay', (q.approved->>'total_cents')::bigint, q.created_at, COALESCE(q.approved->'items','[]'::jsonb) FROM live_quote q )''' @router.get('/api/customer/orders') def orders(identity=Depends(owner), status: Literal['all','pay','prod','cor','fin'] = 'all', number: int | None = Query(None, ge=1), days: int = Query(0, ge=0, le=3650), page: int = Query(1, ge=1, le=10000), size: int = Query(10, ge=1, le=50)): """The customer's orders and the cart waiting for payment, newest first, filtered and a page at a time, with how many there are in each group.""" params = {'me': identity, 'grp': None if status == 'all' else status, 'number': number, 'since': datetime.now(timezone.utc) - timedelta(days=days) if days else None, 'size': size, 'offset': (page - 1) * size} where = '''WHERE (%(grp)s::text IS NULL OR grp=%(grp)s) AND (%(number)s::int IS NULL OR number=%(number)s) AND (%(since)s::timestamptz IS NULL OR created_at>=%(since)s)''' with db.connect() as c: counts = {r['grp']: r['n'] for r in c.execute(ENTRIES + ' SELECT grp, count(*) AS n FROM entries GROUP BY grp', params).fetchall()} total = c.execute(ENTRIES + ' SELECT count(*) AS n FROM entries ' + where, params).fetchone()['n'] rows = c.execute(ENTRIES + ' SELECT * FROM entries ' + where + ' ORDER BY created_at DESC LIMIT %(size)s OFFSET %(offset)s', params).fetchall() items = [] for r in rows: entry = {'kind': r['kind'], 'id': r['id'], 'number': r['number'], 'state': r['state'], 'group': r['grp'], 'total_cents': r['total_cents'], 'created_at': r['created_at'], 'items': [{'mode': i['mode'], 'billed_metres': i.get('billed_metres')} for i in r['items']]} if r['kind'] == 'quote': # A PIX code still open is paid on its own page. pix = c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix' AND status='pending' AND COALESCE((response->>'expires_at')::timestamptz > now(), false)''', (r['id'],)).fetchone() entry['pay_with'] = 'pix' if pix else 'page' items.append(entry) return {'items': items, 'total': total, 'page': page, 'size': size, 'counts': {g: counts.get(g, 0) for g in GROUPS}, 'groups': GROUPS, 'states': STATES} @router.get('/api/customer/orders/{oid}') def detail(oid: UUID, identity=Depends(owner)): with db.connect() as c: row = owned_order(c, oid, identity) # A move back undoes an operator's mistake and its reason is internal; # 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() return {'id': row['id'], 'number': row['number'], 'state': row['state'], 'version': row['version'], 'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history, 'files': file_rows(c,oid)} @router.post('/api/customer/orders/{oid}/corrections') def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)): with db.connect() as c: order = owned_order(c, oid, identity, lock=True) return submit_files(c,order,body,identity,'correction','customer') @router.get('/api/customer/orders/{oid}/files/{fid}/download') def customer_download(oid: UUID, fid: UUID, identity=Depends(owner)): with db.connect() as c: owned_order(c,oid,identity) row = c.execute('SELECT u.* FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.id=%s AND f.order_id=%s AND f.active', (fid,oid)).fetchone() if not row: raise HTTPException(404, 'Active file not found') if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'File expired') require_clean(row) return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}