100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Feature: Notification management (#2673)
Koenfd04e4bcb6d6
diff --git a/AGENTS.md b/AGENTS.mdindex 94490f723..551a838ba 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -3,7 +3,7 @@## DB update scriptsFlyway is used to automate execution of DB update scripts.-When naming scripts, use \<date>_\<time> as version number, date being YYYYMMDD and time being HHmm in UTC e.g. `v20260611_0755__Changes.sql`+When naming scripts, use \<date>_\<time> as version number, date being YYYYMMDD and time being HHmm in UTC e.g. `V20260611_0755__Changes.sql` (the `V` prefix is required by Flyway and must be uppercase)## Dev environmentThe backend is written in Java, we target JDK 21, use modern language features up to that version during implementation.@@ -21,6 +21,14 @@ Running `./gradlew clean` deletes the root `tmp/` directory that is mounted into`ui/component/model/src/model.ts` is generated from the Java backend by typescript-generator. Do not edit it by hand. When a TypeScript type mirrors a backend class, import it from `@openremote/model` instead of redeclaring a local interface. Regenerate it from the backend rather than patching the output.+### Base element++Own Lit components extend `OrElement` from `@openremote/or-element` instead of `LitElement` (also through mixins, e.g. `translate(i18next)(OrElement)`). It applies the shared shadow-DOM styling automatically. Vaadin wrappers are exempt; they extend their Vaadin base and are themed via Lumo.++### Adding a new component package++New packages under `ui/component/` are picked up automatically by the yarn workspace and by Gradle (any dir with a `build.gradle`). The rsbuild apps are not automatic: add the package to the `@openremote/*` alias maps in `ui/app/manager/rsbuild.config.ts` and `ui/app/storybook/rsbuild.config.ts`, which resolve workspace packages to their `src` dirs. A missing entry fails the build with "Module not found" for any file importing the package.+### Adding a new Vaadin componentVaadin-based components live in `ui/component/or-vaadin-components/src/` as thin wrappers that extend a Vaadin class and re-register it under an `or-vaadin-<name>` tag, e.g. `export class OrVaadinX extends (X as new () => X & LitElement)` with `@customElement("or-vaadin-x")`. Keep all `@vaadin/*` dependency versions aligned.@@ -54,8 +62,26 @@ Storybook covers any component under `ui/component/` (e.g. `or-chart`, `or-map`,Stories call `getORStorybookHelpers(tagName)` (from `ui/component/storybook-utils.js`) and `setCustomElementsManifest(customElements)` off the package's own `../custom-elements.json`. That manifest is generated per-package by `npm run analyze` (cem), so a newly added component will render but show no args/argTypes/description until you regenerate its package's manifest. `custom-elements.json` (and `custom-elements-jsx.d.ts`) are generated and untracked.+### Writing UI tests++- **Test Naming:** `test.describe` blocks describe a feature. Tests should be named starting with "should ...".+- **Test Structure:** Keep tests flat by default. Omit top-level `test.describe` blocks. If grouping is needed, target a specific feature (e.g., filtering notifications) rather than a parent concept like the whole page. Example: `test.describe("Filter Notifications", ...)` instead of `test.describe("Notifications", ...)`.++#### Fixtures++- **Avoid Redundant Actions:** Do not create methods in fixtures that simply wrap native Playwright actions (e.g., `click()`, `getByRole()`, `expect()`). Use native Playwright actions directly in the tests where possible.+- **Provide Locators:** Provide fixture methods for locators with non-standard or complex paths (e.g., reliant on specific DOM structures) so others can reuse the correct locators across tests.++#### App tests++- **Compilation:** Run `./gradlew clean installDist` after making changes to the UI source code to ensure they are applied before testing.+- **Location:** Define tests in `ui/app/<app-name>/test/`. Define fixtures in `ui/app/<app-name>/test/fixtures/`.+- **Comments:** Add scenario comments above tests (`@given`, `@when`, `@then`, `@and`) based on the acceptance criteria.+- **Auth State:** Select correct `storageState` for the task to be tested. Use `adminStatePath` for master/admin tasks. Use `userStatePath` for regular realm user tasks.++#### Component testing-### Component testing+- **Location:** Define tests in `ui/component/<component-name>/test/`. Define fixtures in `ui/component/<component-name>/test/fixtures/`.Component tests use Playwright component testing (`@sand4rt/experimental-ct-web`). They live in each package's `test/*.test.ts`, import `{ ct, expect }` from `@openremote/test`, and `mount(ComponentClass, { props, slots, on })`. Run them with `npm test` in the package (which does `tsc -b && playwright test`). CI runs `./gradlew -p ui/component npmTest`, which only executes packages that register an `npmTest` task, so when adding the first test to a package also register `npmTest` (and `npmTestUI`) in its `build.gradle` file; copy the tasks from a sibling package. Prefer web-first, role-based assertions (`getByRole("checkbox", { name }).toBeChecked()`, `toHaveCount(...)`) over poking at JS properties (`toHaveJSProperty`) or internal locators. Some important quirks to know about:@@ -67,3 +93,4 @@ Component tests use Playwright component testing (`@sand4rt/experimental-ct-web`- **The default slot must be an array of single-element strings.** The CT runner builds each slot via `createContextualFragment(str).firstChild`, so a single string containing multiple elements silently keeps only the first; pass `slots: { default: ["<a>…</a>", "<b>…</b>"] }`.- **Vaadin's `theme` is attribute-only.** `ThemePropertyMixin` derives a read-only `_theme` from the `theme` *attribute*; there is no writable reflecting `theme` property. So `mount(..., { props: { theme: "vertical" } })` sets an ignored JS property and the `:host([theme~='vertical'])` styles never apply (e.g. a "vertical" checkbox-group stays horizontal). Set it as an attribute instead: `await component.evaluate((el) => el.setAttribute("theme", "vertical"))`. (In Storybook/Lit templates `theme="vertical"` is already a real attribute, so it works there.)- The `on` handler type is `Record<string, Function>`, so typed handler params are fine.+- **Mounted component sources must be JavaScript.** The CT bundle compiles `.ts` against `ui/test/tsconfig.json` (`rootDir` `ui/test`), so a TS component file anywhere else fails with TS6059. Mount components from the package's built lib, or write test-only fixture elements as plain `.js` (no decorators; register with `customElements.define`).diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.javaindex 9f5522ef2..75e2aef6a 100644--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java@@ -1,5 +1,5 @@/*- * Copyright 2018, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -58,6 +58,7 @@ public class EmailNotificationHandler implements NotificationHandler {protected Map<String, String> headers;protected ManagerIdentityService managerIdentityService;protected AssetStorageService assetStorageService;+ protected boolean devMode;@Overridepublic int getPriority() {@@ -69,6 +70,7 @@ public class EmailNotificationHandler implements NotificationHandler {managerIdentityService = container.getService(ManagerIdentityService.class);assetStorageService = container.getService(AssetStorageService.class);+ devMode = container.isDevMode();// Configure SMTPString host = container.getConfig().getOrDefault(OR_EMAIL_HOST, null);@@ -176,7 +178,8 @@ public class EmailNotificationHandler implements NotificationHandler {@Overridepublic boolean isValid() {- return mailTransport != null;+ // In dev mode the handler is always valid so notifications are processed and persisted even without SMTP config+ return mailTransport != null || devMode;}@Override@@ -308,6 +311,13 @@ public class EmailNotificationHandler implements NotificationHandler {if (!addresses.isEmpty()) {mappedTargets.add(new Notification.Target(Notification.TargetType.CUSTOM, String.join(";", addresses)));}++ if (devMode && mappedTargets.isEmpty() && targets != null && !targets.isEmpty()) {+ // Keep the no-targets behaviour identical to production but make the dropped notification visible+ LOG.info("Dev mode: no email recipients mapped for email notification, original targets=["+ + targets.stream().map(Object::toString).collect(Collectors.joining(",")) + "], message=" + message);+ }+return mappedTargets;}@@ -394,6 +404,11 @@ public class EmailNotificationHandler implements NotificationHandler {}protected void sendMessage(Message email) throws Exception {+ if (devMode && mailTransport == null) {+ // SMTP not configured; log the notification instead of sending so the sent record is still created+ LOG.info("Dev mode: SMTP not configured so skipping email notification send: " + email);+ return;+ }if (!mailTransport.isConnected()) {mailTransport.connect();}diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.javaindex 7678a3a7f..d545275b3 100644--- a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java@@ -1,5 +1,5 @@/*- * Copyright 2017, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -20,22 +20,30 @@package org.openremote.manager.notification;import com.fasterxml.jackson.databind.JsonNode;+import org.openremote.container.message.MessageBrokerService;+import org.openremote.container.security.AuthContext;import org.openremote.container.web.WebResource;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.Constants;import org.openremote.model.asset.Asset;import org.openremote.model.http.RequestParams;+import org.openremote.model.notification.AbstractNotificationMessage;+import org.openremote.model.notification.LocalizedNotificationMessage;import org.openremote.model.notification.Notification;import org.openremote.model.notification.NotificationResource;+import org.openremote.model.notification.PushNotificationMessage;import org.openremote.model.notification.SentNotification;import org.openremote.model.query.AssetQuery;import org.openremote.model.util.ValueUtil;import jakarta.ws.rs.WebApplicationException;++import java.time.Instant;import java.util.Collections;import java.util.HashMap;+import java.util.List;import java.util.Map;import java.util.logging.Logger;@@ -62,30 +70,37 @@ public class NotificationResourceImpl extends WebResource implements Notificatio}@Override- public SentNotification[] getNotifications(RequestParams requestParams, Long id, String type, Long fromTimestamp, Long toTimestamp, String realmId, String userId, String assetId) {+ public SentNotification[] getNotifications(RequestParams requestParams, Long id, String type, Long from, Long to, String realmId, String userId, String assetId, Notification.Source source, SentNotification.SortField sort, Boolean descending, Integer offset, Integer limit) {+ AuthContext authContext = getAuthContext();+ realmId = resolveAndAuthoriseRealm(authContext, realmId);+try {- return notificationService.getNotifications(+ List<SentNotification> notifications = notificationService.getNotifications(id != null ? Collections.singletonList(id) : null,type != null ? Collections.singletonList(type) : null,- fromTimestamp,- toTimestamp,+ from != null ? Instant.ofEpochMilli(from) : null,+ to != null ? Instant.ofEpochMilli(to) : null,realmId != null ? Collections.singletonList(realmId) : null,userId != null ? Collections.singletonList(userId) : null,- assetId != null ? Collections.singletonList(assetId) : null- ).toArray(new SentNotification[0]);+ assetId != null ? Collections.singletonList(assetId) : null,+ source, sort, descending != null && descending, offset, limit, authContext,+ managerIdentityService.getIdentityProvider().isRestrictedUser(authContext)+ );+ sanitiseNotifications(notifications, authContext);+ return notifications.toArray(new SentNotification[0]);} catch (IllegalArgumentException e) {throw new WebApplicationException("Invalid criteria set", BAD_REQUEST);}}@Override- public void removeNotifications(RequestParams requestParams, Long id, String type, Long fromTimestamp, Long toTimestamp, String realmId, String userId, String assetId) {+ public void removeNotifications(RequestParams requestParams, Long id, String type, Long from, Long to, String realmId, String userId, String assetId) {try {notificationService.removeNotifications(id != null ? Collections.singletonList(id) : null,type != null ? Collections.singletonList(type) : null,- fromTimestamp,- toTimestamp,+ from != null ? Instant.ofEpochMilli(from) : null,+ to != null ? Instant.ofEpochMilli(to) : null,realmId != null ? Collections.singletonList(realmId) : null,userId != null ? Collections.singletonList(userId) : null,assetId != null ? Collections.singletonList(assetId) : null);@@ -169,7 +184,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatiothrow new WebApplicationException("Anonymous request can only update public assets", FORBIDDEN);}- // Check asset is public read amd not linked to any users+ // Check asset is public read and not linked to any usersAsset<?> asset = assetStorageService.find(sentNotification.getTargetId(), false, AssetQuery.Access.PUBLIC);if (asset == null) {LOG.fine("DENIED: Anonymous request to update a notification sent to an asset that doesn't exist or isn't public");@@ -218,4 +233,112 @@ public class NotificationResourceImpl extends WebResource implements Notificatio}}}++ @Override+ public long getNotificationsCount(RequestParams requestParams, String type, Long from, Long to, String realmId, String userId, String assetId, Notification.Source source) {+ AuthContext authContext = getAuthContext();+ realmId = resolveAndAuthoriseRealm(authContext, realmId);++ try {+ return notificationService.getNotificationsCount(+ type != null ? Collections.singletonList(type) : null,+ from != null ? Instant.ofEpochMilli(from) : null,+ to != null ? Instant.ofEpochMilli(to) : null,+ realmId != null ? Collections.singletonList(realmId) : null,+ userId != null ? Collections.singletonList(userId) : null,+ assetId != null ? Collections.singletonList(assetId) : null,+ source, authContext,+ managerIdentityService.getIdentityProvider().isRestrictedUser(authContext)+ );+ } catch (IllegalArgumentException e) {+ throw new WebApplicationException("Invalid criteria set", BAD_REQUEST);+ }+ }++ /**+ * Resolves the realm to query and verifies the caller may access it. Superusers may query any realm (or all+ * realms when {@code realmId} is null); other callers default to their own realm and may not query a realm they+ * cannot access (which would otherwise let them read another realm's notifications by passing its ID).+ */+ protected String resolveAndAuthoriseRealm(AuthContext authContext, String realmId) {+ if (authContext == null || authContext.isSuperUser()) {+ return realmId;+ }+ if (realmId == null) {+ return authContext.getAuthenticatedRealmName();+ }+ if (!managerIdentityService.getIdentityProvider().isRealmActiveAndAccessible(authContext, realmId)) {+ throw new WebApplicationException("Realm '" + realmId + "' is nonexistent, inactive or inaccessible", FORBIDDEN);+ }+ return realmId;+ }++ /**+ * Strips data the caller isn't allowed to see: user IDs (CLIENT source, USER target) and CUSTOM target IDs+ * (which can contain email addresses) without read:users, asset IDs (ASSET_RULESET source, ASSET target)+ * without read:assets. REALM_RULESET source IDs are realm+ * names and stay visible; realm access is enforced separately. Delivery details stored on the message after+ * handler resolution (push device tokens) are stripped for every caller.+ */+ protected void sanitiseNotifications(List<SentNotification> notifications, AuthContext authContext) {+ boolean canReadUsers = authContext != null && (authContext.isSuperUser()+ || authContext.hasResourceRole(Constants.READ_ADMIN_ROLE, Constants.KEYCLOAK_CLIENT_ID)+ || authContext.hasResourceRole(Constants.READ_USERS_ROLE, Constants.KEYCLOAK_CLIENT_ID));+ boolean canReadAssets = authContext != null && (authContext.isSuperUser()+ || authContext.hasResourceRole(Constants.READ_ADMIN_ROLE, Constants.KEYCLOAK_CLIENT_ID)+ || authContext.hasResourceRole(Constants.READ_ASSETS_ROLE, Constants.KEYCLOAK_CLIENT_ID));++ notifications.forEach(n -> sanitiseNotification(n, canReadUsers, canReadAssets));+ }++ protected void sanitiseNotification(SentNotification n, boolean canReadUsers, boolean canReadAssets) {+ sanitiseMessage(n.getMessage());++ if (!canReadUsers) {+ if (n.getSource() == Notification.Source.CLIENT) {+ redactErrorId(n, n.getSourceId());+ n.setSourceId(null);+ }+ // Custom targets can carry raw email addresses+ if (n.getTarget() == Notification.TargetType.USER || n.getTarget() == Notification.TargetType.CUSTOM) {+ redactErrorId(n, n.getTargetId());+ n.setTargetId(null);+ }+ }+ if (!canReadAssets) {+ if (n.getSource() == Notification.Source.ASSET_RULESET) {+ redactErrorId(n, n.getSourceId());+ n.setSourceId(null);+ }+ if (n.getTarget() == Notification.TargetType.ASSET) {+ redactErrorId(n, n.getTargetId());+ n.setTargetId(null);+ }+ }+ }++ /**+ * Redacts a stripped id (asset/user id or custom email address) from the stored error message, which+ * handlers embed verbatim (e.g. "No recipients set for asset: {id}"). The error text is kept so the row+ * still reports as failed.+ */+ protected void redactErrorId(SentNotification n, String id) {+ if (n.getError() != null && id != null && !id.isEmpty()) {+ n.setError(n.getError().replace(id, "***"));+ }+ }++ /**+ * Removes delivery-only fields from a stored message: push messages carry the resolved FCM device token in+ * their target after sending, which must never leave the server. Recurses into localized messages.+ */+ protected void sanitiseMessage(AbstractNotificationMessage message) {+ if (message instanceof PushNotificationMessage pushMessage) {+ pushMessage.setTarget(null);+ pushMessage.setTargetType(null);+ } else if (message instanceof LocalizedNotificationMessage localizedMessage && localizedMessage.getMessages() != null) {+ localizedMessage.getMessages().values().forEach(this::sanitiseMessage);+ }+ }+}diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.javaindex 5464c156e..abd6f4667 100644--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java@@ -1,5 +1,5 @@/*- * Copyright 2017, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -21,6 +21,7 @@ package org.openremote.manager.notification;import jakarta.persistence.Query;import jakarta.persistence.TypedQuery;+import org.apache.camel.Exchange;import org.apache.camel.builder.RouteBuilder;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.persistence.PersistenceService;@@ -29,11 +30,15 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;+import org.openremote.manager.event.ClientEventService;import org.openremote.model.Constants;import org.openremote.model.Container;import org.openremote.model.ContainerService;import org.openremote.model.asset.Asset;+import org.openremote.model.event.shared.EventSubscription;+import org.openremote.model.event.shared.RealmFilter;import org.openremote.model.notification.Notification;+import org.openremote.model.notification.NotificationEvent;import org.openremote.model.notification.NotificationSendResult;import org.openremote.model.notification.RepeatFrequency;import org.openremote.model.notification.SentNotification;@@ -69,6 +74,7 @@ public class NotificationService extends RouteBuilder implements ContainerServicprotected ManagerIdentityService identityService;protected MessageBrokerService messageBrokerService;protected ExecutorService executorService;+ protected ClientEventService clientEventService;protected Map<String, NotificationHandler> notificationHandlerMap = new HashMap<>();@Override@@ -81,6 +87,7 @@ public class NotificationService extends RouteBuilder implements ContainerServicthis.timerService = container.getService(TimerService.class);this.persistenceService = container.getService(PersistenceService.class);this.assetStorageService = container.getService(AssetStorageService.class);+ this.clientEventService = container.getService(ClientEventService.class);this.identityService = container.getService(ManagerIdentityService.class);this.messageBrokerService = container.getService(MessageBrokerService.class);executorService = container.getExecutor();@@ -95,6 +102,21 @@ public class NotificationService extends RouteBuilder implements ContainerServiccontainer.getService(AssetStorageService.class),container.getService(ManagerIdentityService.class)));+ clientEventService.addSubscriptionAuthorizer((realm, authContext, eventSubscription) -> {+ if (!eventSubscription.isEventType(NotificationEvent.class) || authContext == null) {+ return false;+ }++ if (!authContext.isSuperUser()) {+ @SuppressWarnings("unchecked")+ EventSubscription<NotificationEvent> subscription = (EventSubscription<NotificationEvent>) eventSubscription;+ subscription.setFilter(new RealmFilter<>(authContext.getAuthenticatedRealmName()));+ }++ return true;+ });++}@Override@@ -151,24 +173,35 @@ public class NotificationService extends RouteBuilder implements ContainerServicAtomicReference<String> sourceId = new AtomicReference<>("");boolean isSuperUser = false;boolean isRestrictedUser = false;+ AtomicReference<String> notificationRealm = new AtomicReference<>();switch (source) {- case INTERNAL -> isSuperUser = true;+ case INTERNAL -> {+ isSuperUser = true;+ notificationRealm.set(Constants.MASTER_REALM);+ }case CLIENT -> {AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);if (authContext == null) {// Anonymous clients cannot send notificationsthrow new NotificationProcessingException(INSUFFICIENT_ACCESS);}+ // Client notifications are scoped to the caller's authenticated realmrealm = authContext.getAuthenticatedRealmName();+ notificationRealm.set(realm);userId = authContext.getUserId();sourceId.set(userId);isSuperUser = authContext.isSuperUser();isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext);}- case GLOBAL_RULESET -> isSuperUser = true;+ case GLOBAL_RULESET -> {+ isSuperUser = true;+ // Global rulesets are realm-less, so unresolvable targets are stored under the master realm+ notificationRealm.set(Constants.MASTER_REALM);+ }case REALM_RULESET -> {realm = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);+ notificationRealm.set(realm);sourceId.set(realm);}case ASSET_RULESET -> {@@ -176,6 +209,7 @@ public class NotificationService extends RouteBuilder implements ContainerServicsourceId.set(assetId);Asset<?> asset = assetStorageService.find(assetId, false);realm = asset.getRealm();+ notificationRealm.set(realm);}}@@ -217,6 +251,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic.setTarget(target.getType()).setTargetId(target.getId()).setMessage(notification.getMessage())+ .setRealm(resolveTargetRealm(target, notificationRealm.get())).setSentOn(timerService.getNow());sentNotification = em.merge(sentNotification);@@ -267,11 +302,38 @@ public class NotificationService extends RouteBuilder implements ContainerServic.logStackTrace(false).handled(true).process(exchange -> {- // Just notify sender in case of RequestReply+ // Log the failure reason; notify sender in case of RequestReply+ Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);+ if (exception instanceof NotificationProcessingException) {+ LOG.warning("Notification processing failed: " + exception.getMessage());+ } else {+ LOG.log(Level.WARNING, "Notification processing failed", exception);+ }exchange.getMessage().setBody(false);});}+ /**+ * Resolves the realm a {@link SentNotification} should be stored against from its target so cross-realm+ * notifications are visible in the recipient's realm; falls back to the sender's realm when the target+ * cannot be resolved (e.g. {@link Notification.TargetType#CUSTOM} targets).+ */+ protected String resolveTargetRealm(Notification.Target target, String fallbackRealm) {+ switch (target.getType()) {+ case REALM:+ return target.getId();+ case USER:+ User user = identityService.getIdentityProvider().getUser(target.getId());+ if (user != null && user.getRealm() != null) return user.getRealm();+ break;+ case ASSET:+ Asset<?> asset = assetStorageService.find(target.getId(), false);+ if (asset != null) return asset.getRealm();+ break;+ }+ return fallbackRealm != null ? fallbackRealm : Constants.MASTER_REALM;+ }+public boolean sendNotification(Notification notification) {return sendNotification(notification, INTERNAL, "");}@@ -321,21 +383,116 @@ public class NotificationService extends RouteBuilder implements ContainerServicreturn persistenceService.doReturningTransaction(em -> em.find(SentNotification.class, notificationId));}- public List<SentNotification> getNotifications(List<Long> ids, List<String> types, Long fromTimestamp, Long toTimestamp, List<String> realmIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {- StringBuilder builder = new StringBuilder();- builder.append("select n from SentNotification n where 1=1");+ public List<SentNotification> getNotifications(List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, SentNotification.SortField sort, boolean descending, Integer offset, Integer limit, AuthContext authContext, boolean restricted) throws IllegalArgumentException {+ StringBuilder builder = new StringBuilder("select n from SentNotification n where 1=1");List<Object> parameters = new ArrayList<>();- processCriteria(builder, parameters, ids, types, fromTimestamp, toTimestamp, realmIds, userIds, assetIds, false);- builder.append(" order by n.sentOn asc");+ buildNotificationCriteria(builder, parameters, ids, types, from, to, realmIds, userIds, assetIds, source, authContext, restricted);+ builder.append(buildOrderBy(sort, descending));+return persistenceService.doReturningTransaction(entityManager -> {TypedQuery<SentNotification> query = entityManager.createQuery(builder.toString(), SentNotification.class);IntStream.rangeClosed(1, parameters.size())- .forEach(i -> query.setParameter(i, parameters.get(i-1)));+ .forEach(i -> query.setParameter(i, parameters.get(i - 1)));+ if (offset != null && offset > 0) {+ query.setFirstResult(offset);+ }+ if (limit != null && limit > 0) {+ query.setMaxResults(limit);+ }return query.getResultList();+ });+ }++ public long getNotificationsCount(List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, AuthContext authContext, boolean restricted) throws IllegalArgumentException {+ StringBuilder builder = new StringBuilder("select count(n) from SentNotification n where 1=1");+ List<Object> parameters = new ArrayList<>();+ buildNotificationCriteria(builder, parameters, null, types, from, to, realmIds, userIds, assetIds, source, authContext, restricted);+ return persistenceService.doReturningTransaction(entityManager -> {+ TypedQuery<Long> query = entityManager.createQuery(builder.toString(), Long.class);+ IntStream.rangeClosed(1, parameters.size())+ .forEach(i -> query.setParameter(i, parameters.get(i - 1)));+ return query.getSingleResult();});}+ /**+ * Builds the {@code order by} clause for {@link #getNotifications}. Each {@link SentNotification.SortField} maps+ * to a fixed persisted column (never a caller-supplied string) so ordering is injection-safe; a null sort keeps+ * the default of newest-sent first. Status orders by the derived sent/delivered/error state. Every ordering+ * ends with an id tie-breaker so paginated requests return a stable sequence.+ */+ protected String buildOrderBy(SentNotification.SortField sort, boolean descending) {+ String direction = sort == null || descending ? " desc" : " asc";+ String orderBy = switch (sort == null ? SentNotification.SortField.SENT_ON : sort) {+ case TITLE -> " order by n.name" + direction;+ case SOURCE -> " order by n.source" + direction;+ // sent (0) sorts before delivered (1) before error (2) when ascending+ case STATUS -> " order by case when n.error is not null then 2 when n.deliveredOn is not null then 1 else 0 end" + direction;+ case SENT_ON -> " order by n.sentOn" + direction;+ case DELIVERED_ON -> " order by n.deliveredOn" + direction;+ };+ // Secondary id sort keeps pagination stable when rows tie on the sorted column+ return orderBy + ", n.id" + direction;+ }++ /**+ * Appends the shared filter criteria used by {@link #getNotifications} and {@link #getNotificationsCount}.+ * Restricted callers are additionally limited to notifications they sent, that target them, or that target+ * their realm; any other caller with access sees all notifications matching the criteria.+ */+ protected void buildNotificationCriteria(StringBuilder builder, List<Object> parameters, List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, AuthContext authContext, boolean restricted) {+ int idx = 1;++ if (ids != null && !ids.isEmpty()) {+ builder.append(" AND n.id IN ?").append(idx++);+ parameters.add(ids);+ }+ if (types != null && !types.isEmpty()) {+ builder.append(" AND n.type IN ?").append(idx++);+ parameters.add(types);+ }+ if (from != null) {+ builder.append(" AND n.sentOn >= ?").append(idx++);+ parameters.add(from);+ }+ if (to != null) {+ builder.append(" AND n.sentOn <= ?").append(idx++);+ parameters.add(to);+ }+ if (source != null) {+ builder.append(" AND n.source = ?").append(idx++);+ parameters.add(source);+ }+ if (realmIds != null && !realmIds.isEmpty()) {+ builder.append(" AND n.realm IN ?").append(idx++);+ parameters.add(realmIds);+ }+ if (assetIds != null && !assetIds.isEmpty()) {+ builder.append(" AND n.target = ?").append(idx++).append(" AND n.targetId IN ?").append(idx++);+ parameters.add(Notification.TargetType.ASSET);+ parameters.add(assetIds);+ } else if (userIds != null && !userIds.isEmpty()) {+ builder.append(" AND n.target = ?").append(idx++).append(" AND n.targetId IN ?").append(idx++);+ parameters.add(Notification.TargetType.USER);+ parameters.add(userIds);+ }++ // Only restricted users are limited to notifications they sent, that target them, or that target their realm;+ // any other caller with access (read:notifications / read:admin / superuser) sees all of them. Whether the+ // caller is restricted is decided by the caller (resource layer) so authorization logic stays in one place.+ if (restricted && authContext != null) {+ builder.append(" AND (n.sourceId = ?").append(idx++)+ .append(" OR (n.target = ?").append(idx++).append(" AND n.targetId = ?").append(idx++).append(")")+ .append(" OR (n.target = ?").append(idx++).append(" AND n.targetId = ?").append(idx++).append("))");+ parameters.add(authContext.getUserId());+ parameters.add(Notification.TargetType.USER);+ parameters.add(authContext.getUserId());+ parameters.add(Notification.TargetType.REALM);+ parameters.add(authContext.getAuthenticatedRealmName());+ }+ }+public void removeNotification(Long id) {persistenceService.doTransaction(entityManager -> entityManager.createQuery("delete SentNotification where id = :id")@@ -344,12 +501,12 @@ public class NotificationService extends RouteBuilder implements ContainerServic);}- public void removeNotifications(List<Long> ids, List<String> types, Long fromTimestamp, Long toTimestamp, List<String> realmIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {+ public void removeNotifications(List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {StringBuilder builder = new StringBuilder();builder.append("delete from SentNotification n where 1=1");List<Object> parameters = new ArrayList<>();- processCriteria(builder, parameters, ids, types, fromTimestamp, toTimestamp, realmIds, userIds, assetIds, true);+ processCriteria(builder, parameters, ids, types, from, to, realmIds, userIds, assetIds, true);persistenceService.doTransaction(entityManager -> {Query query = entityManager.createQuery(builder.toString());@@ -359,7 +516,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic});}- protected void processCriteria(StringBuilder builder, List<Object> parameters, List<Long> ids, List<String> types, Long fromTimestamp, Long toTimestamp, List<String> realmIds, List<String> userIds, List<String> assetIds, boolean isRemove) {+ protected void processCriteria(StringBuilder builder, List<Object> parameters, List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, boolean isRemove) {boolean hasIds = ids != null && !ids.isEmpty();boolean hasTypes = types != null && !types.isEmpty();boolean hasRealms = realmIds != null && !realmIds.isEmpty();@@ -383,7 +540,7 @@ public class NotificationService extends RouteBuilder implements ContainerServiccounter++;}- if (isRemove && fromTimestamp == null && toTimestamp == null && counter == 0) {+ if (isRemove && from == null && to == null && counter == 0) {LOG.fine("No filters set for remove notifications request so not allowed");throw new IllegalArgumentException("No criteria specified");}@@ -401,18 +558,18 @@ public class NotificationService extends RouteBuilder implements ContainerServicparameters.add(types);}- if (fromTimestamp != null) {+ if (from != null) {builder.append(" AND n.sentOn >= ?").append(parameters.size() + 1);- parameters.add(Instant.ofEpochMilli(fromTimestamp));+ parameters.add(from);}- if (toTimestamp != null) {+ if (to != null) {builder.append(" AND n.sentOn <= ?").append(parameters.size() + 1);- parameters.add(Instant.ofEpochMilli(toTimestamp));+ parameters.add(to);}if (hasAssets) {@@ -444,6 +601,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic}}+protected Instant getRepeatAfterTimestamp(Notification notification, Instant lastSend) {Instant timestamp = null;diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.javaindex 214fdb55e..fec288fae 100644--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java@@ -1,5 +1,5 @@/*- * Copyright 2018, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -73,6 +73,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatioprotected AssetStorageService assetStorageService;protected GatewayService gatewayService;protected boolean valid;+ protected boolean devMode;protected Map<String, String> consoleFCMTokenMap = new ConcurrentHashMap<>();protected Set<String> fcmTokenBlacklist = Collections.synchronizedSet(new HashSet<>());@@ -85,6 +86,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatiothis.managerIdentityService = container.getService(ManagerIdentityService.class);this.assetStorageService = container.getService(AssetStorageService.class);this.gatewayService = container.getService(GatewayService.class);+ this.devMode = container.isDevMode();container.getService(MessageBrokerService.class).getContext().addRoutes(this);String firebaseConfigFilePath = container.getConfig().get(OR_FIREBASE_CONFIG_FILE);@@ -289,12 +291,24 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio});}+ if (devMode && mappedTargets.isEmpty() && targets != null && !targets.isEmpty()) {+ // Keep the no-targets behaviour identical to production but make the dropped notification visible+ LOG.info("Dev mode: no console asset targets mapped for push notification, original targets=["+ + targets.stream().map(Object::toString).collect(Collectors.joining(",")) + "], message=" + message);+ }+return mappedTargets;}@Overridepublic void sendMessage(long id, Notification.Source source, String sourceId, Notification.Target target, AbstractNotificationMessage message) throws Exception {+ if (devMode && !valid) {+ // FCM not configured; log the notification instead of sending so the sent record is still created+ LOG.info("Dev mode: FCM not configured so skipping push notification send: id=" + id + ", target=" + target + ", message=" + message);+ return;+ }+Notification.TargetType targetType = target.getType();String targetId = target.getId();@@ -361,7 +375,8 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio@Overridepublic boolean isValid() {- return valid;+ // In dev mode the handler is always valid so notifications are processed and persisted even without FCM config+ return valid || devMode;}public void sendMessage(Message message) throws Exception {@@ -403,13 +418,13 @@ public class PushNotificationHandler extends RouteBuilder implements NotificatioWebpushConfig.Builder webpushConfigBuilder = WebpushConfig.builder();if (!dataOnly) {- // Don't set basic notification on Android if there is data so even if app is in background we can show a custom notification- // with actions that use the actions from the data- if (pushMessage.getData() != null || pushMessage.getAction() != null || pushMessage.getButtons() != null) {- androidConfigBuilder.putData("or-title", pushMessage.getTitle());- if (pushMessage.getBody() != null) {- androidConfigBuilder.putData("or-body", pushMessage.getBody());- }+ // The OpenRemote console builds the Android notification from this data (rather than a basic FCM+ // notification) so it can show a custom notification with actions even when the app is in the background.+ // Always include the title/body: a plain push with no data/action/buttons would otherwise arrive with+ // nothing for the Android console to display.+ androidConfigBuilder.putData("or-title", pushMessage.getTitle());+ if (pushMessage.getBody() != null) {+ androidConfigBuilder.putData("or-body", pushMessage.getBody());}// Use alert dictionary for apnsdiff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.javaindex e4cb40a9a..a9ecb7201 100644--- a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -52,12 +52,14 @@ public abstract class AbstractKeycloakSetup implements Setup {ClientRole.READ_RULES,ClientRole.READ_INSIGHTS,ClientRole.READ_ALARMS,+ ClientRole.READ_NOTIFICATIONS,ClientRole.READ_SERVICES,ClientRole.WRITE_ASSETS,ClientRole.WRITE_ATTRIBUTES,ClientRole.WRITE_RULES,ClientRole.WRITE_INSIGHTS,ClientRole.WRITE_ALARMS,+ ClientRole.WRITE_NOTIFICATIONS,ClientRole.WRITE_SERVICES};diff --git a/manager/src/main/java/org/openremote/manager/setup/database/AbstractKeycloakMigration.java b/manager/src/main/java/org/openremote/manager/setup/database/AbstractKeycloakMigration.javanew file mode 100644index 000000000..073e75a9f--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/setup/database/AbstractKeycloakMigration.java@@ -0,0 +1,156 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.setup.database;++import org.flywaydb.core.api.migration.BaseJavaMigration;+import org.keycloak.admin.client.Keycloak;+import org.openremote.container.persistence.PersistenceService;+import org.openremote.container.security.IdentityProvider;+import org.openremote.container.security.IdentityService;+import org.openremote.container.security.keycloak.KeycloakIdentityProvider;+import org.openremote.manager.security.ManagerKeycloakIdentityProvider;+import org.openremote.model.Constants;+import org.openremote.model.auth.OAuthGrant;+import org.openremote.model.auth.OAuthPasswordGrant;+import org.openremote.model.util.TextUtil;+import org.openremote.model.util.ValueUtil;++import jakarta.ws.rs.core.UriBuilder;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.Paths;+import java.util.logging.Logger;++/**+ * Base class for Flyway Java migrations that need to interact with the Keycloak Admin API. Provides shared+ * credential resolution ({@link #resolveCredentials()}), a pre-authenticated {@link Keycloak} client+ * ({@link #openKeycloak()}), and the identity-provider guard ({@link #isKeycloakDeployment()}).+ * <p>+ * All subclasses talk to Keycloak over HTTP rather than through the migration's DB connection, so+ * {@link #canExecuteInTransaction()} returns {@code false}.+ * <p>+ * Subclasses must stay Java migrations and not be converted to {@code .sql} files: Flyway records a+ * {@code BaseJavaMigration} as type JDBC with a null checksum, whereas a {@code .sql} file for the same version+ * is type SQL with a real checksum, so converting one would fail validation on any database that has already+ * applied that version. The bodies may be edited freely — Java migrations have no checksum.+ */+public abstract class AbstractKeycloakMigration extends BaseJavaMigration {++ protected final Logger LOG = Logger.getLogger(getClass().getName());++ protected boolean isKeycloakDeployment() {+ String identityProvider = System.getenv().getOrDefault(+ IdentityService.OR_IDENTITY_PROVIDER, IdentityService.OR_IDENTITY_PROVIDER_DEFAULT);+ return IdentityService.OR_IDENTITY_PROVIDER_DEFAULT.equals(identityProvider);+ }++ protected Keycloak openKeycloak() {+ OAuthPasswordGrant credentials = resolveCredentials();+ return Keycloak.getInstance(+ buildKeycloakUrl(),+ Constants.MASTER_REALM,+ credentials.getUsername(),+ credentials.getPassword(),+ KeycloakIdentityProvider.ADMIN_CLI_CLIENT_ID);+ }++ /**+ * Resolves the credentials used to authenticate against Keycloak: prefers the stored manager grant written by+ * the identity provider on first startup, falls back to {@code OR_ADMIN_PASSWORD} (or the default admin+ * password when that env var is unset), so a clean install can still complete the migration.+ */+ protected OAuthPasswordGrant resolveCredentials() {+ OAuthPasswordGrant stored = loadStoredCredentials();+ return stored != null ? stored : loadAdminFallbackCredentials();+ }++ private OAuthPasswordGrant loadStoredCredentials() {+ String storageDir = System.getenv().getOrDefault(+ PersistenceService.OR_STORAGE_DIR, PersistenceService.OR_STORAGE_DIR_DEFAULT);+ String grantFile = System.getenv().getOrDefault(+ ManagerKeycloakIdentityProvider.OR_KEYCLOAK_GRANT_FILE,+ ManagerKeycloakIdentityProvider.OR_KEYCLOAK_GRANT_FILE_DEFAULT);++ if (grantFile == null || grantFile.isBlank()) {+ return null;+ }++ Path grantPath = Paths.get(storageDir).resolve(grantFile);+ if (!Files.isReadable(grantPath)) {+ return null;+ }++ try {+ String grantJson = Files.readString(grantPath, StandardCharsets.UTF_8);+ OAuthGrant grant = ValueUtil.parse(grantJson, OAuthGrant.class).orElse(null);+ if (grant instanceof OAuthPasswordGrant passwordGrant) {+ LOG.info("Loaded stored keycloak credentials from: " + grantPath);+ return passwordGrant;+ }+ LOG.warning("Stored keycloak credentials at " + grantPath + " are not a password grant; skipping");+ } catch (Exception ex) {+ LOG.warning("Failed to read stored keycloak credentials at " + grantPath + ": " + ex.getMessage());+ }+ return null;+ }++ private OAuthPasswordGrant loadAdminFallbackCredentials() {+ // Blank values are treated as absent, matching Config.init which filters them from the runtime config+ String adminPassword = System.getenv(IdentityProvider.OR_ADMIN_PASSWORD);+ if (TextUtil.isNullOrEmpty(adminPassword)) {+ adminPassword = IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT;+ LOG.warning("Stored keycloak credentials not available and " + IdentityProvider.OR_ADMIN_PASSWORD+ + " is not set; using the default admin password for Keycloak migration");+ } else {+ LOG.warning("Stored keycloak credentials not available; falling back to "+ + IdentityProvider.OR_ADMIN_PASSWORD + " for Keycloak migration");+ }+ return new OAuthPasswordGrant(+ null,+ KeycloakIdentityProvider.ADMIN_CLI_CLIENT_ID,+ null,+ "openid",+ Constants.MASTER_REALM_ADMIN_USER,+ adminPassword);+ }++ protected String buildKeycloakUrl() {+ UriBuilder uriBuilder = UriBuilder.fromPath("/")+ .scheme("http")+ .host(System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_HOST,+ KeycloakIdentityProvider.OR_KEYCLOAK_HOST_DEFAULT))+ .port(Integer.parseInt(System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_PORT,+ String.valueOf(KeycloakIdentityProvider.OR_KEYCLOAK_PORT_DEFAULT))));++ String path = System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_PATH,+ KeycloakIdentityProvider.OR_KEYCLOAK_PATH_DEFAULT);+ if (path != null && !path.isBlank()) {+ uriBuilder.path(path);+ }++ return uriBuilder.build().toString();+ }++ @Override+ public boolean canExecuteInTransaction() {+ return false;+ }+}diff --git a/manager/src/main/java/org/openremote/manager/setup/database/AbstractKeycloakRolesMigration.java b/manager/src/main/java/org/openremote/manager/setup/database/AbstractKeycloakRolesMigration.javanew file mode 100644index 000000000..718968afe--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/setup/database/AbstractKeycloakRolesMigration.java@@ -0,0 +1,114 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.setup.database;++import org.flywaydb.core.api.migration.Context;+import org.keycloak.admin.client.Keycloak;+import org.keycloak.admin.client.resource.ClientResource;+import org.keycloak.admin.client.resource.RealmResource;+import org.keycloak.admin.client.resource.RolesResource;+import org.keycloak.representations.idm.ClientRepresentation;+import org.keycloak.representations.idm.RealmRepresentation;+import org.keycloak.representations.idm.RoleRepresentation;+import org.openremote.model.Constants;+import org.openremote.model.security.ClientRole;++import jakarta.ws.rs.NotFoundException;+import java.util.ArrayList;+import java.util.List;++/**+ * Base class for Flyway migrations that add client roles to the {@code openremote} client of every realm and wire+ * them into the existing {@code read}/{@code write} composite roles (read → {@link #getReadRoles()},+ * write → {@link #getReadRoles()} + {@link #getWriteRoles()}). See {@link AbstractKeycloakMigration} for+ * credential handling, the identity-provider guard, and why subclasses must stay Java migrations.+ */+public abstract class AbstractKeycloakRolesMigration extends AbstractKeycloakMigration {++ /**+ * The leaf roles to create and wire into both the {@code read} and {@code write} composite roles.+ */+ protected abstract List<ClientRole> getReadRoles();++ /**+ * The leaf roles to create and wire into the {@code write} composite role only.+ */+ protected abstract List<ClientRole> getWriteRoles();++ @Override+ public void migrate(Context context) throws Exception {+ if (!isKeycloakDeployment()) {+ LOG.info("Identity provider is not keycloak; skipping role migration");+ return;+ }++ try (Keycloak keycloak = openKeycloak()) {+ List<String> realmNames = keycloak.realms().findAll().stream()+ .map(RealmRepresentation::getRealm)+ .toList();++ for (String realmName : realmNames) {+ RealmResource realm = keycloak.realm(realmName);++ List<ClientRepresentation> clients = realm.clients().findByClientId(Constants.KEYCLOAK_CLIENT_ID);+ if (clients.isEmpty()) {+ LOG.warning("Client '" + Constants.KEYCLOAK_CLIENT_ID + "' not found in realm " + realmName+ + ", skipping role creation.");+ continue;+ }+ ClientResource clientResource = realm.clients().get(clients.get(0).getId());+ RolesResource clientRoles = clientResource.roles();++ List<RoleRepresentation> readComposites = new ArrayList<>();+ List<RoleRepresentation> writeComposites = new ArrayList<>();++ for (ClientRole role : getReadRoles()) {+ createRoleIfNotFound(clientRoles, role);+ RoleRepresentation representation = clientRoles.get(role.getValue()).toRepresentation();+ readComposites.add(representation);+ writeComposites.add(representation);+ }+ for (ClientRole role : getWriteRoles()) {+ createRoleIfNotFound(clientRoles, role);+ writeComposites.add(clientRoles.get(role.getValue()).toRepresentation());+ }++ addToComposite(clientRoles, ClientRole.READ.getValue(), readComposites);+ addToComposite(clientRoles, ClientRole.WRITE.getValue(), writeComposites);+ }+ }+ }++ private void createRoleIfNotFound(RolesResource roles, ClientRole role) {+ try {+ roles.get(role.getValue()).toRepresentation();+ } catch (NotFoundException e) {+ roles.create(new RoleRepresentation(role.getValue(), role.getDescription(), false));+ }+ }++ private void addToComposite(RolesResource roles, String compositeName, List<RoleRepresentation> children) {+ try {+ roles.get(compositeName).addComposites(children); // addComposites is idempotent+ } catch (NotFoundException e) {+ LOG.warning("Composite role '" + compositeName + "' not found; skipping composite wiring");+ }+ }+}diff --git a/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.java b/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.javaindex 94afa8a7f..a4d39cd1c 100644--- a/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.java+++ b/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.java@@ -19,215 +19,25 @@*/package org.openremote.manager.setup.database;-import org.flywaydb.core.api.migration.BaseJavaMigration;-import org.flywaydb.core.api.migration.Context;-import org.keycloak.admin.client.Keycloak;-import org.keycloak.admin.client.resource.ClientResource;-import org.keycloak.admin.client.resource.RealmResource;-import org.keycloak.admin.client.resource.RolesResource;-import org.keycloak.representations.idm.ClientRepresentation;-import org.keycloak.representations.idm.RealmRepresentation;-import org.keycloak.representations.idm.RoleRepresentation;-import org.openremote.container.persistence.PersistenceService;-import org.openremote.container.security.IdentityProvider;-import org.openremote.container.security.IdentityService;-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;-import org.openremote.manager.security.ManagerKeycloakIdentityProvider;-import org.openremote.model.Constants;-import org.openremote.model.auth.OAuthGrant;-import org.openremote.model.auth.OAuthPasswordGrant;import org.openremote.model.security.ClientRole;-import org.openremote.model.util.TextUtil;-import org.openremote.model.util.ValueUtil;-import jakarta.ws.rs.NotFoundException;-import jakarta.ws.rs.core.UriBuilder;--import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.nio.file.Paths;import java.util.List;-import java.util.logging.Logger;/*** Flyway migration that adds the {@code read:services} and {@code write:services} client roles to the- * {@code openremote} client of every realm, using the Keycloak admin API, and wires them into the existing- * {@code read}/{@code write} composite roles (matching ClientRole.READ / ClientRole.WRITE:- * read -> read:services, write -> read:services + write:services).- * <p>- * It authenticates with the stored manager credentials written to {@code <OR_STORAGE_DIR>/manager/keycloak-credentials.json}- * (the {@code manager-keycloak} super-user that the identity provider provisions on first startup) rather than the- * {@code OR_ADMIN_PASSWORD} admin credentials. The admin password is only meant to be used once, at initial startup, to- * create those manager credentials; reusing the stored grant here keeps the migration working even when the admin- * password isn't available (e.g. rotated or unset after bootstrap).- * <p>- * When {@code OR_IDENTITY_PROVIDER} is not {@code keycloak} (e.g. the basic identity provider) the migration skips- * entirely, as there is no Keycloak to talk to. If the stored credentials are unavailable, it falls back to- * {@code OR_ADMIN_PASSWORD}, or to the default admin password when that is unset or blank, so a clean install- * (where the stored grant file doesn't exist yet) can still complete the migration.- * <p>- * This must stay a Java migration and not be converted to a {@code .sql} file: Flyway records a {@code BaseJavaMigration}- * as type JDBC with a null checksum, whereas a {@code .sql} file for the same version is type SQL with a real checksum,- * so converting it would fail validation on any database that already applied this (released) version. The body may be- * edited freely - Java migrations have no checksum, so changes here don't affect already-migrated databases.+ * {@code openremote} client of every realm and wires them into the existing {@code read}/{@code write} composite+ * roles. See {@link AbstractKeycloakRolesMigration} for the credential handling and why this must stay a Java+ * migration.*/-public class V20250916_01__AddServiceRoles extends BaseJavaMigration {-- private static final Logger LOG = Logger.getLogger(V20250916_01__AddServiceRoles.class.getName());+public class V20250916_01__AddServiceRoles extends AbstractKeycloakRolesMigration {@Override- public void migrate(Context context) throws Exception {-- String identityProvider = System.getenv().getOrDefault(- IdentityService.OR_IDENTITY_PROVIDER, IdentityService.OR_IDENTITY_PROVIDER_DEFAULT);- if (!IdentityService.OR_IDENTITY_PROVIDER_DEFAULT.equals(identityProvider)) {- LOG.info("Identity provider is '" + identityProvider + "'; skipping service role migration");- return;- }-- // Upgrade path: resolve credentials to authenticate against Keycloak.- OAuthPasswordGrant credentials = loadStoredCredentials();- if (credentials == null) {- // Stored grant file is absent or unreadable; fall back to OR_ADMIN_PASSWORD or, when unset, the default admin password- credentials = loadAdminFallbackCredentials();- }-- String keycloakUrl = buildKeycloakUrl();-- try (Keycloak keycloak = Keycloak.getInstance(- keycloakUrl,- Constants.MASTER_REALM,- credentials.getUsername(),- credentials.getPassword(),- KeycloakIdentityProvider.ADMIN_CLI_CLIENT_ID)) {-- List<String> realmNames = keycloak.realms().findAll().stream()- .map(RealmRepresentation::getRealm)- .toList();-- // For every realm, ensure the openremote client has the read:services and write:services roles- for (String realmName : realmNames) {- RealmResource realm = keycloak.realm(realmName);-- List<ClientRepresentation> clients = realm.clients().findByClientId(Constants.KEYCLOAK_CLIENT_ID);-- if (clients.isEmpty()) {- LOG.warning("Client '" + Constants.KEYCLOAK_CLIENT_ID + "' not found in realm " + realmName- + ", skipping role creation.");- continue; // Skip realms without the openremote client- }- ClientResource clientResource = realm.clients().get(clients.get(0).getId());- RolesResource clientRoles = clientResource.roles();- createRoleIfNotFound(clientRoles, ClientRole.WRITE_SERVICES);- createRoleIfNotFound(clientRoles, ClientRole.READ_SERVICES);-- RoleRepresentation readServices = clientRoles.get(ClientRole.READ_SERVICES.getValue()).toRepresentation();- RoleRepresentation writeServices = clientRoles.get(ClientRole.WRITE_SERVICES.getValue()).toRepresentation();- addToComposite(clientRoles, ClientRole.READ.getValue(), readServices);- addToComposite(clientRoles, ClientRole.WRITE.getValue(), readServices, writeServices);- }- }- }-- /**- * Loads the stored manager credentials, similar to {@link ManagerKeycloakIdentityProvider}: it reads- * {@code OR_KEYCLOAK_GRANT_FILE} (a JSON-serialised {@link OAuthGrant}) resolved relative to {@code OR_STORAGE_DIR}.- * Returns {@code null} if the file is absent or doesn't hold a usable password grant.- */- private OAuthPasswordGrant loadStoredCredentials() {- String storageDir = System.getenv().getOrDefault(- PersistenceService.OR_STORAGE_DIR, PersistenceService.OR_STORAGE_DIR_DEFAULT);- String grantFile = System.getenv().getOrDefault(- ManagerKeycloakIdentityProvider.OR_KEYCLOAK_GRANT_FILE,- ManagerKeycloakIdentityProvider.OR_KEYCLOAK_GRANT_FILE_DEFAULT);-- if (grantFile == null || grantFile.isBlank()) {- return null;- }-- Path grantPath = Paths.get(storageDir).resolve(grantFile);- if (!Files.isReadable(grantPath)) {- return null;- }-- try {- String grantJson = Files.readString(grantPath, StandardCharsets.UTF_8);- OAuthGrant grant = ValueUtil.parse(grantJson, OAuthGrant.class).orElse(null);- if (grant instanceof OAuthPasswordGrant passwordGrant) {- LOG.info("Loaded stored keycloak credentials from: " + grantPath);- return passwordGrant;- }- LOG.warning("Stored keycloak credentials at " + grantPath + " are not a password grant; skipping");- } catch (Exception ex) {- LOG.warning("Failed to read stored keycloak credentials at " + grantPath + ": " + ex.getMessage());- }- return null;- }-- /**- * Builds an admin-password grant from {@link IdentityProvider#OR_ADMIN_PASSWORD}, but only when that env var is- * explicitly set. Returns {@code null} when it isn't, so the caller can fail the migration rather than silently- * using the default {@code "secret"} (which is wrong on any deployment that changed the admin password at- * bootstrap).- */- private OAuthPasswordGrant loadAdminFallbackCredentials() {- // Blank values are treated as absent, matching Config.init which filters them from the runtime config- String adminPassword = System.getenv(IdentityProvider.OR_ADMIN_PASSWORD);- if (TextUtil.isNullOrEmpty(adminPassword)) {- adminPassword = IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT;- LOG.warning("Stored keycloak credentials not available and " + IdentityProvider.OR_ADMIN_PASSWORD- + " is not set; using the default admin password to add service roles");- } else {- LOG.warning("Stored keycloak credentials not available; falling back to "- + IdentityProvider.OR_ADMIN_PASSWORD + " to add service roles");- }- return new OAuthPasswordGrant(- null,- KeycloakIdentityProvider.ADMIN_CLI_CLIENT_ID,- null,- "openid",- Constants.MASTER_REALM_ADMIN_USER,- adminPassword);- }-- private String buildKeycloakUrl() {- UriBuilder uriBuilder = UriBuilder.fromPath("/")- .scheme("http")- .host(System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_HOST,- KeycloakIdentityProvider.OR_KEYCLOAK_HOST_DEFAULT))- .port(Integer.parseInt(System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_PORT,- String.valueOf(KeycloakIdentityProvider.OR_KEYCLOAK_PORT_DEFAULT))));-- String path = System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_PATH,- KeycloakIdentityProvider.OR_KEYCLOAK_PATH_DEFAULT);-- if (path != null && !path.isBlank()) {- uriBuilder.path(path);- }-- return uriBuilder.build().toString();- }-- private void createRoleIfNotFound(RolesResource roles, ClientRole role) {- try {- roles.get(role.getValue()).toRepresentation();- } catch (NotFoundException e) {- roles.create(new RoleRepresentation(role.getValue(), role.getDescription(), false));- }- }-- private void addToComposite(RolesResource roles, String compositeName, RoleRepresentation... children) {- try {- roles.get(compositeName).addComposites(List.of(children)); // addComposites is idempotent- } catch (NotFoundException e) {- LOG.warning("Composite role '" + compositeName + "' not found; skipping composite wiring");- }+ protected List<ClientRole> getReadRoles() {+ return List.of(ClientRole.READ_SERVICES);}- // Talks to Keycloak over HTTP (not the migration's DB connection), so it can't run in a DB transaction@Override- public boolean canExecuteInTransaction() {- return false;+ protected List<ClientRole> getWriteRoles() {+ return List.of(ClientRole.WRITE_SERVICES);}}diff --git a/manager/src/main/java/org/openremote/manager/setup/database/V20260715_1443_1__BackfillNotificationRealmUsers.java b/manager/src/main/java/org/openremote/manager/setup/database/V20260715_1443_1__BackfillNotificationRealmUsers.javanew file mode 100644index 000000000..3cd3632b8--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/setup/database/V20260715_1443_1__BackfillNotificationRealmUsers.java@@ -0,0 +1,153 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.setup.database;++import org.flywaydb.core.api.migration.Context;+import org.keycloak.admin.client.Keycloak;+import org.keycloak.representations.idm.RealmRepresentation;+import org.keycloak.representations.idm.UserRepresentation;++import java.sql.PreparedStatement;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * Companion to {@code V20260715_1443__AddNotificationRealm.sql}: backfills the {@code realm} column for+ * USER-targeted and CLIENT-sourced notifications by looking up each referenced user's realm via the Keycloak+ * Admin API (the stable public interface, not the internal schema). The Keycloak lookup is skipped entirely when+ * no rows reference a user (e.g. clean installs) or on non-Keycloak deployments. Any rows still unresolved after+ * the backfill (CUSTOM targets, deleted users/assets, INTERNAL/GLOBAL_RULESET sources) fall back to {@code master}.+ * Also applies the master fallback and {@code NOT NULL} constraint that the SQL migration deferred until all+ * resolvable rows were filled.+ */+public class V20260715_1443_1__BackfillNotificationRealmUsers extends AbstractKeycloakMigration {++ private static final int USER_PAGE_SIZE = 100;++ @Override+ public void migrate(Context context) throws Exception {+ if (isKeycloakDeployment()) {+ Set<String> unresolvedUserIds = findUnresolvedUserIds(context);+ if (unresolvedUserIds.isEmpty()) {+ LOG.info("No notifications reference a user; skipping Keycloak lookup");+ } else {+ Map<String, List<String>> realmUserIds = buildRealmUserIdsMap(unresolvedUserIds);+ if (!realmUserIds.isEmpty()) {+ applyRealmUserIds(context, realmUserIds);+ }+ }+ } else {+ LOG.info("Identity provider is not keycloak; skipping user realm backfill");+ }++ // Master fallback for anything still unresolved, then enforce NOT NULL+ try (var stmt = context.getConnection().createStatement()) {+ stmt.executeUpdate("UPDATE NOTIFICATION SET realm = 'master' WHERE realm IS NULL");+ stmt.executeUpdate("ALTER TABLE NOTIFICATION ALTER COLUMN realm SET NOT NULL");+ }+ }++ private Set<String> findUnresolvedUserIds(Context context) throws Exception {+ Set<String> userIds = new HashSet<>();+ // USER-targeted rows hold the recipient's user id in TARGET_ID, CLIENT-sourced rows hold the+ // sender's user id in SOURCE_ID; UNION deduplicates ids appearing in both+ try (var stmt = context.getConnection().createStatement();+ var rs = stmt.executeQuery(+ "SELECT TARGET_ID FROM NOTIFICATION WHERE realm IS NULL AND TARGET = 'USER'"+ + " UNION SELECT SOURCE_ID FROM NOTIFICATION WHERE realm IS NULL AND SOURCE = 'CLIENT'")) {+ while (rs.next()) {+ String id = rs.getString(1);+ if (id != null) {+ userIds.add(id);+ }+ }+ }+ return userIds;+ }++ private Map<String, List<String>> buildRealmUserIdsMap(Set<String> unresolvedUserIds) {+ Map<String, List<String>> realmUserIds = new HashMap<>();+ Set<String> remaining = new HashSet<>(unresolvedUserIds);++ try (Keycloak keycloak = openKeycloak()) {+ List<String> realmNames = keycloak.realms().findAll().stream()+ .map(RealmRepresentation::getRealm)+ .toList();++ for (String realmName : realmNames) {+ List<String> matched = findUserIdsInRealm(keycloak, realmName, remaining);+ if (!matched.isEmpty()) {+ realmUserIds.put(realmName, matched);+ matched.forEach(remaining::remove);+ }+ if (remaining.isEmpty()) {+ break;+ }+ }+ }++ LOG.info("Resolved realm for " + (unresolvedUserIds.size() - remaining.size()) + " of "+ + unresolvedUserIds.size() + " users referenced by notifications");+ return realmUserIds;+ }++ /**+ * Pages through the realm's users and returns the ids present in {@code wanted}, stopping as soon as all of+ * them have been found.+ */+ private List<String> findUserIdsInRealm(Keycloak keycloak, String realmName, Set<String> wanted) {+ List<String> matched = new ArrayList<>();+ int first = 0;+ List<UserRepresentation> page;+ do {+ page = keycloak.realm(realmName).users().list(first, USER_PAGE_SIZE);+ page.stream()+ .map(UserRepresentation::getId)+ .filter(wanted::contains)+ .forEach(matched::add);+ first += page.size();+ } while (page.size() == USER_PAGE_SIZE && matched.size() < wanted.size());+ return matched;+ }++ private void applyRealmUserIds(Context context, Map<String, List<String>> realmUserIds) throws Exception {+ // USER-targeted notifications: targetId is the user id+ updateRealmByUserIds(context, realmUserIds,+ "UPDATE NOTIFICATION SET realm = ? WHERE realm IS NULL AND TARGET = 'USER' AND TARGET_ID = ANY(?)");+ // CLIENT-sourced notifications: sourceId is the sending user id+ updateRealmByUserIds(context, realmUserIds,+ "UPDATE NOTIFICATION SET realm = ? WHERE realm IS NULL AND SOURCE = 'CLIENT' AND SOURCE_ID = ANY(?)");+ }++ private void updateRealmByUserIds(Context context, Map<String, List<String>> realmUserIds, String sql) throws Exception {+ try (PreparedStatement ps = context.getConnection().prepareStatement(sql)) {+ for (Map.Entry<String, List<String>> entry : realmUserIds.entrySet()) {+ ps.setString(1, entry.getKey());+ ps.setArray(2, context.getConnection().createArrayOf("varchar", entry.getValue().toArray()));+ ps.addBatch();+ }+ ps.executeBatch();+ }+ }+}diff --git a/manager/src/main/java/org/openremote/manager/setup/database/V20260715_1444__AddNotificationRoles.java b/manager/src/main/java/org/openremote/manager/setup/database/V20260715_1444__AddNotificationRoles.javanew file mode 100644index 000000000..ac990ef88--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/setup/database/V20260715_1444__AddNotificationRoles.java@@ -0,0 +1,43 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.setup.database;++import org.openremote.model.security.ClientRole;++import java.util.List;++/**+ * Flyway migration that adds the {@code read:notifications} and {@code write:notifications} client roles to the+ * {@code openremote} client of every realm and wires them into the existing {@code read}/{@code write} composite+ * roles. See {@link AbstractKeycloakRolesMigration} for the credential handling and why this must stay a Java+ * migration.+ */+public class V20260715_1444__AddNotificationRoles extends AbstractKeycloakRolesMigration {++ @Override+ protected List<ClientRole> getReadRoles() {+ return List.of(ClientRole.READ_NOTIFICATIONS);+ }++ @Override+ protected List<ClientRole> getWriteRoles() {+ return List.of(ClientRole.WRITE_NOTIFICATIONS);+ }+}diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20260715_1443__AddNotificationRealm.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20260715_1443__AddNotificationRealm.sqlnew file mode 100644index 000000000..416acb295--- /dev/null+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20260715_1443__AddNotificationRealm.sql@@ -0,0 +1,31 @@+-- Adds and backfills the NOTIFICATION.realm column. NOTIFICATION/ASSET are unqualified so they resolve to the+-- manager schema (the connection's default schema). USER-targeted and CLIENT-sourced rows require a Keycloak API+-- lookup to resolve correctly; that is handled by the companion Java migration V20260715_1443_1, which also applies+-- the master fallback and the NOT NULL constraint once all resolvable rows are filled.++-- add the realm column (initially nullable so existing rows can be backfilled)+ALTER TABLE NOTIFICATION ADD COLUMN realm VARCHAR(255);++-- backfill the realm of existing notifications from their target, mirroring NotificationService.resolveTargetRealm:+-- REALM target -> the target id is the realm name itself+-- ASSET target -> the asset's realm+UPDATE NOTIFICATION+ SET realm = TARGET_ID+ WHERE realm IS NULL AND TARGET = 'REALM';++UPDATE NOTIFICATION n+ SET realm = a.REALM+ FROM ASSET a+ WHERE n.realm IS NULL AND n.TARGET = 'ASSET' AND a.ID = n.TARGET_ID;++-- backfill from the sender for rows whose target could not be resolved:+-- REALM_RULESET source -> the source id is the realm name itself+-- ASSET_RULESET source -> the source asset's realm+UPDATE NOTIFICATION+ SET realm = SOURCE_ID+ WHERE realm IS NULL AND SOURCE = 'REALM_RULESET';++UPDATE NOTIFICATION n+ SET realm = a.REALM+ FROM ASSET a+ WHERE n.realm IS NULL AND n.SOURCE = 'ASSET_RULESET' AND a.ID = n.SOURCE_ID;diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.javaindex 9eea73568..b251fb636 100644--- a/model/src/main/java/org/openremote/model/Constants.java+++ b/model/src/main/java/org/openremote/model/Constants.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -37,6 +37,7 @@ public interface Constants {String READ_RULES_ROLE = "read:rules";String READ_INSIGHTS_ROLE = "read:insights";String READ_ALARMS_ROLE = "read:alarms";+ String READ_NOTIFICATIONS_ROLE = "read:notifications";String READ_SERVICES_ROLE = "read:services";String WRITE_SERVICES_ROLE = "write:services";String WRITE_USER_ROLE = "write:user";@@ -47,6 +48,7 @@ public interface Constants {String WRITE_RULES_ROLE = "write:rules";String WRITE_INSIGHTS_ROLE = "write:insights";String WRITE_ALARMS_ROLE = "write:alarms";+ String WRITE_NOTIFICATIONS_ROLE = "write:notifications";String RESTRICTED_USER_REALM_ROLE = "restricted_user";String AUTH_CONTEXT = "AUTH_CONTEXT";String SESSION_OPEN = "connection.sessionOpen";diff --git a/model/src/main/java/org/openremote/model/notification/NotificationEvent.java b/model/src/main/java/org/openremote/model/notification/NotificationEvent.javanew file mode 100644index 000000000..f628905a2--- /dev/null+++ b/model/src/main/java/org/openremote/model/notification/NotificationEvent.java@@ -0,0 +1,44 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.notification;++import org.openremote.model.PersistenceEvent;+import org.openremote.model.event.shared.RealmScopedEvent;++public class NotificationEvent extends RealmScopedEvent {+ protected PersistenceEvent.Cause cause;++ public NotificationEvent(String realm, PersistenceEvent.Cause cause) {+ super(realm);+ this.cause = cause;+ }++ public PersistenceEvent.Cause getCause() {+ return cause;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "realm=" + realm ++ ", cause=" + cause ++ "}";+ }+}diff --git a/model/src/main/java/org/openremote/model/notification/NotificationResource.java b/model/src/main/java/org/openremote/model/notification/NotificationResource.javaindex 2d5f64bed..08ffe2e5e 100644--- a/model/src/main/java/org/openremote/model/notification/NotificationResource.java+++ b/model/src/main/java/org/openremote/model/notification/NotificationResource.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -34,17 +34,15 @@ import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;public interface NotificationResource {/**- * Gets all sent notifications that have been sent to the specified targets; optionally limiting the scope of the- * request by {@link AbstractNotificationMessage} type and/or sent datetime. If type(s) or timestamp are not set- * then it is assumed no type or time constraint is required. Can also provide a list of notification IDs to get- * specific notifications.- * <p>- * Only the superuser can call this operation.+ * Gets sent notifications matching the supplied criteria; optionally limiting the scope by {@link+ * AbstractNotificationMessage} type, sent datetime, realm, target user/asset, {@link Notification.Source} and/or+ * pagination (offset/limit). Restricted users only ever see notifications they sent or that target them or their+ * realm; non-superusers are limited to a realm they can access (their own when none is specified).*/@GET@Produces(APPLICATION_JSON)- @RolesAllowed({Constants.READ_ADMIN_ROLE})- @Operation(operationId = "getNotifications", summary = "Retrieve all sent notifications by targets")+ @RolesAllowed({Constants.READ_ADMIN_ROLE, Constants.READ_NOTIFICATIONS_ROLE})+ @Operation(operationId = "getNotifications", summary = "Retrieve sent notifications matching the supplied criteria")SentNotification[] getNotifications(@BeanParam RequestParams requestParams,@QueryParam("id") Long id,@QueryParam("type") String type,@@ -52,17 +50,12 @@ public interface NotificationResource {@QueryParam("to") Long toTimestamp,@QueryParam("realmId") String realmId,@QueryParam("userId") String userId,- @QueryParam("assetId") String assetId);- // RT: Was using lists here but they don't work with JSAPI because GWT doesn't use JSArrays for lists - another- // reason to get away from GWT-// SentNotification[] getNotifications(@BeanParam RequestParams requestParams,-// @QueryParam("id") List<Long> ids,-// @QueryParam("type") List<String> types,-// @QueryParam("from") Long fromTimestamp,-// @QueryParam("to") Long toTimestamp,-// @QueryParam("realmId") List<String> realmIds,-// @QueryParam("userId") List<String> userIds,-// @QueryParam("assetId") List<String> assetIds);+ @QueryParam("assetId") String assetId,+ @QueryParam("source") Notification.Source source,+ @QueryParam("sort") SentNotification.SortField sort,+ @QueryParam("descending") Boolean descending,+ @QueryParam("offset") Integer offset,+ @QueryParam("limit") Integer limit);/*** Removes all sent notifications that have been sent to the specified targets; optionally limiting the scope of the@@ -83,16 +76,6 @@ public interface NotificationResource {@QueryParam("realmId") String realmId,@QueryParam("userId") String userId,@QueryParam("assetId") String assetId);- // RT: Was using lists here but they don't work with JSAPI because GWT doesn't use JSArrays for lists - another- // reason to get away from GWT-// void removeNotifications(@BeanParam RequestParams requestParams,-// @QueryParam("id") List<Long> ids,-// @QueryParam("type") List<String> types,-// @QueryParam("from") Long fromTimestamp,-// @QueryParam("to") Long toTimestamp,-// @QueryParam("realmId") List<String> realmIds,-// @QueryParam("userId") List<String> userIds,-// @QueryParam("assetId") List<String> assetIds);/*** Remove a specific sent notification by ID.@@ -114,6 +97,7 @@ public interface NotificationResource {@POST@Path("alert")@Consumes(APPLICATION_JSON)+ @RolesAllowed({Constants.WRITE_ADMIN_ROLE, Constants.WRITE_NOTIFICATIONS_ROLE})@Operation(operationId = "sendNotification", summary = "Send a notification to one or more targets")void sendNotification(@BeanParam RequestParams requestParams,Notification notification);@@ -145,4 +129,22 @@ public interface NotificationResource {@QueryParam("targetId") String targetId,@PathParam("notificationId") Long notificationId,JsonNode acknowledgement);++ /**+ * Counts sent notifications matching the supplied criteria; uses the same scoping and access rules as+ * {@link #getNotifications}.+ */+ @GET+ @Path("count")+ @Produces(APPLICATION_JSON)+ @RolesAllowed({Constants.READ_ADMIN_ROLE, Constants.READ_NOTIFICATIONS_ROLE})+ @Operation(operationId = "getNotificationsCount", summary = "Count sent notifications matching the supplied criteria")+ long getNotificationsCount(@BeanParam RequestParams requestParams,+ @QueryParam("type") String type,+ @QueryParam("from") Long fromTimestamp,+ @QueryParam("to") Long toTimestamp,+ @QueryParam("realmId") String realmId,+ @QueryParam("userId") String userId,+ @QueryParam("assetId") String assetId,+ @QueryParam("source") Notification.Source source);}diff --git a/model/src/main/java/org/openremote/model/notification/SentNotification.java b/model/src/main/java/org/openremote/model/notification/SentNotification.javaindex 84c2e47c8..b6c7354ef 100644--- a/model/src/main/java/org/openremote/model/notification/SentNotification.java+++ b/model/src/main/java/org/openremote/model/notification/SentNotification.java@@ -1,5 +1,5 @@/*- * Copyright 2017, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -32,6 +32,18 @@ import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;@Table(name = "NOTIFICATION")public class SentNotification {+ /**+ * Columns that {@link SentNotification}s can be ordered by server-side; each maps to a fixed persisted column+ * (see the notification service) so ordering stays injection-safe and consistent across paginated results.+ */+ public enum SortField {+ TITLE,+ SOURCE,+ STATUS,+ SENT_ON,+ DELIVERED_ON+ }+@Id@Column(name = "ID")@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)@@ -59,6 +71,10 @@ public class SentNotification {@Enumerated(EnumType.STRING)protected Notification.Source source;+ @NotNull+ @Column(name = "REALM", nullable = false, updatable = false)+ protected String realm;+@Column(name = "SOURCE_ID", length = 43)protected String sourceId;@@ -189,6 +205,16 @@ public class SentNotification {return this;}+ public String getRealm() {+ return realm;+ }++ public SentNotification setRealm(String realm) {+ this.realm = realm;+ return this;+ }++public String getError() {return error;}diff --git a/model/src/main/java/org/openremote/model/security/ClientRole.java b/model/src/main/java/org/openremote/model/security/ClientRole.javaindex b03aecfa2..08b862c65 100644--- a/model/src/main/java/org/openremote/model/security/ClientRole.java+++ b/model/src/main/java/org/openremote/model/security/ClientRole.java@@ -1,5 +1,5 @@/*- * Copyright 2017, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -39,6 +39,7 @@ public enum ClientRole {READ_RULES(Constants.READ_RULES_ROLE, "Read rulesets"),READ_INSIGHTS(Constants.READ_INSIGHTS_ROLE, "Read dashboards"),READ_ALARMS(Constants.READ_ALARMS_ROLE, "Read alarms"),+ READ_NOTIFICATIONS(Constants.READ_NOTIFICATIONS_ROLE, "Read notifications"),READ_SERVICES(Constants.READ_SERVICES_ROLE, "View services"),WRITE_SERVICES(Constants.WRITE_SERVICES_ROLE, "Write service data"),@@ -50,6 +51,7 @@ public enum ClientRole {WRITE_RULES(Constants.WRITE_RULES_ROLE, "Write rulesets (NOTE: effectively super-user access!)"),WRITE_INSIGHTS(Constants.WRITE_INSIGHTS_ROLE, "Write dashboard data"),WRITE_ALARMS(Constants.WRITE_ALARMS_ROLE, "Write alarm data"),+ WRITE_NOTIFICATIONS(Constants.WRITE_NOTIFICATIONS_ROLE, "Write notification data"),READ("read", "Read all data", new ClientRole[]{READ_ADMIN,@@ -60,6 +62,7 @@ public enum ClientRole {READ_RULES,READ_INSIGHTS,READ_ALARMS,+ READ_NOTIFICATIONS,READ_SERVICES}),@@ -72,6 +75,7 @@ public enum ClientRole {READ_RULES,READ_INSIGHTS,READ_ALARMS,+ READ_NOTIFICATIONS,READ_SERVICES,WRITE_USER,WRITE_ADMIN,@@ -81,6 +85,7 @@ public enum ClientRole {WRITE_RULES,WRITE_INSIGHTS,WRITE_ALARMS,+ WRITE_NOTIFICATIONS,WRITE_SERVICES});diff --git a/project.gradle b/project.gradleindex 6096bc69d..808019508 100644--- a/project.gradle+++ b/project.gradle@@ -164,6 +164,13 @@ if (project == rootProject) {OR_SETUP_TYPE: "clustering"]}+ "Notification Setup"(Application) {+ moduleName = getProject().idea.module.name + ".setup.notification"+ envs = [+ OR_SETUP_TYPE: "notification",+ OR_APP_DOCROOT: "manager/build/install/manager/web"+ ]+ }"Test Setup"(Application) {moduleName = getProject().idea.module.name + ".setup.integration"}diff --git a/setup/build.gradle b/setup/build.gradleindex e1f7690ba..bbe63b763 100644--- a/setup/build.gradle+++ b/setup/build.gradle@@ -13,6 +13,7 @@ sourceSets {integrationload1load2+ notification}// dependencies declaration@@ -21,6 +22,7 @@ configurations {integrationImplementation.extendsFrom(implementation)load1Implementation.extendsFrom(implementation)load2Implementation.extendsFrom(implementation)+ notificationImplementation.extendsFrom(implementation)}dependencies {@@ -42,6 +44,11 @@ tasks.register('load2Jar', Jar) {from sourceSets.load2.output}+tasks.register('notificationJar', Jar) {+ archiveBaseName.set("openremote-notification-${project.name}")+ from sourceSets.notification.output+}+tasks.named("compileJava") {dependsOn("load1Jar", "load2Jar")}diff --git a/setup/src/notification/java/org/openremote/setup/notification/KeycloakNotificationSetup.java b/setup/src/notification/java/org/openremote/setup/notification/KeycloakNotificationSetup.javanew file mode 100644index 000000000..9f2e695e5--- /dev/null+++ b/setup/src/notification/java/org/openremote/setup/notification/KeycloakNotificationSetup.java@@ -0,0 +1,138 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.setup.notification;++import org.openremote.manager.setup.AbstractKeycloakSetup;+import org.openremote.model.Container;+import org.openremote.model.security.ClientRole;+import org.openremote.model.security.Realm;+import org.openremote.model.security.User;++import java.util.logging.Logger;++import static org.openremote.model.Constants.MASTER_REALM;+import static org.openremote.model.Constants.RESTRICTED_USER_REALM_ROLE;++/**+ * Creates test users covering each notification RBAC requirement:+ *+ * <ul>+ * <li><b>read</b> — read:notifications only; sees only own notifications, no name resolution</li>+ * <li><b>assets</b> — read:notifications + read:assets; asset names resolved in the table</li>+ * <li><b>users</b> — read:notifications + read:users; user names resolved, users recipient option shown</li>+ * <li><b>view-users</b> — read:notifications + read:users + read:assets; full user/asset resolution</li>+ * <li><b>write</b> — write:notifications + write:notifications; can send and view own notifications</li>+ * <li><b>restricted</b> — write:notifications + restricted realm role; no send notification option</li>+ * <li><b>restricted</b> — write:notifications + restricted realm role; no user/realm recipient option in dialog</li>+ * </ul>+ *+ * All users share the password {@code secret}.+ */+public class KeycloakNotificationSetup extends AbstractKeycloakSetup {++ private static final Logger LOG = Logger.getLogger(KeycloakNotificationSetup.class.getName());+ public static final String PASSWORD = "secret";+ public static final String SMARTCITY_REALM = "smartcity";++ public User notifRead;+ public User notifAssets;+ public User notifUsers;+ public User notifViewUsers;+ public User notifWrite;+ public User notifRestricted;+ public User notifRestrictedAssets;+ public Realm realmSmartCity;+ public User smartCityUser;++ public KeycloakNotificationSetup(Container container) {+ super(container);+ }++ @Override+ public void onStart() throws Exception {+ super.onStart();++ // Sees only own notifications; no asset/user name resolution+ notifRead = createUser(MASTER_REALM, "read", PASSWORD, "Notification","Read", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS+ });++ // Sees only own notifications; asset names resolved in the table+ notifAssets = createUser(MASTER_REALM, "assets", PASSWORD, "Notification","Assets", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.READ_ASSETS+ });++ // Sees only own notifications; user names resolved and users recipient option shown in dialog+ notifUsers = createUser(MASTER_REALM, "users", PASSWORD, "Notification","Users", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.READ_USERS+ });++ // Sees only own notifications; user/asset names resolved, users recipient option shown; read:admin needed for users page+ notifViewUsers = createUser(MASTER_REALM, "view-users", PASSWORD, "Notification", "ViewUsers", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.READ_USERS,+ ClientRole.READ_ASSETS,+ // ClientRole.READ_ADMIN+ });++ // Can send notifications and view own notifications+ notifWrite = createUser(MASTER_REALM, "write", PASSWORD, "Notification","Write", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.WRITE_NOTIFICATIONS+ });++ // Restricted: no access to sending notifications (even though has write:notifications)+ notifRestricted = createUser(MASTER_REALM, "restricted", PASSWORD, "Notification","Restricted", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.WRITE_NOTIFICATIONS+ });+ identityService.getIdentityProvider().updateUserRealmRoles(+ MASTER_REALM,+ notifRestricted.getId(),+ identityService.getIdentityProvider().addUserRealmRoles(MASTER_REALM, notifRestricted.getId(), RESTRICTED_USER_REALM_ROLE)+ );++ // Restricted Assets: no user or realm recipient option in the send dialog (only assets)+ notifRestrictedAssets = createUser(MASTER_REALM, "restricted-assets", PASSWORD, "Notification","RestrictedAssets", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.WRITE_NOTIFICATIONS,+ ClientRole.READ_ASSETS+ });+ identityService.getIdentityProvider().updateUserRealmRoles(+ MASTER_REALM,+ notifRestrictedAssets.getId(),+ identityService.getIdentityProvider().addUserRealmRoles(MASTER_REALM, notifRestrictedAssets.getId(), RESTRICTED_USER_REALM_ROLE)+ );++ realmSmartCity = createRealm(SMARTCITY_REALM, "Smart City", true);+ smartCityUser = createUser(SMARTCITY_REALM, "smartcity", PASSWORD, "Smart", "City", "[email protected]", true, new ClientRole[]{+ ClientRole.READ_NOTIFICATIONS,+ ClientRole.WRITE_NOTIFICATIONS,+ ClientRole.READ_USERS,+ ClientRole.WRITE_USER,+ ClientRole.READ_ASSETS,+ ClientRole.WRITE_ASSETS+ });++ LOG.info("Notification RBAC test users created (password: " + PASSWORD + ")");+ }+}diff --git a/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.java b/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.javanew file mode 100644index 000000000..8edb9f5e4--- /dev/null+++ b/setup/src/notification/java/org/openremote/setup/notification/ManagerNotificationSetup.java@@ -0,0 +1,275 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.setup.notification;++import org.openremote.manager.setup.ManagerSetup;+import org.openremote.model.Container;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.UserAssetLink;+import org.openremote.model.asset.impl.ConsoleAsset;+import org.openremote.model.asset.impl.ThingAsset;+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.Notification;+import org.openremote.model.notification.PushNotificationMessage;+import org.openremote.model.notification.SentNotification;+import org.openremote.model.rules.RealmRuleset;+import org.openremote.model.rules.Ruleset;+import org.openremote.model.security.User;++import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.Arrays;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;++import static org.openremote.model.Constants.MASTER_REALM;+import static org.openremote.model.value.MetaItemType.RULE_STATE;++public class ManagerNotificationSetup extends ManagerSetup {++ /**+ * Value of the notes attribute (with RULE_STATE meta) on the seeded assets; can be matched in the when+ * clause of manually created rules to test rule triggered notifications.+ */+ public static final String RULE_TRIGGER_VALUE = "notification-test";++ private final KeycloakNotificationSetup keycloakSetup;++ public ManagerNotificationSetup(Container container, KeycloakNotificationSetup keycloakSetup) {+ super(container);+ this.keycloakSetup = keycloakSetup;+ }++ @Override+ public void onStart() throws Exception {+ super.onStart();++ // Create a shared test asset in the master realm; the notes attribute is matched by the notification rulesets+ // and needs the RULE_STATE meta item so it is available as a fact in the rule engines+ ThingAsset testAsset = new ThingAsset("Notification Test Asset");+ testAsset.setRealm(MASTER_REALM);+ testAsset.setNotes(RULE_TRIGGER_VALUE);+ testAsset.getAttribute(Asset.NOTES).ifPresent(attr -> attr.addMeta(new MetaItem<>(RULE_STATE, true)));+ testAsset = assetStorageService.merge(testAsset);+ final String assetId = testAsset.getId();++ // Link all users to the asset+ List<User> users = List.of(+ keycloakSetup.notifRead,+ keycloakSetup.notifAssets,+ keycloakSetup.notifUsers,+ keycloakSetup.notifViewUsers,+ keycloakSetup.notifWrite,+ keycloakSetup.notifRestricted,+ keycloakSetup.notifRestrictedAssets+ );++ assetStorageService.storeUserAssetLinks(+ users.stream()+ .map(u -> new UserAssetLink(MASTER_REALM, u.getId(), assetId))+ .toList()+ );++ // Provision a console asset per user so push notification targets resolve to consoles in dev+ for (User user : users) {+ createConsole(MASTER_REALM, user);+ }++ // Persist three notifications per user spaced 1 minute apart, oldest first+ Instant base = Instant.now();+ int slot = 0;+ for (User user : users) {+ persistPushNotification("Welcome", "Welcome to OpenRemote notifications", user.getId(), assetId, MASTER_REALM, base.minus(++slot, ChronoUnit.MINUTES));+ persistPushNotification("Test Alert", "This is a pending test notification", user.getId(), assetId, MASTER_REALM, base.minus(++slot, ChronoUnit.MINUTES));+ persistEmailNotification("Email Alert", "<p>This is a test email notification</p>", user.getId(), assetId, MASTER_REALM, base.minus(++slot, ChronoUnit.MINUTES));+ }++ // Smartcity realm: asset, user-asset link, and seeded notifications+ ThingAsset smartCityAsset = new ThingAsset("Smart City Test Asset");+ smartCityAsset.setRealm(KeycloakNotificationSetup.SMARTCITY_REALM);+ smartCityAsset.setNotes(RULE_TRIGGER_VALUE);+ smartCityAsset.getAttribute(Asset.NOTES).ifPresent(attr -> attr.addMeta(new MetaItem<>(RULE_STATE, true)));+ smartCityAsset = assetStorageService.merge(smartCityAsset);+ final String smartCityAssetId = smartCityAsset.getId();++ assetStorageService.storeUserAssetLinks(List.of(+ new UserAssetLink(KeycloakNotificationSetup.SMARTCITY_REALM, keycloakSetup.smartCityUser.getId(), smartCityAssetId)+ ));++ createConsole(KeycloakNotificationSetup.SMARTCITY_REALM, keycloakSetup.smartCityUser);++ persistPushNotification("Welcome", "Welcome to Smart City", keycloakSetup.smartCityUser.getId(), smartCityAssetId, KeycloakNotificationSetup.SMARTCITY_REALM, base.minus(++slot, ChronoUnit.MINUTES));+ persistPushNotification("Test Alert", "This is a pending test notification", keycloakSetup.smartCityUser.getId(), smartCityAssetId, KeycloakNotificationSetup.SMARTCITY_REALM, base.minus(++slot, ChronoUnit.MINUTES));++ // Realm ruleset whose Groovy script body sends notifications directly once on deployment, so notifications+ // with the REALM_RULESET source show up for testing the source filter. Plain rules with a when clause+ // don't evaluate reliably on initial deployment.+ rulesetStorageService.merge(new RealmRuleset(+ MASTER_REALM,+ "Notification test realm rule",+ Ruleset.Lang.GROOVY,+ buildNotificationRulesGroovy("Realm rule", assetId)+ ));++ // Global rulesets are too problematic to use for this (see global-ruleset-issues.md) so the+ // GLOBAL_RULESET source records are persisted directly instead+ persistGlobalRuleNotifications(assetId, MASTER_REALM, base.minus(++slot, ChronoUnit.MINUTES));+ persistGlobalRuleNotifications(smartCityAssetId, KeycloakNotificationSetup.SMARTCITY_REALM, base.minus(++slot, ChronoUnit.MINUTES));+ }++ /**+ * Persists a push and an email notification record with the {@link Notification.Source#GLOBAL_RULESET} source+ * targeting the given asset, mimicking what a global ruleset notification action would produce.+ */+ private void persistGlobalRuleNotifications(String assetId, String realm, Instant sentOn) {+ SentNotification push = new SentNotification()+ .setName("Global rule push")+ .setType(PushNotificationMessage.TYPE)+ .setSource(Notification.Source.GLOBAL_RULESET)+ .setSourceId("")+ .setTarget(Notification.TargetType.ASSET)+ .setTargetId(assetId)+ .setMessage(new PushNotificationMessage()+ .setTitle("Global rule push")+ .setBody("Rule triggered push notification"))+ .setRealm(realm)+ .setSentOn(sentOn);++ SentNotification email = new SentNotification()+ .setName("Global rule email")+ .setType(EmailNotificationMessage.TYPE)+ .setSource(Notification.Source.GLOBAL_RULESET)+ .setSourceId("")+ .setTarget(Notification.TargetType.ASSET)+ .setTargetId(assetId)+ .setMessage(new EmailNotificationMessage()+ .setSubject("Global rule email")+ .setHtml("<p>Rule triggered email notification</p>"))+ .setRealm(realm)+ .setSentOn(sentOn);++ persistenceService.doTransaction(em -> {+ em.merge(push);+ em.merge(email);+ });+ }++ /**+ * Builds a Groovy ruleset whose script body executes once on deployment and sends a push and an email+ * notification targeting the given assets; push resolves to the consoles of linked users, email to their addresses.+ */+ private static String buildNotificationRulesGroovy(String namePrefix, String... assetIds) {+ String targets = Arrays.stream(assetIds)+ .map(id -> "new Notification.Target(Notification.TargetType.ASSET, \"" + id + "\")")+ .collect(Collectors.joining(", "));++ return """+ import org.openremote.model.notification.EmailNotificationMessage+ import org.openremote.model.notification.Notification+ import org.openremote.model.notification.PushNotificationMessage++ // Executed once when the ruleset is deployed+ def push = new Notification()+ .setName("%1$s push")+ .setMessage(new PushNotificationMessage()+ .setTitle("%1$s push")+ .setBody("Rule triggered push notification"))+ push.setTargets(%2$s)+ notifications.send(push)++ def email = new Notification()+ .setName("%1$s email")+ .setMessage(new EmailNotificationMessage()+ .setSubject("%1$s email")+ .setHtml("<p>Rule triggered email notification</p>"))+ email.setTargets(%2$s)+ notifications.send(email)+ """.formatted(namePrefix, targets);+ }++ /**+ * Creates a {@link ConsoleAsset} with a (fake) FCM push provider token and links it to the given user, mirroring+ * what a real console registration does, so USER/ASSET/REALM push targets resolve to consoles in dev.+ */+ private void createConsole(String realm, User user) {+ ConsoleAsset console = new ConsoleAsset(user.getUsername() + " console")+ .setConsoleName(user.getUsername() + " console")+ .setConsoleVersion("1.0.0")+ .setConsolePlatform("Android 14")+ .setConsoleProvider(PushNotificationMessage.TYPE, new ConsoleProvider(+ "fcm", true, true, true, true, false, Map.of("token", "dev-fcm-token-" + user.getUsername())+ ));+ console.setRealm(realm);+ console = assetStorageService.merge(console);++ assetStorageService.storeUserAssetLinks(List.of(new UserAssetLink(realm, user.getId(), console.getId())));+ }++ private void persistPushNotification(String title, String body, String userId, String assetId, String realm, Instant sentOn) {+ PushNotificationMessage message = new PushNotificationMessage()+ .setTitle(title)+ .setBody(body);++ persistNotification(title, PushNotificationMessage.TYPE, message, userId, assetId, realm, sentOn);+ }++ private void persistEmailNotification(String subject, String html, String userId, String assetId, String realm, Instant sentOn) {+ EmailNotificationMessage message = new EmailNotificationMessage()+ .setSubject(subject)+ .setHtml(html);++ persistNotification(subject, EmailNotificationMessage.TYPE, message, userId, assetId, realm, sentOn);+ }++ private void persistNotification(String name, String type, AbstractNotificationMessage message, String userId, String assetId, String realm, Instant sentOn) {+ // One notification targeting the user directly+ SentNotification toUser = new SentNotification()+ .setName(name)+ .setType(type)+ .setSource(Notification.Source.INTERNAL)+ .setSourceId(userId)+ .setTarget(Notification.TargetType.USER)+ .setTargetId(userId)+ .setMessage(message)+ .setRealm(realm)+ .setSentOn(sentOn);++ // One notification targeting the shared asset+ SentNotification toAsset = new SentNotification()+ .setName(name)+ .setType(type)+ .setSource(Notification.Source.INTERNAL)+ .setSourceId(userId)+ .setTarget(Notification.TargetType.ASSET)+ .setTargetId(assetId)+ .setMessage(message)+ .setRealm(realm)+ .setSentOn(sentOn);++ persistenceService.doTransaction(em -> {+ em.merge(toUser);+ em.merge(toAsset);+ });+ }+}diff --git a/setup/src/notification/java/org/openremote/setup/notification/SetupTasks.java b/setup/src/notification/java/org/openremote/setup/notification/SetupTasks.javanew file mode 100644index 000000000..1821519fa--- /dev/null+++ b/setup/src/notification/java/org/openremote/setup/notification/SetupTasks.java@@ -0,0 +1,38 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+package org.openremote.setup.notification;++import org.openremote.model.Container;+import org.openremote.model.setup.Setup;++import java.util.Arrays;+import java.util.List;++public class SetupTasks implements org.openremote.model.setup.SetupTasks {++ @Override+ public List<Setup> createTasks(Container container, String setupType, boolean keycloakEnabled) {+ KeycloakNotificationSetup keycloakSetup = new KeycloakNotificationSetup(container);+ return Arrays.asList(+ keycloakSetup,+ new ManagerNotificationSetup(container, keycloakSetup)+ );+ }+}diff --git a/setup/src/notification/resources/META-INF/services/org.openremote.model.setup.SetupTasks b/setup/src/notification/resources/META-INF/services/org.openremote.model.setup.SetupTasksnew file mode 100644index 000000000..6d49dae14--- /dev/null+++ b/setup/src/notification/resources/META-INF/services/org.openremote.model.setup.SetupTasks@@ -0,0 +1 @@+org.openremote.setup.notification.SetupTasksdiff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovyindex 8455b1c9f..68f2f20a2 100644--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy@@ -196,13 +196,13 @@ class NotificationTest extends Specification implements ManagerContainerTrait {assert notificationMessages.count { m -> m instanceof PushNotificationMessage && m.title == "Test Action" && m.body == "Click to cancel" && m.action != null } == 3}- when: "a regular user sends a push notification to an entire realm"+ when: "a regular user without write:notifications sends a push notification to an entire realm"testuser2NotificationResource.sendNotification(null, notification)- then: "no notification should have been sent"+ then: "the request should be forbidden (no write:notifications role)"WebApplicationException ex = thrown()ex.response.withCloseable { r ->- assert r.status == 400+ assert r.status == 403return true}@@ -254,10 +254,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {when: "an anonymous user sends a push notification to a user"anonymousNotificationResource.sendNotification(null, notification)- then: "no notification should have been sent"+ then: "the request should be forbidden (no write:notifications role)"ex = thrown()ex.response.withCloseable { r ->- assert r.status == 400+ assert r.status == 403return true}@@ -289,19 +289,18 @@ class NotificationTest extends Specification implements ManagerContainerTrait {return true}- when: "a regular user sends a push notification to the console assets in the same realm"+ when: "a regular user without write:notifications sends a push notification to the console assets in the same realm"notificationIds.clear()advancePseudoClock(1, TimeUnit.HOURS, container)testuser2NotificationResource.sendNotification(null, notification)- then: "the notification should have been sent (inc. testuser2 as message was direct to console)"- conditions.eventually {- assert notificationIds.size() == 4- assert notificationTargetIds.contains(testuser2Console.id)- assert notificationTargetIds.contains(testuser3Console1.id)- assert notificationTargetIds.contains(testuser3Console2.id)- assert notificationTargetIds.contains(anonymousConsole.id)+ then: "the request should be forbidden and no notification sent (write:notifications is now required to send)"+ ex = thrown()+ ex.response.withCloseable { r ->+ assert r.status == 403+ return true}+ notificationIds.size() == 0when: "a notification is sent using the same mechanism as an asset ruleset"notificationIds.clear()@@ -395,8 +394,8 @@ class NotificationTest extends Specification implements ManagerContainerTrait {and: "the notification should be recorded in the DB with the exception set as the error"conditions.eventually {- notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id)- notifications.last().error == "Failed to send notification"+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null)+ notifications.first().error == "Failed to send notification"}@@ -406,9 +405,9 @@ class NotificationTest extends Specification implements ManagerContainerTrait {and: "all notifications sent to consoles in the building realm should be available via the REST API"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser2Console.id).length == 3- notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id)- assert notifications.length == 6+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser2Console.id, null, null, null, null, null).length == 2+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id, null, null, null, null, null)+ assert notifications.length == 5assert notifications.every {n ->PushNotificationMessage pushMessage = n.message as PushNotificationMessagepushMessage.getTitle() == "Test Action" &&@@ -417,8 +416,8 @@ class NotificationTest extends Specification implements ManagerContainerTrait {n.deliveredOn == null &&n.acknowledgedOn == null}- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 8- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id).length == 4+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 7+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id, null, null, null, null, null).length == 3}when: "the admin user marks a Building console notification as delivered and requests the notifications for Building consoles"@@ -426,8 +425,8 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "the notification should have been updated"conditions.eventually {- notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id)- assert notifications.length == 6+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id, null, null, null, null, null)+ assert notifications.length == 5assert notifications.count {n -> n.deliveredOn != null} == 1}@@ -436,8 +435,8 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "the notification should have been updated"conditions.eventually {- notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id)- assert notifications.length == 6+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id, null, null, null, null, null)+ assert notifications.length == 5assert notifications.count {n -> n.deliveredOn != null && n.acknowledgedOn != null && n.acknowledgement == "\"dismissed\""} == 1}@@ -456,7 +455,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "the notification should have been updated"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).count {it.deliveredOn != null} == 1+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id, null, null, null, null, null).count {it.deliveredOn != null} == 1}// TODO: Update once console permissions model finalised@@ -470,12 +469,12 @@ class NotificationTest extends Specification implements ManagerContainerTrait {// }when: "an anonymous user marks a console notification for their own console as delivered"- notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id)+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id, null, null, null, null, null)anonymousNotificationResource.notificationDelivered(null, anonymousConsole.id, notifications.find {n -> n.targetId == anonymousConsole.id}.id)then: "the notification should have been updated"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id).count {it.deliveredOn != null} == 1+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id, null, null, null, null, null).count {it.deliveredOn != null} == 1}when: "a regular user tries to remove notifications"@@ -499,14 +498,14 @@ class NotificationTest extends Specification implements ManagerContainerTrait {}when: "the admin user removes notifications by timestamp and the notifications are retrieved again"- notifications = adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, null).reverse(true)+ notifications = adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, null, null, null, null, null, null)def sentNotification = notifications[0]def removeCount = notifications.count {it.sentOn >= sentNotification.sentOn}adminNotificationResource.removeNotifications(null, null, PushNotificationMessage.TYPE, sentNotification.sentOn.toEpochMilli(), null, null, null, null)then: "notifications sent after or at that time should have been removed"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, null).length == (notifications.length - removeCount)+ assert adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, null, null, null, null, null, null).length == (notifications.length - removeCount)}when: "the admin user removes notifications sent to specific console assets without other constraints and the notifications are retrieved again"@@ -515,9 +514,9 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "all notifications sent to those consoles should have been removed"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 0- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 0- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id).length == 4+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id, null, null, null, null, null).length == 0+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 0+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id, null, null, null, null, null).length == 3}when: "the admin user removes notifications by type and the notifications are retrieved again"@@ -525,7 +524,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "the notifications should have been removed"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, anonymousConsole.id).length == 0+ assert adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, anonymousConsole.id, null, null, null, null, null).length == 0}when: "the admin user removes notifications without sufficient constraints"@@ -557,7 +556,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "the notification should have been sent to the console"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 1+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 1}when: "a repeat frequency is set and a notification with the same name and scope as a previous notification is sent within the repeat window"@@ -565,7 +564,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "no new notifications should have been sent"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 1+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 1}when: "a repeat frequency is set and a notification with the same name but different scope is sent within the repeat window"@@ -573,7 +572,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "new notifications should have been sent"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 2+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 2}when: "time advances less than the repeat frequency and the notification is sent again"@@ -582,7 +581,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "no new notifications should have been sent"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 2+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 2}when: "time advances more than the repeat frequency and the notification is sent again"@@ -591,7 +590,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "new notifications should have been sent"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 3+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 3}when: "a repeat interval is used and a notification with the same name and scope is sent within the repeat window"@@ -601,7 +600,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "no new notifications should have been sent"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 3+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 3}when: "time advances more than the repeat interval and the notification is sent again"@@ -610,17 +609,17 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "new notifications should have been sent"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 4+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id, null, null, null, null, null).length == 4}and: "notifications are retrieved only for the past day only the relevant notifications should have been returned"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000*24), null, null, null, testuser3Console2.id).length == 1+ assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000*24), null, null, null, testuser3Console2.id, null, null, null, null, null).length == 1}and: "notifications are retrieved only for the past 40 days only the relevant notifications should have been returned"conditions.eventually {- assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000L*24*40), null, null, null, testuser3Console2.id).length == 4+ assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000L*24*40), null, null, null, testuser3Console2.id, null, null, null, null, null).length == 4}cleanup: "the mock is removed"@@ -1071,4 +1070,162 @@ class NotificationTest extends Specification implements ManagerContainerTrait {/*when: "if the notification became valid, and the TRIGGER_ASSETS placeholder is inserted"((LocalizedNotificationMessage) invalidNotification.getMessage()).setMessage("nl", new PushNotificationMessage())*/}++ def "Check get notifications by realm access control"() {++ List<Message> sentEmails = new CopyOnWriteArrayList<>()++ given: "the container environment is started with a mock email handler"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)+ def notificationService = container.getService(NotificationService.class)+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)++ and: "a mock email notification handler that records sent emails (so notifications get persisted without SMTP)"+ EmailNotificationHandler mockEmailNotificationHandler = Spy(emailNotificationHandler)+ mockEmailNotificationHandler.isValid() >> true+ mockEmailNotificationHandler.sendMessage(_ as Message) >> {+ Message email ->+ sentEmails << email+ return NotificationSendResult.success()+ }+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockEmailNotificationHandler)++ and: "the building realm and the ids of two of its users"+ def buildingRealm = managerTestSetup.realmBuildingName+ def testuser2Id = keycloakTestSetup.testuser2Id+ // building user: has read:notifications and receives the realm email; testuser2: receives the email but has no read:notifications+ def buildingUserId = keycloakTestSetup.buildingUserId++ and: "a transient building user whose ONLY granting role is read:notifications"+ // Created in-test (not in KeycloakTestSetup) so the shared fixture and the user-count assertions of other+ // specs are untouched; startContainer purges users that aren't part of the fixture baseline between features.+ def identityProvider = container.getService(ManagerIdentityService.class).getIdentityProvider()+ def notifUserInput = new User()+ notifUserInput.username = "notifuser"+ notifUserInput.firstName = "Notif"+ notifUserInput.lastName = "User"+ notifUserInput.email = "[email protected]"+ notifUserInput.enabled = true+ def notifUser = identityProvider.createUpdateUser(buildingRealm, notifUserInput, "notifuser", true)+ identityProvider.updateUserClientRoles(buildingRealm, notifUser.id, KEYCLOAK_CLIENT_ID, READ_NOTIFICATIONS_ROLE)+ def notifUserId = notifUser.id++ and: "authenticated users with differing permissions"+ def adminAccessToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, MASTER_REALM_ADMIN_USER, getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT))+ def testuser2AccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "testuser2", "testuser2")+ def buildingUserAccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "building", "building")+ def notifUserAccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "notifuser", "notifuser")++ and: "a helper that requests notifications for a realm over REST as the given user"+ // realm is selected via the realmId query param (the consolidated endpoint has no realm path segment)+ def requestNotificationsByRealm = { String authRealm, String token, String realmId ->+ getClientApiTarget(serverUri(serverPort), authRealm, token)+ .path("notification").queryParam("realmId", realmId)+ .request().get()+ }++ when: "an email notification is sent to the entire building realm"+ def notification = new Notification(+ "RealmAccessTest",+ new EmailNotificationMessage().setSubject("Realm access test").setText("Hello building"),+ Collections.singletonList(new Notification.Target(Notification.TargetType.REALM, buildingRealm)), null, null)+ notificationService.sendNotification(notification, Notification.Source.REALM_RULESET, buildingRealm)++ then: "all three recipients' notifications are persisted correctly and a superuser can read them in full, cross-realm from master"+ conditions.eventually {+ assert sentEmails.size() == 3+ def response = requestNotificationsByRealm(MASTER_REALM, adminAccessToken, buildingRealm)+ assert response.status == 200+ def sent = response.readEntity(SentNotification[].class).findAll { it.name == "RealmAccessTest" }+ response.close()++ // one persisted notification per email recipient, each fully populated and unredacted for the superuser+ assert sent.size() == 3+ assert sent.collect { it.targetId }.toSet() == [testuser2Id, buildingUserId, notifUserId].toSet()+ assert sent.every { it.id != null }+ assert sent.every { it.name == "RealmAccessTest" }+ assert sent.every { it.type == EmailNotificationMessage.TYPE }+ assert sent.every { it.target == Notification.TargetType.USER }+ assert sent.every { it.source == Notification.Source.REALM_RULESET }+ assert sent.every { it.sourceId == buildingRealm }+ assert sent.every { it.realm == buildingRealm }+ assert sent.every { it.sentOn != null && it.deliveredOn == null && it.acknowledgedOn == null && it.error == null }+ assert sent.every { (it.message as EmailNotificationMessage).subject == "Realm access test" }+ assert sent.every { (it.message as EmailNotificationMessage).text == "Hello building" }+ }++ when: "a user without read:notifications or read:admin requests notifications for their realm"+ def forbiddenResponse = requestNotificationsByRealm(buildingRealm, testuser2AccessToken, buildingRealm)++ then: "access is forbidden by the endpoint role check"+ forbiddenResponse.status == 403+ forbiddenResponse.close()++ when: "a restricted user (read:notifications + read:users) requests notifications for their own realm"+ def ownRealmResponse = requestNotificationsByRealm(buildingRealm, buildingUserAccessToken, buildingRealm)+ def ownNotifications = ownRealmResponse.readEntity(SentNotification[].class)+ ownRealmResponse.close()+ def ownSent = ownNotifications.findAll { it.name == "RealmAccessTest" }++ then: "a restricted user only sees the notification that targets them, with full details"+ ownRealmResponse.status == 200+ ownSent.size() == 1+ ownSent[0].name == "RealmAccessTest"+ ownSent[0].type == EmailNotificationMessage.TYPE+ ownSent[0].target == Notification.TargetType.USER+ ownSent[0].targetId == buildingUserId+ ownSent[0].source == Notification.Source.REALM_RULESET+ ownSent[0].sourceId == buildingRealm+ ownSent[0].realm == buildingRealm+ (ownSent[0].message as EmailNotificationMessage).subject == "Realm access test"+ // being restricted, they don't see notifications addressed to other users in the realm+ !ownNotifications.any { it.targetId == testuser2Id }+ !ownNotifications.any { it.targetId == notifUserId }++ when: "a non-restricted user whose only granting role is read:notifications requests their realm's notifications"+ def notifUserResponse = requestNotificationsByRealm(buildingRealm, notifUserAccessToken, buildingRealm)+ def notifNotifications = notifUserResponse.readEntity(SentNotification[].class)+ notifUserResponse.close()+ def notifSent = notifNotifications.findAll { it.name == "RealmAccessTest" }++ then: "read:notifications lets a non-restricted user read ALL of the realm's notifications, but ids are sanitized without read:users/read:assets"+ notifUserResponse.status == 200+ // unlike the restricted user, they see every recipient's notification in the realm, not just their own+ notifSent.size() == 3+ notifSent.collect { it.target }.toSet() == [Notification.TargetType.USER].toSet()+ notifSent.every { it.name == "RealmAccessTest" }+ notifSent.every { it.type == EmailNotificationMessage.TYPE }+ notifSent.every { it.source == Notification.Source.REALM_RULESET }+ notifSent.every { it.realm == buildingRealm }+ notifSent.every { (it.message as EmailNotificationMessage).subject == "Realm access test" }+ // without read:users the recipient ids are stripped; realm ruleset source ids are realm names and stay visible+ notifSent.every { it.targetId == null }+ notifSent.every { it.sourceId == buildingRealm }++ when: "a non-restricted building user requests notifications for the master realm they cannot access"+ def otherRealmResponse = requestNotificationsByRealm(buildingRealm, notifUserAccessToken, MASTER_REALM)++ then: "access is forbidden — even a non-restricted user cannot read another realm's notifications"+ otherRealmResponse.status == 403+ otherRealmResponse.close()++ when: "a user with read:notifications requests notifications without specifying a realm"+ def noRealmResponse = getClientApiTarget(serverUri(serverPort), buildingRealm, buildingUserAccessToken)+ .path("notification")+ .request().get()+ def noRealmSent = noRealmResponse.readEntity(SentNotification[].class).findAll { it.name == "RealmAccessTest" }++ then: "the query defaults to the caller's own realm rather than failing"+ noRealmResponse.status == 200+ // the restricted building user still only sees the notification targeting them+ noRealmSent.size() == 1+ noRealmSent[0].targetId == buildingUserId+ noRealmResponse.close()++ cleanup: "the mock is removed"+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), emailNotificationHandler)+ }}diff --git a/ui/app/manager/package.json b/ui/app/manager/package.jsonindex 88c5aeb68..07de62842 100644--- a/ui/app/manager/package.json+++ b/ui/app/manager/package.json@@ -41,6 +41,7 @@"@openremote/or-attribute-picker": "workspace:*","@openremote/or-components": "workspace:*","@openremote/or-dashboard-builder": "workspace:*",+ "@openremote/or-element": "workspace:*","@openremote/or-icon": "workspace:*","@openremote/or-json-forms": "workspace:*","@openremote/or-log-viewer": "workspace:*",diff --git a/ui/app/manager/rsbuild.config.ts b/ui/app/manager/rsbuild.config.tsindex 0a01b8e99..420b10cad 100644--- a/ui/app/manager/rsbuild.config.ts+++ b/ui/app/manager/rsbuild.config.ts@@ -32,6 +32,7 @@ export default defineConfig({"@openremote/or-components": "../../component/or-components/src","@openremote/or-chart": "../../component/or-chart/src","@openremote/or-dashboard-builder": "../../component/or-dashboard-builder/src",+ "@openremote/or-element": "../../component/or-element/src","@openremote/or-gauge": "../../component/or-gauge/src","@openremote/or-icon": "../../component/or-icon/src","@openremote/or-json-forms": "../../component/or-json-forms/src",diff --git a/ui/app/manager/src/components/notifications/or-notification-form.ts b/ui/app/manager/src/components/notifications/or-notification-form.tsnew file mode 100644index 000000000..5c47d3d64--- /dev/null+++ b/ui/app/manager/src/components/notifications/or-notification-form.ts@@ -0,0 +1,732 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import {css, html} from "lit";+import {OrElement} from "@openremote/or-element";+import {customElement, property, state} from "lit/decorators.js";+import {when} from "lit/directives/when.js";+import { i18next } from "@openremote/or-translate";+import manager, {Util} from "@openremote/core";+import {+ Asset,+ EmailNotificationMessage,+ Notification,+ NotificationTargetType,+ PushNotificationButton,+ PushNotificationMessage,+ PushNotificationMessageMessagePriority,+ SentNotification,+ User+} from "@openremote/model";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {OrAssetTree, OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";+import "@openremote/or-asset-tree";+import {OrVaadinSelect, SelectItem} from "@openremote/or-vaadin-components/or-vaadin-select";+// or-vaadin-checkbox-group registers the native vaadin-checkbox used for its children+import "@openremote/or-vaadin-components/or-vaadin-checkbox-group";+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;++// 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.+const ACTION_URL_PATTERN = "^[a-zA-Z][a-zA-Z0-9+.\\-]*://.+$";++interface TargetOption {+ label: string;+ value: string;+}++export class OrNotificationFormChangedEvent extends CustomEvent<void> {+ static readonly NAME = "or-notification-form-changed";++ constructor() {+ super(OrNotificationFormChangedEvent.NAME, {+ bubbles: true,+ composed: true+ });+ }+}++@customElement("or-notification-form")+export class OrNotificationForm extends OrElement {+ static styles = css`+ :host {+ display: block;+ }++ .form-container {+ height: 100%;+ }++ or-vaadin-select,+ or-vaadin-checkbox-group,+ or-vaadin-text-field,+ or-vaadin-text-area,+ or-vaadin-toggle {+ width: 100%;+ margin-bottom: 16px;+ }++ or-asset-tree {+ flex: 0 0 auto;+ }++ /* Grid styles */++ .formGridContainer {+ position: relative;+ display: grid;+ grid-template-columns: 1fr 2fr;+ grid-template-areas:+ "targetContainer messageContentContainer"+ "targetContainer actionButtonContainer";+ gap: var(--lumo-space-m);+ height: 100%;+ }++ .formGridContainer-readonly {+ position: relative;+ display: grid;+ grid-template-columns: 1fr 2fr;+ grid-template-areas:+ "targetContainer messageContentContainer"+ "propContainer actionButtonContainer";+ gap: var(--lumo-space-m);+ height: 100%;+ }++ [class*="formGridContainer"] > * {+ background-color: white;+ border-radius: var(--lumo-border-radius-m);+ box-sizing: border-box;+ padding: var(--lumo-space-l);+ }++ .targetContainer {+ grid-area: targetContainer;+ position: absolute;+ width: 100%;+ height: 100%;+ }++ .messageContentContainer {+ grid-area: messageContentContainer;+ height: 100%;+ }++ .actionButtonContainer {+ grid-area: actionButtonContainer;+ }++ .propContainer {+ grid-area: propContainer;+ }++ .target-area {+ flex: 1 1 auto;+ overflow: auto;+ }++ :host([readonly]) .form-container {+ opacity: 0.9;+ }++ @media (max-width: 1024px) {+ :host {+ height: auto;+ }++ .formGridContainer,+ .formGridContainer-readonly {+ grid-template-columns: 1fr;+ height: auto;+ }++ .formGridContainer {+ grid-template-areas:+ "targetContainer"+ "messageContentContainer"+ "actionButtonContainer";+ }++ .formGridContainer-readonly {+ grid-template-areas:+ "targetContainer"+ "messageContentContainer"+ "propContainer"+ "actionButtonContainer";+ }++ /* Return the target column to normal flow so its stacked row keeps a height */+ .targetContainer {+ position: relative;+ height: auto;+ }+ }+ `;++ @state()+ protected _message: NotificationMessage = {type: "push"};++ @state()+ protected _targetType: NotificationTargetType = this._defaultTargetType();++ @state()+ protected _targets: string[] = [];++ @state()+ protected _users?: User[];++ @state()+ protected _assets?: Asset[];++ @state()+ protected _realms?: string[];++ @state()+ protected _targetOptions: TargetOption[] = [];++ @state()+ protected _selectedAssetIds: string[] = [];++ @property({type: Boolean})+ public disabled = false;++ @property({type: Boolean})+ public readonly = false;++ @property({type: Object})+ public notification?: SentNotification;++ // The realm to load target data for; supplied by the page from the store so it stays in sync with the app realm+ @property({type: String})+ public realm?: string;++ 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.+ if (this.readonly) {+ return;+ }++ const canReadAssets = manager.hasRole("read:assets") || manager.hasRole("read:admin");++ const promises = [];+ if (canReadAssets) {+ promises.push(this._loadAssets());+ }+ if (manager.hasRole("read:users") || manager.hasRole("read:admin")) {+ promises.push(this._loadUsers());+ }+ if (manager.hasRole("read:admin")) {+ promises.push(this._loadRealms());+ }+ await Promise.all(promises);++ // Select the initial target type through the shared path so its option list is populated too+ await this._onTargetTypeChanged(this._defaultTargetType());+ }++ updated(changedProps: Map<string, any>) {+ if (changedProps.has('notification') && this.notification) {+ this._populateFromNotification()+ }+ // Reload target data when the realm changes; skip the initial assignment (handled by firstUpdated) and+ // readonly mode (the details view doesn't use the option lists)+ if (!this.readonly && changedProps.has('realm') && changedProps.get('realm') !== undefined) {+ this._reloadTargetData();+ }+ // Notify listeners (e.g. the create dialog) so they can re-evaluate form validity+ if (!this.readonly) {+ this.dispatchEvent(new OrNotificationFormChangedEvent());+ }+ }++ /**+ * Resets the form to its initial empty state. Called when the create dialog is (re)opened, since the form+ * instance persists between opens. Target data isn't reloaded here — that's driven by the realm property.+ */+ public reset() {+ this._message = {type: "push"};+ this._targets = [];+ this._selectedAssetIds = [];+ return this._onTargetTypeChanged(this._defaultTargetType());+ }++ /** Users are the default recipient type; falls back to assets for callers not allowed to pick users. */+ protected _defaultTargetType(): NotificationTargetType {+ const canSelectUsers = !manager.isRestrictedUser()+ && (manager.hasRole("read:users") || manager.hasRole("read:admin"));+ return canSelectUsers ? NotificationTargetType.USER : NotificationTargetType.ASSET;+ }++ /** Drops cached realm-specific target data and rebuilds the options for the current target type. */+ protected _reloadTargetData() {+ this._users = undefined;+ this._assets = undefined;+ this._realms = undefined;+ // The asset tree fetches and caches its nodes itself+ this.shadowRoot?.querySelector<OrAssetTree>("#asset-selector")?.refresh();+ return this._onTargetTypeChanged(this._targetType);+ }++ protected async _loadUsers(): Promise<User[]> {+ if (!manager.hasRole("read:users") && !manager.hasRole("read:admin")) {+ return [];+ }+ try {+ const response = await manager.rest.api.UserResource.query({+ realmPredicate: { name: this.realm ?? manager.displayRealm },+ serviceUsers: false+ });+ // filter out keycloak service account+ return this._users = response.data.filter((u) => u.username !== 'manager-keycloak');+ } catch (error) {+ console.error("Failed to load users:", error);+ showSnackbar(undefined, i18next.t("loadingUsersFailed"));+ return [];+ }+ }++ protected async _loadAssets(): Promise<Asset[]> {+ if (!manager.hasRole("read:assets") && !manager.hasRole("read:admin")) {+ return [];+ }+ try {+ const response = await manager.rest.api.AssetResource.queryAssets({+ realm: { name: this.realm ?? manager.displayRealm }+ });+ this._assets = response.data;+ return response.data;+ } catch (error) {+ console.error("Failed to load assets:", error);+ showSnackbar(undefined, i18next.t("loadingAssetsFailed"));+ return [];+ }+ }++ protected async _loadRealms(): Promise<string[]> {+ try {+ const response = await manager.rest.api.RealmResource.getAccessible();+ this._realms = response.data.map(realm => realm.name);+ return this._realms;+ } catch (error) {+ console.error("Failed to load realms:", error);+ showSnackbar(undefined, i18next.t("loadingRealmsFailed"));+ return [];+ }+ }++ protected async _onTargetTypeChanged(type: NotificationTargetType) {+ if (!type) return;++ this._targetType = type;+ this._targetOptions = [];+ // Drop any previously selected targets; they belong to the previous target type (or realm) and would+ // otherwise be submitted as ids of the new type+ this._targets = [];+ this._selectedAssetIds = [];++ switch (type) {+ case NotificationTargetType.USER:+ if (!this._users) {+ await this._loadUsers();+ }+ this._targetOptions = (this._users || []).map(user => ({+ label: user.username,+ value: user.id+ }));+ break;++ case NotificationTargetType.ASSET:+ if (!this._assets) {+ await this._loadAssets();+ }+ break;++ case NotificationTargetType.REALM:+ if (!this._realms) {+ await this._loadRealms();+ }+ this._targetOptions = (this._realms || []).map(realm => ({+ label: realm,+ value: realm+ }));+ break;+ }++ this.requestUpdate();+ }++ protected _onAssetSelectionChanged(e: OrAssetTreeSelectionEvent): void {+ this._selectedAssetIds = e.detail.newNodes.map(node => node.asset.id);+ this._targets = this._selectedAssetIds;+ }++ protected _onMessageTypeChanged(type: NotificationMessage["type"]) {+ if (type === this._message.type) return;+ this._message = {type} as NotificationMessage;+ }++ protected _updateMessage(props: Partial<NotificationMessage>) {+ this._message = {...this._message, ...props} as NotificationMessage;+ }++ /**+ * Humanizes an enum-like ALL_CAPS token (e.g. "REALM_RULESET" -> "Realm_ruleset") for display. Any other+ * value (IDs, realm names and other case-sensitive strings) is returned unchanged so it isn't corrupted.+ */+ private _normalizeValue(value: string): string {+ if (value && /^[A-Z][A-Z0-9_]*$/.test(value)) {+ return value.charAt(0) + value.slice(1).toLowerCase();+ }+ return value;+ }++ private async _populateFromNotification() {+ if (!this.notification) return;++ this._message = (this.notification.message || {type: "push"}) as NotificationMessage;+ this._targetType = this.notification.target || NotificationTargetType.ASSET;+ this._targets = this.notification.targetId ? [this.notification.targetId] : [];++ this.requestUpdate();+ }++ /**+ * Builds a {@link Notification} from the current form state or returns null when required fields are missing.+ */+ public getNotification(): Notification | null {+ const name = this._message.type === "email"+ ? (this._message as EmailNotificationMessage).subject+ : (this._message as PushNotificationMessage).title;+ const body = this._message.type === "email"+ ? (this._message as EmailNotificationMessage).html+ : (this._message as PushNotificationMessage).body;++ if (!name || !body || !this._targetType || this._targets.length === 0) {+ return null;+ }++ let message = this._message;+ if (message.type === "push") {+ const push = {...message} as PushNotificationMessage;+ // The action URL is optional, but reject a malformed one+ if (push.action?.url && !new RegExp(ACTION_URL_PATTERN).test(push.action.url)) {+ return null;+ }+ // Drop empty button slots and attach the action to the open button (index 0)+ const buttons = (push.buttons || []).filter(button => button?.title);+ if (buttons.length > 0) {+ if (push.action) {+ buttons[0] = {...buttons[0], action: push.action};+ }+ push.buttons = buttons;+ } else {+ delete push.buttons;+ }+ message = push;+ }++ return {+ name,+ message,+ targets: this._targets.map(id => ({+ id,+ type: this._targetType+ }))+ };+ }++ protected render() {+ const inputDisabled = this.disabled || this.readonly;++ return html`+ <div class="form-container">+ <div class="${this.readonly ? "formGridContainer-readonly" : "formGridContainer"}">+ ${this._renderTargetContainer(inputDisabled)}+ ${this._renderMessageContentContainer(inputDisabled)}+ ${this._message.type === "push" ? this._renderActionButtonContainer(inputDisabled) : ''}+ ${this.readonly ? this._renderPropertiesContainer() : ''}+ </div>+ </div>+ `;+ }++ protected _renderPropertiesContainer() {+ if (!this.notification) return '';++ const canReadUsers = manager.hasRole("read:users") || manager.hasRole("read:admin");+ const source = (canReadUsers && this.notification.sourceId) ?+ `${this._normalizeValue(this.notification.source)}, ${this.notification.sourceId}` :+ this._normalizeValue(this.notification.source);+ const status = this.notification.error ? i18next.t("error")+ : this.notification.deliveredOn ? i18next.t("delivered")+ : i18next.t("sent");+ const sent = this.notification.sentOn ? new Date(this.notification.sentOn).toLocaleString() : '-';+ const delivered = this.notification.deliveredOn ? new Date(this.notification.deliveredOn).toLocaleString() : '-';++ return html`+ <div class="propContainer">+ <h4><or-translate value="properties"></or-translate></h4>+ ${this._renderReadOnlyField("source", source)}+ ${this._renderReadOnlyField("status", status)}+ ${this._renderReadOnlyField("sent", sent)}+ ${this._renderReadOnlyField("delivered", delivered)}+ </div>+ `;+ }++ // TODO: Make the Target field similar to the cell in the table: icon with asset/user/realm name instead of ID+ protected _renderTargetContainer(inputDisabled: boolean) {+ if (inputDisabled) {+ const canSeeTargetId = manager.hasRole("read:admin")+ || (this._targetType === NotificationTargetType.USER && manager.hasRole("read:users"))+ || (this._targetType === NotificationTargetType.ASSET && manager.hasRole("read:assets"));+ const targetDisplay = canSeeTargetId ? this._normalizeValue(this._targets[0]) : '-';+ return html`+ <div class="targetContainer">+ <h4 style="flex:0 0 auto;"><or-translate value="notifications.target"></or-translate></h4>+ ${this._renderReadOnlyField("notifications.targetType", this._normalizeValue(this._targetType))}+ ${this._renderReadOnlyField("notifications.target", targetDisplay)}+ </div>+ `;+ }++ const allowedTargetTypes: SelectItem[] = [];+ if (manager.hasRole("read:assets") || manager.hasRole("read:admin")) {+ allowedTargetTypes.push({label: i18next.t("notifications.targetTypes.ASSET"), value: NotificationTargetType.ASSET});+ }+ if (!manager.isRestrictedUser() && (manager.hasRole("read:users") || manager.hasRole("read:admin"))) {+ allowedTargetTypes.unshift({label: i18next.t("notifications.targetTypes.USER"), value: NotificationTargetType.USER});+ }+ // Realm targets only work for superusers+ if (manager.isSuperUser()) {+ allowedTargetTypes.push({label: i18next.t("notifications.targetTypes.REALM"), value: NotificationTargetType.REALM});+ }++ return html`+ <div class="targetContainer">+ <h4 style="flex:0 0 auto;"><or-translate value="notifications.target"></or-translate></h4>+ <or-vaadin-select+ style="flex:0 0 auto;"+ id="targetType"+ required+ ?disabled="${inputDisabled || allowedTargetTypes.length === 1}"+ .items="${allowedTargetTypes}"+ value="${this._targetType}"+ @change="${(ev: Event) => this._onTargetTypeChanged((ev.currentTarget as OrVaadinSelect).value as NotificationTargetType)}">+ <or-translate slot="label" value="notifications.targetType"></or-translate>+ </or-vaadin-select>++ <div class="target-area">+ ${when(this._targetType === NotificationTargetType.ASSET,+ () => html`+ <or-asset-tree+ id="asset-selector"+ .selectedIds="${this._selectedAssetIds}"+ .showSortBtn="${false}"+ checkboxes+ expandNodes+ readonly+ @or-asset-tree-selection="${(e: OrAssetTreeSelectionEvent) => this._onAssetSelectionChanged(e)}"+ ></or-asset-tree>+ `,+ () => html`+ <or-vaadin-checkbox-group+ id="target"+ required+ theme="vertical"+ ?disabled="${inputDisabled}"+ .value="${this._targets}"+ @value-changed="${(ev: CustomEvent) => {+ // Guard against the value-changed re-firing when we re-bind .value, which would recurse+ if (!Util.objectsEqual(ev.detail.value, this._targets, true)) {+ this._targets = [...ev.detail.value];+ }+ }}">+ <or-translate slot="label" value="${this._targetType === NotificationTargetType.REALM ? "notifications.targetListLabel.REALM" : "notifications.targetListLabel.USER"}"></or-translate>+ ${this._targetOptions+ .sort(Util.sortByString((option: TargetOption) => option.label))+ .map(option => html`+ <vaadin-checkbox value="${option.value}" label="${option.label}"></vaadin-checkbox>+ `)}+ </or-vaadin-checkbox-group>+ `+ )}+ </div>+ </div>+ `;+ }++ protected _renderMessageContentContainer(inputDisabled: boolean) {+ const messageTypeOptions: SelectItem[] = [+ {label: i18next.t("notifications.types.push"), value: "push"},+ {label: i18next.t("notifications.types.email"), value: "email"}+ ];++ return html`+ <div class="messageContentContainer">+ <h4><or-translate value="content"></or-translate></h4>+ <or-vaadin-select+ id="messageType"+ required+ ?disabled="${inputDisabled}"+ .items="${messageTypeOptions}"+ value="${this._message.type}"+ @change="${(ev: Event) => this._onMessageTypeChanged((ev.currentTarget as OrVaadinSelect).value as NotificationMessage["type"])}">+ <or-translate slot="label" value="type"></or-translate>+ </or-vaadin-select>+ ${this._message.type === "push"+ ? this._renderPushContent(this._message as PushNotificationMessage, inputDisabled)+ : this._renderEmailContent(this._message as EmailNotificationMessage, inputDisabled)}+ </div>+ `;+ }++ protected _renderPushContent(message: PushNotificationMessage, inputDisabled: boolean) {+ return html`+ <or-vaadin-text-field+ id="notificationTitle"+ required+ ?readonly="${inputDisabled}"+ value="${message.title || ''}"+ @change="${(ev: Event) => this._updateMessage({title: (ev.currentTarget as HTMLInputElement).value})}">+ <or-translate slot="label" value="title"></or-translate>+ </or-vaadin-text-field>++ <or-vaadin-text-area+ id="notificationBody"+ required+ style="flex: 1;"+ min-rows="4"+ ?readonly="${inputDisabled}"+ value="${message.body || ''}"+ @change="${(ev: Event) => this._updateMessage({body: (ev.currentTarget as HTMLInputElement).value})}">+ <or-translate slot="label" value="body"></or-translate>+ </or-vaadin-text-area>+ `;+ }++ protected _renderEmailContent(message: EmailNotificationMessage, inputDisabled: boolean) {+ return html`+ <or-vaadin-text-field+ id="notificationSubject"+ required+ ?readonly="${inputDisabled}"+ value="${message.subject || ''}"+ @change="${(ev: Event) => this._updateMessage({subject: (ev.currentTarget as HTMLInputElement).value})}">+ <or-translate slot="label" value="subject"></or-translate>+ </or-vaadin-text-field>++ <or-vaadin-text-area+ id="notificationEmailBody"+ required+ style="flex: 1;"+ min-rows="4"+ ?readonly="${inputDisabled}"+ value="${message.html ?? message.text ?? ''}"+ @change="${(ev: Event) => this._updateMessage({html: (ev.currentTarget as HTMLInputElement).value})}">+ <or-translate slot="label" value="body"></or-translate>+ </or-vaadin-text-area>+ `;+ }++ protected _renderActionButtonContainer(inputDisabled: boolean) {+ const message = this._message as PushNotificationMessage;+ const priorityOptions: SelectItem[] = [+ {label: i18next.t('normal'), value: PushNotificationMessageMessagePriority.NORMAL},+ {label: i18next.t('high'), value: PushNotificationMessageMessagePriority.HIGH}+ ];++ return html`+ <div class="actionButtonContainer">+ <h4><or-translate value="actions"></or-translate></h4>+ <or-vaadin-text-field+ id="actionUrl"+ type="url"+ pattern="${ACTION_URL_PATTERN}"+ error-message="${i18next.t("invalidUrl")}"+ placeholder="https://example.com"+ ?readonly="${inputDisabled}"+ value="${message.action?.url || ''}"+ @change="${(ev: Event) => {+ const url = (ev.currentTarget as HTMLInputElement).value;+ this._updateMessage({action: url ? {...message.action, url} : undefined});+ }}">+ <or-translate slot="label" value="openWebsiteUrl"></or-translate>+ </or-vaadin-text-field>++ <or-vaadin-toggle+ id="openInBrowser"+ ?disabled="${inputDisabled}"+ ?checked="${message.action?.openInBrowser ?? false}"+ @change="${(ev: Event) => {+ const openInBrowser = (ev.currentTarget as HTMLInputElement).checked;+ this._updateMessage({action: {...message.action, openInBrowser}});+ }}">+ <or-translate slot="label" value="openInBrowser"></or-translate>+ </or-vaadin-toggle>++ <or-vaadin-text-field+ id="openButtonText"+ ?readonly="${inputDisabled}"+ value="${message.buttons?.[0]?.title || ''}"+ @change="${(ev: Event) => this._updateButton(0, (ev.currentTarget as HTMLInputElement).value)}">+ <or-translate slot="label" value="buttonTextConfirm"></or-translate>+ </or-vaadin-text-field>++ <or-vaadin-text-field+ id="closeButtonText"+ ?readonly="${inputDisabled}"+ value="${message.buttons?.[1]?.title || ''}"+ @change="${(ev: Event) => this._updateButton(1, (ev.currentTarget as HTMLInputElement).value)}">+ <or-translate slot="label" value="buttonTextDecline"></or-translate>+ </or-vaadin-text-field>++ <or-vaadin-select+ id="notificationPriority"+ ?disabled="${inputDisabled}"+ .items="${priorityOptions}"+ value="${message.priority || PushNotificationMessageMessagePriority.NORMAL}"+ @change="${(ev: Event) => this._updateMessage({priority: (ev.currentTarget as OrVaadinSelect).value as PushNotificationMessageMessagePriority})}">+ <or-translate slot="label" value="priority"></or-translate>+ </or-vaadin-select>+ </div>+ `;+ }++ protected _updateButton(index: number, title?: string) {+ const message = this._message as PushNotificationMessage;+ const buttons: (PushNotificationButton | undefined)[] = [...(message.buttons || [])];+ buttons[index] = title ? {title} : undefined;+ this._updateMessage({buttons: buttons as PushNotificationButton[]});+ }++ protected _renderReadOnlyField(label: string, value: string | undefined) {+ return html`+ <or-vaadin-text-field readonly value="${value || '-'}">+ <or-translate slot="label" value="${label}"></or-translate>+ </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.tsnew file mode 100644index 000000000..ac74a5906--- /dev/null+++ b/ui/app/manager/src/components/notifications/or-notifications-table.ts@@ -0,0 +1,468 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import {OrMwcTable, TableColumn, TableConfig, TableRow} from "@openremote/or-mwc-components/or-mwc-table";+import {DefaultColor4} from "@openremote/core";+import { SentNotification, SentNotificationSortField, PushNotificationMessage, EmailNotificationMessage, NotificationTargetType, NotificationSource } from "@openremote/model";+import {i18next} from "@openremote/or-translate";+import {classMap} from "lit/directives/class-map.js";+import { NotificationService } from "../../pages/page-notifications";+import { getAssetsRoute, getUsersRoute } from "../../routes";++export interface NotificationTableRow extends TableRow {+ data: {+ notification: SentNotification+ }+}++export class NotificationTableClickEvent extends CustomEvent<{notificationId: number}> {+ static readonly NAME="or-notification-selected";++ constructor(notificationId: number) {+ super(NotificationTableClickEvent.NAME, {+ detail: {notificationId},+ bubbles: true,+ composed: true+ })+ }+ }++export class OrNotificationsPageChangedEvent extends CustomEvent<{page: number, size: number}> {+ static readonly NAME = "or-notifications-page-changed";++ constructor(page: number, size: number) {+ super(OrNotificationsPageChangedEvent.NAME, {+ detail: {page, size},+ bubbles: true,+ composed: true+ });+ }+}++export class OrNotificationsSortChangedEvent extends CustomEvent<{sort: SentNotificationSortField, descending: boolean}> {+ static readonly NAME = "or-notifications-sort-changed";++ constructor(sort: SentNotificationSortField, descending: boolean) {+ super(OrNotificationsSortChangedEvent.NAME, {+ detail: {sort, descending},+ bubbles: true,+ composed: true+ });+ }+}++// Maps a sortable column index to the server-side sort field. Columns absent here (body, target) aren't sortable.+const SORT_FIELD_BY_COLUMN: Record<number, SentNotificationSortField> = {+ 0: SentNotificationSortField.TITLE,+ 2: SentNotificationSortField.STATUS,+ 3: SentNotificationSortField.SOURCE,+ 5: SentNotificationSortField.SENT_ON,+ 6: SentNotificationSortField.DELIVERED_ON,+};++@customElement("or-notifications-table")+export class OrNotificationsTable extends OrMwcTable {+ static get styles() {+ return [+ ...super.styles,+ css`+ :host {+ display: flex;+ flex-direction: column;+ min-height: 0;+ }++ /* Size the table to its rows; the host height only acts as an upper bound */+ .mdc-data-table,+ .mdc-data-table__paginated {+ max-height: none;+ min-height: 0;+ }++ /* Scroll rows within the table so the pagination footer stays visible when space runs out */+ .mdc-data-table__table-container {+ overflow-y: auto;+ }++ .notification-container {+ padding: 20px;+ margin: 0 20px;+ overflow: auto;+ }++ tbody tr:hover {+ background-color: var(--or-table-row-hover-color, rgba(0,0,0,0.04));+ }++ td:nth-child(1), th:nth-child(1) { width: 15%; } /* Title column */+ td:nth-child(2), th:nth-child(2) { width: 25%; } /* Content column */+ td:nth-child(3), th:nth-child(3) { width: 6%; } /* Status column */+ td:nth-child(4), th:nth-child(4) { width: 4%; } /* Source column */+ td:nth-child(5), th:nth-child(5) { width: 15%; } /* Target column */+ td:nth-child(6), th:nth-child(6) { width: 6%; } /* SentOn column */+ td:nth-child(7), th:nth-child(7) { width: 6%; } /* DeliveredOn column */++ .notification-status {+ padding: 4px 8px;+ border-radius: 4px;+ display: inline-flex;+ align-items: center;+ font-size: 0.875rem;+ font-weight: 500;+ }++ .status-delivered {+ color: var(--or-notification-status-delivered-color, #22A06B);+ background: var(--or-notification-status-delivered-bg, rgba(34, 160, 107, 0.1));+ }++ .status-sent {+ color: var(--or-notification-status-sent-color, #8F7EE7);+ background: var(--or-notification-status-sent-bg, rgba(143, 126, 231, 0.1));+ }++ .status-error {+ color: var(--or-notification-status-error-color, rgb(231, 126, 126));+ background: var(--or-notification-status-error-bg, rgba(231, 126, 126, 0.1));+ }++ .title-wrapper {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .type-icon {+ --or-icon-width: 16px;+ --or-icon-height: 16px;+ color: var(--or-app-color3);+ flex: 0 0 auto;+ }++ .target-wrapper {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .target-link {+ color: var(--or-app-color4, ${unsafeCSS(DefaultColor4)});+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .target-icon {+ --or-icon-width: 16px;+ --or-icon-height: 16px;+ }++ .target-loading {+ color: var(--or-app-color3);+ font-style: italic;+ }+ `+ ];+ }++ @property({type: Array})+ public notifications?: SentNotification[] = [];++ @property({type: Boolean})+ public loading = false;++ @property({type: Array})+ public selectedIndices: number[] = []++ @property({type: Boolean})+ public selectable: boolean = true;++ @property({type: Boolean})+ public readonly = true++ @property({type: Object})+ public notificationService!: NotificationService;++ @property({type: Number})+ public currentPage: number = 0;++ @property({type: Number})+ public totalCount: number = 0;++ @state()+ protected targetDetailsMap: Map<string, {name: string, type: string, link: string}> = new Map();++ // Map keys whose lookup failed; their cached fallback entries are retried on the next resolve+ protected failedTargetKeys: Set<string> = new Set();++ protected getTargetMapKey(targetId: string, targetType: string): string {+ 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}+ ];++ protected config: TableConfig = {+ columnFilter: [],+ stickyFirstColumn: false,+ pagination: {+ enable: true+ },+ multiSelect: false+ }++ protected sortIndex = 5; // sort by sent date by default (column 5 = sentOn)+ protected sortDirection: "ASC" | "DESC" = "DESC";++ protected async willUpdate(changedProps: PropertyValues) {+ // update rows when notifications change+ if (changedProps.has("notifications")) {+ if (this.notifications?.length) {+ await this.resolveAllTargetDetails(this.notifications);+ }+ this.rows = this.getTableRows(this.notifications || []);+ }++ // handle readonly state changes+ if (changedProps.has("readonly")) {+ this.config.multiSelect = !this.readonly;+ }++ return super.willUpdate(changedProps);+ }++ protected getTableRows(notifications: SentNotification[]): TableRow[] | undefined {+ return notifications.map((notification) => {+ const message = notification.message as PushNotificationMessage | EmailNotificationMessage;+ const isEmail = message?.type === "email";+ const title = isEmail ? (message as EmailNotificationMessage).subject : (message as PushNotificationMessage)?.title;+ // Emails may carry a plain-text body instead of html (EmailNotificationHandler supports both); fall back to it+ const body = isEmail+ ? ((message as EmailNotificationMessage).html ?? (message as EmailNotificationMessage).text)+ : (message as PushNotificationMessage)?.body;+ return {+ content: [+ this.getTitleContent(notification, title),+ body,+ this.getStatusContent(notification),+ this.getSourceContent(notification.source),+ this.getTargetContent(notification),+ this.getDateContent(notification.sentOn),+ this.getDateContent(notification.deliveredOn)+ ],+ clickable: true,+ // store the full notification object in the row data+ data: { notification },+ } as NotificationTableRow;+ });+ }++ protected getTitleContent(notification: SentNotification, title?: string): TemplateResult {+ const iconMap: {[type: string]: string} = {+ "push": "cellphone-message",+ "email": "email-outline"+ };++ // 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>`}+ <span>${title || "-"}</span>+ </div>+ `;+ }++ protected getSourceContent(source: NotificationSource): TemplateResult {+ return html`<or-translate value="notifications.sources.${source}"></or-translate>`;+ }++ protected getTargetContent(notification: SentNotification): TemplateResult {+ const details = this.targetDetailsMap.get(this.getTargetMapKey(notification.targetId, notification.target));++ if (!details) {+ // show ID while loading or if we couldn't load details+ return html`+ <span class="target-loading">+ ${notification.targetId ?+ html`<or-translate value="loading"/>` :+ '-'+ }+ </span>+ `;+ }++ const iconMap = {+ 'asset': 'cube-outline',+ 'user': 'account',+ 'realm': 'domain'+ };++ return html`+ <div class="target-wrapper">+ <or-icon+ class="target-icon"+ icon="${iconMap[details.type] || 'help-circle-outline'}">+ </or-icon>+ ${details.link+ ? html`<a href="${details.link}" class="target-link ${details.type}-link">${details.name}</a>`+ : html`<span class="target-link">${details.name}</span>`+ }+ </div>+ `;+ }++ protected getStatusContent(notification: SentNotification): TemplateResult {+ const isError = !!notification.error;+ const isDelivered = !isError && !!notification.deliveredOn;++ const classes = {+ "notification-status": true,+ "status-error": isError,+ "status-delivered": isDelivered,+ // Delivery can only be confirmed by consoles acknowledging a push+ "status-sent": !isError && !isDelivered+ };++ return html`+ <span class="${classMap(classes)}" title="${notification.error || ""}">+ ${i18next.t(isError ? "error" : isDelivered ? "delivered" : "sent")}+ </span>+ `;+ }++ protected getDateContent(date?: number): TemplateResult {+ return html`${date ? new Date(date).toLocaleString() : '-'}`;+ }++ // Sorting is done server-side (across all pages) rather than on the current page's rows: emit the chosen+ // column/direction so the page can re-query. Rows are already returned in sorted order, so we don't sort locally.+ async onColumnSort(_ev: MouseEvent, index: number, sortDirection: "ASC" | "DESC") {+ const sort = SORT_FIELD_BY_COLUMN[index];+ if (!sort) return; // body/target columns aren't sortable++ const descending = sortDirection === "ASC"; // toggle relative to the current direction+ this.sortIndex = index;+ this.sortDirection = descending ? "DESC" : "ASC";+ this.dispatchEvent(new OrNotificationsSortChangedEvent(sort, descending));+ }++ protected async resolveAllTargetDetails(notifications: SentNotification[]) {+ // Drop entries cached by failed lookups so they get requested again; entries for deleted+ // targets stay cached since they can never resolve+ this.failedTargetKeys.forEach(key => this.targetDetailsMap.delete(key));+ this.failedTargetKeys.clear();++ const assetIds = new Set<string>();+ const userIds = new Set<string>();++ notifications.forEach((n) => {+ if (!n.targetId || this.targetDetailsMap.has(this.getTargetMapKey(n.targetId, n.target))) return;+ if (n.target === NotificationTargetType.ASSET) assetIds.add(n.targetId);+ else if (n.target === NotificationTargetType.USER) userIds.add(n.targetId);+ else {+ // REALM or unknown — just display the ID directly, no API lookup needed+ this.targetDetailsMap.set(this.getTargetMapKey(n.targetId, n.target), { name: n.targetId, type: "realm", link: "" });+ }+ });++ if (assetIds.size === 0 && userIds.size === 0) return;++ // Each kind handles its own failure so a failing asset request cannot discard user results (and vice versa)+ await Promise.all([+ this.resolveTargetDetails(assetIds, NotificationTargetType.ASSET, "asset",+ this.notificationService.hasAssetReadPermissions(),+ ids => this.notificationService.getAssetsDetails(ids),+ asset => ({ id: asset.id!, name: asset.name || asset.id!, link: `#/${getAssetsRoute(false, asset.id!)}` })),+ this.resolveTargetDetails(userIds, NotificationTargetType.USER, "user",+ this.notificationService.hasUserReadPermissions(),+ ids => this.notificationService.getUsersDetails(ids),+ user => ({ id: user.id!, name: user.username, link: `#/${getUsersRoute(user.id!)}` })),+ ]);+ this.requestUpdate();+ }++ protected async resolveTargetDetails<T>(+ ids: Set<string>,+ targetType: NotificationTargetType,+ type: string,+ canRead: boolean,+ fetchDetails: (ids: string[]) => Promise<T[]>,+ toEntry: (item: T) => { id: string, name: string, link: string }+ ) {+ if (ids.size === 0) return;++ // Hide targets the caller has no permission to resolve+ if (!canRead) {+ ids.forEach(id => this.targetDetailsMap.set(this.getTargetMapKey(id, targetType), { name: "-", type, link: "" }));+ return;+ }++ try {+ (await fetchDetails(Array.from(ids))).forEach(item => {+ const { id, name, link } = toEntry(item);+ this.targetDetailsMap.set(this.getTargetMapKey(id, targetType), { name, type, link });+ });+ } catch (err) {+ console.error(`Failed to resolve ${type} target details`, err);+ ids.forEach(id => this.failedTargetKeys.add(this.getTargetMapKey(id, targetType)));+ }++ // Ids that resolved to nothing (deleted target or failed lookup) fall back to the raw id+ // without a link, so they don't stay in a permanent loading state+ ids.forEach(id => {+ const key = this.getTargetMapKey(id, targetType);+ if (!this.targetDetailsMap.has(key)) {+ this.targetDetailsMap.set(key, { name: id, type, link: "" });+ }+ });+ }++ protected onRowClick(ev: MouseEvent, item: NotificationTableRow) {+ if (item?.data?.notification) {+ const event = new NotificationTableClickEvent(item.data.notification.id)+ this.dispatchEvent(event);+ }+ }++ async getRowCount(): Promise<number> {+ return this.totalCount ?? await super.getRowCount();+ }++ async getPaginationControls(): Promise<TemplateResult> {+ // Reuse the base template but drive pagination server-side: emit a page-changed event instead of+ // mutating the local paginationIndex. `max` comes from the overridden getRowCount() (the total count).+ return this.renderPaginationControls(this.currentPage, (page) =>+ this.dispatchEvent(new OrNotificationsPageChangedEvent(page, this.paginationSize)));+ }++ protected updated(changedProperties: Map<string, any>) {+ super.updated(changedProperties);+ if (changedProperties.has('paginationSize') && this.totalCount) {+ this.dispatchEvent(new OrNotificationsPageChangedEvent(0, this.paginationSize));+ }+ }+}diff --git a/ui/app/manager/src/headers.ts b/ui/app/manager/src/headers.tsindex ea42e0a2f..85b1c452c 100644--- a/ui/app/manager/src/headers.ts+++ b/ui/app/manager/src/headers.ts@@ -1,7 +1,26 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */import { manager } from "@openremote/core";import { AppStateKeyed, HeaderItem, OrApp } from "@openremote/or-app";import {AnyAction} from "@reduxjs/toolkit";-import { getMapRoute } from "./routes";+import { getMapRoute, getNotificationsRoute } from "./routes";export function headerItemMap<S extends AppStateKeyed, A extends AnyAction>(orApp: OrApp<S>): HeaderItem {return {@@ -103,6 +122,17 @@ export function headerItemLogs<S extends AppStateKeyed, A extends AnyAction>(orAroles: ["write:logs", "read:logs"]};}++export function headerItemNotifications<S extends AppStateKeyed, A extends AnyAction>(orApp: OrApp<S>): HeaderItem {+ return {+ icon: "message",+ value: "notifications",+ href: getNotificationsRoute(),+ text: "notification_other",+ roles: ["read:admin", "read:notifications"]+ }+}+export function headerItemAccount<S extends AppStateKeyed, A extends AnyAction>(orApp: OrApp<S>): HeaderItem {return {icon: "account",diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.tsindex 7b2398de4..7f7044da5 100644--- a/ui/app/manager/src/index.ts+++ b/ui/app/manager/src/index.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */// Declare require method which we'll use for importing webpack resources (using ES6 imports will confuse typescript parser)import {pageProvisioningProvider} from "./pages/page-provisioning";import {combineReducers, configureStore} from "@reduxjs/toolkit";@@ -17,6 +36,7 @@ import {headerItemLogout,headerItemLogs,headerItemMap,+ headerItemNotifications,headerItemProvisioning,headerItemRealms,headerItemRoles,@@ -50,6 +70,8 @@ import { pageConfigurationProvider } from "./pages/page-configuration";import {pageAlarmsProvider} from "./pages/page-alarms";import { ManagerAppConfig } from "@openremote/model";import {pageGatewayTunnelProvider} from "./pages/page-gateway-tunnel";+import { pageNotificationsProvider } from "./pages/page-notifications";+import "./pages/page-notifications";declare var MANAGER_URL: string | undefined;@@ -85,7 +107,8 @@ export const DefaultPagesConfig: PageProvider<any>[] = [pageExportProvider(store),pageProvisioningProvider(store),pageConfigurationProvider(store),- pageAlarmsProvider(store)+ pageAlarmsProvider(store),+ pageNotificationsProvider(store)];export const DefaultHeaderMainMenu: {[name: string]: HeaderItem} = {@@ -101,6 +124,7 @@ export const DefaultHeaderSecondaryMenu: {[name: string]: HeaderItem} = {gatewayTunnel: headerItemGatewayTunnel(orApp),language: headerItemLanguage(orApp),logs: headerItemLogs(orApp),+ notifications: headerItemNotifications(orApp),account: headerItemAccount(orApp),users: headerItemUsers(orApp),roles: headerItemRoles(orApp),diff --git a/ui/app/manager/src/pages/page-notifications.ts b/ui/app/manager/src/pages/page-notifications.tsnew file mode 100644index 000000000..a7f466a28--- /dev/null+++ b/ui/app/manager/src/pages/page-notifications.ts@@ -0,0 +1,680 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import {css, html, unsafeCSS} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import {AppStateKeyed, Page, PageProvider} from "@openremote/or-app";+import {Store} from "@reduxjs/toolkit";+import {+ Asset,+ Notification,+ NotificationSource,+ NotificationTargetType,+ SentNotification,+ SentNotificationSortField,+ User+} from "@openremote/model";+import manager, {DefaultColor3} from "@openremote/core";+import {i18next} from "@openremote/or-translate";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {AxiosError} from "@openremote/rest";+import {OrVaadinSelect, SelectItem} from "@openremote/or-vaadin-components/or-vaadin-select";+import {OrVaadinDateTimePicker} from "@openremote/or-vaadin-components/or-vaadin-date-time-picker";+import "@openremote/or-vaadin-components/or-vaadin-button";+import {dialogRenderer, dialogFooterRenderer, dialogHeaderRenderer} from "@openremote/or-vaadin-components/or-vaadin-dialog";+import "@openremote/or-vaadin-components/or-vaadin-dialog";+import {OrNotificationForm} from "../components/notifications/or-notification-form";+import "../components/notifications/or-notification-form";+import {NotificationTableClickEvent, OrNotificationsPageChangedEvent, OrNotificationsSortChangedEvent} from "../components/notifications/or-notifications-table";+import "../components/notifications/or-notifications-table";++type NotificationSourceKeys = keyof typeof NotificationSource+const sources = [+ NotificationSource.INTERNAL,+ NotificationSource.CLIENT,+ NotificationSource.GLOBAL_RULESET,+ NotificationSource.REALM_RULESET,+ // NotificationSource.ASSET_RULESET, // Not implemented+] satisfies NotificationSourceKeys[];++export class NotificationService {++ async getNotifications(realm: string, fromDate?: number, toDate?: number, source?: NotificationSource, offset?: number, limit?: number, sort?: SentNotificationSortField, descending?: boolean, signal?: AbortSignal): Promise<SentNotification[]> {+ try {+ const timeRange = fromDate && toDate ?+ {fromDate, toDate} :+ this.getDefaultTimeRange();++ const response = await manager.rest.api.NotificationResource.getNotifications(+ {+ from: timeRange.fromDate,+ to: timeRange.toDate,+ realmId: realm,+ source,+ sort,+ descending,+ offset,+ limit+ }, {signal});++ if (!response.data) {+ console.warn("No data in response:", response);+ return [];+ }++ return response.data;+ } catch (err: unknown) {+ if (!signal?.aborted) {+ console.error('Failed to fetch notifications:', err);+ }+ throw err;+ }+ }++ async getNotificationsCount(realm: string, fromDate?: number, toDate?: number, source?: NotificationSource, signal?: AbortSignal): Promise<number> {+ try {+ const timeRange = fromDate && toDate ?+ {fromDate, toDate} :+ this.getDefaultTimeRange();++ const response = await manager.rest.api.NotificationResource.getNotificationsCount(+ {+ from: timeRange.fromDate,+ to: timeRange.toDate,+ realmId: realm,+ source+ }, {signal});++ return typeof response.data === 'number' ? response.data : 0;+ } catch (err: unknown) {+ if (!signal?.aborted) {+ console.error('Failed to fetch notification count:', err);+ }+ throw err;+ }+ }++ async sendNotification(notification: Notification): Promise<boolean> {+ try {+ const response = await manager.rest.api.NotificationResource.sendNotification(+ notification+ );+ return response.status === 200;+ } catch (err: unknown) {+ const error = err as AxiosError;+ console.error("Failed to send notification:", error);+ throw error;+ }+ }++ async getAssetsDetails(assetIds: string[]): Promise<Asset[]> {+ const response = await manager.rest.api.AssetResource.queryAssets({ ids: assetIds });+ return response.data || [];+ }++ async getUsersDetails(userIds: string[]): Promise<User[]> {+ const response = await manager.rest.api.UserResource.query({ ids: userIds });+ return response.data || [];+ }++ hasUserReadPermissions(): boolean {+ return manager.hasRole("read:users") || manager.hasRole("read:admin");+ }++ hasAssetReadPermissions(): boolean {+ return manager.hasRole("read:assets") || manager.hasRole("read:admin");+ }++ public getDefaultTimeRange(): { fromDate: number, toDate: number } {+ const now = new Date();+ const toDate = new Date(now);+ toDate.setHours(23, 59, 59, 999);++ // default to the last day only (beginning of today); the range can be extended manually+ const fromDate = new Date(now);+ fromDate.setHours(0, 0, 0, 0);++ const fromTimestamp = fromDate.getTime();+ const toTimestamp = toDate.getTime();++ if (!Number.isInteger(fromTimestamp) || !Number.isInteger(toTimestamp)) {+ console.error("Invalid timestamp generation:", {fromTimestamp, toTimestamp});+ throw new Error("Invalid timestamp generation")+ }++ return {+ fromDate: fromTimestamp,+ toDate: toTimestamp+ }+ }++}++export interface PageNotificationsConfig {+ targetId?: string;+ targetType?: string;+ fromTimestamp?: number;+ toTimestamp?: number;+}++export function pageNotificationsProvider(store: Store<AppStateKeyed>, config?: PageNotificationsConfig): PageProvider<AppStateKeyed> {+ return {+ name: "notifications",+ routes: ["notifications"],+ pageCreator: () => {+ return new PageNotifications(store);+ }+ };+}++@customElement("page-notifications")+export class PageNotifications extends Page<AppStateKeyed> {+ static get styles() {+ return [+ css`+ :host {+ flex: 1;+ width: 100%;+ }++ #wrapper {+ height: 100%;+ width: 100%;+ display: flex;+ flex-direction: column;+ overflow: auto;+ }++ #title {+ padding: 0 20px;+ font-size: 18px;+ font-weight: bold;+ margin: 10px 0;+ display: flex;+ align-items: center;+ color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});+ justify-content: space-between;+ gap: var(--lumo-space-m);+ }++ /* Once the controls no longer fit beside the title, stack them underneath it. Switching to a+ column (rather than flex-wrapping) keeps the title centered against the controls while inline+ and avoids the title shifting up when they move below. */+ @media only screen and (max-width: 1360px) {+ #title {+ flex-direction: column;+ align-items: flex-start;+ }+ }++ #table-container {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ margin: 0 20px 20px 20px;+ }++ /* Table sizes to its rows but may shrink (and scroll internally) when it hits the bottom of the page */+ #table-container or-notifications-table {+ flex: 0 1 auto;+ min-height: 0;+ }++ .controls {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ /* gap supplies the row spacing too, so wrapped fields keep their spacing below */+ gap: var(--lumo-space-m);+ }++ .controls or-vaadin-select {+ width: 180px;+ }++ .controls or-vaadin-date-time-picker {+ width: 280px;+ &::part(label) {+ padding-bottom: 0.5em; /* TODO: find a structural fix */+ /* "from"/"to" share lowercase i18n keys with inline usages elsewhere; capitalize here */+ text-transform: capitalize;+ }+ }+ `];+ }++ @property()+ protected realm?: string;++ @state()+ protected _data?: SentNotification[];++ @state()+ protected notification?: SentNotification;++ @state()+ protected _fromDate?: number;++ @state()+ protected _toDate?: number;++ @state()+ protected _dateRange?: number[];++ @state()+ protected _selectedSource?: string;++ @state()+ protected _isFilteredDate: boolean = false;++ @state()+ protected _isFilteredSource: boolean = false;++ @state()+ protected _currentPage: number = 0;++ @state()+ protected _totalCount: number = 0;++ @state()+ protected _pageSize: number = 10;++ // Server-side sort; defaults to newest-sent first (matches the table's default sort indicator on "Sent")+ protected _sortField: SentNotificationSortField = SentNotificationSortField.SENT_ON;+ protected _sortDescending: boolean = true;++ @state()+ protected _createDialogOpen: boolean = false;++ @state()+ protected _detailsDialogOpen: boolean = false;++ @state()+ protected _createFormValid: boolean = false;++ protected _createForm?: OrNotificationForm;++ protected _loading: boolean = false;+ protected _loadAbortController?: AbortController;++ protected notificationService: NotificationService;++ constructor(store: Store<AppStateKeyed>) {+ super(store);+ this.notificationService = new NotificationService();++ // set initial date range+ const {fromDate, toDate} = this.notificationService.getDefaultTimeRange();+ this._fromDate = fromDate;+ this._toDate = toDate;+ }++ public stateChanged(state: AppStateKeyed): void {+ if (state.app.page === "notifications") {+ const realmChanged = this.realm !== state.app.realm;+ this.realm = state.app.realm;+ this.requestUpdate('realm');++ // Only fetch when relevant state changed; stateChanged fires on every store update+ // (e.g. visibility changes during page unload) which shouldn't trigger requests+ if (realmChanged) {+ this.reset();+ this._loadData();+ } else if (!this._data && !this._loading) {+ // Initial load when entering the page+ this._loadData();+ }+ }+ }++ protected reset(): void {+ this._data = undefined;+ this._totalCount = 0;+ this._currentPage = 0;+ this.requestUpdate();+ }++ get name(): string {+ return "notification_other"+ }++ protected async _loadData() {+ if (!this.realm) {+ return;+ }+ this._loadAbortController?.abort();+ const abortController = new AbortController();+ this._loadAbortController = abortController;+ this._loading = true;++ try {++ const timeRange = this._isFilteredDate && this._fromDate && this._toDate ?+ {+ fromDate: this._fromDate,+ toDate: this._toDate+ } :+ this.notificationService.getDefaultTimeRange();++ if (!this._isFilteredDate) {+ this._fromDate = timeRange.fromDate;+ this._toDate = timeRange.toDate;+ }++ if (!this._isFilteredSource) {+ this._selectedSource = "ALL_SOURCES"+ }++ // Filter on source in the query so it applies to all pages rather than the current one+ const source = this._selectedSource && this._selectedSource !== "ALL_SOURCES"+ ? this._selectedSource as NotificationSource+ : undefined;++ const offset = this._currentPage * this._pageSize;++ const [data, count] = await Promise.all([+ this.notificationService.getNotifications(this.realm, timeRange.fromDate, timeRange.toDate, source, offset, this._pageSize, this._sortField, this._sortDescending, abortController.signal),+ this.notificationService.getNotificationsCount(this.realm, timeRange.fromDate, timeRange.toDate, source, abortController.signal)+ ]);++ this._data = data;+ this._totalCount = count;++ this.requestUpdate();+ } catch (err: unknown) {+ if (abortController.signal.aborted) {+ return;+ }+ console.error("Failed to load notifications:", err);+ showSnackbar(undefined, i18next.t("loadingNotificationFailed"));+ } finally {+ // Only the latest request may clear the loading flag+ if (this._loadAbortController === abortController) {+ this._loading = false;+ }+ }+ }++ protected async _handleCreateNotification() {+ const notification = this._createForm?.getNotification();++ // validate required fields per schema+ if (!notification) {+ showSnackbar(undefined, i18next.t("notifications.missingFields"));+ return;+ }++ try {+ await this.notificationService.sendNotification(notification);++ showSnackbar(undefined, i18next.t("notifications.successfullySentNotification"));+ this._createDialogOpen = false;+ // Reload explicitly: setting _createDialogOpen=false above means the @opened-changed handler's+ // guard is already false, so it won't reload for us. Without this the new notification only+ // appears after the next refetch (e.g. a filter change).+ await this._loadData();+ } catch (_error) {+ showSnackbar(undefined, i18next.t("notifications.failedToCreateNotification"));+ }+ }++ protected isValidTargetType(type: string): boolean {+ return type === NotificationTargetType.REALM ||+ type === NotificationTargetType.USER ||+ type === NotificationTargetType.ASSET ||+ type === NotificationTargetType.CUSTOM;+ }++ protected render() {+ const writeNotifications = manager.hasRole("write:admin") || manager.hasRole("write:notifications");+ const hasRecipientType = manager.hasRole("read:admin")+ || manager.hasRole("read:assets")+ || manager.hasRole("read:users");++ return html`+ <div id="wrapper">+ ${html`+ ${this._renderHeader(writeNotifications, hasRecipientType)}+ <div id="table-container">+ ${this._renderNotificationsTable()}+ </div>`+ }+ </div>+ ${this._renderCreateDialog()}+ ${this._renderDetailsDialog()}+ `;+ }++ protected _renderCreateDialog() {+ return html`+ <or-vaadin-dialog+ id="createDialog"+ width="1024px"+ no-close-on-outside-click+ no-close-on-esc+ header-title="${i18next.t("notifications.createNotification")}"+ ?opened="${this._createDialogOpen}"+ @opened-changed="${(ev: CustomEvent) => {+ // Safety net for dialog-initiated closes; Cancel and a successful create close+ // (and reload) through their own handlers, which this guard skips+ if (!ev.detail.value && this._createDialogOpen) {+ this._createDialogOpen = false;+ this._loadData();+ }+ }}"+ ${dialogHeaderRenderer(() => html`+ <or-vaadin-button theme="tertiary" @click="${() => this._cancelCreateDialog()}">+ <or-icon icon="mdi:close"></or-icon>+ </or-vaadin-button>+ `, [])}+ ${dialogRenderer(() => this._renderCreateForm(), [this.realm])}+ ${dialogFooterRenderer(() => html`+ <or-vaadin-button theme="tertiary" @click="${() => this._cancelCreateDialog()}">+ <or-translate value="cancel"></or-translate>+ </or-vaadin-button>+ <or-vaadin-button theme="primary" ?disabled="${!this._createFormValid}"+ @click="${() => this._handleCreateNotification()}">+ <or-translate value="create"></or-translate>+ </or-vaadin-button>+ `, [this._createFormValid])}>+ </or-vaadin-dialog>+ `;+ }++ protected _renderDetailsDialog() {+ return html`+ <or-vaadin-dialog+ id="detailsDialog"+ width="1024px"+ header-title="${i18next.t("notifications.details")}"+ ?opened="${this._detailsDialogOpen}"+ @opened-changed="${(ev: CustomEvent) => {+ if (!ev.detail.value && this._detailsDialogOpen) {+ this._detailsDialogOpen = false;+ this._loadData();+ }+ }}"+ ${dialogHeaderRenderer(() => html`+ <or-vaadin-button theme="tertiary" @click="${() => this._detailsDialogOpen = false}">+ <or-icon icon="mdi:close"></or-icon>+ </or-vaadin-button>+ `, [])}+ ${dialogRenderer(() => this._renderDetailsForm(this.notification), [this.notification, this.realm])}>+ </or-vaadin-dialog>+ `;+ }++ // The form stays mounted across opens (so closing the dialog doesn't visibly clear it before it animates out);+ // _showCreateDialog calls form.reset() on each open instead, which clears prior input and reloads the active+ // realm's users/assets/realms.+ protected _renderCreateForm() {+ return html`+ <or-notification-form+ id="notificationForm"+ .realm=${this.realm}+ @or-notification-form-changed="${(ev: Event) => this._onCreateFormChanged(ev)}">+ </or-notification-form>+ `;+ }++ protected _renderDetailsForm(notification?: SentNotification) {+ return html`+ <or-notification-form+ .realm=${this.realm}+ .notification=${notification}+ readonly>+ </or-notification-form>+ `;+ }++ protected _onCreateFormChanged(ev: Event) {+ this._createForm = ev.target as OrNotificationForm;+ const valid = !!this._createForm.getNotification();+ if (valid !== this._createFormValid) {+ this._createFormValid = valid;+ }+ }++ protected _renderHeader(writeNotifications: boolean, hasRecipientType: boolean = true) {+ const sourceOptions: SelectItem[] = [+ {label: i18next.t("notifications.sources.ALL_SOURCES"), value: "ALL_SOURCES"},+ ...sources.map(s => ({label: i18next.t(`notifications.sources.${s}`), value: s as string}))+ ];++ return html`+ <div id="title">+ <div style="display: flex; align-items: center; min-height: 60px;">+ <or-icon icon="message-outline" style="padding: 0 10px 0 4px;"></or-icon>+ <span><or-translate value="notification_other"/></span>+ </div>++ <div class="controls">+ <or-vaadin-select+ .items="${sourceOptions}"+ value="${this._selectedSource || "ALL_SOURCES"}"+ @change="${(ev: Event) => {+ this._selectedSource = (ev.currentTarget as OrVaadinSelect).value;+ this._isFilteredSource = true; // set filter changes+ this._currentPage = 0;+ this._loadData();+ }}">+ <or-translate slot="label" value="source"></or-translate>+ </or-vaadin-select>++ <or-vaadin-date-time-picker+ value="${this._fromDate ? OrVaadinDateTimePicker.getLocalizedISOString(new Date(this._fromDate)) : ""}"+ @change="${(ev: Event) => {+ const value = (ev.currentTarget as OrVaadinDateTimePicker).value;+ if (!value) return;+ this._fromDate = new Date(value).getTime();+ this._isFilteredDate = true;+ this._currentPage = 0;+ this._loadData();+ }}">+ <or-translate slot="label" value="from"></or-translate>+ </or-vaadin-date-time-picker>++ <or-vaadin-date-time-picker+ value="${this._toDate ? OrVaadinDateTimePicker.getLocalizedISOString(new Date(this._toDate)) : ""}"+ @change="${(ev: Event) => {+ const value = (ev.currentTarget as OrVaadinDateTimePicker).value;+ if (!value) return;+ this._toDate = new Date(value).getTime();+ this._isFilteredDate = true;+ this._currentPage = 0;+ this._loadData();+ }}">+ <or-translate slot="label" value="to"></or-translate>+ </or-vaadin-date-time-picker>++ ${writeNotifications ? html`+ <or-vaadin-button ?disabled="${!hasRecipientType}" @click="${() => this._showCreateDialog()}">+ <or-icon slot="prefix" icon="plus"></or-icon>+ <or-translate value="notifications.sendNew"></or-translate>+ </or-vaadin-button>+ ` : ``}+ </div>+ </div>+ `;+ }++ protected _renderNotificationsTable() {+ const notifications = this._data || [];+ return html`+ <or-notifications-table+ .notifications=${notifications}+ .notificationService=${this.notificationService}+ .totalCount=${this._totalCount}+ .currentPage=${this._currentPage}+ .paginationSize=${this._pageSize}+ @or-notifications-page-changed="${(e: OrNotificationsPageChangedEvent) => {+ this._currentPage = e.detail.page;+ this._pageSize = e.detail.size;+ this._loadData();+ }}"+ @or-notifications-sort-changed="${(e: OrNotificationsSortChangedEvent) => {+ this._sortField = e.detail.sort;+ this._sortDescending = e.detail.descending;+ this._currentPage = 0; // sorting spans all pages, so restart from the first+ this._loadData();+ }}"+ @or-notification-selected="${(e: NotificationTableClickEvent) => this._onRowClick(e)}"+ ></or-notifications-table>+ ${!this._loading && notifications && notifications.length === 0 ? html`+ <div style="padding: 20px; text-align: center; font-style: italic; color: var(--or-app-color3);">+ <or-translate value="noResults"></or-translate>+ </div>+ ` : ''}+ `;+ }+++ protected _showCreateDialog() {+ // The form persists between opens, so clear any input left over from a previous open+ this._createForm?.reset();+ this._createFormValid = false;+ this._createDialogOpen = true;+ }++ protected _cancelCreateDialog() {+ this._createDialogOpen = false;+ // A failed send may still have persisted the notification with its error, so refresh the table+ this._loadData();+ }++ private _onRowClick(e: NotificationTableClickEvent) {+ if (!this._data || !e.detail) {+ console.warn("No data available.");+ return;+ }+ const notificationId = e.detail.notificationId;++ const notification = this._data.find(n => n.id === notificationId);++ if (!notification) {+ console.warn(`No notification found with id ${notificationId}`);+ return;+ }++ this.notification = notification;+ this._detailsDialogOpen = true;+ }+}+diff --git a/ui/app/manager/src/routes.ts b/ui/app/manager/src/routes.tsindex 63d018d4e..8acea082b 100644--- a/ui/app/manager/src/routes.ts+++ b/ui/app/manager/src/routes.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */export function getMapRoute(assetId?: string) {let route = "map";@@ -48,9 +67,18 @@ export function getAlarmsRoute(alarmId?: string) {}return route;}++export function getNotificationsRoute(notificationId?: string) {+ let route = "notifications";+ if (notificationId) {+ route += "/" + notificationId;+ }+ return route;+}+export function getServicesRoute(serviceId?: string) {let route = "services";- if(serviceId) {+ if (serviceId) {route += "/" + serviceId;}return route;diff --git a/ui/app/manager/test/fixtures/manager.ts b/ui/app/manager/test/fixtures/manager.tsindex 8105f4006..10db5634b 100644--- a/ui/app/manager/test/fixtures/manager.ts+++ b/ui/app/manager/test/fixtures/manager.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */import path from "node:path";import rest, { RestApi } from "@openremote/rest";@@ -10,23 +29,31 @@ import { Asset, AssetModelUtil, ManagerAppConfig, Role } from "@openremote/modelimport {test as base,expect,+ type APIRequestContext,type Page,type SharedComponentTestFixtures,type Shared,type TestFixture,withPage,} from "@openremote/test";-import { AssetsPage, InsightsPage, RealmsPage, RolesPage, RulesPage, UsersPage } from "./pages";+import { playwrightRequestAdapter } from "./request-adapter";+import { AssetsPage, InsightsPage, NotificationsPage, RealmsPage, RolesPage, RulesPage, UsersPage } from "./pages";import { AssetViewer } from "../../../../component/or-asset-viewer/test/fixtures";import { CollapsiblePanel } from "../../../../component/or-components/test/fixtures";import { MwcInput, MwcMenu } from "../../../../component/or-mwc-components/test/fixtures";import { JsonForms } from "../../../../component/or-json-forms/test/fixtures";import { AssetTree } from "../../../../component/or-asset-tree/test/fixtures";-import { type AxiosRequestConfig } from "axios";+import { isAxiosError, type AxiosRequestConfig } from "axios";export const adminStatePath = path.join(__dirname, "data/.auth/admin.json");export const userStatePath = path.join(__dirname, "data/.auth/user.json");+/** Logs a warning for a failed HTTP request; any other error is a test bug and is rethrown to fail the test. */+function warnOnHttpError(e: unknown, message: string, ...context: unknown[]) {+ if (!isAxiosError(e)) throw e;+ console.warn(message, ...context, e.response?.status ?? e.message);+}+export class Manager {private readonly clientId = "openremote";private readonly managerHost: String;@@ -39,12 +66,17 @@ export class Manager {public assets: Asset[] = [];public rules: number[] = [];public dashboards: string[] = [];+ public provisionedUsers: { realm: string; id: string }[] = [];- constructor(readonly page: Page, readonly baseURL: string) {+ constructor(readonly page: Page, readonly baseURL: string, request?: APIRequestContext) {this.managerHost = process.env.managerUrl || "http://localhost:8080";rest.initialise(`${this.managerHost}/api/master/`);this.api = rest.api;this.axios = rest.axiosInstance;+ // Route the rest client through Playwright's request context so setup calls appear in the trace viewer+ if (request) {+ this.axios.defaults.adapter = playwrightRequestAdapter(request);+ }}/**@@ -163,6 +195,62 @@ export class Manager {return access_token;}+ /**+ * Build an axios request config authenticated as the master-realm admin, for REST setup calls.+ */+ async adminConfig(): Promise<AxiosRequestConfig<any>> {+ const token = await this.getAccessToken("master", admin.username, admin.password);+ return { headers: { Authorization: `Bearer ${token}` } };+ }++ /**+ * Provision a user with client roles (and optionally a password/email) in the given realm via REST, returning+ * the created user. Unlike {@link createUser} this is stateless (it doesn't touch `this.realm`/`this.user`), so+ * it can set up arbitrary users for e.g. access-control tests. Defaults to the admin config when none is given.+ * @param realm The realm to create the user in+ * @param user The username, client roles, and optional initial password/email+ * @param config The axios request config+ */+ async provisionUser(+ realm: string,+ { username, roles = [], password, email }: { username: string; roles?: string[]; password?: string; email?: string },+ config?: AxiosRequestConfig<any>+ ): Promise<UserModel | undefined> {+ config ??= await this.adminConfig();+ const user = await this.api.UserResource.create(realm, { username, email, enabled: true } as UserModel, config)+ .then((r) => r.data)+ .catch(() => undefined);++ if (user?.id) {+ // track for teardown so provisioned users don't leak between tests/runs+ this.provisionedUsers.push({ realm, id: user.id });+ if (roles.length > 0) {+ await this.api.UserResource.updateUserClientRoles(realm, user.id, this.clientId, roles, config);+ }+ if (password) {+ await this.api.UserResource.updatePassword(realm, user.id, { value: password }, config);+ }+ }+ return user;+ }++ /**+ * Deletes all users provisioned via {@link provisionUser} (across realms). Called by {@link cleanUp}.+ * @param config The axios request config+ */+ async deleteUsers(config?: AxiosRequestConfig<any>) {+ config ??= await this.adminConfig();+ for (const { realm, id } of this.provisionedUsers) {+ try {+ const response = await this.api.UserResource.delete(realm, id, config);+ expect(response.status).toBe(204);+ } catch (e) {+ warnOnHttpError(e, "Could not delete user: ", id);+ }+ }+ this.provisionedUsers = [];+ }+/*** When an application initialises a WebSocket this will assign that instance to the `window.ws` object.*@@ -209,7 +297,7 @@ export class Manager {expect(response.status).toBe(200);return response.data;} catch (e) {- console.error("Failed to get roles", e.response.status);+ warnOnHttpError(e, "Failed to get roles");}}@@ -235,7 +323,7 @@ export class Manager {expect(response.status).toBe(204);this.role = newRole;} catch (e) {- console.error("Failed to create role", e.response.status);+ warnOnHttpError(e, "Failed to create role");}}@@ -252,7 +340,7 @@ export class Manager {expect(response.status).toBe(200);this.user = response.data;} catch (e) {- console.error("Failed to create user", e.response.status);+ warnOnHttpError(e, "Failed to create user");}}@@ -274,7 +362,7 @@ export class Manager {);expect(response.status).toBe(204);} catch (e) {- console.error("Failed to update users' roles", e.response.status);+ warnOnHttpError(e, "Failed to update users' roles");}}@@ -294,7 +382,7 @@ export class Manager {);expect(response.status).toBe(204);} catch (e) {- console.error("Failed to reset user password", e.response.status);+ warnOnHttpError(e, "Failed to reset user password");}}@@ -305,8 +393,7 @@ export class Manager {*/async createAsset(asset: Asset, config?: AxiosRequestConfig<any>) {if (!config) {- const access_token = await this.getAccessToken("master", "admin", users.admin.password!);- config = { headers: { Authorization: `Bearer ${access_token}` } };+ config = await this.adminConfig();}await rest.api.AssetResource.create(asset, config).then((response) => {@@ -314,7 +401,8 @@ export class Manager {this.assets.push(response.data);}).catch((e) => {- expect(e.response.status, { message: "Failed to create asset" }).toBe(409);+ if (!isAxiosError(e)) throw e;+ expect(e.response?.status, { message: "Failed to create asset" }).toBe(409);});}@@ -325,8 +413,7 @@ export class Manager {*/async updateAsset(asset: Asset, config?: AxiosRequestConfig<any>) {if (!config) {- const access_token = await this.getAccessToken("master", "admin", users.admin.password!);- config = { headers: { Authorization: `Bearer ${access_token}` } };+ config = await this.adminConfig();}await rest.api.AssetResource.update(asset.id!, asset, config).then((response) => {@@ -334,7 +421,8 @@ export class Manager {this.assets = [...this.assets.filter((a) => a.id !== response.data.id), response.data as Asset];}).catch((e) => {- expect(e.response.status, { message: "Failed to update asset" }).toBe(409);+ if (!isAxiosError(e)) throw e;+ expect(e.response?.status, { message: "Failed to update asset" }).toBe(409);});}@@ -350,8 +438,7 @@ export class Manager {realm: string,{ user, role, assets }: { user?: UserModel; role?: Role; assets?: Asset[] | DefaultAssets } = {}) {- const access_token = await this.getAccessToken("master", admin.username, admin.password);- const config = { headers: { Authorization: `Bearer ${access_token}` } };+ const config = await this.adminConfig();this.realm = realm;@@ -390,7 +477,7 @@ export class Manager {expect(response.status).toBe(204);this.dashboards.splice(i, 1);} catch (e) {- console.warn("Could not delete dashboard: ", id, e);+ warnOnHttpError(e, "Could not delete dashboard: ", id);}}}@@ -406,7 +493,7 @@ export class Manager {expect(response.status).toBe(204);this.rules.splice(i, 1);} catch (e) {- console.warn("Could not delete realm rule: ", id, e);+ warnOnHttpError(e, "Could not delete realm rule: ", id);}}}@@ -422,7 +509,7 @@ export class Manager {expect(response.status).toBe(204);this.assets = [];} catch (e) {- console.warn("Could not delete asset(s): ", assetIds, e);+ warnOnHttpError(e, "Could not delete asset(s): ", assetIds);}}@@ -440,7 +527,7 @@ export class Manager {expect(response.status).toBe(204);delete this.role;} catch (e) {- console.warn("Could not update roles: ", this.role, e);+ warnOnHttpError(e, "Could not update roles: ", this.role);}}@@ -448,8 +535,7 @@ export class Manager {* Clean up the environment*/async cleanUp() {- const access_token = await this.getAccessToken("master", "admin", users.admin.password!);- const config = { headers: { Authorization: `Bearer ${access_token}` } };+ const config = await this.adminConfig();if (this.dashboards.length > 0) {await this.deleteDashboards(config);@@ -463,6 +549,10 @@ export class Manager {await this.deleteAssets(config);}+ if (this.provisionedUsers.length > 0) {+ await this.deleteUsers(config);+ }+if (this.role && this.realm) {const roles = await this.getClientRoles(config);if (roles) {@@ -486,6 +576,7 @@ function withManager<R>(managerPage: Function): TestFixture<R, { page: Page; shainterface PageFixtures {assetsPage: AssetsPage;insightsPage: InsightsPage;+ notificationsPage: NotificationsPage;realmsPage: RealmsPage;rolesPage: RolesPage;rulesPage: RulesPage;@@ -506,10 +597,11 @@ interface Fixtures extends PageFixtures, ComponentFixtures {}export const test = base.extend<Fixtures>({- manager: async ({ page, baseURL }, use) => await use(new Manager(page, baseURL!)),+ manager: async ({ page, baseURL, request }, use) => await use(new Manager(page, baseURL!, request)),// PagesassetsPage: withManager(AssetsPage),insightsPage: withManager(InsightsPage),+ notificationsPage: withManager(NotificationsPage),realmsPage: withManager(RealmsPage),rolesPage: withManager(RolesPage),rulesPage: withManager(RulesPage),diff --git a/ui/app/manager/test/fixtures/pages/index.ts b/ui/app/manager/test/fixtures/pages/index.tsindex d4c56ad7b..354760748 100644--- a/ui/app/manager/test/fixtures/pages/index.ts+++ b/ui/app/manager/test/fixtures/pages/index.ts@@ -1,6 +1,26 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */export { AssetsPage } from "./assets";export { InsightsPage } from "./insights";export { RealmsPage } from "./realms";export { RolesPage } from "./roles";export { RulesPage } from "./rules";export { UsersPage } from "./users";+export { NotificationsPage } from "./notifications";diff --git a/ui/app/manager/test/fixtures/pages/notifications.ts b/ui/app/manager/test/fixtures/pages/notifications.tsnew file mode 100644index 000000000..5f71514c2--- /dev/null+++ b/ui/app/manager/test/fixtures/pages/notifications.ts@@ -0,0 +1,203 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import { BasePage, Locator, Page, Shared, expect } from "@openremote/test";+import { Manager } from "../manager.js";++/**+ * Page object for the notifications management page (page-notifications).+ *+ * The page is built on the Vaadin component wrappers: the create/details dialogs are `or-vaadin-dialog`s whose+ * content is teleported into a `vaadin` overlay, so dialog content (form, footer buttons) is located by its own+ * id/role rather than via the dialog host element. Selects open an overlay whose items expose role="option".+ */+export class NotificationsPage implements BasePage {+ constructor(private readonly page: Page, private readonly shared: Shared, private readonly manager: Manager) {}++ async goto() {+ await this.manager.navigateToMenuItem("Notifications");+ await expect(this.getTable()).toBeVisible();+ }++ // --- Table -------------------------------------------------------------++ getTable(): Locator {+ return this.page.locator("or-notifications-table");+ }++ getRows(): Locator {+ return this.getTable().locator("tbody tr");+ }++ /** A table row containing the given text (e.g. a notification's subject/title). */+ getRowByText(text: string): Locator {+ return this.getRows().filter({ hasText: text });+ }++ /** The status badge (Sent/Delivered/Error) of the (first) row containing the given text. */+ getStatusBadge(rowText: string): Locator {+ return this.getRowByText(rowText).first().locator(".notification-status");+ }++ // --- Header / filters --------------------------------------------------++ getCreateButton(): Locator {+ return this.page.getByRole("button", { name: "Send new" });+ }++ getSourceSelect(): Locator {+ return this.page.locator(".controls or-vaadin-select").first();+ }++ getDatePickers(): Locator {+ return this.page.locator(".controls or-vaadin-date-time-picker");+ }++ /**+ * Set the from/to date-range filter. Values are local `YYYY-MM-DDTHH:mm` strings (as the picker uses).+ * The picker only commits on `change`, which isn't fired by a programmatic value assignment, so we set the+ * value and dispatch `change` ourselves to trigger the page's reload.+ */+ async setDateRange(fromValue: string, toValue: string) {+ const pickers = this.getDatePickers();+ await this.setPickerValue(pickers.nth(0), fromValue);+ await this.setPickerValue(pickers.nth(1), toValue);+ }++ private async setPickerValue(picker: Locator, value: string) {+ await picker.evaluate((el, val) => {+ (el as unknown as { value: string }).value = val;+ el.dispatchEvent(new Event("change", { bubbles: true }));+ }, value);+ }++ /**+ * Click the option with the given exact label in the currently-open Vaadin select overlay.+ *+ * Vaadin teleports the items into a `<vaadin-select-overlay>` and positions the currently-selected item+ * under the trigger; scoping the lookup to the open overlay (and waiting for it to open/close) avoids+ * clicking a stale or repositioning item, which could otherwise re-pick the previously-selected value.+ */+ private async pickOverlayOption(label: string) {+ // Vaadin slots the items into a <vaadin-select-list-box> in the select's light DOM (projected into the+ // overlay), so the options live under the list box, not the overlay element. Inert copies exist for the+ // responsive desktop/mobile selects; the open one is the only visible list box.+ const listBox = this.page.locator("vaadin-select-list-box:visible");+ await expect(listBox).toBeVisible();+ await listBox.getByRole("option", { name: label, exact: true }).click();+ await expect(listBox).not.toBeVisible();+ }++ /** Pick a source from the source filter via its overlay (e.g. "All sources", "Client"). */+ async setSourceFilter(label: string) {+ await this.getSourceSelect().click();+ await this.pickOverlayOption(label);+ }++ // --- Create dialog / form ---------------------------------------------++ /** The create form is teleported into an overlay; target it by its (unique) id. */+ getCreateForm(): Locator {+ return this.page.locator("#notificationForm");+ }++ getSubmitButton(): Locator {+ return this.page.getByRole("button", { name: "Create", exact: true });+ }++ async openCreateDialog() {+ await this.getCreateButton().click();+ await expect(this.getCreateForm()).toBeVisible();+ }++ /** Choose the message type (e.g. "Push", "Email"). */+ async selectMessageType(label: string) {+ await this.getCreateForm().locator("#messageType").click();+ await this.pickOverlayOption(label);+ }++ /** Choose the target type (e.g. "Users", "Users linked to assets", "All users in realms"). */+ async selectTargetType(label: string) {+ await this.getCreateForm().locator("#targetType").click();+ await this.pickOverlayOption(label);+ }++ async fillEmailMessage(subject: string, body: string) {+ // The fields commit on `change` (blur), so blur after filling to update the form model.+ const subjectInput = this.getCreateForm().locator("#notificationSubject input");+ await subjectInput.fill(subject);+ await subjectInput.blur();++ const bodyInput = this.getCreateForm().locator("#notificationEmailBody textarea");+ await bodyInput.fill(body);+ await bodyInput.blur();+ }++ async fillPushMessage(title: string, body: string) {+ // The fields commit on `change` (blur), so blur after filling to update the form model.+ const titleInput = this.getCreateForm().locator("#notificationTitle input");+ await titleInput.fill(title);+ await titleInput.blur();++ const bodyInput = this.getCreateForm().locator("#notificationBody textarea");+ await bodyInput.fill(body);+ await bodyInput.blur();+ }++ /** Tick a specific recipient (by visible label) in the (Users/Realms) checkbox list. */+ async checkTarget(label: string) {+ await this.getCreateForm().locator("#target").getByRole("checkbox", { name: label }).check();+ }++ /** Select an asset (by name) in the "Users linked to assets" target's asset tree. */+ async checkAssetTarget(name: string) {+ await this.getCreateForm().locator("#asset-selector .node-container", { hasText: name }).click();+ }++ // --- Details dialog ----------------------------------------------------++ /** The details dialog renders a read-only or-notification-form (reflected `readonly` attribute). */+ getDetailsForm(): Locator {+ return this.page.locator("or-notification-form[readonly]");+ }++ /**+ * The input/textarea of a read-only details field, located by its visible label (e.g. "Source").+ * Pass `exact` for labels that are substrings of another ("Recipient" vs "Recipient type").+ */+ getDetailsFieldByLabel(label: string, exact = false): Locator {+ return this.getDetailsForm()+ .locator("or-vaadin-text-field, or-vaadin-text-area")+ .filter({ hasText: exact ? new RegExp(`^\\s*${label}\\s*$`) : label })+ .locator("input, textarea");+ }++ /** Open the details dialog for the (first) row containing the given text. */+ async openDetailsByText(text: string) {+ await this.getRowByText(text).first().click();+ await expect(this.getDetailsForm()).toBeVisible();+ }++ /** The details dialog's top-right close cross (an or-vaadin-button wrapping the mdi:close icon). */+ getDetailsCloseButton(): Locator {+ return this.page+ .locator("or-vaadin-button")+ .filter({ has: this.page.locator("or-icon[icon='mdi:close']") });+ }+}diff --git a/ui/app/manager/test/fixtures/request-adapter.ts b/ui/app/manager/test/fixtures/request-adapter.tsnew file mode 100644index 000000000..21372ecec--- /dev/null+++ b/ui/app/manager/test/fixtures/request-adapter.ts@@ -0,0 +1,114 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";+import type { APIRequestContext, APIResponse } from "@openremote/test";++/**+ * Builds the absolute request URL (baseURL + url + serialized query params) the way axios' default adapter would,+ * reusing the request's paramsSerializer so array params keep the same repeat format as the app's rest client.+ */+function buildUrl(config: InternalAxiosRequestConfig): string {+ const base = (config.baseURL ?? "").replace(/\/+$/, "");+ const path = config.url ?? "";+ const url = /^https?:\/\//i.test(path) ? path : `${base}/${path.replace(/^\/+/, "")}`;++ if (!config.params) {+ return url;+ }+ const serialize = typeof config.paramsSerializer === "function"+ ? config.paramsSerializer+ : (params: Record<string, unknown>) => new URLSearchParams(params as Record<string, string>).toString();+ const query = serialize(config.params);+ return query ? `${url}${url.includes("?") ? "&" : "?"}${query}` : url;+}++/** Flattens axios' (possibly AxiosHeaders) headers into a plain string map for Playwright's request. */+function toHeaders(config: InternalAxiosRequestConfig): Record<string, string> {+ const raw: Record<string, unknown> =+ config.headers && typeof (config.headers as { toJSON?: () => unknown }).toJSON === "function"+ ? (config.headers as { toJSON: () => Record<string, unknown> }).toJSON()+ : ((config.headers as Record<string, unknown>) ?? {});+ const headers: Record<string, string> = {};+ for (const [key, value] of Object.entries(raw)) {+ if (value == null) continue;+ headers[key] = Array.isArray(value) ? value.join(", ") : String(value);+ }+ return headers;+}++/** Decodes a Playwright response body into the value axios would expose as {@link AxiosResponse.data}. */+async function decodeBody(response: APIResponse, config: InternalAxiosRequestConfig): Promise<unknown> {+ const responseType = config.responseType ?? "json";+ if (responseType === "arraybuffer") {+ return response.body();+ }+ const text = await response.text();+ if (!text) {+ return undefined;+ }+ const isJson = responseType === "json"+ && (response.headers()["content-type"] ?? "").toLowerCase().includes("application/json");+ return isJson ? JSON.parse(text) : text;+}++/**+ * An axios adapter that dispatches every request through Playwright's {@link APIRequestContext} (`request`) instead+ * of Node's http stack. This keeps the generated `@openremote/rest` typed client while ensuring the REST calls made+ * during test setup are captured in the Playwright trace viewer.+ *+ * axios interceptors and `transformRequest` have already run by the time the adapter is invoked, so the body is a+ * serialized string (or undefined) and the params serializer is set; this only translates the final config into a+ * `request.fetch` call and the response back into an {@link AxiosResponse} (throwing an {@link AxiosError} on a+ * status the request's `validateStatus` rejects, to match the default adapter).+ */+export function playwrightRequestAdapter(request: APIRequestContext): AxiosAdapter {+ return async (config: InternalAxiosRequestConfig): Promise<AxiosResponse> => {+ const response = await request.fetch(buildUrl(config), {+ method: (config.method ?? "get").toUpperCase(),+ headers: toHeaders(config),+ ...(config.data != null && { data: config.data }),+ ...(config.timeout && { timeout: config.timeout }),+ ...(config.maxRedirects != null && { maxRedirects: config.maxRedirects }),+ // Never throw on status; validateStatus is applied below to mirror axios+ failOnStatusCode: false,+ });++ const axiosResponse: AxiosResponse = {+ data: await decodeBody(response, config),+ status: response.status(),+ statusText: response.statusText(),+ headers: response.headers(),+ config,+ request: undefined,+ };++ const validateStatus = config.validateStatus ?? ((status: number) => status >= 200 && status < 300);+ if (!validateStatus(axiosResponse.status)) {+ throw new AxiosError(+ `Request failed with status code ${axiosResponse.status}`,+ axiosResponse.status >= 500 ? AxiosError.ERR_BAD_RESPONSE : AxiosError.ERR_BAD_REQUEST,+ config,+ undefined,+ axiosResponse,+ );+ }+ return axiosResponse;+ };+}diff --git a/ui/app/manager/test/notifications.test.ts b/ui/app/manager/test/notifications.test.tsnew file mode 100644index 000000000..9f9215f97--- /dev/null+++ b/ui/app/manager/test/notifications.test.ts@@ -0,0 +1,436 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import { expect, Page } from "@openremote/test";+import { Asset, EmailNotificationMessage, Notification, NotificationTargetType } from "@openremote/model";+import { type AxiosRequestConfig } from "axios";+import { Manager, adminStatePath, test } from "./fixtures/manager.js";++test.use({ storageState: adminStatePath });++test.afterEach(async ({ manager }) => {+ await manager.cleanUp();+});++const RECIPIENT_USERNAME = "e2e-notif-recipient";++/** Ensure a user with an email exists in the given realm, so email notifications resolve to a deliverable target. */+async function ensureRecipient(manager: Manager, realm = "master", config?: AxiosRequestConfig) {+ await manager.provisionUser(realm, {+ username: RECIPIENT_USERNAME,+ email: `${RECIPIENT_USERNAME}@openremote.local`,+ }, config);+}++/** Persist a notification via REST (email to the given realm) and return its subject for table lookups. */+async function seedNotification(manager: Manager, realm = "master", subject = `E2E seed ${Date.now()}`) {+ const config = await manager.adminConfig();+ await ensureRecipient(manager, realm, config);+ await manager.api.NotificationResource.sendNotification({+ name: subject,+ message: { type: "email", subject, html: "<p>seed</p>" } as EmailNotificationMessage,+ targets: [{ type: NotificationTargetType.REALM, id: realm }],+ } as Notification, config);+ return subject;+}++/** Create an asset in `realm` (REST, tracked for teardown) and return its id. */+async function createAssetAndGetId(manager: Manager, asset: Asset, config: AxiosRequestConfig): Promise<string> {+ await manager.createAsset(asset, config);+ const created = manager.assets.find((a) => a.name === asset.name);+ expect(created?.id).toBeTruthy();+ return created!.id!;+}++/** Link each of `userIds` to `assetId` in `realm` (REST). One call per user, as a batch must be for a single user. */+async function linkUsersToAsset(manager: Manager, realm: string, assetId: string, userIds: string[], config: AxiosRequestConfig) {+ for (const userId of userIds) {+ await manager.api.AssetResource.createUserAssetLinks([{ id: { realm, userId, assetId } }], config);+ }+}++/**+ * Create a ConsoleAsset with a (fake) FCM push token in `realm` and link it to `userId` (REST, tracked for teardown),+ * so push targets resolve to a console in dev mode. Mirrors ManagerNotificationSetup#createConsole.+ */+async function createConsoleForUser(manager: Manager, realm: string, userId: string, username: string, config: AxiosRequestConfig) {+ const consoleId = await createAssetAndGetId(manager, {+ name: `${username} console`,+ type: "ConsoleAsset",+ realm,+ // ConsoleAsset requires these well-known attributes to be present to pass validation+ attributes: {+ notes: { name: "notes", type: "text" },+ location: { name: "location", type: "GEO_JSONPoint" },+ consoleName: { name: "consoleName", type: "text", value: `${username} console` },+ consoleVersion: { name: "consoleVersion", type: "text", value: "1.0.0" },+ consolePlatform: { name: "consolePlatform", type: "text", value: "Android 14" },+ consoleProviders: {+ name: "consoleProviders",+ type: "consoleProviders",+ value: {+ push: {+ version: "fcm",+ requiresPermission: true,+ hasPermission: true,+ success: true,+ enabled: true,+ disabled: false,+ data: { token: `dev-fcm-token-${username}` },+ },+ },+ },+ },+ } as Asset, config);+ await linkUsersToAsset(manager, realm, consoleId, [userId], config);+}++/**+ * Create a throwaway user with the given client roles in the given realm (REST), then log in as them through the UI.+ * Used to exercise the page under a specific permission set without disturbing the stored admin session.+ */+async function createUserAndLogin(+ manager: Manager,+ page: Page,+ { realm, username, roles }: { realm: string; username: string; roles: string[] },+) {+ // set an initial password (== username) so the throwaway user can log in via the UI+ await manager.provisionUser(realm, { username, roles, password: username });++ await manager.goToRealmStartPage(realm);+ await page.getByRole("textbox", { name: "Username or email" }).fill(username);+ await page.getByRole("textbox", { name: "Password" }).fill(username);+ await page.keyboard.press("Enter");+ await page.waitForURL("**/manager/**");+}++/** 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);+}++/** A Date at `days` ago (0 = today) with the given time-of-day. */+function daysAgo(days: number, hours = 0, minutes = 0): Date {+ const d = new Date();+ d.setDate(d.getDate() - days);+ d.setHours(hours, minutes, 0, 0);+ return d;+}++/**+ * @given Logged into the "master" realm as "admin"+ * @and A notification has just been sent (REST setup), so it falls within today's default range+ * @and Navigated to the "Notifications" page+ * @then Both date filters are pre-populated and the notification is listed under the default (last day) range+ * @when The range is moved to a window in the past that excludes today+ * @then The notification is filtered out, and reappears once the range is widened to include today again+ */+test("should filter the notifications table by the date range", async ({ manager, notificationsPage }) => {+ // a REST-sent notification is stamped "now", so it sits inside the default (today) range+ const subject = await seedNotification(manager);++ await manager.goToRealmStartPage("master");+ await notificationsPage.goto();++ // the default range is pre-populated ...+ const pickers = notificationsPage.getDatePickers();+ await expect(pickers).toHaveCount(2);+ await expect(pickers.nth(0).locator("input").first()).not.toHaveValue("");+ await expect(pickers.nth(1).locator("input").first()).not.toHaveValue("");++ // ... and the just-sent notification falls within it+ await expect(notificationsPage.getRowByText(subject)).toBeVisible();++ // moving the window to a past range that excludes today filters the notification out+ await notificationsPage.setDateRange(pickerValue(daysAgo(10)), pickerValue(daysAgo(9, 23, 59)));+ await expect(notificationsPage.getRowByText(subject)).toHaveCount(0);++ // widening the range back to include today brings it back+ await notificationsPage.setDateRange(pickerValue(daysAgo(0)), pickerValue(daysAgo(0, 23, 59)));+ await expect(notificationsPage.getRowByText(subject)).toBeVisible();+});++/**+ * @given Logged into the "master" realm as "admin"+ * @and A recipient user with an email exists (REST setup)+ * @and Navigated to the "Notifications" page+ * @when The user fills in the send form step by step and submits it+ * @then The submit button stays disabled until a message and a recipient are provided+ * @and Submitting closes the dialog and the new notification appears in the table+ */+test("should disable the submit button until valid, then send and show it in the table", async ({ manager, notificationsPage }) => {+ // setup via REST: a recipient with an email so the email notification is deliverable/persisted+ await ensureRecipient(manager);++ await manager.goToRealmStartPage("master");+ await notificationsPage.goto();++ const subject = `E2E created ${Date.now()}`;+ await notificationsPage.openCreateDialog();++ // nothing filled in -> cannot submit+ await expect(notificationsPage.getSubmitButton()).toBeDisabled();++ // a message but still no recipient -> cannot submit+ await notificationsPage.selectMessageType("Email");+ await notificationsPage.fillEmailMessage(subject, "Hello from the E2E test");+ await expect(notificationsPage.getSubmitButton()).toBeDisabled();++ // add a recipient -> the form is now valid+ await notificationsPage.selectTargetType("Users");+ await notificationsPage.checkTarget(RECIPIENT_USERNAME);+ await expect(notificationsPage.getSubmitButton()).toBeEnabled();++ // submitting closes the dialog and the notification appears in the table+ await notificationsPage.getSubmitButton().click();+ await expect(notificationsPage.getCreateForm()).not.toBeVisible();+ await expect(notificationsPage.getRowByText(subject)).toBeVisible();+});++/**+ * @given Logged into the "master" realm as "admin"+ * @and A notification with source CLIENT has been seeded (REST setup)+ * @and Navigated to the "Notifications" page+ * @when The user changes the source filter+ * @then Only notifications matching the selected source remain in the table+ */+test("should filter notifications by source", async ({ manager, notificationsPage }) => {+ // a REST-sent notification has source CLIENT+ const subject = await seedNotification(manager);++ await manager.goToRealmStartPage("master");+ await notificationsPage.goto();++ // visible under the default ("All sources") filter+ await expect(notificationsPage.getRowByText(subject)).toBeVisible();++ // a source it does not have hides it+ await notificationsPage.setSourceFilter("Realm ruleset");+ await expect(notificationsPage.getRowByText(subject)).toHaveCount(0);++ // its own source shows it again+ await notificationsPage.setSourceFilter("Client");+ await expect(notificationsPage.getRowByText(subject)).toBeVisible();+});++/**+ * @given Logged into the "master" realm as "admin"+ * @and A notification has been seeded via the REST API+ * @and Navigated to the "Notifications" page+ * @when The user clicks the notification row+ * @then A read-only details dialog opens+ * @and It can be closed via the top-right cross+ */+test("should show the correct data in the notification details dialog", async ({ manager, notificationsPage }) => {+ // setup via REST: persist a known notification so there is a row to open+ const subject = await seedNotification(manager);++ // --- action (E2E): open the seeded row's details dialog ---+ await manager.goToRealmStartPage("master");+ await notificationsPage.goto();++ await expect(notificationsPage.getRowByText(subject)).toBeVisible();+ await notificationsPage.openDetailsByText(subject);++ const details = notificationsPage.getDetailsForm();++ // the dialog reflects the seeded notification's content and resolved metadata+ await expect(details.locator("#notificationSubject input")).toHaveValue(subject);+ await expect(details.locator("#notificationEmailBody textarea")).toHaveValue("<p>seed</p>");+ // the realm-targeted email resolves to a per-user record, sent from the REST client+ await expect(notificationsPage.getDetailsFieldByLabel("Recipient type")).toHaveValue("User");+ await expect(notificationsPage.getDetailsFieldByLabel("Source")).toHaveValue(/Client/i);++ await notificationsPage.getDetailsCloseButton().click();+ await expect(details).not.toBeVisible();+});++/**+ * @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+ * @when Navigated to the "Notifications" page+ * @then Their rows show the "Sent", "Delivered" and "Error" status badges respectively+ * @and The error badge carries the failure reason as its tooltip+ */+test("should show the sent, delivered and error statuses in the table", async ({ manager, notificationsPage }) => {+ const config = await manager.adminConfig();+ const now = Date.now();++ // Sent: a plain seed persists without delivery confirmation (dev mode skips the actual SMTP send)+ const sentSubject = await seedNotification(manager, "master", `E2E sent ${now}`);++ // Delivered: seed another and mark its per-user rows delivered via the REST API+ const deliveredSubject = await seedNotification(manager, "master", `E2E delivered ${now}`);+ const seeded = (await manager.api.NotificationResource.getNotifications({+ from: now - 60_000,+ to: now + 60_000,+ realmId: "master",+ }, config)).data.filter((n) => n.name === deliveredSubject);+ expect(seeded.length).toBeGreaterThan(0);+ for (const n of seeded) {+ await manager.api.NotificationResource.notificationDelivered(n.id!, { targetId: n.targetId! }, config);+ }++ // Error: a custom target without any address persists the notification, then fails with "no recipients"+ // (the send request itself returns a 400 after the row is stored, so swallow it)+ const errorSubject = `E2E error ${now}`;+ await manager.api.NotificationResource.sendNotification({+ name: errorSubject,+ message: { type: "email", subject: errorSubject, html: "<p>seed</p>" } as EmailNotificationMessage,+ targets: [{ type: NotificationTargetType.CUSTOM, id: "to:" }],+ } as Notification, config).catch(() => {});++ await manager.goToRealmStartPage("master");+ await notificationsPage.goto();++ await expect(notificationsPage.getStatusBadge(sentSubject)).toHaveText("Sent");+ await expect(notificationsPage.getStatusBadge(deliveredSubject)).toHaveText("Delivered");+ await expect(notificationsPage.getStatusBadge(errorSubject)).toHaveText("Error");+ await expect(notificationsPage.getStatusBadge(errorSubject)).toHaveAttribute("title", /no recipients/i);+});++/**+ * @given Logged into the "master" realm as "admin"+ * @and An asset with two users linked to it, each with a push-registered console (REST setup)+ * @and Navigated to the "Notifications" page+ * @when A push notification is composed and sent to that asset target+ * @then Submitting closes the dialog and the push fans out to a row per linked user's console+ */+test("should send a push notification to an asset target linked to multiple users", async ({ manager, notificationsPage }) => {+ const config = await manager.adminConfig();+ const stamp = Date.now();+ const assetName = `E2E push asset ${stamp}`;+ const assetId = await createAssetAndGetId(manager, {+ name: assetName,+ type: "ThingAsset",+ realm: "master",+ // ThingAsset requires these well-known attributes to be present to pass validation+ attributes: {+ notes: { name: "notes", type: "text" },+ location: { name: "location", type: "GEO_JSONPoint" },+ },+ } as Asset, config);++ // two users linked to the asset, each with a push-registered console so an asset push resolves to their consoles+ const usernames = [`e2e-push-1-${stamp}`, `e2e-push-2-${stamp}`];+ for (const username of usernames) {+ const user = await manager.provisionUser("master", { username }, config);+ expect(user?.id).toBeTruthy();+ await linkUsersToAsset(manager, "master", assetId, [user!.id!], config);+ await createConsoleForUser(manager, "master", user!.id!, username, config);+ }++ await manager.goToRealmStartPage("master");+ await notificationsPage.goto();++ const title = `E2E asset push ${stamp}`;+ await notificationsPage.openCreateDialog();+ await notificationsPage.selectMessageType("Push");+ await notificationsPage.fillPushMessage(title, "Hello from the E2E push test");++ // pick the asset as the target -> the form becomes valid+ await notificationsPage.selectTargetType("Users linked to assets");+ await notificationsPage.checkAssetTarget(assetName);+ await expect(notificationsPage.getSubmitButton()).toBeEnabled();++ // submitting closes the dialog and the push fans out to a record per linked user's console+ await notificationsPage.getSubmitButton().click();+ await expect(notificationsPage.getCreateForm()).not.toBeVisible();+ await expect(notificationsPage.getRowByText(title)).toHaveCount(usernames.length);+});++/**+ * Each test logs in as a freshly-created "smartcity" user with a specific permission set (REST setup) and asserts+ * the distinct UI condition that permission set should produce on the notifications page.+ */+test.describe("Role-Based Access Control", () => {+ // Start from a clean session so we can log in as the low-privilege user rather than a stored admin state.+ test.use({ storageState: { cookies: [], origins: [] } });++ /**+ * @given A "smartcity" user with read:notifications only (no write:admin/write:notifications)+ * @then The table is visible but the write-gated "Send new" button is hidden+ */+ test("should hide the send button for a user without write permission", async ({ page, manager, notificationsPage }) => {+ await createUserAndLogin(manager, page, {+ realm: "smartcity",+ username: "e2e-readonly",+ roles: ["read:notifications"],+ });++ await notificationsPage.goto();+ await expect(notificationsPage.getCreateButton()).not.toBeVisible();+ });++ /**+ * @given A "smartcity" user with write:notifications but no read:admin/read:users/read:assets+ * @then The "Send new" button is shown (write permission) but disabled (no recipient type can be chosen)+ */+ test("should disable the send button for a user who cannot choose any recipient type", async ({ page, manager, notificationsPage }) => {+ await createUserAndLogin(manager, page, {+ realm: "smartcity",+ username: "e2e-sender",+ roles: ["read:notifications", "write:notifications"],+ });++ await notificationsPage.goto();+ await expect(notificationsPage.getCreateButton()).toBeVisible();+ await expect(notificationsPage.getCreateButton()).toBeDisabled();+ });++ /**+ * @given A "smartcity" user with write:notifications and read:users but no asset read permission+ * @when The create dialog is opened for the first time+ * @then The target type is forced to Users and the recipient checkbox list is populated+ */+ test("should list user recipients on first open for a user who cannot read assets", async ({ page, manager, notificationsPage }) => {+ await ensureRecipient(manager, "smartcity", await manager.adminConfig());+ await createUserAndLogin(manager, page, {+ realm: "smartcity",+ username: "e2e-user-sender",+ roles: ["read:notifications", "write:notifications", "read:users"],+ });++ await notificationsPage.goto();+ await notificationsPage.openCreateDialog();+ await expect(notificationsPage.getCreateForm().locator("#target")+ .getByRole("checkbox", { name: RECIPIENT_USERNAME })).toBeVisible();+ });++ /**+ * @given A notification seeded into "smartcity" (REST) and a "smartcity" user with read:notifications only+ * @when That user opens the notification's details dialog+ * @then The recipient type is shown, but the recipient's identity is sanitised away (shown as "-")+ */+ test("should hide the recipient identity for a viewer without user/asset read permission", async ({ page, manager, notificationsPage }) => {+ const subject = await seedNotification(manager, "smartcity");+ await createUserAndLogin(manager, page, {+ realm: "smartcity",+ username: "e2e-viewer",+ roles: ["read:notifications"],+ });++ await notificationsPage.goto();+ await notificationsPage.openDetailsByText(subject);++ // the realm email resolves to per-user USER targets; the type is visible, the identity is not+ await expect(notificationsPage.getDetailsFieldByLabel("Recipient type")).toHaveValue("User");+ await expect(notificationsPage.getDetailsFieldByLabel("Recipient", true)).toHaveValue("-");+ });+});diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.jsonindex 242b3adbb..9970c338b 100644--- a/ui/app/shared/locales/en/or.json+++ b/ui/app/shared/locales/en/or.json@@ -1,4 +1,5 @@{+ "actions": "Actions","map": "Map","map_plural": "Maps","rule": "Rule",@@ -809,6 +810,7 @@"realmAlreadyExists": "Realm name already exists","invalidUsername": "Username must be 3-255 alpha numerical characters","invalidEmail": "Invalid email address",+ "invalidUrl": "Enter a valid URL, e.g. https://example.com","invalidRealm": "Realm must be 2-255 alpha numerical characters","yes": "Yes","no": "No",@@ -1060,7 +1062,7 @@"inactive_plural": "Inactive alarms","active_plural": "Active alarms","title": "Title",- "content": "Description",+ "content": "Content","severity": "Severity","status": "Status","status_CLOSED": "Closed",@@ -1103,6 +1105,56 @@},"expandAll": "Expand all","collapseAll": "Collapse all",+ "title": "Title",+ "body": "Body",+ "content": "Content",+ "priority": "Priority",+ "normal": "Normal",+ "high": "High",+ "source": "Source",+ "sent": "Sent",+ "delivered": "Delivered",+ "sentOn": "Sent on",+ "deliveredOn": "Delivered on",+ "pending": "Pending",+ "loadingRealmsFailed": "Failed to load realms",+ "loadingAssetsFailed": "Failed to load assets",+ "loadingUsersFailed": "Failed to load users",+ "loadingNotificationFailed": "Failed to load notification",+ "notification_one": "Notification",+ "notification_other": "Notifications",+ "notifications": {+ "source": "Source",+ "sources": {+ "ALL_SOURCES": "All sources",+ "CLIENT": "Client",+ "INTERNAL": "Internal",+ "GLOBAL_RULESET": "Global ruleset",+ "REALM_RULESET": "Realm ruleset",+ "ASSET_RULESET": "Asset ruleset"+ },+ "types": {+ "push": "Push",+ "email": "Email"+ },+ "targetTypes": {+ "USER": "Users",+ "ASSET": "Users linked to assets",+ "REALM": "All users in realms"+ },+ "targetListLabel": {+ "USER": "Recipients",+ "REALM": "Recipients in realms"+ },+ "target": "Recipient",+ "targetType": "Recipient type",+ "failedToCreateNotification": "Failed to send notification.",+ "successfullySentNotification": "Successfully sent notification.",+ "missingFields": "Failed to create notification, missing required fields.",+ "details": "Notification details",+ "createNotification": "Send notification",+ "sendNew": "Send new"+ },"services": "Services","service": {"noServiceSelected": "Please select a service on the left",diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.jsonindex 18538d677..c8d1891f4 100644--- a/ui/app/shared/locales/nl/or.json+++ b/ui/app/shared/locales/nl/or.json@@ -1,4 +1,5 @@{+ "actions": "Acties","map": "Kaart","map_plural": "Kaarten","rule": "Regel",@@ -800,6 +801,7 @@"realmAlreadyExists": "Realm naam bestaat al","invalidUsername": "De gebruikersnaam mag 3-255 numerieke tekens bevatten","invalidEmail": "Ongeldig emailadres",+ "invalidUrl": "Voer een geldige URL in, bijv. https://example.com","invalidRealm": "De realm naam mag 2-255 numerieke tekens bevatten","yes": "Ja","no": "Nee",@@ -1050,7 +1052,7 @@"inactive_plural": "Inactieve alarmen","active_plural": "Actieve alarmen","title": "Titel",- "content": "Beschrijving",+ "content": "Inhoud","severity": "Ernst","status": "Status","status_CLOSED": "Gesloten",@@ -1093,6 +1095,56 @@},"expandAll": "Alles uitklappen","collapseAll": "Alles inklappen",+ "title": "Titel",+ "body": "Bericht",+ "content": "Inhoud",+ "priority": "Prioriteit",+ "normal": "Normaal",+ "high": "Hoog",+ "source": "Bron",+ "sent": "Gestuurd",+ "delivered": "Bezorgd",+ "sentOn": "Gestuurd op",+ "deliveredOn": "Bezorgd op",+ "pending": "In afwachting",+ "loadingRealmsFailed": "Realms laden niet gelukt",+ "loadingAssetsFailed": "Assets laden niet gelukt",+ "loadingUsersFailed": "Gebruikers laden niet gelukt",+ "loadingNotificationFailed": "Notificatie laden niet gelukt",+ "notification_one": "Notificatie",+ "notification_other": "Notificaties",+ "notifications": {+ "source": "Afkomst",+ "sources": {+ "ALL_SOURCES": "Alle bronnen",+ "CLIENT": "Client",+ "INTERNAL": "Intern",+ "GLOBAL_RULESET": "Globale regels",+ "REALM_RULESET": "Realm regels",+ "ASSET_RULESET": "Asset regels"+ },+ "types": {+ "push": "Push",+ "email": "E-mail"+ },+ "targetTypes": {+ "USER": "Gebruikers",+ "ASSET": "Gebruikers gekoppeld aan assets",+ "REALM": "Alle gebruikers in realms"+ },+ "targetListLabel": {+ "USER": "Ontvangers",+ "REALM": "Ontvangers in realms"+ },+ "target": "Ontvanger",+ "targetType": "Ontvanger type",+ "failedToCreateNotification": "Notificatie versturen mislukt.",+ "successfullySentNotification": "Notificatie verstuurd",+ "missingFields": "Notificatie maken mislukt, niet alle verplichte velden waren gevuld.",+ "details": "Notificatie details",+ "createNotification": "Notificatie versturen",+ "sendNew": "Aanmaken"+ },"services": "Services","service": {"noServiceSelected": "Selecteer een service aan de linkerkant",diff --git a/ui/app/storybook/rsbuild.config.ts b/ui/app/storybook/rsbuild.config.tsindex 1ba588a5a..4d64ede1a 100644--- a/ui/app/storybook/rsbuild.config.ts+++ b/ui/app/storybook/rsbuild.config.ts@@ -41,6 +41,7 @@ export default defineConfig({"@openremote/or-attribute-picker": "../../component/or-attribute-picker/src","@openremote/or-components": "../../component/or-components/src","@openremote/or-chart": "../../component/or-chart/src",+ "@openremote/or-element": "../../component/or-element/src","@openremote/or-icon": "../../component/or-icon/src","@openremote/or-map": "../../component/or-map/src","@openremote/or-mwc-components": "../../component/or-mwc-components/src",diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.tsindex 8c2820b70..e32a2da7a 100644--- a/ui/component/or-asset-tree/src/index.ts+++ b/ui/component/or-asset-tree/src/index.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */import {html, LitElement, PropertyValues, TemplateResult} from "lit";import {customElement, property, query, state} from "lit/decorators.js";import {type OrVaadinTextField} from "@openremote/or-vaadin-components/or-vaadin-text-field";@@ -1556,6 +1575,8 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {<style>.mdc-dialog__content {padding: 0 !important;+ border-bottom: solid var(--or-app-color5, #CCCCCC) 1px;+ border-top: solid var(--or-app-color5, #CCCCCC) 1px;}</style>`)@@ -2177,7 +2198,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {<div class="node-name"><div class="expander" ?data-expandable="${treeNode.expandable}"></div>${getAssetDescriptorIconTemplate(descriptor, undefined, undefined, (filterColorForNonMatchingAsset ? 'd3d3d3' : undefined))}- <span style="color: ${filterColorForNonMatchingAsset ? '#d3d3d3;' : ''}">${treeNode.asset!.name}</span>+ <span class="${this.checkboxes ? 'node-name-withCheck' : 'node-name-noCheck'}" title="${treeNode.asset!.name}" style="color: ${filterColorForNonMatchingAsset ? '#d3d3d3;' : ''}">${treeNode.asset!.name}</span>${this.checkboxes ? html`<span class="mdc-list-item__graphic">${treeNode.expandablediff --git a/ui/component/or-asset-tree/src/style.ts b/ui/component/or-asset-tree/src/style.tsindex 58eadb574..69966fb35 100644--- a/ui/component/or-asset-tree/src/style.ts+++ b/ui/component/or-asset-tree/src/style.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */import {css, unsafeCSS} from "lit";import { DefaultColor1, DefaultColor2, DefaultColor4, DefaultColor5, DefaultColor8 } from "@openremote/core";import {mdiChevronRight} from "@mdi/js";@@ -163,6 +182,7 @@ export const style = css`}.expander {+ flex: 0 0 auto;width: 36px;height: 100%;display: inline-block;@@ -187,13 +207,23 @@ export const style = css`}.node-name {+ width: 100%;margin: -4px 0;flex: 1 0 auto;display: flex;align-items: center;}- .node-name > span {+ .node-name-withCheck {+ flex: 1 1 auto;+ white-space: nowrap;+ overflow: hidden;+ margin-right: 4px;+ text-overflow: ellipsis;+ vertical-align: middle;+ }++ .node-name-noCheck {vertical-align: middle;}@@ -231,7 +261,6 @@ export const style = css`}.mdc-checkbox or-icon {- height: 15px;width: auto;color: var(--internal-or-asset-tree-line-color);}diff --git a/ui/component/or-element/build.gradle b/ui/component/or-element/build.gradlenew file mode 100644index 000000000..f8c0b80c1--- /dev/null+++ b/ui/component/or-element/build.gradle@@ -0,0 +1,23 @@+tasks.register('clean', Delete) {+ delete layout.projectDirectory.dir('dist')+ delete layout.projectDirectory.dir('lib')+}++tasks.register('npmBuild', Exec) {+ mustRunAfter npmClean+ dependsOn getYarnInstallTask()+ commandLine npmCommand("yarn"), "run", "build"+}++tasks.register('npmTest', Exec) {+ dependsOn getYarnInstallTask()+ commandLine npmCommand("yarn"), "run", "test"+}++tasks.register('prepareUi') {+ dependsOn clean, npmPublish, npmPrepare+}++tasks.register('publishUi') {+ dependsOn clean, npmPublish+}diff --git a/ui/component/or-element/package.json b/ui/component/or-element/package.jsonnew file mode 100644index 000000000..b53714b95--- /dev/null+++ b/ui/component/or-element/package.json@@ -0,0 +1,26 @@+{+ "name": "@openremote/or-element",+ "version": "1.28.0-snapshot",+ "description": "Base element and shared shadow-DOM styling for OpenRemote UI components",+ "main": "lib/index.js",+ "module": "lib/index.js",+ "exports": {+ ".": "./lib/index.js",+ "./*": "./lib/*.js"+ },+ "types": "lib/index.d.ts",+ "scripts": {+ "build": "npx tsc -b",+ "test": "npx tsc -b && npx playwright test",+ "prepack": "npx tsc -b"+ },+ "author": "OpenRemote",+ "license": "AGPL-3.0-or-later",+ "repository": "https://github.com/openremote/openremote",+ "dependencies": {+ "lit": "^3.3.1"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/ui/component/or-element/playwright.config.ts b/ui/component/or-element/playwright.config.tsnew file mode 100644index 000000000..94d454129--- /dev/null+++ b/ui/component/or-element/playwright.config.ts@@ -0,0 +1,3 @@+import { defineCtConfig } from "@openremote/test/component.config";++export default defineCtConfig(__dirname);diff --git a/ui/component/or-element/src/index.ts b/ui/component/or-element/src/index.tsnew file mode 100644index 000000000..26df19359--- /dev/null+++ b/ui/component/or-element/src/index.ts@@ -0,0 +1,44 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import { css, CSSResult, CSSResultGroup, CSSResultOrNative, LitElement } from "lit";++/**+ * Shared styling for components rendered in shadow DOM (where the global theme CSS can't reach).+ * Applied automatically to components extending {@link OrElement}.+ */+export const globals: CSSResult = css`+ h4 {+ margin: 0;+ padding-bottom: var(--lumo-space-m);+ font-size: var(--lumo-font-size-l);+ font-weight: 600;+ line-height: 125.303%;+ }+`;++/**+ * Base class for OpenRemote Lit components: prepends the shared {@link globals} styling to the+ * component's own `static styles`, so it applies inside the shadow DOM without a per-component include.+ */+export class OrElement extends LitElement {+ protected static finalizeStyles(styles?: CSSResultGroup): CSSResultOrNative[] {+ return [globals, ...super.finalizeStyles(styles)];+ }+}diff --git a/ui/component/or-element/test/fixtures/elements.js b/ui/component/or-element/test/fixtures/elements.jsnew file mode 100644index 000000000..327419916--- /dev/null+++ b/ui/component/or-element/test/fixtures/elements.js@@ -0,0 +1,46 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+// Plain JS on purpose: the component-test bundle compiles .ts files against ui/test's tsconfig+// (rootDir ui/test), so TS component sources outside that dir fail the build.+import { css, html } from "lit";+import { OrElement } from "@openremote/or-element";++/** Renders a heading without defining any styles of its own. */+export class UnstyledElement extends OrElement {+ render() {+ return html`<h4>Heading</h4>`;+ }+}+customElements.define("test-unstyled-element", UnstyledElement);++/** Renders a heading with own styles that add to (underline) and override (font-weight) the shared ones. */+export class StyledElement extends OrElement {+ static styles = css`+ h4 {+ font-weight: 400;+ text-decoration: underline;+ }+ `;++ render() {+ return html`<h4>Heading</h4>`;+ }+}+customElements.define("test-styled-element", StyledElement);diff --git a/ui/component/or-element/test/or-element.test.ts b/ui/component/or-element/test/or-element.test.tsnew file mode 100644index 000000000..cd8dce4a9--- /dev/null+++ b/ui/component/or-element/test/or-element.test.ts@@ -0,0 +1,48 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */+import { ct, expect } from "@openremote/test";++import { StyledElement, UnstyledElement } from "./fixtures/elements.js";++ct("should apply the shared heading styling when the component defines no styles", async ({ mount }) => {+ const component = await mount(UnstyledElement);+ const heading = component.getByRole("heading", { name: "Heading" });++ // from the shared globals: h4 { margin: 0; font-weight: 600; ... }+ await expect(heading).toHaveCSS("font-weight", "600");+ await expect(heading).toHaveCSS("margin-top", "0px");+});++ct("should merge the shared styling with the component's own styles", async ({ mount }) => {+ const component = await mount(StyledElement);+ const heading = component.getByRole("heading", { name: "Heading" });++ // the component's own rule applies ...+ await expect(heading).toHaveCSS("text-decoration-line", "underline");+ // ... while shared rules it does not touch remain in effect+ await expect(heading).toHaveCSS("margin-top", "0px");+});++ct("should let the component's own styles override the shared ones", async ({ mount }) => {+ const component = await mount(StyledElement);+ const heading = component.getByRole("heading", { name: "Heading" });++ await expect(heading).toHaveCSS("font-weight", "400");+});diff --git a/ui/component/or-element/tsconfig.json b/ui/component/or-element/tsconfig.jsonnew file mode 100644index 000000000..dd3861cf9--- /dev/null+++ b/ui/component/or-element/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "../../tsconfig",+ "compilerOptions": {+ "outDir": "./lib",+ "rootDir": "src"+ },+ "include": [+ "./src"+ ]+}diff --git a/ui/component/or-mwc-components/src/or-mwc-table.ts b/ui/component/or-mwc-components/src/or-mwc-table.tsindex 0e8d6a0fa..8cd5599ee 100644--- a/ui/component/or-mwc-components/src/or-mwc-table.ts+++ b/ui/component/or-mwc-components/src/or-mwc-table.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";import {customElement, property, state} from "lit/decorators.js";import {classMap} from "lit/directives/class-map.js";@@ -263,6 +282,9 @@ export class OrMwcTable extends LitElement {@property({type: Number})public paginationSize: number = 10;+ @property({type: Number})+ public totalCount?: number;+@state()protected _dataTable?: MDCDataTable;@@ -306,8 +328,12 @@ export class OrMwcTable extends LitElement {"mdc-data-table__fullheight": !!this.config.fullHeight,"has-sticky-first-column": !!this.config.stickyFirstColumn}- // Only show pagination if enabled in config, and when "the amount of rows doesn't fit on the page".- const showPagination = this.config.pagination?.enable && (!!this.rowsTemplate || (this.rows && (this.rows.length > this.paginationSize)));+ // Only show pagination if enabled in config, and when the amount of rows doesn't fit on the page using the+ // smallest page size available; comparing against the smallest size (rather than the selected one) ensures the+ // rows-per-page control stays visible after selecting a page size larger than the row count.+ const paginationOptions = this.config.pagination?.options || [10, 25, 100];+ const minPageSize = Math.min(...paginationOptions, this.paginationSize);+ const showPagination = this.config.pagination?.enable && (!!this.rowsTemplate || ((this.totalCount ?? this.rows?.length ?? 0) > minPageSize));const tableWidth = this.shadowRoot?.firstElementChild?.clientWidth;return html`<div class="${classMap(tableClasses)}">@@ -432,7 +458,7 @@ export class OrMwcTable extends LitElement {</div><!-- Pagination HTML, shown on the bottom right. Same as Material Design spec -->${when(showPagination, () => {- const options = this.config.pagination?.options || [10, 25, 100];+ const options = paginationOptions;return html`<div class="mdc-data-table__pagination"><div class="mdc-data-table__pagination-trailing">@@ -647,36 +673,40 @@ export class OrMwcTable extends LitElement {// HTML for the controls on the bottom of the table.// Includes basic pagination for browsing pages, with calculations of where to go.async getPaginationControls(): Promise<TemplateResult> {+ return this.renderPaginationControls(this.paginationIndex, (page) => {+ this.paginationIndex = page;+ });+ }++ /**+ * Renders the bottom pagination controls for the given (zero-based) current page. Navigation is delegated to+ * {@link goToPage} so subclasses can drive pagination differently (e.g. this component's local+ * `paginationIndex`, or server-side pagination via an event).+ */+ protected async renderPaginationControls(page: number, goToPage: (page: number) => void): Promise<TemplateResult> {const max: number = await this.getRowCount();- const start: number = (this.paginationIndex * this.paginationSize) + 1;- let end: number = this.paginationIndex * this.paginationSize + this.paginationSize;- if (end > max) {- end = max;- }+ const start: number = page * this.paginationSize + 1;+ const end: number = Math.min(page * this.paginationSize + this.paginationSize, max);+ const isFirst: boolean = page === 0;+ const isLast: boolean = end >= max;+ const lastPage: number = Math.max(0, Math.ceil(max / this.paginationSize) - 1);return html`<div class="mdc-data-table__pagination-navigation"><div class="mdc-data-table__pagination-total"><span>${start}-${end} of ${max}</span></div><or-mwc-input class="mdc-data-table__pagination-button" .type="${InputType.BUTTON}"- data-first-page="true" icon="page-first" .disabled="${this.paginationIndex == 0}"- @or-mwc-input-changed="${() => this.paginationIndex = 0}"></or-mwc-input>+ data-first-page="true" icon="page-first" .disabled="${isFirst}"+ @or-mwc-input-changed="${() => goToPage(0)}"></or-mwc-input><or-mwc-input class="mdc-data-table__pagination-button" .type="${InputType.BUTTON}"- data-prev-page="true" icon="chevron-left" .disabled="${this.paginationIndex == 0}"- @or-mwc-input-changed="${() => this.paginationIndex--}"></or-mwc-input>+ data-prev-page="true" icon="chevron-left" .disabled="${isFirst}"+ @or-mwc-input-changed="${() => goToPage(page - 1)}"></or-mwc-input><or-mwc-input class="mdc-data-table__pagination-button" .type="${InputType.BUTTON}"- data-next-page="true" icon="chevron-right"- .disabled="${this.paginationIndex * this.paginationSize + this.paginationSize >= max}"- @or-mwc-input-changed="${() => this.paginationIndex++}"></or-mwc-input>+ data-next-page="true" icon="chevron-right" .disabled="${isLast}"+ @or-mwc-input-changed="${() => goToPage(page + 1)}"></or-mwc-input><or-mwc-input class="mdc-data-table__pagination-button" .type="${InputType.BUTTON}"- data-last-page="true" icon="page-last"- .disabled="${this.paginationIndex * this.paginationSize + this.paginationSize >= max}"- @or-mwc-input-changed="${async () => {- let pages: number = max / this.paginationSize;- pages = pages.toString().includes('.') ? Math.floor(pages) : (pages - 1);- this.paginationIndex = pages;- }}"- ></or-mwc-input>+ data-last-page="true" icon="page-last" .disabled="${isLast}"+ @or-mwc-input-changed="${() => goToPage(lastPage)}"></or-mwc-input></div>`;}diff --git a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-email-message.ts b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-email-message.tsindex f8c7a00ac..ccd7c3c34 100644--- a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-email-message.ts+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-email-message.ts@@ -57,7 +57,7 @@ export class OrRuleFormEmailMessage extends translate(i18next)(LitElement) {</or-vaadin-text-field><or-vaadin-text-area value=${this.message?.html} required style="min-height: 200px;"@change=${(ev: Event) => this.setActionNotificationName((ev.currentTarget as HTMLInputElement).value, "html")}>- <or-translate slot="label" value="message"></or-translate>+ <or-translate slot="label" value="body"></or-translate></or-vaadin-text-area></div>`diff --git a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-push-notification.ts b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-push-notification.tsindex 2e132723b..0d80039ba 100644--- a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-push-notification.ts+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-push-notification.ts@@ -1,3 +1,22 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * 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 <http://www.gnu.org/licenses/>.+ */import {html, LitElement, css, TemplateResult} from "lit";import {customElement, property, query} from "lit/decorators.js";import "@openremote/or-mwc-components/or-mwc-input";@@ -67,13 +86,15 @@ export class OrRuleFormPushNotification extends translate(i18next)(LitElement) {<form style="display:grid"><or-vaadin-text-field id="push-title" value=${message.title} required@change=${(ev: Event) => onchange(ev, message).then(msg => this._onTitleChange(this._pushTitleElem!, msg))}>- <or-translate slot="label" value="subject"></or-translate>+ <or-translate slot="label" value="title"></or-translate></or-vaadin-text-field><or-vaadin-text-area id="push-body" value=${message.body} required style="min-height: 200px;"@change=${(ev: Event) => onchange(ev, message).then(msg => this._onBodyChange(this._pushBodyElem!, msg))}>- <or-translate slot="label" value="message"></or-translate>+ <or-translate slot="label" value="body"></or-translate></or-vaadin-text-area>- <or-vaadin-text-field id="push-url" value=${message.action?.url}+ <or-vaadin-text-field id="push-url" type="url" pattern="^[a-zA-Z][a-zA-Z0-9+.\\-]*://.+$"+ error-message="${i18next.t("invalidUrl")}"+ placeholder="https://example.com" value=${message.action?.url}@change=${(ev: Event) => onchange(ev, message).then(msg => this._onActionUrlChange(this._pushUrlElem!, msg))}><or-translate slot="label" value="openWebsiteUrl"></or-translate></or-vaadin-text-field>diff --git a/ui/component/or-scheduler/package.json b/ui/component/or-scheduler/package.jsonindex d58d6a1fb..d7e0311ac 100644--- a/ui/component/or-scheduler/package.json+++ b/ui/component/or-scheduler/package.json@@ -22,9 +22,11 @@"dependencies": {"@openremote/core": "workspace:*","@openremote/model": "workspace:*",+ "@openremote/or-element": "workspace:*","@openremote/or-icon": "workspace:*","@openremote/or-translate": "workspace:*","@openremote/or-vaadin-components": "workspace:*",+ "@openremote/theme": "workspace:*","lit": "^3.3.1","moment": "^2.29.4","rrule": "^2.6.4"diff --git a/ui/component/or-scheduler/src/index.ts b/ui/component/or-scheduler/src/index.tsindex 2b2f89bec..b9fff2dd5 100644--- a/ui/component/or-scheduler/src/index.ts+++ b/ui/component/or-scheduler/src/index.ts@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -30,7 +30,8 @@ import "@openremote/or-vaadin-components/or-vaadin-radio-group";import "@openremote/or-vaadin-components/or-vaadin-select";import "@openremote/or-vaadin-components/or-vaadin-multi-select-combo-box";import "@openremote/or-vaadin-components/or-vaadin-time-picker";-import { css, html, LitElement, PropertyValues, TemplateResult } from "lit";+import { css, html, PropertyValues, TemplateResult } from "lit";+import { OrElement } from "@openremote/or-element";import { customElement, property, query, state } from "lit/decorators.js";import { when } from "lit/directives/when.js";import { Util } from "@openremote/core";@@ -104,8 +105,13 @@ declare global {}@customElement("or-scheduler")-export class OrScheduler extends translate(i18next)(LitElement) {+export class OrScheduler extends translate(i18next)(OrElement) {+static styles = css`+ or-vaadin-dialog::part(overlay) {+ max-width: 600px;+ }+.time-label {display: flex;&>:first-child {@@ -473,13 +479,6 @@ export class OrScheduler extends translate(i18next)(LitElement) {padding: var(--lumo-space-l);}- .title {- padding-bottom: var(--lumo-space-m);- font-size: var(--lumo-font-size-l);- font-style: normal;- font-weight: 600;- line-height: 125.303%; /* 22.554px */- }.label {margin-left: 10px;@@ -509,7 +508,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {</style><div style="display: flex; flex-direction: column; gap: var(--lumo-space-m)"><div id="event-type" class="section">- <label class="title"><or-translate value="schedule.type"></or-translate></label>+ <h4><or-translate value="schedule.type"></or-translate></h4><or-vaadin-select style="flex: 1" .value="${this._eventType}" .items="${eventTypes}" @change="${this._setCalendarEventType}"></or-vaadin-select></div>${when(this._eventType !== EventTypes.default, () => this._getPeriodTemplate())}@@ -596,7 +595,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {return html`<div id="recurrence" class="section">- <label class="title"><or-translate value="schedule.repeat"></or-translate></label>+ <h4><or-translate value="schedule.repeat"></or-translate></h4><div style="display: flex; gap: 8px">${when(!this.disabledRRuleParts?.includes("interval"), () => html`<or-vaadin-number-field min="1" max="9" step-buttons-visible style="width: 106px" .value="${interval}"@@ -608,7 +607,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {</or-vaadin-select></div>${when(BY_RRULE_PARTS.some((p) => this._byRRuleParts?.includes(p)), () => html`- <label class="title" style="margin-top: var(--lumo-space-l)"><or-translate value="schedule.repeatOn"></or-translate></label>+ <h4 style="margin-top: var(--lumo-space-l)"><or-translate value="schedule.repeatOn"></or-translate></h4><div>${this._getByRulePart("bymonth", InputType.CHECKBOX_LIST, Object.entries(MONTHS))}</div><div>${this._getByRulePart("byweekno", InputType.SELECT, byWeekNoOptions)}@@ -662,7 +661,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {const calendar = this._scheduleWithOffset!;return html`<div id="period" class="section">- <label class="title"><or-translate value="period"></or-translate></label>+ <h4><or-translate value="period"></or-translate></h4><div style="display: flex; gap: 8px"><div class="period"><or-vaadin-date-picker style="text-transform: capitalize" ?combined="${!this.isAllDay}" .value="${moment(calendar.start).format("YYYY-MM-DD")}"@@ -698,7 +697,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {protected _getEndsTemplate(): TemplateResult {return html`<div id="recurrence-ends" class="section">- <label class="title"><or-translate value="schedule._ends"></or-translate></label>+ <h4><or-translate value="schedule._ends"></or-translate></h4><div style="display: flex; gap: 8px;"><or-vaadin-radio-group style="padding-right: 10px; width: unset" .value="${this._ends}" theme="vertical"@change="${this._onPartChange("recurrence-ends", "value")}">diff --git a/ui/component/or-scheduler/tsconfig.json b/ui/component/or-scheduler/tsconfig.jsonindex 3b50d5ef2..8b4058d24 100644--- a/ui/component/or-scheduler/tsconfig.json+++ b/ui/component/or-scheduler/tsconfig.json@@ -10,6 +10,7 @@"references": [{ "path": "../model" },{ "path": "../core" },+ { "path": "../or-element" },{ "path": "../or-translate" },{ "path": "../or-vaadin-components" }]diff --git a/ui/component/or-vaadin-components/src/or-vaadin-dialog.ts b/ui/component/or-vaadin-components/src/or-vaadin-dialog.tsindex e0d4b4e3a..a6d4e1c54 100644--- a/ui/component/or-vaadin-components/src/or-vaadin-dialog.ts+++ b/ui/component/or-vaadin-components/src/or-vaadin-dialog.ts@@ -49,6 +49,10 @@ export class OrVaadinDialog extends (Dialog as new () => Dialog & LitElement) im::part(content) {background-color: var(--lumo-contrast-5pct);}+ ::part(header) {+ /* Colour header icons (e.g. the close cross) with the primary colour */+ --internal-or-icon-fill: var(--lumo-primary-color);+ }::part(header),::part(footer) {padding: var(--lumo-space-l);diff --git a/ui/component/theme/src/components/or-vaadin-dialog.css b/ui/component/theme/src/components/or-vaadin-dialog.cssindex 9328ba96d..57113d041 100644--- a/ui/component/theme/src/components/or-vaadin-dialog.css+++ b/ui/component/theme/src/components/or-vaadin-dialog.css@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -21,9 +21,11 @@@media lumo_components_dialog-overlay-internal {:host::part(overlay) {- max-width: 600px;width: 100%;}+ :host(:not([has-footer])) [part="content"] {+ padding: 0 var(--lumo-space-l) var(--lumo-space-l) !important;+ }}:root::before,diff --git a/ui/component/theme/src/index.d.ts b/ui/component/theme/src/index.d.tsindex 1e1c46e24..d36422b90 100644--- a/ui/component/theme/src/index.d.ts+++ b/ui/component/theme/src/index.d.ts@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.diff --git a/ui/component/theme/src/index.js b/ui/component/theme/src/index.jsindex 18155cc82..116ab2804 100644--- a/ui/component/theme/src/index.js+++ b/ui/component/theme/src/index.js@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.diff --git a/ui/test/fixtures/index.ts b/ui/test/fixtures/index.tsindex 3cf483e62..f7b90264b 100644--- a/ui/test/fixtures/index.ts+++ b/ui/test/fixtures/index.ts@@ -1,4 +1,6 @@import type {+ APIRequestContext,+ APIResponse,Fixtures,PlaywrightTestArgs,Page,@@ -41,4 +43,4 @@ export const ctFixtures: Fixtures<PlaywrightTestArgs & PlaywrightTestOptions & S};export const ct = test;-export type { BasePage, ComponentTestType, Locator, Page, Project, Shared, TestFixture };+export type { APIRequestContext, APIResponse, BasePage, ComponentTestType, Locator, Page, Project, Shared, TestFixture };diff --git a/yarn.lock b/yarn.lockindex 93ada5086..542027650 100644--- a/yarn.lock+++ b/yarn.lock@@ -1929,6 +1929,7 @@ __metadata:"@openremote/or-attribute-picker": "workspace:*""@openremote/or-components": "workspace:*""@openremote/or-dashboard-builder": "workspace:*"+ "@openremote/or-element": "workspace:*""@openremote/or-icon": "workspace:*""@openremote/or-json-forms": "workspace:*""@openremote/or-log-viewer": "workspace:*"@@ -2189,6 +2190,14 @@ __metadata:languageName: unknownlinkType: soft+"@openremote/or-element@workspace:*, @openremote/or-element@workspace:ui/component/or-element":+ version: 0.0.0-use.local+ resolution: "@openremote/or-element@workspace:ui/component/or-element"+ dependencies:+ lit: "npm:^3.3.1"+ languageName: unknown+ linkType: soft+"@openremote/or-gauge@workspace:*, @openremote/or-gauge@workspace:ui/component/or-gauge":version: 0.0.0-use.localresolution: "@openremote/or-gauge@workspace:ui/component/or-gauge"@@ -2360,9 +2369,11 @@ __metadata:dependencies:"@openremote/core": "workspace:*""@openremote/model": "workspace:*"+ "@openremote/or-element": "workspace:*""@openremote/or-icon": "workspace:*""@openremote/or-translate": "workspace:*""@openremote/or-vaadin-components": "workspace:*"+ "@openremote/theme": "workspace:*""@openremote/util": "workspace:*"lit: "npm:^3.3.1"moment: "npm:^2.29.4"