import { readFileSync } from 'node:fs' import nodemailer, { type Transporter } from 'nodemailer' type VerificationEmailData = { email: string; url: string; name?: string } type PasswordResetEmailData = { email: string; url: string; name?: string } type InvitationEmailData = { email: string; url: string; organizationName: string } type StudentEmailConfirmationData = { email: string; url: string; name: string } type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] } type StudentPaymentReviewedData = { email: string name: string confirmed: boolean amount: string reason?: string | null } // Brand colors (same system as the web app: index.css in apps/web). const BRAND_600 = '#2544ea' const TEXT_STRONG = '#0f172a' const TEXT_MUTED = '#475569' const ON_ACCENT = '#ffffff' const LINK_BG = BRAND_600 // Logo embedded as a data URI so the emails don't depend on hosting. function loadLogoTypoDataUri(): string { try { const base64 = readFileSync( new URL('../assets/logotipo-y-organica.png', import.meta.url), ).toString('base64') return `data:image/png;base64,${base64}` } catch { return '' } } const LOGO_DATA_URI = loadLogoTypoDataUri() export interface EmailProvider { sendVerificationEmail(data: VerificationEmailData): Promise sendPasswordResetEmail(data: PasswordResetEmailData): Promise sendOrganizationInvitation(data: InvitationEmailData): Promise sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise } // Names come from what teachers and students type: never raw into the HTML. function escapeHtml(value: string): string { return value .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, ''') } function button(url: string, label: string): string { return `${escapeHtml(label)}` } class SMTPEmailProvider implements EmailProvider { private transporter: Transporter constructor() { this.transporter = nodemailer.createTransport({ host: process.env.EMAIL_SERVER_HOST, port: Number(process.env.EMAIL_SERVER_PORT ?? 587), secure: (process.env.EMAIL_SERVER_PORT ?? '587') === '465', auth: { user: process.env.EMAIL_SERVER_USER, pass: process.env.EMAIL_SERVER_PASSWORD, }, }) } private from() { return process.env.EMAIL_FROM ?? 'Gruperly ' } private layout(title: string, body: string) { const header = LOGO_DATA_URI ? `Gruperly` : '

Gruperly

' return `
${header}

${title}

${body}

` } private async send(to: string, subject: string, html: string) { // With no SMTP configured (dev) the flow still doesn't break: it only logs a warning if (!process.env.EMAIL_SERVER_HOST) { console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`) return } await this.transporter.sendMail({ from: this.from(), to, subject, html }) } async sendVerificationEmail({ email, url, name }: VerificationEmailData) { const link = `Verificar email` await this.send( email, 'Verifica tu email en Gruperly', this.layout( 'Confirma tu dirección de email', `${name ? `Hola ${name}, ` : 'Hola, '}gracias por crear tu cuenta en Gruperly. Para empezar, verifica tu email con el botón de abajo (el enlace vence en 1 hora).

${link}`, ), ) } async sendPasswordResetEmail({ email, url, name }: PasswordResetEmailData) { const link = `Restablecer contraseña` await this.send( email, 'Restablece tu contraseña en Gruperly', this.layout( 'Solicitaste restablecer tu contraseña', `${name ? `Hola ${name}, ` : 'Hola, '}haz clic en el botón para elegir una nueva contraseña (el enlace vence en 1 hora). Si no fuiste tú, ignora este email.

${link}`, ), ) } async sendOrganizationInvitation({ email, url, organizationName }: InvitationEmailData) { const link = `Unirme a ${organizationName}` await this.send( email, `Te invitaron a ${organizationName} en Gruperly`, this.layout( `Te invitaron a ${organizationName}`, `Acepta la invitación con el botón de abajo para empezar a colaborar en Gruperly.

${link}`, ), ) } async sendStudentEmailConfirmation({ email, url, name }: StudentEmailConfirmationData) { await this.send( email, 'Confirmá tu mail de recuperación en Gruperly', this.layout( 'Confirmá tu mail', `Hola ${escapeHtml(name)}, confirmá este mail para poder pedir un link de ingreso si perdés el acceso a la app (el enlace vence en 24 horas). Si no fuiste vos, ignorá este mail.

${button(url, 'Confirmar mail')}`, ), ) } async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) { // A guardian may have one account per child with the same email: one button each. const buttons = links .map((link) => links.length > 1 ? `

${escapeHtml(link.name)}

${button(link.url, 'Ingresar')}` : button(link.url, 'Ingresar'), ) .join('
') await this.send( email, 'Tu link para ingresar a Gruperly', this.layout( 'Tu link de ingreso', `Pediste un link para volver a entrar. Sirve una sola vez y vence en 15 minutos. Si no fuiste vos, ignorá este mail.

${buttons}`, ), ) } async sendStudentPaymentReviewed({ email, name, confirmed, amount, reason }: StudentPaymentReviewedData) { const body = confirmed ? `Hola ${escapeHtml(name)}, tu profe confirmó el pago de ${escapeHtml(amount)}. ¡Gracias!` : `Hola ${escapeHtml(name)}, tu profe no pudo confirmar el pago de ${escapeHtml(amount)}.${reason ? `

Motivo: ${escapeHtml(reason)}` : ''}

Podés volver a informarlo desde la app.` await this.send( email, confirmed ? 'Tu pago fue confirmado' : 'Tu pago no fue confirmado', this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body), ) } } // Future: transactional providers (Resend, SendGrid, Postmark). // Add implementations and switch between them with EMAIL_PROVIDER. export function createEmailProvider(): EmailProvider { return new SMTPEmailProvider() } export const emailProvider = createEmailProvider()