Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | 22x 22x 22x 27x 27x 27x 36x 2x 2x 34x 30x 30x 4x 4x 1x 1x 17x 2x 3x 9x 9x 2x 2x 2x | import { Resend } from 'resend';
import { logger } from '../../shared/logging/logger';
const UNDELIVERABLE_TLD = '.invalid';
export interface SendEmailInput {
to: string;
subject: string;
html: string;
}
// Narrow interface covering just the reminder-related template methods, so use cases that only
// need to send reminder emails (e.g. `GenerateReminderNotificationsUseCase`) can depend on this
// instead of the full `EmailService` class — a plain object satisfies it in tests without having
// to duck-type a class with a private field.
export interface ReminderEmailSender {
sendVaccineOverdueEmail(to: string, babyName: string, vaccineName: string): Promise<void>;
sendAppointmentReminderEmail(to: string, babyName: string, doctorName: string, scheduledAt: Date): Promise<void>;
}
/**
* Shared body for the two code e-mails. The code is rendered large and letter-spaced because it is
* read off the screen and typed into another one — and repeated in the subject line, so it is
* legible from a notification without opening anything.
*/
function verificationCodeHtml(parts: { heading: string; intro: string; code: string; footer: string }): string {
return `
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto; color: #1f2933;">
<h1 style="color: #2A9D8F; font-size: 20px;">${parts.heading}</h1>
<p>${parts.intro}</p>
<p style="font-size: 32px; font-weight: bold; letter-spacing: 8px; color: #1f2933; margin: 24px 0;">${parts.code}</p>
<p style="font-size: 13px; color: #6b7280;">${parts.footer}</p>
</div>
`.trim();
}
// The web stores an appointment as the real instant (the parent's local time converted to UTC), and
// the server does not know each parent's time zone. Brasília time is the reference the PNI schedule
// and most of the country use, so reminders are written in it and say so, which leaves a parent in
// Manaus or Rio Branco a clear label to adjust from instead of a silently shifted hour.
const REMINDER_TIME_ZONE = 'America/Sao_Paulo';
// Thin wrapper around the Resend SDK, kept generic (`send`) so it can be reused for anything
// transactional — guardian invites today, reminder emails later (vaccines/appointments), without
// changing this class. Template-specific methods (like `sendGuardianInviteEmail` below) just build
// the HTML and delegate to `send`.
export class EmailService implements ReminderEmailSender {
private readonly client: Resend | null;
constructor(
private readonly apiKey: string | undefined,
private readonly fromEmail: string | undefined,
) {
this.client = apiKey ? new Resend(apiKey) : null;
}
async send(input: SendEmailInput): Promise<void> {
// `.invalid` is reserved (RFC 2606) and never resolves, and it is where demo accounts live
// (`DEMO_EMAIL_DOMAIN`). Handing such an address to Resend buys a bounce on the sending
// domain's reputation and nothing else, and every path that mails "the account's own address" —
// reminders, deletion codes, a sign-in code requested for an address copied off a demo
// profile — would otherwise try.
if (input.to.trim().toLowerCase().endsWith(UNDELIVERABLE_TLD)) {
logger.info({ subject: input.subject }, 'email_service.skipped_undeliverable_address');
return;
}
if (!this.client || !this.fromEmail) {
logger.warn(
{ to: input.to, subject: input.subject },
'email_service.not_configured — RESEND_API_KEY/RESEND_FROM_EMAIL unset, skipping send',
);
return;
}
const { error } = await this.client.emails.send({
from: this.fromEmail,
to: input.to,
subject: input.subject,
html: input.html,
});
Iif (error) {
throw new Error(`Failed to send email via Resend: ${error.message}`);
}
}
async sendGuardianInviteEmail(to: string, inviterName: string, babyName: string, inviteUrl: string): Promise<void> {
const html = `
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto; color: #1f2933;">
<h1 style="color: #2A9D8F; font-size: 20px;">Você foi convidado(a) para cuidar de ${babyName}</h1>
<p>${inviterName} convidou você para acompanhar, junto com ele(a), o acompanhamento de saúde de ${babyName} no Cygnus — vacinas, consultas e marcos de desenvolvimento.</p>
<p>
<a href="${inviteUrl}" style="display: inline-block; background-color: #2A9D8F; color: #ffffff; padding: 12px 20px; border-radius: 8px; text-decoration: none; font-weight: bold;">
Aceitar convite
</a>
</p>
<p style="font-size: 13px; color: #6b7280;">Este convite expira em 7 dias. Se você não esperava este e-mail, pode ignorá-lo com segurança.</p>
</div>
`.trim();
await this.send({
to,
subject: `${inviterName} convidou você para cuidar de ${babyName}`,
html,
});
}
async sendPasswordlessCodeEmail(to: string, code: string): Promise<void> {
await this.send({
to,
subject: `${code} é o seu código de acesso ao Cygnus`,
html: verificationCodeHtml({
heading: 'Seu código de acesso',
intro: 'Use o código abaixo para entrar no Cygnus sem senha.',
code,
footer:
'O código vale por 10 minutos e só pode ser usado uma vez. Se não foi você que pediu, ignore este e-mail — ' +
'ninguém entra na sua conta só por ter pedido o código.',
}),
});
}
async sendAccountDeletionCodeEmail(to: string, code: string): Promise<void> {
await this.send({
to,
subject: `${code} é o seu código para excluir a conta do Cygnus`,
html: verificationCodeHtml({
heading: 'Excluir sua conta',
intro: 'Use o código abaixo para confirmar a exclusão da sua conta do Cygnus.',
code,
footer:
'Excluir a conta apaga também o histórico das crianças — vacinas, consultas, marcos e medidas — e não tem ' +
'volta. O código vale por 10 minutos e só pode ser usado uma vez. Se não foi você que pediu, ignore este ' +
'e-mail: nada é apagado sem o código.',
}),
});
}
async sendPasswordResetCodeEmail(to: string, code: string): Promise<void> {
await this.send({
to,
subject: `${code} é o seu código para redefinir a senha do Cygnus`,
html: verificationCodeHtml({
heading: 'Redefinir sua senha',
intro: 'Use o código abaixo para criar uma nova senha do Cygnus.',
code,
footer:
'O código vale por 10 minutos e só pode ser usado uma vez. Ao redefinir a senha, você sai de todos os ' +
'outros aparelhos conectados. Se não foi você que pediu, ignore este e-mail: sua senha atual continua valendo.',
}),
});
}
async sendVaccineOverdueEmail(to: string, babyName: string, vaccineName: string): Promise<void> {
const html = `
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto; color: #1f2933;">
<h1 style="color: #2A9D8F; font-size: 20px;">Vacina atrasada: ${vaccineName}</h1>
<p>A vacina <strong>${vaccineName}</strong> de ${babyName} está atrasada no calendário de vacinação.</p>
<p>Acesse o Cygnus para registrar a aplicação ou reagendar com o pediatra.</p>
<p style="font-size: 13px; color: #6b7280;">Você está recebendo este e-mail porque é responsável por ${babyName} no Cygnus. Você pode desativar lembretes por e-mail nas configurações do seu perfil.</p>
</div>
`.trim();
await this.send({
to,
subject: `Vacina atrasada: ${vaccineName} (${babyName})`,
html,
});
}
async sendAppointmentReminderEmail(to: string, babyName: string, doctorName: string, scheduledAt: Date): Promise<void> {
const formattedDate = scheduledAt.toLocaleString('pt-BR', { timeZone: REMINDER_TIME_ZONE, dateStyle: 'short', timeStyle: 'short' });
const html = `
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto; color: #1f2933;">
<h1 style="color: #2A9D8F; font-size: 20px;">Consulta próxima de ${babyName}</h1>
<p>${babyName} tem consulta marcada com <strong>${doctorName}</strong> em <strong>${formattedDate}</strong> (horário de Brasília).</p>
<p>Acesse o Cygnus para ver mais detalhes ou reagendar, se necessário.</p>
<p style="font-size: 13px; color: #6b7280;">Você está recebendo este e-mail porque é responsável por ${babyName} no Cygnus. Você pode desativar lembretes por e-mail nas configurações do seu perfil.</p>
</div>
`.trim();
await this.send({
to,
subject: `Consulta próxima: ${babyName} com ${doctorName}`,
html,
});
}
}
|