feat: customer e-mails in the Site's look, and an order confirmation
All checks were successful
Build and deploy / Validate source (push) Successful in 49s
Build and deploy / Integration suite on a real stack (push) Successful in 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m17s
All checks were successful
Build and deploy / Validate source (push) Successful in 49s
Build and deploy / Integration suite on a real stack (push) Successful in 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m17s
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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: |
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
56
app/mail.py
56
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 <nao-responda@localhost>')
|
||||
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):
|
||||
|
||||
203
app/mail_html.py
Normal file
203
app/mail_html.py
Normal file
@@ -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'<tr><td style="padding:0 0 20px 0">{block}</td></tr>' for block in blocks)
|
||||
return f'''<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>DTF Dropstar</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background:#EEEBE6">
|
||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0">{escape(preheader)}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#EEEBE6">
|
||||
<tr><td align="center" style="padding:32px 12px">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;font-family:{FONT}">
|
||||
<tr><td style="background:{INK};border-radius:16px 16px 0 0;padding:22px 32px">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>
|
||||
<td style="font-family:{FONT};font-size:24px;font-weight:800;font-style:italic;letter-spacing:-0.5px;color:{ORANGE}">DROPSTAR
|
||||
<span style="font-size:12px;font-style:normal;letter-spacing:1px;color:{INK};background:{ORANGE};border-radius:6px;padding:3px 7px;vertical-align:middle">DTF</span></td>
|
||||
<td align="right" style="font-family:{FONT};font-size:12px;font-weight:600;letter-spacing:0.7px;text-transform:uppercase;color:#B9B4AC">{escape(label)}</td>
|
||||
</tr></table>
|
||||
</td></tr>
|
||||
<tr><td style="background:#FFFFFF;border-radius:0 0 16px 16px;padding:36px 36px 16px 36px">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">{rows}</table>
|
||||
</td></tr>
|
||||
<tr><td align="center" style="padding:22px 8px 0 8px;font-family:{FONT};font-size:12.5px;line-height:19px;color:{MUTED}">
|
||||
DTF Dropstar · Franca-SP · WhatsApp <a href="{WHATSAPP}" style="color:{MUTED}">16 99428-0056</a><br>
|
||||
E-mail automático, não precisa responder.
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
'''
|
||||
|
||||
|
||||
def title(text):
|
||||
return (f'<h1 style="margin:0;font-family:{FONT};font-size:26px;line-height:32px;font-weight:800;'
|
||||
f'color:{INK}">{escape(text)}</h1>')
|
||||
|
||||
|
||||
def para(text):
|
||||
return f'<p style="margin:0;font-family:{FONT};font-size:16px;line-height:25px;color:{TEXT}">{escape(text)}</p>'
|
||||
|
||||
|
||||
def small(text, html=''):
|
||||
return (f'<p style="margin:0;font-family:{FONT};font-size:13.5px;line-height:21px;color:{MUTED}">'
|
||||
f'{escape(text)}{html}</p>')
|
||||
|
||||
|
||||
def pill(text, tone='ok'):
|
||||
background, color = {'ok': ('#E7F4EA', '#1E6B34'), 'info': ('#FFF4E0', DARK_ORANGE)}[tone]
|
||||
return (f'<span style="display:inline-block;font-family:{FONT};font-size:12.5px;font-weight:700;'
|
||||
f'letter-spacing:0.7px;text-transform:uppercase;background:{background};color:{color};'
|
||||
f'border-radius:999px;padding:5px 11px">{escape(text)}</span>')
|
||||
|
||||
|
||||
def code_box(code):
|
||||
spaced = ' '.join(escape(code))
|
||||
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">'
|
||||
f'<tr><td align="center" style="background:#FFF4E0;border:1px solid #F5D9A8;border-radius:12px;padding:22px">'
|
||||
f'<div style="font-family:{FONT};font-size:12px;font-weight:700;letter-spacing:1.2px;'
|
||||
f'text-transform:uppercase;color:{DARK_ORANGE}">Seu código</div>'
|
||||
f'<div style="font-family:{FONT};font-size:38px;line-height:48px;font-weight:800;letter-spacing:6px;'
|
||||
f'color:{INK}">{spaced}</div></td></tr></table>')
|
||||
|
||||
|
||||
def button(text, url, dark=False):
|
||||
background, color = (INK, ORANGE) if dark else (ORANGE, '#241703')
|
||||
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center">'
|
||||
f'<a href="{escape(url, quote=True)}" style="display:inline-block;background:{background};color:{color};'
|
||||
f'font-family:{FONT};font-size:16px;font-weight:800;text-decoration:none;border-radius:10px;'
|
||||
f'padding:15px 30px">{escape(text)}</a></td></tr></table>')
|
||||
|
||||
|
||||
def facts(rows):
|
||||
cells = ''.join(
|
||||
f'<tr><td style="{"" if i == 0 else f"border-top:1px solid {LINE};"}padding:12px 16px;width:92px;'
|
||||
f'vertical-align:top;font-family:{FONT};font-size:15px;font-weight:600;color:{MUTED}">{escape(key)}</td>'
|
||||
f'<td style="{"" if i == 0 else f"border-top:1px solid {LINE};"}padding:12px 16px 12px 0;'
|
||||
f'font-family:{FONT};font-size:15px;line-height:22px;font-weight:500;color:{INK};white-space:pre-line">{escape(value)}</td></tr>'
|
||||
for i, (key, value) in enumerate(rows))
|
||||
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
|
||||
f'style="border:1px solid {LINE};border-radius:12px;border-collapse:separate">{cells}</table>')
|
||||
|
||||
|
||||
def callout(heading, text, warn=False):
|
||||
background, border, color = ('#FFF1EC', '#F4C7B6', '#8A2A0A') if warn else ('#F4F2EE', '#E4DFD8', TEXT)
|
||||
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>'
|
||||
f'<td style="background:{background};border:1px solid {border};border-radius:12px;padding:16px 18px">'
|
||||
f'<div style="font-family:{FONT};font-size:15px;font-weight:700;color:{color}">{escape(heading)}</div>'
|
||||
f'<div style="font-family:{FONT};font-size:14.5px;line-height:22px;color:{TEXT};padding-top:4px">'
|
||||
f'{escape(text)}</div></td></tr></table>')
|
||||
|
||||
|
||||
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'<div style="width:24px;height:24px;line-height:24px;border-radius:12px;background:{ORANGE};'
|
||||
f'color:#241703;font-family:{FONT};font-size:14px;font-weight:800;text-align:center">✓</div>'
|
||||
if done else
|
||||
'<div style="width:20px;height:20px;border-radius:12px;border:2px solid #D9D3CB;background:#FFFFFF"></div>')
|
||||
rows.append(f'<tr><td style="{top}padding:11px 14px 11px 0;width:24px;vertical-align:middle">{mark}</td>'
|
||||
f'<td style="{top}padding:11px 0;font-family:{FONT}">'
|
||||
f'<div style="font-size:15px;font-weight:{700 if done else 500};color:{INK if done else MUTED}">'
|
||||
f'{escape(label)}</div><div style="font-size:13px;line-height:19px;color:{MUTED}">{escape(hint)}</div>'
|
||||
f'</td></tr>')
|
||||
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
|
||||
f'style="border:1px solid {LINE};border-radius:12px;border-collapse:separate;padding:4px 16px">'
|
||||
f'{"".join(rows)}</table>')
|
||||
|
||||
|
||||
# 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'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
|
||||
f'{escape(link)}</a>'),
|
||||
])
|
||||
|
||||
|
||||
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.'),
|
||||
])
|
||||
@@ -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})
|
||||
|
||||
@@ -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'));
|
||||
|
||||
@@ -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 <nao-responda@dropstar.test>')
|
||||
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', '<p>código 123456</p>'))]
|
||||
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 '<p>código 123456</p>' 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 <nao-responda@dropstar.test>'
|
||||
@@ -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)
|
||||
|
||||
36
tests/test_mail_html.py
Normal file
36
tests/test_mail_html.py
Normal file
@@ -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('<b>Ana</b> Souza', 'a@x.test', 'b"<script>@x.test')
|
||||
self.assertNotIn('<script>', html)
|
||||
self.assertNotIn('<b>Ana</b>', html)
|
||||
self.assertIn('Olá, <b>Ana</b>!', html)
|
||||
self.assertEqual(mail_html.greeting(''), 'Olá!')
|
||||
self.assertEqual(mail_html.greeting(' Maria da Silva'), 'Olá, Maria!')
|
||||
|
||||
def test_every_message_is_tables_and_inline_styles(self):
|
||||
messages = [mail_html.code('Maria', 'Confirme seu e-mail', 'criar a sua conta', '216561', 15, 'nada muda.'),
|
||||
mail_html.reset('Maria', 'https://dtf.test/conta/redefinir#abc', 60),
|
||||
mail_html.account_exists('Maria', 'https://dtf.test/conta/entrar'),
|
||||
mail_html.email_changed('Maria', 'a@x.test', 'b@x.test'),
|
||||
mail_html.order_paid('Maria', 12, [('Itens', 'DTF Têxtil · 2,8 m\nDTF UV · 1 m'),
|
||||
('Total', 'R$ 70,00')], 'https://dtf.test/conta/pedidos?order=1')]
|
||||
for html in messages:
|
||||
with self.subTest(html=html[:80]):
|
||||
self.assertNotIn('<style', html)
|
||||
self.assertNotIn('display:flex', html.replace(' ', ''))
|
||||
self.assertIn('role="presentation"', html)
|
||||
self.assertIn('2 1 6 5 6 1', messages[0])
|
||||
self.assertIn('href="https://dtf.test/conta/redefinir#abc"', messages[1])
|
||||
self.assertTrue(re.search(r'Recebemos seu pedido #12', messages[4]))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user