feat: the team no longer gets alert e-mails; the Kanban user form drops the option
All checks were successful
Build and deploy / Validate source (push) Successful in 47s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m20s
All checks were successful
Build and deploy / Validate source (push) Successful in 47s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,7 +7,7 @@ from uuid import UUID, uuid4
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import mail, payments
|
||||
from .. import payments
|
||||
from ..core import db
|
||||
from ..core.auth import owner
|
||||
from ..core.models import QuoteRequest
|
||||
@@ -61,9 +61,6 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
if row['id'] == uid:
|
||||
# An operator reviews it first; the files wait for that review.
|
||||
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD)
|
||||
mail.alert(c, 'Cotação esperando revisão',
|
||||
['Um cliente montou um carrinho que precisa de revisão antes do pagamento.',
|
||||
f'Motivo: {reason}', '', *mail.summary(draft)], '/')
|
||||
return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
|
||||
|
||||
@router.get('/api/quotes/{uid}')
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
"""Kanban users and print machines, managed by the administrators.
|
||||
|
||||
An administrator creates each account with a first password and the person
|
||||
changes it in "Minha senha". Whoever wants the team's alerts by e-mail has
|
||||
them switched on here. The superadmin is
|
||||
the system's own account, set from the console (python -m app.operators);
|
||||
changes it in "Minha senha". The superadmin is the system's own account, set from the console (python -m app.operators);
|
||||
administrators manage everyone else. Nobody can remove, disable or demote
|
||||
themselves, so the last administrator cannot lock the team out by accident.
|
||||
"""
|
||||
@@ -29,8 +27,6 @@ class UserIn(StrictModel):
|
||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||
active: bool = True
|
||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||
# The team's alerts by e-mail: orders paid, carts waiting for review, payments to look at.
|
||||
alerts: bool = False
|
||||
|
||||
@field_validator('email')
|
||||
@classmethod
|
||||
@@ -74,7 +70,7 @@ def change_password(body: PasswordChange, request: Request):
|
||||
|
||||
|
||||
def user_rows(c):
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.alerts,o.last_login_at,o.created_at,
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
||||
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
|
||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
|
||||
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
||||
@@ -117,9 +113,9 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
|
||||
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active,alerts)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active, body.alerts))
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active))
|
||||
set_machines(c, uid, body.machines)
|
||||
audit('operator_created', operator=user, account=body.email, role=body.role)
|
||||
return {'id': str(uid)}
|
||||
@@ -137,8 +133,8 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
||||
if body.email != row['email'] and c.execute(
|
||||
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s,alerts=%s WHERE id=%s',
|
||||
(body.name.strip(), body.email, role, body.active, body.alerts, uid))
|
||||
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
|
||||
(body.name.strip(), body.email, role, body.active, uid))
|
||||
if body.password:
|
||||
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
||||
if body.email != row['email']:
|
||||
@@ -220,7 +216,7 @@ def test_mail(request: Request, user=Depends(can('manage'))):
|
||||
with db.connect() as c:
|
||||
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
||||
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
|
||||
'recuperação de senha dos clientes e alertas da equipe.'):
|
||||
'os e-mails dos clientes.'):
|
||||
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
||||
audit('mail_test_queued', operator=user)
|
||||
return {'ok': True, 'to': user}
|
||||
|
||||
42
app/mail.py
42
app/mail.py
@@ -1,8 +1,7 @@
|
||||
"""E-mail: the customers' account messages and order confirmation, and the
|
||||
team's alerts.
|
||||
"""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 quote waiting for review) and sent by the worker, so a slow
|
||||
(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:
|
||||
|
||||
@@ -15,7 +14,7 @@ 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.
|
||||
text.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
@@ -25,8 +24,6 @@ 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
|
||||
@@ -55,18 +52,6 @@ def queue(c, kind, to, subject, body, html=None):
|
||||
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."""
|
||||
@@ -110,24 +95,6 @@ def money(cents):
|
||||
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)
|
||||
@@ -210,8 +177,7 @@ def status(c):
|
||||
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,
|
||||
'last_sent': last, 'pending': pending,
|
||||
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}
|
||||
|
||||
@@ -107,8 +107,6 @@ def create_order(c, quote, payment):
|
||||
{'order_id': str(order['id']), 'number': order['number'],
|
||||
'event': 'payment_approved', 'order': approved,
|
||||
'payment': {'method': paid['method']} if paid else {}})
|
||||
mail.alert(c, f"Pedido #{order['number']} pago · {mail.money(approved['total_cents'])}",
|
||||
['Um pedido novo foi pago e está em Arte recebida.', '', *mail.summary(approved)], '/')
|
||||
return order, True
|
||||
|
||||
|
||||
@@ -127,19 +125,8 @@ def apply(c, event):
|
||||
|
||||
Outcomes starting 'refused' (money arrived, no order) or 'attention' (an
|
||||
order exists but its payment was reversed) stay on the Kanban until an
|
||||
operator records a resolution, and the team is told by e-mail.
|
||||
operator records a resolution.
|
||||
"""
|
||||
outcome = _apply(c, event)
|
||||
if outcome.startswith(('refused', 'attention')):
|
||||
paid = mail.money(event.amount_cents) if type(event.amount_cents) is int else 'valor não informado'
|
||||
mail.alert(c, f'Pagamento precisa de atenção · {paid}',
|
||||
['O Mercado Pago avisou de um pagamento que não virou pedido, ou que foi estornado depois.',
|
||||
'Abra Pagamentos no Kanban para ver o que aconteceu e registrar a resolução.', '',
|
||||
f'Situação: {event.status} · cotação {event.reference or "—"}', f'Registro: {outcome}'], '/')
|
||||
return outcome
|
||||
|
||||
|
||||
def _apply(c, event):
|
||||
provider_id = event.raw.get('payment_id')
|
||||
if provider_id:
|
||||
c.execute('''UPDATE dtf_local.payment_intents SET status=%s, updated_at=now()
|
||||
|
||||
Reference in New Issue
Block a user