Some checks failed
The signups that marked an account as confirmed are deleted after a day, so an older account was left unconfirmed and brought nothing. The code e-mail sent before the account existed stays in the queue and now counts too. A password reset, whose link came by e-mail, also confirms the address and brings the orders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
502 lines
28 KiB
Python
502 lines
28 KiB
Python
"""Customer accounts, their orders, and the corrections they submit."""
|
|
import hashlib
|
|
import secrets
|
|
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, rate_limit, session_row, throttle, transfer_guest)
|
|
from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
|
|
PasswordChange, PasswordReset, ProfileUpdate, Register, SignupCode, SignupResend)
|
|
from .. import mail
|
|
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
|
from ..scanning import require_clean
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def current(request):
|
|
try: return session_row(request)
|
|
except HTTPException: return None
|
|
|
|
|
|
# Signup: with e-mail on, the account exists only once the code sent to the
|
|
# address is entered, so nobody opens an account on someone else's e-mail. The
|
|
# answer is the same whether or not the address already has an account: that
|
|
# address gets a notice to sign in instead of a code, and no code works.
|
|
CODE_ATTEMPTS = 5
|
|
CODE_SENDS = 5
|
|
RESEND_SECONDS = 60
|
|
|
|
|
|
def signup_code(c, signup_id, email, exists):
|
|
"""A fresh code for a signup (or the notice for an address that already has
|
|
an account), queued by e-mail. Returns the code's hash, None for the notice."""
|
|
if exists:
|
|
mail.queue(c, 'account', email, 'Você já tem conta · DTF Dropstar',
|
|
'Olá!\n\nAlguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já tem conta.\n\n'
|
|
f'Para entrar: {PUBLIC_ORIGIN}/conta/entrar\n'
|
|
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
|
|
'Se não foi você, ignore este e-mail: nada muda na sua conta.')
|
|
return None
|
|
return send_code(c, signup_id, email, 'criar a conta no DTF Dropstar')
|
|
|
|
|
|
def send_code(c, key, email, purpose):
|
|
"""A fresh 6-digit code by e-mail for `purpose`; returns its hash."""
|
|
code = f'{secrets.randbelow(10 ** 6):06d}'
|
|
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
|
|
f'Olá!\n\nO seu código para {purpose} é:\n\n{code}\n\n'
|
|
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail.')
|
|
return code_digest(key, code)
|
|
|
|
|
|
def checked_code(c, table, key, code, request, extra=''):
|
|
"""The pending row a code confirms, locked, or the refusal to raise. A wrong
|
|
code counts against the row; the caller raises after its block commits."""
|
|
row = c.execute(f'SELECT * FROM dtf_local.{table} WHERE id=%s AND done_at IS NULL {extra} FOR UPDATE',
|
|
key).fetchone()
|
|
if not row or row['expires_at'] <= datetime.now(timezone.utc):
|
|
return None, HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
|
|
if row['attempts'] >= CODE_ATTEMPTS:
|
|
return None, HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
|
|
if row['code_hash'] and secrets.compare_digest(row['code_hash'], code_digest(row['id'], code)):
|
|
c.execute(f'UPDATE dtf_local.{table} SET done_at=now() WHERE id=%s', (row['id'],))
|
|
return row, None
|
|
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
|
left = CODE_ATTEMPTS - row['attempts'] - 1
|
|
audit('code_wrong', kind=table, ip=client_ip(request))
|
|
return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
|
|
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
|
|
|
|
|
|
def resend_wait(row):
|
|
"""Why another code cannot go yet, or None."""
|
|
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - row['sent_at']).total_seconds()
|
|
if wait > 0:
|
|
return HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
|
|
if row['sends'] >= CODE_SENDS:
|
|
return HTTPException(429, 'Limite de códigos atingido. Comece de novo em alguns minutos.')
|
|
return None
|
|
|
|
|
|
def code_digest(signup_id, code):
|
|
return hashlib.sha256(f'{signup_id}:{code}'.encode()).hexdigest()
|
|
|
|
|
|
@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)
|
|
profile = body.customer.model_dump()
|
|
profile['mail'] = email
|
|
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, 'Saia da conta atual antes de criar outra.')
|
|
if mail.configured():
|
|
rate_limit('signup-account', email, CODE_SENDS, 3600)
|
|
signup_id = uuid4()
|
|
with db.connect() as c:
|
|
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
|
digest = signup_code(c, signup_id, email, exists)
|
|
c.execute('''INSERT INTO dtf_local.account_signups(id,email,profile,password_hash,code_hash,expires_at)
|
|
VALUES(%s,%s,%s,%s,%s,now() + %s * interval '1 minute')''',
|
|
(signup_id, email, Jsonb(profile), password_hash(body.password), digest, mail.CODE_MINUTES))
|
|
audit('account_signup_started', ip=client_ip(request))
|
|
return {'verify': str(signup_id), 'email': email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
|
# Without e-mail there is no code to send: the account is created at once.
|
|
return create_account(profile=profile, password=password_hash(body.password), previous=previous, response=response)
|
|
|
|
|
|
def claim_orders(c, identity, profile):
|
|
"""Orders bought without an account with this account's CPF/CNPJ and
|
|
e-mail, from any browser. Only for an e-mail confirmed with a code: a
|
|
CPF or CNPJ alone, which others may know, never brings anyone's orders.
|
|
Each order comes with its cart and the customer's files."""
|
|
document = ''.join(ch for ch in str(profile.get('cnpj') or '') if ch.isdigit())
|
|
if not document:
|
|
return 0
|
|
orders = c.execute('''SELECT o.id,o.owner,o.quote_id,o.snapshot FROM dtf_local.orders o
|
|
WHERE o.owner<>%s AND NOT EXISTS (SELECT 1 FROM dtf_local.accounts a WHERE a.id=o.owner)
|
|
AND regexp_replace(coalesce(o.snapshot->'customer'->>'cnpj',''),'\\D','','g')=%s
|
|
AND lower(trim(o.snapshot->'customer'->>'mail'))=%s
|
|
FOR UPDATE''', (identity, document, profile['mail'].strip().lower())).fetchall()
|
|
for order in orders:
|
|
uploads = [uid for item in order['snapshot'].get('items') or [] for uid in item.get('uploads') or []]
|
|
uploads += [row['upload_id'] for row in c.execute(
|
|
'SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s', (order['id'],)).fetchall()]
|
|
c.execute('UPDATE dtf_local.orders SET owner=%s WHERE id=%s', (identity, order['id']))
|
|
c.execute('UPDATE dtf_local.quotes SET owner=%s WHERE id=%s AND owner=%s', (identity, order['quote_id'], order['owner']))
|
|
c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s',
|
|
(identity, [str(uid) for uid in uploads], order['owner']))
|
|
if orders:
|
|
audit('account_orders_claimed', account=str(identity), orders=len(orders))
|
|
return len(orders)
|
|
|
|
|
|
def create_account(profile, password, previous, response, verified=False):
|
|
identity = uuid4()
|
|
try:
|
|
with db.connect() as c:
|
|
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile,email_verified) VALUES(%s,%s,%s,%s,%s)',
|
|
(identity, profile['mail'], password, Jsonb(profile), verified))
|
|
if previous: transfer_guest(c, previous, identity)
|
|
if verified: claim_orders(c, identity, profile)
|
|
new_session(c, response, identity)
|
|
except UniqueViolation:
|
|
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
|
|
audit('account_registered', account=str(identity))
|
|
return {'customer': profile}
|
|
|
|
|
|
@router.post('/api/account/register/verify')
|
|
def register_verify(body: SignupCode, request: Request, response: Response):
|
|
rate_limit('code-verify', client_ip(request), 30)
|
|
with db.connect() as c:
|
|
signup, refusal = checked_code(c, 'account_signups', (body.signup,), body.code, request)
|
|
# Raised outside the block, so a wrong attempt is counted, not rolled back.
|
|
if refusal:
|
|
raise refusal
|
|
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
|
previous=current(request), response=response, verified=True)
|
|
|
|
|
|
@router.get('/api/account/register/dev-code')
|
|
def register_dev_code(signup: UUID):
|
|
"""The local stack's last code for a signup, for the browser test, which
|
|
cannot read the database. Only where e-mail stays in the log; elsewhere
|
|
the code exists only in the customer's inbox."""
|
|
if ENVIRONMENT != 'local' or mail.ADAPTER != 'log':
|
|
raise HTTPException(404, 'Not found')
|
|
with db.connect() as c:
|
|
row = c.execute('''SELECT m.body FROM dtf_local.account_signups s JOIN dtf_local.mail_queue m
|
|
ON m.to_addr=s.email AND m.kind='code' WHERE s.id=%s ORDER BY m.id DESC LIMIT 1''', (signup,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Not found')
|
|
return {'code': next(word for word in row['body'].split() if word.isdigit() and len(word) == 6)}
|
|
|
|
|
|
@router.post('/api/account/register/resend')
|
|
def register_resend(body: SignupResend, request: Request):
|
|
rate_limit('code-verify', client_ip(request), 30)
|
|
with db.connect() as c:
|
|
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
|
(body.signup,)).fetchone()
|
|
if not signup:
|
|
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
|
|
if refusal := resend_wait(signup):
|
|
raise refusal
|
|
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (signup['email'],)).fetchone()
|
|
digest = signup_code(c, signup['id'], signup['email'], exists)
|
|
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
|
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, signup['id']))
|
|
audit('account_signup_code_resent', ip=client_ip(request))
|
|
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
|
|
|
@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'],))
|
|
# Orders bought without the account since, on any device.
|
|
if account['email_verified']:
|
|
claim_orders(c, account['id'], account['profile'])
|
|
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 CPF or 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.')
|
|
if body.email == row['email']:
|
|
raise HTTPException(422, 'Este já é o e-mail da sua conta.')
|
|
if not mail.configured():
|
|
return apply_email(identity, row, body.email)
|
|
# With e-mail on, the change waits for the code sent to the new address.
|
|
rate_limit('email-change', str(identity), CODE_SENDS, 3600)
|
|
change = uuid4()
|
|
with db.connect() as c:
|
|
if c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (body.email,)).fetchone():
|
|
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
|
digest = send_code(c, change, body.email, 'trocar o e-mail da sua conta no DTF Dropstar')
|
|
c.execute('''INSERT INTO dtf_local.email_changes(id,account_id,new_email,code_hash,expires_at)
|
|
VALUES(%s,%s,%s,%s,now() + %s * interval '1 minute')''', (change, identity, body.email, digest, mail.CODE_MINUTES))
|
|
audit('account_email_change_started', account=str(identity))
|
|
return {'verify': str(change), 'email': body.email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
|
|
|
|
|
def apply_email(identity, row, email):
|
|
"""Switch the account to the new e-mail and tell the old address."""
|
|
profile = {**row['profile'], 'mail': email}
|
|
try:
|
|
with db.connect() as c:
|
|
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s, email_verified=true WHERE id=%s',
|
|
(email, Jsonb(profile), identity))
|
|
claim_orders(c, identity, profile)
|
|
mail.queue(c, 'notice', row['email'], 'O e-mail da sua conta foi trocado · DTF Dropstar',
|
|
f'Olá!\n\nO e-mail da sua conta no DTF Dropstar foi trocado para {email}. '
|
|
'A partir de agora, entre com ele.\n\n'
|
|
'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.')
|
|
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/email/verify')
|
|
def change_email_verify(body: EmailCode, request: Request, identity=Depends(owner)):
|
|
rate_limit('code-verify', client_ip(request), 30)
|
|
with db.connect() as c:
|
|
change, refusal = checked_code(c, 'email_changes', (body.change, identity), body.code, request,
|
|
extra='AND account_id=%s')
|
|
row = account_row(c, identity) if change else None
|
|
if refusal:
|
|
raise refusal
|
|
return apply_email(identity, row, change['new_email'])
|
|
|
|
|
|
@router.post('/api/account/email/resend')
|
|
def change_email_resend(body: EmailResend, request: Request, identity=Depends(owner)):
|
|
rate_limit('code-verify', client_ip(request), 30)
|
|
with db.connect() as c:
|
|
change = c.execute('''SELECT * FROM dtf_local.email_changes WHERE id=%s AND account_id=%s AND done_at IS NULL
|
|
FOR UPDATE''', (body.change, identity)).fetchone()
|
|
if not change:
|
|
raise HTTPException(410, 'Esta troca venceu. Comece de novo.')
|
|
if refusal := resend_wait(change):
|
|
raise refusal
|
|
digest = send_code(c, change['id'], change['new_email'], 'trocar o e-mail da sua conta no DTF Dropstar')
|
|
c.execute('''UPDATE dtf_local.email_changes SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
|
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, change['id']))
|
|
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
|
|
|
@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}
|
|
|
|
# Password recovery: a link by e-mail that works once, for an hour. The answer
|
|
# never says whether the e-mail has an account.
|
|
RESET_SENT = 'Se houver uma conta com este e-mail, enviamos um link para criar uma nova senha. Ele vale por 1 hora.'
|
|
|
|
@router.post('/api/account/forgot')
|
|
def forgot_password(body: ForgotPassword, request: Request):
|
|
if not mail.configured():
|
|
raise HTTPException(503, 'A recuperação por e-mail ainda não está disponível. Fale com a Dropstar pelo WhatsApp.')
|
|
email = body.email.strip().lower()
|
|
rate_limit('reset-source', client_ip(request), 10)
|
|
# Per address: a few links an hour, so nobody fills someone's inbox.
|
|
rate_limit('reset-account', email, 3, 3600)
|
|
token = secrets.token_urlsafe(32)
|
|
with db.connect() as c:
|
|
account = c.execute('SELECT id FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
|
if account:
|
|
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
|
|
VALUES(%s,%s,now() + %s * interval '1 minute')''',
|
|
(hashlib.sha256(token.encode()).hexdigest(), account['id'], mail.RESET_MINUTES))
|
|
# In the fragment, not the query: it is never sent to a server,
|
|
# nor in the Referer of the fonts and the logo the page loads.
|
|
link = f'{PUBLIC_ORIGIN}/conta/redefinir#{token}'
|
|
mail.queue(c, 'reset', email, 'Crie uma nova senha · DTF Dropstar',
|
|
'Olá!\n\nAlguém pediu para criar uma nova senha na sua conta do DTF Dropstar. '
|
|
f'Para criar, abra o link abaixo. Ele vale por 1 hora e funciona uma vez só.\n\n{link}\n\n'
|
|
'Se não foi você, ignore este e-mail: a sua senha continua a mesma.')
|
|
audit('password_reset_requested', account=str(account['id']) if account else None, ip=client_ip(request))
|
|
return {'ok': True, 'message': RESET_SENT}
|
|
|
|
@router.post('/api/account/reset')
|
|
def reset_password(body: PasswordReset, request: Request, response: Response):
|
|
rate_limit('reset-source', client_ip(request), 10)
|
|
digest = hashlib.sha256(body.token.encode()).hexdigest()
|
|
previous = current(request)
|
|
with db.connect() as c:
|
|
reset = c.execute('''SELECT * FROM dtf_local.password_resets WHERE token_hash=%s
|
|
AND used_at IS NULL AND expires_at>now() FOR UPDATE''', (digest,)).fetchone()
|
|
if not reset:
|
|
audit('password_reset_refused', ip=client_ip(request))
|
|
raise HTTPException(400, 'Este link venceu ou já foi usado. Peça outro em “Esqueci minha senha”.')
|
|
identity = reset['account_id']
|
|
account = account_row(c, identity, lock=True)
|
|
# The link came by e-mail, so the address is confirmed too.
|
|
c.execute('UPDATE dtf_local.accounts SET password_hash=%s, email_verified=true WHERE id=%s',
|
|
(password_hash(body.password), identity))
|
|
c.execute('UPDATE dtf_local.password_resets SET used_at=now() WHERE token_hash=%s', (digest,))
|
|
# Every other link to this account stops working, and so does every
|
|
# session signed in with the old password.
|
|
c.execute('DELETE FROM dtf_local.password_resets WHERE account_id=%s AND used_at IS NULL', (identity,))
|
|
if previous:
|
|
transfer_guest(c, previous, identity)
|
|
claim_orders(c, identity, account['profile'])
|
|
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (identity,))
|
|
if previous:
|
|
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
|
new_session(c, response, identity)
|
|
audit('password_reset', account=str(identity))
|
|
return {'customer': account['profile']}
|
|
|
|
# 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 q.discarded_at 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, CASE WHEN o.cancelled_at IS NOT NULL THEN 'cancelled' ELSE o.state END,
|
|
CASE WHEN o.cancelled_at IS NOT NULL OR 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), code: str | None = Query(None, max_length=12, pattern=r'^[0-9A-Fa-f]+$'),
|
|
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,
|
|
'code': code.lower() + '%' if code else None,
|
|
'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 (%(code)s::text IS NULL OR (kind='order' AND replace(id::text,'-','') LIKE %(code)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'],
|
|
'code': order_code(r['id']) if r['kind'] == 'order' else None,
|
|
'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'], '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)}
|
|
|
|
@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, 'Arquivo não encontrado.')
|
|
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Este arquivo não está mais disponível: os arquivos ficam guardados por 30 dias.')
|
|
require_clean(row)
|
|
return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}
|