feat: email notifications via Resend on new incident

This commit is contained in:
2026-07-10 13:24:44 +08:00
parent 3f8da5bd91
commit 2239b6e2df
6 changed files with 254 additions and 38 deletions
+66
View File
@@ -0,0 +1,66 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { mockSend, mockFrom } = vi.hoisted(() => ({
mockSend: vi.fn(),
mockFrom: vi.fn(),
}))
vi.mock('resend', () => {
function MockResend() {}
MockResend.prototype.emails = { send: mockSend }
return { Resend: MockResend }
})
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn().mockResolvedValue({ from: mockFrom }),
}))
import { sendNewIncidentEmail } from '@/lib/notifications/email'
const mockIncidentRow = {
reported_at: '2026-07-10T09:00:00Z',
sites: { name: 'SCW1' },
reporter: { name: 'John Doe' },
}
function setupMocks(recipientData: object[]) {
mockFrom.mockImplementation((table: string) => {
if (table === 'users') {
return {
select: vi.fn().mockReturnThis(),
in: vi.fn().mockReturnThis(),
eq: vi.fn().mockResolvedValue({ data: recipientData, error: null }),
}
}
return {
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
single: vi.fn().mockResolvedValue({ data: mockIncidentRow, error: null }),
}
})
}
beforeEach(() => {
vi.clearAllMocks()
mockSend.mockResolvedValue({ data: { id: 'email-123' }, error: null })
setupMocks([
{ email: 'supervisor@setiacorp.com', name: 'Ahmad', role: 'supervisor' },
{ email: 'hse@setiacorp.com', name: 'Priya', role: 'hse' },
])
})
describe('sendNewIncidentEmail', () => {
it('sends email to supervisor and hse users', async () => {
await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss')
expect(mockSend).toHaveBeenCalledTimes(1)
const call = mockSend.mock.calls[0][0]
expect(call.to).toEqual(expect.arrayContaining(['supervisor@setiacorp.com', 'hse@setiacorp.com']))
expect(call.subject).toContain('SCW1-202607-0001')
})
it('does not send if no recipients', async () => {
setupMocks([])
await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss')
expect(mockSend).not.toHaveBeenCalled()
})
})