Skip to content

armgit / core

Public Imported from GitHub
0

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

Notification bug fixes and enhancements add linkedUsers action target

Rich Turner67ff86cc6bd1
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 89e060245..79133363f 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -1060,22 +1060,34 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
public List<UserAssetLink> findUserAssetLinks(String realm, String userId, String assetId) {
+ return findUserAssetLinks(
+ realm,
+ userId != null ? Collections.singletonList(userId) : null,
+ assetId != null ? Collections.singletonList(assetId) : null);
+ }
+
+ public List<UserAssetLink> findUserAssetLinks(String realm, List<String> userIds, List<String> assetIds) {
+
+ if (realm == null && (userIds == null || userIds.isEmpty()) && (assetIds == null || assetIds.isEmpty())) {
+ return Collections.emptyList();
+ }
+
return persistenceService.doReturningTransaction(entityManager -> {
StringBuilder sb = new StringBuilder();
Map<String, Object> parameters = new HashMap<>(3);
sb.append("select ua from UserAssetLink ua where 1=1");
if (!isNullOrEmpty(realm)) {
- sb.append(" and ua.id.realm = :realm");
+ sb.append(" and ua.id.realm in :realm");
parameters.put("realm", realm);
}
- if (!isNullOrEmpty(userId)) {
- sb.append(" and ua.id.userId = :userId");
- parameters.put("userId", userId);
+ if (userIds != null && !userIds.isEmpty()) {
+ sb.append(" and ua.id.userId in :userId");
+ parameters.put("userId", userIds);
}
- if (!isNullOrEmpty(assetId)) {
- sb.append(" and ua.id.assetId = :assetId");
- parameters.put("assetId", assetId);
+ if (assetIds != null && !assetIds.isEmpty()) {
+ sb.append(" and ua.id.assetId in :assetId");
+ parameters.put("assetId", assetIds);
}
sb.append(" order by ua.createdOn desc");
diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
index 721e46a6c..bc58a97f2 100644
--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
@@ -28,10 +28,9 @@ import org.openremote.model.notification.AbstractNotificationMessage;
import org.openremote.model.notification.EmailNotificationMessage;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationSendResult;
-import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.UserQuery;
-import org.openremote.model.query.filter.*;
-import org.openremote.model.security.User;
+import org.openremote.model.query.filter.TenantPredicate;
+import org.openremote.model.query.filter.UserAssetPredicate;
import org.openremote.model.util.TextUtil;
import org.simplejavamail.email.Email;
import org.simplejavamail.email.EmailBuilder;
@@ -146,73 +145,55 @@ public class EmailNotificationHandler implements NotificationHandler {
targets.forEach(target -> {
Notification.TargetType targetType = target.getType();
String targetId = target.getId();
+ UserQuery userQuery = new UserQuery();
switch (targetType) {
case TENANT:
+ userQuery.tenant(new TenantPredicate(targetId));
case USER:
- // Find all users in this tenant or by id
- User[] users = targetType == Notification.TargetType.TENANT
- ? managerIdentityService
- .getIdentityProvider()
- .queryUsers(new UserQuery().tenant(new TenantPredicate(targetId)))
- : managerIdentityService
- .getIdentityProvider()
- .queryUsers(new UserQuery().ids(targetId));
-
- if (users.length == 0) {
- if (targetType == Notification.TargetType.USER) {
- LOG.info("User not found: " + targetId);
- } else {
- LOG.info("No users found in target realm: " + targetId);
- }
- return;
- }
-
- mappedTargets.addAll(
- Arrays.stream(users)
- .filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
- .map(user -> {
- Notification.Target userAssetTarget = new Notification.Target(Notification.TargetType.USER, user.getId());
- userAssetTarget.setData(new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail()));
- return userAssetTarget;
- })
- .collect(Collectors.toList()));
+ userQuery.ids(targetId);
break;
case CUSTOM:
// Nothing to do here
mappedTargets.add(new Notification.Target(targetType, targetId));
break;
case ASSET:
- // Find descendant assets with email attribute
- List<Asset<?>> assets = assetStorageService.findAll(
- new AssetQuery()
- .select(new AssetQuery.Select()
- .attributes(Asset.EMAIL.getName()))
- .paths(new PathPredicate(targetId))
- .attributes(new AttributePredicate(
- new StringPredicate(Asset.EMAIL.getName()),
- new ValueEmptyPredicate().negate(true))));
-
- if (assets.isEmpty()) {
- LOG.fine("No assets with email attribute descendants of target asset");
- return;
+ // If asset has an email attribute include that in the targets
+ Asset<?> asset = assetStorageService.find(targetId);
+ if (asset != null) {
+ asset.getEmail().map(email -> {
+ Notification.Target assetTarget = new Notification.Target(Notification.TargetType.ASSET, asset.getId());
+ assetTarget.setData(new EmailNotificationMessage.Recipient(asset.getName(), email));
+ return assetTarget;
+ }
+ ).ifPresent(mappedTargets::add);
}
- mappedTargets.addAll(assets.stream()
- .map(asset -> {
- Notification.Target assetTarget =new Notification.Target(Notification.TargetType.ASSET, asset.getId());
- assetTarget.setData(new EmailNotificationMessage.Recipient(
- asset.getName(),
- asset.getEmail()
- .orElse(null)));
- return assetTarget;
- })
- .collect(Collectors.toList()));
+ userQuery.asset(new UserAssetPredicate(targetId));
break;
}
+
+ // Filter users that don't have disabled email notifications attribute
+ List<Notification.Target> userTargets = Arrays.stream(managerIdentityService
+ .getIdentityProvider()
+ .queryUsers(userQuery))
+ .filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
+ .filter(user -> !TextUtil.isNullOrEmpty(user.getEmail()))
+ .map(user -> {
+ Notification.Target emailTarget = new Notification.Target(Notification.TargetType.USER, user.getId());
+ emailTarget.setData(new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail()));
+ return emailTarget;
+ }).toList();
+
+ if (userTargets.isEmpty()) {
+ LOG.info("No email targets have been mapped");
+ } else {
+ mappedTargets.addAll(userTargets);
+ }
});
}
+
EmailNotificationMessage email = (EmailNotificationMessage)message;
// Map to/cc/bcc into a custom target for traceability in sent notifications
@@ -222,8 +203,7 @@ public class EmailNotificationHandler implements NotificationHandler {
addresses.addAll(
email.getTo().stream()
.map(EmailNotificationMessage.Recipient::getAddress)
- .map(address -> "to:" + address)
- .collect(Collectors.toList()));
+ .map(address -> "to:" + address).toList());
email.setTo((List<EmailNotificationMessage.Recipient>) null);
}
@@ -231,8 +211,7 @@ public class EmailNotificationHandler implements NotificationHandler {
addresses.addAll(
email.getCc().stream()
.map(EmailNotificationMessage.Recipient::getAddress)
- .map(address -> "cc:" + address)
- .collect(Collectors.toList()));
+ .map(address -> "cc:" + address).toList());
email.setCc((List<EmailNotificationMessage.Recipient>) null);
}
@@ -240,8 +219,7 @@ public class EmailNotificationHandler implements NotificationHandler {
addresses.addAll(
email.getBcc().stream()
.map(EmailNotificationMessage.Recipient::getAddress)
- .map(address -> "bcc:" + address)
- .collect(Collectors.toList()));
+ .map(address -> "bcc:" + address).toList());
email.setBcc((List<EmailNotificationMessage.Recipient>) null);
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index a4d82bb20..c3538d2b5 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -27,13 +27,13 @@ import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.*;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.container.message.MessageBrokerService;
-import org.openremote.model.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
+import org.openremote.model.PersistenceEvent;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.UserAssetLink;
import org.openremote.model.asset.impl.ConsoleAsset;
@@ -44,7 +44,10 @@ import org.openremote.model.notification.NotificationSendResult;
import org.openremote.model.notification.PushNotificationMessage;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.UserQuery;
-import org.openremote.model.query.filter.*;
+import org.openremote.model.query.filter.AttributePredicate;
+import org.openremote.model.query.filter.NameValuePredicate;
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.User;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
@@ -201,112 +204,71 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
Notification.TargetType targetType = target.getType();
String targetId = target.getId();
+ AssetQuery assetQuery = new AssetQuery()
+ .select(new AssetQuery.Select().excludeAttributes())
+ .types(ConsoleAsset.class)
+ .attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE)));
switch (targetType) {
+ case TENANT ->
+ // Any console assets in the target realm
+ assetQuery.tenant(new TenantPredicate(targetId));
+ case USER ->
+ // Any console assets linked to the target user
+ assetQuery.userIds(targetId);
+ case ASSET ->
+ // Any users linked to this asset and then their linked console assets
+ assetQuery.userIds(
+ assetStorageService.findUserAssetLinks(null, null, targetId)
+ .stream()
+ .map(ual -> ual.getId().getUserId())
+ .toArray(String[]::new));
+ }
- case TENANT:
- // Get all console assets with a push provider defined within the specified tenant
- List<Asset<?>> consoleAssets = assetStorageService.findAll(
- new AssetQuery()
- .select(new AssetQuery.Select().excludeAttributes())
- .tenant(new TenantPredicate(targetId))
- .types(ConsoleAsset.class)
- .attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE))));
-
- // Get all user ids which have pushNotificationsDisabled set to false
- String[] userIds = Arrays.stream(managerIdentityService
- .getIdentityProvider()
- .queryUsers(new UserQuery().tenant(new TenantPredicate((targetId))))
- )
- .filter(user -> Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
- .map(User::getId)
- .toArray(String[]::new);
-
- String[] assetIds = assetStorageService.findUserAssetLinks(targetId, null, null).stream()
- .filter(userAssetLink -> Arrays.stream(userIds).anyMatch(userId->userId.equals(userAssetLink.getId().getUserId())))
- .map(userAssetLink -> userAssetLink.getId().getAssetId())
- .toArray(String[]::new);
-
- //Remove consoleAssets which are linked to an User which has pushNotificationsDisabled set to false
- consoleAssets = consoleAssets.stream()
- .filter(consoleAsset -> Arrays.stream(assetIds).noneMatch(assetId -> assetId.equals(consoleAsset.getId())))
- .collect(Collectors.toList());
-
- mappedTargets.addAll(
- consoleAssets
- .stream()
- .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
- .collect(Collectors.toList()));
- break;
-
- case USER:
- Optional<User> user = Arrays.stream(managerIdentityService
- .getIdentityProvider()
- .queryUsers(new UserQuery().ids(targetId))).findFirst();
-
- if (user.isPresent() && !Boolean.parseBoolean(user.get().getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0))) {
-
- // Get all console assets linked to the specified user
- String[] ids = assetStorageService.findUserAssetLinks(null, targetId, null)
- .stream()
- .map(userAssetLink -> userAssetLink.getId().getAssetId()).toArray(String[]::new);
-
- if (ids.length > 0) {
- mappedTargets.addAll(
- assetStorageService.findAll(
- new AssetQuery()
- .select(new AssetQuery.Select().excludeAttributes())
- .ids(ids)
- .types(ConsoleAsset.class)
- .attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE))))
- .stream()
- .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
- .collect(Collectors.toList()));
- }
+ List<String> consoleAssetIds = assetStorageService.findAll(assetQuery).stream().map(Asset::getId).distinct().toList();
+
+ if (!consoleAssetIds.isEmpty()) {
+ // Special handling if target type is user (don't need to find all linked users)
+ if (targetType == Notification.TargetType.USER) {
+ User[] matchedUsers = managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().ids(targetId));
+ if (matchedUsers.length != 1) {
+ consoleAssetIds = Collections.emptyList();
} else {
- LOG.fine("No console assets linked to target user");
- return;
+ boolean disabled = Boolean.parseBoolean(matchedUsers[0].getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0));
+ if (disabled) {
+ consoleAssetIds = Collections.emptyList();
+ }
}
+ } else {
+ // Any consoles linked to users; the user should not have push notification disabled attribute
+ Map<String, List<String>> consoleUserIdsMap = assetStorageService.findUserAssetLinks(null, null, consoleAssetIds)
+ .stream()
+ .map(UserAssetLink::getId)
+ .collect(Collectors.groupingBy(UserAssetLink.Id::getAssetId, Collectors.mapping(UserAssetLink.Id::getUserId, Collectors.toList())));
+
+ consoleAssetIds = consoleAssetIds.stream()
+ .filter(consoleId -> {
+ if (!consoleUserIdsMap.containsKey(consoleId)) {
+ return true;
+ }
+
+ long count = Arrays.stream(managerIdentityService.getIdentityProvider().queryUsers(
+ new UserQuery().ids(consoleUserIdsMap.get(consoleId).toArray(new String[0]))))
+ .filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
+ .count();
+ return count > 0;
+ }).collect(Collectors.toList());
+ }
+ }
- break;
-
- case ASSET:
- // Find all console descendants of the specified asset
- consoleAssets = assetStorageService.findAll(new AssetQuery()
- .select(new AssetQuery.Select().excludeAttributes())
- .paths(new PathPredicate(targetId))
- .types(ConsoleAsset.class)
- .attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE))));
-
- UserAssetLink[] userAssetLinks = consoleAssets.stream()
- .map(consoleAsset -> assetStorageService.findUserAssetLinks(null, null, consoleAsset.getId()))
- .flatMap(Collection::stream)
- .toArray(UserAssetLink[]::new);
-
- // Get all user ids which have pushNotificationsDisabled set to false
- assetIds = Arrays.stream(userAssetLinks)
- .filter(userAssetLink -> Arrays.stream(managerIdentityService
- .getIdentityProvider()
- .queryUsers(new UserQuery().asset(new UserAssetPredicate(userAssetLink.getId().getAssetId())))
- )
- .filter(user1 -> Boolean.parseBoolean(user1.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
- .map(User::getId)
- .anyMatch(userId -> userId.equals(userAssetLink.getId().getUserId()))
- ).map(userAssetLink -> userAssetLink.getId().getAssetId())
- .toArray(String[]::new);
-
- //Remove consoleAssets which are linked to an User which has pushNotificationsDisabled set to false
- consoleAssets = consoleAssets.stream()
- .filter(consoleAsset -> Arrays.stream(assetIds).noneMatch(assetId -> assetId.equals(consoleAsset.getId())))
- .collect(Collectors.toList());
-
-
- mappedTargets.addAll(
- consoleAssets
- .stream()
- .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
- .collect(Collectors.toList()));
- break;
+ if (consoleAssetIds.isEmpty()) {
+ LOG.info("No console asset targets have been mapped");
+ } else {
+ mappedTargets.addAll(
+ consoleAssetIds
+ .stream()
+ .map(id -> new Notification.Target(Notification.TargetType.ASSET, id))
+ .toList());
}
});
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index 48fbc4774..6c938aba9 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -34,6 +34,7 @@ import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.AttributePredicate;
+import org.openremote.model.query.filter.UserAssetPredicate;
import org.openremote.model.rules.*;
import org.openremote.model.rules.json.*;
import org.openremote.model.util.TextUtil;
@@ -725,8 +726,7 @@ public class JsonRulesBuilder extends RulesBuilder {
protected static RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, PredictedDatapoints predictedDatapointsFacade) {
- if (ruleAction instanceof RuleActionNotification) {
- RuleActionNotification notificationAction = (RuleActionNotification) ruleAction;
+ if (ruleAction instanceof RuleActionNotification notificationAction) {
if (notificationAction.notification != null) {
@@ -779,6 +779,8 @@ public class JsonRulesBuilder extends RulesBuilder {
&& ruleAction.target.assets == null
&& ruleAction.target.matchedAssets == null) {
targetType = Notification.TargetType.USER;
+ } else if (ruleAction.target.linkedUsers != null && ruleAction.target.linkedUsers) {
+ targetType = Notification.TargetType.USER;
} else if (ruleAction.target.custom != null
&& ruleAction.target.conditionAssets == null
&& ruleAction.target.assets == null
@@ -802,14 +804,12 @@ public class JsonRulesBuilder extends RulesBuilder {
}
}
- if (ruleAction instanceof RuleActionWriteAttribute) {
+ if (ruleAction instanceof RuleActionWriteAttribute attributeAction) {
if (targetIsNotAssets(ruleAction.target)) {
return null;
}
- RuleActionWriteAttribute attributeAction = (RuleActionWriteAttribute) ruleAction;
-
if (TextUtil.isNullOrEmpty(attributeAction.attributeName)) {
log(Level.WARNING, "Attribute name is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
return null;
@@ -836,15 +836,13 @@ public class JsonRulesBuilder extends RulesBuilder {
log(Level.FINEST, "Invalid delay for wait rule action so skipping: " + rule.name + " '" + actionsName + "' action index " + index);
}
- if (ruleAction instanceof RuleActionUpdateAttribute) {
+ if (ruleAction instanceof RuleActionUpdateAttribute attributeUpdateAction) {
if (targetIsNotAssets(ruleAction.target)) {
log(Level.FINEST, "Invalid target update attribute rule action so skipping: " + rule.name + " '" + actionsName + "' action index " + index);
return null;
}
- RuleActionUpdateAttribute attributeUpdateAction = (RuleActionUpdateAttribute) ruleAction;
-
if (TextUtil.isNullOrEmpty(attributeUpdateAction.attributeName)) {
log(Level.WARNING, "Attribute name is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
return null;
@@ -853,7 +851,7 @@ public class JsonRulesBuilder extends RulesBuilder {
List<String> matchingAssetIds;
if (ruleAction.target == null || ruleAction.target.assets == null) {
- if (ruleAction.target != null && ruleAction.target.users != null) {
+ if (targetIsNotAssets(ruleAction.target)) {
throw new IllegalStateException("Cannot use action type '" + RuleActionUpdateAttribute.class.getSimpleName() + "' with user target");
}
matchingAssetIds = new ArrayList<>(getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts));
@@ -1028,17 +1026,22 @@ public class JsonRulesBuilder extends RulesBuilder {
return triggerState != null ? triggerState.getUnmatchedAssetIds() : Collections.emptyList();
}
- if (conditionStateMap != null && target.matchedAssets != null) {
+ if (conditionStateMap != null && (target.matchedAssets != null || (target.linkedUsers != null && target.linkedUsers))) {
List<String> compareAssetIds = conditionStateMap.values().stream()
.flatMap(triggerState ->
- useUnmatched ? triggerState.getUnmatchedAssetIds().stream() : triggerState.getMatchedAssetIds().stream())
- .collect(Collectors.toList());
+ useUnmatched ? triggerState.getUnmatchedAssetIds().stream() : triggerState.getMatchedAssetIds().stream()).toList();
- return facts.matchAssetState(target.matchedAssets)
- .map(AssetState::getId)
- .distinct()
- .filter(compareAssetIds::contains)
- .collect(Collectors.toList());
+ if (target.matchedAssets != null) {
+ return facts.matchAssetState(target.matchedAssets)
+ .map(AssetState::getId)
+ .distinct()
+ .filter(compareAssetIds::contains)
+ .collect(Collectors.toList());
+ }
+
+ // Find linked users
+ return compareAssetIds.stream().flatMap(assetId ->
+ usersFacade.getResults(new UserQuery().asset(new UserAssetPredicate(assetId)))).collect(Collectors.toList());
}
if (target.assets != null) {
@@ -1070,7 +1073,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
protected static boolean targetIsNotAssets(RuleActionTarget target) {
- return target != null && target.users != null;
+ return target != null && (target.users != null || (target.linkedUsers != null && target.linkedUsers));
}
protected static void log(Level level, String message) {
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 38ed9b7f8..84ce671fa 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -466,5 +466,6 @@
"createUserFailed": "Create user failed",
"saveUserFailed": "Save user failed",
"invalidUsername": "Username must be 3-255 alpha numerical characters",
- "invalidEmail": "Invalid email address"
+ "invalidEmail": "Invalid email address",
+ "linked": "Linked"
}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java
index 7c0b38d67..10eaf27f2 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java
@@ -31,6 +31,7 @@ import org.openremote.model.query.UserQuery;
* <li>{@link #matchedAssets} - Assets that matched with additional {@link AssetQuery} applied</li>
* <li>{@link #assets}</li>
* <li>{@link #users}</li>
+ * <li>{@link #linkedUsers} - Users linked to matched assets</li>
* <li>{@link #custom} - A custom string that the Rule Action interprets to generate targets</li>
* </ol>
*/
@@ -39,5 +40,6 @@ public class RuleActionTarget {
public AssetQuery matchedAssets;
public AssetQuery assets;
public UserQuery users;
+ public Boolean linkedUsers;
public String custom;
}
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.groovy
index 54a5483b4..d2e52eeec 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
@@ -15,6 +15,7 @@ import org.openremote.manager.rules.RulesetDeployment
import org.openremote.manager.rules.RulesetStorageService
import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
import org.openremote.manager.setup.SetupService
+import org.openremote.model.asset.UserAssetLink
import org.openremote.test.setup.KeycloakTestSetup
import org.openremote.test.setup.ManagerTestSetup
import org.openremote.model.asset.Asset
@@ -53,9 +54,9 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
def "Turn all lights off when console exits the residence geofence"() {
- List<PushNotificationMessage> notificationMessages = []
+ List<PushNotificationMessage> pushMessages = []
List<Email> emailMessages = []
- List<Notification.Target> targets = []
+ List<Notification.Target> pushTargets = []
List<Notification.Target> emailTargets = []
given: "the geofence notifier debounce is set to a small value for testing"
@@ -86,8 +87,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
mockPushNotificationHandler.isValid() >> true
mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
id, source, sourceId, target, message ->
- notificationMessages << message
- targets << target
+ pushMessages << message
+ pushTargets << target
callRealMethod()
}
// Assume sent to FCM
@@ -185,10 +186,15 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "the console should have been registered and a geofence refresh notification should have been sent"
conditions.eventually {
assert consoleRegistration.id != null
- assert notificationMessages.size() == 1
+ assert pushMessages.size() == 1
}
- when: "the console location is set to the apartment"
+ when:"an additional user is linked to this console (to help with testing)"
+ assetStorageService.storeUserAssetLinks(
+ Collections.singletonList(new UserAssetLink(keycloakTestSetup.tenantBuilding.getRealm(), keycloakTestSetup.testuser2Id, consoleRegistration.id))
+ )
+
+ and: "the console location is set to the apartment"
assetProcessingService.sendAttributeEvent(new AttributeEvent(consoleRegistration.id, Asset.LOCATION.name, ManagerTestSetup.SMART_BUILDING_LOCATION), AttributeEvent.Source.CLIENT)
then: "the consoles location should have been updated"
@@ -225,24 +231,35 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
assert !bathRoomAsset.getAttribute("lightSwitch").get().value.get()
}
- and: "a notification should have been sent to the console"
+ and: "a push notification should have been sent to the console via the asset target with the title 'Test title'"
+ conditions.eventually {
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 1
+ assert pushTargets.any {it.type == Notification.TargetType.ASSET && it.id == consoleRegistration.id}
+ }
+
+ and: "a push notification should have been sent to the console via the user target with the title 'Linked user test'"
+ conditions.eventually {
+ assert pushMessages.findAll {it.title == "Linked user test"}.size() == 1
+ assert pushTargets.any {it.type == Notification.TargetType.ASSET && it.id == consoleRegistration.id}
+ }
+
+ and: "an email notification should have been sent to [email protected] with the triggered asset in the body"
conditions.eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 1
- assert targets[0].type == Notification.TargetType.ASSET
- assert targets[0].id == consoleRegistration.id
+ assert emailMessages.any {it.recipients.size() == 1
+ && it.recipients[0].address == "[email protected]"
+ && it.HTMLText == "<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 email should have been sent to [email protected] with the triggered asset in the body"
+ and : "an email notification should have been sent to the asset's linked user(s) (only testuser2 has email notifications enabled)"
conditions.eventually {
- assert emailMessages.size() == 1
- assert emailMessages[0].recipients.size() == 1
- assert emailMessages[0].recipients[0].address == "[email protected]"
- assert emailMessages[0].HTMLText == "<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>"
+ assert emailMessages.any {it.recipients.size() == 1
+ && it.recipients[0].address == "[email protected]"
+ && it.HTMLText == "<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: "after a few seconds the rule should not have fired again"
new PollingConditions(timeout: 5, initialDelay: 1).eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 1
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 1
}
when: "the console device moves back inside the home geofence (as defined in the rule)"
@@ -259,8 +276,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console"
conditions.eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 2
- assert targets[1].id == consoleRegistration.id
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 2
}
when: "the console sends a location update with a new location but still outside the geofence"
@@ -270,7 +286,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "after a few seconds the rule should not have fired again"
new PollingConditions(timeout: 5, initialDelay: 1).eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 2
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 2
}
when: "the ruleset is modified to add a 4hr recurrence per asset"
@@ -288,8 +304,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "another notification should have been sent to the console when rule is redeployed"
conditions.eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 3
- assert targets[2].id == consoleRegistration.id
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 3
}
when: "the console device moves back inside the home geofence (as defined in the rule)"
@@ -307,7 +322,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "after a few seconds the rule should not have fired again"
new PollingConditions(timeout: 5, initialDelay: 1).eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 3
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 3
}
when: "the console device moves back inside the home geofence (as defined in the rule)"
@@ -328,8 +343,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console"
conditions.eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 4
- assert targets[3].id == consoleRegistration.id
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 4
+ assert pushTargets[3].id == consoleRegistration.id
}
when: "the Rules PAUSE_SCHEDULER is overridden to facilitate testing"
@@ -384,7 +399,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
}
and: "no notification should have been sent as outside the validity period"
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 4
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 4
when: "the pause elapses"
engine.unPauseRuleset(deployment)
@@ -407,8 +422,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "another notification should have been sent as inside the validity period"
conditions.eventually {
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 5
- assert targets[4].id == consoleRegistration.id
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 5
}
when: "the un-pause elapses"
@@ -431,7 +445,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
}
and: "no notification should have been sent as outside the validity period"
- assert notificationMessages.findAll {it.title == "Test title"}.size() == 5
+ assert pushMessages.findAll {it.title == "Test title"}.size() == 5
when: "the pause elapses"
engine.unPauseRuleset(deployment)
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
index a7f1d1c78..679864306 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
@@ -51,6 +51,34 @@
}
}
},
+ {
+ "action": "notification",
+ "target": {
+ "linkedUsers": true
+ },
+ "notification": {
+ "name": "linkedPushTest",
+ "message": {
+ "type": "push",
+ "title": "Linked user test"
+ }
+ }
+ },
+ {
+ "action": "notification",
+ "target": {
+ "linkedUsers": true
+ },
+ "notification": {
+ "name": "linkedEmailTest",
+ "message": {
+ "type": "email",
+ "subject": "%RULESET_NAME%",
+ "html": "%TRIGGER_ASSETS%",
+ "title": "Linked user test"
+ }
+ }
+ },
{
"action": "notification",
"notification": {
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
index da58afca8..7b548a80b 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
@@ -95,6 +95,8 @@ export class OrRuleActionNotification extends LitElement {
if (action.target) {
if (action.target.users && !action.target.conditionAssets && !action.target.matchedAssets && !action.target.assets) {
targetType = NotificationTargetType.USER;
+ } else if (action.target.linkedUsers) {
+ targetType = NotificationTargetType.USER;
} else if (action.target.custom !== undefined && !action.target.conditionAssets && !action.target.matchedAssets && !action.target.assets) {
targetType = NotificationTargetType.CUSTOM;
}
@@ -190,6 +192,9 @@ export class OrRuleActionNotification extends LitElement {
});
}
values = [...additionalValues, ...values];
+ } else if (targetType === NotificationTargetType.USER) {
+ // Add additional option for linked users
+ values = [["linkedUsers", i18next.t("linked")], ...values];
}
return html`
@@ -306,9 +311,14 @@ export class OrRuleActionNotification extends LitElement {
protected _onTargetChanged(targetType: NotificationTargetType, value: string | undefined) {
switch (targetType) {
case NotificationTargetType.USER:
- if(value){
- const users:UserQuery = {ids: [value]}
- this.action.target = {users: users}
+ if (value === "linkedUsers") {
+ this.action.target = {
+ linkedUsers: true
+ }
+ } else if (value) {
+ this.action.target = {
+ users: {ids: [value]}
+ }
}
break;
case NotificationTargetType.CUSTOM:
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.ts
index 14544c4b9..cb0720ac0 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
@@ -300,7 +300,7 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
}
}
- if(readonly) {
+ if (readonly) {
typeTemplate = html`
<div id="type" style="--or-mwc-input-color: #${buttonColor}">
<or-mwc-input type="${InputType.BUTTON}" .icon="${buttonIcon || ""}"></or-mwc-input>