Files
dtf-system/app/mail.py
Cauê Faleiros b83e60ef0c
All checks were successful
Build and deploy / Validate source (push) Successful in 1m38s
Build and deploy / Integration suite on a real stack (push) Successful in 4m57s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 2m1s
feat: customers buy with a CPF or a CNPJ
The cart and the account signup take either document, each with its own
mask and check digits. Tiny gets a person (F) for a CPF, Mercado Pago the
matching identification type, and only CNPJs go to the company registry.
The Kanban, the account page and the alerts show which one it is.

Also pins the Correios test's clock: its fake token expired today, so the
suite failed from Oct 16 on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:33:50 -03:00

177 lines
7.8 KiB
Python

"""E-mail: password recovery for customers and alerts for the team.
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.
"""
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):
"""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))
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)
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:]}'
lines = [f"Cliente: {document} · {customer.get('mail', '')}"]
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):
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)
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'])
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='', 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 WHERE id=%s''', (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}