Files
ims/lib/notifications/email.ts
T
adminandClaude Sonnet 4.6 d785d86636 feat(email): phase 6 — replace Resend with Brevo transactional email
Removes resend npm dependency. Adds lib/notifications/mailer.ts with a
raw-HTTP Brevo wrapper (sendEmail + sendPasswordResetEmail). All three
notification files updated to use the new wrapper.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 22:20:12 +08:00

60 lines
1.8 KiB
TypeScript

import 'server-only'
import { sendEmail } from '@/lib/notifications/mailer'
import { asAdmin } from '@/lib/db/with-user'
import { users, incidents, sites } from '@/lib/db/schema'
import { and, eq, inArray } from 'drizzle-orm'
import { newIncidentTemplate } from '@/lib/notifications/templates/new-incident'
export async function sendNewIncidentEmail(
incidentId: string,
siteId: string,
reference_no: string,
incidentType: string,
): Promise<void> {
const recipients = await asAdmin(db =>
db.select({ email: users.email })
.from(users)
.where(and(
inArray(users.role, ['supervisor', 'hse']),
eq(users.siteId, siteId),
))
)
if (!recipients || recipients.length === 0) return
const to = recipients.map(r => r.email).filter(Boolean) as string[]
if (to.length === 0) return
const incidentRows = await asAdmin(db =>
db.select({
reportedAt: incidents.reportedAt,
siteName: sites.name,
reporterName: users.name,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(users, eq(incidents.reportedBy, users.id))
.where(eq(incidents.id, incidentId))
.limit(1)
)
const incident = incidentRows[0]
const siteName = incident?.siteName ?? 'Unknown Site'
const reporterName = incident?.reporterName ?? 'Unknown'
const reportedAt = incident?.reportedAt
? new Date(incident.reportedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })
: '-'
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000'
const { subject, html, text } = newIncidentTemplate({
reference_no,
incident_type: incidentType,
site_name: siteName,
reporter_name: reporterName,
reported_at: reportedAt,
site_url: siteUrl,
incident_id: incidentId,
})
await sendEmail({ to, subject, html, text })
}