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
Support for multiple languages in push- and email notifications (#1436)
Martin Peeters856fbe362c28
diff --git a/manager/src/main/java/org/openremote/manager/notification/LocalizedNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/LocalizedNotificationHandler.javanew file mode 100644index 000000000..2828c4548--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/notification/LocalizedNotificationHandler.java@@ -0,0 +1,210 @@+/*+ * Copyright 2024, 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.notification;++import org.apache.camel.builder.RouteBuilder;+import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.security.ManagerIdentityService;+import org.openremote.model.Container;+import org.openremote.model.asset.UserAssetLink;+import org.openremote.model.notification.AbstractNotificationMessage;+import org.openremote.model.notification.LocalizedNotificationMessage;+import org.openremote.model.notification.Notification;+import org.openremote.model.security.User;+import org.openremote.model.util.TextUtil;++import static org.openremote.manager.notification.NotificationProcessingException.Reason.*;+import static org.openremote.model.security.User.LOCALE_ATTRIBUTE;++import java.util.*;+import java.util.logging.Logger;+import java.util.stream.Collectors;++/**+ * This {@link LocalizedNotificationHandler} handles notification differently compared to other handlers.+ * When a {@link LocalizedNotificationMessage} is processed, that normally contains a configuration for multiple languages,+ * we repeat the {@link #isMessageValid} and {@link #getTargets} methods for each individual locale. (using the {@link #notificationHandlerMap})+ */+public class LocalizedNotificationHandler extends RouteBuilder implements NotificationHandler {++ private static final Logger LOG = Logger.getLogger(LocalizedNotificationHandler.class.getName());+ private ManagerIdentityService identityService;+ private AssetStorageService assetStorageService;++ protected Map<String, NotificationHandler> notificationHandlerMap = new HashMap<>();+ protected boolean valid;++ @Override+ public void init(Container container) throws Exception {+ identityService = container.getService(ManagerIdentityService.class);+ assetStorageService = container.getService(AssetStorageService.class);+ container.getServices(NotificationHandler.class).forEach(notificationHandler -> {+ if (!notificationHandler.getTypeName().equals(this.getTypeName())) {+ notificationHandlerMap.put(notificationHandler.getTypeName(), notificationHandler);+ }+ });+ valid = true;+ }++ @Override+ public void start(Container container) throws Exception {++ }++ @Override+ public void stop(Container container) throws Exception {++ }++ @Override+ public void configure() throws Exception {++ }++ @Override+ public String getTypeName() {+ return LocalizedNotificationMessage.TYPE;+ }++ @Override+ public boolean isMessageValid(AbstractNotificationMessage message) {++ if (!(message instanceof LocalizedNotificationMessage localizedMessage)) {+ LOG.warning("Invalid message: '" + message.getClass().getSimpleName() + "' is not an instance of LocalizedNotificationMessage");+ return false;+ }++ if (localizedMessage.getMessages().isEmpty()) {+ LOG.warning("Invalid message: must either contain at least one localized message.");+ return false;+ }++ // For each language message, check its handler if the message is valid.+ return localizedMessage.getMessages().values().stream().allMatch(msg -> {+ if (notificationHandlerMap.containsKey(msg.getType())) {+ return notificationHandlerMap.get(msg.getType()).isMessageValid(msg);+ }+ return false;+ });+ }++ @Override+ public boolean isValid() {+ return this.valid;+ }+++ @Override+ public List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> requestedTargets, AbstractNotificationMessage message) {++ LocalizedNotificationMessage localizedMessage = (LocalizedNotificationMessage) message;++ try {+ // Make a list of targets for each language+ Map<String, List<Notification.Target>> targetsMap = localizedMessage.getMessages().entrySet().stream()+ .map(entry -> {++ // Check if handler exists for this message type+ if (!notificationHandlerMap.containsKey(entry.getValue().getType())) {+ return Map.entry(entry.getKey(), Collections.<Notification.Target>emptyList());+ }+ // Get valid targets for this language+ return Map.entry(entry.getKey(), notificationHandlerMap.get(entry.getValue().getType()).getTargets(source, sourceId, requestedTargets, entry.getValue()));++ })+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));++ // Merge these targets into a single List<Notification.Target>,+ // and add the list allowed language messages to the target using addAllowedLocales();+ Map<String, Notification.Target> mergedTargetsMap = new HashMap<>();+ targetsMap.forEach((language, targets) -> {+ for (Notification.Target target : targets) {+ mergedTargetsMap.computeIfAbsent(target.getId(), k -> target)+ .addAllowedLocales(new HashSet<>(Collections.singletonList(language)));+ }+ });+ return new ArrayList<>(mergedTargetsMap.values());+++ } catch (Exception e) {+ LOG.severe(e.getMessage());+ }++ return Collections.emptyList();+ }++ @Override+ public void sendMessage(long id, Notification.Source source, String sourceId, Notification.Target target, AbstractNotificationMessage message) throws Exception {++ if (!(message instanceof LocalizedNotificationMessage localizedMessage)) {+ throw new NotificationProcessingException(SEND_FAILURE, "Invalid message: '" + message.getClass().getSimpleName() + "' is not an instance of LocalizedNotificationMessage");+ }++ // If all locales are 'blocked' for this target, don't send any message+ if (target.getAllowedLocales() == null || target.getAllowedLocales().isEmpty()) {+ throw new NotificationProcessingException(SEND_FAILURE, "No localized message could not be sent to target " + target.getId());+ }++ String targetLocale = target.getLocale();+ if (TextUtil.isNullOrEmpty(targetLocale)) {++ // If locale of the target cannot be found, we try to get the user preferred language through the identity provider.+ // For ASSET targets, we have to query the linked user of the console asset.+ User user = null;+ if (target.getType().equals(Notification.TargetType.USER)) {+ user = identityService.getIdentityProvider().getUser(target.getId());+ }+ else if (target.getType().equals(Notification.TargetType.ASSET)) {+ List<UserAssetLink> links = assetStorageService.findUserAssetLinks(null, null, target.getId());+ if (!links.isEmpty()) {+ user = identityService.getIdentityProvider().getUser(links.get(0).getId().getUserId());+ }+ }++ // If user has configured their locale (through the user attribute), update the targetLocale+ if (user != null && user.getAttributeMap() != null && user.getAttributeMap().containsKey(LOCALE_ATTRIBUTE)) {+ targetLocale = user.getAttributeMap().get(LOCALE_ATTRIBUTE).get(0);+ }++ }+ // If target locale is not set yet, or there is no message available for that locale,+ // use the default language configured in the notification message+ if (TextUtil.isNullOrEmpty(targetLocale) || !localizedMessage.getMessages().containsKey(targetLocale)) {+ targetLocale = localizedMessage.getDefaultLanguage();+ }++ // Check if the message configured for this language is allowed to be sent towards this target.+ if (!target.getAllowedLocales().contains(targetLocale)) {+ throw new NotificationProcessingException(SEND_FAILURE, "The localized message could not be sent to target '" + target.getId() + "' (" + targetLocale + "), because only " + target.getAllowedLocales() + " were allowed.");+ }++ AbstractNotificationMessage targetMsg = localizedMessage.getMessage(targetLocale);+ if (targetMsg == null) {+ throw new NotificationProcessingException(SEND_FAILURE, "Could not get message for the '" + targetLocale + "' language of target " + target.getId());+ }++ if (!notificationHandlerMap.containsKey(targetMsg.getType())) {+ throw new NotificationProcessingException(SEND_FAILURE, "Could not find the handler of type '" + targetMsg.getType() + "' for the message of target " + target.getId());+ }++ // Send message+ notificationHandlerMap.get(targetMsg.getType()).sendMessage(id, source, sourceId, target, targetMsg);+ }+}diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex 5167a0020..d9f9d9821 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -30,9 +30,7 @@ import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeInfo;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.geo.GeoJSONPoint;-import org.openremote.model.notification.EmailNotificationMessage;-import org.openremote.model.notification.Notification;-import org.openremote.model.notification.PushNotificationMessage;+import org.openremote.model.notification.*;import org.openremote.model.query.AssetQuery;import org.openremote.model.query.LogicGroup;import org.openremote.model.query.UserQuery;@@ -556,7 +554,7 @@ public class JsonRulesBuilder extends RulesBuilder {protected static Logger LOG;public JsonRulesBuilder(Logger logger, Ruleset ruleset, RulesEngine<?> rulesEngine, TimerService timerService, AssetStorageService assetStorageService,- Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade,+ Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade,Alarms alarmsFacade, HistoricDatapoints historicDatapoints, PredictedDatapoints predictedDatapoints,BiConsumer<Runnable, Long> scheduledActionConsumer) throws Exception {this.rulesEngine = rulesEngine;@@ -567,7 +565,7 @@ public class JsonRulesBuilder extends RulesBuilder {this.notificationsFacade = notificationsFacade;this.webhooksFacade = webhooksFacade;this.alarmsFacade = alarmsFacade;- this.historicDatapointsFacade= historicDatapoints;+ this.historicDatapointsFacade = historicDatapoints;this.predictedDatapointsFacade = predictedDatapoints;this.scheduledActionConsumer = scheduledActionConsumer;LOG = logger;@@ -788,6 +786,7 @@ public class JsonRulesBuilder extends RulesBuilder {Notification notification = ValueUtil.clone(notificationAction.notification);String body;boolean linkedUsersTarget = ruleAction.target != null && Boolean.TRUE.equals(ruleAction.target.linkedUsers);+ boolean isLocalized = Objects.equals(notification.getMessage().getType(), LocalizedNotificationMessage.TYPE);boolean isEmail = Objects.equals(notification.getMessage().getType(), EmailNotificationMessage.TYPE);boolean isPush = Objects.equals(notification.getMessage().getType(), PushNotificationMessage.TYPE);boolean isHtml;@@ -823,9 +822,35 @@ public class JsonRulesBuilder extends RulesBuilder {}Collection<String> targetIds;- boolean bodyContainsTriggeredAssetInfo = !TextUtil.isNullOrEmpty(body) && body.contains(PLACEHOLDER_TRIGGER_ASSETS);+ boolean bodyContainsTriggeredAssetInfo;++ // In case of a localized message, we build a Map of all bodies in each language.+ // We also cache a list of languages that are using HTML, to use later+ Map<String, String> localizedBodies = new HashMap<>();+ Map<String, Boolean> localizedIsHtml = new HashMap<>();+ if(isLocalized) {+ ((LocalizedNotificationMessage) notification.getMessage()).getMessages().forEach((lang, msg) -> {+ if (msg instanceof PushNotificationMessage pushMsg) {+ localizedBodies.put(lang, pushMsg.getBody());+ localizedIsHtml.put(lang, false);+ } else if (msg instanceof EmailNotificationMessage emailMsg) {+ boolean isMsgHtml = !TextUtil.isNullOrEmpty(emailMsg.getHtml());+ localizedBodies.put(lang, isMsgHtml ? emailMsg.getHtml() : emailMsg.getText());+ localizedIsHtml.put(lang, true);+ }+ });+ }++ // Check if the body containers the PLACEHOLDER_TRIGGER_ASSETS+ if(isLocalized) {+ bodyContainsTriggeredAssetInfo = localizedBodies.values().stream().anyMatch(+ text -> !TextUtil.isNullOrEmpty(text) && text.contains(PLACEHOLDER_TRIGGER_ASSETS));+ } else {+ bodyContainsTriggeredAssetInfo = !TextUtil.isNullOrEmpty(body) && body.contains(PLACEHOLDER_TRIGGER_ASSETS);+ }if (linkedUsersTarget) {+// Find users linked to the matched assets applying any additional use query in the actionSet<String> assetIds = useUnmatched ? ruleState.otherwiseMatchedAssetIds : ruleState.thenMatchedAssetIds;UserQuery userQuery = ruleAction.target.users != null ? ruleAction.target.users : new UserQuery();@@ -857,18 +882,18 @@ public class JsonRulesBuilder extends RulesBuilder {Map<String, Set<AttributeInfo>> assetStates = getMatchedAssetStates(ruleState, useUnmatched, userAssetLinks, userId);Notification customNotification = ValueUtil.clone(notification);- String newBody = insertTriggeredAssetInfo(finalBody, assetStates, isHtml, false);-- if (isEmail) {- EmailNotificationMessage email = (EmailNotificationMessage) customNotification.getMessage();- if (isHtml) {- email.setHtml(newBody);- } else {- email.setText(newBody);- }- } else if (isPush) {- PushNotificationMessage pushNotificationMessage = (PushNotificationMessage) customNotification.getMessage();- pushNotificationMessage.setBody(newBody);+++ if(isLocalized) {+ LocalizedNotificationMessage localizedMsg = ((LocalizedNotificationMessage) customNotification.getMessage());+ localizedMsg.getMessages().forEach((lang, msg) -> {+ String newBody = insertTriggeredAssetInfo(localizedBodies.get(lang), assetStates, localizedIsHtml.get(lang), false);+ localizedMsg.setMessage(lang, insertBodyInMessage(msg, localizedIsHtml.get(lang), newBody));+ });++ } else {+ String newBody = insertTriggeredAssetInfo(finalBody, assetStates, isHtml, false);+ customNotification.setMessage(insertBodyInMessage(customNotification.getMessage(), isHtml, newBody));}customNotification.setTargets(new Notification.Target(Notification.TargetType.USER, userId));@@ -896,18 +921,17 @@ public class JsonRulesBuilder extends RulesBuilder {if (bodyContainsTriggeredAssetInfo) {// Extract asset states for matched asset IDsMap<String, Set<AttributeInfo>> assetStates = getMatchedAssetStates(ruleState, useUnmatched, null, null);- body = insertTriggeredAssetInfo(body, assetStates, isHtml, false);- if (isEmail) {- EmailNotificationMessage email = (EmailNotificationMessage) notification.getMessage();- if (isHtml) {- email.setHtml(body);- } else {- email.setText(body);- }- } else if (isPush) {- PushNotificationMessage pushNotificationMessage = (PushNotificationMessage) notification.getMessage();- pushNotificationMessage.setBody(body);+ if(isLocalized) {+ LocalizedNotificationMessage localizedMsg = ((LocalizedNotificationMessage) notification.getMessage());+ localizedMsg.getMessages().forEach((lang, msg) -> {+ String newBody = insertTriggeredAssetInfo(localizedBodies.get(lang), assetStates, localizedIsHtml.get(lang), false);+ localizedMsg.setMessage(lang, insertBodyInMessage(msg, localizedIsHtml.get(lang), newBody));+ });++ } else {+ String newBody = insertTriggeredAssetInfo(body, assetStates, isHtml, false);+ notification.setMessage(insertBodyInMessage(notification.getMessage(), isHtml, newBody));}}@@ -1217,6 +1241,19 @@ public class JsonRulesBuilder extends RulesBuilder {return sourceText.replace(PLACEHOLDER_TRIGGER_ASSETS, sb.toString());}+ protected AbstractNotificationMessage insertBodyInMessage(AbstractNotificationMessage sourceMessage, boolean isHtml, String body) {+ if(sourceMessage instanceof EmailNotificationMessage emailMsg) {+ if (isHtml) {+ emailMsg.setHtml(body);+ } else {+ emailMsg.setText(body);+ }+ } else if(sourceMessage instanceof PushNotificationMessage pushMsg) {+ pushMsg.setBody(body);+ }+ return sourceMessage;+ }+protected static Collection<String> getRuleActionTargetIds(RuleActionTarget target, boolean useUnmatched, RuleState ruleState, Assets assetsFacade, Users usersFacade, RulesFacts facts) {Map<String, RuleConditionState> conditionStateMap = ruleState.conditionStateMap;diff --git a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.javaindex d5b3b6f88..f1c93de9f 100644--- a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java@@ -19,6 +19,7 @@*/package org.openremote.manager.security;+import com.fasterxml.jackson.databind.JsonNode;import org.openremote.container.security.AuthContext;import org.openremote.container.security.keycloak.KeycloakIdentityProvider;import org.openremote.container.timer.TimerService;@@ -32,11 +33,10 @@ import org.openremote.model.query.filter.StringPredicate;import org.openremote.model.security.*;import jakarta.ws.rs.*;+import org.openremote.model.util.TextUtil;+import org.openremote.model.util.ValueUtil;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.List;-import java.util.Objects;+import java.util.*;import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;import static org.openremote.model.Constants.MASTER_REALM;@@ -336,6 +336,22 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource}}+ @Override+ public void updateCurrentUserLocale(RequestParams requestParams, String locale) {+ String parsed = locale.replaceAll("\"", "");+ if(TextUtil.isNullOrEmpty(parsed)) {+ throw new BadRequestException("Locale cannot be empty");+ }++ User user = getCurrent(requestParams);+ if(user == null) {+ throw new NotFoundException("User not found");+ }++ user.setAttribute(User.LOCALE_ATTRIBUTE, parsed);+ update(requestParams, getRequestRealmName(), user);+ }+@Overridepublic UserSession[] getUserSessions(RequestParams requestParams, String realm, String userId) {boolean hasAdminReadRole = hasResourceRole(ClientRole.READ_ADMIN.getValue(), Constants.KEYCLOAK_CLIENT_ID);diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerServiceindex 6c09fd7bd..b877ede2e 100644--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService@@ -20,6 +20,7 @@ org.openremote.manager.apps.ConsoleAppServiceorg.openremote.manager.web.ManagerWebServiceorg.openremote.manager.notification.PushNotificationHandlerorg.openremote.manager.notification.EmailNotificationHandler+org.openremote.manager.notification.LocalizedNotificationHandlerorg.openremote.manager.datapoint.AssetPredictedDatapointServiceorg.openremote.manager.gateway.GatewayServiceorg.openremote.manager.gateway.GatewayClientServicediff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex 45694a37a..cec82788f 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -280,6 +280,8 @@"openInBrowser": "Open in browser (for external websites)","buttonTextConfirm": "Text for action button","buttonTextDecline": "Text for decline button",+ "defaultLanguageChangedError": "Update default language",+ "languagesInvalidError": "Incomplete language forms: ","custom": "Custom attribute","realm": "Realm","realm_plural": "Realms",@@ -746,6 +748,9 @@"navigationDescription": "Primary navigation is shown in the page header, secondary items can be found in the menu on the right.","primaryNavigation" : "Primary menu","secondaryNavigation" : "Secondary menu",+ "notificationLanguages": "Notification languages",+ "notificationLanguagesDesc": "Languages set here can be used in notifications to be sent to users with locale attribute set.",+ "notificationLanguagesLabel": "Search other languages...","reloadPage" : "To see the changes that have been made, reload the page","deleteRealmCustomization": "Delete Style","deleteRealmCustomizationConfirm":"Are you sure you want to delete this Realm style?",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex d585a09eb..9b4630395 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -280,6 +280,8 @@"openInBrowser": "Openen in browser (voor externe websites)","buttonTextConfirm": "Tekst voor actie knop","buttonTextDecline": "Tekst voor negeerknop",+ "defaultLanguageChangedError": "Standaardtaal updaten",+ "languagesInvalidError": "Onvolledige talen: ","custom": "Nieuw attribuut","realm": "Realm","realm_plural": "Realms",@@ -742,6 +744,9 @@"--or-app-color8": "Tekst op primair: tekst op onderdelen met de primaire kleur","navigation" : "Navigatie","navigationDescription": "De primaire navigatie staat in de header, secundaire items kun je in het menu rechtsboven vinden.",+ "notificationLanguages": "Notificatie talen",+ "notificationLanguagesDesc": "Talen die hier ingesteld zijn kunnen gebruikt worden in notificaties voor gebruikers die hun taal hebben ingesteld.",+ "notificationLanguagesLabel": "Zoek naar andere talen...","primaryNavigation" : "Primair menu","secondaryNavigation" : "Secundair menu","reloadPage" : "Om de wijzigingen te zien die gemaakt zijn, herlaad de pagina",diff --git a/model/src/main/java/org/openremote/model/manager/ManagerAppRealmConfig.java b/model/src/main/java/org/openremote/model/manager/ManagerAppRealmConfig.javaindex c4cdfa5ce..dcaad61ea 100644--- a/model/src/main/java/org/openremote/model/manager/ManagerAppRealmConfig.java+++ b/model/src/main/java/org/openremote/model/manager/ManagerAppRealmConfig.java@@ -1,5 +1,5 @@/*- * Copyright 2022, OpenRemote Inc.+ * Copyright 2024, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -20,11 +20,12 @@package org.openremote.model.manager;public class ManagerAppRealmConfig {- protected String appTitle = null;- protected String styles = null;- protected String logo = null;- protected String logoMobile = null;- protected String favicon = null;- protected String language = null;- protected String[] headers = null;+ protected String appTitle;+ protected String styles;+ protected String logo;+ protected String logoMobile;+ protected String favicon;+ protected String language;+ protected String[] headers;+ protected ManagerAppRealmNotificationConfig notifications;}diff --git a/model/src/main/java/org/openremote/model/manager/ManagerAppRealmNotificationConfig.java b/model/src/main/java/org/openremote/model/manager/ManagerAppRealmNotificationConfig.javanew file mode 100644index 000000000..1516ab230--- /dev/null+++ b/model/src/main/java/org/openremote/model/manager/ManagerAppRealmNotificationConfig.java@@ -0,0 +1,25 @@+/*+ * Copyright 2024, 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.manager;++public class ManagerAppRealmNotificationConfig {+ protected String[] languages;+ protected String defaultLanguage;+}diff --git a/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.javaindex fe070050b..68c995bf1 100644--- a/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.java+++ b/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.java@@ -24,7 +24,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;@JsonSubTypes({@JsonSubTypes.Type(value = PushNotificationMessage.class, name = PushNotificationMessage.TYPE),- @JsonSubTypes.Type(value = EmailNotificationMessage.class, name = EmailNotificationMessage.TYPE)+ @JsonSubTypes.Type(value = EmailNotificationMessage.class, name = EmailNotificationMessage.TYPE),+ @JsonSubTypes.Type(value = LocalizedNotificationMessage.class, name = LocalizedNotificationMessage.TYPE)})@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,diff --git a/model/src/main/java/org/openremote/model/notification/LocalizedNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/LocalizedNotificationMessage.javanew file mode 100644index 000000000..159f2a8f9--- /dev/null+++ b/model/src/main/java/org/openremote/model/notification/LocalizedNotificationMessage.java@@ -0,0 +1,67 @@+/*+ * Copyright 2024, 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 com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;++import java.util.Map;+import java.util.Optional;++public class LocalizedNotificationMessage extends AbstractNotificationMessage {++ public static final String TYPE = "localized";++ protected String defaultLanguage;+ protected Map<String, AbstractNotificationMessage> languages;++ @JsonCreator+ public LocalizedNotificationMessage(@JsonProperty("defaultLanguage") String defaultLanguage,+ @JsonProperty("languages") Map<String, AbstractNotificationMessage> languages) {+ super(TYPE);+ this.defaultLanguage = defaultLanguage;+ this.languages = languages;+ }++ public LocalizedNotificationMessage() {+ super(TYPE);+ }++ public String getDefaultLanguage() {+ return defaultLanguage;+ }++ public LocalizedNotificationMessage setDefaultLanguage(String defaultLanguage) {+ this.defaultLanguage = defaultLanguage;+ return this;+ }++ public AbstractNotificationMessage getMessage(String language) {+ return Optional.ofNullable(languages.get(language)).orElse(languages.get(defaultLanguage));+ }++ public Map<String, AbstractNotificationMessage> getMessages() {+ return languages;+ }++ public void setMessage(String language, AbstractNotificationMessage message) {+ languages.put(language, message);+ }+}diff --git a/model/src/main/java/org/openremote/model/notification/Notification.java b/model/src/main/java/org/openremote/model/notification/Notification.javaindex 887d38b42..56c9a156f 100644--- a/model/src/main/java/org/openremote/model/notification/Notification.java+++ b/model/src/main/java/org/openremote/model/notification/Notification.java@@ -22,8 +22,7 @@ package org.openremote.model.notification;import com.fasterxml.jackson.annotation.JsonCreator;import com.fasterxml.jackson.annotation.JsonProperty;-import java.util.Arrays;-import java.util.List;+import java.util.*;public class Notification {@@ -46,6 +45,8 @@ public class Notification {protected TargetType type;protected String id;+ protected String locale;+ protected Set<String> allowedLocales = new HashSet<>();protected Object data; // Handlers can store temporary data here@JsonCreator@@ -54,6 +55,16 @@ public class Notification {this.id = id;}+ /**+ * Manual constructor for the Target class+ * @param locale ISO 639-1 code; for example "nl" or "en"+ */+ public Target(TargetType type, String id, String locale) {+ this.type = type;+ this.id = id;+ this.locale = locale;+ }+public TargetType getType() {return type;}@@ -66,6 +77,33 @@ public class Notification {return id;}+ public void setLocale(String locale) {+ this.locale = locale;+ }++ public String getLocale() {+ return locale;+ }++ public Target setAllowedLocales(Set<String> allowedLocales) {+ this.allowedLocales = allowedLocales;+ return this;+ }++ public Target addAllowedLocale(String locale) {+ this.allowedLocales.add(locale);+ return this;+ }++ public Target addAllowedLocales(Set<String> allowedLocales) {+ this.allowedLocales.addAll(allowedLocales);+ return this;+ }++ public Set<String> getAllowedLocales() {+ return allowedLocales;+ }+public Target setData(Object data) {this.data = data;return this;diff --git a/model/src/main/java/org/openremote/model/security/User.java b/model/src/main/java/org/openremote/model/security/User.javaindex b0033b79a..cf253af92 100644--- a/model/src/main/java/org/openremote/model/security/User.java+++ b/model/src/main/java/org/openremote/model/security/User.java@@ -49,6 +49,7 @@ public class User {public static final String SYSTEM_ACCOUNT_ATTRIBUTE = "systemAccount";public static final String EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE = "emailNotificationsDisabled";public static final String PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE = "pushNotificationsDisabled";+ public static final String LOCALE_ATTRIBUTE = "locale";protected static Field[] propertyFields;@Formula("(select r.NAME from PUBLIC.REALM r where r.ID = REALM_ID)")diff --git a/model/src/main/java/org/openremote/model/security/UserResource.java b/model/src/main/java/org/openremote/model/security/UserResource.javaindex 81981cf9a..312843a5e 100644--- a/model/src/main/java/org/openremote/model/security/UserResource.java+++ b/model/src/main/java/org/openremote/model/security/UserResource.java@@ -19,6 +19,7 @@*/package org.openremote.model.security;+import com.fasterxml.jackson.databind.JsonNode;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import org.openremote.model.Constants;@@ -182,6 +183,12 @@ public interface UserResource {@Operation(operationId = "updateUserRealmRoles", summary = "Update realm roles for a user in a realm")void updateUserRealmRoles(@BeanParam RequestParams requestParams, @PathParam("realm") String realm, @PathParam("userId") String userId, Role[] roles);+ @PUT+ @Path("locale")+ @Consumes(APPLICATION_JSON)+ @Operation(operationId = "updateCurrentUserLocale", summary = "Update locale for the current user in a realm")+ void updateCurrentUserLocale(@BeanParam RequestParams requestParams, String locale);+@GET@Path("{realm}/userSessions/{userId}")@Produces(APPLICATION_JSON)diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovyindex 32cb7eea5..15a8aae9f 100644--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy@@ -4,11 +4,13 @@ package org.openremote.test.notificationimport com.fasterxml.jackson.databind.node.TextNodeimport jakarta.mail.Messageimport jakarta.mail.internet.InternetAddress+import jakarta.ws.rs.BadRequestExceptionimport jakarta.ws.rs.WebApplicationExceptionimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.asset.console.ConsoleResourceImplimport org.openremote.manager.notification.EmailNotificationHandler+import org.openremote.manager.notification.LocalizedNotificationHandlerimport org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandlerimport org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter@@ -23,6 +25,7 @@ import org.openremote.model.console.ConsoleResourceimport org.openremote.model.notification.*import org.openremote.model.query.UserQueryimport org.openremote.model.query.filter.RealmPredicate+import org.openremote.model.security.Userimport org.openremote.model.util.TextUtilimport org.openremote.setup.integration.KeycloakTestSetupimport org.openremote.setup.integration.ManagerTestSetup@@ -674,4 +677,366 @@ class NotificationTest extends Specification implements ManagerContainerTrait {cleanup: "the mock is removed"notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), emailNotificationHandler)}++ def "Check localized notification functionality"() {++ List<String> localizedNotificationIds = []+ List<Notification.TargetType> localizedNotificationTargetTypes = []+ List<String> localizedNotificationTargetIds = []+ List<AbstractNotificationMessage> localizedNotificationMessages = []++ List<String> pushNotificationIds = []+ List<Notification.TargetType> pushNotificationTargetTypes = []+ List<String> pushNotificationTargetIds = []+ List<AbstractNotificationMessage> pushNotificationMessages = []++ given: "the container environment is started with the mock handler"+ def conditions = new PollingConditions(timeout: 10, initialDelay: 0.1, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())+ def identityService = container.getService(ManagerIdentityService.class)+ def notificationService = container.getService(NotificationService.class)+ def pushNotificationHandler = container.getService(PushNotificationHandler.class)+ def localizedNotificationHandler = container.getService(LocalizedNotificationHandler.class)++ /* ----- */++ and: "a mock push notification handler"+ def throwPushHandlerException = false+ PushNotificationHandler mockPushNotificationHandler = Spy(pushNotificationHandler)+ mockPushNotificationHandler.isValid() >> true++ // Intercept the messages sent+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ if (throwPushHandlerException) {+ throw new Exception("Failed to send notification")+ }+ pushNotificationIds << id+ pushNotificationTargetTypes << target.type+ pushNotificationTargetIds << target.id+ pushNotificationMessages << message+ callRealMethod()+ }+ // Auto accept the messages sent to Firebase (without calling its logic)+ mockPushNotificationHandler.sendMessage(_ as com.google.firebase.messaging.Message) >> {+ message -> return NotificationSendResult.success()+ }++ notificationService.notificationHandlerMap.put(mockPushNotificationHandler.getTypeName(), mockPushNotificationHandler)++ /* ----- */++ and: "a mock localized notification handler"+ def throwLocalizedHandlerException = false+ LocalizedNotificationHandler mockLocalizedNotificationHandler = Spy(localizedNotificationHandler)+ mockLocalizedNotificationHandler.isValid() >> true++ // Intercept the messages sent+ mockLocalizedNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ if (throwLocalizedHandlerException) {+ throw new Exception("Failed to send notification")+ }+ localizedNotificationIds << id+ localizedNotificationTargetTypes << target.type+ localizedNotificationTargetIds << target.id+ localizedNotificationMessages << message+ callRealMethod()+ }+ // the notificationHandlerMap in the localized handler, should also use the same mock handlers+ mockLocalizedNotificationHandler.notificationHandlerMap = notificationService.notificationHandlerMap++ notificationService.notificationHandlerMap.put(localizedNotificationHandler.getTypeName(), mockLocalizedNotificationHandler)++ /* ----- */++ and: "an authenticated superuser"+ def adminAccessToken = authenticate(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)+ ).token++ def notification = new Notification(+ "MultiLanguageAction",+ new LocalizedNotificationMessage(+ "en",+ new HashMap<String, AbstractNotificationMessage>() {{+ put("nl", new PushNotificationMessage("Nederlandse titel", "Nederlandse body", null, null, null))+ put("en", new PushNotificationMessage("English title", "English body", null, null, null))+ }}+ ),+ null,+ null,+ null)++ and: "the admin notification resource"+ def adminNotificationResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(NotificationResource.class)+ def adminConsoleResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(ConsoleResource.class)++ when: "the admin console is registered"+ def consoleRegistration = new ConsoleRegistration(null,+ "Admin Console",+ "1.0",+ "Android 7.0",+ new HashMap<String, ConsoleProvider>() {+ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ false,+ false,+ null+ ))+ put("push", new ConsoleProvider(+ "fcm",+ true,+ true,+ true,+ true,+ false,+ (Map) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)+ ))+ }+ },+ "",+ ["manager"] as String[])+ def adminConsole = adminConsoleResource.register(null, consoleRegistration)++ then: "the admin console should have been created"+ adminConsole.id != null++ when: "the admin user sends a push notification to the entire MASTER realm (which is only himself)"+ notification.targets = [new Notification.Target(Notification.TargetType.REALM, MASTER_REALM)]+ adminNotificationResource.sendNotification(null, notification)++ then: "all consoles in that realm should have been sent a notification"+ conditions.eventually {+ assert localizedNotificationIds.size() == 1+ assert localizedNotificationTargetIds.size() == 1+ assert localizedNotificationTargetIds.contains(adminConsole.id)+ assert pushNotificationIds.size() == 1+ assert pushNotificationTargetIds.size() == 1+ assert pushNotificationTargetIds.contains(adminConsole.id)+ assert pushNotificationMessages.size() == 1+ assert pushNotificationMessages.get(0).type == "push"+ assert ((PushNotificationMessage)pushNotificationMessages.get(0)).title == "English title"+ assert ((PushNotificationMessage)pushNotificationMessages.get(0)).body == "English body"+ }++ and: "we clear the cached notifications"+ localizedNotificationIds.clear()+ localizedNotificationTargetTypes.clear()+ localizedNotificationTargetIds.clear()+ localizedNotificationMessages.clear()+ pushNotificationIds.clear()+ pushNotificationTargetTypes.clear()+ pushNotificationTargetIds.clear()+ pushNotificationMessages.clear()++ /* ------------ */++ when: "a new user gets added"+ def testuser1AccessToken = authenticate(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ "testuser1",+ "testuser1"+ ).token++ and: "their language is updated to dutch"+ def testuser1 = identityService.getIdentityProvider().getUserByUsername(MASTER_REALM, "testuser1")+ testuser1.setAttribute(User.LOCALE_ATTRIBUTE, "nl")+ identityService.getIdentityProvider().createUpdateUser(MASTER_REALM, testuser1, null, true)++ and: "the console of the dutch user is registered"+ def testuser1ConsoleResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, testuser1AccessToken).proxy(ConsoleResource.class)+ def testuser1ConsoleRegistration = new ConsoleRegistration(null,+ "Test user 1 Console",+ "1.0",+ "Android 7.0",+ new HashMap<String, ConsoleProvider>() {+ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ false,+ false,+ null+ ))+ put("push", new ConsoleProvider(+ "fcm",+ true,+ true,+ true,+ true,+ false,+ (Map) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)+ ))+ }+ },+ "",+ ["manager"] as String[])+ def testuser1Console = testuser1ConsoleResource.register(null, testuser1ConsoleRegistration)++ and: "the console is created"+ testuser1Console.id != null++ and: "the same notification is sent, now to both users"+ adminNotificationResource.sendNotification(null, notification)++ then: "both consoles in that realm should have been sent a notification"+ conditions.eventually {+ assert localizedNotificationIds.size() == 2+ assert localizedNotificationTargetIds.size() == 2+ assert pushNotificationIds.size() == 2+ assert pushNotificationTargetIds.size() == 2+ }++ and: "we clear the cached notifications again"+ localizedNotificationIds.clear()+ localizedNotificationTargetTypes.clear()+ localizedNotificationTargetIds.clear()+ localizedNotificationMessages.clear()+ pushNotificationIds.clear()+ pushNotificationTargetTypes.clear()+ pushNotificationTargetIds.clear()+ pushNotificationMessages.clear()++ /* ------------ */++ when: "testuser1 their language is updated to an unknown language, like italian"+ testuser1.setAttribute(User.LOCALE_ATTRIBUTE, "it")+ identityService.getIdentityProvider().createUpdateUser(MASTER_REALM, testuser1, null, true)++ and: "the same notification is sent again, to both users"+ adminNotificationResource.sendNotification(null, notification)++ then: "testuser1 should still receive the notification, but in the default language"+ conditions.eventually {+ assert localizedNotificationMessages.size() == 2+ assert pushNotificationMessages.size() == 2+ assert pushNotificationMessages.stream().allMatch { msg -> (msg as PushNotificationMessage).title == "English title" && (msg as PushNotificationMessage).body == "English body" }+ }++ and: "we clear the cached notifications again"+ localizedNotificationIds.clear()+ localizedNotificationTargetTypes.clear()+ localizedNotificationTargetIds.clear()+ localizedNotificationMessages.clear()+ pushNotificationIds.clear()+ pushNotificationTargetTypes.clear()+ pushNotificationTargetIds.clear()+ pushNotificationMessages.clear()++ and: "testuser1 sets their language back to dutch"+ testuser1.setAttribute(User.LOCALE_ATTRIBUTE, "nl")+ identityService.getIdentityProvider().createUpdateUser(MASTER_REALM, testuser1, null, true)++ /* ----------- */++ when: "a complex notification with different types per language is set up"+ def complexNotification = new Notification(+ "MultiTypeAction",+ new LocalizedNotificationMessage(+ "en",+ new HashMap<String, AbstractNotificationMessage>() {{+ put("en", new PushNotificationMessage("English title", "English body", null, null, null))+ put("nl", new EmailNotificationMessage().setSubject("Nederlandse titel").setText("Nederlandse tekst"))+ }}+ ),+ null,+ null,+ null)++ complexNotification.targets = [new Notification.Target(Notification.TargetType.REALM, MASTER_REALM)]++ and: "the mock email notification handler has been added"+ List<Message> sentEmails = []+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)+ EmailNotificationHandler mockEmailNotificationHandler = Spy(emailNotificationHandler)+ mockEmailNotificationHandler.isValid() >> true++ // Log email and assume sent to SMTP Server+ mockEmailNotificationHandler.sendMessage(_ as Message) >> {+ Message email ->+ sentEmails << email+ return NotificationSendResult.success()+ }++ // Add email handler to the list of handlers+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockEmailNotificationHandler)+ mockLocalizedNotificationHandler.notificationHandlerMap = notificationService.notificationHandlerMap++ and: "testuser1 configures their email address"+ testuser1.setEmail("[email protected]")+ identityService.getIdentityProvider().createUpdateUser(MASTER_REALM, testuser1, null, true)++ and: "the complex notification is sent"+ adminNotificationResource.sendNotification(null, complexNotification)++ then: "it should return a BAD_REQUEST because testuser1 only gets one notification"+ thrown(BadRequestException)++ and: "the other notifications should be sent correctly through email and with push"+ conditions.eventually {+ assert localizedNotificationMessages.size() == 3+ assert localizedNotificationTargetIds.size() == 3+ assert pushNotificationMessages.size() == 1+ assert sentEmails.size() == 1+ }++ and: "we clear the cached notifications once again"+ localizedNotificationIds.clear()+ localizedNotificationTargetTypes.clear()+ localizedNotificationTargetIds.clear()+ localizedNotificationMessages.clear()+ pushNotificationIds.clear()+ pushNotificationTargetTypes.clear()+ pushNotificationTargetIds.clear()+ pushNotificationMessages.clear()+++ /* ------------ */++ when: "an invalid notification is created"+ def invalidNotification = new Notification(+ "InvalidNotification",+ new LocalizedNotificationMessage(+ "en",+ new HashMap<String, AbstractNotificationMessage>() {{+ put("nl", new PushNotificationMessage())+ put("en", new PushNotificationMessage("English title", "English body", null, null, null))+ }}+ ),+ null,+ null,+ null)++ and: "the invalid notification is sent to all users"+ adminNotificationResource.sendNotification(null, invalidNotification)++ then: "it should return a BAD_REQUEST, because the message is invalid"+ thrown(BadRequestException)++ and: "all users should receive the english message"+ conditions.eventually {+ assert localizedNotificationMessages.size() == 0+ assert localizedNotificationTargetIds.size() == 0+ assert pushNotificationMessages.size() == 0+ }+++ /* ------------------------ */++ /*when: "if the notification became valid, and the TRIGGER_ASSETS placeholder is inserted"+ ((LocalizedNotificationMessage) invalidNotification.getMessage()).setMessage("nl", new PushNotificationMessage())*/+ }}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovyindex 7b1630e74..cf727cbb2 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy@@ -10,6 +10,9 @@ import jakarta.ws.rs.core.Responseimport net.fortuna.ical4j.model.Recurimport org.openremote.container.timer.TimerServiceimport org.openremote.container.util.MailUtil+import org.openremote.manager.notification.LocalizedNotificationHandler+import org.openremote.model.notification.EmailNotificationMessage+import org.openremote.model.notification.LocalizedNotificationMessageimport org.openremote.model.util.UniqueIdentifierGeneratorimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService@@ -111,6 +114,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {List<Tuple2<Notification.Target, PushNotificationMessage>> pushTargetsAndMessages = []List<jakarta.mail.Message> emailMessages = []List<Notification.Target> emailTargets = []+ List<LocalizedNotificationMessage> localizedMessages = []given: "the geofence notifier debounce is set to a small value for testing"Integer originalDebounceMillis = ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS@@ -121,6 +125,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {def container = startContainer(defaultConfig(), defaultServices())def pushNotificationHandler = container.getService(PushNotificationHandler.class)def emailNotificationHandler = container.getService(EmailNotificationHandler.class)+ def localizedNotificationHandler = container.getService(LocalizedNotificationHandler.class)def notificationService = container.getService(NotificationService.class)def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)@@ -162,6 +167,16 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockEmailNotificationHandler)+ // Register localized handler+ LocalizedNotificationHandler mockLocalizedNotificationHandler = Spy(localizedNotificationHandler)+ mockLocalizedNotificationHandler.isValid() >> true+ mockLocalizedNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ localizedMessages << message+ }+ mockLocalizedNotificationHandler.notificationHandlerMap = notificationService.notificationHandlerMap+ notificationService.notificationHandlerMap.put(localizedNotificationHandler.getTypeName(), mockLocalizedNotificationHandler)+and: "some rules"Ruleset ruleset = new RealmRuleset(keycloakTestSetup.realmBuilding.name,@@ -366,6 +381,27 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {&& MailUtil.toMailMessage(it, true).content == "<table cellpadding=\"30\"><tr><th>Asset ID</th><th>Asset Name</th><th>Attribute</th><th>Value</th></tr><tr><td>${consoleRegistration.id}</td><td>Test Console</td><td>location</td><td>" + ValueUtil.asJSON(outsideLocation).orElse("") + "</td></tr></table>"}}+ and: "an localized email notification should have been sent with the triggered asset in the body but only containing the triggered asset states"+ String expectedHtml = "<table cellpadding=\"30\"><tr><th>Asset ID</th><th>Asset Name</th><th>Attribute</th><th>Value</th></tr><tr><td>${consoleRegistration.id}</td><td>Test Console</td><td>location</td><td>" + ValueUtil.asJSON(outsideLocation).orElse("") + "</td></tr></table>"+ conditions.eventually {+ assert localizedMessages.size() == 5+ assert localizedMessages.stream().allMatch {+ it.getMessages().values().stream().allMatch(m -> {+ m.type == EmailNotificationMessage.TYPE && ((EmailNotificationMessage) m).getHtml() == expectedHtml+ })+ }+ assert localizedMessages.stream().filter {+ it.getMessages().values().stream().allMatch {+ ((EmailNotificationMessage) it).getSubject() == "Demo Apartment - All Lights Off"+ }+ }.count() == 3+ assert localizedMessages.stream().filter {+ it.getMessages().values().stream().allMatch {+ ((EmailNotificationMessage) it).getSubject() == "Linked user localized user test"+ }+ }.count() == 2+ }+and: "after a few seconds the rule should not have fired again"new PollingConditions(timeout: 5, initialDelay: 1).eventually {assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 1diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.jsonindex 39c0399ca..9a5de0280 100644--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json@@ -146,6 +146,47 @@}}},+ {+ "action": "notification",+ "notification": {+ "message": {+ "type": "localized",+ "defaultLanguage": "en",+ "languages": {+ "en": {+ "type": "email",+ "subject": "%RULESET_NAME%",+ "html": "%TRIGGER_ASSETS%",+ "to": [+ {+ "address": "[email protected]",+ "name": "OR localized test"+ }+ ]+ }+ }+ }+ }+ },+ {+ "action": "notification",+ "target": {+ "linkedUsers": true+ },+ "notification": {+ "message": {+ "type": "localized",+ "defaultLanguage": "en",+ "languages": {+ "en": {+ "type": "email",+ "subject": "Linked user localized user test",+ "html": "%TRIGGER_ASSETS%"+ }+ }+ }+ }+ },{"action": "write-attribute","target": {diff --git a/ui/app/manager/package.json b/ui/app/manager/package.jsonindex 823935c53..90a74d75f 100644--- a/ui/app/manager/package.json+++ b/ui/app/manager/package.json@@ -25,7 +25,8 @@"test": "echo \"Error: no test specified\" && exit 1"},"dependencies": {- "@openremote/or-app": "^1.1.0"+ "@openremote/or-app": "^1.1.0",+ "iso-639-1": "^3.1.3"},"devDependencies": {"@openremote/util": "workspace:*"diff --git a/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.ts b/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.tsindex 39befbe2e..43e31eef9 100644--- a/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.ts+++ b/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.ts@@ -36,6 +36,7 @@ import { i18next } from "@openremote/or-translate";import { FileInfo, ManagerAppRealmConfig } from "@openremote/model";import { DialogAction, OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";import {when} from 'lit/directives/when.js';+import ISO6391 from 'iso-639-1';@customElement("or-conf-realm-card")export class OrConfRealmCard extends LitElement {@@ -153,6 +154,18 @@ export class OrConfRealmCard extends LitElement {];+ protected commonLanguages: string[] = Object.entries(DEFAULT_LANGUAGES).map(entry => ISO6391.getName(entry[0]));+ protected _languages: string[][] = [];++ connectedCallback() {+ const languageNames = ISO6391.getAllNames();+ this._languages = ISO6391.getAllCodes()+ .map((code, index) => ([code, languageNames[index]]))+ .sort((a, b) => a[1].localeCompare(b[1]));++ return super.connectedCallback();+ }+protected _getColors() {const colors: { [name: string]: string } = {"--or-app-color1": unsafeCSS(DefaultColor1).toString(),@@ -274,6 +287,14 @@ export class OrConfRealmCard extends LitElement {render() {const colors = this._getColors();const app = this;++ // On an empty search; return the common language as set in DEFAULT_LANGUAGES+ // If searching, compare strings using lowercase. (with no maximum)+ const searchProvider = (search: string) => this._languages.filter(entry =>+ (!search && this.commonLanguages.includes(entry[1])) ||+ (!search && app.realm.notifications?.languages.includes(entry[0])) ||+ entry[1].toLowerCase().includes(search?.toLowerCase()))+return html`<or-collapsible-panel .expanded="${app.expanded}"><div slot="header" class="header-container">@@ -360,6 +381,51 @@ export class OrConfRealmCard extends LitElement {></or-mwc-input></div></div>+ <div class="header-group">+ <div class="subheader">${i18next.t("configuration.notificationLanguages")}</div>+ <span>${i18next.t("configuration.notificationLanguagesDesc")}</span>+ <div>+ <or-mwc-input+ .type="${InputType.SELECT}" multiple+ class="header-item"+ searchLabel="configuration.notificationLanguagesLabel"+ .label="${i18next.t("configuration.notificationLanguages")}"+ .value="${app.realm.notifications?.languages || []}"+ .options="${this._languages}"+ .searchProvider="${searchProvider}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {+ const newLanguages: string[] | undefined = e.detail.value;+ const currentDefault: string | undefined = app.realm.notifications?.defaultLanguage;+ app.realm.notifications = {+ languages: newLanguages,+ defaultLanguage: newLanguages?.includes(currentDefault) ? currentDefault : newLanguages?.[0]+ }+ app.notifyConfigChange(app.realm);+ this.requestUpdate(); // force render+ }}"+ ></or-mwc-input>+ ${when(app.realm.notifications?.languages?.length > 0, () => html`+ <or-mwc-input+ .type="${InputType.SELECT}"+ class="header-item"+ .label="${i18next.t("configuration.defaultLanguage")}"+ .value="${app.realm.notifications?.defaultLanguage || []}"+ .options="${this._languages.filter(entry => app.realm.notifications?.languages.includes(entry[0]))}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {+ app.realm.notifications.defaultLanguage = e.detail.value;+ app.notifyConfigChange(app.realm);+ this.requestUpdate(); // force render+ }}"+ ></or-mwc-input>+ `, () => html`+ <or-mwc-input+ .type="${InputType.SELECT}" disabled+ class="header-item"+ .label="${i18next.t("configuration.defaultLanguage")}"+ ></or-mwc-input>+ `)}+ </div>+ </div>${when(app.canRemove, () => html`<or-mwc-input outlined id="remove-realm" .type="${InputType.BUTTON}"diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.tsindex aab2f92f3..1579c0a65 100644--- a/ui/app/manager/src/index.ts+++ b/ui/app/manager/src/index.ts@@ -166,7 +166,7 @@ fetch(configURL).then(async (result) => {// Replace any supplied page configspages = pages.map(pageProvider => {- const config = appConfig.pages[pageProvider.name];+ const config: {[p: string]: any} | undefined = appConfig.pages[pageProvider.name];switch (pageProvider.name) {case "map": {@@ -178,7 +178,15 @@ fetch(configURL).then(async (result) => {break;}case "rules": {- pageProvider = config ? pageRulesProvider(store, config as PageRulesConfig) : pageProvider;+ const newConfig = (config || {+ rules: {}+ }) as PageRulesConfig;+ if(!newConfig.rules?.notifications) {+ newConfig.rules.notifications = Object.fromEntries(+ Object.entries(appConfig.realms).map(entry => [entry[0], entry[1].notifications])+ );+ }+ pageProvider = pageRulesProvider(store, newConfig);break;}case "insights": {@@ -245,19 +253,25 @@ fetch(configURL).then(async (result) => {.concat(pages.filter(pageProvider => !headerPaths.includes(pageProvider.name)));}+ // If the user does not have a preferred language configured (in Keycloak),+ // we need to update it with their preferred language from other sources. (consoles, realm configuration etc.)// Check local storage for set language, otherwise use language set in config- manager.console.retrieveData("LANGUAGE").then((value: string | undefined) => {- if (value) {- manager.language = value;- } else if (orAppConfig.realms[manager.displayRealm]) {- manager.language = orAppConfig.realms[manager.displayRealm].language- } else if (orAppConfig.realms['default']) {- manager.language = orAppConfig.realms['default'].language- } else {- manager.language = 'en'+ manager.getUserPreferredLanguage().then((userLang: string | undefined) => {+ if(!userLang) {+ manager.getConsolePreferredLanguage().then((consoleLang: string | undefined) => {+ if (consoleLang) {+ manager.language = consoleLang;+ } else if (orAppConfig.realms[manager.displayRealm]) {+ manager.language = orAppConfig.realms[manager.displayRealm].language+ } else if (orAppConfig.realms['default']) {+ manager.language = orAppConfig.realms['default'].language+ } else {+ manager.language = 'en'+ }+ }).catch(reason => {+ console.error("Failed to initialise app: " + reason);+ })}- }).catch(reason => {- console.error("Failed to initialise app: " + reason);})// Add config prefix if defined (used in dev)diff --git a/ui/app/manager/src/pages/page-rules.ts b/ui/app/manager/src/pages/page-rules.tsindex 439a47f4f..e5c1410b5 100644--- a/ui/app/manager/src/pages/page-rules.ts+++ b/ui/app/manager/src/pages/page-rules.ts@@ -22,9 +22,9 @@ export function pageRulesProvider(store: Store<AppStateKeyed>, config: PageRules],pageCreator: () => {const page = new PageRules(store);- if (config) {- page.config = config;- }+ page.config = {+ rules: {...PAGE_RULES_CONFIG_DEFAULT.rules, ...config.rules}+ };return page;}};@@ -41,7 +41,9 @@ export const PAGE_RULES_CONFIG_DEFAULT: PageRulesConfig = {attribute: [],webhook: [],email: [NotificationTargetType.USER, NotificationTargetType.CUSTOM],+ email_localized: [NotificationTargetType.USER, NotificationTargetType.CUSTOM],push: [NotificationTargetType.USER, NotificationTargetType.ASSET],+ push_localized: [NotificationTargetType.USER, NotificationTargetType.ASSET]}}},diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.tsindex 7c141123f..047eeadee 100644--- a/ui/component/core/src/index.ts+++ b/ui/component/core/src/index.ts@@ -238,9 +238,11 @@ export class Manager implements EventProviderFactory {}set language(lang: string) {+ console.debug(`Changing language to ${lang}.`);if (lang) {i18next.changeLanguage(lang);this.console.storeData("LANGUAGE", lang);+ this.updateKeycloakUserLanguage(lang).catch(e => console.error(e));}}@@ -472,9 +474,8 @@ export class Manager implements EventProviderFactory {});// Look for language preference in local storage- const language: string | undefined = !this.console ? undefined : await this.console.retrieveData("LANGUAGE");const initOptions: InitOptions = {- lng: !language || language === "null" ? this.config.defaultLanguage || "en" : language, // somehow language is "null" sometimes+ lng: await this.getConsolePreferredLanguage() || await this.getUserPreferredLanguage() || this.config.defaultLanguage || "en",fallbackLng: "en",defaultNS: "app",fallbackNS: "or",@@ -662,6 +663,46 @@ export class Manager implements EventProviderFactory {}}+ /**+ * Checks the native console to gather the preferred language of the device.+ */+ public async getConsolePreferredLanguage(orConsole = this.console): Promise<string | undefined> {+ return orConsole.retrieveData("LANGUAGE");+ }++ /**+ * Checks the keycloak access token to gather the preferred language of a user.+ */+ public async getUserPreferredLanguage(keycloak = this._keycloak): Promise<string | undefined> {++ if(keycloak) {+ const profile: Keycloak.KeycloakProfile | undefined = keycloak?.profile || await keycloak?.loadUserProfile();+ if(profile?.attributes) {+ const attributes = new Map(Object.entries(profile.attributes));+ if(attributes.has("locale")) {+ const attr = attributes.get("locale") as any[];+ if(typeof attr[0] === "string") {+ return attr[0];+ }+ }+ console.warn("Could not get user language from keycloak: no user attributes were found.");+ } else {+ console.warn("Could not get user language from keycloak: no valid keycloak user profile was found.");+ }+ }+ }++ protected async updateKeycloakUserLanguage(lang: string, keycloak = this._keycloak, rest = this.rest): Promise<void> {+ if(!keycloak) {+ return;+ }+ if(!rest) {+ console.warn("Tried updating user language in keycloak, but the REST API is not initialized yet.");+ return;+ }+ await rest.api.UserResource.updateCurrentUserLocale(lang, { headers: { "Content-Type": "application/json" } });+ }+public logout(redirectUrl?: string) {if (!this._authenticated) {return;diff --git a/ui/component/or-app/src/or-header.ts b/ui/component/or-app/src/or-header.tsindex a09c2a035..682898b00 100644--- a/ui/component/or-app/src/or-header.ts+++ b/ui/component/or-app/src/or-header.ts@@ -373,10 +373,6 @@ export class OrHeader extends LitElement {return super.shouldUpdate(changedProperties);}- firstUpdated() {- this._getAlarmButton();- }-connectedCallback() {super.connectedCallback();this._subscribeEvents();diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.tsindex 21f52d793..6d005cc82 100644--- a/ui/component/or-mwc-components/src/or-mwc-input.ts+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts@@ -723,6 +723,9 @@ export class OrMwcInput extends LitElement {@property({type: Object})public searchProvider?: (search?: string) => Promise<[any, string][]>+ @property({type: String})+ public searchLabel = "search"+/* STYLING PROPERTIES BELOW */@property({type: String})@@ -1122,7 +1125,9 @@ export class OrMwcInput extends LitElement {<div id="mdc-select-menu" class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fixed ${this.searchProvider != undefined ? 'mdc-menu__searchable' : undefined}" @MDCMenuSurface:closed="${menuCloseHandler}">${when(this.searchProvider != undefined, () => html`<label id="select-searchable" class="mdc-text-field mdc-text-field--filled">- <span class="mdc-floating-label" style="color: rgba(0, 0, 0, 0.6); text-transform: capitalize; visibility: ${this.searchableValue ? 'hidden' : 'visible'}" id="my-label-id">${i18next.t('search')}</span>+ <span class="mdc-floating-label" style="color: rgba(0, 0, 0, 0.6); text-transform: capitalize; visibility: ${this.searchableValue ? 'hidden' : 'visible'}" id="my-label-id">+ <or-translate .value="${this.searchLabel}"></or-translate>+ </span><input class="mdc-text-field__input" type="text"@keyup="${(e: KeyboardEvent) => this.searchableValue = (e.target as HTMLInputElement).value}"/>diff --git a/ui/component/or-rules/package.json b/ui/component/or-rules/package.jsonindex 55f3d4159..0a768b79e 100644--- a/ui/component/or-rules/package.json+++ b/ui/component/or-rules/package.json@@ -25,6 +25,7 @@"@openremote/or-translate": "^1.1.0","@openremote/rest": "workspace:*","ace-builds": "^1.4.13",+ "iso-639-1": "^3.1.3","linqts": "^1.12.6","lit": "^2.0.2","moment": "^2.29.4",diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.tsindex 524007776..0162fb416 100644--- a/ui/component/or-rules/src/index.ts+++ b/ui/component/or-rules/src/index.ts@@ -55,7 +55,9 @@ export const enum ActionType {WAIT = "wait",ALARM = "alarm",EMAIL = "email",+ EMAIL_LOCALIZED = "email_localized",PUSH_NOTIFICATION = "push",+ PUSH_LOCALIZED = "push_localized",ATTRIBUTE = "attribute",WEBHOOK = "webhook"}@@ -137,6 +139,12 @@ export interface RulesConfig {then?: RuleActionUnion;otherwise?: RuleActionUnion;};+ notifications?: {+ [realm: string]: {+ defaultLanguage?: string;+ languages?: string[];+ }+ }}export interface RulesDescriptorSection {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 133e3ccc5..ab78a15fc 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@@ -5,18 +5,14 @@ import i18next from "i18next";import {translate} from "@openremote/or-translate";import "@openremote/or-mwc-components/or-mwc-input";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";-import {- RuleActionNotification,- EmailNotificationMessage-} from "@openremote/model";+import {EmailNotificationMessage} from "@openremote/model";import { OrRulesJsonRuleChangedEvent } from "../or-rule-json-viewer";@customElement("or-rule-form-email-message")export class OrRuleFormEmailMessage extends translate(i18next)(LitElement) {- @property({type: Object, attribute: false})- public action!: RuleActionNotification;-+ @property({type: Object})+ public message?: EmailNotificationMessage;static get styles() {return css`@@ -25,25 +21,25 @@ export class OrRuleFormEmailMessage extends translate(i18next)(LitElement) {min-width: 420px;width: 100%;}- `+ `;}protected render() {- const message: EmailNotificationMessage | undefined = this.action.notification!.message as EmailNotificationMessage;+ if(!this.message) {+ return html`<or-translate .value="${"errorOccurred"}"></or-translate>`;+ }return html`<form style="display:grid">- <or-mwc-input value="${message && message.subject ? message.subject : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "subject")}" .label="${i18next.t("subject")}" type="${InputType.TEXT}" required placeholder=" "></or-mwc-input>- <or-mwc-input value="${message && message.html ? message.html : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "html")}" .label="${i18next.t("message")}" type="${InputType.TEXTAREA}" required placeholder=" " ></or-mwc-input>+ <or-mwc-input value="${this.message.subject || ''}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "subject")}" .label="${i18next.t("subject")}" type="${InputType.TEXT}" required placeholder=" "></or-mwc-input>+ <or-mwc-input value="${this.message.html || ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "html")}" .label="${i18next.t("message")}" type="${InputType.TEXTAREA}" required placeholder=" " ></or-mwc-input></form>`}protected setActionNotificationName(value: string | undefined, key?: string) {- if(key && this.action.notification && this.action.notification.message){- const message:any = this.action.notification.message;- message[key] = value;- this.action.notification.message = {...message};+ if(key && this.message){+ (this.message as any)[key] = value;}this.dispatchEvent(new OrRulesJsonRuleChangedEvent());diff --git a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-localized.ts b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-localized.tsnew file mode 100644index 000000000..35a43d776--- /dev/null+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-localized.ts@@ -0,0 +1,248 @@+import {i18next, translate} from "@openremote/or-translate";+import {LitElement, PropertyValues, TemplateResult, css, html} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import {AbstractNotificationMessageUnion, LocalizedNotificationMessage} from "@openremote/model";+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {OrRulesJsonRuleChangedEvent} from "../or-rule-json-viewer";+import {when} from "lit/directives/when.js";+import {until} from "lit/directives/until.js";+import {guard} from "lit/directives/guard.js";+import "./or-rule-form-email-message";+import "./or-rule-form-push-notification";+import ISO6391 from "iso-639-1";+import {DefaultColor6} from "@openremote/core";++@customElement("or-rule-form-localized")+export class OrRuleFormLocalized extends translate(i18next)(LitElement) {++ @property({type: Object})+ public message?: LocalizedNotificationMessage;++ @property({type: String})+ public type: "push" | "email" = "push";++ @property()+ public languages: string[] = ["en"];++ @property()+ public defaultLang = "en";++ @property()+ public wrongLanguage = false;++ @state()+ protected _selectedLanguage = "en";++ @state()+ protected _validLanguages?: string[];++ static get styles() {+ return css`+ or-mwc-input {+ margin-bottom: 20px;+ min-width: 420px;+ width: 100%;+ }++ .divider {+ margin-bottom: 20px;+ border-top: 1px solid rgba(0, 0, 0, 12%);+ }+ `;+ }++ connectedCallback() {+ super.connectedCallback();+ if(!this.defaultLang || !this.languages.includes(this.defaultLang)) {+ this.defaultLang = this.languages[0];+ }+ this._selectedLanguage = this.defaultLang;+ }++ protected render() {+ return html`+ <div>+ ${when(this.wrongLanguage, () => until(this._getWrongLanguageTemplate()))}+ ${guard([this.message, this._selectedLanguage, this.languages, this.type], () => html`+ ${until(this._getLanguageSelectForm(this._selectedLanguage, this.languages), html`Loading...`)}+ ${until(this._getNotificationForm(this.message, this._selectedLanguage), html`Loading...`)}+ `)}+ ${when(this.languages?.length && this._validLanguages && (this._validLanguages.length < this.languages.length),+ () => until(this._getLanguageErrorTemplate(this.languages!, this._validLanguages!))+ )}+ </div>+ `;+ }++ /**+ * Internal function that returns we "the default language has changed! Fix here" warning. (using {@link TemplateResult})+ * This template includes a button that will update the default language to the correct one.+ */+ protected async _getWrongLanguageTemplate(): Promise<TemplateResult> {+ return html`+ <or-mwc-input .type="${InputType.BUTTON}" fullWidth outlined+ label="defaultLanguageChangedError" style="margin-top: 10px;"+ @or-mwc-input-changed="${this._fixDefaultLanguage}"+ ></or-mwc-input>+ `;+ }++ /**+ * Function that corrects the default language in the {@link LocalizedNotificationMessage},+ * to the one provided by parent elements using {@link defaultLang}.+ * The {@link wrongLanguage} property will be updated to 'false'.+ */+ protected _fixDefaultLanguage(): void {+ if(this.message) {+ console.debug("Updating default language from " + this.message.defaultLanguage + " to " + this.defaultLang);+ this.message.defaultLanguage = this.defaultLang;+ this.wrongLanguage = false;+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ } else {+ console.warn("Could not fix language, because the message could not be found.");+ showSnackbar(undefined, "Could not fix language, because the message could not be found.");+ }+ }++ /**+ * Internal function that returns the "select language" controls form. (using {@link TemplateResult})+ * Based on {@link languageCodes}, it lists all languages of the ISO6391 specification.+ */+ protected async _getLanguageSelectForm(selected: string, languageCodes: string[] = [this._selectedLanguage], divider = true): Promise<TemplateResult> {+ const languages = languageCodes.map(key => [key, ISO6391.getName(key)]);+ return html`+ <div style="display: flex; justify-content: space-between;">+ <or-mwc-input .type="${InputType.SELECT}" .options="${languages}" .value="${selected}"+ @or-mwc-input-changed="${this._onLanguageChange}"+ ></or-mwc-input>+ </div>+ ${when(divider, () => html`+ <div class="divider"></div>`)}+ `;+ }++ /**+ * HTML callback for when the selected language changes.+ */+ protected _onLanguageChange(ev: OrInputChangedEvent) {+ this._selectedLanguage = ev.detail.value;+ }++ /**+ * Internal function that returns the correct notification form, based on the type.+ * Based on {@link lang}, it uses the Notification configured for that language.+ */+ protected async _getNotificationForm(message = this.message, lang = this._selectedLanguage): Promise<TemplateResult> {+ if(!message?.languages) {+ return html`<or-translate .value="${"errorOccurred"}"></or-translate>`;+ }+ if(!message.languages[lang]) {+ message.languages[lang] = {+ type: this.type+ };+ }+ const msg = message.languages[lang];++ if(msg.type === "push") {+ return html`+ <or-rule-form-push-notification .message="${msg}"></or-rule-form-push-notification>+ `;+ } else if(msg.type === "email") {+ return html`+ <or-rule-form-email-message .message="${msg}"></or-rule-form-email-message>+ `;+ } else {+ return html`+ <or-translate .value="${"errorOccurred"}"></or-translate>+ `;+ }+ }++ /**+ * Internal function that returns the "language error" text, if a message is invalid. (using {@link TemplateResult})+ * Based on {@link validLanguages} and the listed {@link languages}, it shows a string of which ones are invalid.+ */+ protected async _getLanguageErrorTemplate(languages: string[], validLanguages: string[]): Promise<TemplateResult> {+ const invalidLocalesStr = languages.filter(l => !validLanguages.includes(l)).map(l => ISO6391.getName(l)).join(", ");+ return html`+ <div style="margin-top: 10px; display: flex; justify-content: end; color: ${DefaultColor6};">+ <or-translate value="languagesInvalidError"></or-translate>+ <span style="padding-left: 4px;">${invalidLocalesStr}</span>+ </div>+ `;+ }++ /**+ * A public function that checks if the localized {@link message} is valid.+ * By looping through the languages, we verify for each email- and push notification if some required variables are empty.+ * Returns true, or false if ANY language is not valid.+ */+ public isValid(): boolean {+ if(this.message?.languages && this.languages?.length) {++ // First, cleanup the message+ this._cleanNotificationMessage();++ const validLanguages = this.languages?.filter(lang => {+ if(!this.message?.languages?.[lang]) {+ return true;+ }+ const msg = this.message.languages[lang];+ switch(msg.type) {+ case "email":+ return msg.subject && msg.html;+ case "push":+ return msg.title && msg.body;+ case "localized":+ return false;+ default:+ return true;+ }+ });+ // Update cached list of valid languages+ if(JSON.stringify(this._validLanguages) !== JSON.stringify(validLanguages)) {+ this._validLanguages = validLanguages;+ }++ return validLanguages.length === this.languages.length;+ }+ return false;+ }++ /**+ * Function that cleans up the localized notification message, by removing empty (or not filled in-) messages.+ * By looping through the languages, checking the amount of keys in the JS object, we delete languages that can be cleared.+ */+ protected _cleanNotificationMessage() {++ if(this.message?.languages) {+ const languageEntries = Object.entries(this.message.languages).filter(([lang, msg]) => {++ const userDefinedFields = Object.entries(msg).filter(entry => {+ if(entry[0] === "type") return false;+ if(entry[1] == null) return false; // key has no value+ if(typeof entry[1] === "string" && entry[1].length === 0) return false;+ if(Array.isArray(entry[1])) {+ // Check if any object in the array has at least one key-value pair with a truthy value+ const arrayHasValue = entry[1].some(obj =>+ Object.keys(obj).length > 0 && Object.values(obj).some(value => value)+ );+ if(!arrayHasValue) return false;++ } else if(typeof entry[1] === "object") {+ if(Object.keys(entry[1]).length === 0 || Object.values(entry[1]).filter(value => value).length === 0) return false;+ }+ return true;+ });++ if(userDefinedFields.length === 0) {+ console.debug(`Removing fields of notification language '${lang}', as they were all empty.`);+ return false;+ }+ return true;+ });+ this.message.languages = Object.fromEntries(languageEntries) as {[p: string]: AbstractNotificationMessageUnion};+ }+ }+}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 591a0f5f2..9218d10f3 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,107 +1,144 @@-import {html, LitElement, css} from "lit";+import {html, LitElement, css, TemplateResult} from "lit";import {customElement, property} from "lit/decorators.js";import "@openremote/or-mwc-components/or-mwc-input";import i18next from "i18next";import {translate} from "@openremote/or-translate";-import "@openremote/or-mwc-components/or-mwc-input";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";-import {- RuleActionNotification,- PushNotificationMessage-} from "@openremote/model";-import { OrRulesJsonRuleChangedEvent } from "../or-rule-json-viewer";-import set from "lodash-es/set";+import {PushNotificationMessage, PushNotificationButton} from "@openremote/model";+import {OrRulesJsonRuleChangedEvent} from "../or-rule-json-viewer";+import {until} from "lit/directives/until.js";+import {when} from "lit/directives/when.js";@customElement("or-rule-form-push-notification")export class OrRuleFormPushNotification extends translate(i18next)(LitElement) {- @property({type: Object, attribute: false})- public action!: RuleActionNotification;-+ @property({type: Object})+ public message?: PushNotificationMessage;static get styles() {return css`+ .input-small {+ min-width: auto;+ }+or-mwc-input {margin-bottom: 20px;min-width: 420px;width: 100%;}- `- }-- protected updated(_changedProperties: Map<PropertyKey, unknown>): void {- if(_changedProperties.has("action")) {- let message: PushNotificationMessage | undefined = this.action.notification!.message as PushNotificationMessage;- if (this.action.notification && message && !message.action) {- message = {type: "push", action: {openInBrowser: true}}- this.action.notification.message = {...this.action.notification.message, ...message};++ .divider {+ margin-bottom: 20px;+ border-top: 1px solid rgba(0, 0, 0, 12%);}- }+ `;}protected render() {- const message: PushNotificationMessage | undefined = this.action.notification!.message as PushNotificationMessage;- const title = message && message.title ? message.title : "";- const body = message && message.body ? message.body : "";- const action = message && message.action ? message.action : "";- const actionUrl = action && action.url ? action.url : "";- const buttons = message && message.buttons ? message.buttons : [];+ return html`+ ${when(this.message,+ () => until(this._getPushNotificationForm(this.message!), html`Loading...`),+ () => html`<or-translate value="errorOccurred"></or-translate>`+ )}+ `;+ }++ /**+ * Internal function that returns a form for configuring a {@link PushNotificationMessage}.+ * {@link onchange} is a callback function can be used to process changes before they are applied.+ */+ protected async _getPushNotificationForm(message: PushNotificationMessage, onchange = async (_ev: OrInputChangedEvent, msg?: PushNotificationMessage) => msg!): Promise<TemplateResult> {+return html`<form style="display:grid">- <or-mwc-input value="${title}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "title")}"- .label="${i18next.t("subject")}"- type="${InputType.TEXT}"- required- placeholder=" "></or-mwc-input>-- <or-mwc-input value="${body}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "body")}"- .label="${i18next.t("message")}"- type="${InputType.TEXTAREA}"- required- placeholder=" " ></or-mwc-input>- <or-mwc-input value="${actionUrl}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "action.url")}"- .label="${i18next.t("openWebsiteUrl")}"- type="${InputType.TEXT}"- required- placeholder=" "></or-mwc-input>-- <or-mwc-input .value="${action && typeof action.openInBrowser !== "undefined" ? (action && action.openInBrowser) : true}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "action.openInBrowser")}"- .label="${i18next.t("openInBrowser")}"- type="${InputType.SWITCH}"- placeholder=" "></or-mwc-input>-- <or-mwc-input value="${buttons && buttons[0] && buttons[0].title ? buttons[0].title : ""}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "buttons.0.title")}"- .label="${i18next.t("buttonTextConfirm")}"- type="${InputType.TEXT}"- required- placeholder=" "></or-mwc-input>- <or-mwc-input value="${buttons && buttons[1] && buttons[1].title ? buttons[1].title : ""}"- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "buttons.1.title")}"- .label="${i18next.t("buttonTextDecline")}"- type="${InputType.TEXT}"- placeholder=" "></or-mwc-input>+ <or-mwc-input .value="${message.title}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onchange(ev, message).then(msg => this._onTitleChange(ev, msg))}"+ .label="${i18next.t("subject")}"+ type="${InputType.TEXT}"+ required+ placeholder=" "></or-mwc-input>++ <or-mwc-input .value="${message.body}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onchange(ev, message).then(msg => this._onBodyChange(ev, msg))}"+ .label="${i18next.t("message")}"+ type="${InputType.TEXTAREA}"+ required+ placeholder=" "></or-mwc-input>+ <or-mwc-input .value="${message.action?.url}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onchange(ev, message).then(msg => this._onActionUrlChange(ev, msg))}"+ .label="${i18next.t("openWebsiteUrl")}"+ type="${InputType.TEXT}"+ placeholder=" "></or-mwc-input>++ <!-- Open in browser switch -->+ <or-mwc-input .value="${message.action?.openInBrowser}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onchange(ev, message).then(msg => this._onOpenInBrowserChange(ev, msg))}"+ .label="${i18next.t("openInBrowser")}"+ type="${InputType.SWITCH}"+ fullWidth+ placeholder=" "></or-mwc-input>++ <!-- Button controls -->+ <div style="display: flex; gap: 20px;">+ <or-mwc-input .value="${message.buttons?.[0]?.title}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onchange(ev, message).then(msg => this._onButtonTitleChange(ev, 0, msg))}"+ .label="${i18next.t("buttonTextConfirm")}"+ type="${InputType.TEXT}"+ class="input-small"+ placeholder=" "></or-mwc-input>+ <or-mwc-input .value="${message.buttons?.[1]?.title}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onchange(ev, message).then(msg => this._onButtonTitleChange(ev, 1, msg))}"+ .label="${i18next.t("buttonTextDecline")}"+ type="${InputType.TEXT}"+ class="input-small"+ placeholder=" "></or-mwc-input>+ </div></form>- `+ `;+ }++ /**+ * HTML callback function when the subject of a notification message has changed.+ */+ protected _onTitleChange(ev: OrInputChangedEvent, message: PushNotificationMessage) {+ message.title = ev.detail.value;+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());}+ /**+ * HTML callback function when the body of a notification message has changed.+ */+ protected _onBodyChange(ev: OrInputChangedEvent, message: PushNotificationMessage) {+ message.body = ev.detail.value;+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ }+ /**+ * HTML callback function when the "click here to open URL" of a notification has changed.+ */+ protected _onActionUrlChange(ev: OrInputChangedEvent, message: PushNotificationMessage) {+ message.action = message.action || {};+ message.action.url = ev.detail.value;+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ }- protected setActionNotificationName(value: string | undefined, key?: string) {- if(key && this.action.notification && this.action.notification.message){- let message:any = this.action.notification.message;- set(message, key, value);- if(key.includes('action')) {- set(message, "buttons.0."+key, value);- }- this.action.notification.message = {...message};- }+ /**+ * HTML callback function when the "open in browser switch" of a notification has changed.+ */+ protected _onOpenInBrowserChange(ev: OrInputChangedEvent, message: PushNotificationMessage) {+ message.action = message.action || {};+ message.action.openInBrowser = ev.detail.value;+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ }+ /**+ * HTML callback function when any button text of the notification has changed.+ */+ protected _onButtonTitleChange(ev: OrInputChangedEvent, key: number, message: PushNotificationMessage) {+ message.buttons = message.buttons || [];+ message.buttons[key] = {+ title: ev.detail.value+ } as PushNotificationButton;this.dispatchEvent(new OrRulesJsonRuleChangedEvent());- this.requestUpdate();}}diff --git a/ui/component/or-rules/src/json-viewer/modals/or-rule-notification-modal.ts b/ui/component/or-rules/src/json-viewer/modals/or-rule-notification-modal.tsindex c943b7f41..c6de60cdc 100644--- a/ui/component/or-rules/src/json-viewer/modals/or-rule-notification-modal.ts+++ b/ui/component/or-rules/src/json-viewer/modals/or-rule-notification-modal.ts@@ -1,5 +1,5 @@import {html, LitElement, PropertyValues} from "lit";-import {customElement, property} from "lit/decorators.js";+import {customElement, property, query} from "lit/decorators.js";import {RuleActionNotification,AssetQuery,@@ -10,18 +10,21 @@ import {InputType} from "@openremote/or-mwc-components/or-mwc-input";import i18next from "i18next";import {translate} from "@openremote/or-translate";-import {DialogAction, OrMwcDialog, OrMwcDialogOpenedEvent} from "@openremote/or-mwc-components/or-mwc-dialog";-const checkValidity = (form:HTMLElement | null, dialog:OrMwcDialog) => {+import {DialogAction, DialogActionBase, OrMwcDialog, OrMwcDialogOpenedEvent} from "@openremote/or-mwc-components/or-mwc-dialog";+import {OrRuleFormLocalized} from "../forms/or-rule-form-localized";+import {OrRulesJsonRuleChangedEvent} from "../or-rule-json-viewer";++const checkValidity = (form:HTMLElement | null) => {if(form) {const inputs = form.querySelectorAll('or-mwc-input');const elements = Array.prototype.slice.call(inputs);- const valid = elements.every((element) => {+ return elements.every((element) => {if(element.shadowRoot) {const input = element.shadowRoot.querySelector('input, textarea, select') as anyif(input && input.checkValidity()) {- return true+ return true;} else {element._mdcComponent.valid = false;element._mdcComponent.helperTextContent = 'required';@@ -31,16 +34,38 @@ const checkValidity = (form:HTMLElement | null, dialog:OrMwcDialog) => {} else {return false;}- })- if(valid) {- dialog.close();- }+ });+ }+}++export class OrRulesNotificationModalCancelEvent extends CustomEvent<void> {++ public static readonly NAME = "or-rules-notification-modal-cancel";++ constructor() {+ super(OrRulesNotificationModalCancelEvent.NAME, {+ bubbles: true,+ composed: true+ });+ }+}++export class OrRulesNotificationModalOkEvent extends CustomEvent<void> {++ public static readonly NAME = "or-rules-notification-modal-ok";++ constructor() {+ super(OrRulesNotificationModalOkEvent.NAME, {+ bubbles: true,+ composed: true+ });}}+@customElement("or-rule-notification-modal")export class OrRuleNotificationModal extends translate(i18next)(LitElement) {- @property({type: Object, attribute: false})+ @property({type: Object})public action!: RuleActionNotification;@property({type: String})@@ -48,15 +73,31 @@ export class OrRuleNotificationModal extends translate(i18next)(LitElement) {@property({type: Object})public query?: AssetQuery;++ @query("#notification-modal")+ protected _orMwcDialog?: OrMwcDialog;constructor() {super();this.addEventListener(OrMwcDialogOpenedEvent.NAME, this.initDialog)}+ connectedCallback() {+ this.addEventListener(OrRulesJsonRuleChangedEvent.NAME, this._onJsonRuleChanged);+ return super.connectedCallback();+ }++ disconnectedCallback() {+ this.removeEventListener(OrRulesJsonRuleChangedEvent.NAME, this._onJsonRuleChanged);+ return super.disconnectedCallback();+ }++ protected _onJsonRuleChanged() {+ this.validateForm();+ }+initDialog() {- const modal = this.shadowRoot!.getElementById('notification-modal');- if(!modal) return;+ if(!this._orMwcDialog) return;}renderDialogHTML(action:RuleActionNotification) {@@ -81,42 +122,84 @@ export class OrRuleNotificationModal extends translate(i18next)(LitElement) {if(changedProperties.has("action")){this.renderDialogHTML(this.action);}+ // Possibly, a render is triggered by renderDialogHTML(), so we await the pending update. (if there is any)+ this.getUpdateComplete().finally(() => {+ this.validateForm();+ });}- checkForm() {- const dialog: OrMwcDialog = this.shadowRoot!.host as OrMwcDialog;+ validateForm() {+ const valid = this.checkForm();+ this._orMwcDialog?.setActions(this._orMwcDialog?.actions?.map(action => {+ if(action.actionName === "ok") {+ action.disabled = !valid;+ }+ return action;+ }));+ }+ checkForm() {if (this.shadowRoot) {- const messageNotification = this.shadowRoot.querySelector('or-rule-form-email-message');- const pushNotification = this.shadowRoot.querySelector('or-rule-form-push-notification');- if(pushNotification && pushNotification.shadowRoot) {- const form = pushNotification.shadowRoot.querySelector('form');- return checkValidity(form, dialog);- }- else if(messageNotification && messageNotification.shadowRoot) {- const form = messageNotification.shadowRoot.querySelector('form');- return checkValidity(form, dialog);+ const dialog = this._orMwcDialog;+ const root = dialog?.shadowRoot;+ if(dialog && root) {++ const messageNotification = root.querySelector("or-rule-form-email-message");+ const pushNotification = root.querySelector("or-rule-form-push-notification");+ const localizedNotification = root.querySelector("or-rule-form-localized");++ if(pushNotification?.shadowRoot) {+ const form = pushNotification.shadowRoot.querySelector('form');+ return checkValidity(form);+ }+ else if(messageNotification?.shadowRoot) {+ const form = messageNotification.shadowRoot.querySelector('form');+ return checkValidity(form);+ }+ else if(localizedNotification?.shadowRoot) {+ return (localizedNotification as OrRuleFormLocalized).isValid();+ }}}}protected render() {- if(!this.action) return html``;-- const notificationPickerModalActions: DialogAction[] = [++ const onCancel = () => {+ this.dispatchEvent(new OrRulesNotificationModalCancelEvent());+ };++ const onOk = () => {+ this.dispatchEvent(new OrRulesNotificationModalOkEvent());+ };++ const dismissAction: DialogActionBase = {+ actionName: "cancel",+ action: onCancel+ };++ const actions: DialogAction[] = [{actionName: "cancel",content: html`<or-mwc-input class="button" .type="${InputType.BUTTON}" label="cancel"></or-mwc-input>`,- action: (dialog) => {-- }+ action: onCancel},{- actionName: "",- content: html`<or-mwc-input class="button" .type="${InputType.BUTTON}" label="ok" @or-mwc-input-changed="${this.checkForm}"></or-mwc-input>`+ actionName: "ok",+ content: "ok",+ disabled: true, // (by default, can be changed in checkForm())+ action: onOk}];++ const styles = html`+ <style>+ .mdc-dialog__actions {+ justify-content: space-between !important;+ }+ </style>+ `;const notificationPickerModalOpen = () => {@@ -128,8 +211,8 @@ export class OrRuleNotificationModal extends translate(i18next)(LitElement) {return html`<or-mwc-input .type="${InputType.BUTTON}" label="message" @or-mwc-input-changed="${notificationPickerModalOpen}"></or-mwc-input>- <or-mwc-dialog id="notification-modal" heading="${this.title}" .actions="${notificationPickerModalActions}"></or-mwc-dialog>+ <or-mwc-dialog id="notification-modal" .heading="${this.title}" .dismissAction="${dismissAction}" .actions="${actions}" .styles="${styles}"></or-mwc-dialog><slot class="notification-form-slot"></slot>- `+ `;}}diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.tsindex dc3bc0303..667d9921d 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts@@ -1,4 +1,4 @@-import {css, html, LitElement, TemplateResult} from "lit";+import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";import {customElement, property} from "lit/decorators.js";import {until} from "lit/directives/until.js";import {ActionType, OrRulesRuleUnsupportedEvent, RulesConfig} from "../index";@@ -11,16 +11,18 @@ import {RuleActionNotification,UserQuery,WellknownAssets,- NotificationTargetType+ NotificationTargetType, PushNotificationMessage, EmailNotificationMessage, LocalizedNotificationMessage} from "@openremote/model";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";import {getTargetTypeMap, OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";import "./modals/or-rule-notification-modal";import "./forms/or-rule-form-email-message";import "./forms/or-rule-form-push-notification";+import "./forms/or-rule-form-localized";import "./or-rule-action-attribute";import {i18next} from "@openremote/or-translate";import manager, {Util} from "@openremote/core";+import {OrRulesNotificationModalCancelEvent, OrRulesNotificationModalOkEvent} from "./modals/or-rule-notification-modal";// language=CSSconst style = css`@@ -62,6 +64,53 @@ export class OrRuleActionNotification extends LitElement {@property({type: Object})public config?: RulesConfig;+ protected _initialAction?: RuleActionNotification;++ connectedCallback() {+ this.addEventListener(OrRulesJsonRuleChangedEvent.NAME, this._onJsonRuleChanged);+ this._initialAction = structuredClone(this.action);+ return super.connectedCallback();+ }++ willUpdate(changedProps: PropertyValues) {++ // If the rule property changes, we assume it is a "new rule".+ // For example when the SAVE button is pressed in the JSON editor (which triggers an update of this 'rule' property),+ // we want to reset the _initialAction cache variable.+ if(changedProps.has("rule") && changedProps.get("rule") !== undefined) {+ this._initialAction = structuredClone(this.action);+ }++ return super.willUpdate(changedProps);+ }++ disconnectedCallback() {+ this.removeEventListener(OrRulesJsonRuleChangedEvent.NAME, this._onJsonRuleChanged);+ return super.disconnectedCallback();+ }++ protected _onJsonRuleChanged() {++ // Upon rule change, we update the name of the "Notification action" to a sensible value, for example with the subject of an email+ // This is to prevent the NAME (for example showing up in the logs) being NULL or not identifiable.+ if(this.action.notification) {+ const message = this.action.notification.message;+ if(message?.type === "localized") {+ const locale = this.config?.notifications?.[manager.displayRealm]?.defaultLanguage || this.config?.notifications?.["default"]?.defaultLanguage || manager.config.defaultLanguage;+ const msg = message.languages?.[locale]; // if localized, we use the default language+ if(msg?.type === "push") {+ this.action.notification.name = msg.title;+ } else if(msg?.type === "email") {+ this.action.notification.name = msg.subject;+ }+ } else if (message?.type === "push") {+ this.action.notification.name = message.title;+ } else if (message?.type === "email") {+ this.action.notification.name = message.subject;+ }+ }+ }+protected static getActionTargetTemplate(targetTypeMap: [string, string?][], action: RuleAction, actionType: ActionType, readonly: boolean, config: RulesConfig | undefined, baseAssetQuery: AssetQuery | undefined, onTargetTypeChangedCallback: (type: NotificationTargetType) => void, onTargetChangedCallback: (type: NotificationTargetType, value: string | undefined) => void): PromiseLike<TemplateResult> | undefined {let allowedTargetTypes: [NotificationTargetType, string][] = [@@ -288,19 +337,71 @@ export class OrRuleActionNotification extends LitElement {return ``;}+ // When 'cancel' is pressed, reset ACTION to the initial state (all changes get removed)+ const onModalCancel = (ev: OrRulesNotificationModalCancelEvent) => {+ if(this._initialAction && this.action.notification) {+ const newAction = structuredClone(this._initialAction);++ // Check if anything in the message has changed+ if(JSON.stringify(this.action.notification.message) !== JSON.stringify(newAction.notification?.message)) {+ console.debug("Rolling back the notification to former state...");+ this.action.notification.message = newAction.notification?.message;+ this.requestUpdate('action');+ } else {+ console.debug("Rolling back was not necessary, as no changes have been done.");+ }++ } else {+ console.warn("Could not rollback notification form.");+ }+ };++ const onModalOk = (ev: OrRulesNotificationModalOkEvent) => {+ this._initialAction = structuredClone(this.action); // update initial action for opening the modal in the future+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ };+if (message) {if (messageType === "push") {modalTemplate = html`- <or-rule-notification-modal title="push-notification" .action="${this.action}">- <or-rule-form-push-notification .action="${this.action}"></or-rule-form-push-notification>+ <or-rule-notification-modal title="push-notification" .action="${this.action}"+ @or-rules-notification-modal-cancel="${onModalCancel}"+ @or-rules-notification-modal-ok="${onModalOk}">+ <or-rule-form-push-notification .message="${message as PushNotificationMessage}"></or-rule-form-push-notification></or-rule-notification-modal>`;}- if (messageType === "email") {+ else if (messageType === "email") {+ modalTemplate = html`+ <or-rule-notification-modal title="email" .action="${this.action}"+ @or-rules-notification-modal-cancel="${onModalCancel}"+ @or-rules-notification-modal-ok="${onModalOk}">+ <or-rule-form-email-message .message="${message as EmailNotificationMessage}"></or-rule-form-email-message>+ </or-rule-notification-modal>+ `;+ }++ else if(messageType === "localized") {+ const notificationConfig = this.config?.notifications?.[manager.displayRealm] || this.config?.notifications?.["default"];+ const languages = [...new Set([+ ...(notificationConfig?.languages || []),+ ...(Object.keys((message as LocalizedNotificationMessage).languages || {}) || [])+ ])] as string[];+ const defaultLang = notificationConfig?.defaultLanguage || manager.config.defaultLanguage;+ if(languages.length === 0 && defaultLang) {+ languages.push(defaultLang);+ }+ const defaultLangHasChanged = defaultLang !== (message as LocalizedNotificationMessage).defaultLanguage;+ const type = this.actionType === ActionType.EMAIL_LOCALIZED ? "email" : "push";+ const title = this.actionType === ActionType.EMAIL_LOCALIZED ? "email" : "push-notification";modalTemplate = html`- <or-rule-notification-modal title="email" .action="${this.action}">- <or-rule-form-email-message .action="${this.action}"></or-rule-form-email-message>+ <or-rule-notification-modal title="${title}" .action="${this.action}"+ @or-rules-notification-modal-cancel="${onModalCancel}"+ @or-rules-notification-modal-ok="${onModalOk}">+ <or-rule-form-localized .message="${message}" .type="${type}" .languages="${languages}" .defaultLang="${defaultLang}"+ .wrongLanguage="${defaultLangHasChanged}"+ ></or-rule-form-localized></or-rule-notification-modal>`;}diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.tsindex 8297555cc..28b71de57 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts@@ -143,6 +143,11 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements}}+ disconnectedCallback() {+ this.removeEventListener(OrRulesJsonRuleChangedEvent.NAME, this._onJsonRuleChanged);+ return super.disconnectedCallback();+ }+public set ruleset(ruleset: RulesetUnion) {if (this._ruleset === ruleset) {return;diff --git a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.tsindex 87e87166e..4f50201d3 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts@@ -5,13 +5,14 @@ import "./or-rule-asset-query";import {ActionType, getAssetTypeFromQuery, RulesConfig} from "../index";import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";import {+ AbstractNotificationMessageUnion,AlarmSeverity,AlarmStatus,Asset,AssetModelUtil,- AssetTypeInfo,+ AssetTypeInfo, EmailNotificationMessage,HTTPMethod,- JsonRule,+ JsonRule, LocalizedNotificationMessage, PushNotificationMessage,RuleActionAlarm,RuleActionNotification,RuleActionUnion,@@ -23,7 +24,7 @@ import i18next from "i18next";import {InputType} from "@openremote/or-mwc-components/or-mwc-input";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";-import {Util} from "@openremote/core";+import {manager, Util} from "@openremote/core";import "./or-rule-action-attribute";import "./or-rule-action-notification";import "./or-rule-action-webhook";@@ -39,19 +40,31 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):let addAssetTypes = true;let addWait = true;let addAlarm = true;- let addNotification = true;+ let addEmailNotification = true;+ let addEmailLocalizedNotification = true;let addPushNotification = true;+ let addPushLocalizedNotification = true;let addWebhook = true;+ let multiLanguage = false;+if (config && config.controls && config.controls.allowedActionTypes) {addAssetTypes = config.controls.allowedActionTypes.indexOf(ActionType.ATTRIBUTE) >= 0;addWait = config.controls.allowedActionTypes.indexOf(ActionType.WAIT) >= 0;addAlarm = config.controls.allowedActionTypes.indexOf(ActionType.ALARM) >= 0;- addNotification = config.controls.allowedActionTypes.indexOf(ActionType.EMAIL) >= 0;+ addEmailNotification = config.controls.allowedActionTypes.indexOf(ActionType.EMAIL) >= 0;+ addEmailLocalizedNotification = config.controls.allowedActionTypes.indexOf(ActionType.EMAIL_LOCALIZED) >= 0;addPushNotification = config.controls.allowedActionTypes.indexOf(ActionType.PUSH_NOTIFICATION) >= 0;+ addPushLocalizedNotification = config.controls.allowedActionTypes.indexOf(ActionType.PUSH_LOCALIZED) >= 0;addWebhook = config.controls.allowedActionTypes.indexOf(ActionType.WEBHOOK) >= 0;}+ // If the RulesConfig has an entry for notifications, check if there are languages configured.+ // When there are, new notifications will be a "multi-language notification", with a different modal form.+ if (config?.notifications) {+ multiLanguage = Object.entries(config.notifications).filter(x =>+ (x[0] === manager.displayRealm || x[0] === "default") && x[1] !== undefined).length > 0;+ }const menu: (ListItem | null)[] = [];@@ -74,11 +87,11 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):menu.sort(Util.sortByString((listItem) => listItem?.value!));menu.push(null); // divider- if (addNotification) {+ if (addEmailNotification) {menu.push({text: i18next.t("email"),icon: "email",- value: ActionType.EMAIL,+ value: multiLanguage && addEmailLocalizedNotification ? ActionType.EMAIL_LOCALIZED : ActionType.EMAIL,styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}} as ListItem);}@@ -87,7 +100,7 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):menu.push({text: i18next.t("push-notification"),icon: "cellphone-message",- value: ActionType.PUSH_NOTIFICATION,+ value: multiLanguage && addPushLocalizedNotification ? ActionType.PUSH_LOCALIZED : ActionType.PUSH_NOTIFICATION,styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}} as ListItem);}@@ -116,7 +129,7 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):icon: "webhook",value: ActionType.WEBHOOK,styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}- })+ });}return menu;@@ -323,7 +336,7 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {break;case "notification":action = action as RuleActionNotification- if (type === "push") {+ if (type === ActionType.PUSH_NOTIFICATION || type === ActionType.PUSH_LOCALIZED) {buttonIcon = "cellphone-message";buttonColor = NOTIFICATION_COLOR;} else {@@ -368,10 +381,11 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {template = html`<span>WAIT NOT IMPLEMENTED</span>`;break;case ActionType.PUSH_NOTIFICATION:- template = html`<or-rule-action-notification id="push-notification" .rule="${this.rule}" .action="${action}" .actionType="${ActionType.PUSH_NOTIFICATION}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-notification>`;- break;+ case ActionType.PUSH_LOCALIZED:case ActionType.EMAIL:- template = html`<or-rule-action-notification id="email-notification" .rule="${this.rule}" .action="${action}" .actionType="${ActionType.EMAIL}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-notification>`;+ case ActionType.EMAIL_LOCALIZED:+ const id = type + "-notification";+ template = html`<or-rule-action-notification id="${id}" .rule="${this.rule}" .action="${action}" .actionType="${type}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-notification>`;break;case ActionType.WEBHOOK:template = html`<or-rule-action-webhook .rule="${this.rule}" .action="${action}" .actionType="${ActionType.WEBHOOK}"></or-rule-action-webhook>`;@@ -431,6 +445,12 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {break;case "notification":const type = action.notification && action.notification.message && action.notification.message.type ? action.notification.message.type : action.action;+ if(type === "localized") {+ const messages = Object.values((action.notification!.message as LocalizedNotificationMessage).languages!);+ if(messages && messages.length > 0) {+ return messages[0].type + "_localized";+ }+ }return type;break;case "alarm":@@ -531,22 +551,57 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {action = action as RuleActionNotification;action.action = "notification";action.notification = {+ name: this.rule.name,message: {type: "email",subject: "%RULESET_NAME%",html: "%TRIGGER_ASSETS%"- }+ } as EmailNotificationMessage};- } else if (value === ActionType.PUSH_NOTIFICATION) {+ } else if (value === ActionType.PUSH_NOTIFICATION) {action = action as RuleActionNotification;action.action = "notification";action.notification = {+ name: this.rule.name,message: {type: "push",title: "%RULESET_NAME%",- body: "%TRIGGER_ASSETS%"- }+ body: "%TRIGGER_ASSETS%",+ action: {+ openInBrowser: false+ }+ } as PushNotificationMessage+ };+ } else if (value === ActionType.EMAIL_LOCALIZED || value === ActionType.PUSH_LOCALIZED) {+ action = action as RuleActionNotification;+ action.action = "notification";+ const locale = this.config?.notifications?.[manager.displayRealm]?.defaultLanguage || this.config?.notifications?.["default"]?.defaultLanguage || manager.config.defaultLanguage || "en";+ const languages: { [p: string]: AbstractNotificationMessageUnion } = {};+ if(value === ActionType.EMAIL_LOCALIZED) {+ languages[locale] = {+ type: "email",+ subject: "%RULESET_NAME%",+ html: "%TRIGGER_ASSETS%"+ } as EmailNotificationMessage;+ } else {+ languages[locale] = {+ type: "push",+ title: "%RULESET_NAME%",+ body: "%TRIGGER_ASSETS%",+ action: {+ openInBrowser: false+ }+ } as PushNotificationMessage;+ }+ action.notification = {+ name: this.rule.name,+ message: {+ type: "localized",+ defaultLanguage: locale,+ languages: languages+ } as LocalizedNotificationMessage};+} else {action.action = "write-attribute";action.target = {diff --git a/yarn.lock b/yarn.lockindex 3de988fcb..1c6ef4998 100644--- a/yarn.lock+++ b/yarn.lock@@ -2413,6 +2413,7 @@ __metadata:dependencies:"@openremote/or-app": "npm:^1.1.0""@openremote/util": "workspace:*"+ iso-639-1: "npm:^3.1.3"languageName: unknownlinkType: soft@@ -2757,6 +2758,7 @@ __metadata:"@openremote/util": "workspace:*""@types/shortid": "npm:^0.0.29"ace-builds: "npm:^1.4.13"+ iso-639-1: "npm:^3.1.3"linqts: "npm:^1.12.6"lit: "npm:^2.0.2"moment: "npm:^2.29.4"@@ -6693,6 +6695,13 @@ __metadata:languageName: nodelinkType: hard+"iso-639-1@npm:^3.1.3":+ version: 3.1.3+ resolution: "iso-639-1@npm:3.1.3"+ checksum: 10c0/416112e3df8b00efd4dabda33b581d3323e77c217a05b4c262dffacff89ee17b73debff2673a1ea0c7a36bd7dfb4f6d234249b1addacf36aa7bb70481a462cc0+ languageName: node+ linkType: hard+"isobject@npm:^3.0.1":version: 3.0.1resolution: "isobject@npm:3.0.1"