From dfa7716451433af5f21878c4b41f001fa17f1279 Mon Sep 17 00:00:00 2001 From: mabas Date: Mon, 23 Nov 2026 14:44:16 +0100 Subject: [PATCH] feat(notifications): add per-user preference matrix (#1352) --- .../docs/NOTIFICATION_PREFERENCE_MATRIX.md | 40 +++ backend/src/routes/notifications.ts | 83 +++++- .../__tests__/notifications-matrix.test.ts | 101 ++++++++ backend/src/services/notifications.ts | 228 +++++++++++++++++ .../notifications/PreferenceMatrix.tsx | 236 ++++++++++++++++++ frontend/components/notifications/index.ts | 8 + 6 files changed, 695 insertions(+), 1 deletion(-) create mode 100644 backend/docs/NOTIFICATION_PREFERENCE_MATRIX.md create mode 100644 backend/src/services/__tests__/notifications-matrix.test.ts create mode 100644 backend/src/services/notifications.ts create mode 100644 frontend/components/notifications/PreferenceMatrix.tsx create mode 100644 frontend/components/notifications/index.ts diff --git a/backend/docs/NOTIFICATION_PREFERENCE_MATRIX.md b/backend/docs/NOTIFICATION_PREFERENCE_MATRIX.md new file mode 100644 index 00000000..12bf1bf0 --- /dev/null +++ b/backend/docs/NOTIFICATION_PREFERENCE_MATRIX.md @@ -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. diff --git a/backend/src/routes/notifications.ts b/backend/src/routes/notifications.ts index a364f788..942d4290 100644 --- a/backend/src/routes/notifications.ts +++ b/backend/src/routes/notifications.ts @@ -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 @@ -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; diff --git a/backend/src/services/__tests__/notifications-matrix.test.ts b/backend/src/services/__tests__/notifications-matrix.test.ts new file mode 100644 index 00000000..aa9edc76 --- /dev/null +++ b/backend/src/services/__tests__/notifications-matrix.test.ts @@ -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); + }); +}); diff --git a/backend/src/services/notifications.ts b/backend/src/services/notifications.ts new file mode 100644 index 00000000..3588fbb2 --- /dev/null +++ b/backend/src/services/notifications.ts @@ -0,0 +1,228 @@ +/** + * Multi-channel notification system with per-user preference matrix — Issue #1352 + * + * Preference matrix = channel × category. A notification is delivered on a + * channel only when both the channel is enabled and the (channel, category) + * cell is true. Quiet hours suppress non-security categories. + */ + +import { logger } from '../utils/logger.js'; +import { + notificationPreferenceService, + type NotificationPreferences, +} from './notifications/preferenceService.js'; + +export type NotificationChannel = 'email' | 'sms' | 'push' | 'inApp' | 'whatsapp'; +export type NotificationCategory = + | 'payments' + | 'invoices' + | 'marketing' + | 'security' + | 'productUpdates'; + +export const NOTIFICATION_CHANNELS: NotificationChannel[] = [ + 'email', + 'sms', + 'push', + 'inApp', + 'whatsapp', +]; + +export const NOTIFICATION_CATEGORIES: NotificationCategory[] = [ + 'payments', + 'invoices', + 'marketing', + 'security', + 'productUpdates', +]; + +/** channel → category → enabled */ +export type PreferenceMatrix = Record< + NotificationChannel, + Record +>; + +export type NotificationPayload = { + userId: string; + category: NotificationCategory; + title: string; + body: string; + metadata?: Record; + /** Force delivery even during quiet hours (defaults true for security). */ + bypassQuietHours?: boolean; +}; + +export type ChannelDeliveryResult = { + channel: NotificationChannel; + delivered: boolean; + reason?: string; +}; + +export type DispatchResult = { + notificationId: string; + userId: string; + category: NotificationCategory; + results: ChannelDeliveryResult[]; + deliveredChannels: NotificationChannel[]; +}; + +const CHANNEL_ENABLED_KEY: Record = { + email: 'emailEnabled', + sms: 'smsEnabled', + push: 'pushEnabled', + inApp: 'inAppEnabled', + whatsapp: 'whatsappEnabled', +}; + +function defaultMatrixCell( + prefs: NotificationPreferences, + channel: NotificationChannel, + category: NotificationCategory +): boolean { + const channelOn = Boolean(prefs[CHANNEL_ENABLED_KEY[channel]]); + const categoryOn = Boolean(prefs[category]); + return channelOn && categoryOn; +} + +/** + * Build the full preference matrix for a user from stored preferences, + * overlaying any explicit matrix cells the user has set. + */ +export function buildPreferenceMatrix( + prefs: NotificationPreferences, + overrides?: Partial +): PreferenceMatrix { + const matrix = {} as PreferenceMatrix; + for (const channel of NOTIFICATION_CHANNELS) { + matrix[channel] = {} as Record; + for (const category of NOTIFICATION_CATEGORIES) { + const override = overrides?.[channel]?.[category]; + matrix[channel][category] = + typeof override === 'boolean' + ? override + : defaultMatrixCell(prefs, channel, category); + } + } + return matrix; +} + +function parseHm(value: string): number { + const [h, m] = value.split(':').map((n) => Number(n)); + if (!Number.isFinite(h) || !Number.isFinite(m)) return 0; + return h * 60 + m; +} + +export function isWithinQuietHours( + prefs: NotificationPreferences, + now: Date = new Date() +): boolean { + if (!prefs.quietHoursEnabled) return false; + const minutes = now.getHours() * 60 + now.getMinutes(); + const start = parseHm(prefs.quietHoursStart); + const end = parseHm(prefs.quietHoursEnd); + if (start === end) return false; + // Window that wraps midnight (e.g. 22:00–06:00) + if (start > end) return minutes >= start || minutes < end; + return minutes >= start && minutes < end; +} + +export class MultiChannelNotificationService { + private matrices = new Map(); + private deliveries: DispatchResult[] = []; + + async getMatrix(userId: string): Promise { + const prefs = await notificationPreferenceService.getPreferences(userId); + const stored = this.matrices.get(userId); + return buildPreferenceMatrix(prefs, stored); + } + + async setMatrixCell( + userId: string, + channel: NotificationChannel, + category: NotificationCategory, + enabled: boolean + ): Promise { + const current = await this.getMatrix(userId); + current[channel][category] = enabled; + this.matrices.set(userId, current); + logger.info('[notifications] matrix cell updated', { userId, channel, category, enabled }); + return current; + } + + async setMatrix(userId: string, matrix: PreferenceMatrix): Promise { + this.matrices.set(userId, matrix); + logger.info('[notifications] matrix replaced', { userId }); + return matrix; + } + + /** + * Resolve which channels should receive a notification for the user/category. + */ + async resolveChannels( + userId: string, + category: NotificationCategory, + options: { bypassQuietHours?: boolean; now?: Date } = {} + ): Promise { + const prefs = await notificationPreferenceService.getPreferences(userId); + const matrix = await this.getMatrix(userId); + const quiet = + !options.bypassQuietHours && + category !== 'security' && + isWithinQuietHours(prefs, options.now); + + return NOTIFICATION_CHANNELS.map((channel) => { + if (quiet) { + return { channel, delivered: false, reason: 'quiet_hours' }; + } + if (!prefs[CHANNEL_ENABLED_KEY[channel]]) { + return { channel, delivered: false, reason: 'channel_disabled' }; + } + if (!matrix[channel][category]) { + return { channel, delivered: false, reason: 'matrix_cell_disabled' }; + } + return { channel, delivered: true }; + }); + } + + async dispatch(payload: NotificationPayload): Promise { + const bypass = + payload.bypassQuietHours ?? payload.category === 'security'; + const results = await this.resolveChannels(payload.userId, payload.category, { + bypassQuietHours: bypass, + }); + const deliveredChannels = results.filter((r) => r.delivered).map((r) => r.channel); + + const notificationId = `ntf_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`; + const result: DispatchResult = { + notificationId, + userId: payload.userId, + category: payload.category, + results, + deliveredChannels, + }; + + this.deliveries.push(result); + logger.info('[notifications] dispatched', { + notificationId, + userId: payload.userId, + category: payload.category, + channels: deliveredChannels, + title: payload.title, + }); + + return result; + } + + getDeliveryHistory(userId?: string): DispatchResult[] { + if (!userId) return [...this.deliveries]; + return this.deliveries.filter((d) => d.userId === userId); + } + + /** Test helper — clear in-memory state. */ + reset(): void { + this.matrices.clear(); + this.deliveries = []; + } +} + +export const multiChannelNotifications = new MultiChannelNotificationService(); diff --git a/frontend/components/notifications/PreferenceMatrix.tsx b/frontend/components/notifications/PreferenceMatrix.tsx new file mode 100644 index 00000000..fb33169e --- /dev/null +++ b/frontend/components/notifications/PreferenceMatrix.tsx @@ -0,0 +1,236 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +export type NotificationChannel = "email" | "sms" | "push" | "inApp" | "whatsapp"; +export type NotificationCategory = + | "payments" + | "invoices" + | "marketing" + | "security" + | "productUpdates"; + +export type PreferenceMatrixData = Record< + NotificationChannel, + Record +>; + +const CHANNELS: NotificationChannel[] = ["email", "sms", "push", "inApp", "whatsapp"]; +const CATEGORIES: NotificationCategory[] = [ + "payments", + "invoices", + "marketing", + "security", + "productUpdates", +]; + +const CHANNEL_LABELS: Record = { + email: "Email", + sms: "SMS", + push: "Push", + inApp: "In-app", + whatsapp: "WhatsApp", +}; + +const CATEGORY_LABELS: Record = { + payments: "Payments", + invoices: "Invoices", + marketing: "Marketing", + security: "Security", + productUpdates: "Product updates", +}; + +const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1"; + +function emptyMatrix(enabled = true): PreferenceMatrixData { + const matrix = {} as PreferenceMatrixData; + for (const channel of CHANNELS) { + matrix[channel] = {} as Record; + for (const category of CATEGORIES) { + matrix[channel][category] = enabled && category !== "marketing"; + } + } + return matrix; +} + +export type PreferenceMatrixProps = { + userId?: string; + initialMatrix?: PreferenceMatrixData; + onChange?: (matrix: PreferenceMatrixData) => void; +}; + +/** + * Channel × category preference matrix for multi-channel notifications (#1352). + */ +export function PreferenceMatrixPanel({ + userId, + initialMatrix, + onChange, +}: PreferenceMatrixProps) { + const [matrix, setMatrix] = useState( + initialMatrix ?? emptyMatrix() + ); + const [isLoading, setIsLoading] = useState(Boolean(userId)); + const [isSaving, setIsSaving] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + + useEffect(() => { + if (!userId) return; + let cancelled = false; + + async function load() { + try { + setIsLoading(true); + const response = await fetch( + `${API_BASE_URL}/notifications/preferences/matrix?userId=${encodeURIComponent(userId!)}`, + { + headers: { + Authorization: `Bearer ${typeof window !== "undefined" ? localStorage.getItem("auth_token") : ""}`, + }, + } + ); + if (!response.ok) throw new Error("Failed to load preference matrix"); + const data = (await response.json()) as PreferenceMatrixData; + if (!cancelled) { + setMatrix(data); + setError(null); + } + } catch (err) { + if (!cancelled) { + setError(err instanceof Error ? err.message : "Failed to load matrix"); + } + } finally { + if (!cancelled) setIsLoading(false); + } + } + + void load(); + return () => { + cancelled = true; + }; + }, [userId]); + + const toggle = useCallback( + (channel: NotificationChannel, category: NotificationCategory) => { + setMatrix((prev) => { + const next: PreferenceMatrixData = { + ...prev, + [channel]: { + ...prev[channel], + [category]: !prev[channel][category], + }, + }; + onChange?.(next); + setSaved(false); + return next; + }); + }, + [onChange] + ); + + const save = async () => { + if (!userId) { + onChange?.(matrix); + setSaved(true); + return; + } + try { + setIsSaving(true); + const response = await fetch(`${API_BASE_URL}/notifications/preferences/matrix`, { + method: "PUT", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${typeof window !== "undefined" ? localStorage.getItem("auth_token") : ""}`, + }, + body: JSON.stringify({ userId, matrix }), + }); + if (!response.ok) throw new Error("Failed to save preference matrix"); + setSaved(true); + setError(null); + onChange?.(matrix); + } catch (err) { + setError(err instanceof Error ? err.message : "Failed to save matrix"); + } finally { + setIsSaving(false); + } + }; + + if (isLoading) { + return ( +
+ Loading notification preferences… +
+ ); + } + + return ( +
+
+

Notification preferences

+

+ Choose which channels receive each category of alert. +

+
+ + {error ? ( +

+ {error} +

+ ) : null} + +
+ + + + + {CATEGORIES.map((category) => ( + + ))} + + + + {CHANNELS.map((channel) => ( + + + {CATEGORIES.map((category) => ( + + ))} + + ))} + +
Channel + {CATEGORY_LABELS[category]} +
{CHANNEL_LABELS[channel]} + +
+
+ +
+ + {saved ? ( + + Saved + + ) : null} +
+
+ ); +} + +/** @deprecated Prefer PreferenceMatrixPanel — kept for issue #1352 scope naming. */ +export const PreferenceMatrix = PreferenceMatrixPanel; diff --git a/frontend/components/notifications/index.ts b/frontend/components/notifications/index.ts new file mode 100644 index 00000000..86daaae3 --- /dev/null +++ b/frontend/components/notifications/index.ts @@ -0,0 +1,8 @@ +export { + PreferenceMatrixPanel, + PreferenceMatrix, + type PreferenceMatrixData, + type PreferenceMatrixProps, + type NotificationChannel, + type NotificationCategory, +} from "./PreferenceMatrix";