Files
dtf-system/app/mail.py
Cauê Faleiros 1a9611942d
All checks were successful
Build and deploy / Validate source (push) Successful in 1m15s
Build and deploy / Integration suite on a real stack (push) Successful in 5m10s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m29s
feat: an approved order nobody paid expires in 24 h (front 9)
An approved quote with no payment expires on its own after 24 h, never
while a Pix or card attempt is still live: the worker marks
quotes.expired_at, frees its files and e-mails the customer that the
order expired and can be sent again on the Site. The backlog from before
this front expires silently.

Kanban: Cotações › Aguardando pagamento shows when each one expires and
the review gets an "Abrir conversa" WhatsApp button; Números gets
"Pedidos sem pagamento" (made, paid, expired, waiting, abandonment rate).

release_files moves to app/payments.py so the worker can use it; an
expired quote no longer counts as open there. New tests/unpaid_test.py
in the integration job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:01:26 -03:00

211 lines
10 KiB
Python

"""E-mail: the customers' account messages and order confirmation.
Messages are queued in the database inside the transaction that caused them
(an order paid, a password to recover) 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.
"""
import logging
import os
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, formatdate, make_msgid, parseaddr
from .core.pricing import sheet_label
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
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 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'))}{sheet_label(i)} · "
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 quote_expired(c, quote, origin):
"""The customer's notice that an approved, unpaid order expired after 24 h
(Fase 2, front 9): its files were deleted and they can send it again on
the Site. Returns whether it was queued (False without an e-mail)."""
customer = (quote.get('draft') or {}).get('customer') or {}
if not customer.get('mail'):
return False
from . import mail_html
link = f'{origin}/'
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
f'Quando quiser, é só montar de novo no site: {link}'])
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
mail_html.pill('Pedido expirado', 'info'),
mail_html.title('Seu pedido expirou'),
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
'expirou. Os arquivos que você enviou foram apagados.'),
mail_html.button('Montar de novo', link),
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
])
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
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
# Neither EmailMessage nor smtplib adds it, and filters (Outlook's among them) count it missing.
msg['Date'] = formatdate(localtime=True)
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']
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,
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}