import { eq } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { auditLog } from '../db/schema.ts' import { createTestContext, hoursAgo } from '../test/helpers.ts' let ctx: Awaited> let site: { id: string } let area: { id: string } let reporter: Awaited> let supervisor: Awaited> const report = (overrides: Record = {}) => ({ title: 'Forklift reversed into pallet stack', type: 'near_miss', severity: 'high', occurredAt: hoursAgo(2), siteId: site.id, ...overrides, }) beforeAll(async () => { ctx = await createTestContext() site = await ctx.createSite('North Campus') area = (await ctx.admin.post(`/api/sites/${site.id}/areas`, { name: 'Loading bay C' })).body.area reporter = await ctx.createUser('reporter') supervisor = await ctx.createUser('supervisor') }) afterAll(() => ctx.close()) describe('reporting', () => { it('creates an incident with a sequential reference and the reporter recorded', async () => { const res = await reporter.post('/api/incidents', report({ areaId: area.id, locationDetail: 'Dock door 3' })) expect(res.status).toBe(201) expect(res.body.incident).toMatchObject({ number: 1, reference: 'INC-0001', status: 'reported', site: { id: site.id, name: 'North Campus' }, area: { id: area.id, name: 'Loading bay C' }, reporter: { id: reporter.user.id, name: 'reporter user' }, }) }) it('assigns distinct numbers to simultaneous reports', async () => { const results = await Promise.all(Array.from({ length: 8 }, (_, i) => reporter.post('/api/incidents', report({ title: `Concurrent ${i}` })))) const numbers = results.map((r) => r.body.incident.number) expect(new Set(numbers).size).toBe(8) }) it('keeps anonymous reports anonymous', async () => { const res = await reporter.post('/api/incidents', report({ title: 'Blocked fire exit', anonymous: true })) expect(res.body.incident).toMatchObject({ anonymous: true, reporter: null }) }) it('validates location and time', async () => { const otherSite = await ctx.createSite('South Campus') expect((await reporter.post('/api/incidents', report({ siteId: otherSite.id, areaId: area.id }))).status).toBe(400) expect((await reporter.post('/api/incidents', report({ occurredAt: new Date(Date.now() + 86_400_000).toISOString() }))).status).toBe(400) expect((await reporter.post('/api/incidents', report({ type: 'explosion' }))).status).toBe(400) }) it('writes an audit entry', async () => { const res = await reporter.post('/api/incidents', report({ title: 'Audited' })) const entries = await ctx.db.select().from(auditLog).where(eq(auditLog.entityId, res.body.incident.id)) expect(entries).toHaveLength(1) expect(entries[0]).toMatchObject({ action: 'create', actorId: reporter.user.id }) }) }) describe('visibility', () => { it('shows reporters only their own incidents', async () => { const other = await ctx.createUser('reporter', 'other-reporter@example.com') const mine = await other.post('/api/incidents', report({ title: 'Only mine' })) const list = await other.get('/api/incidents') expect(list.body.items.map((i: { title: string }) => i.title)).toEqual(['Only mine']) expect((await reporter.get(`/api/incidents/${mine.body.incident.number}`)).status).toBe(404) }) it('shows supervisors every incident', async () => { const list = await supervisor.get('/api/incidents?pageSize=100') expect(list.body.total).toBeGreaterThan(10) }) }) describe('listing', () => { it('paginates newest first', async () => { const page1 = await supervisor.get('/api/incidents?pageSize=3&page=1') const page2 = await supervisor.get('/api/incidents?pageSize=3&page=2') expect(page1.body.items).toHaveLength(3) expect(page1.body.items[0].id).not.toBe(page2.body.items[0].id) const times = page1.body.items.map((i: { occurredAt: string }) => i.occurredAt) expect([...times].sort().reverse()).toEqual(times) }) it('searches title and reference, treating % and _ literally', async () => { await reporter.post('/api/incidents', report({ title: 'Oil leak under press 4', type: 'hazard', severity: 'medium' })) expect((await supervisor.get('/api/incidents?q=press')).body.items[0].title).toBe('Oil leak under press 4') expect((await supervisor.get('/api/incidents?q=INC-0001')).body.items[0].number).toBe(1) expect((await supervisor.get('/api/incidents?q=%25')).body.total).toBe(0) }) it('filters by type, severity and status', async () => { const hazards = await supervisor.get('/api/incidents?type=hazard&severity=medium') expect(hazards.body.items.every((i: { type: string; severity: string }) => i.type === 'hazard' && i.severity === 'medium')).toBe(true) expect((await supervisor.get('/api/incidents?status=closed')).body.total).toBe(0) expect((await supervisor.get('/api/incidents?status=bogus')).status).toBe(400) }) }) describe('updating', () => { it('lets supervisors edit details, recording what changed', async () => { const created = await reporter.post('/api/incidents', report({ title: 'Wet floor' })) const number = created.body.incident.number expect((await reporter.patch(`/api/incidents/${number}`, { severity: 'low' })).status).toBe(403) const edited = await supervisor.patch(`/api/incidents/${number}`, { severity: 'low', title: 'Wet floor by entrance' }) expect(edited.status).toBe(200) expect(edited.body.incident).toMatchObject({ severity: 'low', title: 'Wet floor by entrance' }) const [entry] = await ctx.db.select().from(auditLog).where(eq(auditLog.action, 'update')) expect(entry.changes).toMatchObject({ severity: ['high', 'low'], title: ['Wet floor', 'Wet floor by entrance'] }) }) it('does not change status through edits', async () => { const created = await reporter.post('/api/incidents', report()) const res = await supervisor.patch(`/api/incidents/${created.body.incident.number}`, { status: 'closed' }) expect(res.body.incident.status).toBe('reported') }) it('clears the area when moving an incident to another site', async () => { const created = await reporter.post('/api/incidents', report({ areaId: area.id })) const west = await ctx.createSite('West Campus') const moved = await supervisor.patch(`/api/incidents/${created.body.incident.number}`, { siteId: west.id }) expect(moved.body.incident).toMatchObject({ site: { id: west.id }, area: null }) }) }) describe('notifications', () => { it('alerts safety managers about high-severity reports, not low ones', async () => { const manager = await ctx.createUser('safety_manager', 'alerts@example.com') await reporter.post('/api/incidents', report({ title: 'Arm caught in conveyor', type: 'injury', severity: 'critical' })) await reporter.post('/api/incidents', report({ title: 'Scuffed paint', severity: 'low' })) await ctx.notifier.flush() const mails = ctx.mailer.sent.filter((mail) => mail.to === manager.user.email) expect(mails).toHaveLength(1) expect(mails[0].subject).toMatch(/^\[Critical\] INC-\d{4}: Arm caught in conveyor$/) expect(mails[0].text).toContain('http://safety.test/incidents/') }) }) describe('export', () => { it('exports the filtered list as CSV, neutralising spreadsheet formulas', async () => { await reporter.post('/api/incidents', report({ title: '=HYPERLINK("http://evil")', type: 'environmental', severity: 'low' })) const res = await supervisor.get('/api/incidents/export?type=environmental') expect(res.status).toBe(200) expect(res.headers.get('content-type')).toContain('text/csv') const csv = res.body.toString('utf8') const lines = csv.trimEnd().split('\r\n') expect(lines[0]).toMatch(/^\uFEFFReference,Title,Type/) expect(lines).toHaveLength(2) expect(lines[1]).toContain(`"'=HYPERLINK(""http://evil"")"`) }) it('only exports what the user can see', async () => { const other = await ctx.createUser('reporter', 'csv-reporter@example.com') const res = await other.get('/api/incidents/export') expect(res.body.toString('utf8').trimEnd().split('\r\n')).toHaveLength(1) }) })