From 28c8ac625fd871de7e6f03274ac1f35d1861e9d5 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Tue, 17 Nov 2026 00:02:57 +0100 Subject: [PATCH 1/5] feat(dms): deliver notifications through registered channels --- .../dms-notifications/index.ts | 95 +++++-- .../src/pages/settings/users/notifications.ts | 38 ++- .../integration/notification-channels.test.ts | 256 ++++++++++++++++++ .../dms/src/utils/notification-channels.ts | 110 ++++++++ .../src/utils/notification-registry/index.ts | 1 + .../interface-dms/src/notifications/index.ts | 17 ++ .../src/notifications/internal.ts | 5 + .../src/notifications/sendable.ts | 18 +- .../interface-dms/src/notifications/types.ts | 54 ++++ 9 files changed, 558 insertions(+), 36 deletions(-) create mode 100644 packages/dms/src/test/integration/notification-channels.test.ts create mode 100644 packages/dms/src/utils/notification-channels.ts diff --git a/packages/dms/src/implementations/dms-notifications/index.ts b/packages/dms/src/implementations/dms-notifications/index.ts index 5daf5ced5..827d784ae 100644 --- a/packages/dms/src/implementations/dms-notifications/index.ts +++ b/packages/dms/src/implementations/dms-notifications/index.ts @@ -7,6 +7,7 @@ import { UserModel } from "@antelopejs/interface-dms/auth/db"; import type { DeliveryOptions, NotificationCategoryInfo, + NotificationChannelInfo, NotificationData, NotificationSubjectInfo, ReadScope, @@ -24,6 +25,8 @@ import { getRealtimeBroker, buildUserNotificationTopic } from "../../realtime"; import { runInBatches } from "../../utils/run-in-batches/index"; import { categoryRegistry, + channelRegistry, + isChannelOn, isSubjectLocked, subjectRegistry, } from "../../utils/notification-registry/index"; @@ -167,6 +170,42 @@ async function store( ); } +/** + * Hands a stored notification to every registered channel the recipient has + * on for its subject. A channel that throws is logged; the others still run + * and the in-app delivery stands. + */ +async function deliverToChannels( + userId: string, + data: NotificationData, + notification: UserNotification, + preferences: () => Promise>, + idempotencyKey?: string, +): Promise { + const subject = subjectRegistry.get( + `${data.subject.category.id}:${data.subject.id}`, + ); + const channels = [...channelRegistry.values()].filter( + (channel) => subject?.channels?.[channel.id], + ); + if (!subject || channels.length === 0) return; + const stored = await preferences(); + for (const channel of channels) { + if (!isChannelOn(subject, channel.id, stored)) continue; + try { + await channel.deliver(userId, data, { + notificationId: notification._id, + idempotencyKey, + }); + } catch (error) { + Logging.Error( + `[DMS] Notification channel "${channel.id}" failed to deliver "${data.title}" to "${userId}"`, + error, + ); + } + } +} + /** Tells the user's open tabs the whole feed is read, with its counts after it. */ export async function publishAllNotificationsRead( userId: string, @@ -193,6 +232,20 @@ export namespace internal { }, }; + export const RegisterNotificationChannel = { + register: (info: NotificationChannelInfo) => { + if (channelRegistry.has(info.id)) { + Logging.Warn( + `[DMS] Notification channel "${info.id}" registered again: the latest registration replaces the previous one`, + ); + } + channelRegistry.set(info.id, info); + }, + unregister: (info: NotificationChannelInfo) => { + channelRegistry.delete(info.id); + }, + }; + export const RegisterNotificationSubject = { register: (info: NotificationSubjectInfo) => { if (!categoryRegistry.has(info.category.id)) { @@ -215,26 +268,28 @@ export namespace internal { }, }; - const buildPreferenceKey = ( - categoryId: string, - subjectId: string, - ): string => { - return `${categoryId}:${subjectId}`; - }; + /** A user's stored preferences, read once per delivery and only when needed. */ + function preferencesReader( + userId: string, + ): () => Promise> { + let read: Promise> | undefined; + return () => { + read ??= GetModel(UserNotificationPreferencesModel) + .getOrCreatePreferences(userId) + .then((stored) => stored.preferences ?? {}); + return read; + }; + } async function canSendNotification( - userId: string, - categoryId: string, - subjectId: string, + data: NotificationData, + preferences: () => Promise>, ): Promise { - const preferenceKey = buildPreferenceKey(categoryId, subjectId); + const preferenceKey = `${data.subject.category.id}:${data.subject.id}`; const subject = subjectRegistry.get(preferenceKey); if (!subject) return false; if (isSubjectLocked(subject)) return true; - - const preferencesModel = GetModel(UserNotificationPreferencesModel); - const preferences = await preferencesModel.getOrCreatePreferences(userId); - return preferences.preferences?.[preferenceKey] ?? true; + return (await preferences())[preferenceKey] ?? true; } export async function SendToUser( @@ -246,15 +301,8 @@ export namespace internal { ): Promise { if (!isDeliverable(data, `"${userId}"`)) return; - const isAllowed = await canSendNotification( - userId, - data.subject.category.id, - data.subject.id, - ); - - if (!isAllowed) { - return; - } + const preferences = preferencesReader(userId); + if (!(await canSendNotification(data, preferences))) return; const created = await store(userId, data, { groupId, @@ -266,6 +314,7 @@ export namespace internal { await publishNotificationEvent(userId, NOTIFICATION_NEW_EVENT, { notification: created, }); + await deliverToChannels(userId, data, created, preferences, idempotencyKey); } export async function SendToUsers( diff --git a/packages/dms/src/pages/settings/users/notifications.ts b/packages/dms/src/pages/settings/users/notifications.ts index d8ef32dbf..92a3c5c64 100644 --- a/packages/dms/src/pages/settings/users/notifications.ts +++ b/packages/dms/src/pages/settings/users/notifications.ts @@ -31,7 +31,10 @@ import { TABLE_DISPLAY_ID, TableView, } from "@antelopejs/interface-dms/base/table-view"; -import type { NotificationSubjectInfo } from "@antelopejs/interface-dms/notifications/types"; +import type { + NotificationChannelId, + NotificationSubjectInfo, +} from "@antelopejs/interface-dms/notifications/types"; import { type UserNotificationCounts, UserNotificationPreferencesModel, @@ -45,10 +48,13 @@ import { parseNotificationFeedQuery, } from "../../../db/models"; import { - findSubjectByPreferenceKey, + type ChannelOffer, + findPreferenceTarget, getRegisteredCategories, + getRegisteredChannelIds, getRegisteredSubjects, isSubjectLocked, + registeredChannelOffers, publishAllNotificationsRead, publishNotificationsRead, publishNotificationsUnread, @@ -65,14 +71,20 @@ const HTTP_NOT_FOUND = 404; /** A registered subject as the settings screen lists it. */ export interface NotificationSubjectView extends NotificationSubjectInfo { - /** The user may not turn this subject off. */ + /** The user may not turn this subject off, on any channel. */ locked: boolean; + /** The registered channels the subject offers. */ + channels: Partial>; } function toSubjectView( subject: NotificationSubjectInfo, ): NotificationSubjectView { - return { ...subject, locked: isSubjectLocked(subject) }; + return { + ...subject, + locked: isSubjectLocked(subject), + channels: registeredChannelOffers(subject), + }; } function parsePageSize(value: QueryValue): number { @@ -208,19 +220,22 @@ function readFeedFilter(context: RequestContext): NotificationFeedFilter { return filter; } -/** Refuses keys that name no registered subject, and turning a locked subject off. */ +/** + * Refuses keys that name no registered subject, or a channel the subject does + * not offer or no module registered, and turning a locked subject off. + */ function assertChangesAllowed(changes: Record): void { for (const key of Object.keys(changes)) { assert( - findSubjectByPreferenceKey(key), + findPreferenceTarget(key), HTTP_BAD_REQUEST, "error.request_refused", ); } for (const [key, enabled] of Object.entries(changes)) { - const subject = findSubjectByPreferenceKey(key); + const target = findPreferenceTarget(key); assert( - enabled || !subject || !isSubjectLocked(subject), + enabled || !target || !isSubjectLocked(target.subject), HTTP_FORBIDDEN, "error.forbidden", ); @@ -296,11 +311,16 @@ export class NotificationsApiController extends Controller(NOTIFICATIONS_API) { return preferencesModel.mergePreferences(this.user._id, changes); } + /** + * The registered categories and subjects, and the ids of the registered + * delivery channels (`channels`): the screen draws a channel's column + * only when a module registered it. + */ @Get("/categories") async getCategories() { const categories = getRegisteredCategories(); const subjects = getRegisteredSubjects().map(toSubjectView); - return { categories, subjects }; + return { categories, subjects, channels: getRegisteredChannelIds() }; } /** diff --git a/packages/dms/src/test/integration/notification-channels.test.ts b/packages/dms/src/test/integration/notification-channels.test.ts new file mode 100644 index 000000000..8274d2515 --- /dev/null +++ b/packages/dms/src/test/integration/notification-channels.test.ts @@ -0,0 +1,256 @@ +import type { AxiosInstance } from "axios"; +import { expect } from "chai"; +import { SendableNotification } from "@antelopejs/interface-dms/notifications/sendable"; +import type { + NotificationCategoryInfo, + NotificationChannelInfo, + NotificationData, + NotificationDeliveryContext, + NotificationSubjectInfo, +} from "@antelopejs/interface-dms/notifications/types"; +import { pageRoutePath } from "@antelopejs/interface-dms/page"; +import { internal } from "../../implementations/dms-notifications"; +import { authorizedClient, registerUser } from "../helpers/auth"; +import { resetDatabase } from "../helpers/db"; + +const NOTIFICATIONS = "/settings/user/notifications"; +const PREFERENCES = pageRoutePath(NOTIFICATIONS, "/preferences"); +const CATEGORIES = pageRoutePath(NOTIFICATIONS, "/categories"); +const LIST = pageRoutePath(NOTIFICATIONS, "/list"); +const HTTP_OK = 200; +const HTTP_BAD_REQUEST = 400; +const HTTP_FORBIDDEN = 403; + +const category: NotificationCategoryInfo = { + id: "channel-test", + labelKey: "channel", + icon: "i-ph-envelope", + togglePermission: "default", +}; +const optIn: NotificationSubjectInfo = { + id: "opt-in", + labelKey: "opt-in", + category, + channels: { email: true }, +}; +const optOut: NotificationSubjectInfo = { + id: "opt-out", + labelKey: "opt-out", + category, + channels: { email: { defaultOn: true } }, +}; +const inAppOnly: NotificationSubjectInfo = { + id: "in-app-only", + labelKey: "in-app-only", + category, +}; +const locked: NotificationSubjectInfo = { + id: "locked", + labelKey: "locked", + category, + togglePermission: "forbidden", + channels: { email: true }, +}; +const SUBJECTS = [optIn, optOut, inAppOnly, locked]; +const emailKey = (subject: NotificationSubjectInfo) => + `${category.id}:${subject.id}@email`; +const inAppKey = (subject: NotificationSubjectInfo) => + `${category.id}:${subject.id}`; + +interface Delivery { + userId: string; + data: NotificationData; + context: NotificationDeliveryContext; +} + +interface CatalogSubject { + id: string; + channels: Record; +} + +let deliveries: Delivery[] = []; +let failing = false; +const channel: NotificationChannelInfo = { + id: "email", + deliver: (userId, data, context) => { + if (failing) throw new Error("mail server down"); + deliveries.push({ userId, data, context }); + }, +}; + +let sequence = 0; +function notificationOn( + subject: NotificationSubjectInfo, +): SendableNotification { + sequence += 1; + return new SendableNotification({ + icon: "i-ph-envelope", + title: `Channel test ${sequence} on ${subject.id}`, + description: "Channel test.", + subject, + }); +} + +async function titlesOf(client: AxiosInstance): Promise { + const list = await client.get<{ title: string }[]>(LIST); + return list.data.map((row) => row.title); +} + +/** The signed-in user of a suite. */ +interface ChannelTestUser { + client: () => AxiosInstance; + userId: () => string; +} + +/** Registers the test taxonomy on a fresh database and signs a user in. */ +function useChannelTestUser(): ChannelTestUser { + let client: AxiosInstance | undefined; + let userId = ""; + before(async () => { + await resetDatabase(); + const user = await registerUser({ owner: true }); + client = authorizedClient(user.accessToken); + userId = user.userId; + internal.RegisterNotificationCategory.register(category); + for (const subject of SUBJECTS) { + internal.RegisterNotificationSubject.register(subject); + } + }); + after(() => { + for (const subject of SUBJECTS) { + internal.RegisterNotificationSubject.unregister(subject); + } + internal.RegisterNotificationCategory.unregister(category); + }); + return { + client: () => { + if (!client) throw new Error("The test user is not signed in"); + return client; + }, + userId: () => userId, + }; +} + +interface Catalog { + channels: string[]; + subjects: CatalogSubject[]; +} + +describe("[integration] notification channels, none registered", () => { + const user = useChannelTestUser(); + + it("lists no channel and no offer (fails when the screen would draw an e-mail switch no module delivers)", async () => { + const catalog = await user.client().get(CATEGORIES); + const subject = catalog.data.subjects.find((s) => s.id === optIn.id); + expect(catalog.data.channels).to.deep.equal([]); + expect(subject?.channels).to.deep.equal({}); + }); + + it("refuses an e-mail preference (fails when a key for an unregistered channel is stored)", async () => { + const refused = await user.client().patch(PREFERENCES, { + [emailKey(optIn)]: true, + }); + expect(refused.status).to.equal(HTTP_BAD_REQUEST); + }); +}); + +describe("[integration] notification channels, one registered", () => { + const user = useChannelTestUser(); + const patch = (changes: Record) => + user.client().patch>(PREFERENCES, changes); + + before(() => { + internal.RegisterNotificationChannel.register(channel); + }); + + after(() => { + internal.RegisterNotificationChannel.unregister(channel); + }); + + beforeEach(() => { + deliveries = []; + failing = false; + }); + + it("lists the channel and each subject's offer with its default (fails when the defaults are not read from the subject)", async () => { + const catalog = await user.client().get(CATEGORIES); + const offers = Object.fromEntries( + catalog.data.subjects.map((s) => [s.id, s.channels]), + ); + expect(catalog.data.channels).to.deep.equal(["email"]); + expect(offers[optIn.id]).to.deep.equal({ email: { defaultOn: false } }); + expect(offers[optOut.id]).to.deep.equal({ email: { defaultOn: true } }); + expect(offers[inAppOnly.id]).to.deep.equal({}); + }); + + it("does not mail a subject offered off until the user turns it on, then mails it with its tenant (fails when the default is on or the tenant is lost)", async () => { + await notificationOn(optIn).toUser(user.userId()); + expect(deliveries).to.have.length(0); + + const saved = await patch({ [emailKey(optIn)]: true }); + expect(saved.status, JSON.stringify(saved.data)).to.equal(HTTP_OK); + expect(saved.data[emailKey(optIn)]).to.equal(true); + + await notificationOn(optIn).toUser(user.userId(), { tenantId: "tenant-a" }); + expect(deliveries).to.have.length(1); + expect(deliveries[0]?.userId).to.equal(user.userId()); + expect(deliveries[0]?.data.tenantId).to.equal("tenant-a"); + expect(deliveries[0]?.context.notificationId).to.be.a("string"); + }); + + it("mails a subject offered on until the user turns it off (fails when defaultOn is ignored or the choice is not read)", async () => { + await notificationOn(optOut).toUser(user.userId()); + expect(deliveries).to.have.length(1); + + await patch({ [emailKey(optOut)]: false }); + await notificationOn(optOut).toUser(user.userId()); + expect(deliveries).to.have.length(1); + }); + + it("never mails a subject that offers no e-mail, and refuses its e-mail key (fails when every subject is mailed)", async () => { + await notificationOn(inAppOnly).toUser(user.userId()); + const refused = await patch({ [emailKey(inAppOnly)]: true }); + expect(deliveries).to.have.length(0); + expect(refused.status).to.equal(HTTP_BAD_REQUEST); + }); + + it("does not mail a subject the user turned off in the app (fails when the channel runs without a stored notification)", async () => { + await patch({ [inAppKey(optIn)]: false, [emailKey(optIn)]: true }); + await notificationOn(optIn).toUser(user.userId()); + await patch({ [inAppKey(optIn)]: true }); + expect(deliveries).to.have.length(0); + }); + + it("mails a locked subject whatever is stored, and refuses turning its e-mail off (fails when the lock covers only the app)", async () => { + const refused = await patch({ [emailKey(locked)]: false }); + await notificationOn(locked).toUser(user.userId()); + expect(refused.status).to.equal(HTTP_FORBIDDEN); + expect(deliveries).to.have.length(1); + }); + + it("mails an idempotent send once however often it is retried (fails when a retry mails again)", async () => { + await patch({ [emailKey(optOut)]: true }); + const keyed = notificationOn(optOut); + await keyed.toUsersIdempotently([user.userId()], "channel-test-event"); + await keyed.toUsersIdempotently([user.userId()], "channel-test-event"); + expect(deliveries).to.have.length(1); + expect(deliveries[0]?.context.idempotencyKey).to.equal( + "channel-test-event", + ); + }); + + it("mails a repeat dropped by the duplicate window once (fails when a deduplicated send still mails)", async () => { + const sendable = notificationOn(optOut); + await sendable.toUser(user.userId()); + await sendable.toUser(user.userId()); + expect(deliveries).to.have.length(1); + }); + + it("keeps the in-app notification when the channel throws (fails when a channel error fails the send)", async () => { + failing = true; + await notificationOn(optOut).toUser(user.userId()); + expect(await titlesOf(user.client())).to.include( + `Channel test ${sequence} on ${optOut.id}`, + ); + }); +}); diff --git a/packages/dms/src/utils/notification-channels.ts b/packages/dms/src/utils/notification-channels.ts new file mode 100644 index 000000000..d3e0b3295 --- /dev/null +++ b/packages/dms/src/utils/notification-channels.ts @@ -0,0 +1,110 @@ +import type { + NotificationChannelId, + NotificationChannelInfo, + NotificationSubjectInfo, +} from "@antelopejs/interface-dms/notifications/types"; +import { + findSubjectByPreferenceKey, + isSubjectLocked, +} from "./notification-registry"; +import { ownValue } from "./own-value"; + +export const channelRegistry = new Map< + NotificationChannelId, + NotificationChannelInfo +>(); + +/** The ids of the channels a module has registered. */ +export function getRegisteredChannelIds(): NotificationChannelId[] { + return Array.from(channelRegistry.keys()); +} + +/** How a subject offers a channel once its shorthand is read. */ +export interface ChannelOffer { + /** The channel is on for a user who never chose. */ + defaultOn: boolean; +} + +/** The subject's offer of `channel`, or undefined when it does not offer it. */ +export function channelOffer( + subject: NotificationSubjectInfo, + channel: NotificationChannelId, +): ChannelOffer | undefined { + const offer = subject.channels?.[channel]; + if (offer === undefined || offer === false) return undefined; + return { defaultOn: offer !== true && offer.defaultOn === true }; +} + +/** The registered channels the subject offers, read. */ +export function registeredChannelOffers( + subject: NotificationSubjectInfo, +): Partial> { + const offers: Partial> = {}; + for (const channel of getRegisteredChannelIds()) { + const offer = channelOffer(subject, channel); + if (offer) offers[channel] = offer; + } + return offers; +} + +export function subjectPreferenceKey(subject: NotificationSubjectInfo): string { + return `${subject.category.id}:${subject.id}`; +} + +const CHANNEL_KEY_SEPARATOR = "@"; + +/** + * The key a user's choice for `channel` on a subject is stored under, next + * to the subject's in-app key in the same preference map. + */ +export function channelPreferenceKey( + subject: NotificationSubjectInfo, + channel: NotificationChannelId, +): string { + return `${subjectPreferenceKey(subject)}${CHANNEL_KEY_SEPARATOR}${channel}`; +} + +/** What a stored preference key switches. */ +export interface PreferenceTarget { + subject: NotificationSubjectInfo; + /** Unset for the in-app switch. */ + channel?: NotificationChannelId; +} + +/** + * The subject and channel a preference key names, or undefined when it names + * no registered subject, or a channel the subject does not offer or no module + * has registered. + */ +export function findPreferenceTarget( + key: string, +): PreferenceTarget | undefined { + const inApp = findSubjectByPreferenceKey(key); + if (inApp) return { subject: inApp }; + const separator = key.lastIndexOf(CHANNEL_KEY_SEPARATOR); + if (separator < 0) return undefined; + const subject = findSubjectByPreferenceKey(key.slice(0, separator)); + const channelId = key.slice(separator + 1); + const channel = getRegisteredChannelIds().find((id) => id === channelId); + if (!subject || !channel || !channelOffer(subject, channel)) return undefined; + return { subject, channel }; +} + +/** + * Whether a user with these stored preferences receives the subject through + * `channel`. A locked subject reaches its recipients on every channel it + * offers, whatever they stored. + */ +export function isChannelOn( + subject: NotificationSubjectInfo, + channel: NotificationChannelId, + preferences: Record, +): boolean { + const offer = channelOffer(subject, channel); + if (!offer) return false; + if (isSubjectLocked(subject)) return true; + return ( + ownValue(preferences, channelPreferenceKey(subject, channel)) ?? + offer.defaultOn + ); +} diff --git a/packages/dms/src/utils/notification-registry/index.ts b/packages/dms/src/utils/notification-registry/index.ts index e919a239d..3a6eda18b 100644 --- a/packages/dms/src/utils/notification-registry/index.ts +++ b/packages/dms/src/utils/notification-registry/index.ts @@ -1 +1,2 @@ export * from "../notification-registry"; +export * from "../notification-channels"; diff --git a/packages/interface-dms/src/notifications/index.ts b/packages/interface-dms/src/notifications/index.ts index 96f53ddc2..9c7073d58 100644 --- a/packages/interface-dms/src/notifications/index.ts +++ b/packages/interface-dms/src/notifications/index.ts @@ -5,6 +5,7 @@ export { internal }; export * from "./types"; import type { NotificationCategoryInfo, + NotificationChannelInfo, NotificationSubjectInfo, } from "./types"; @@ -36,6 +37,22 @@ export function NotificationSubject( return notificationSubject; } +/** + * Registers a delivery channel (`email`): every notification stored in a + * user's feed is also handed to `deliver` when its subject offers the channel + * and the user has it on. One module registers a channel id; a later + * registration of the same id replaces it. The registration goes away with + * the module that made it. + */ +export function NotificationChannel( + id: NotificationChannelInfo["id"], + channel: Omit, +): NotificationChannelInfo { + const notificationChannel: NotificationChannelInfo = { id, ...channel }; + internal.RegisterNotificationChannel.register(notificationChannel); + return notificationChannel; +} + export const SystemCategory = NotificationCategory("system", { labelKey: "dms.notifications.categories.system", descriptionKey: "dms.notifications.categories.system_desc", diff --git a/packages/interface-dms/src/notifications/internal.ts b/packages/interface-dms/src/notifications/internal.ts index c784a4b55..71595748e 100644 --- a/packages/interface-dms/src/notifications/internal.ts +++ b/packages/interface-dms/src/notifications/internal.ts @@ -5,6 +5,7 @@ import { import type { DeliveryOptions, NotificationCategoryInfo, + NotificationChannelInfo, NotificationData, NotificationSubjectInfo, ReadScope, @@ -22,6 +23,10 @@ export namespace internal { (info: NotificationSubjectInfo) => void >(); + export const RegisterNotificationChannel = new RegisteringProxy< + (info: NotificationChannelInfo) => void + >(); + export const SendToUser = InterfaceFunction< ( diff --git a/packages/interface-dms/src/notifications/sendable.ts b/packages/interface-dms/src/notifications/sendable.ts index 0c726133c..1cb89fc05 100644 --- a/packages/interface-dms/src/notifications/sendable.ts +++ b/packages/interface-dms/src/notifications/sendable.ts @@ -10,6 +10,16 @@ function deliveryOf(options: SendOptions): DeliveryOptions { return { dedupe: options.dedupe }; } +/** The notification as sent: `options.tenantId`, when set, names its workspace. */ +function sentData( + data: NotificationData, + options: SendOptions, +): NotificationData { + return options.tenantId === undefined + ? data + : { ...data, tenantId: options.tenantId }; +} + export class SendableNotification { private readonly data: NotificationData; @@ -25,7 +35,7 @@ export class SendableNotification { async toUser(userId: string, options: SendOptions = {}): Promise { await internal.SendToUser( userId, - this.data, + sentData(this.data, options), undefined, options.idempotencyKey, deliveryOf(options), @@ -35,7 +45,7 @@ export class SendableNotification { async toUsers(userIds: string[], options: SendOptions = {}): Promise { await internal.SendToUsers( userIds, - this.data, + sentData(this.data, options), options.readScope, options.idempotencyKey, deliveryOf(options), @@ -56,12 +66,12 @@ export class SendableNotification { roleIds: string[], options: RoleSendOptions = {}, ): Promise { - await internal.SendToRoles(roleIds, this.data, options); + await internal.SendToRoles(roleIds, sentData(this.data, options), options); } async broadcast(options: SendOptions = {}): Promise { await internal.SendToAll( - this.data, + sentData(this.data, options), options.readScope, options.idempotencyKey, deliveryOf(options), diff --git a/packages/interface-dms/src/notifications/types.ts b/packages/interface-dms/src/notifications/types.ts index 32537a7fc..71033dfe9 100644 --- a/packages/interface-dms/src/notifications/types.ts +++ b/packages/interface-dms/src/notifications/types.ts @@ -28,6 +28,52 @@ export interface NotificationSubjectInfo { togglePermission?: TogglePermission; /** Translation key of a badge shown next to the subject label (`Developer mode`). */ badgeKey?: string; + /** + * The channels this subject also reaches its recipients through, next to + * the in-app feed. A subject that names none is in-app only. A channel + * delivers only when a module registers it (`NotificationChannel`). + */ + channels?: NotificationChannelOffers; +} + +/** The delivery channels a subject can offer next to the in-app feed. */ +export type NotificationChannelId = "email"; + +/** + * How a subject offers a channel. `true` offers it off until the user turns + * it on; `{ defaultOn: true }` offers it on until the user turns it off. + * `false` does not offer it. + */ +export type NotificationChannelOffer = boolean | { defaultOn?: boolean }; + +export type NotificationChannelOffers = Partial< + Record +>; + +/** What a channel learns about one delivery besides its recipient and content. */ +export interface NotificationDeliveryContext { + /** Id of the in-app notification this delivery follows. */ + notificationId: string; + /** The event key of a keyed send (`idempotencyKey`). */ + idempotencyKey?: string; +} + +/** + * A channel a notification also reaches its recipient through. The DMS calls + * `deliver` once per stored in-app notification whose recipient has the + * channel on for its subject. + */ +export interface NotificationChannelInfo { + id: NotificationChannelId; + /** + * Hands one notification to the channel. A rejection is logged and never + * fails the in-app delivery. Sends wait for it, so queue slow work. + */ + deliver( + userId: string, + data: NotificationData, + context: NotificationDeliveryContext, + ): Promise | void; } /** How a delivery is stored, whoever receives it. */ @@ -45,6 +91,12 @@ export interface DeliveryOptions { export interface SendOptions extends DeliveryOptions { readScope?: ReadScope; + /** + * The workspace the notification is about. Channels receive it in + * `NotificationData.tenantId`; `toRoles` also limits its recipients to + * this tenant's members. + */ + tenantId?: string; /** Stable event key, unique across notification producers. Retries preserve delivery and dismissal state. */ idempotencyKey?: string; } @@ -68,6 +120,8 @@ export interface NotificationData { params?: Record; /** Icon well colour; unset notifications use `primary` while unread, neutral once read. */ tone?: NotificationTone; + /** The workspace the notification is about, from `SendOptions.tenantId`. */ + tenantId?: string; } export type RequiredFields = "icon" | "title" | "description" | "subject"; From e6f1268bbc1f8a46a252786c5f9ae5138b6530d4 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Tue, 17 Nov 2026 00:07:47 +0100 Subject: [PATCH 2/5] feat(dms): draw the e-mail column of the notification preferences when a channel is registered --- .../docs/02.building/06.backend-services.md | 8 +- .../03.auth-and-tenancy/01.authentication.md | 2 +- .../NotificationMatrixSubject.vue | 35 +++- .../NotificationPreferencesForm.vue | 14 +- .../notification/useNotificationCatalog.ts | 24 +++ .../useNotificationPreferences.ts | 44 +++- .../dms-layout/i18n/locales/layout-en-GB.json | 3 + .../dms-layout/i18n/locales/layout-fr-FR.json | 3 + .../notification-preferences-email.test.ts | 189 ++++++++++++++++++ .../dms/src/utils/notification-channels.ts | 4 +- .../docs/4.notifications/1.introduction.md | 1 + .../2.categories-and-subjects.md | 7 +- .../docs/4.notifications/3.sending.md | 5 +- .../4.notifications/4.delivery-channels.md | 80 ++++++++ packages/interface-dms/docs/index.md | 2 +- 15 files changed, 404 insertions(+), 17 deletions(-) create mode 100644 packages/dms/frontend-vue/tests/notification-preferences-email.test.ts create mode 100644 packages/interface-dms/docs/4.notifications/4.delivery-channels.md diff --git a/packages/dms/docs/02.building/06.backend-services.md b/packages/dms/docs/02.building/06.backend-services.md index 9d6282c1e..1dc8bf273 100644 --- a/packages/dms/docs/02.building/06.backend-services.md +++ b/packages/dms/docs/02.building/06.backend-services.md @@ -84,17 +84,17 @@ const n = Notification() .linkTo("/dashboard") .build(); // SendableNotification -await n.toUser(userId); // optional 2nd arg: { idempotencyKey, dedupe } -await n.toUsers([a, b]); // optional 2nd arg: { readScope, idempotencyKey, dedupe } +await n.toUser(userId); // optional 2nd arg: { tenantId, idempotencyKey, dedupe } +await n.toUsers([a, b]); // optional 2nd arg: { tenantId, readScope, idempotencyKey, dedupe } await n.toRoles([roleId]); // optional 2nd arg: { tenantId, readScope, idempotencyKey, dedupe } -await n.broadcast(); // optional arg: { readScope, idempotencyKey, dedupe } +await n.broadcast(); // optional arg: { tenantId, readScope, idempotencyKey, dedupe } ``` `.tone(tone)` colours the icon well the notification is listed with: `neutral`, `primary`, `success`, `warning` or `error`. Notifications are organized by **category**, then **subject**. Users toggle the subjects they receive from their notification settings, and a send to a user who disabled the subject is skipped without an error. The built-in subjects are `GeneralSubject`, `SecuritySubject`, `AccountSubject`, `CollaborationSubject` and `AutomationSubject`, under `SystemCategory`. -Register your own with the public `NotificationCategory(id, opts)` and `NotificationSubject(id, opts)` functions, then pass your subject to `.subject(...)`. A category or subject can set `togglePermission: "forbidden"` so users cannot turn it off. `GeneralSubject` does. +Register your own with the public `NotificationCategory(id, opts)` and `NotificationSubject(id, opts)` functions, then pass your subject to `.subject(...)`. A category or subject can set `togglePermission: "forbidden"` so users cannot turn it off. `GeneralSubject` does. A subject can also offer e-mail (`channels: { email: true }`), which a mail module delivers once it registers the channel with `NotificationChannel("email", { deliver })` ([Delivery channels](/docs/interfaces/notifications/delivery-channels)). Three delivery details: diff --git a/packages/dms/docs/03.auth-and-tenancy/01.authentication.md b/packages/dms/docs/03.auth-and-tenancy/01.authentication.md index 47d79a0d9..d1d596b6d 100644 --- a/packages/dms/docs/03.auth-and-tenancy/01.authentication.md +++ b/packages/dms/docs/03.auth-and-tenancy/01.authentication.md @@ -157,7 +157,7 @@ Go to **Settings → Notifications** and expand a category to see its subjects. ![Notification preferences in the Helio demo, with the System category expanded to its subjects](../images/captures/notification-preferences.webp) -The Email column is marked **Soon**. These switches do not configure an email channel. Turning a subject off stops new notifications of that subject, and the messages already in the inbox stay. +Without a mail module, the Email column is marked **Soon** and holds no switch. Once a module registers the e-mail channel, each subject that offers e-mail gets an Email switch, saved on its own like the in-app one; it is disabled while the subject is off in the app, since e-mail is a copy of the in-app notification ([Delivery channels](/docs/interfaces/notifications/delivery-channels)). Turning a subject off stops new notifications of that subject, and the messages already in the inbox stay. ```text Category → subject → recipient diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue b/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue index 8ab90ad04..fd3a15148 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue @@ -10,18 +10,37 @@ interface NotificationMatrixSubjectProps { subject: NotificationSubject; enabled: boolean; state: SaveStatusState; + /** The e-mail column holds a switch for this subject. */ + offersEmail?: boolean; + emailEnabled?: boolean; } const props = defineProps(); -const emit = defineEmits<{ toggle: [enabled: boolean]; retry: [] }>(); +const emit = defineEmits<{ + toggle: [enabled: boolean]; + "toggle-email": [enabled: boolean]; + retry: []; +}>(); const { t } = useI18n(); const label = computed(() => t(props.subject.labelKey)); const isLocked = computed(() => props.subject.locked === true); +/** E-mail follows the in-app notification: none is sent without it. */ +const isEmailDisabled = computed(() => isLocked.value || !props.enabled); +const emailTitle = computed(() => { + if (isLocked.value) return t("page.settings.notifications.locked_hint"); + return props.enabled + ? undefined + : t("page.settings.notifications.email_needs_in_app"); +}); const onToggle = (value: boolean) => { if (props.state !== "saving") emit("toggle", value); }; + +const onToggleEmail = (value: boolean) => { + if (props.state !== "saving") emit("toggle-email", value); +}; - {{ t("page.settings.notifications.email_hint") }} + {{ + hasEmailChannel + ? t("page.settings.notifications.email_hint_active") + : t("page.settings.notifications.email_hint") + }} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts index f6bbbb137..3a82c368a 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts @@ -11,6 +11,15 @@ export interface NotificationCategory { tagKey?: string; } +/** The delivery channels a subject can offer next to the in-app feed. */ +export type NotificationChannelId = "email"; + +/** How a subject offers a channel, as the server reads it. */ +export interface NotificationChannelOffer { + /** The channel is on for a user who never chose. */ + defaultOn: boolean; +} + export interface NotificationSubject { id: string; category: NotificationCategory; @@ -20,11 +29,15 @@ export interface NotificationSubject { badgeKey?: string; /** Set by the server: the user may not turn the subject off. */ locked?: boolean; + /** Set by the server: the registered channels the subject offers. */ + channels?: Partial>; } interface NotificationCatalogResponse { categories: NotificationCategory[]; subjects: NotificationSubject[]; + /** The channels a module registered; none on an installation without one. */ + channels?: NotificationChannelId[]; } export const buildPreferenceKey = (categoryId: string, subjectId: string) => @@ -33,6 +46,12 @@ export const buildPreferenceKey = (categoryId: string, subjectId: string) => export const subjectPreferenceKey = (subject: NotificationSubject) => buildPreferenceKey(subject.category.id, subject.id); +/** The key the subject's switch for `channel` is stored under. */ +export const channelPreferenceKey = ( + subject: NotificationSubject, + channel: NotificationChannelId, +) => `${subjectPreferenceKey(subject)}@${channel}`; + const CATALOG_URL = pageRoutePath( "/settings/user/notifications", "/categories", @@ -55,6 +74,10 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => { ); const categories = computed(() => catalog.data.value?.categories ?? []); const subjects = computed(() => catalog.data.value?.subjects ?? []); + const channels = computed(() => catalog.data.value?.channels ?? []); + /** A module registered `channel`: its column holds switches. */ + const hasChannel = (channel: NotificationChannelId) => + channels.value.includes(channel); const isLoaded = computed(() => !!catalog.data.value); const loadFailed = computed(() => !isLoaded.value && hasFailed(catalog)); @@ -76,6 +99,7 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => { return { categories, subjects, + hasChannel, isLoaded, loadFailed, loadCatalog, diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts index 25359fabf..ac32f0679 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts @@ -1,7 +1,9 @@ import { pageRoutePath } from "#dms-core/app/utils/pageRoutes"; import type { SaveStatusState } from "#dms-ui/app/components/save-bar/SaveStatus.vue"; import { useInstantSave } from "#dms-ui/app/entries/composables/instant-save/useInstantSave"; +import { combineSaveStates } from "#dms-ui/app/composables/layout/useInstantSaveHeader"; import { + channelPreferenceKey, hasFailed, type NotificationCategory, type NotificationSubject, @@ -51,8 +53,24 @@ export const useNotificationPreferences = ( () => !(isStoredRead.value && catalog.isLoaded.value) && !loadFailed.value, ); + /** What an e-mail switch the user never touched reads, by its key. */ + const emailDefaults = computed(() => + Object.fromEntries( + catalog.subjects.value.flatMap((subject) => + subject.channels?.email + ? [ + [ + channelPreferenceKey(subject, "email"), + subject.channels.email.defaultOn, + ], + ] + : [], + ), + ), + ); + const instant = useInstantSave({ - read: (key) => preferences.value[key] ?? true, + read: (key) => preferences.value[key] ?? emailDefaults.value[key] ?? true, write: (key, enabled) => { preferences.value = { ...preferences.value, [key]: enabled }; }, @@ -63,8 +81,23 @@ export const useNotificationPreferences = ( const isEnabled = (subject: NotificationSubject) => preferences.value[subjectPreferenceKey(subject)] ?? true; + /** The subject has an e-mail switch: a module delivers e-mail and the subject offers it. */ + const offersEmail = (subject: NotificationSubject) => + catalog.hasChannel("email") && !!subject.channels?.email; + + /** A locked subject is mailed whatever is stored, as the server sends it. */ + const isEmailEnabled = (subject: NotificationSubject) => + subject.locked === true || + (preferences.value[channelPreferenceKey(subject, "email")] ?? + subject.channels?.email?.defaultOn ?? + false); + + /** The row's state cell sums up its in-app and e-mail switches. */ const rowState = (subject: NotificationSubject): SaveStatusState => - instant.states[subjectPreferenceKey(subject)] ?? "idle"; + combineSaveStates([ + instant.states[subjectPreferenceKey(subject)], + instant.states[channelPreferenceKey(subject, "email")], + ]); const toggleableSubjectsOf = (category: NotificationCategory) => catalog.subjectsOf(category.id).filter((subject) => !subject.locked); @@ -72,6 +105,9 @@ export const useNotificationPreferences = ( const toggleSubject = (subject: NotificationSubject, enabled: boolean) => instant.change(subjectPreferenceKey(subject), enabled); + const toggleEmail = (subject: NotificationSubject, enabled: boolean) => + instant.change(channelPreferenceKey(subject, "email"), enabled); + const toggleCategory = (category: NotificationCategory, enabled: boolean) => instant.changeMany( Object.fromEntries( @@ -95,6 +131,10 @@ export const useNotificationPreferences = ( return { categories: catalog.categories, subjectsOf: catalog.subjectsOf, + hasEmailChannel: computed(() => catalog.hasChannel("email")), + offersEmail, + isEmailEnabled, + toggleEmail, preferences, failedChanges: instant.failed, saveState: instant.state, diff --git a/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-en-GB.json b/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-en-GB.json index 47bce77b8..ec8bb78e9 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-en-GB.json +++ b/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-en-GB.json @@ -174,6 +174,9 @@ "category_collapse": "Hide {name} notifications", "locked_hint": "Required for account safety", "email_hint": "Only in-app notifications are available today. Email delivery is on the way.", + "email_hint_active": "Subjects with a switch in the Email column can also reach you by email, on top of the app.", + "email_switch": "Email: {name}", + "email_needs_in_app": "Turn the in-app notification on to also receive it by email.", "save_failed_on": "Couldn’t save — the switch was turned back on.", "save_failed_off": "Couldn’t save — the switch was turned back off.", "save_failed_many": "Couldn’t save — the switches were turned back.", diff --git a/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-fr-FR.json b/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-fr-FR.json index 400afbef7..6ebfa429d 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-fr-FR.json +++ b/packages/dms/frontend-vue/layers/dms-layout/i18n/locales/layout-fr-FR.json @@ -174,6 +174,9 @@ "category_collapse": "Masquer les notifications {name}", "locked_hint": "Requis pour la sécurité du compte", "email_hint": "Seules les notifications dans l’app sont disponibles aujourd’hui. L’envoi par e-mail arrive bientôt.", + "email_hint_active": "Les sujets marqués d’un interrupteur dans la colonne E-mail peuvent aussi vous parvenir par e-mail, en plus de l’app.", + "email_switch": "E-mail : {name}", + "email_needs_in_app": "Activez la notification dans l’app pour la recevoir aussi par e-mail.", "save_failed_on": "Échec de l’enregistrement — l’interrupteur a été réactivé.", "save_failed_off": "Échec de l’enregistrement — l’interrupteur a été désactivé à nouveau.", "save_failed_many": "Échec de l’enregistrement — les interrupteurs ont été rétablis.", diff --git a/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts new file mode 100644 index 000000000..75d91df97 --- /dev/null +++ b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts @@ -0,0 +1,189 @@ +/** @vitest-environment jsdom */ +import { + computed, + createApp, + defineComponent, + h, + onMounted, + ref, + type App, +} from "vue"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import NotificationPreferencesForm from "../layers/dms-layout/app/entries/components/pages/settings/notification/NotificationPreferencesForm"; +import { NOTIFICATION_GROUP_STORAGE_PREFIX } from "../layers/dms-layout/app/entries/composables/notification/useNotificationGroupsOpen"; +import { + browserRuntime, + stubApiData, + type ApiAnswer, +} from "./helpers/api-data-runtime"; +import { installAuthSettingsRuntime } from "./helpers/auth-settings-runtime"; + +const PREFERENCES_URL = "/dms/pages/settings/user/notifications/preferences"; +const category = { id: "work", labelKey: "Work", icon: "i-ph-briefcase" }; + +function catalog(channels: string[], stored: Record = {}) { + const offered = channels.length > 0; + return vi.fn(async (url: string): Promise => { + if (url.endsWith("/categories")) { + return { + categories: [category], + channels, + subjects: [ + { + id: "assigned", + category, + labelKey: "Assigned", + channels: offered ? { email: { defaultOn: false } } : {}, + }, + { + id: "digest", + category, + labelKey: "Digest", + channels: offered ? { email: { defaultOn: true } } : {}, + }, + { id: "mentions", category, labelKey: "Mentions", channels: {} }, + ], + }; + } + return url === PREFERENCES_URL ? stored : {}; + }); +} + +let app: App | undefined; + +async function mount(authFetch: ReturnType) { + stubApiData(authFetch); + localStorage.setItem(`${NOTIFICATION_GROUP_STORAGE_PREFIX}work`, "open"); + app = createApp( + defineComponent({ setup: () => () => h(NotificationPreferencesForm) }), + ); + browserRuntime(app); + const passThrough = defineComponent({ + setup: + (_props, { slots }) => + () => + h("div", [slots.default?.(), slots.footer?.()]), + }); + for (const [name, stub] of Object.entries({ + DmsSectionPanel: passThrough, + DmsEmptyState: passThrough, + DmsIconWell: defineComponent({ render: () => h("span") }), + UBadge: defineComponent({ + props: { label: String }, + setup: (props) => () => h("span", { "data-badge": "" }, props.label), + }), + UIcon: defineComponent({ render: () => h("span") }), + UButton: defineComponent({ render: () => h("button") }), + USwitch: defineComponent({ + props: { modelValue: Boolean, disabled: Boolean }, + emits: ["update:modelValue"], + setup: + (props, { emit, attrs }) => + () => + h("button", { + ...attrs, + type: "button", + role: "switch", + disabled: props.disabled, + "aria-checked": String(props.modelValue), + onClick: () => emit("update:modelValue", !props.modelValue), + }), + }), + UCollapsible: defineComponent({ + props: { open: Boolean }, + setup: + (props, { slots }) => + () => + h("div", props.open ? slots.content?.() : []), + }), + })) { + app.component(name, stub); + } + const container = document.createElement("div"); + document.body.append(container); + app.mount(container); + await vi.waitFor(() => expect(rowOf(container, "Assigned")).toBeTruthy()); + return container; +} + +const rowOf = (container: HTMLElement, label: string) => + [ + ...container.querySelectorAll( + '[role="rowgroup"] [role="row"]', + ), + ].find((row) => + row.querySelector('[role="rowheader"]')?.textContent?.includes(label), + ); + +const emailSwitchOf = (container: HTMLElement, label: string) => + rowOf(container, label)?.querySelector( + '[data-channel="email"]', + ) ?? null; + +beforeEach(() => { + installAuthSettingsRuntime(); + localStorage.clear(); + vi.stubGlobal("computed", computed); + vi.stubGlobal("ref", ref); + vi.stubGlobal("onMounted", onMounted); + vi.stubGlobal("useI18n", () => ({ t: (key: string) => key })); +}); + +afterEach(() => { + app?.unmount(); + app = undefined; + document.body.innerHTML = ""; + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +describe("notification preferences e-mail column", () => { + it("keeps the Soon column without a registered channel (fails when an installation without a mail module draws e-mail switches)", async () => { + const container = await mount(catalog([])); + + expect(emailSwitchOf(container, "Assigned")).toBeNull(); + expect(container.querySelector("[data-badge]")?.textContent).toBe( + "page.settings.notifications.soon", + ); + expect(container.textContent).toContain( + "page.settings.notifications.email_hint", + ); + }); + + it("draws a switch for each subject offering e-mail, on its default (fails when the default of the offer is ignored)", async () => { + const container = await mount(catalog(["email"])); + + expect( + emailSwitchOf(container, "Assigned")?.getAttribute("aria-checked"), + ).toBe("false"); + expect( + emailSwitchOf(container, "Digest")?.getAttribute("aria-checked"), + ).toBe("true"); + expect(emailSwitchOf(container, "Mentions")).toBeNull(); + expect(container.querySelector("[data-badge]")).toBeNull(); + expect(container.textContent).toContain( + "page.settings.notifications.email_hint_active", + ); + }); + + it("saves the e-mail switch under its own key (fails when it changes the in-app preference)", async () => { + const authFetch = catalog(["email"]); + const container = await mount(authFetch); + + emailSwitchOf(container, "Assigned")?.click(); + + await vi.waitFor(() => + expect(authFetch).toHaveBeenCalledWith(PREFERENCES_URL, { + method: "PATCH", + body: { "work:assigned@email": true }, + }), + ); + }); + + it("disables the e-mail switch of a subject off in the app (fails when e-mail looks on for a notification never sent)", async () => { + const container = await mount(catalog(["email"], { "work:digest": false })); + + expect(emailSwitchOf(container, "Digest")?.disabled).toBe(true); + expect(emailSwitchOf(container, "Assigned")?.disabled).toBe(false); + }); +}); diff --git a/packages/dms/src/utils/notification-channels.ts b/packages/dms/src/utils/notification-channels.ts index d3e0b3295..88c9765f2 100644 --- a/packages/dms/src/utils/notification-channels.ts +++ b/packages/dms/src/utils/notification-channels.ts @@ -47,7 +47,7 @@ export function registeredChannelOffers( return offers; } -export function subjectPreferenceKey(subject: NotificationSubjectInfo): string { +function subjectPreferenceKey(subject: NotificationSubjectInfo): string { return `${subject.category.id}:${subject.id}`; } @@ -65,7 +65,7 @@ export function channelPreferenceKey( } /** What a stored preference key switches. */ -export interface PreferenceTarget { +interface PreferenceTarget { subject: NotificationSubjectInfo; /** Unset for the in-app switch. */ channel?: NotificationChannelId; diff --git a/packages/interface-dms/docs/4.notifications/1.introduction.md b/packages/interface-dms/docs/4.notifications/1.introduction.md index b948088ca..5a5bf4082 100644 --- a/packages/interface-dms/docs/4.notifications/1.introduction.md +++ b/packages/interface-dms/docs/4.notifications/1.introduction.md @@ -21,6 +21,7 @@ The [Read notifications](/docs/auth-and-tenancy/authentication#read-notification - **Four dispatch targets.** You send to one user, to a list of users, to every user holding at least one of a set of roles, or to every user. - **Shared or individual read state.** A multi-recipient send can give each recipient their own read state. It can also group the copies, so that one recipient reading the notification marks it read for all of them. - **Preference-aware delivery.** The DMS skips a send without an error for a user who turned the subject off. `togglePermission` marks the subjects that users may not turn off. +- **Delivery channels.** A subject can offer e-mail next to the app, and a mail module registers the channel that sends it. See [Delivery channels](/docs/interfaces/notifications/delivery-channels). ## Dependencies diff --git a/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md b/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md index 4fe232825..c39c219d5 100644 --- a/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md +++ b/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md @@ -10,7 +10,7 @@ You declare categories and subjects by calling `NotificationCategory()` and `Not Declarations are function calls, not decorators. They run when the module that contains them is imported. Declare them at the top level of a module that is imported during startup, so the taxonomy is complete before the first notification is sent. -The [Notification preferences](/docs/auth-and-tenancy/authentication#notification-preferences) walkthrough shows the System category expanded to its subjects, and describes the locked General subject in prose. Its Email column is marked **Soon**. These switches control in-app delivery, not the transactional authentication emails. +The [Notification preferences](/docs/auth-and-tenancy/authentication#notification-preferences) walkthrough shows the System category expanded to its subjects, and describes the locked General subject in prose. The Email column holds a switch for each subject that offers e-mail once a module registers the e-mail channel, and is marked **Soon** otherwise (see [Delivery channels](/docs/interfaces/notifications/delivery-channels)). These switches control notifications, not the transactional authentication emails. ## Declaring a category @@ -88,6 +88,7 @@ export const stockSubject = NotificationSubject("stock", { | `descriptionKey` | `string` (optional) | Translation key for a longer description. | | `togglePermission` | [`TogglePermission`](#toggle-permissions) (optional) | Whether users may turn this subject off. The DMS reads it together with the category's value. | | `badgeKey` | `string` (optional) | Translation key of a badge that the settings screen shows next to the subject label, for example `Developer mode`. | +| `channels` | `NotificationChannelOffers` (optional) | The channels the subject also reaches its recipients through, `{ email: true }` or `{ email: { defaultOn: true } }`. In-app only when unset. See [Delivery channels](/docs/interfaces/notifications/delivery-channels). | A subject carries the whole category object, not only its id, so `subject.category.id` is always available from a subject you hold. A send uses it to build the preference key from the subject you passed to the builder. @@ -123,8 +124,8 @@ Every other combination leaves the subject toggleable. The value on a category a A locked subject behaves the same way everywhere: - The settings screen shows its switch disabled, with a hint. -- The preferences route refuses a change that turns it off, with HTTP 403. -- Every dispatch method delivers it whatever preference the user has stored for it. +- The preferences route refuses a change that turns it off, with HTTP 403, in the app or on a channel it offers. +- Every dispatch method delivers it whatever preference the user has stored for it, on every channel it offers. For a notification a user must always receive, declare `togglePermission: "forbidden"` on the subject **and** `togglePermission: "default"` on its category. `SystemCategory` declares `"default"`, which is what makes `GeneralSubject` mandatory. diff --git a/packages/interface-dms/docs/4.notifications/3.sending.md b/packages/interface-dms/docs/4.notifications/3.sending.md index b5fd8541b..f6189706e 100644 --- a/packages/interface-dms/docs/4.notifications/3.sending.md +++ b/packages/interface-dms/docs/4.notifications/3.sending.md @@ -164,7 +164,7 @@ Every dispatch method accepts an optional `SendOptions` object. | `readScope` | `ReadScope` (optional) | Read-state grouping for a multi-recipient send. Defaults to `"individual"`. See [Read scope](/docs/interfaces/notifications/categories-and-subjects#read-scope). | | `idempotencyKey` | `string` (optional) | Stable event key, unique across producers. Prefix it with your module ID. Reusing it for a recipient preserves the original notification and its dismissal state. | | `dedupe` | `boolean` (optional) | With `false`, the DMS stores every unkeyed send, even one identical to a notification the recipient got less than 10 seconds earlier. Defaults to `true`. See [Repeated sends](#repeated-sends). | -| `tenantId` | `string` (optional, `toRoles` only through `RoleSendOptions`) | Only the members of this tenant holding the roles. Every tenant when unset. | +| `tenantId` | `string` (optional) | The workspace the notification is about. [Delivery channels](/docs/interfaces/notifications/delivery-channels) receive it as `data.tenantId`. With `toRoles`, it also limits the recipients to the members of this tenant holding the roles; every tenant when unset. | Pick `"shared"` for an alert that only needs one person to act on it, and `"individual"` for anything each recipient has to see. @@ -212,6 +212,7 @@ Every dispatch method resolves to one delivery per user, so the DMS applies the - **Skipping is silent.** A skipped delivery is not an error. The promise resolves normally, and there is no per-recipient result to inspect. - **Each recipient gets a row.** Each recipient gets their own stored notification. With `readScope: "shared"`, the DMS ties those copies together for read state, and they stay separate rows. - **Stored notifications are pushed live.** The DMS also publishes each new delivery on the recipient's realtime stream, so the dashboard's badge and preview update without a reload. +- **Stored notifications reach the registered channels.** When a module registers a channel (e-mail) and the subject offers it, each new delivery is also handed to the channel for recipients who have it on. A repeat or a retry that stores nothing new reaches no channel. See [Delivery channels](/docs/interfaces/notifications/delivery-channels). A send can be skipped for reasons outside your control, so treat notifications as best-effort and do not make a workflow depend on one having been stored. To keep a failed send from breaking the operation that triggered it, wrap the call: @@ -250,7 +251,7 @@ The interface root exports `Notification()` and the data types. The `types` subp | `NotificationBuilder` | `@antelopejs/interface-dms/notifications/builder` | | `SendableNotification` | `@antelopejs/interface-dms/notifications/sendable` | -`NotificationData` is the shape the builder assembles. It holds `icon`, `title`, `description` and `subject`, plus the optional `linkTo`, `params` and `tone`. Name it when you carry notification content around before you build it: +`NotificationData` is the shape the builder assembles. It holds `icon`, `title`, `description` and `subject`, plus the optional `linkTo`, `params` and `tone`, and the `tenantId` a send names. Name it when you carry notification content around before you build it: ```typescript import { Notification } from "@antelopejs/interface-dms/notifications"; diff --git a/packages/interface-dms/docs/4.notifications/4.delivery-channels.md b/packages/interface-dms/docs/4.notifications/4.delivery-channels.md new file mode 100644 index 000000000..7d284b364 --- /dev/null +++ b/packages/interface-dms/docs/4.notifications/4.delivery-channels.md @@ -0,0 +1,80 @@ +--- +title: "Delivery channels" +description: "How a module delivers notifications by e-mail, and how a subject offers it." +mode: reference +--- + +Every notification lands in the recipient's in-app feed. A **delivery channel** also hands it to another medium. The DMS defines the `email` channel and ships no implementation for it. A mail module registers it, and every subject that offers e-mail then reaches the users who turn it on. + +Two parties take part: + +- **A subject offers the channel** with `channels: { email: ... }` on its declaration. A subject that names no channel stays in-app only. +- **A module registers the channel** with `NotificationChannel("email", { deliver })`. Without a registration, nothing is mailed and the settings screen shows the Email column marked **Soon**, as on an installation without a mail module. + +## Offering e-mail on a subject + +```typescript +import { + NotificationCategory, + NotificationSubject, +} from "@antelopejs/interface-dms/notifications"; + +const shopCategory = NotificationCategory("shop", { + labelKey: "shop.notifications.categories.shop", + icon: "i-ph-shopping-cart", +}); + +export const orderShippedSubject = NotificationSubject("order-shipped", { + category: shopCategory, + labelKey: "shop.notifications.subjects.order_shipped", + channels: { email: true }, +}); + +export const invoiceSubject = NotificationSubject("invoice", { + category: shopCategory, + labelKey: "shop.notifications.subjects.invoice", + channels: { email: { defaultOn: true } }, +}); +``` + +| Value of `channels.email` | Meaning | +| ------------------------- | ------- | +| omitted or `false` | The subject is not offered by e-mail. Its Email cell shows `—`. | +| `true` or `{ defaultOn: false }` | Offered, off until the user turns it on. | +| `{ defaultOn: true }` | Offered, on until the user turns it off. | + +## Registering the channel + +```typescript +import { NotificationChannel } from "@antelopejs/interface-dms/notifications"; + +NotificationChannel("email", { + deliver: (userId, data, context) => { + // Queue a mail for `userId` about `data` (its title, description, + // params, link and `tenantId`), keyed by `context.notificationId`. + }, +}); +``` + +`deliver(userId, data, context)` receives: + +| Argument | Description | +| -------- | ----------- | +| `userId` | The recipient. | +| `data` | The `NotificationData` sent, with `tenantId` when the send named a workspace (`SendOptions.tenantId`). | +| `context.notificationId` | Id of the in-app notification stored for this recipient. One id is mailed at most once. | +| `context.idempotencyKey` | The event key of a keyed send, when there is one. | + +One module registers a channel id. A later registration of the same id replaces the earlier one and logs a warning. The registration goes away with the module that made it. + +## When the DMS calls a channel + +For each recipient, after the in-app notification is handled: + +- **Only a new in-app notification is mailed.** The DMS calls `deliver` once the in-app row is stored and published. A send the recipient turned off in the app, a repeat inside the [10-second window](/docs/interfaces/notifications/sending#repeated-sends) and a retry of a keyed send (`toUsersIdempotently`) store no new row, so they mail nothing. E-mail is a copy of an in-app notification: a user who turns a subject off in the app receives no e-mail for it either, and the settings screen disables its Email switch. +- **The user preference decides.** The choice is stored under `categoryId:subjectId@email`, next to the in-app key in the same per-user map. A user who never chose gets the subject's `defaultOn`. +- **A locked subject is mailed whatever is stored.** A [locked subject](/docs/interfaces/notifications/categories-and-subjects#toggle-permissions) that offers e-mail reaches every recipient by e-mail, and the preferences route refuses turning its e-mail off with HTTP 403. +- **A failing channel never fails the send.** A `deliver` that throws or rejects is logged with `[DMS] Notification channel "email" failed to deliver`. The in-app notification stays, and the send resolves. +- **Sends wait for `deliver`.** Queue slow work, such as talking to a mail server, instead of doing it inside `deliver`. + +Preferences are per user and global: one choice per subject covers every workspace the user belongs to, for e-mail as for the app. `data.tenantId` tells the channel which workspace the notification is about, for example to pick its sender or branding. diff --git a/packages/interface-dms/docs/index.md b/packages/interface-dms/docs/index.md index 4520ded11..de1ee7a03 100644 --- a/packages/interface-dms/docs/index.md +++ b/packages/interface-dms/docs/index.md @@ -82,7 +82,7 @@ Each subpath is its own entry point, and importing one does not load the others. | `/base/table-view` | `TableView`, `@Column`, `TableViewRoutes`, guards, row actions | [Base](/docs/interfaces/base/tables) | | `/base/data-types` | `DataType`, the registration decorators, `DefaultDataTypes`, `DefaultDataCompareTypes`, `StatusType` | [Base](/docs/interfaces/base/data-types) | | `/base/…` | The per-component subpaths, such as `chart`, `grid`, `stack`, `tab`, `custom`, `layouts` and `helpers/…` | [Base](/docs/interfaces/base/introduction) | -| `/notifications`, `/notifications/types` | Categories, subjects, the notification builder and its dispatch targets | [Notifications](/docs/interfaces/notifications/introduction) | +| `/notifications`, `/notifications/types` | Categories, subjects, the notification builder, its dispatch targets and delivery channels | [Notifications](/docs/interfaces/notifications/introduction) | | `/html-render` | `RegisterHtmlTemplate`, `GenerateHtml` and the template reference types | [HTML Render](/docs/interfaces/html-render/introduction) | Beyond these entry points, built files are importable through the `./*` export (`@antelopejs/interface-dms/base/form-types`). Moving or renaming a public path is a breaking change, like removing an export. From e5a4027abb006005e6dd0cad2ff0f59eb91c0fed Mon Sep 17 00:00:00 2001 From: Antony Rizzitelli Date: Fri, 20 Nov 2026 14:48:39 +0000 Subject: [PATCH 3/5] refactor(dms): collapse notification channels to an e-mail option A subject now offers e-mail with email?: boolean | { defaultOn?: boolean } and a mail module registers it with NotificationEmailChannel({ deliver }). The one-member channel id union, the generic @ key parsing and the frontend's copy of the channel id type are gone; the frontend reads every switch default through one function. --- .../docs/02.building/06.backend-services.md | 2 +- .../03.auth-and-tenancy/01.authentication.md | 2 +- .../NotificationMatrixSubject.vue | 4 +- .../NotificationPreferencesForm.vue | 2 - .../notification/useNotificationCatalog.ts | 38 +++--- .../useNotificationPreferences.ts | 35 +++--- .../notification-preferences-email.test.ts | 19 ++- .../dms-notifications/index.ts | 60 +++++----- .../src/pages/settings/users/notifications.ts | 48 ++++---- ...els.test.ts => notification-email.test.ts} | 37 +++--- .../dms/src/utils/notification-channels.ts | 110 ------------------ packages/dms/src/utils/notification-email.ts | 75 ++++++++++++ .../src/utils/notification-registry/index.ts | 2 +- .../docs/4.notifications/1.introduction.md | 2 +- .../2.categories-and-subjects.md | 8 +- .../docs/4.notifications/3.sending.md | 4 +- .../{4.delivery-channels.md => 4.email.md} | 24 ++-- packages/interface-dms/docs/index.md | 2 +- .../interface-dms/src/notifications/index.ts | 23 ++-- .../src/notifications/internal.ts | 6 +- .../interface-dms/src/notifications/types.ts | 35 ++---- 21 files changed, 232 insertions(+), 306 deletions(-) rename packages/dms/src/test/integration/{notification-channels.test.ts => notification-email.test.ts} (89%) delete mode 100644 packages/dms/src/utils/notification-channels.ts create mode 100644 packages/dms/src/utils/notification-email.ts rename packages/interface-dms/docs/4.notifications/{4.delivery-channels.md => 4.email.md} (71%) diff --git a/packages/dms/docs/02.building/06.backend-services.md b/packages/dms/docs/02.building/06.backend-services.md index 1dc8bf273..672fe9fc2 100644 --- a/packages/dms/docs/02.building/06.backend-services.md +++ b/packages/dms/docs/02.building/06.backend-services.md @@ -94,7 +94,7 @@ await n.broadcast(); // optional arg: { tenantId, readScope, idempotencyKey, ded Notifications are organized by **category**, then **subject**. Users toggle the subjects they receive from their notification settings, and a send to a user who disabled the subject is skipped without an error. The built-in subjects are `GeneralSubject`, `SecuritySubject`, `AccountSubject`, `CollaborationSubject` and `AutomationSubject`, under `SystemCategory`. -Register your own with the public `NotificationCategory(id, opts)` and `NotificationSubject(id, opts)` functions, then pass your subject to `.subject(...)`. A category or subject can set `togglePermission: "forbidden"` so users cannot turn it off. `GeneralSubject` does. A subject can also offer e-mail (`channels: { email: true }`), which a mail module delivers once it registers the channel with `NotificationChannel("email", { deliver })` ([Delivery channels](/docs/interfaces/notifications/delivery-channels)). +Register your own with the public `NotificationCategory(id, opts)` and `NotificationSubject(id, opts)` functions, then pass your subject to `.subject(...)`. A category or subject can set `togglePermission: "forbidden"` so users cannot turn it off. `GeneralSubject` does. A subject can also offer e-mail (`email: true`), which a mail module delivers once it registers the channel with `NotificationEmailChannel({ deliver })` ([E-mail](/docs/interfaces/notifications/email)). Three delivery details: diff --git a/packages/dms/docs/03.auth-and-tenancy/01.authentication.md b/packages/dms/docs/03.auth-and-tenancy/01.authentication.md index d1d596b6d..68465e4af 100644 --- a/packages/dms/docs/03.auth-and-tenancy/01.authentication.md +++ b/packages/dms/docs/03.auth-and-tenancy/01.authentication.md @@ -157,7 +157,7 @@ Go to **Settings → Notifications** and expand a category to see its subjects. ![Notification preferences in the Helio demo, with the System category expanded to its subjects](../images/captures/notification-preferences.webp) -Without a mail module, the Email column is marked **Soon** and holds no switch. Once a module registers the e-mail channel, each subject that offers e-mail gets an Email switch, saved on its own like the in-app one; it is disabled while the subject is off in the app, since e-mail is a copy of the in-app notification ([Delivery channels](/docs/interfaces/notifications/delivery-channels)). Turning a subject off stops new notifications of that subject, and the messages already in the inbox stay. +Without a mail module, the Email column is marked **Soon** and holds no switch. Once a module registers the e-mail channel, each subject that offers e-mail gets an Email switch, saved on its own like the in-app one; it is disabled while the subject is off in the app, since e-mail is a copy of the in-app notification ([E-mail](/docs/interfaces/notifications/email)). Turning a subject off stops new notifications of that subject, and the messages already in the inbox stay. ```text Category → subject → recipient diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue b/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue index fd3a15148..806501933 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue @@ -10,8 +10,6 @@ interface NotificationMatrixSubjectProps { subject: NotificationSubject; enabled: boolean; state: SaveStatusState; - /** The e-mail column holds a switch for this subject. */ - offersEmail?: boolean; emailEnabled?: boolean; } @@ -87,7 +85,7 @@ const onToggleEmail = (value: boolean) => { @update:model-value="onToggle" /> -
+
{ :subject="subject" :enabled="isEnabled(subject)" :state="rowState(subject)" - :offers-email="offersEmail(subject)" :email-enabled="isEmailEnabled(subject)" @toggle="(enabled) => toggleSubject(subject, enabled)" @toggle-email="(enabled) => toggleEmail(subject, enabled)" diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts index 3a82c368a..7ab5be678 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationCatalog.ts @@ -11,15 +11,6 @@ export interface NotificationCategory { tagKey?: string; } -/** The delivery channels a subject can offer next to the in-app feed. */ -export type NotificationChannelId = "email"; - -/** How a subject offers a channel, as the server reads it. */ -export interface NotificationChannelOffer { - /** The channel is on for a user who never chose. */ - defaultOn: boolean; -} - export interface NotificationSubject { id: string; category: NotificationCategory; @@ -29,15 +20,18 @@ export interface NotificationSubject { badgeKey?: string; /** Set by the server: the user may not turn the subject off. */ locked?: boolean; - /** Set by the server: the registered channels the subject offers. */ - channels?: Partial>; + /** Set by the server when the subject has an e-mail switch: it offers e-mail and a module delivers it. */ + email?: { + /** E-mail is on for a user who never chose. */ + defaultOn: boolean; + }; } interface NotificationCatalogResponse { categories: NotificationCategory[]; subjects: NotificationSubject[]; - /** The channels a module registered; none on an installation without one. */ - channels?: NotificationChannelId[]; + /** A module registered the e-mail channel. */ + emailChannel?: boolean; } export const buildPreferenceKey = (categoryId: string, subjectId: string) => @@ -46,11 +40,9 @@ export const buildPreferenceKey = (categoryId: string, subjectId: string) => export const subjectPreferenceKey = (subject: NotificationSubject) => buildPreferenceKey(subject.category.id, subject.id); -/** The key the subject's switch for `channel` is stored under. */ -export const channelPreferenceKey = ( - subject: NotificationSubject, - channel: NotificationChannelId, -) => `${subjectPreferenceKey(subject)}@${channel}`; +/** The key the subject's e-mail switch is stored under. */ +export const emailPreferenceKey = (subject: NotificationSubject) => + `${subjectPreferenceKey(subject)}@email`; const CATALOG_URL = pageRoutePath( "/settings/user/notifications", @@ -74,10 +66,10 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => { ); const categories = computed(() => catalog.data.value?.categories ?? []); const subjects = computed(() => catalog.data.value?.subjects ?? []); - const channels = computed(() => catalog.data.value?.channels ?? []); - /** A module registered `channel`: its column holds switches. */ - const hasChannel = (channel: NotificationChannelId) => - channels.value.includes(channel); + /** A module registered the e-mail channel: its column holds switches. */ + const hasEmailChannel = computed( + () => catalog.data.value?.emailChannel === true, + ); const isLoaded = computed(() => !!catalog.data.value); const loadFailed = computed(() => !isLoaded.value && hasFailed(catalog)); @@ -99,7 +91,7 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => { return { categories, subjects, - hasChannel, + hasEmailChannel, isLoaded, loadFailed, loadCatalog, diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts index ac32f0679..5b2371e63 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts @@ -3,7 +3,7 @@ import type { SaveStatusState } from "#dms-ui/app/components/save-bar/SaveStatus import { useInstantSave } from "#dms-ui/app/entries/composables/instant-save/useInstantSave"; import { combineSaveStates } from "#dms-ui/app/composables/layout/useInstantSaveHeader"; import { - channelPreferenceKey, + emailPreferenceKey, hasFailed, type NotificationCategory, type NotificationSubject, @@ -57,20 +57,19 @@ export const useNotificationPreferences = ( const emailDefaults = computed(() => Object.fromEntries( catalog.subjects.value.flatMap((subject) => - subject.channels?.email - ? [ - [ - channelPreferenceKey(subject, "email"), - subject.channels.email.defaultOn, - ], - ] + subject.email + ? [[emailPreferenceKey(subject), subject.email.defaultOn]] : [], ), ), ); + /** What a switch reads: the stored choice, else its default. */ + const read = (key: string) => + preferences.value[key] ?? emailDefaults.value[key] ?? true; + const instant = useInstantSave({ - read: (key) => preferences.value[key] ?? emailDefaults.value[key] ?? true, + read, write: (key, enabled) => { preferences.value = { ...preferences.value, [key]: enabled }; }, @@ -79,24 +78,17 @@ export const useNotificationPreferences = ( }); const isEnabled = (subject: NotificationSubject) => - preferences.value[subjectPreferenceKey(subject)] ?? true; - - /** The subject has an e-mail switch: a module delivers e-mail and the subject offers it. */ - const offersEmail = (subject: NotificationSubject) => - catalog.hasChannel("email") && !!subject.channels?.email; + read(subjectPreferenceKey(subject)); /** A locked subject is mailed whatever is stored, as the server sends it. */ const isEmailEnabled = (subject: NotificationSubject) => - subject.locked === true || - (preferences.value[channelPreferenceKey(subject, "email")] ?? - subject.channels?.email?.defaultOn ?? - false); + subject.locked === true || read(emailPreferenceKey(subject)); /** The row's state cell sums up its in-app and e-mail switches. */ const rowState = (subject: NotificationSubject): SaveStatusState => combineSaveStates([ instant.states[subjectPreferenceKey(subject)], - instant.states[channelPreferenceKey(subject, "email")], + instant.states[emailPreferenceKey(subject)], ]); const toggleableSubjectsOf = (category: NotificationCategory) => @@ -106,7 +98,7 @@ export const useNotificationPreferences = ( instant.change(subjectPreferenceKey(subject), enabled); const toggleEmail = (subject: NotificationSubject, enabled: boolean) => - instant.change(channelPreferenceKey(subject, "email"), enabled); + instant.change(emailPreferenceKey(subject), enabled); const toggleCategory = (category: NotificationCategory, enabled: boolean) => instant.changeMany( @@ -131,8 +123,7 @@ export const useNotificationPreferences = ( return { categories: catalog.categories, subjectsOf: catalog.subjectsOf, - hasEmailChannel: computed(() => catalog.hasChannel("email")), - offersEmail, + hasEmailChannel: catalog.hasEmailChannel, isEmailEnabled, toggleEmail, preferences, diff --git a/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts index 75d91df97..680709059 100644 --- a/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts +++ b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts @@ -21,27 +21,26 @@ import { installAuthSettingsRuntime } from "./helpers/auth-settings-runtime"; const PREFERENCES_URL = "/dms/pages/settings/user/notifications/preferences"; const category = { id: "work", labelKey: "Work", icon: "i-ph-briefcase" }; -function catalog(channels: string[], stored: Record = {}) { - const offered = channels.length > 0; +function catalog(emailChannel: boolean, stored: Record = {}) { return vi.fn(async (url: string): Promise => { if (url.endsWith("/categories")) { return { categories: [category], - channels, + emailChannel, subjects: [ { id: "assigned", category, labelKey: "Assigned", - channels: offered ? { email: { defaultOn: false } } : {}, + email: emailChannel ? { defaultOn: false } : undefined, }, { id: "digest", category, labelKey: "Digest", - channels: offered ? { email: { defaultOn: true } } : {}, + email: emailChannel ? { defaultOn: true } : undefined, }, - { id: "mentions", category, labelKey: "Mentions", channels: {} }, + { id: "mentions", category, labelKey: "Mentions" }, ], }; } @@ -139,7 +138,7 @@ afterEach(() => { describe("notification preferences e-mail column", () => { it("keeps the Soon column without a registered channel (fails when an installation without a mail module draws e-mail switches)", async () => { - const container = await mount(catalog([])); + const container = await mount(catalog(false)); expect(emailSwitchOf(container, "Assigned")).toBeNull(); expect(container.querySelector("[data-badge]")?.textContent).toBe( @@ -151,7 +150,7 @@ describe("notification preferences e-mail column", () => { }); it("draws a switch for each subject offering e-mail, on its default (fails when the default of the offer is ignored)", async () => { - const container = await mount(catalog(["email"])); + const container = await mount(catalog(true)); expect( emailSwitchOf(container, "Assigned")?.getAttribute("aria-checked"), @@ -167,7 +166,7 @@ describe("notification preferences e-mail column", () => { }); it("saves the e-mail switch under its own key (fails when it changes the in-app preference)", async () => { - const authFetch = catalog(["email"]); + const authFetch = catalog(true); const container = await mount(authFetch); emailSwitchOf(container, "Assigned")?.click(); @@ -181,7 +180,7 @@ describe("notification preferences e-mail column", () => { }); it("disables the e-mail switch of a subject off in the app (fails when e-mail looks on for a notification never sent)", async () => { - const container = await mount(catalog(["email"], { "work:digest": false })); + const container = await mount(catalog(true, { "work:digest": false })); expect(emailSwitchOf(container, "Digest")?.disabled).toBe(true); expect(emailSwitchOf(container, "Assigned")?.disabled).toBe(false); diff --git a/packages/dms/src/implementations/dms-notifications/index.ts b/packages/dms/src/implementations/dms-notifications/index.ts index 827d784ae..46f1bd1f4 100644 --- a/packages/dms/src/implementations/dms-notifications/index.ts +++ b/packages/dms/src/implementations/dms-notifications/index.ts @@ -7,7 +7,7 @@ import { UserModel } from "@antelopejs/interface-dms/auth/db"; import type { DeliveryOptions, NotificationCategoryInfo, - NotificationChannelInfo, + NotificationEmailChannelInfo, NotificationData, NotificationSubjectInfo, ReadScope, @@ -25,8 +25,8 @@ import { getRealtimeBroker, buildUserNotificationTopic } from "../../realtime"; import { runInBatches } from "../../utils/run-in-batches/index"; import { categoryRegistry, - channelRegistry, - isChannelOn, + emailChannelSlot, + isEmailOn, isSubjectLocked, subjectRegistry, } from "../../utils/notification-registry/index"; @@ -171,38 +171,34 @@ async function store( } /** - * Hands a stored notification to every registered channel the recipient has - * on for its subject. A channel that throws is logged; the others still run + * Hands a stored notification to the registered e-mail channel when the + * recipient has e-mail on for its subject. A channel that throws is logged * and the in-app delivery stands. */ -async function deliverToChannels( +async function deliverByEmail( userId: string, data: NotificationData, notification: UserNotification, preferences: () => Promise>, idempotencyKey?: string, ): Promise { + const channel = emailChannelSlot.channel; const subject = subjectRegistry.get( `${data.subject.category.id}:${data.subject.id}`, ); - const channels = [...channelRegistry.values()].filter( - (channel) => subject?.channels?.[channel.id], - ); - if (!subject || channels.length === 0) return; - const stored = await preferences(); - for (const channel of channels) { - if (!isChannelOn(subject, channel.id, stored)) continue; - try { - await channel.deliver(userId, data, { - notificationId: notification._id, - idempotencyKey, - }); - } catch (error) { - Logging.Error( - `[DMS] Notification channel "${channel.id}" failed to deliver "${data.title}" to "${userId}"`, - error, - ); - } + if (!channel || !subject || !isEmailOn(subject, await preferences())) { + return; + } + try { + await channel.deliver(userId, data, { + notificationId: notification._id, + idempotencyKey, + }); + } catch (error) { + Logging.Error( + `[DMS] Notification e-mail channel failed to deliver "${data.title}" to "${userId}"`, + error, + ); } } @@ -232,17 +228,17 @@ export namespace internal { }, }; - export const RegisterNotificationChannel = { - register: (info: NotificationChannelInfo) => { - if (channelRegistry.has(info.id)) { + export const RegisterNotificationEmailChannel = { + register: (channel: NotificationEmailChannelInfo) => { + if (emailChannelSlot.channel) { Logging.Warn( - `[DMS] Notification channel "${info.id}" registered again: the latest registration replaces the previous one`, + "[DMS] Notification e-mail channel registered again: the latest registration replaces the previous one", ); } - channelRegistry.set(info.id, info); + emailChannelSlot.channel = channel; }, - unregister: (info: NotificationChannelInfo) => { - channelRegistry.delete(info.id); + unregister: () => { + emailChannelSlot.channel = undefined; }, }; @@ -314,7 +310,7 @@ export namespace internal { await publishNotificationEvent(userId, NOTIFICATION_NEW_EVENT, { notification: created, }); - await deliverToChannels(userId, data, created, preferences, idempotencyKey); + await deliverByEmail(userId, data, created, preferences, idempotencyKey); } export async function SendToUsers( diff --git a/packages/dms/src/pages/settings/users/notifications.ts b/packages/dms/src/pages/settings/users/notifications.ts index 92a3c5c64..eb20c87ea 100644 --- a/packages/dms/src/pages/settings/users/notifications.ts +++ b/packages/dms/src/pages/settings/users/notifications.ts @@ -31,10 +31,7 @@ import { TABLE_DISPLAY_ID, TableView, } from "@antelopejs/interface-dms/base/table-view"; -import type { - NotificationChannelId, - NotificationSubjectInfo, -} from "@antelopejs/interface-dms/notifications/types"; +import type { NotificationSubjectInfo } from "@antelopejs/interface-dms/notifications/types"; import { type UserNotificationCounts, UserNotificationPreferencesModel, @@ -48,13 +45,13 @@ import { parseNotificationFeedQuery, } from "../../../db/models"; import { - type ChannelOffer, - findPreferenceTarget, + type EmailOffer, + emailChannelSlot, + emailOffer, + findPreferenceSubject, getRegisteredCategories, - getRegisteredChannelIds, getRegisteredSubjects, isSubjectLocked, - registeredChannelOffers, publishAllNotificationsRead, publishNotificationsRead, publishNotificationsUnread, @@ -70,11 +67,14 @@ const HTTP_FORBIDDEN = 403; const HTTP_NOT_FOUND = 404; /** A registered subject as the settings screen lists it. */ -export interface NotificationSubjectView extends NotificationSubjectInfo { - /** The user may not turn this subject off, on any channel. */ +export interface NotificationSubjectView extends Omit< + NotificationSubjectInfo, + "email" +> { + /** The user may not turn this subject off, in the app or by e-mail. */ locked: boolean; - /** The registered channels the subject offers. */ - channels: Partial>; + /** Set when the subject offers e-mail and a module registered the channel. */ + email?: EmailOffer; } function toSubjectView( @@ -83,7 +83,7 @@ function toSubjectView( return { ...subject, locked: isSubjectLocked(subject), - channels: registeredChannelOffers(subject), + email: emailOffer(subject), }; } @@ -221,21 +221,21 @@ function readFeedFilter(context: RequestContext): NotificationFeedFilter { } /** - * Refuses keys that name no registered subject, or a channel the subject does - * not offer or no module registered, and turning a locked subject off. + * Refuses keys that name no registered subject, or an e-mail switch the + * subject does not offer, and turning a locked subject off. */ function assertChangesAllowed(changes: Record): void { for (const key of Object.keys(changes)) { assert( - findPreferenceTarget(key), + findPreferenceSubject(key), HTTP_BAD_REQUEST, "error.request_refused", ); } for (const [key, enabled] of Object.entries(changes)) { - const target = findPreferenceTarget(key); + const subject = findPreferenceSubject(key); assert( - enabled || !target || !isSubjectLocked(target.subject), + enabled || !subject || !isSubjectLocked(subject), HTTP_FORBIDDEN, "error.forbidden", ); @@ -312,15 +312,19 @@ export class NotificationsApiController extends Controller(NOTIFICATIONS_API) { } /** - * The registered categories and subjects, and the ids of the registered - * delivery channels (`channels`): the screen draws a channel's column - * only when a module registered it. + * The registered categories and subjects, and whether a module registered + * the e-mail channel (`emailChannel`): the screen draws e-mail switches + * only then. */ @Get("/categories") async getCategories() { const categories = getRegisteredCategories(); const subjects = getRegisteredSubjects().map(toSubjectView); - return { categories, subjects, channels: getRegisteredChannelIds() }; + return { + categories, + subjects, + emailChannel: emailChannelSlot.channel !== undefined, + }; } /** diff --git a/packages/dms/src/test/integration/notification-channels.test.ts b/packages/dms/src/test/integration/notification-email.test.ts similarity index 89% rename from packages/dms/src/test/integration/notification-channels.test.ts rename to packages/dms/src/test/integration/notification-email.test.ts index 8274d2515..447bd0eea 100644 --- a/packages/dms/src/test/integration/notification-channels.test.ts +++ b/packages/dms/src/test/integration/notification-email.test.ts @@ -3,9 +3,9 @@ import { expect } from "chai"; import { SendableNotification } from "@antelopejs/interface-dms/notifications/sendable"; import type { NotificationCategoryInfo, - NotificationChannelInfo, NotificationData, NotificationDeliveryContext, + NotificationEmailChannelInfo, NotificationSubjectInfo, } from "@antelopejs/interface-dms/notifications/types"; import { pageRoutePath } from "@antelopejs/interface-dms/page"; @@ -31,13 +31,13 @@ const optIn: NotificationSubjectInfo = { id: "opt-in", labelKey: "opt-in", category, - channels: { email: true }, + email: true, }; const optOut: NotificationSubjectInfo = { id: "opt-out", labelKey: "opt-out", category, - channels: { email: { defaultOn: true } }, + email: { defaultOn: true }, }; const inAppOnly: NotificationSubjectInfo = { id: "in-app-only", @@ -49,7 +49,7 @@ const locked: NotificationSubjectInfo = { labelKey: "locked", category, togglePermission: "forbidden", - channels: { email: true }, + email: true, }; const SUBJECTS = [optIn, optOut, inAppOnly, locked]; const emailKey = (subject: NotificationSubjectInfo) => @@ -65,13 +65,12 @@ interface Delivery { interface CatalogSubject { id: string; - channels: Record; + email?: { defaultOn: boolean }; } let deliveries: Delivery[] = []; let failing = false; -const channel: NotificationChannelInfo = { - id: "email", +const channel: NotificationEmailChannelInfo = { deliver: (userId, data, context) => { if (failing) throw new Error("mail server down"); deliveries.push({ userId, data, context }); @@ -132,18 +131,18 @@ function useChannelTestUser(): ChannelTestUser { } interface Catalog { - channels: string[]; + emailChannel: boolean; subjects: CatalogSubject[]; } -describe("[integration] notification channels, none registered", () => { +describe("[integration] notification e-mail, no channel registered", () => { const user = useChannelTestUser(); it("lists no channel and no offer (fails when the screen would draw an e-mail switch no module delivers)", async () => { const catalog = await user.client().get(CATEGORIES); const subject = catalog.data.subjects.find((s) => s.id === optIn.id); - expect(catalog.data.channels).to.deep.equal([]); - expect(subject?.channels).to.deep.equal({}); + expect(catalog.data.emailChannel).to.equal(false); + expect(subject?.email).to.equal(undefined); }); it("refuses an e-mail preference (fails when a key for an unregistered channel is stored)", async () => { @@ -154,17 +153,17 @@ describe("[integration] notification channels, none registered", () => { }); }); -describe("[integration] notification channels, one registered", () => { +describe("[integration] notification e-mail, channel registered", () => { const user = useChannelTestUser(); const patch = (changes: Record) => user.client().patch>(PREFERENCES, changes); before(() => { - internal.RegisterNotificationChannel.register(channel); + internal.RegisterNotificationEmailChannel.register(channel); }); after(() => { - internal.RegisterNotificationChannel.unregister(channel); + internal.RegisterNotificationEmailChannel.unregister(); }); beforeEach(() => { @@ -175,12 +174,12 @@ describe("[integration] notification channels, one registered", () => { it("lists the channel and each subject's offer with its default (fails when the defaults are not read from the subject)", async () => { const catalog = await user.client().get(CATEGORIES); const offers = Object.fromEntries( - catalog.data.subjects.map((s) => [s.id, s.channels]), + catalog.data.subjects.map((s) => [s.id, s.email]), ); - expect(catalog.data.channels).to.deep.equal(["email"]); - expect(offers[optIn.id]).to.deep.equal({ email: { defaultOn: false } }); - expect(offers[optOut.id]).to.deep.equal({ email: { defaultOn: true } }); - expect(offers[inAppOnly.id]).to.deep.equal({}); + expect(catalog.data.emailChannel).to.equal(true); + expect(offers[optIn.id]).to.deep.equal({ defaultOn: false }); + expect(offers[optOut.id]).to.deep.equal({ defaultOn: true }); + expect(offers[inAppOnly.id]).to.equal(undefined); }); it("does not mail a subject offered off until the user turns it on, then mails it with its tenant (fails when the default is on or the tenant is lost)", async () => { diff --git a/packages/dms/src/utils/notification-channels.ts b/packages/dms/src/utils/notification-channels.ts deleted file mode 100644 index 88c9765f2..000000000 --- a/packages/dms/src/utils/notification-channels.ts +++ /dev/null @@ -1,110 +0,0 @@ -import type { - NotificationChannelId, - NotificationChannelInfo, - NotificationSubjectInfo, -} from "@antelopejs/interface-dms/notifications/types"; -import { - findSubjectByPreferenceKey, - isSubjectLocked, -} from "./notification-registry"; -import { ownValue } from "./own-value"; - -export const channelRegistry = new Map< - NotificationChannelId, - NotificationChannelInfo ->(); - -/** The ids of the channels a module has registered. */ -export function getRegisteredChannelIds(): NotificationChannelId[] { - return Array.from(channelRegistry.keys()); -} - -/** How a subject offers a channel once its shorthand is read. */ -export interface ChannelOffer { - /** The channel is on for a user who never chose. */ - defaultOn: boolean; -} - -/** The subject's offer of `channel`, or undefined when it does not offer it. */ -export function channelOffer( - subject: NotificationSubjectInfo, - channel: NotificationChannelId, -): ChannelOffer | undefined { - const offer = subject.channels?.[channel]; - if (offer === undefined || offer === false) return undefined; - return { defaultOn: offer !== true && offer.defaultOn === true }; -} - -/** The registered channels the subject offers, read. */ -export function registeredChannelOffers( - subject: NotificationSubjectInfo, -): Partial> { - const offers: Partial> = {}; - for (const channel of getRegisteredChannelIds()) { - const offer = channelOffer(subject, channel); - if (offer) offers[channel] = offer; - } - return offers; -} - -function subjectPreferenceKey(subject: NotificationSubjectInfo): string { - return `${subject.category.id}:${subject.id}`; -} - -const CHANNEL_KEY_SEPARATOR = "@"; - -/** - * The key a user's choice for `channel` on a subject is stored under, next - * to the subject's in-app key in the same preference map. - */ -export function channelPreferenceKey( - subject: NotificationSubjectInfo, - channel: NotificationChannelId, -): string { - return `${subjectPreferenceKey(subject)}${CHANNEL_KEY_SEPARATOR}${channel}`; -} - -/** What a stored preference key switches. */ -interface PreferenceTarget { - subject: NotificationSubjectInfo; - /** Unset for the in-app switch. */ - channel?: NotificationChannelId; -} - -/** - * The subject and channel a preference key names, or undefined when it names - * no registered subject, or a channel the subject does not offer or no module - * has registered. - */ -export function findPreferenceTarget( - key: string, -): PreferenceTarget | undefined { - const inApp = findSubjectByPreferenceKey(key); - if (inApp) return { subject: inApp }; - const separator = key.lastIndexOf(CHANNEL_KEY_SEPARATOR); - if (separator < 0) return undefined; - const subject = findSubjectByPreferenceKey(key.slice(0, separator)); - const channelId = key.slice(separator + 1); - const channel = getRegisteredChannelIds().find((id) => id === channelId); - if (!subject || !channel || !channelOffer(subject, channel)) return undefined; - return { subject, channel }; -} - -/** - * Whether a user with these stored preferences receives the subject through - * `channel`. A locked subject reaches its recipients on every channel it - * offers, whatever they stored. - */ -export function isChannelOn( - subject: NotificationSubjectInfo, - channel: NotificationChannelId, - preferences: Record, -): boolean { - const offer = channelOffer(subject, channel); - if (!offer) return false; - if (isSubjectLocked(subject)) return true; - return ( - ownValue(preferences, channelPreferenceKey(subject, channel)) ?? - offer.defaultOn - ); -} diff --git a/packages/dms/src/utils/notification-email.ts b/packages/dms/src/utils/notification-email.ts new file mode 100644 index 000000000..f0122dfdb --- /dev/null +++ b/packages/dms/src/utils/notification-email.ts @@ -0,0 +1,75 @@ +import type { + NotificationEmailChannelInfo, + NotificationSubjectInfo, +} from "@antelopejs/interface-dms/notifications/types"; +import { + findSubjectByPreferenceKey, + isSubjectLocked, +} from "./notification-registry"; +import { ownValue } from "./own-value"; + +interface EmailChannelSlot { + /** The e-mail channel a module registered, if any. */ + channel?: NotificationEmailChannelInfo; +} + +export const emailChannelSlot: EmailChannelSlot = {}; + +/** How a subject offers e-mail once its shorthand is read. */ +export interface EmailOffer { + /** E-mail is on for a user who never chose. */ + defaultOn: boolean; +} + +/** + * The subject's e-mail offer, or undefined when the subject does not offer + * e-mail or no module registered the e-mail channel. + */ +export function emailOffer( + subject: NotificationSubjectInfo, +): EmailOffer | undefined { + if (!emailChannelSlot.channel || !subject.email) return undefined; + return { + defaultOn: subject.email !== true && subject.email.defaultOn === true, + }; +} + +const EMAIL_KEY_SUFFIX = "@email"; + +/** + * The key a user's e-mail choice for a subject is stored under, next to the + * subject's in-app key in the same preference map. + */ +export function emailPreferenceKey(subject: NotificationSubjectInfo): string { + return `${subject.category.id}:${subject.id}${EMAIL_KEY_SUFFIX}`; +} + +/** + * The subject a preference key switches, in the app or by e-mail, or + * undefined when it names no registered subject or an e-mail switch the + * subject does not offer. + */ +export function findPreferenceSubject( + key: string, +): NotificationSubjectInfo | undefined { + const inApp = findSubjectByPreferenceKey(key); + if (inApp || !key.endsWith(EMAIL_KEY_SUFFIX)) return inApp; + const subject = findSubjectByPreferenceKey( + key.slice(0, -EMAIL_KEY_SUFFIX.length), + ); + return subject && emailOffer(subject) ? subject : undefined; +} + +/** + * Whether a user with these stored preferences receives the subject by + * e-mail. A locked subject that offers e-mail is mailed whatever they stored. + */ +export function isEmailOn( + subject: NotificationSubjectInfo, + preferences: Record, +): boolean { + const offer = emailOffer(subject); + if (!offer) return false; + if (isSubjectLocked(subject)) return true; + return ownValue(preferences, emailPreferenceKey(subject)) ?? offer.defaultOn; +} diff --git a/packages/dms/src/utils/notification-registry/index.ts b/packages/dms/src/utils/notification-registry/index.ts index 3a6eda18b..3bae667a6 100644 --- a/packages/dms/src/utils/notification-registry/index.ts +++ b/packages/dms/src/utils/notification-registry/index.ts @@ -1,2 +1,2 @@ export * from "../notification-registry"; -export * from "../notification-channels"; +export * from "../notification-email"; diff --git a/packages/interface-dms/docs/4.notifications/1.introduction.md b/packages/interface-dms/docs/4.notifications/1.introduction.md index 5a5bf4082..fac08af94 100644 --- a/packages/interface-dms/docs/4.notifications/1.introduction.md +++ b/packages/interface-dms/docs/4.notifications/1.introduction.md @@ -21,7 +21,7 @@ The [Read notifications](/docs/auth-and-tenancy/authentication#read-notification - **Four dispatch targets.** You send to one user, to a list of users, to every user holding at least one of a set of roles, or to every user. - **Shared or individual read state.** A multi-recipient send can give each recipient their own read state. It can also group the copies, so that one recipient reading the notification marks it read for all of them. - **Preference-aware delivery.** The DMS skips a send without an error for a user who turned the subject off. `togglePermission` marks the subjects that users may not turn off. -- **Delivery channels.** A subject can offer e-mail next to the app, and a mail module registers the channel that sends it. See [Delivery channels](/docs/interfaces/notifications/delivery-channels). +- **E-mail.** A subject can offer e-mail next to the app, and a mail module registers the channel that sends it. See [E-mail](/docs/interfaces/notifications/email). ## Dependencies diff --git a/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md b/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md index c39c219d5..9c42c40d8 100644 --- a/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md +++ b/packages/interface-dms/docs/4.notifications/2.categories-and-subjects.md @@ -10,7 +10,7 @@ You declare categories and subjects by calling `NotificationCategory()` and `Not Declarations are function calls, not decorators. They run when the module that contains them is imported. Declare them at the top level of a module that is imported during startup, so the taxonomy is complete before the first notification is sent. -The [Notification preferences](/docs/auth-and-tenancy/authentication#notification-preferences) walkthrough shows the System category expanded to its subjects, and describes the locked General subject in prose. The Email column holds a switch for each subject that offers e-mail once a module registers the e-mail channel, and is marked **Soon** otherwise (see [Delivery channels](/docs/interfaces/notifications/delivery-channels)). These switches control notifications, not the transactional authentication emails. +The [Notification preferences](/docs/auth-and-tenancy/authentication#notification-preferences) walkthrough shows the System category expanded to its subjects, and describes the locked General subject in prose. The Email column holds a switch for each subject that offers e-mail once a module registers the e-mail channel, and is marked **Soon** otherwise (see [E-mail](/docs/interfaces/notifications/email)). These switches control notifications, not the transactional authentication emails. ## Declaring a category @@ -88,7 +88,7 @@ export const stockSubject = NotificationSubject("stock", { | `descriptionKey` | `string` (optional) | Translation key for a longer description. | | `togglePermission` | [`TogglePermission`](#toggle-permissions) (optional) | Whether users may turn this subject off. The DMS reads it together with the category's value. | | `badgeKey` | `string` (optional) | Translation key of a badge that the settings screen shows next to the subject label, for example `Developer mode`. | -| `channels` | `NotificationChannelOffers` (optional) | The channels the subject also reaches its recipients through, `{ email: true }` or `{ email: { defaultOn: true } }`. In-app only when unset. See [Delivery channels](/docs/interfaces/notifications/delivery-channels). | +| `email` | `boolean \| { defaultOn?: boolean }` (optional) | Whether the subject also reaches its recipients by e-mail: `true` (off until the user turns it on) or `{ defaultOn: true }` (on until the user turns it off). In-app only when unset. See [E-mail](/docs/interfaces/notifications/email). | A subject carries the whole category object, not only its id, so `subject.category.id` is always available from a subject you hold. A send uses it to build the preference key from the subject you passed to the builder. @@ -124,8 +124,8 @@ Every other combination leaves the subject toggleable. The value on a category a A locked subject behaves the same way everywhere: - The settings screen shows its switch disabled, with a hint. -- The preferences route refuses a change that turns it off, with HTTP 403, in the app or on a channel it offers. -- Every dispatch method delivers it whatever preference the user has stored for it, on every channel it offers. +- The preferences route refuses a change that turns it off, with HTTP 403, in the app or by e-mail when it offers e-mail. +- Every dispatch method delivers it whatever preference the user has stored for it, by e-mail too when it offers e-mail. For a notification a user must always receive, declare `togglePermission: "forbidden"` on the subject **and** `togglePermission: "default"` on its category. `SystemCategory` declares `"default"`, which is what makes `GeneralSubject` mandatory. diff --git a/packages/interface-dms/docs/4.notifications/3.sending.md b/packages/interface-dms/docs/4.notifications/3.sending.md index f6189706e..f72036483 100644 --- a/packages/interface-dms/docs/4.notifications/3.sending.md +++ b/packages/interface-dms/docs/4.notifications/3.sending.md @@ -164,7 +164,7 @@ Every dispatch method accepts an optional `SendOptions` object. | `readScope` | `ReadScope` (optional) | Read-state grouping for a multi-recipient send. Defaults to `"individual"`. See [Read scope](/docs/interfaces/notifications/categories-and-subjects#read-scope). | | `idempotencyKey` | `string` (optional) | Stable event key, unique across producers. Prefix it with your module ID. Reusing it for a recipient preserves the original notification and its dismissal state. | | `dedupe` | `boolean` (optional) | With `false`, the DMS stores every unkeyed send, even one identical to a notification the recipient got less than 10 seconds earlier. Defaults to `true`. See [Repeated sends](#repeated-sends). | -| `tenantId` | `string` (optional) | The workspace the notification is about. [Delivery channels](/docs/interfaces/notifications/delivery-channels) receive it as `data.tenantId`. With `toRoles`, it also limits the recipients to the members of this tenant holding the roles; every tenant when unset. | +| `tenantId` | `string` (optional) | The workspace the notification is about. The [e-mail channel](/docs/interfaces/notifications/email) receives it as `data.tenantId`. With `toRoles`, it also limits the recipients to the members of this tenant holding the roles; every tenant when unset. | Pick `"shared"` for an alert that only needs one person to act on it, and `"individual"` for anything each recipient has to see. @@ -212,7 +212,7 @@ Every dispatch method resolves to one delivery per user, so the DMS applies the - **Skipping is silent.** A skipped delivery is not an error. The promise resolves normally, and there is no per-recipient result to inspect. - **Each recipient gets a row.** Each recipient gets their own stored notification. With `readScope: "shared"`, the DMS ties those copies together for read state, and they stay separate rows. - **Stored notifications are pushed live.** The DMS also publishes each new delivery on the recipient's realtime stream, so the dashboard's badge and preview update without a reload. -- **Stored notifications reach the registered channels.** When a module registers a channel (e-mail) and the subject offers it, each new delivery is also handed to the channel for recipients who have it on. A repeat or a retry that stores nothing new reaches no channel. See [Delivery channels](/docs/interfaces/notifications/delivery-channels). +- **Stored notifications reach the e-mail channel.** When a module registers the e-mail channel and the subject offers e-mail, each new delivery is also handed to the channel for recipients who have e-mail on. A repeat or a retry that stores nothing new is not mailed. See [E-mail](/docs/interfaces/notifications/email). A send can be skipped for reasons outside your control, so treat notifications as best-effort and do not make a workflow depend on one having been stored. To keep a failed send from breaking the operation that triggered it, wrap the call: diff --git a/packages/interface-dms/docs/4.notifications/4.delivery-channels.md b/packages/interface-dms/docs/4.notifications/4.email.md similarity index 71% rename from packages/interface-dms/docs/4.notifications/4.delivery-channels.md rename to packages/interface-dms/docs/4.notifications/4.email.md index 7d284b364..4404c01bf 100644 --- a/packages/interface-dms/docs/4.notifications/4.delivery-channels.md +++ b/packages/interface-dms/docs/4.notifications/4.email.md @@ -1,15 +1,15 @@ --- -title: "Delivery channels" +title: "E-mail" description: "How a module delivers notifications by e-mail, and how a subject offers it." mode: reference --- -Every notification lands in the recipient's in-app feed. A **delivery channel** also hands it to another medium. The DMS defines the `email` channel and ships no implementation for it. A mail module registers it, and every subject that offers e-mail then reaches the users who turn it on. +Every notification lands in the recipient's in-app feed. The **e-mail channel** also mails it. The DMS defines the channel and ships no implementation for it. A mail module registers it, and every subject that offers e-mail then reaches the users who turn it on. Two parties take part: -- **A subject offers the channel** with `channels: { email: ... }` on its declaration. A subject that names no channel stays in-app only. -- **A module registers the channel** with `NotificationChannel("email", { deliver })`. Without a registration, nothing is mailed and the settings screen shows the Email column marked **Soon**, as on an installation without a mail module. +- **A subject offers e-mail** with `email` on its declaration. A subject without it stays in-app only. +- **A module registers the channel** with `NotificationEmailChannel({ deliver })`. Without a registration, nothing is mailed and the settings screen shows the Email column marked **Soon**, as on an installation without a mail module. ## Offering e-mail on a subject @@ -27,18 +27,18 @@ const shopCategory = NotificationCategory("shop", { export const orderShippedSubject = NotificationSubject("order-shipped", { category: shopCategory, labelKey: "shop.notifications.subjects.order_shipped", - channels: { email: true }, + email: true, }); export const invoiceSubject = NotificationSubject("invoice", { category: shopCategory, labelKey: "shop.notifications.subjects.invoice", - channels: { email: { defaultOn: true } }, + email: { defaultOn: true }, }); ``` -| Value of `channels.email` | Meaning | -| ------------------------- | ------- | +| Value of `email` | Meaning | +| ---------------- | ------- | | omitted or `false` | The subject is not offered by e-mail. Its Email cell shows `—`. | | `true` or `{ defaultOn: false }` | Offered, off until the user turns it on. | | `{ defaultOn: true }` | Offered, on until the user turns it off. | @@ -46,9 +46,9 @@ export const invoiceSubject = NotificationSubject("invoice", { ## Registering the channel ```typescript -import { NotificationChannel } from "@antelopejs/interface-dms/notifications"; +import { NotificationEmailChannel } from "@antelopejs/interface-dms/notifications"; -NotificationChannel("email", { +NotificationEmailChannel({ deliver: (userId, data, context) => { // Queue a mail for `userId` about `data` (its title, description, // params, link and `tenantId`), keyed by `context.notificationId`. @@ -65,7 +65,7 @@ NotificationChannel("email", { | `context.notificationId` | Id of the in-app notification stored for this recipient. One id is mailed at most once. | | `context.idempotencyKey` | The event key of a keyed send, when there is one. | -One module registers a channel id. A later registration of the same id replaces the earlier one and logs a warning. The registration goes away with the module that made it. +One module registers the channel. A later registration replaces the earlier one and logs a warning. The registration goes away with the module that made it. ## When the DMS calls a channel @@ -74,7 +74,7 @@ For each recipient, after the in-app notification is handled: - **Only a new in-app notification is mailed.** The DMS calls `deliver` once the in-app row is stored and published. A send the recipient turned off in the app, a repeat inside the [10-second window](/docs/interfaces/notifications/sending#repeated-sends) and a retry of a keyed send (`toUsersIdempotently`) store no new row, so they mail nothing. E-mail is a copy of an in-app notification: a user who turns a subject off in the app receives no e-mail for it either, and the settings screen disables its Email switch. - **The user preference decides.** The choice is stored under `categoryId:subjectId@email`, next to the in-app key in the same per-user map. A user who never chose gets the subject's `defaultOn`. - **A locked subject is mailed whatever is stored.** A [locked subject](/docs/interfaces/notifications/categories-and-subjects#toggle-permissions) that offers e-mail reaches every recipient by e-mail, and the preferences route refuses turning its e-mail off with HTTP 403. -- **A failing channel never fails the send.** A `deliver` that throws or rejects is logged with `[DMS] Notification channel "email" failed to deliver`. The in-app notification stays, and the send resolves. +- **A failing channel never fails the send.** A `deliver` that throws or rejects is logged with `[DMS] Notification e-mail channel failed to deliver`. The in-app notification stays, and the send resolves. - **Sends wait for `deliver`.** Queue slow work, such as talking to a mail server, instead of doing it inside `deliver`. Preferences are per user and global: one choice per subject covers every workspace the user belongs to, for e-mail as for the app. `data.tenantId` tells the channel which workspace the notification is about, for example to pick its sender or branding. diff --git a/packages/interface-dms/docs/index.md b/packages/interface-dms/docs/index.md index de1ee7a03..61361a7cf 100644 --- a/packages/interface-dms/docs/index.md +++ b/packages/interface-dms/docs/index.md @@ -82,7 +82,7 @@ Each subpath is its own entry point, and importing one does not load the others. | `/base/table-view` | `TableView`, `@Column`, `TableViewRoutes`, guards, row actions | [Base](/docs/interfaces/base/tables) | | `/base/data-types` | `DataType`, the registration decorators, `DefaultDataTypes`, `DefaultDataCompareTypes`, `StatusType` | [Base](/docs/interfaces/base/data-types) | | `/base/…` | The per-component subpaths, such as `chart`, `grid`, `stack`, `tab`, `custom`, `layouts` and `helpers/…` | [Base](/docs/interfaces/base/introduction) | -| `/notifications`, `/notifications/types` | Categories, subjects, the notification builder, its dispatch targets and delivery channels | [Notifications](/docs/interfaces/notifications/introduction) | +| `/notifications`, `/notifications/types` | Categories, subjects, the notification builder, its dispatch targets and the e-mail channel | [Notifications](/docs/interfaces/notifications/introduction) | | `/html-render` | `RegisterHtmlTemplate`, `GenerateHtml` and the template reference types | [HTML Render](/docs/interfaces/html-render/introduction) | Beyond these entry points, built files are importable through the `./*` export (`@antelopejs/interface-dms/base/form-types`). Moving or renaming a public path is a breaking change, like removing an export. diff --git a/packages/interface-dms/src/notifications/index.ts b/packages/interface-dms/src/notifications/index.ts index 9c7073d58..2210174d7 100644 --- a/packages/interface-dms/src/notifications/index.ts +++ b/packages/interface-dms/src/notifications/index.ts @@ -5,7 +5,7 @@ export { internal }; export * from "./types"; import type { NotificationCategoryInfo, - NotificationChannelInfo, + NotificationEmailChannelInfo, NotificationSubjectInfo, } from "./types"; @@ -38,19 +38,16 @@ export function NotificationSubject( } /** - * Registers a delivery channel (`email`): every notification stored in a - * user's feed is also handed to `deliver` when its subject offers the channel - * and the user has it on. One module registers a channel id; a later - * registration of the same id replaces it. The registration goes away with - * the module that made it. + * Registers the e-mail channel: every notification stored in a user's feed is + * also handed to `deliver` when its subject offers e-mail and the user has it + * on. One module registers it; a later registration replaces the earlier one. + * The registration goes away with the module that made it. */ -export function NotificationChannel( - id: NotificationChannelInfo["id"], - channel: Omit, -): NotificationChannelInfo { - const notificationChannel: NotificationChannelInfo = { id, ...channel }; - internal.RegisterNotificationChannel.register(notificationChannel); - return notificationChannel; +export function NotificationEmailChannel( + channel: NotificationEmailChannelInfo, +): NotificationEmailChannelInfo { + internal.RegisterNotificationEmailChannel.register(channel); + return channel; } export const SystemCategory = NotificationCategory("system", { diff --git a/packages/interface-dms/src/notifications/internal.ts b/packages/interface-dms/src/notifications/internal.ts index 71595748e..bc5eb2a69 100644 --- a/packages/interface-dms/src/notifications/internal.ts +++ b/packages/interface-dms/src/notifications/internal.ts @@ -5,7 +5,7 @@ import { import type { DeliveryOptions, NotificationCategoryInfo, - NotificationChannelInfo, + NotificationEmailChannelInfo, NotificationData, NotificationSubjectInfo, ReadScope, @@ -23,8 +23,8 @@ export namespace internal { (info: NotificationSubjectInfo) => void >(); - export const RegisterNotificationChannel = new RegisteringProxy< - (info: NotificationChannelInfo) => void + export const RegisterNotificationEmailChannel = new RegisteringProxy< + (info: NotificationEmailChannelInfo) => void >(); export const SendToUser = diff --git a/packages/interface-dms/src/notifications/types.ts b/packages/interface-dms/src/notifications/types.ts index 71033dfe9..6001f89ed 100644 --- a/packages/interface-dms/src/notifications/types.ts +++ b/packages/interface-dms/src/notifications/types.ts @@ -29,28 +29,16 @@ export interface NotificationSubjectInfo { /** Translation key of a badge shown next to the subject label (`Developer mode`). */ badgeKey?: string; /** - * The channels this subject also reaches its recipients through, next to - * the in-app feed. A subject that names none is in-app only. A channel - * delivers only when a module registers it (`NotificationChannel`). + * Whether the subject also reaches its recipients by e-mail, next to the + * in-app feed. `true` offers it off until the user turns it on; + * `{ defaultOn: true }` offers it on until the user turns it off. Unset or + * `false`: in-app only. E-mail is delivered only once a module registers + * the e-mail channel (`NotificationEmailChannel`). */ - channels?: NotificationChannelOffers; + email?: boolean | { defaultOn?: boolean }; } -/** The delivery channels a subject can offer next to the in-app feed. */ -export type NotificationChannelId = "email"; - -/** - * How a subject offers a channel. `true` offers it off until the user turns - * it on; `{ defaultOn: true }` offers it on until the user turns it off. - * `false` does not offer it. - */ -export type NotificationChannelOffer = boolean | { defaultOn?: boolean }; - -export type NotificationChannelOffers = Partial< - Record ->; - -/** What a channel learns about one delivery besides its recipient and content. */ +/** What the e-mail channel learns about one delivery besides its recipient and content. */ export interface NotificationDeliveryContext { /** Id of the in-app notification this delivery follows. */ notificationId: string; @@ -59,12 +47,11 @@ export interface NotificationDeliveryContext { } /** - * A channel a notification also reaches its recipient through. The DMS calls - * `deliver` once per stored in-app notification whose recipient has the - * channel on for its subject. + * The e-mail channel a mail module registers. The DMS calls `deliver` once + * per stored in-app notification whose recipient has e-mail on for its + * subject. */ -export interface NotificationChannelInfo { - id: NotificationChannelId; +export interface NotificationEmailChannelInfo { /** * Hands one notification to the channel. A rejection is logged and never * fails the in-app delivery. Sends wait for it, so queue slow work. From d712cf05c112ea9f79c1d685a3997c079ce986b4 Mon Sep 17 00:00:00 2001 From: Antony Rizzitelli Date: Fri, 20 Nov 2026 15:03:50 +0000 Subject: [PATCH 4/5] fix(dms): keep the e-mail channel when a replaced registration unloads An unregister now clears the channel only when it names the live registration, stamped with a RegistrationIdentity, so a hot reload no longer turns e-mail off. deliver receives the notification id directly, SendOptions holds the one tenantId, and a subject off in the app shows its e-mail switch off. --- .../useNotificationPreferences.ts | 8 +++- .../notification-preferences-email.test.ts | 3 ++ .../dms-notifications/index.ts | 25 ++++++------ .../integration/notification-email.test.ts | 39 ++++++++++++------- .../docs/4.notifications/4.email.md | 13 +++---- .../interface-dms/src/notifications/index.ts | 1 + .../src/notifications/internal.ts | 7 ++++ .../interface-dms/src/notifications/types.ts | 31 +++++---------- 8 files changed, 70 insertions(+), 57 deletions(-) diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts index 5b2371e63..b043f819a 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/build/composables/notification/useNotificationPreferences.ts @@ -80,9 +80,13 @@ export const useNotificationPreferences = ( const isEnabled = (subject: NotificationSubject) => read(subjectPreferenceKey(subject)); - /** A locked subject is mailed whatever is stored, as the server sends it. */ + /** + * As the server sends it: a locked subject is mailed whatever is stored, + * and a subject off in the app is not mailed at all. + */ const isEmailEnabled = (subject: NotificationSubject) => - subject.locked === true || read(emailPreferenceKey(subject)); + subject.locked === true || + (isEnabled(subject) && read(emailPreferenceKey(subject))); /** The row's state cell sums up its in-app and e-mail switches. */ const rowState = (subject: NotificationSubject): SaveStatusState => diff --git a/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts index 680709059..b440f9c34 100644 --- a/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts +++ b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts @@ -183,6 +183,9 @@ describe("notification preferences e-mail column", () => { const container = await mount(catalog(true, { "work:digest": false })); expect(emailSwitchOf(container, "Digest")?.disabled).toBe(true); + expect( + emailSwitchOf(container, "Digest")?.getAttribute("aria-checked"), + ).toBe("false"); expect(emailSwitchOf(container, "Assigned")?.disabled).toBe(false); }); }); diff --git a/packages/dms/src/implementations/dms-notifications/index.ts b/packages/dms/src/implementations/dms-notifications/index.ts index 46f1bd1f4..086ee1ab4 100644 --- a/packages/dms/src/implementations/dms-notifications/index.ts +++ b/packages/dms/src/implementations/dms-notifications/index.ts @@ -13,6 +13,7 @@ import type { ReadScope, RoleSendOptions, } from "@antelopejs/interface-dms/notifications/types"; +import { internal as interfaceInternal } from "@antelopejs/interface-dms/notifications/internal"; import { UserNotificationPreferencesModel, type UserNotificationCounts, @@ -180,7 +181,6 @@ async function deliverByEmail( data: NotificationData, notification: UserNotification, preferences: () => Promise>, - idempotencyKey?: string, ): Promise { const channel = emailChannelSlot.channel; const subject = subjectRegistry.get( @@ -190,10 +190,7 @@ async function deliverByEmail( return; } try { - await channel.deliver(userId, data, { - notificationId: notification._id, - idempotencyKey, - }); + await channel.deliver(userId, data, notification._id); } catch (error) { Logging.Error( `[DMS] Notification e-mail channel failed to deliver "${data.title}" to "${userId}"`, @@ -230,15 +227,17 @@ export namespace internal { export const RegisterNotificationEmailChannel = { register: (channel: NotificationEmailChannelInfo) => { - if (emailChannelSlot.channel) { - Logging.Warn( - "[DMS] Notification e-mail channel registered again: the latest registration replaces the previous one", - ); - } emailChannelSlot.channel = channel; }, - unregister: () => { - emailChannelSlot.channel = undefined; + unregister: (channel: NotificationEmailChannelInfo) => { + if ( + interfaceInternal.emailChannelIdentity.isSame( + emailChannelSlot.channel, + channel, + ) + ) { + emailChannelSlot.channel = undefined; + } }, }; @@ -310,7 +309,7 @@ export namespace internal { await publishNotificationEvent(userId, NOTIFICATION_NEW_EVENT, { notification: created, }); - await deliverByEmail(userId, data, created, preferences, idempotencyKey); + await deliverByEmail(userId, data, created, preferences); } export async function SendToUsers( diff --git a/packages/dms/src/test/integration/notification-email.test.ts b/packages/dms/src/test/integration/notification-email.test.ts index 447bd0eea..3ec8e1589 100644 --- a/packages/dms/src/test/integration/notification-email.test.ts +++ b/packages/dms/src/test/integration/notification-email.test.ts @@ -1,10 +1,11 @@ import type { AxiosInstance } from "axios"; import { expect } from "chai"; +import { NotificationEmailChannel } from "@antelopejs/interface-dms/notifications"; +import { internal as interfaceInternal } from "@antelopejs/interface-dms/notifications/internal"; import { SendableNotification } from "@antelopejs/interface-dms/notifications/sendable"; import type { NotificationCategoryInfo, NotificationData, - NotificationDeliveryContext, NotificationEmailChannelInfo, NotificationSubjectInfo, } from "@antelopejs/interface-dms/notifications/types"; @@ -60,7 +61,7 @@ const inAppKey = (subject: NotificationSubjectInfo) => interface Delivery { userId: string; data: NotificationData; - context: NotificationDeliveryContext; + notificationId: string; } interface CatalogSubject { @@ -70,12 +71,15 @@ interface CatalogSubject { let deliveries: Delivery[] = []; let failing = false; -const channel: NotificationEmailChannelInfo = { - deliver: (userId, data, context) => { - if (failing) throw new Error("mail server down"); - deliveries.push({ userId, data, context }); - }, +const deliver: NotificationEmailChannelInfo["deliver"] = ( + userId, + data, + notificationId, +) => { + if (failing) throw new Error("mail server down"); + deliveries.push({ userId, data, notificationId }); }; +const channel: NotificationEmailChannelInfo = { deliver }; let sequence = 0; function notificationOn( @@ -158,12 +162,14 @@ describe("[integration] notification e-mail, channel registered", () => { const patch = (changes: Record) => user.client().patch>(PREFERENCES, changes); + let registered = channel; + before(() => { - internal.RegisterNotificationEmailChannel.register(channel); + NotificationEmailChannel(channel); }); after(() => { - internal.RegisterNotificationEmailChannel.unregister(); + interfaceInternal.RegisterNotificationEmailChannel.unregister(registered); }); beforeEach(() => { @@ -194,7 +200,7 @@ describe("[integration] notification e-mail, channel registered", () => { expect(deliveries).to.have.length(1); expect(deliveries[0]?.userId).to.equal(user.userId()); expect(deliveries[0]?.data.tenantId).to.equal("tenant-a"); - expect(deliveries[0]?.context.notificationId).to.be.a("string"); + expect(deliveries[0]?.notificationId).to.be.a("string"); }); it("mails a subject offered on until the user turns it off (fails when defaultOn is ignored or the choice is not read)", async () => { @@ -233,9 +239,6 @@ describe("[integration] notification e-mail, channel registered", () => { await keyed.toUsersIdempotently([user.userId()], "channel-test-event"); await keyed.toUsersIdempotently([user.userId()], "channel-test-event"); expect(deliveries).to.have.length(1); - expect(deliveries[0]?.context.idempotencyKey).to.equal( - "channel-test-event", - ); }); it("mails a repeat dropped by the duplicate window once (fails when a deduplicated send still mails)", async () => { @@ -252,4 +255,14 @@ describe("[integration] notification e-mail, channel registered", () => { `Channel test ${sequence} on ${optOut.id}`, ); }); + + it("keeps mailing when a replaced registration unloads after its replacement, as on a hot reload (fails when any unregister clears the channel)", async () => { + registered = NotificationEmailChannel({ deliver }); + interfaceInternal.RegisterNotificationEmailChannel.unregister(channel); + + const catalog = await user.client().get(CATEGORIES); + expect(catalog.data.emailChannel).to.equal(true); + await notificationOn(optOut).toUser(user.userId()); + expect(deliveries).to.have.length(1); + }); }); diff --git a/packages/interface-dms/docs/4.notifications/4.email.md b/packages/interface-dms/docs/4.notifications/4.email.md index 4404c01bf..3138543e1 100644 --- a/packages/interface-dms/docs/4.notifications/4.email.md +++ b/packages/interface-dms/docs/4.notifications/4.email.md @@ -49,25 +49,24 @@ export const invoiceSubject = NotificationSubject("invoice", { import { NotificationEmailChannel } from "@antelopejs/interface-dms/notifications"; NotificationEmailChannel({ - deliver: (userId, data, context) => { + deliver: (userId, data, notificationId) => { // Queue a mail for `userId` about `data` (its title, description, - // params, link and `tenantId`), keyed by `context.notificationId`. + // params, link and `tenantId`), keyed by `notificationId`. }, }); ``` -`deliver(userId, data, context)` receives: +`deliver(userId, data, notificationId)` receives: | Argument | Description | | -------- | ----------- | | `userId` | The recipient. | | `data` | The `NotificationData` sent, with `tenantId` when the send named a workspace (`SendOptions.tenantId`). | -| `context.notificationId` | Id of the in-app notification stored for this recipient. One id is mailed at most once. | -| `context.idempotencyKey` | The event key of a keyed send, when there is one. | +| `notificationId` | Id of the in-app notification stored for this recipient. Key the mail on it to send it at most once. | -One module registers the channel. A later registration replaces the earlier one and logs a warning. The registration goes away with the module that made it. +One module registers the channel. A later registration replaces the earlier one. Unloading the module whose registration is live removes the channel; unloading one that was replaced, as a hot reload does, leaves the live one in place. -## When the DMS calls a channel +## When the DMS calls the channel For each recipient, after the in-app notification is handled: diff --git a/packages/interface-dms/src/notifications/index.ts b/packages/interface-dms/src/notifications/index.ts index 2210174d7..044c9276a 100644 --- a/packages/interface-dms/src/notifications/index.ts +++ b/packages/interface-dms/src/notifications/index.ts @@ -46,6 +46,7 @@ export function NotificationSubject( export function NotificationEmailChannel( channel: NotificationEmailChannelInfo, ): NotificationEmailChannelInfo { + internal.emailChannelIdentity.stamp(channel); internal.RegisterNotificationEmailChannel.register(channel); return channel; } diff --git a/packages/interface-dms/src/notifications/internal.ts b/packages/interface-dms/src/notifications/internal.ts index bc5eb2a69..2ac6ea4da 100644 --- a/packages/interface-dms/src/notifications/internal.ts +++ b/packages/interface-dms/src/notifications/internal.ts @@ -11,6 +11,7 @@ import type { ReadScope, RoleSendOptions, } from "./types"; +import { RegistrationIdentity } from "../page/internal/registry"; /** * @internal @@ -27,6 +28,12 @@ export namespace internal { (info: NotificationEmailChannelInfo) => void >(); + /** Tells the registration a module unloads from the one that replaced it. */ + export const emailChannelIdentity = + new RegistrationIdentity( + "notification-email-channel", + ); + export const SendToUser = InterfaceFunction< ( diff --git a/packages/interface-dms/src/notifications/types.ts b/packages/interface-dms/src/notifications/types.ts index 6001f89ed..8d7a3a803 100644 --- a/packages/interface-dms/src/notifications/types.ts +++ b/packages/interface-dms/src/notifications/types.ts @@ -38,14 +38,6 @@ export interface NotificationSubjectInfo { email?: boolean | { defaultOn?: boolean }; } -/** What the e-mail channel learns about one delivery besides its recipient and content. */ -export interface NotificationDeliveryContext { - /** Id of the in-app notification this delivery follows. */ - notificationId: string; - /** The event key of a keyed send (`idempotencyKey`). */ - idempotencyKey?: string; -} - /** * The e-mail channel a mail module registers. The DMS calls `deliver` once * per stored in-app notification whose recipient has e-mail on for its @@ -53,13 +45,14 @@ export interface NotificationDeliveryContext { */ export interface NotificationEmailChannelInfo { /** - * Hands one notification to the channel. A rejection is logged and never - * fails the in-app delivery. Sends wait for it, so queue slow work. + * Hands one notification to the channel, with the id of the in-app + * notification it follows. A rejection is logged and never fails the + * in-app delivery. Sends wait for it, so queue slow work. */ deliver( userId: string, data: NotificationData, - context: NotificationDeliveryContext, + notificationId: string, ): Promise | void; } @@ -79,9 +72,10 @@ export interface DeliveryOptions { export interface SendOptions extends DeliveryOptions { readScope?: ReadScope; /** - * The workspace the notification is about. Channels receive it in - * `NotificationData.tenantId`; `toRoles` also limits its recipients to - * this tenant's members. + * The workspace the notification is about. The e-mail channel receives it + * in `NotificationData.tenantId`. `toRoles` also limits its recipients to + * this tenant's members holding the roles; without it, the holders are + * looked up in every tenant. */ tenantId?: string; /** Stable event key, unique across notification producers. Retries preserve delivery and dismissal state. */ @@ -89,14 +83,7 @@ export interface SendOptions extends DeliveryOptions { } /** Options of `toRoles`: a send to the holders of roles. */ -export interface RoleSendOptions extends SendOptions { - /** - * Only the members of this tenant holding the roles. Role ids belong to a - * tenant, so a send about one tenant names it; without it, the holders are - * looked up in every tenant. - */ - tenantId?: string; -} +export type RoleSendOptions = SendOptions; export interface NotificationData { icon: string; From 9d35ac4558be69207f68c852000cfd2dda1c7b47 Mon Sep 17 00:00:00 2001 From: Antony Rizzitelli Date: Fri, 20 Nov 2026 17:45:25 +0000 Subject: [PATCH 5/5] refactor(dms): keep RoleSendOptions an interface so it stays open to merging --- packages/interface-dms/src/notifications/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/interface-dms/src/notifications/types.ts b/packages/interface-dms/src/notifications/types.ts index 8d7a3a803..bffae16f0 100644 --- a/packages/interface-dms/src/notifications/types.ts +++ b/packages/interface-dms/src/notifications/types.ts @@ -83,7 +83,7 @@ export interface SendOptions extends DeliveryOptions { } /** Options of `toRoles`: a send to the holders of roles. */ -export type RoleSendOptions = SendOptions; +export interface RoleSendOptions extends SendOptions {} export interface NotificationData { icon: string;