From 3879754397b5536d55ff84687de07360e0a6bfa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 19 Oct 2026 09:18:20 -0300 Subject: [PATCH] feat: customer e-mails in the Site's look, and an order confirmation The account e-mails (signup and e-mail change codes, new password, an address that already has an account, the changed-e-mail notice) gain an HTML version beside their plain text: the DROPSTAR header, a white card, orange buttons, the customer greeted by first name. Built with tables and inline styles only, so Gmail, Outlook and phone apps show it the same. A paid order now also e-mails the customer "Recebemos seu pedido #N": the items, delivery and total, the stages to come, and a link to the order in the account. Not for an operator's test order. A code's or a recovery link's HTML is erased with its text once sent. The team's alerts stay plain text. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/deploy.yml | 2 +- app/api/customer.py | 66 ++++++++---- app/mail.py | 56 ++++++++-- app/mail_html.py | 203 ++++++++++++++++++++++++++++++++++++ app/payments.py | 3 +- app/schema.sql | 8 +- tests/mail_test.py | 27 +++-- tests/test_mail_html.py | 36 +++++++ 8 files changed, 359 insertions(+), 42 deletions(-) create mode 100644 app/mail_html.py create mode 100644 tests/test_mail_html.py diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 8a971a3..45d1a61 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -86,7 +86,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html -v - name: Runtime and retention regressions run: | diff --git a/app/api/customer.py b/app/api/customer.py index 977f5ea..17fb8ad 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -16,7 +16,7 @@ from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, own 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 .. import mail, mail_html from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage from ..scanning import require_clean @@ -37,25 +37,42 @@ CODE_SENDS = 5 RESEND_SECONDS = 60 -def signup_code(c, signup_id, email, exists): +def signup_code(c, signup_id, email, name): """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: + an account, greeting that account's owner), queued by e-mail. Returns the + code's hash, None for the notice.""" + existing = c.execute('SELECT profile FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone() + if existing: + owner = existing['profile'].get('name') + login = f'{PUBLIC_ORIGIN}/conta/entrar' 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' + f'{mail_html.greeting(owner)}\n\nAlguém tentou criar uma conta no DTF Dropstar com este e-mail, ' + 'mas ele já tem conta.\n\n' + f'Para entrar: {login}\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.') + 'Se não foi você, ignore este e-mail: nada muda na sua conta.', + mail_html.account_exists(owner, login)) return None - return send_code(c, signup_id, email, 'criar a conta no DTF Dropstar') + return send_code(c, signup_id, email, 'signup', name) -def send_code(c, key, email, purpose): - """A fresh 6-digit code by e-mail for `purpose`; returns its hash.""" +# What a code is for: the text, the e-mail's heading, and what stays the same +# if it was not the customer who asked. +CODE_PURPOSES = { + 'signup': ('criar a sua conta no DTF Dropstar', 'Confirme seu e-mail', 'nenhuma conta é criada sem ele.'), + 'email': ('trocar o e-mail da sua conta no DTF Dropstar', 'Confirme seu novo e-mail', + 'o e-mail da conta continua o mesmo.'), +} + + +def send_code(c, key, email, purpose, name=''): + """A fresh 6-digit code by e-mail for `purpose` (CODE_PURPOSES); returns its hash.""" + text, heading, unchanged = CODE_PURPOSES[purpose] 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.') + f'{mail_html.greeting(name)}\n\nO seu código para {text} é:\n\n{code}\n\n' + f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail: {unchanged}', + mail_html.code(name, heading, text, code, mail.CODE_MINUTES, unchanged)) return code_digest(key, code) @@ -108,8 +125,7 @@ def register(body: Register, request: Request, response: Response): 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) + digest = signup_code(c, signup_id, email, profile.get('name')) 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)) @@ -197,8 +213,7 @@ def register_resend(body: SignupResend, request: Request): 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) + digest = signup_code(c, signup['id'], signup['email'], signup['profile'].get('name')) 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)) @@ -286,7 +301,7 @@ def change_email(body: EmailChange, request: Request, identity=Depends(owner)): 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') + digest = send_code(c, change, body.email, 'email', row['profile'].get('name')) 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)) @@ -301,10 +316,12 @@ def apply_email(identity, row, email): 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) + name = row['profile'].get('name') 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}. ' + f'{mail_html.greeting(name)}\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.') + 'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.', + mail_html.email_changed(name, row['email'], email)) except UniqueViolation: raise HTTPException(409, 'Este e-mail já é de outra conta.') audit('account_email_changed', account=str(identity)) @@ -333,7 +350,8 @@ def change_email_resend(body: EmailResend, request: Request, identity=Depends(ow 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') + name = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()['profile'].get('name') + digest = send_code(c, change['id'], change['new_email'], 'email', name) 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} @@ -368,7 +386,7 @@ def forgot_password(body: ForgotPassword, request: Request): 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() + account = c.execute('SELECT id,profile 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')''', @@ -376,10 +394,12 @@ def forgot_password(body: ForgotPassword, request: Request): # 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}' + name = account['profile'].get('name') 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'{mail_html.greeting(name)}\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.') + 'Se não foi você, ignore este e-mail: a sua senha continua a mesma.', + mail_html.reset(name, link, mail.RESET_MINUTES)) audit('password_reset_requested', account=str(account['id']) if account else None, ip=client_ip(request)) return {'ok': True, 'message': RESET_SENT} diff --git a/app/mail.py b/app/mail.py index e2697f4..b26a833 100644 --- a/app/mail.py +++ b/app/mail.py @@ -1,4 +1,5 @@ -"""E-mail: password recovery for customers and alerts for the team. +"""E-mail: the customers' account messages and order confirmation, and the +team's alerts. Messages are queued in the database inside the transaction that caused them (an order paid, a quote waiting for review) and sent by the worker, so a slow @@ -13,6 +14,8 @@ retried. MAIL_ADAPTER chooses where they go: A recovery link or a signup code lets someone in, so its text is erased once it is sent (or once it expired unsent); only its subject stays as a record. +Customer messages carry an HTML version (app/mail_html.py) beside the plain +text; the team's alerts are plain text. """ import logging import os @@ -42,13 +45,13 @@ def required_settings(): return ('SMTP_HOST', 'MAIL_FROM') -def queue(c, kind, to, subject, body): +def queue(c, kind, to, subject, body, html=None): """Queue one message in the caller's transaction. Returns False when e-mail is off, so the caller can say so instead of promising a message.""" if not configured(): return False - c.execute('INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body) VALUES(%s,%s,%s,%s)', - (kind, to, subject, body)) + c.execute('INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,html) VALUES(%s,%s,%s,%s,%s)', + (kind, to, subject, body, html)) return True @@ -64,6 +67,40 @@ def alert(c, subject, lines, link=''): queue(c, 'alert', row['email'], subject, body) +def order_paid(c, order, origin): + """The customer's confirmation of a paid order, with a link to it in the + account. Not for an operator's test order.""" + snapshot = order['snapshot'] + customer = snapshot.get('customer') or {} + if not customer.get('mail'): + return False + from . import mail_html + method = c.execute("""SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' + ORDER BY created_at DESC LIMIT 1""", (order['quote_id'],)).fetchone() + paid = {'pix': 'Pix', 'card': 'cartão'}.get((method or {}).get('method'), '') + freight = snapshot.get('freight') or {} + if freight.get('service') == 'pickup': + delivery = 'Retirada em Franca-SP' + else: + delivery = freight.get('description') or 'Entrega' + if freight.get('days'): + delivery += f" · até {freight['days']} dias úteis" + rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))} · " + f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m" + for i in snapshot.get('items', []))), + ('Entrega', delivery), + ('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else ''))] + number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}" + text = '\n'.join([mail_html.greeting(customer.get('name')), '', + f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. ' + 'Agora a gente confere a arte e coloca na fila de impressão.', '', + *(f'{key}: {value}' for key, value in rows), '', + f'Acompanhe cada etapa em Minha conta: {link}', '', + 'Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.']) + return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text, + mail_html.order_paid(customer.get('name'), number, rows, link)) + + PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas', 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'} @@ -91,7 +128,7 @@ def summary(order): return lines -def message(to, subject, body): +def message(to, subject, body, html=None): sender = os.environ.get('MAIL_FROM', 'DTF Dropstar ') name, address = parseaddr(sender) msg = EmailMessage() @@ -103,6 +140,8 @@ def message(to, subject, body): if reply: msg['Reply-To'] = reply msg.set_content(body) + if html: + msg.add_alternative(html, subtype='html') return msg @@ -125,7 +164,7 @@ def send_smtp(msg): def deliver(row): - msg = message(row['to_addr'], row['subject'], row['body']) + msg = message(row['to_addr'], row['subject'], row['body'], row.get('html')) if ADAPTER == 'smtp': send_smtp(msg) else: @@ -140,7 +179,7 @@ def send_pending(connect, limit=5, ids=None): with connect() as c: # A link or a code that expired before it could be sent is useless. for kind, minutes in SECRET_KINDS.items(): - c.execute("""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now() + c.execute("""UPDATE dtf_local.mail_queue SET body='', html=NULL, last_error='expirou sem ser enviado', failed_at=now() WHERE kind=%s AND sent_at IS NULL AND failed_at IS NULL AND created_at < now() - %s * interval '1 minute'""", (kind, minutes)) rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL @@ -161,7 +200,8 @@ def send_pending(connect, limit=5, ids=None): # The local log keeps the text so the link can be followed by hand. erase = row['kind'] in SECRET_KINDS and ADAPTER != 'log' c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL, - body=CASE WHEN %s THEN '' ELSE body END WHERE id=%s''', (erase, row['id'])) + body=CASE WHEN %s THEN '' ELSE body END, html=CASE WHEN %s THEN NULL ELSE html END + WHERE id=%s''', (erase, erase, row['id'])) def status(c): diff --git a/app/mail_html.py b/app/mail_html.py new file mode 100644 index 0000000..f08b2ed --- /dev/null +++ b/app/mail_html.py @@ -0,0 +1,203 @@ +"""The customer e-mails' HTML, next to the plain text every message keeps. + +Built for mail clients, not browsers: tables for layout, every style inline, +no web fonts or images (Outlook ignores flex, many clients block images until +asked), so it reads the same in Gmail, Outlook and phone apps. The look is +the Site's: the DROPSTAR wordmark in orange on black, a white card, orange +buttons. Every value put in is escaped here; callers pass plain text. +""" +from html import escape + +ORANGE, INK, DARK_ORANGE = '#FFA81A', '#03060B', '#C25E00' +TEXT, MUTED, LINE = '#3A3733', '#5E5A54', '#ECE8E2' +FONT = "Inter, 'Helvetica Neue', Helvetica, Arial, sans-serif" +WHATSAPP = 'https://wa.me/5516994280056' + + +def greeting(name): + first = (name or '').split() + return f'Olá, {first[0]}!' if first else 'Olá!' + + +def layout(preheader, label, blocks): + """The whole message: the dark header, the card holding `blocks` (already + HTML), and the footer. The preheader is the line inboxes show after the + subject.""" + rows = ''.join(f'{block}' for block in blocks) + return f''' + + + + + +DTF Dropstar + + +
{escape(preheader)}
+ + +
+ + + + +
+ + + +
DROPSTAR +DTF{escape(label)}
+
+{rows}
+
+DTF Dropstar · Franca-SP · WhatsApp 16 99428-0056
+E-mail automático, não precisa responder. +
+
+ + +''' + + +def title(text): + return (f'

{escape(text)}

') + + +def para(text): + return f'

{escape(text)}

' + + +def small(text, html=''): + return (f'

' + f'{escape(text)}{html}

') + + +def pill(text, tone='ok'): + background, color = {'ok': ('#E7F4EA', '#1E6B34'), 'info': ('#FFF4E0', DARK_ORANGE)}[tone] + return (f'{escape(text)}') + + +def code_box(code): + spaced = ' '.join(escape(code)) + return (f'' + f'
' + f'
Seu código
' + f'
{spaced}
') + + +def button(text, url, dark=False): + background, color = (INK, ORANGE) if dark else (ORANGE, '#241703') + return (f'
' + f'{escape(text)}
') + + +def facts(rows): + cells = ''.join( + f'{escape(key)}' + f'{escape(value)}' + for i, (key, value) in enumerate(rows)) + return (f'{cells}
') + + +def callout(heading, text, warn=False): + background, border, color = ('#FFF1EC', '#F4C7B6', '#8A2A0A') if warn else ('#F4F2EE', '#E4DFD8', TEXT) + return (f'' + f'
' + f'
{escape(heading)}
' + f'
' + f'{escape(text)}
') + + +def steps(items): + """The order's stages: (label, hint, done).""" + rows = [] + for i, (label, hint, done) in enumerate(items): + top = '' if i == 0 else 'border-top:1px solid #F1EDE7;' + mark = (f'
✓
' + if done else + '
') + rows.append(f'{mark}' + f'' + f'
' + f'{escape(label)}
{escape(hint)}
' + f'') + return (f'' + f'{"".join(rows)}
') + + +# The messages --------------------------------------------------------------- + +def code(name, heading, purpose, digits, minutes, ignore): + return layout(f'{digits} é o seu código', 'Sua conta', [ + title(heading), + para(f'{greeting(name)} Use o código abaixo para {purpose}.'), + code_box(digits), + small(f'O código vale por {minutes} minutos. Se não foi você que pediu, ignore este e-mail: {ignore}'), + ]) + + +def reset(name, link, minutes): + hours = 'por 1 hora' if minutes == 60 else f'por {minutes} minutos' + return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [ + title('Crie uma nova senha'), + para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. ' + 'É só clicar no botão abaixo.'), + button('Criar nova senha', link), + small(f'O link vale {hours} e funciona uma vez só. Se não foi você, ignore este e-mail: ' + 'sua senha continua a mesma.'), + small('O botão não abriu? Copie este endereço no navegador: ', + f'
' + f'{escape(link)}'), + ]) + + +def account_exists(name, login_link): + return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [ + title('Este e-mail já tem uma conta'), + para(f'{greeting(name)} Alguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já está ' + 'cadastrado. Para ver seus pedidos, é só entrar.'), + button('Entrar na minha conta', login_link), + callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link ' + 'para criar outra.'), + small('Se não foi você, ignore este e-mail: nada muda na sua conta.'), + ]) + + +def email_changed(name, old, new): + return layout('O e-mail da sua conta foi trocado.', 'Sua conta', [ + title('O e-mail da sua conta foi trocado'), + para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'), + facts([('Antes', old), ('Agora', new)]), + callout('Não foi você?', 'Fale com a Dropstar agora pelo WhatsApp: a gente ajuda a recuperar a conta.', + warn=True), + button('Falar no WhatsApp', WHATSAPP, dark=True), + ]) + + +def order_paid(name, number, rows, link): + return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [ + pill('Pagamento aprovado'), + title(f'Recebemos seu pedido #{number}'), + para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. Agora a gente ' + 'confere a arte e coloca na fila de impressão.'), + facts(rows), + steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True), + ('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False), + ('Impressão', 'Seu filme entra na máquina', False), + ('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]), + button('Ver meu pedido', link), + small('Acompanhe cada etapa em Minha conta. Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ ' + 'do pedido: ele aparece lá na hora.'), + ]) diff --git a/app/payments.py b/app/payments.py index 5f3b3b3..586fcce 100644 --- a/app/payments.py +++ b/app/payments.py @@ -19,7 +19,7 @@ from psycopg.types.json import Jsonb from . import mail from .core.auth import audit from .printjobs import queue as queue_print_files -from .runtime import enqueue, upload_row +from .runtime import PUBLIC_ORIGIN, enqueue, upload_row from .scanning import require_clean QUOTE_VALID_HOURS = 24 @@ -99,6 +99,7 @@ def create_order(c, quote, payment): queue_print_files(c, order['id'], len(approved['items'])) if is_test(order): return order, True + mail.order_paid(c, order, PUBLIC_ORIGIN) enqueue(c, f"{order['id']}:paid:tiny", 'tiny', {'order_id': str(order['id']), 'number': order['number'], 'event': 'payment_approved', 'order': approved}) diff --git a/app/schema.sql b/app/schema.sql index bee0c05..a9fbcb9 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -276,6 +276,9 @@ CREATE TABLE IF NOT EXISTS dtf_local.mail_queue ( created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(), attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz ); +-- The HTML version of a customer message (app/mail_html.py); erased with the +-- text for a code or a recovery link. +ALTER TABLE dtf_local.mail_queue ADD COLUMN IF NOT EXISTS html text; CREATE INDEX IF NOT EXISTS mail_queue_pending ON dtf_local.mail_queue(available_at, id) WHERE sent_at IS NULL AND failed_at IS NULL; -- A customer's password recovery: only the token's hash is kept, for an hour, @@ -321,9 +324,10 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A OR EXISTS (SELECT 1 FROM dtf_local.mail_queue m WHERE m.kind='code' AND lower(m.to_addr)=a.email AND m.created_at<=a.created_at)); -- E-mail kinds: a password-recovery link, a code, the notice that an account --- already exists, the notice of a changed e-mail, the team's alerts and a test. +-- already exists, the notice of a changed e-mail, a customer's paid order, +-- the team's alerts and a test. -- Defined once, here: the schema runs on every start, and an earlier, narrower -- copy would refuse the rows of the kinds added after it. ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check - CHECK(kind IN ('reset','code','account','notice','alert','test')); + CHECK(kind IN ('reset','code','account','notice','order','alert','test')); diff --git a/tests/mail_test.py b/tests/mail_test.py index 3d57a55..dbb94ba 100644 --- a/tests/mail_test.py +++ b/tests/mail_test.py @@ -140,6 +140,8 @@ def signup(tag): with db.connect() as c: assert not c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone() first = code_of(c, address) + html = queued(c, address, 'code')[-1]['html'] + assert ' '.join(first) in html and 'Confirme seu e-mail' in html, html[:200] # The password is stored hashed from the first step. assert c.execute('SELECT password_hash FROM dtf_local.account_signups WHERE id=%s', (started['verify'],)).fetchone()['password_hash'].startswith('scrypt-v2$') @@ -240,14 +242,20 @@ def smtp_delivery(tag): MAIL_FROM='DTF Dropstar ') with db.connect() as c: # Not due yet, so the stack's own worker leaves them to this test. - ids = [c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at) - VALUES(%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''', - (kind, to, subject, body)).fetchone()['id'] - for kind, subject, body in (('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção'), - ('alert', 'Pedido pago', 'olá equipe'), - ('code', '123456 é o seu código', 'código 123456'))] + ids = [c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,html,available_at) + VALUES(%s,%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''', + (kind, to, subject, body, html)).fetchone()['id'] + for kind, subject, body, html in ( + ('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção', None), + ('alert', 'Pedido pago', 'olá equipe', None), + ('code', '123456 é o seu código', 'código 123456', '

código 123456

'))] mail.send_pending(db.connect, ids=ids) assert len(sink.messages) == 3, sink.messages + # A customer message goes as plain text and HTML, the client picks. + coded = sink.messages[2][1] + assert coded.get_content_type() == 'multipart/alternative', coded.get_content_type() + assert coded.get_body(('plain',)).get_content().strip() == 'código 123456' + assert '

código 123456

' in coded.get_body(('html',)).get_content() rcpt, first = sink.messages[0] assert to in rcpt[0] and first['Subject'] == 'Crie uma nova senha · DTF Dropstar' assert first['From'] == 'DTF Dropstar ' @@ -256,7 +264,7 @@ def smtp_delivery(tag): sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'alert') + queued(c, to, 'code')} # A recovery link or a signup code is erased once sent; an alert keeps its text. assert sent['reset']['sent_at'] and sent['reset']['body'] == '' - assert sent['code']['sent_at'] and sent['code']['body'] == '' + assert sent['code']['sent_at'] and sent['code']['body'] == '' and sent['code']['html'] is None assert sent['alert']['sent_at'] and sent['alert']['body'] == 'olá equipe' # A server that does not answer: retried later, with the error kept. @@ -306,6 +314,11 @@ def alerts(tag): [alert] = [r for r in queued(c, wants, 'alert') if f"#{order['number']}" in r['subject']] assert 'pago' in alert['subject'] and '11.222.333/0001-81' in alert['body'] and '1,2 m' in alert['body'] assert 'Abrir no Kanban: http' in alert['body'] + # The customer gets the confirmation, with the order in the account. + [confirmed] = queued(c, f'alerta-{tag}@example.test', 'order') + assert confirmed['subject'] == f"Recebemos seu pedido #{order['number']} · DTF Dropstar" + assert f"/conta/pedidos?order={order['id']}" in confirmed['body'] and 'Retirada em Franca-SP' in confirmed['body'] + assert f"Recebemos seu pedido #{order['number']}" in confirmed['html'] and 'Ver meu pedido' in confirmed['html'] assert not queued(c, quiet, 'alert') and not queued(c, away, 'alert') # The test message goes to whoever asked for it. sent = su.call('/operator/mail/test', {}, operator=True) diff --git a/tests/test_mail_html.py b/tests/test_mail_html.py new file mode 100644 index 0000000..08fea92 --- /dev/null +++ b/tests/test_mail_html.py @@ -0,0 +1,36 @@ +"""The customer e-mails' HTML: escaped values, the name in the greeting, and a +layout mail clients render (tables and inline styles only).""" +import re +import unittest + +from app import mail_html + + +class MailHtmlTest(unittest.TestCase): + def test_values_are_escaped_and_the_first_name_greets(self): + html = mail_html.email_changed('Ana Souza', 'a@x.test', 'b"