Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions backend/docs/NOTIFICATION_PREFERENCE_MATRIX.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Multi-Channel Notifications — Preference Matrix

Issue #1352 — channel × category matrix.

## Backend

`backend/src/services/notifications.ts`

Channels: `email`, `sms`, `push`, `inApp`, `whatsapp`
Categories: `payments`, `invoices`, `marketing`, `security`, `productUpdates`

A notification is delivered on a channel only when:

1. The channel master switch is on
2. The `(channel, category)` matrix cell is true
3. Quiet hours are not active (security always bypasses quiet hours)

`dispatch()` resolves and records channel eligibility (`deliveredChannels`); the existing channel services remain the transport layer.

```ts
import { multiChannelNotifications } from '../services/notifications.js';

await multiChannelNotifications.setMatrixCell(userId, 'email', 'marketing', false);
await multiChannelNotifications.dispatch({
userId,
category: 'payments',
title: 'Payment received',
body: '…',
});
```

### HTTP

- `GET /api/v1/notifications/preferences/matrix?userId=`
- `PUT /api/v1/notifications/preferences/matrix` `{ userId, matrix }`
- `POST /api/v1/notifications/dispatch`

## Frontend

`frontend/components/notifications/PreferenceMatrix.tsx` renders the editable matrix UI.
83 changes: 82 additions & 1 deletion backend/src/routes/notifications.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
import { Router, Request, Response, NextFunction } from 'express';
import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../middleware/errorHandler.js';
import { validateRequest } from '../middleware/validate.js';
import { NotificationService } from '../services/notificationService.js';
import { multiChannelNotifications } from '../services/notifications.js';
import { whatsappNotificationRouter } from './whatsapp.js';

const categorySchema = z.enum([
'payments',
'invoices',
'marketing',
'security',
'productUpdates',
]);
const categoryCellSchema = z.object({
payments: z.boolean(),
invoices: z.boolean(),
marketing: z.boolean(),
security: z.boolean(),
productUpdates: z.boolean(),
});
const matrixSchema = z.object({
email: categoryCellSchema,
sms: categoryCellSchema,
push: categoryCellSchema,
inApp: categoryCellSchema,
whatsapp: categoryCellSchema,
});

export const notificationsRouter = Router();

// Mount WhatsApp notifications sub-router
Expand All @@ -11,6 +36,62 @@ notificationsRouter.use('/whatsapp', whatsappNotificationRouter);
// Initialize notification service
const notificationService = new NotificationService();

// Preference matrix (channel × category) — Issue #1352
notificationsRouter.get(
'/preferences/matrix',
asyncHandler(async (req: Request, res: Response) => {
const userId =
(typeof req.query.userId === 'string' && req.query.userId) ||
(req as Request & { user?: { id?: string } }).user?.id;
if (!userId) {
res.status(400).json({ error: 'userId is required' });
return;
}
const matrix = await multiChannelNotifications.getMatrix(userId);
res.status(200).json(matrix);
})
);

notificationsRouter.put(
'/preferences/matrix',
validateRequest({
body: z.object({ userId: z.string().min(1), matrix: matrixSchema }),
}),
asyncHandler(async (req: Request, res: Response) => {
const saved = await multiChannelNotifications.setMatrix(
req.body.userId,
req.body.matrix
);
res.status(200).json(saved);
})
);

notificationsRouter.post(
'/dispatch',
validateRequest({
body: z.object({
userId: z.string().min(1),
category: categorySchema,
title: z.string().min(1),
body: z.string().min(1),
metadata: z.record(z.unknown()).optional(),
bypassQuietHours: z.boolean().optional(),
}),
}),
asyncHandler(async (req: Request, res: Response) => {
const { userId, category, title, body, metadata, bypassQuietHours } = req.body;
const result = await multiChannelNotifications.dispatch({
userId,
category,
title,
body,
metadata,
bypassQuietHours,
});
res.status(200).json(result);
})
);

// Send notification endpoint
notificationsRouter.post('/send', asyncHandler(async (req: Request, res: Response) => {
const { templateId, variables, channels, userId, recipient, priority, scheduledFor } = req.body;
Expand Down
101 changes: 101 additions & 0 deletions backend/src/services/__tests__/notifications-matrix.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { describe, it, expect, beforeEach } from 'vitest';
import {
multiChannelNotifications,
buildPreferenceMatrix,
isWithinQuietHours,
type PreferenceMatrix,
} from '../notifications.js';
import { notificationPreferenceService } from '../notifications/preferenceService.js';

describe('MultiChannelNotificationService (#1352)', () => {
beforeEach(() => {
multiChannelNotifications.reset();
});

it('builds a channel × category preference matrix from defaults', async () => {
const prefs = await notificationPreferenceService.getPreferences('user-matrix-1');
const matrix = buildPreferenceMatrix(prefs);

expect(matrix.email.payments).toBe(true);
expect(matrix.email.marketing).toBe(false);
expect(matrix.sms.security).toBe(true);
});

it('honours matrix cell overrides when resolving channels', async () => {
const userId = 'user-matrix-2';
await multiChannelNotifications.setMatrixCell(userId, 'email', 'payments', false);
await multiChannelNotifications.setMatrixCell(userId, 'push', 'payments', true);

const results = await multiChannelNotifications.resolveChannels(userId, 'payments', {
bypassQuietHours: true,
});

expect(results.find((r) => r.channel === 'email')?.delivered).toBe(false);
expect(results.find((r) => r.channel === 'email')?.reason).toBe('matrix_cell_disabled');
expect(results.find((r) => r.channel === 'push')?.delivered).toBe(true);
});

it('suppresses non-security categories during quiet hours', async () => {
const userId = 'user-quiet';
await notificationPreferenceService.updatePreferences(userId, {
quietHoursEnabled: true,
quietHoursStart: '00:00',
quietHoursEnd: '23:59',
});

const marketing = await multiChannelNotifications.resolveChannels(userId, 'marketing');
expect(marketing.every((r) => !r.delivered && r.reason === 'quiet_hours')).toBe(true);

const security = await multiChannelNotifications.resolveChannels(userId, 'security');
expect(security.some((r) => r.delivered)).toBe(true);
});

it('detects quiet-hour windows that wrap midnight', () => {
const prefs = {
userId: 'x',
emailEnabled: true,
smsEnabled: true,
pushEnabled: true,
inAppEnabled: true,
whatsappEnabled: true,
payments: true,
invoices: true,
marketing: false,
security: true,
productUpdates: true,
quietHoursEnabled: true,
quietHoursStart: '22:00',
quietHoursEnd: '06:00',
updatedAt: new Date().toISOString(),
};

expect(isWithinQuietHours(prefs, new Date('2026-01-01T23:00:00'))).toBe(true);
expect(isWithinQuietHours(prefs, new Date('2026-01-01T03:00:00'))).toBe(true);
expect(isWithinQuietHours(prefs, new Date('2026-01-01T12:00:00'))).toBe(false);
});

it('dispatches only to enabled matrix channels and records history', async () => {
const userId = 'user-dispatch';
const matrix = await multiChannelNotifications.getMatrix(userId);
const disabled: PreferenceMatrix = {
...matrix,
email: { ...matrix.email, invoices: false },
sms: { ...matrix.sms, invoices: false },
push: { ...matrix.push, invoices: false },
inApp: { ...matrix.inApp, invoices: true },
whatsapp: { ...matrix.whatsapp, invoices: false },
};
await multiChannelNotifications.setMatrix(userId, disabled);

const result = await multiChannelNotifications.dispatch({
userId,
category: 'invoices',
title: 'Invoice ready',
body: 'Your invoice is ready',
bypassQuietHours: true,
});

expect(result.deliveredChannels).toEqual(['inApp']);
expect(multiChannelNotifications.getDeliveryHistory(userId)).toHaveLength(1);
});
});
Loading
Loading