diff --git a/packages/dms/docs/02.building/06.backend-services.md b/packages/dms/docs/02.building/06.backend-services.md index 9d6282c1e..672fe9fc2 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 (`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 47d79a0d9..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) -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 ([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 8ab90ad04..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,18 +10,35 @@ interface NotificationMatrixSubjectProps { subject: NotificationSubject; enabled: boolean; state: SaveStatusState; + 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..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 @@ -20,11 +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 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[]; + /** A module registered the e-mail channel. */ + emailChannel?: boolean; } export const buildPreferenceKey = (categoryId: string, subjectId: string) => @@ -33,6 +40,10 @@ export const buildPreferenceKey = (categoryId: string, subjectId: string) => export const subjectPreferenceKey = (subject: NotificationSubject) => buildPreferenceKey(subject.category.id, subject.id); +/** 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", "/categories", @@ -55,6 +66,10 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => { ); const categories = computed(() => catalog.data.value?.categories ?? []); const subjects = computed(() => catalog.data.value?.subjects ?? []); + /** 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)); @@ -76,6 +91,7 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => { return { categories, subjects, + 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 25359fabf..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 @@ -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 { + emailPreferenceKey, hasFailed, type NotificationCategory, type NotificationSubject, @@ -51,8 +53,23 @@ 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.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] ?? true, + read, write: (key, enabled) => { preferences.value = { ...preferences.value, [key]: enabled }; }, @@ -61,10 +78,22 @@ export const useNotificationPreferences = ( }); const isEnabled = (subject: NotificationSubject) => - preferences.value[subjectPreferenceKey(subject)] ?? true; + read(subjectPreferenceKey(subject)); + /** + * 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 || + (isEnabled(subject) && read(emailPreferenceKey(subject))); + + /** 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[emailPreferenceKey(subject)], + ]); const toggleableSubjectsOf = (category: NotificationCategory) => catalog.subjectsOf(category.id).filter((subject) => !subject.locked); @@ -72,6 +101,9 @@ export const useNotificationPreferences = ( const toggleSubject = (subject: NotificationSubject, enabled: boolean) => instant.change(subjectPreferenceKey(subject), enabled); + const toggleEmail = (subject: NotificationSubject, enabled: boolean) => + instant.change(emailPreferenceKey(subject), enabled); + const toggleCategory = (category: NotificationCategory, enabled: boolean) => instant.changeMany( Object.fromEntries( @@ -95,6 +127,9 @@ export const useNotificationPreferences = ( return { categories: catalog.categories, subjectsOf: catalog.subjectsOf, + hasEmailChannel: catalog.hasEmailChannel, + 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..b440f9c34 --- /dev/null +++ b/packages/dms/frontend-vue/tests/notification-preferences-email.test.ts @@ -0,0 +1,191 @@ +/** @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(emailChannel: boolean, stored: Record = {}) { + return vi.fn(async (url: string): Promise => { + if (url.endsWith("/categories")) { + return { + categories: [category], + emailChannel, + subjects: [ + { + id: "assigned", + category, + labelKey: "Assigned", + email: emailChannel ? { defaultOn: false } : undefined, + }, + { + id: "digest", + category, + labelKey: "Digest", + email: emailChannel ? { defaultOn: true } : undefined, + }, + { id: "mentions", category, labelKey: "Mentions" }, + ], + }; + } + 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(false)); + + 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(true)); + + 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(true); + 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(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 5daf5ced5..086ee1ab4 100644 --- a/packages/dms/src/implementations/dms-notifications/index.ts +++ b/packages/dms/src/implementations/dms-notifications/index.ts @@ -7,11 +7,13 @@ import { UserModel } from "@antelopejs/interface-dms/auth/db"; import type { DeliveryOptions, NotificationCategoryInfo, + NotificationEmailChannelInfo, NotificationData, NotificationSubjectInfo, ReadScope, RoleSendOptions, } from "@antelopejs/interface-dms/notifications/types"; +import { internal as interfaceInternal } from "@antelopejs/interface-dms/notifications/internal"; import { UserNotificationPreferencesModel, type UserNotificationCounts, @@ -24,6 +26,8 @@ import { getRealtimeBroker, buildUserNotificationTopic } from "../../realtime"; import { runInBatches } from "../../utils/run-in-batches/index"; import { categoryRegistry, + emailChannelSlot, + isEmailOn, isSubjectLocked, subjectRegistry, } from "../../utils/notification-registry/index"; @@ -167,6 +171,34 @@ async function store( ); } +/** + * 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 deliverByEmail( + userId: string, + data: NotificationData, + notification: UserNotification, + preferences: () => Promise>, +): Promise { + const channel = emailChannelSlot.channel; + const subject = subjectRegistry.get( + `${data.subject.category.id}:${data.subject.id}`, + ); + if (!channel || !subject || !isEmailOn(subject, await preferences())) { + return; + } + try { + await channel.deliver(userId, data, notification._id); + } catch (error) { + Logging.Error( + `[DMS] Notification e-mail channel 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 +225,22 @@ export namespace internal { }, }; + export const RegisterNotificationEmailChannel = { + register: (channel: NotificationEmailChannelInfo) => { + emailChannelSlot.channel = channel; + }, + unregister: (channel: NotificationEmailChannelInfo) => { + if ( + interfaceInternal.emailChannelIdentity.isSame( + emailChannelSlot.channel, + channel, + ) + ) { + emailChannelSlot.channel = undefined; + } + }, + }; + export const RegisterNotificationSubject = { register: (info: NotificationSubjectInfo) => { if (!categoryRegistry.has(info.category.id)) { @@ -215,26 +263,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 +296,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 +309,7 @@ export namespace internal { await publishNotificationEvent(userId, NOTIFICATION_NEW_EVENT, { notification: created, }); + await deliverByEmail(userId, data, created, preferences); } 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..eb20c87ea 100644 --- a/packages/dms/src/pages/settings/users/notifications.ts +++ b/packages/dms/src/pages/settings/users/notifications.ts @@ -45,7 +45,10 @@ import { parseNotificationFeedQuery, } from "../../../db/models"; import { - findSubjectByPreferenceKey, + type EmailOffer, + emailChannelSlot, + emailOffer, + findPreferenceSubject, getRegisteredCategories, getRegisteredSubjects, isSubjectLocked, @@ -64,15 +67,24 @@ 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. */ +export interface NotificationSubjectView extends Omit< + NotificationSubjectInfo, + "email" +> { + /** The user may not turn this subject off, in the app or by e-mail. */ locked: boolean; + /** Set when the subject offers e-mail and a module registered the channel. */ + email?: EmailOffer; } function toSubjectView( subject: NotificationSubjectInfo, ): NotificationSubjectView { - return { ...subject, locked: isSubjectLocked(subject) }; + return { + ...subject, + locked: isSubjectLocked(subject), + email: emailOffer(subject), + }; } function parsePageSize(value: QueryValue): number { @@ -208,17 +220,20 @@ 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 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( - findSubjectByPreferenceKey(key), + findPreferenceSubject(key), HTTP_BAD_REQUEST, "error.request_refused", ); } for (const [key, enabled] of Object.entries(changes)) { - const subject = findSubjectByPreferenceKey(key); + const subject = findPreferenceSubject(key); assert( enabled || !subject || !isSubjectLocked(subject), HTTP_FORBIDDEN, @@ -296,11 +311,20 @@ export class NotificationsApiController extends Controller(NOTIFICATIONS_API) { return preferencesModel.mergePreferences(this.user._id, changes); } + /** + * 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 }; + return { + categories, + subjects, + emailChannel: emailChannelSlot.channel !== undefined, + }; } /** diff --git a/packages/dms/src/test/integration/notification-email.test.ts b/packages/dms/src/test/integration/notification-email.test.ts new file mode 100644 index 000000000..3ec8e1589 --- /dev/null +++ b/packages/dms/src/test/integration/notification-email.test.ts @@ -0,0 +1,268 @@ +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, + NotificationEmailChannelInfo, + 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, + email: true, +}; +const optOut: NotificationSubjectInfo = { + id: "opt-out", + labelKey: "opt-out", + category, + 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", + 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; + notificationId: string; +} + +interface CatalogSubject { + id: string; + email?: { defaultOn: boolean }; +} + +let deliveries: Delivery[] = []; +let failing = false; +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( + 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 { + emailChannel: boolean; + subjects: CatalogSubject[]; +} + +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.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 () => { + const refused = await user.client().patch(PREFERENCES, { + [emailKey(optIn)]: true, + }); + expect(refused.status).to.equal(HTTP_BAD_REQUEST); + }); +}); + +describe("[integration] notification e-mail, channel registered", () => { + const user = useChannelTestUser(); + const patch = (changes: Record) => + user.client().patch>(PREFERENCES, changes); + + let registered = channel; + + before(() => { + NotificationEmailChannel(channel); + }); + + after(() => { + interfaceInternal.RegisterNotificationEmailChannel.unregister(registered); + }); + + 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.email]), + ); + 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 () => { + 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]?.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); + }); + + 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}`, + ); + }); + + 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/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 e919a239d..3bae667a6 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-email"; diff --git a/packages/interface-dms/docs/4.notifications/1.introduction.md b/packages/interface-dms/docs/4.notifications/1.introduction.md index b948088ca..fac08af94 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. +- **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 4fe232825..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. 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 [E-mail](/docs/interfaces/notifications/email)). 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`. | +| `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. @@ -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 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 b5fd8541b..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, `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. 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,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 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: @@ -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.email.md b/packages/interface-dms/docs/4.notifications/4.email.md new file mode 100644 index 000000000..3138543e1 --- /dev/null +++ b/packages/interface-dms/docs/4.notifications/4.email.md @@ -0,0 +1,79 @@ +--- +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. 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 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 + +```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", + email: true, +}); + +export const invoiceSubject = NotificationSubject("invoice", { + category: shopCategory, + labelKey: "shop.notifications.subjects.invoice", + email: { defaultOn: true }, +}); +``` + +| 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. | + +## Registering the channel + +```typescript +import { NotificationEmailChannel } from "@antelopejs/interface-dms/notifications"; + +NotificationEmailChannel({ + deliver: (userId, data, notificationId) => { + // Queue a mail for `userId` about `data` (its title, description, + // params, link and `tenantId`), keyed by `notificationId`. + }, +}); +``` + +`deliver(userId, data, notificationId)` receives: + +| Argument | Description | +| -------- | ----------- | +| `userId` | The recipient. | +| `data` | The `NotificationData` sent, with `tenantId` when the send named a workspace (`SendOptions.tenantId`). | +| `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. 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 the 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 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 4520ded11..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 and its dispatch targets | [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 96f53ddc2..044c9276a 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, + NotificationEmailChannelInfo, NotificationSubjectInfo, } from "./types"; @@ -36,6 +37,20 @@ export function NotificationSubject( return notificationSubject; } +/** + * 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 NotificationEmailChannel( + channel: NotificationEmailChannelInfo, +): NotificationEmailChannelInfo { + internal.emailChannelIdentity.stamp(channel); + internal.RegisterNotificationEmailChannel.register(channel); + return channel; +} + 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..2ac6ea4da 100644 --- a/packages/interface-dms/src/notifications/internal.ts +++ b/packages/interface-dms/src/notifications/internal.ts @@ -5,11 +5,13 @@ import { import type { DeliveryOptions, NotificationCategoryInfo, + NotificationEmailChannelInfo, NotificationData, NotificationSubjectInfo, ReadScope, RoleSendOptions, } from "./types"; +import { RegistrationIdentity } from "../page/internal/registry"; /** * @internal @@ -22,6 +24,16 @@ export namespace internal { (info: NotificationSubjectInfo) => void >(); + export const RegisterNotificationEmailChannel = new RegisteringProxy< + (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/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..bffae16f0 100644 --- a/packages/interface-dms/src/notifications/types.ts +++ b/packages/interface-dms/src/notifications/types.ts @@ -28,6 +28,32 @@ export interface NotificationSubjectInfo { togglePermission?: TogglePermission; /** Translation key of a badge shown next to the subject label (`Developer mode`). */ badgeKey?: string; + /** + * 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`). + */ + email?: boolean | { defaultOn?: boolean }; +} + +/** + * 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 NotificationEmailChannelInfo { + /** + * 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, + notificationId: string, + ): Promise | void; } /** How a delivery is stored, whoever receives it. */ @@ -45,20 +71,20 @@ export interface DeliveryOptions { export interface SendOptions extends DeliveryOptions { readScope?: ReadScope; - /** Stable event key, unique across notification producers. Retries preserve delivery and dismissal state. */ - idempotencyKey?: string; -} - -/** 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 + * 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. */ + idempotencyKey?: string; } +/** Options of `toRoles`: a send to the holders of roles. */ +export interface RoleSendOptions extends SendOptions {} + export interface NotificationData { icon: string; title: string; @@ -68,6 +94,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";