Files
dtf-system/app/mail.py
Cauê Faleiros 3879754397
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
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 <noreply@anthropic.com>
2026-10-19 09:18:20 -03:00

218 lines
10 KiB
Python

"""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
or unreachable mail server never holds up a request and a failed send is
retried. MAIL_ADAPTER chooses where they go:
off nothing is queued and recovery offers WhatsApp instead (the default,
until the client's SMTP details arrive);
log kept in the database and written to the worker's log, for the local
stack, where there is no mail server;
smtp sent through SMTP_HOST as MAIL_FROM.
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
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid, parseaddr
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
# Every Kanban link in an alert points here.
KANBAN_ORIGIN = os.environ.get('KANBAN_ORIGIN', '').rstrip('/')
RESET_MINUTES = 60
CODE_MINUTES = 15
# Messages that let someone in: their text is erased once sent, or once they
# expired unsent (minutes).
SECRET_KINDS = {'reset': RESET_MINUTES, 'code': CODE_MINUTES}
MAX_ATTEMPTS = 12
log = logging.getLogger('dtf.mail')
def configured():
return ADAPTER in ('log', 'smtp')
def required_settings():
return ('SMTP_HOST', 'MAIL_FROM')
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,html) VALUES(%s,%s,%s,%s,%s)',
(kind, to, subject, body, html))
return True
def alert(c, subject, lines, link=''):
"""The same message to every active Kanban user who asked for alerts."""
if not configured():
return
body = '\n'.join(lines)
if link and KANBAN_ORIGIN:
body += f'\n\nAbrir no Kanban: {KANBAN_ORIGIN}{link}'
body += '\n\nVocê recebe este e-mail porque os alertas estão ligados no seu usuário do Kanban (Usuários → Editar).'
for row in c.execute('SELECT email FROM dtf_local.operators WHERE active AND alerts').fetchall():
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'}
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
def summary(order):
"""The lines an alert shows about a cart or an order: who, what, delivery."""
customer = order.get('customer') or {}
document = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit())
if len(document) == 14:
document = f'{document[:2]}.{document[2:5]}.{document[5:8]}/{document[8:12]}-{document[12:]}'
elif len(document) == 11:
document = f'{document[:3]}.{document[3:6]}.{document[6:9]}-{document[9:]}'
who = ' · '.join(part for part in (customer.get('name'), document, customer.get('mail', '')) if part)
lines = [f"Cliente: {who}"]
for item in order.get('items', []):
metres = item.get('billed_metres') or item.get('metres')
lines.append(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} · {str(metres).replace('.', ',')} m")
freight = order.get('freight') or {}
lines.append('Entrega: ' + ('retirada' if freight.get('service') == 'pickup' else 'frete'))
return lines
def message(to, subject, body, html=None):
sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>')
name, address = parseaddr(sender)
msg = EmailMessage()
msg['From'] = formataddr((name or 'DTF Dropstar', address))
msg['To'] = to
msg['Subject'] = subject
msg['Message-ID'] = make_msgid(domain=address.split('@')[-1] or None)
reply = os.environ.get('MAIL_REPLY_TO', '')
if reply:
msg['Reply-To'] = reply
msg.set_content(body)
if html:
msg.add_alternative(html, subtype='html')
return msg
def send_smtp(msg):
host = os.environ['SMTP_HOST']
security = os.environ.get('SMTP_SECURITY', 'starttls')
port = int(os.environ.get('SMTP_PORT') or (465 if security == 'ssl' else 587))
user, password = os.environ.get('SMTP_USER', ''), os.environ.get('SMTP_PASSWORD', '')
context = ssl.create_default_context()
if security == 'ssl':
server = smtplib.SMTP_SSL(host, port, timeout=20, context=context)
else:
server = smtplib.SMTP(host, port, timeout=20)
with server:
if security == 'starttls':
server.starttls(context=context)
if user:
server.login(user, password)
server.send_message(msg)
def deliver(row):
msg = message(row['to_addr'], row['subject'], row['body'], row.get('html'))
if ADAPTER == 'smtp':
send_smtp(msg)
else:
log.warning('mail (%s) to %s: %s', ADAPTER, row['to_addr'], row['subject'])
def send_pending(connect, limit=5, ids=None):
"""Send what is due, a few at a time. Called by the worker every second;
`ids` sends just those messages, due or not (the tests use it)."""
if not configured():
return
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='', 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
AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now()))
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall()
for row in rows:
try:
deliver(row)
except Exception as exc:
attempts = row['attempts'] + 1
gave_up = attempts >= MAX_ATTEMPTS
c.execute('''UPDATE dtf_local.mail_queue SET attempts=%s, last_error=%s,
available_at=now() + %s * interval '1 second',
failed_at=CASE WHEN %s THEN now() END WHERE id=%s''',
(attempts, str(exc)[:500], min(3600, 2 ** min(attempts + 3, 12)), gave_up, row['id']))
log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc)
continue
# 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, html=CASE WHEN %s THEN NULL ELSE html END
WHERE id=%s''', (erase, erase, row['id']))
def status(c):
"""What the Kanban's Integrações shows about e-mail."""
last = c.execute('SELECT max(sent_at) AS at FROM dtf_local.mail_queue').fetchone()['at']
failing = c.execute('''SELECT to_addr, last_error, created_at FROM dtf_local.mail_queue
WHERE sent_at IS NULL AND last_error IS NOT NULL ORDER BY id DESC LIMIT 1''').fetchone()
pending = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL').fetchone()['n']
alerts = c.execute('SELECT count(*) AS n FROM dtf_local.operators WHERE active AND alerts').fetchone()['n']
return {'adapter': ADAPTER, 'from': os.environ.get('MAIL_FROM', '') if configured() else '',
'host': os.environ.get('SMTP_HOST', '') if ADAPTER == 'smtp' else '',
'last_sent': last, 'pending': pending, 'alerts': alerts,
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}