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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/dms/docs/02.building/06.backend-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion packages/dms/docs/03.auth-and-tenancy/01.authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,35 @@ interface NotificationMatrixSubjectProps {
subject: NotificationSubject;
enabled: boolean;
state: SaveStatusState;
emailEnabled?: boolean;
}

const props = defineProps<NotificationMatrixSubjectProps>();
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);
};
</script>

<template>
Expand Down Expand Up @@ -68,7 +85,21 @@ const onToggle = (value: boolean) => {
@update:model-value="onToggle"
/>
</div>
<div v-if="props.subject.email" class="flex justify-center" role="cell">
<USwitch
:model-value="props.emailEnabled"
:disabled="isEmailDisabled"
:title="emailTitle"
:aria-label="
t('page.settings.notifications.email_switch', { name: label })
"
:aria-busy="props.state === 'saving'"
data-channel="email"
@update:model-value="onToggleEmail"
/>
</div>
<div
v-else
class="text-dimmed flex justify-center font-mono text-xs font-medium"
role="cell"
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ const {
toggleableSubjectsOf,
toggleSubject,
toggleCategory,
hasEmailChannel,
isEmailEnabled,
toggleEmail,
retry,
load,
} = useNotificationPreferences();
Expand Down Expand Up @@ -91,6 +94,7 @@ const failureMessage = computed(() => {
>
{{ t("page.settings.notifications.column_email") }}
<UBadge
v-if="!hasEmailChannel"
color="neutral"
size="sm"
class="tracking-[0.04em]"
Expand Down Expand Up @@ -160,7 +164,9 @@ const failureMessage = computed(() => {
:subject="subject"
:enabled="isEnabled(subject)"
:state="rowState(subject)"
:email-enabled="isEmailEnabled(subject)"
@toggle="(enabled) => toggleSubject(subject, enabled)"
@toggle-email="(enabled) => toggleEmail(subject, enabled)"
@retry="retry"
/>
</div>
Expand All @@ -187,7 +193,11 @@ const failureMessage = computed(() => {
</template>
<span v-else class="flex items-center gap-1.5 text-xs">
<UIcon name="i-ph-info" class="text-dimmed size-3.5" />
{{ t("page.settings.notifications.email_hint") }}
{{
hasEmailChannel
? t("page.settings.notifications.email_hint_active")
: t("page.settings.notifications.email_hint")
}}
</span>
</template>
</DmsSectionPanel>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand All @@ -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",
Expand All @@ -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));

Expand All @@ -76,6 +91,7 @@ export const useNotificationCatalog = (enabled: () => boolean = () => true) => {
return {
categories,
subjects,
hasEmailChannel,
isLoaded,
loadFailed,
loadCatalog,
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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<PreferenceMap>(() =>
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<PreferenceMap>({
read: (key) => preferences.value[key] ?? true,
read,
write: (key, enabled) => {
preferences.value = { ...preferences.value, [key]: enabled };
},
Expand All @@ -61,17 +78,32 @@ 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);

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(
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
Loading
Loading