Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Fix localized notifications showing no title or body (#3411)

Koen372129513d9b
diff --git a/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.java b/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.java
index bdde82bb6..65b11ee89 100644
--- a/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.java
+++ b/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.java
@@ -37,6 +37,7 @@ import org.openremote.model.attribute.MetaItem;
import org.openremote.model.console.ConsoleProvider;
import org.openremote.model.notification.AbstractNotificationMessage;
import org.openremote.model.notification.EmailNotificationMessage;
+import org.openremote.model.notification.LocalizedNotificationMessage;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.PushNotificationMessage;
import org.openremote.model.notification.SentNotification;
@@ -174,6 +175,12 @@ public class ManagerNotificationSetup extends ManagerSetup {
smartCityAssetId,
KeycloakNotificationSetup.SMARTCITY_REALM,
base.minus(++slot, ChronoUnit.MINUTES));
+
+ // Localized notifications are sent at the base instant, the newest of all records above, so
+ // they are listed first
+ for (User user : users) {
+ persistLocalizedNotification(user.getId(), assetId, MASTER_REALM, base);
+ }
}
/**
@@ -300,6 +307,36 @@ public class ManagerNotificationSetup extends ManagerSetup {
subject, EmailNotificationMessage.TYPE, message, userId, assetId, realm, sentOn);
}
+ /**
+ * Persists a localized notification record holding one push message per language, as a localized
+ * rule action produces. The default language decides which of them a target without a locale of
+ * its own receives.
+ */
+ private void persistLocalizedNotification(
+ String userId, String assetId, String realm, Instant sentOn) {
+ LocalizedNotificationMessage message =
+ new LocalizedNotificationMessage(
+ "en",
+ Map.<String, AbstractNotificationMessage>of(
+ "en",
+ new PushNotificationMessage()
+ .setTitle("Localized Alert")
+ .setBody("This is a localized test notification"),
+ "nl",
+ new PushNotificationMessage()
+ .setTitle("Gelokaliseerde melding")
+ .setBody("Dit is een gelokaliseerde testmelding")));
+
+ persistNotification(
+ "Localized Alert",
+ LocalizedNotificationMessage.TYPE,
+ message,
+ userId,
+ assetId,
+ realm,
+ sentOn);
+ }
+
private void persistNotification(
String name,
String type,
diff --git a/ui/app/manager/src/components/notifications/or-notification-form.ts b/ui/app/manager/src/components/notifications/or-notification-form.ts
index ccf160c8f..608f276d0 100644
--- a/ui/app/manager/src/components/notifications/or-notification-form.ts
+++ b/ui/app/manager/src/components/notifications/or-notification-form.ts
@@ -22,11 +22,13 @@ import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { classMap } from "lit/directives/class-map.js";
import { i18next } from "@openremote/or-translate";
-import manager, { Util } from "@openremote/core";
+import manager, { DEFAULT_LANGUAGES, Util } from "@openremote/core";
import {
type Asset,
ClientRole,
type EmailNotificationMessage,
+ type LocalizedNotificationMessage,
+ type ManagerAppRealmNotificationConfig,
type Notification,
NotificationTargetType,
type PushNotificationButton,
@@ -34,6 +36,8 @@ import {
PushNotificationMessageMessagePriority,
type SentNotification,
type User,
+ getNotificationLanguages,
+ resolveNotificationMessage,
} from "@openremote/model";
import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
import type { OrAssetTree, OrAssetTreeSelectionEvent } from "@openremote/or-asset-tree";
@@ -45,7 +49,7 @@ import "@openremote/or-vaadin-components/or-vaadin-text-field";
import "@openremote/or-vaadin-components/or-vaadin-text-area";
import "@openremote/or-vaadin-components/or-vaadin-toggle";
-export type NotificationMessage = PushNotificationMessage | EmailNotificationMessage;
+type NotificationMessage = PushNotificationMessage | EmailNotificationMessage;
// Requires a scheme (e.g. https://) before the rest of the URL; shared by the actionUrl field's pattern attribute
// and the create-validation check. The hyphen is escaped so it's valid under the pattern attribute's `v` flag.
@@ -215,6 +219,13 @@ export class OrNotificationForm extends OrElement {
@state()
protected _message: NotificationMessage = { type: "push" };
+ // The language of the message being displayed; only set for a localized notification, which holds one per language
+ @state()
+ protected _messageLanguage?: string;
+
+ // The messages of a localized notification, to switch the displayed language between
+ protected _messageLanguages?: LocalizedNotificationMessage["languages"];
+
@state()
protected _targetType: NotificationTargetType = this._defaultTargetType();
@@ -249,6 +260,10 @@ export class OrNotificationForm extends OrElement {
@property({ type: String })
public realm?: string;
+ // The realm's notification config, which decides the languages a localized notification can be shown for
+ @property({ type: Object })
+ public notificationConfig?: ManagerAppRealmNotificationConfig;
+
async firstUpdated() {
// In readonly (details) mode the form only displays an existing notification's stored values; the
// asset/user/realm option lists are only used by the editable target selectors, so skip loading them.
@@ -433,7 +448,10 @@ export class OrNotificationForm extends OrElement {
private async _populateFromNotification() {
if (!this.notification) return;
- this._message = (this.notification.message || { type: "push" }) as NotificationMessage;
+ const { message, language, languages } = resolveNotificationMessage(this.notification.message, i18next.language);
+ this._message = message || { type: "push" };
+ this._messageLanguage = language;
+ this._messageLanguages = languages;
this._targetType = this.notification.target || NotificationTargetType.ASSET;
this._targets = this.notification.targetId ? [this.notification.targetId] : [];
@@ -654,6 +672,7 @@ export class OrNotificationForm extends OrElement {
>
<or-translate slot="label" value="type"></or-translate>
</or-vaadin-select>
+ ${when(this._messageLanguage, () => this._renderMessageLanguageSelect())}
${
this._message.type === "push"
? this._renderPushContent(this._message as PushNotificationMessage, inputDisabled)
@@ -663,6 +682,40 @@ export class OrNotificationForm extends OrElement {
`;
}
+ /**
+ * Picks which language of a localized notification is shown. Stays enabled while the rest of the form is
+ * readonly, as it selects between stored messages instead of editing one; a language that is supported but
+ * not translated shows empty content.
+ */
+ protected _renderMessageLanguageSelect() {
+ const items: SelectItem[] = getNotificationLanguages(this.notificationConfig, this.notification?.message).map(
+ (language) => ({
+ label: i18next.t(DEFAULT_LANGUAGES[language] || language),
+ value: language,
+ })
+ );
+
+ return html`
+ <or-vaadin-select
+ id="messageLanguage"
+ .items="${items}"
+ value="${this._messageLanguage}"
+ @change="${(ev: Event) => this._onMessageLanguageChanged((ev.currentTarget as OrVaadinSelect).value)}"
+ >
+ <or-translate slot="label" value="language"></or-translate>
+ </or-vaadin-select>
+ `;
+ }
+
+ protected _onMessageLanguageChanged(language: string) {
+ if (language === this._messageLanguage) {
+ return;
+ }
+ this._messageLanguage = language;
+ // A supported language the notification was never translated into holds no message of its own
+ this._message = (this._messageLanguages?.[language] as NotificationMessage) || { type: this._message.type };
+ }
+
protected _renderPushContent(message: PushNotificationMessage, inputDisabled: boolean) {
return html`
<or-vaadin-text-field
diff --git a/ui/app/manager/src/components/notifications/or-notifications-table.ts b/ui/app/manager/src/components/notifications/or-notifications-table.ts
index e0e02736b..242b26b28 100644
--- a/ui/app/manager/src/components/notifications/or-notifications-table.ts
+++ b/ui/app/manager/src/components/notifications/or-notifications-table.ts
@@ -32,8 +32,9 @@ import {
type EmailNotificationMessage,
NotificationTargetType,
type NotificationSource,
+ resolveNotificationMessage,
} from "@openremote/model";
-import { i18next } from "@openremote/or-translate";
+import { i18next, translate } from "@openremote/or-translate";
import { classMap } from "lit/directives/class-map.js";
import type { NotificationService } from "../../pages/page-notifications";
import { getAssetsRoute, getUsersRoute } from "../../routes";
@@ -93,7 +94,7 @@ const SORT_FIELD_BY_COLUMN: Record<number, SentNotificationSortField> = {
};
@customElement("or-notifications-table")
-export class OrNotificationsTable extends OrMwcTable {
+export class OrNotificationsTable extends translate(i18next)(OrMwcTable) {
static get styles() {
return [
...super.styles,
@@ -261,15 +262,19 @@ export class OrNotificationsTable extends OrMwcTable {
return `${targetType}:${targetId}`;
}
- public columns: TableColumn[] = [
- { title: i18next.t("title"), isSortable: true },
- { title: i18next.t("body") },
- { title: i18next.t("status"), isSortable: true },
- { title: i18next.t("notifications.source"), isSortable: true },
- { title: i18next.t("notifications.target") },
- { title: i18next.t("sentOn"), isSortable: true },
- { title: i18next.t("deliveredOn"), isSortable: true },
- ];
+ public columns: TableColumn[] = this.getColumns();
+
+ protected getColumns(): TableColumn[] {
+ return [
+ { title: i18next.t("title"), isSortable: true },
+ { title: i18next.t("body") },
+ { title: i18next.t("status"), isSortable: true },
+ { title: i18next.t("notifications.source"), isSortable: true },
+ { title: i18next.t("notifications.target") },
+ { title: i18next.t("sentOn"), isSortable: true },
+ { title: i18next.t("deliveredOn"), isSortable: true },
+ ];
+ }
protected config: TableConfig = {
columnFilter: [],
@@ -290,6 +295,10 @@ export class OrNotificationsTable extends OrMwcTable {
await this.resolveAllTargetDetails(this.notifications);
}
this.rows = this.getTableRows(this.notifications || []);
+ } else if (changedProps.has("_language")) {
+ // The column titles are translated, and a localized notification is shown for the app language
+ this.columns = this.getColumns();
+ this.rows = this.getTableRows(this.notifications || []);
}
// handle readonly state changes
@@ -302,7 +311,8 @@ export class OrNotificationsTable extends OrMwcTable {
protected getTableRows(notifications: SentNotification[]): TableRow[] | undefined {
return notifications.map((notification) => {
- const message = notification.message as PushNotificationMessage | EmailNotificationMessage;
+ // A localized notification carries a message per language, so resolve the one it is shown for
+ const { message } = resolveNotificationMessage(notification.message, i18next.language);
const isEmail = message?.type === "email";
const title = isEmail
? (message as EmailNotificationMessage).subject
@@ -313,7 +323,7 @@ export class OrNotificationsTable extends OrMwcTable {
: (message as PushNotificationMessage)?.body;
return {
content: [
- this.getTitleContent(notification, title),
+ this.getTitleContent(notification, title, message?.type),
this.getBodyContent(body),
this.getStatusContent(notification),
this.getSourceContent(notification.source),
@@ -328,7 +338,7 @@ export class OrNotificationsTable extends OrMwcTable {
});
}
- protected getTitleContent(notification: SentNotification, title?: string): TemplateResult {
+ protected getTitleContent(notification: SentNotification, title?: string, messageType?: string): TemplateResult {
const iconMap: { [type: string]: string } = {
push: "cellphone-message",
email: "email-outline",
@@ -337,7 +347,7 @@ export class OrNotificationsTable extends OrMwcTable {
// The icon is nested in its own template so the title remains the first string value used for sorting
return html`
<div class="title-wrapper">
- ${html`<or-icon class="type-icon" title="${notification.type || ""}" icon="${iconMap[notification.type] || "bell-outline"}"></or-icon>`}
+ ${html`<or-icon class="type-icon" title="${notification.type || ""}" icon="${iconMap[messageType ?? notification.type] || "bell-outline"}"></or-icon>`}
<span>${title || "-"}</span>
</div>
`;
diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.ts
index dc5fe0c03..0d610418a 100644
--- a/ui/app/manager/src/index.ts
+++ b/ui/app/manager/src/index.ts
@@ -76,7 +76,7 @@ import { pageConfigurationProvider } from "./pages/page-configuration";
import { pageAlarmsProvider } from "./pages/page-alarms";
import type { ManagerAppConfig } from "@openremote/model";
import { pageGatewayTunnelProvider } from "./pages/page-gateway-tunnel";
-import { pageNotificationsProvider } from "./pages/page-notifications";
+import { type PageNotificationsConfig, pageNotificationsProvider } from "./pages/page-notifications";
import "./pages/page-notifications";
declare let MANAGER_URL: string | undefined;
@@ -195,6 +195,10 @@ fetch(configURL)
appConfig.manager.applyConfigToAdmin !== undefined ? appConfig.manager.applyConfigToAdmin : true;
if ((!isAdmin || applyConfigToAdmin) && appConfig.pages) {
+ // The rules and notifications pages both read the notification languages each realm supports
+ const notificationConfigs = Object.fromEntries(
+ Object.entries(appConfig.realms || {}).map(([realm, realmConfig]) => [realm, realmConfig.notifications])
+ );
// Replace any supplied page configs
pages = pages.map((pageProvider) => {
const config: { [p: string]: any } | undefined = appConfig.pages[pageProvider.name];
@@ -213,13 +217,19 @@ fetch(configURL)
rules: {},
}) as PageRulesConfig;
if (!newConfig.rules?.notifications) {
- newConfig.rules.notifications = Object.fromEntries(
- Object.entries(appConfig.realms).map((entry) => [entry[0], entry[1].notifications])
- );
+ newConfig.rules.notifications = notificationConfigs;
}
pageProvider = pageRulesProvider(store, newConfig);
break;
}
+ case "notifications": {
+ const newConfig = (config || {}) as PageNotificationsConfig;
+ if (!newConfig.notifications) {
+ newConfig.notifications = notificationConfigs;
+ }
+ pageProvider = pageNotificationsProvider(store, newConfig);
+ break;
+ }
case "insights": {
pageProvider = config ? pageInsightsProvider(store, config as PageInsightsConfig) : pageProvider;
break;
diff --git a/ui/app/manager/src/pages/page-notifications.ts b/ui/app/manager/src/pages/page-notifications.ts
index e9a2870be..6159090d5 100644
--- a/ui/app/manager/src/pages/page-notifications.ts
+++ b/ui/app/manager/src/pages/page-notifications.ts
@@ -28,7 +28,9 @@ import {
NotificationTargetType,
type SentNotification,
SentNotificationSortField,
+ type ManagerAppRealmNotificationConfig,
type User,
+ getRealmNotificationConfig,
} from "@openremote/model";
import manager, { DefaultColor3 } from "@openremote/core";
import { i18next } from "@openremote/or-translate";
@@ -191,6 +193,7 @@ export interface PageNotificationsConfig {
targetType?: string;
fromTimestamp?: number;
toTimestamp?: number;
+ notifications?: { [realm: string]: ManagerAppRealmNotificationConfig };
}
export function pageNotificationsProvider(
@@ -201,7 +204,7 @@ export function pageNotificationsProvider(
name: "notifications",
routes: ["notifications"],
pageCreator: () => {
- return new PageNotifications(store);
+ return new PageNotifications(store, config);
},
};
}
@@ -340,7 +343,10 @@ export class PageNotifications extends Page<AppStateKeyed> {
protected notificationService: NotificationService;
- constructor(store: Store<AppStateKeyed>) {
+ constructor(
+ store: Store<AppStateKeyed>,
+ protected config?: PageNotificationsConfig
+ ) {
super(store);
this.notificationService = new NotificationService();
@@ -591,7 +597,13 @@ export class PageNotifications extends Page<AppStateKeyed> {
protected _renderDetailsForm(notification?: SentNotification) {
return html`
- <or-notification-form .realm=${this.realm} .notification=${notification} readonly> </or-notification-form>
+ <or-notification-form
+ .realm="${this.realm}"
+ .notification="${notification}"
+ .notificationConfig="${getRealmNotificationConfig(this.config?.notifications, this.realm)}"
+ readonly
+ >
+ </or-notification-form>
`;
}
diff --git a/ui/app/manager/test/fixtures/manager.ts b/ui/app/manager/test/fixtures/manager.ts
index 33426ea91..f1ef457ba 100644
--- a/ui/app/manager/test/fixtures/manager.ts
+++ b/ui/app/manager/test/fixtures/manager.ts
@@ -137,6 +137,16 @@ export class Manager {
await menu.click();
}
+ /**
+ * Switch the app language using the language dialog in the settings menu at the top right.
+ * This also stores it as the user's locale, so reset it with {@link resetLocale} afterwards.
+ * @param language Name of the language as the dialog lists it, in the current app language
+ */
+ async switchLanguage(language: string) {
+ await this.navigateToMenuItem("Language");
+ await this.page.locator("or-vaadin-list-box:visible").getByRole("option").filter({ hasText: language }).click();
+ }
+
/**
* Switch to a realm using the realm picker
* @param name Name of the realm
diff --git a/ui/app/manager/test/fixtures/pages/notifications.ts b/ui/app/manager/test/fixtures/pages/notifications.ts
index 08fc0f370..6c3bde802 100644
--- a/ui/app/manager/test/fixtures/pages/notifications.ts
+++ b/ui/app/manager/test/fixtures/pages/notifications.ts
@@ -191,6 +191,12 @@ export class NotificationsPage implements BasePage {
.locator("input, textarea");
}
+ /** Pick the language a localized notification's content is shown for (by visible label). */
+ async selectMessageLanguage(label: string) {
+ await this.getDetailsForm().locator("#messageLanguage").click();
+ await this.pickOverlayOption(label);
+ }
+
/** Open the details dialog for the (first) row containing the given text. */
async openDetailsByText(text: string) {
await this.getRowByText(text).first().click();
diff --git a/ui/app/manager/test/notifications.test.ts b/ui/app/manager/test/notifications.test.ts
index 1b335391d..0e5241bd7 100644
--- a/ui/app/manager/test/notifications.test.ts
+++ b/ui/app/manager/test/notifications.test.ts
@@ -16,16 +16,19 @@
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
-import { expect } from "@openremote/test";
+import { type Page, expect } from "@openremote/test";
import {
type Asset,
ClientRole,
type EmailNotificationMessage,
+ type LocalizedNotificationMessage,
type Notification,
NotificationTargetType,
+ type PushNotificationMessage,
} from "@openremote/model";
import type { AxiosRequestConfig } from "axios";
import { type Manager, adminStatePath, test } from "./fixtures/manager.js";
+import { users } from "./fixtures/data/users.js";
test.use({ storageState: adminStatePath });
@@ -129,6 +132,45 @@ async function createConsoleForUser(
await linkUsersToAsset(manager, realm, consoleId, [userId], config);
}
+/**
+ * Serve the manager app config with `languages` declared for the realm's notifications, the way a deployment
+ * states which languages its notifications support, without persisting a config the other specs would see.
+ */
+async function withNotificationLanguages(page: Page, realm: string, languages: string[]) {
+ await page.route("**/api/master/configuration/manager", async (route) => {
+ const response = await route.fetch();
+ const config = await response.json();
+ config.realms = { ...config.realms, [realm]: { ...config.realms?.[realm], notifications: { languages } } };
+ await route.fulfill({ response, json: config });
+ });
+}
+
+/**
+ * Persist a localized notification via REST, holding the given message per language, for a freshly provisioned
+ * user with an email and a push-registered console, so a message of either type resolves to a target.
+ */
+async function seedLocalizedNotification(
+ manager: Manager,
+ defaultLanguage: string,
+ languages: { [language: string]: PushNotificationMessage | EmailNotificationMessage },
+ stamp: number
+) {
+ const config = await manager.adminConfig();
+ const username = `e2e-localized-${stamp}`;
+ const user = await manager.provisionUser("master", { username, email: `${username}@openremote.local` }, config);
+ expect(user?.id).toBeTruthy();
+ await createConsoleForUser(manager, "master", user!.id!, username, config);
+
+ await manager.api.NotificationResource.sendNotification(
+ {
+ name: username,
+ message: { type: "localized", defaultLanguage, languages } as LocalizedNotificationMessage,
+ targets: [{ type: NotificationTargetType.USER, id: user!.id! }],
+ } as Notification,
+ config
+ );
+}
+
/** Format a Date as the local `YYYY-MM-DDTHH:mm` string the date-range pickers use. */
function pickerValue(d: Date): string {
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
@@ -273,6 +315,158 @@ test("should show the correct data in the notification details dialog", async ({
await expect(details).not.toBeVisible();
});
+test.describe("Localized Notifications", () => {
+ // A notification can hold a language it was never translated into; the push handler rejects a message
+ // without a title or data, so such a language can only carry data.
+ const untranslated: PushNotificationMessage = { type: "push", data: {} };
+
+ // Switching the language through the UI also stores it as the user's locale, which the other specs expect in English
+ test.afterEach(async ({ manager }) => {
+ await manager.resetLocale("master", "admin", users.admin.password);
+ });
+
+ /**
+ * @given Logged into the "master" realm as "admin"
+ * @and A localized notification translated into English (its default language) and Dutch, supporting German
+ * @when Navigated to the "Notifications" page
+ * @then The row shows the English message
+ * @when The manager language is switched to Dutch
+ * @then The row shows the Dutch message, under the icon of the message's own type
+ * @when The details dialog is opened and another language is selected
+ * @then The content follows the selected language, and German shows as untranslated
+ */
+ test("should show the user's language and switch language in the details dialog", async ({
+ manager,
+ notificationsPage,
+ }) => {
+ const stamp = Date.now();
+ const enTitle = `E2E localized en ${stamp}`;
+ const nlTitle = `E2E localized nl ${stamp}`;
+ await seedLocalizedNotification(
+ manager,
+ "en",
+ {
+ en: { type: "push", title: enTitle, body: "English body" },
+ nl: { type: "push", title: nlTitle, body: "Nederlandse tekst" },
+ de: untranslated,
+ },
+ stamp
+ );
+
+ await manager.goToRealmStartPage("master");
+ await notificationsPage.goto();
+ await expect(notificationsPage.getRowByText(enTitle)).toBeVisible();
+
+ await manager.switchLanguage("Dutch");
+ // the column titles follow the switch too, which shows it has been applied
+ await expect(notificationsPage.getTable()).toContainText("Gestuurd op");
+
+ // the viewer's language is translated, so the row shows it instead of the default language, and follows a
+ // language switch without reloading the page
+ const row = notificationsPage.getRowByText(nlTitle);
+ await expect(row).toBeVisible();
+ await expect(row).toContainText("Nederlandse tekst");
+ await expect(notificationsPage.getRowByText(enTitle)).toHaveCount(0);
+
+ // the title and body used to be empty, and the icon fell back to the generic bell, as "localized" is
+ // neither of the message types the table knew
+ await expect(row.locator("or-icon.type-icon")).toHaveAttribute("icon", "cellphone-message");
+
+ await notificationsPage.openDetailsByText(nlTitle);
+ const details = notificationsPage.getDetailsForm();
+ await expect(details.locator("#notificationTitle input")).toHaveValue(nlTitle);
+
+ // the dialog switches language (its labels are Dutch here, as the app is)
+ await notificationsPage.selectMessageLanguage("Engels");
+ await expect(details.locator("#notificationTitle input")).toHaveValue(enTitle);
+ await expect(details.locator("#notificationBody textarea")).toHaveValue("English body");
+
+ // a supported language without a translation has nothing to show
+ await notificationsPage.selectMessageLanguage("Duits");
+ await expect(details.locator("#notificationTitle input")).toHaveValue("");
+ await expect(details.locator("#notificationBody textarea")).toHaveValue("");
+ });
+
+ /**
+ * @given Logged into the "master" realm as "admin", with the manager language switched to Dutch
+ * @and A localized notification translated into English only, in a realm whose config supports Dutch too
+ * @when Navigated to the "Notifications" page and the details dialog is opened
+ * @then English is shown, and the Dutch the realm supports can be selected to see it carries no message
+ */
+ test("should offer the languages the realm supports but the notification never held", async ({
+ manager,
+ notificationsPage,
+ page,
+ }) => {
+ const stamp = Date.now();
+ const enTitle = `E2E realm languages ${stamp}`;
+ await seedLocalizedNotification(
+ manager,
+ "en",
+ { en: { type: "push", title: enTitle, body: "English body" } },
+ stamp
+ );
+ await withNotificationLanguages(page, "master", ["en", "nl"]);
+
+ await manager.goToRealmStartPage("master");
+ await notificationsPage.goto();
+ await manager.switchLanguage("Dutch");
+ await expect(notificationsPage.getTable()).toContainText("Gestuurd op");
+ await notificationsPage.openDetailsByText(enTitle);
+ const details = notificationsPage.getDetailsForm();
+
+ // the notification only holds English, so that is shown although the app is Dutch
+ await expect(details.locator("#notificationTitle input")).toHaveValue(enTitle);
+
+ // Dutch is offered because the realm supports it, and shows that the notification has no Dutch message
+ await notificationsPage.selectMessageLanguage("Nederlands");
+ await expect(details.locator("#notificationTitle input")).toHaveValue("");
+ });
+
+ /**
+ * @given Logged into the "master" realm as "admin", with the manager language switched to Dutch
+ * @and A localized email translated into English (its default language) only, holding Dutch
+ * @when Navigated to the "Notifications" page
+ * @then The row shows the English message, as the viewer's language has no translation
+ * @and The details dialog opens on English and shows Dutch as untranslated
+ */
+ test("should show the default language when the user's language has no translation", async ({
+ manager,
+ notificationsPage,
+ }) => {
+ const stamp = Date.now();
+ const enSubject = `E2E default only ${stamp}`;
+ await seedLocalizedNotification(
+ manager,
+ "en",
+ // the email handler accepts any email message, so the untranslated language carries nothing at all
+ { en: { type: "email", subject: enSubject, html: "<p>English body</p>" }, nl: { type: "email" } },
+ stamp
+ );
+
+ await manager.goToRealmStartPage("master");
+ await notificationsPage.goto();
+ await manager.switchLanguage("Dutch");
+ await expect(notificationsPage.getTable()).toContainText("Gestuurd op");
+
+ // the default language stands in for the viewer's untranslated one, rather than showing an empty row
+ const row = notificationsPage.getRowByText(enSubject);
+ await expect(row).toBeVisible();
+ await expect(row).toContainText("English body");
+ await expect(row.locator("or-icon.type-icon")).toHaveAttribute("icon", "email-outline");
+
+ await notificationsPage.openDetailsByText(enSubject);
+ const details = notificationsPage.getDetailsForm();
+ await expect(details.locator("#notificationSubject input")).toHaveValue(enSubject);
+ await expect(details.locator("#notificationEmailBody textarea")).toHaveValue("<p>English body</p>");
+
+ // the untranslated language is still offered, and shows that it carries no message
+ await notificationsPage.selectMessageLanguage("Nederlands");
+ await expect(details.locator("#notificationSubject input")).toHaveValue("");
+ await expect(details.locator("#notificationEmailBody textarea")).toHaveValue("");
+ });
+});
+
/**
* @given Logged into the "master" realm as "admin"
* @and Three notifications seeded via REST: a plain send, one marked delivered, and one whose send failed
diff --git a/ui/component/model/src/index.ts b/ui/component/model/src/index.ts
index af081e3c1..6ac8e9b0a 100644
--- a/ui/component/model/src/index.ts
+++ b/ui/component/model/src/index.ts
@@ -18,3 +18,4 @@
*/
export * from "./model";
export { AssetModelUtil } from "./util";
+export * from "./notification";
diff --git a/ui/component/model/src/notification.ts b/ui/component/model/src/notification.ts
new file mode 100644
index 000000000..bbffceeca
--- /dev/null
+++ b/ui/component/model/src/notification.ts
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+import type {
+ AbstractNotificationMessageUnion,
+ LocalizedNotificationMessage,
+ ManagerAppRealmNotificationConfig,
+} from "./model";
+
+/** The notification config of `realm`, falling back to the `default` entry that stands in for every realm. */
+export function getRealmNotificationConfig(
+ configs?: { [realm: string]: ManagerAppRealmNotificationConfig | undefined },
+ realm?: string
+): ManagerAppRealmNotificationConfig | undefined {
+ return (realm ? configs?.[realm] : undefined) || configs?.default;
+}
+
+/**
+ * Every language a localized message can be shown for: those the realm supports and those the message holds,
+ * which can differ as the supported languages change independently of the messages already sent.
+ */
+export function getNotificationLanguages(
+ config?: ManagerAppRealmNotificationConfig,
+ message?: AbstractNotificationMessageUnion
+): string[] {
+ const held = message?.type === "localized" ? Object.keys(message.languages || {}) : [];
+ return [...new Set([...(config?.languages || []), ...held])];
+}
+
+/** Whether a message has anything to show; a language that is supported but not translated has not. */
+function isTranslated(message?: AbstractNotificationMessageUnion): boolean {
+ switch (message?.type) {
+ case "email":
+ return !!(message.subject || message.html || message.text);
+ case "push":
+ return !!(message.title || message.body);
+ default:
+ return false;
+ }
+}
+
+/**
+ * Resolves what to show for a stored message, and for a localized one the language shown and every language it
+ * holds. A localized message keeps its content per language under `languages`, so show `language` (the viewer's)
+ * when that language is translated, and otherwise the message's `defaultLanguage`, which is what a target
+ * without a locale of its own receives.
+ */
+export function resolveNotificationMessage(
+ message?: AbstractNotificationMessageUnion,
+ language?: string
+): {
+ message?: Exclude<AbstractNotificationMessageUnion, LocalizedNotificationMessage>;
+ language?: string;
+ languages?: LocalizedNotificationMessage["languages"];
+} {
+ if (message?.type !== "localized") {
+ return { message };
+ }
+ const languages = message.languages || {};
+ const codes = Object.keys(languages);
+ // Fall through to any translated language, then to an untranslated one, so a language is always named
+ const resolved =
+ [language, message.defaultLanguage, ...codes].find((code) => code && isTranslated(languages[code])) ||
+ (message.defaultLanguage && languages[message.defaultLanguage] ? message.defaultLanguage : codes[0]);
+
+ return {
+ message: resolved
+ ? (languages[resolved] as Exclude<AbstractNotificationMessageUnion, LocalizedNotificationMessage>)
+ : undefined,
+ language: resolved,
+ languages,
+ };
+}
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index fa61fa63e..749538809 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -40,6 +40,7 @@ import {
ClientRole,
type JsonRule,
type LogicGroup,
+ type ManagerAppRealmNotificationConfig,
type NotificationTargetType,
type RuleActionUnion,
type RuleCondition,
@@ -165,12 +166,7 @@ export interface RulesConfig {
then?: RuleActionUnion;
otherwise?: RuleActionUnion;
};
- notifications?: {
- [realm: string]: {
- defaultLanguage?: string;
- languages?: string[];
- };
- };
+ notifications?: { [realm: string]: ManagerAppRealmNotificationConfig };
}
export interface RulesDescriptorSection {
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
index e3b26abc8..6246c6d29 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
@@ -34,6 +34,8 @@ import {
type PushNotificationMessage,
type EmailNotificationMessage,
type LocalizedNotificationMessage,
+ getNotificationLanguages,
+ getRealmNotificationConfig,
} from "@openremote/model";
import { getTargetTypeMap, OrRulesJsonRuleChangedEvent } from "./or-rule-json-viewer";
import "./or-rule-json-dialog";
@@ -116,8 +118,7 @@ export class OrRuleActionNotification extends OrElement {
const message = this.action.notification.message;
if (message?.type === "localized") {
const locale =
- this.config?.notifications?.[manager.displayRealm]?.defaultLanguage ||
- this.config?.notifications?.default?.defaultLanguage ||
+ getRealmNotificationConfig(this.config?.notifications, manager.displayRealm)?.defaultLanguage ||
manager.config.defaultLanguage!;
const msg = message.languages?.[locale]; // if localized, we use the default language
if (msg?.type === "push") {
@@ -464,14 +465,8 @@ export class OrRuleActionNotification extends OrElement {
</or-rule-json-dialog>
`;
} else if (messageType === "localized") {
- const notificationConfig =
- this.config?.notifications?.[manager.displayRealm] || this.config?.notifications?.default;
- const languages = [
- ...new Set([
- ...(notificationConfig?.languages || []),
- ...(Object.keys((message as LocalizedNotificationMessage).languages || {}) || []),
- ]),
- ] as string[];
+ const notificationConfig = getRealmNotificationConfig(this.config?.notifications, manager.displayRealm);
+ const languages = getNotificationLanguages(notificationConfig, message);
const defaultLang = notificationConfig?.defaultLanguage || manager.config.defaultLanguage;
if (languages.length === 0 && defaultLang) {
languages.push(defaultLang);