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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-20 09:37:41 -03:00
parent 14a43f2ada
commit c8857a5bf5
11 changed files with 43 additions and 114 deletions

View File

@@ -7,7 +7,7 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from .. import mail, payments from .. import payments
from ..core import db from ..core import db
from ..core.auth import owner from ..core.auth import owner
from ..core.models import QuoteRequest from ..core.models import QuoteRequest
@@ -61,9 +61,6 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
if row['id'] == uid: if row['id'] == uid:
# An operator reviews it first; the files wait for that review. # An operator reviews it first; the files wait for that review.
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD) 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'} return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
@router.get('/api/quotes/{uid}') @router.get('/api/quotes/{uid}')

View File

@@ -1,9 +1,7 @@
"""Kanban users and print machines, managed by the administrators. """Kanban users and print machines, managed by the administrators.
An administrator creates each account with a first password and the person 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 changes it in "Minha senha". The superadmin is the system's own account, set from the console (python -m app.operators);
them switched on here. 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 administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident. 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) password: str | None = Field(default=None, min_length=8, max_length=128)
active: bool = True active: bool = True
machines: list[UUID] = Field(default_factory=list, max_length=50) 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') @field_validator('email')
@classmethod @classmethod
@@ -74,7 +70,7 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c): 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 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 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() 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: with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone(): 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.') 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) c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password), VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active, body.alerts)) body.role, body.active))
set_machines(c, uid, body.machines) set_machines(c, uid, body.machines)
audit('operator_created', operator=user, account=body.email, role=body.role) audit('operator_created', operator=user, account=body.email, role=body.role)
return {'id': str(uid)} 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( if body.email != row['email'] and c.execute(
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone(): '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.') 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', 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, body.alerts, uid)) (body.name.strip(), body.email, role, body.active, uid))
if body.password: if body.password:
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid)) c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
if body.email != row['email']: if body.email != row['email']:
@@ -220,7 +216,7 @@ def test_mail(request: Request, user=Depends(can('manage'))):
with db.connect() as c: with db.connect() as c:
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF', 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: ' '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.') raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
audit('mail_test_queued', operator=user) audit('mail_test_queued', operator=user)
return {'ok': True, 'to': user} return {'ok': True, 'to': user}

View File

@@ -1,8 +1,7 @@
"""E-mail: the customers' account messages and order confirmation, and the """E-mail: the customers' account messages and order confirmation.
team's alerts.
Messages are queued in the database inside the transaction that caused them 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 or unreachable mail server never holds up a request and a failed send is
retried. MAIL_ADAPTER chooses where they go: 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 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. 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 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 logging
import os import os
@@ -25,8 +24,6 @@ from email.message import EmailMessage
from email.utils import formataddr, make_msgid, parseaddr from email.utils import formataddr, make_msgid, parseaddr
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off') 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 RESET_MINUTES = 60
CODE_MINUTES = 15 CODE_MINUTES = 15
# Messages that let someone in: their text is erased once sent, or once they # 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 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): def order_paid(c, order, origin):
"""The customer's confirmation of a paid order, with a link to it in the """The customer's confirmation of a paid order, with a link to it in the
account. Not for an operator's test order.""" account. Not for an operator's test order."""
@@ -110,24 +95,6 @@ def money(cents):
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}' 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): def message(to, subject, body, html=None):
sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>') sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>')
name, address = parseaddr(sender) 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 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() 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'] 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 '', return {'adapter': ADAPTER, 'from': os.environ.get('MAIL_FROM', '') if configured() else '',
'host': os.environ.get('SMTP_HOST', '') if ADAPTER == 'smtp' 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} 'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}

View File

@@ -107,8 +107,6 @@ def create_order(c, quote, payment):
{'order_id': str(order['id']), 'number': order['number'], {'order_id': str(order['id']), 'number': order['number'],
'event': 'payment_approved', 'order': approved, 'event': 'payment_approved', 'order': approved,
'payment': {'method': paid['method']} if paid else {}}) '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 return order, True
@@ -127,19 +125,8 @@ def apply(c, event):
Outcomes starting 'refused' (money arrived, no order) or 'attention' (an Outcomes starting 'refused' (money arrived, no order) or 'attention' (an
order exists but its payment was reversed) stay on the Kanban until 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') provider_id = event.raw.get('payment_id')
if provider_id: if provider_id:
c.execute('''UPDATE dtf_local.payment_intents SET status=%s, updated_at=now() c.execute('''UPDATE dtf_local.payment_intents SET status=%s, updated_at=now()

View File

@@ -89,7 +89,6 @@ x-app: &app
SMTP_SECURITY: ${SMTP_SECURITY:-starttls} SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
SMTP_USER: ${SMTP_USER:-} SMTP_USER: ${SMTP_USER:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-} SMTP_PASSWORD: ${SMTP_PASSWORD:-}
KANBAN_ORIGIN: ${KANBAN_ORIGIN:-http://localhost:${KANBAN_PORT:-8081}}
STORAGE_ADAPTER: s3-local STORAGE_ADAPTER: s3-local
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500} MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120} MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120}

View File

@@ -123,7 +123,6 @@ x-app-environment: &app-environment
SMTP_SECURITY: ${SMTP_SECURITY:-starttls} SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
SMTP_USER: ${SMTP_USER:-} SMTP_USER: ${SMTP_USER:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-} SMTP_PASSWORD: ${SMTP_PASSWORD:-}
KANBAN_ORIGIN: https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
STORAGE_ADAPTER: s3-r2 STORAGE_ADAPTER: s3-r2
PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN} PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN}
PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN} PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN}

View File

@@ -236,9 +236,9 @@ endpoints, marker/tag behaviour, and rate limits before production use.
`app/mail.py` (2026-10-13): customers' password recovery (a one-time link, `app/mail.py` (2026-10-13): customers' password recovery (a one-time link,
valid one hour, sent to `/conta/redefinir#token`; only the token's hash is valid one hour, sent to `/conta/redefinir#token`; only the token's hash is
stored and the message text is erased once sent) and alerts to the Kanban stored and the message text is erased once sent). Since 2026-10-20 the team
users who switch them on (order paid, quote waiting for review, payment gets no alert e-mails: the Kanban and Tiny are where orders are followed.
needing attention). Messages are queued in the transaction that caused them and Messages are queued in the transaction that caused them and
sent by the worker with retries. `MAIL_ADAPTER` is `off` in production until sent by the worker with retries. `MAIL_ADAPTER` is `off` in production until
the client's SMTP account exists (recovery then offers WhatsApp), `log` on the the client's SMTP account exists (recovery then offers WhatsApp), `log` on the
local stack, `smtp` with `SMTP_*` and `MAIL_FROM`. local stack, `smtp` with `SMTP_*` and `MAIL_FROM`.

View File

@@ -265,11 +265,11 @@ with db.connect() as c:
admin = Client() admin = Client()
textil = admin.call('/operator/machines', {'name': 'Têxtil 1', 'products': ['textil']}, operator=True)['id'] textil = admin.call('/operator/machines', {'name': 'Têxtil 1', 'products': ['textil']}, operator=True)['id']
admin.call('/operator/machines', {'name': 'UV 1', 'products': ['uv']}, operator=True) admin.call('/operator/machines', {'name': 'UV 1', 'products': ['uv']}, operator=True)
for name, email, role, machines, alerts in ( for name, email, role, machines in (
('Ana Souza', 'ana@dropstar.test', 'admin', [], True), ('Diego Ramos', 'diego@dropstar.test', 'gestao', [], True), ('Ana Souza', 'ana@dropstar.test', 'admin', []), ('Diego Ramos', 'diego@dropstar.test', 'gestao', []),
('Bruno Souza', 'bruno@dropstar.test', 'operador', [textil], False), ('Carla Dias', 'carla@dropstar.test', 'vendedor', [], False)): ('Bruno Souza', 'bruno@dropstar.test', 'operador', [textil]), ('Carla Dias', 'carla@dropstar.test', 'vendedor', [])):
admin.call('/operator/users', {'name': name, 'email': email, 'role': role, 'password': 'senha-de-exemplo-123', admin.call('/operator/users', {'name': name, 'email': email, 'role': role, 'password': 'senha-de-exemplo-123',
'machines': machines, 'alerts': alerts}, operator=True) 'machines': machines}, operator=True)
# Pedro's account (Camisetas Ipê): it brings his orders, one in correction, for Minha conta. # Pedro's account (Camisetas Ipê): it brings his orders, one in correction, for Minha conta.
from tests.smoke_test import register from tests.smoke_test import register

View File

@@ -96,7 +96,7 @@ if(which==='kanban'){
board.providers={...board.providers,payment:'mercadopago', board.providers={...board.providers,payment:'mercadopago',
freight:{services:{jadlog:'Jadlog',pac:'Correios PAC',sedex:'Correios SEDEX'},box_cm:['63','15.5','15.5'],production_days:1, freight:{services:{jadlog:'Jadlog',pac:'Correios PAC',sedex:'Correios SEDEX'},box_cm:['63','15.5','15.5'],production_days:1,
base_kg:'0.3',per_metre_kg:'0.075',cubage_kg_m3:'300',cubed_kg:'4.541',metres_per_box:'60'}, base_kg:'0.3',per_metre_kg:'0.075',cubage_kg_m3:'300',cubed_kg:'4.541',metres_per_box:'60'},
mail:{adapter:'smtp',alerts:2,pending:0,last_sent:at(1),from:'nao-responda@dropstardtf.com.br'}, mail:{adapter:'smtp',pending:0,last_sent:at(1),from:'nao-responda@dropstardtf.com.br'},
backup:{last_ok:new Date(now.getFullYear(),now.getMonth(),now.getDate(),3,0).toISOString(),bytes:418000,failed:null,requested:false}}; backup:{last_ok:new Date(now.getFullYear(),now.getMonth(),now.getDate(),3,0).toISOString(),bytes:418000,failed:null,requested:false}};
FOLDER.mode='folder';FOLDER.handle={name:'FlexiPRINT'};FOLDER.granted=true;FOLDER.when='rec';FOLDER.error='';FOLDER.status=''; FOLDER.mode='folder';FOLDER.handle={name:'FlexiPRINT'};FOLDER.granted=true;FOLDER.when='rec';FOLDER.error='';FOLDER.status='';
FOLDER.saved=new Map(Array.from({length:12},(_,i)=>['u'+i,{place:'queue'}]));FOLDER.last=new Date(now-25*60e3); FOLDER.saved=new Map(Array.from({length:12},(_,i)=>['u'+i,{place:'queue'}]));FOLDER.last=new Date(now-25*60e3);

View File

@@ -1,4 +1,4 @@
"""E-mail: a customer's password recovery, and the team's alerts. """E-mail: a customer's password recovery, signup codes and order confirmation.
Run inside the API container: python -m tests.mail_test Run inside the API container: python -m tests.mail_test
The local stack keeps e-mail in the database (MAIL_ADAPTER=log); the SMTP The local stack keeps e-mail in the database (MAIL_ADAPTER=log); the SMTP
@@ -247,7 +247,7 @@ def smtp_delivery(tag):
(kind, to, subject, body, html)).fetchone()['id'] (kind, to, subject, body, html)).fetchone()['id']
for kind, subject, body, html in ( for kind, subject, body, html in (
('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção', None), ('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção', None),
('alert', 'Pedido pago', 'olá equipe', None), ('test', 'Teste de e-mail', 'olá equipe', None),
('code', '123456 é o seu código', 'código 123456', '<p>código 123456</p>'))] ('code', '123456 é o seu código', 'código 123456', '<p>código 123456</p>'))]
mail.send_pending(db.connect, ids=ids) mail.send_pending(db.connect, ids=ids)
assert len(sink.messages) == 3, sink.messages assert len(sink.messages) == 3, sink.messages
@@ -261,17 +261,17 @@ def smtp_delivery(tag):
assert first['From'] == 'DTF Dropstar <nao-responda@dropstar.test>' assert first['From'] == 'DTF Dropstar <nao-responda@dropstar.test>'
assert first.get_content().strip() == 'link secreto ção' assert first.get_content().strip() == 'link secreto ção'
with db.connect() as c: with db.connect() as c:
sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'alert') + queued(c, to, 'code')} sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'test') + queued(c, to, 'code')}
# A recovery link or a signup code is erased once sent; an alert keeps its text. # A recovery link or a signup code is erased once sent; other messages keep their text.
assert sent['reset']['sent_at'] and sent['reset']['body'] == '' assert sent['reset']['sent_at'] and sent['reset']['body'] == ''
assert sent['code']['sent_at'] and sent['code']['body'] == '' and sent['code']['html'] is None assert sent['code']['sent_at'] and sent['code']['body'] == '' and sent['code']['html'] is None
assert sent['alert']['sent_at'] and sent['alert']['body'] == 'olá equipe' assert sent['test']['sent_at'] and sent['test']['body'] == 'olá equipe'
# A server that does not answer: retried later, with the error kept. # A server that does not answer: retried later, with the error kept.
os.environ['SMTP_PORT'] = '1' os.environ['SMTP_PORT'] = '1'
with db.connect() as c: with db.connect() as c:
failing = c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at) failing = c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at)
VALUES('alert',%s,'x','y',now()+interval '1 hour') RETURNING id''', (to,)).fetchone()['id'] VALUES('test',%s,'x','y',now()+interval '1 hour') RETURNING id''', (to,)).fetchone()['id']
mail.send_pending(db.connect, ids=[failing]) mail.send_pending(db.connect, ids=[failing])
with db.connect() as c: with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.mail_queue WHERE id=%s', (failing,)).fetchone() row = c.execute('SELECT * FROM dtf_local.mail_queue WHERE id=%s', (failing,)).fetchone()
@@ -288,38 +288,27 @@ def smtp_delivery(tag):
sink.shutdown() sink.shutdown()
def alerts(tag): def order_confirmation(tag):
"""Who gets the team's alerts, and that a paid order sends one.""" """A paid order sends the customer the confirmation, and the team nothing."""
su = Client() su = Client()
su.call('/session') su.call('/session')
wants, quiet, away = (f'{n}-{tag}@example.test' for n in ('alertas', 'quieto', 'fora'))
for address, on, active in ((wants, True, True), (quiet, False, True), (away, True, False)):
su.call('/operator/users', {'name': address, 'email': address, 'role': 'gestao', 'password': PASSWORD,
'alerts': on, 'active': active}, operator=True)
users = {u['email']: u for u in su.call('/operator/users', operator=True)['users']}
assert users[wants]['alerts'] is True and users[quiet]['alerts'] is False
board = su.call('/operator/board', operator=True)
assert board['providers']['mail']['adapter'] == 'log' and board['providers']['mail']['alerts'] >= 1
customer = Client() customer = Client()
customer.call('/session') customer.call('/session')
uid = upload_bytes(customer, b'MAIL ALERT ARTWORK') uid = upload_bytes(customer, b'MAIL ORDER ARTWORK')
item = item_spec('file', '1.2', 0, uid) item = item_spec('file', '1.2', 0, uid)
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'items': [item], quote = customer.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'alerta-{tag}@example.test'}, 'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'pedido-{tag}@example.test'},
'freight': {'service': 'pickup'}}) 'freight': {'service': 'pickup'}})
approved_quote(customer, quote, [item]) approved_quote(customer, quote, [item])
order = customer.call('/orders/dev-paid', {'quote_id': quote['id']}) order = customer.call('/orders/dev-paid', {'quote_id': quote['id']})
with db.connect() as c: with db.connect() as c:
[alert] = [r for r in queued(c, wants, 'alert') if f"#{order['number']}" in r['subject']]
assert 'pago' in alert['subject'] and '11.222.333/0001-81' in alert['body'] and '1,2 m' in alert['body']
assert 'Abrir no Kanban: http' in alert['body']
# The customer gets the confirmation, with the order in the account. # The customer gets the confirmation, with the order in the account.
[confirmed] = queued(c, f'alerta-{tag}@example.test', 'order') [confirmed] = queued(c, f'pedido-{tag}@example.test', 'order')
assert confirmed['subject'] == f"Recebemos seu pedido #{order['number']} · DTF Dropstar" assert confirmed['subject'] == f"Recebemos seu pedido #{order['number']} · DTF Dropstar"
assert f"/conta/pedidos?order={order['id']}" in confirmed['body'] and 'Retirada em Franca-SP' in confirmed['body'] assert f"/conta/pedidos?order={order['id']}" in confirmed['body'] and 'Retirada em Franca-SP' in confirmed['body']
assert f"Recebemos seu pedido #{order['number']}" in confirmed['html'] and 'Ver meu pedido' in confirmed['html'] assert f"Recebemos seu pedido #{order['number']}" in confirmed['html'] and 'Ver meu pedido' in confirmed['html']
assert not queued(c, quiet, 'alert') and not queued(c, away, 'alert') assert not c.execute("SELECT 1 FROM dtf_local.mail_queue WHERE kind='alert' AND subject LIKE %s",
(f"%#{order['number']} %",)).fetchone()
# The test message goes to whoever asked for it. # The test message goes to whoever asked for it.
sent = su.call('/operator/mail/test', {}, operator=True) sent = su.call('/operator/mail/test', {}, operator=True)
with db.connect() as c: with db.connect() as c:
@@ -393,11 +382,11 @@ def run():
signup(tag) signup(tag)
email_change(tag) email_change(tag)
smtp_delivery(tag) smtp_delivery(tag)
order, quote = alerts(tag) order, quote = order_confirmation(tag)
made.append((order, quote)) made.append((order, quote))
claimed_orders(tag, made) claimed_orders(tag, made)
print('PASS: password recovery by a one-time link, signup and e-mail changes confirmed by an e-mailed code, ' print('PASS: password recovery by a one-time link, signup and e-mail changes confirmed by an e-mailed code, '
'SMTP delivery and retry, alerts to who asked for them, guest orders brought by CPF/CNPJ and e-mail') 'SMTP delivery and retry, order confirmation and no team alerts, guest orders brought by CPF/CNPJ and e-mail')
finally: finally:
with db.connect() as c: with db.connect() as c:
for order, quote in made: for order, quote in made:

View File

@@ -1097,7 +1097,7 @@ function renderUsers(){
const machineName=id=>machines.find(m=>m.id===id)?.name||'—'; const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
const rows=users.map(u=>{ const rows=users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off'); const tr=node('tr');if(!u.active)tr.classList.add('off');
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email+(u.alerts?' · recebe alertas':''),'faint block')); const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email,'faint block'));
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—')); const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—'));
const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint'); const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint');
const actions=node('td',undefined,'actions'); const actions=node('td',undefined,'actions');
@@ -1143,16 +1143,14 @@ function userForm(u){
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'8 caracteres ou mais'; pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'8 caracteres ou mais';
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email; const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)'); const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
const alerts=node('input');alerts.type='checkbox';alerts.checked=!!u?.alerts;
const alertsLabel=node('label',undefined,'check');alertsLabel.append(alerts,'Receber alertas por e-mail (pedido pago, cotação para revisar, pagamento com problema)');
const boxes=usersData.machines.map(m=>{const c=node('input');c.type='checkbox';c.value=m.id;c.checked=!!u?.machines.includes(m.id); const boxes=usersData.machines.map(m=>{const c=node('input');c.type='checkbox';c.value=m.id;c.checked=!!u?.machines.includes(m.id);
const l=node('label',undefined,'check');l.append(c,m.name);return l;}); const l=node('label',undefined,'check');l.append(c,m.name);return l;});
const machinesField=node('div',undefined,'mfield'); const machinesField=node('div',undefined,'mfield');
machinesField.append('Máquinas (só para operadores; nenhuma = todas)',...(boxes.length?boxes:[node('span','Nenhuma máquina cadastrada.','faint')])); machinesField.append('Máquinas (só para operadores; nenhuma = todas)',...(boxes.length?boxes:[node('span','Nenhuma máquina cadastrada.','faint')]));
const syncMachines=()=>{machinesField.hidden=role.value!=='operador';};role.onchange=syncMachines;syncMachines(); const syncMachines=()=>{machinesField.hidden=role.value!=='operador';};role.onchange=syncMachines;syncMachines();
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role), dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel,alertsLabel],async()=>{ field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,alerts:alerts.checked, const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
machines:role.value==='operador'?boxes.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value):[], machines:role.value==='operador'?boxes.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value):[],
password:pass.value||null}; password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body); await api(editing?'/users/'+u.id:'/users',body);
@@ -1689,22 +1687,20 @@ function renderIntegrations(){
$('integrations').replaceChildren(...rows); $('integrations').replaceChildren(...rows);
eventFilters(); eventFilters();
} }
// E-mail: customers' password recovery and the team's alerts (app/mail.py). // E-mail: the customers' messages (app/mail.py).
function mailRow(m){ function mailRow(m){
const name='E-mail'; const name='E-mail';
if(m.adapter!=='smtp'&&m.adapter!=='log')return integration({name,state:'Não configurado',tone:'off', if(m.adapter!=='smtp'&&m.adapter!=='log')return integration({name,state:'Não configurado',tone:'off',
summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'}); summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'});
const local=m.adapter==='log'; const local=m.adapter==='log';
const who=m.alerts?m.alerts+(m.alerts>1?' pessoas recebem':' pessoa recebe')+' os alertas':'ninguém recebe os alertas ainda';
return integration({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok', return integration({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'Recuperação de senha e alertas · '+who+'.', summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'E-mails dos clientes: confirmação de pedido, recuperação de senha e códigos de confirmação.',
actions:[button('Enviar teste',async()=>{const r=await api('/mail/test',{}); actions:[button('Enviar teste',async()=>{const r=await api('/mail/test',{});
say(local?'Teste registrado. Neste ambiente os e-mails ficam só no registro do servidor.':'Teste enviado para '+r.to+'. Confira a caixa de entrada (e o spam).');})], say(local?'Teste registrado. Neste ambiente os e-mails ficam só no registro do servidor.':'Teste enviado para '+r.to+'. Confira a caixa de entrada (e o spam).');})],
details:[...(local?[node('p','Ambiente local: os e-mails não saem do servidor, ficam no registro do worker.')]:[]), details:[...(local?[node('p','Ambiente local: os e-mails não saem do servidor, ficam no registro do worker.')]:[]),
['Remetente',m.from||'—'],...(m.host?[['Servidor',m.host]]:[]), ['Remetente',m.from||'—'],...(m.host?[['Servidor',m.host]]:[]),
['Último envio',m.last_sent?when(m.last_sent):'Nenhum ainda'],['Na fila',String(m.pending||0)], ['Último envio',m.last_sent?when(m.last_sent):'Nenhum ainda'],['Na fila',String(m.pending||0)],
...(m.error?[['Último erro',when(m.error.at)+' · '+m.error.error]]:[]), ...(m.error?[['Último erro',when(m.error.at)+' · '+m.error.error]]:[])]});
node('p','Quem recebe os alertas se escolhe em Usuários → Editar → “Receber alertas por e-mail”.')]});
} }
function mercadoPagoCheck(r){ function mercadoPagoCheck(r){
const w=r.webhooks||{}; const w=r.webhooks||{};