Files
ims/lib/notifications/email.ts
Weei HanandClaude Sonnet 5.5 813395700f feat(auth): merge reporter, supervisor, capa_owner into ssa role
Add Site Safety Assistant (ssa) role replacing reporter, supervisor and
capa_owner. Portals move under /ssa (overview, my-reports, incidents,
capas). Update RLS, schema, API role checks, notification recipients,
nav and tests. Add db/ops/2026-11-06-merge-roles-into-ssa.sql (not yet
applied; needs owner go-ahead and a pg_dump first).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 21:34:10 +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, ['ssa', '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 })
}