- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys opcionales (SimpleWebAuthn) y mail de recuperación con rate limit. - Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta, pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil. - Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar), "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de grupo y datos para transferir en Ajustes. - "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas. - Zona horaria por defecto: Buenos Aires. - Migración add_student_access, tests contra Postgres real (test:db) y docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
7.7 KiB
TypeScript
187 lines
7.7 KiB
TypeScript
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<void>
|
|
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
|
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
|
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
|
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
|
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
|
}
|
|
|
|
// 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, '"')
|
|
.replace(/'/g, ''')
|
|
}
|
|
|
|
function button(url: string, label: string): string {
|
|
return `<a href="${escapeHtml(url)}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">${escapeHtml(label)}</a>`
|
|
}
|
|
|
|
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 <no-reply@gruperly.com>'
|
|
}
|
|
|
|
private layout(title: string, body: string) {
|
|
const header = LOGO_DATA_URI
|
|
? `<img src="${LOGO_DATA_URI}" alt="Gruperly" width="252" height="83" style="height:36px;width:auto;display:block;margin:0 auto;" />`
|
|
: '<h2 style="margin:0 0 16px;">Gruperly</h2>'
|
|
|
|
return `
|
|
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 24px; color: ${TEXT_MUTED};">
|
|
<div style="text-align:center;margin-bottom:20px;">${header}</div>
|
|
<h3 style="margin: 0 0 8px; color: ${TEXT_STRONG};">${title}</h3>
|
|
<p style="line-height: 1.6; color: ${TEXT_MUTED};">${body}</p>
|
|
</div>
|
|
`
|
|
}
|
|
|
|
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 = `<a href="${url}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Verificar email</a>`
|
|
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).<br/><br/>${link}`,
|
|
),
|
|
)
|
|
}
|
|
|
|
async sendPasswordResetEmail({ email, url, name }: PasswordResetEmailData) {
|
|
const link = `<a href="${url}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Restablecer contraseña</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.<br/><br/>${link}`,
|
|
),
|
|
)
|
|
}
|
|
|
|
async sendOrganizationInvitation({ email, url, organizationName }: InvitationEmailData) {
|
|
const link = `<a href="${url}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Unirme a ${organizationName}</a>`
|
|
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.<br/><br/>${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.<br/><br/>${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
|
|
? `<p style="margin:12px 0 4px;">${escapeHtml(link.name)}</p>${button(link.url, 'Ingresar')}`
|
|
: button(link.url, 'Ingresar'),
|
|
)
|
|
.join('<br/>')
|
|
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.<br/><br/>${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 ? `<br/><br/>Motivo: ${escapeHtml(reason)}` : ''}<br/><br/>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() |