Files
dtf-system/app/mail.py
Cauê Faleiros 3664fe827e feat: password recovery by e-mail, team alerts, and a price for files opened by hand
Pilot customers had no way to reset a forgotten password, and the 7 October
meeting asked for two things that only needed the client's inputs to go live.

Password recovery: "Esqueci minha senha" in Minha conta sends a link that
works once, for an hour (/conta/redefinir#token, in the fragment so it never
reaches a server or a Referer). Only the token's hash is stored, the e-mail's
text is erased once sent, the answer never says whether an account exists,
and a reset signs out every other session. Limited per address and source.

Team alerts: Kanban users who tick "Receber alertas por e-mail" in Usuários
get one when an order is paid, a cart waits for review, or a payment needs
attention. Messages are queued in the transaction that caused them and sent
by the worker with retries (app/mail.py). Integrações shows an E-mail row
with "Enviar teste".

E-mail is off in production (MAIL_ADAPTER=off; recovery keeps offering
WhatsApp) until the client's SMTP account exists; then it is only settings
(docs/PORTAINER.md). The local stack keeps messages in the database and log.

Files opened by hand: a finished sheet in CDR, AI, PSD or TIFF (or with a
length the customer typed) pays the full price plus MANUAL_FILE_EXTRA_CENTS
per metre, to steer customers to PNG as the meeting asked. It is 0 until
Marcus gives the amount. The Site shows it before checkout, the server
charges it, Tiny gets it in the unit price, and the Kanban says it.

Tested: new tests/mail_test (reset flow, SMTP delivery against a local SMTP
server, retry, who gets alerts), pricing unit tests, and the browser test now
checks the Site total equals the server's, run with the charge at 0 and at
R$ 5,00. The full CI suite passes in a CI-style stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:48:24 -03:00

170 lines
7.5 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 message carries a link that signs in, so its text is erased once it
is sent (or once the link 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
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 {}
cnpj = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit())
if len(cnpj) == 14:
cnpj = f'{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}'
lines = [f"Cliente: {cnpj} · {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 recovery link that expired before it could be sent is useless.
c.execute(f"""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now()
WHERE kind='reset' AND sent_at IS NULL AND failed_at IS NULL
AND created_at < now() - interval '{RESET_MINUTES} 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'] == 'reset' 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}