import { describe, it, expect } from 'vitest' import { bucketIncidentsByMonth, topRootCauses } from '@/lib/dashboard/trends' describe('bucketIncidentsByMonth', () => { const now = new Date('2026-07-15T12:00:00Z') it('returns one bucket per month, oldest first', () => { const buckets = bucketIncidentsByMonth([], 3, now) expect(buckets.map(b => b.month)).toEqual(['2026-05', '2026-06', '2026-07']) }) it('counts leading and lagging types into the right month', () => { const buckets = bucketIncidentsByMonth( [ { reported_at: '2026-07-01T08:00:00Z', incident_type: 'near_miss' }, { reported_at: '2026-07-02T08:00:00Z', incident_type: 'hazard' }, { reported_at: '2026-07-03T08:00:00Z', incident_type: 'injury' }, { reported_at: '2026-06-03T08:00:00Z', incident_type: 'fire' }, ], 3, now, ) const july = buckets.find(b => b.month === '2026-07')! expect(july).toMatchObject({ total: 3, leading: 2, lagging: 1 }) expect(buckets.find(b => b.month === '2026-06')).toMatchObject({ total: 1, leading: 0, lagging: 0 }) }) it('ignores incidents outside the window', () => { const buckets = bucketIncidentsByMonth( [{ reported_at: '2025-01-01T08:00:00Z', incident_type: 'injury' }], 3, now, ) expect(buckets.every(b => b.total === 0)).toBe(true) }) }) describe('topRootCauses', () => { it('groups normalized duplicates and sorts by count', () => { const result = topRootCauses([ { root_cause_summary: 'Inadequate forklift training.' }, { root_cause_summary: 'inadequate forklift training' }, { root_cause_summary: 'Blocked walkway' }, { root_cause_summary: null }, { root_cause_summary: '' }, ]) expect(result).toHaveLength(2) expect(result[0]).toMatchObject({ count: 2 }) expect(result[0].cause.toLowerCase()).toContain('forklift') }) it('limits to top N', () => { const invs = ['a', 'b', 'c', 'd', 'e', 'f'].map(c => ({ root_cause_summary: c })) expect(topRootCauses(invs, 5)).toHaveLength(5) }) })