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
JSON rules action refactor and rules editor updates
Rich Turner341ded20dc90
diff --git a/deployment/manager/shared/locales/en/or.json b/deployment/manager/shared/locales/en/or.jsonindex 2f76341a1..8b6f196ed 100644--- a/deployment/manager/shared/locales/en/or.json+++ b/deployment/manager/shared/locales/en/or.json@@ -144,6 +144,7 @@"anyOfThisType": "Any of this type","notification": "Notification","matched": "Matched",+ "matchedOfType": "Matched of type {{type}}","unmatched": "Unmatched","wait": "Wait","underlyingAssets": "Underlying assets",diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.javaindex 63fd98373..a7928d0ce 100644--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java@@ -222,32 +222,40 @@ public class EmailNotificationHandler implements NotificationHandler {}EmailNotificationMessage email = (EmailNotificationMessage)message;- // Move to/cc/bcc to targets (for traceability) in sent notifications+ // Map to/cc/bcc into a custom target for traceability in sent notifications+ List<String> addresses = new ArrayList<>();+if (email.getTo() != null) {- mappedTargets.addAll(+ addresses.addAll(email.getTo().stream()- .map(recipient ->- new Notification.Target(Notification.TargetType.CUSTOM, recipient.getAddress()))+ .map(EmailNotificationMessage.Recipient::getAddress)+ .map(address -> "to:" + address).collect(Collectors.toList()));+email.setTo((List<EmailNotificationMessage.Recipient>) null);}if (email.getCc() != null) {- mappedTargets.addAll(+ addresses.addAll(email.getCc().stream()- .map(recipient ->- new Notification.Target(Notification.TargetType.CUSTOM, recipient.getAddress()))+ .map(EmailNotificationMessage.Recipient::getAddress)+ .map(address -> "cc:" + address).collect(Collectors.toList()));+email.setCc((List<EmailNotificationMessage.Recipient>) null);}if (email.getBcc() != null) {- mappedTargets.addAll(+ addresses.addAll(email.getBcc().stream()- .map(recipient ->- new Notification.Target(Notification.TargetType.CUSTOM, recipient.getAddress()))+ .map(EmailNotificationMessage.Recipient::getAddress)+ .map(address -> "bcc:" + address).collect(Collectors.toList()));+email.setBcc((List<EmailNotificationMessage.Recipient>) null);}+ if (!addresses.isEmpty()) {+ mappedTargets.add(new Notification.Target(Notification.TargetType.CUSTOM, String.join(";", addresses)));+ }return mappedTargets;}@@ -260,21 +268,34 @@ public class EmailNotificationHandler implements NotificationHandler {return NotificationSendResult.failure("SMTP invalid configuration so ignoring");}- EmailNotificationMessage.Recipient recipient = null;+ List<EmailNotificationMessage.Recipient> toRecipients = new ArrayList<>();+ List<EmailNotificationMessage.Recipient> ccRecipients = new ArrayList<>();+ List<EmailNotificationMessage.Recipient> bccRecipients = new ArrayList<>();Notification.TargetType targetType = target.getType();String targetId = target.getId();switch (targetType) {case USER:- recipient = getUserRecipient(targetId);+ toRecipients.add(getUserRecipient(targetId));break;case ASSET:- recipient = getAssetRecipient(targetId);+ toRecipients.add(getAssetRecipient(targetId));break;case CUSTOM:- // This recipient is the target ID- recipient = new EmailNotificationMessage.Recipient(targetId);+ // This recipient list is the target ID+ Arrays.stream(targetId.split(";")).forEach(recipient -> {+ if (recipient.startsWith("to:")) {+ toRecipients.add(new EmailNotificationMessage.Recipient(recipient.substring(3)));+ } else if (recipient.startsWith("cc:")) {+ ccRecipients.add(new EmailNotificationMessage.Recipient(recipient.substring(3)));+ } else if (recipient.startsWith("bcc:")) {+ bccRecipients.add(new EmailNotificationMessage.Recipient(recipient.substring(4)));+ } else {+ toRecipients.add(new EmailNotificationMessage.Recipient(recipient));+ }+ });+break;default:LOG.warning("Target type not supported: " + targetType);@@ -283,14 +304,31 @@ public class EmailNotificationHandler implements NotificationHandler {EmailNotificationMessage emailNotificationMessage = (EmailNotificationMessage) message;EmailPopulatingBuilder emailBuilder = buildEmailBuilder(id, emailNotificationMessage);- if (recipient != null && !TextUtil.isNullOrEmpty(recipient.getAddress())) {- emailBuilder.to(convertRecipient(recipient));+ if (!toRecipients.isEmpty()) {+ toRecipients.forEach(recipient -> {+ if (!TextUtil.isNullOrEmpty(recipient.getAddress())) {+ emailBuilder.to(convertRecipient(recipient));+ }+ });+ }+ if (!ccRecipients.isEmpty()) {+ ccRecipients.forEach(recipient -> {+ if (!TextUtil.isNullOrEmpty(recipient.getAddress())) {+ emailBuilder.cc(convertRecipient(recipient));+ }+ });+ }+ if (!bccRecipients.isEmpty()) {+ bccRecipients.forEach(recipient -> {+ if (!TextUtil.isNullOrEmpty(recipient.getAddress())) {+ emailBuilder.bcc(convertRecipient(recipient));+ }+ });}if ((emailNotificationMessage.getTo() == null || emailNotificationMessage.getTo().isEmpty())&& (emailNotificationMessage.getCc() == null || emailNotificationMessage.getCc().isEmpty())- && (emailNotificationMessage.getBcc() == null || emailNotificationMessage.getBcc().isEmpty())- && recipient == null) {+ && (emailNotificationMessage.getBcc() == null || emailNotificationMessage.getBcc().isEmpty())) {LOG.warning("No recipient found for " + targetType.name().toLowerCase() + ": " + targetId);return NotificationSendResult.failure("No recipients set for " + targetType.name().toLowerCase() + ": " + targetId);}diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex ebd79f11d..2093bfcdc 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -747,12 +747,29 @@ public class JsonRulesBuilder extends RulesBuilder {}}- // Override the notification targets if set in the rule- Notification.TargetType targetType = targetIsNotAssets(ruleAction.target) ? Notification.TargetType.USER : Notification.TargetType.ASSET;+ // Transfer the rule action target into notification targets+ Notification.TargetType targetType = Notification.TargetType.ASSET;+ if (ruleAction.target != null) {+ if (ruleAction.target.users != null+ && ruleAction.target.conditionAssets == null+ && ruleAction.target.assets == null+ && ruleAction.target.matchedAssets == null) {+ targetType = Notification.TargetType.USER;+ } else if (ruleAction.target.custom != null+ && ruleAction.target.conditionAssets == null+ && ruleAction.target.assets == null+ && ruleAction.target.matchedAssets == null) {+ targetType = Notification.TargetType.CUSTOM;+ }+ }+Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts);- if (ids != null && !ids.isEmpty()) {- notification.setTargets(ids.stream().map(id -> new Notification.Target(targetType, id)).collect(Collectors.toList()));+ if (ids == null) {+ notificationAction.notification.setTargets((List<Notification.Target>)null);+ } else {+ Notification.TargetType finalTargetType = targetType;+ notificationAction.notification.setTargets(ids.stream().map(id -> new Notification.Target(finalTargetType, id)).collect(Collectors.toList()));}log(Level.FINE, "Sending notification for rule action: " + rule.name + " '" + actionsName + "' action index " + index);@@ -977,8 +994,8 @@ public class JsonRulesBuilder extends RulesBuilder {Map<String, RuleConditionState> conditionStateMap = ruleState.conditionStateMap;if (target != null) {- if (!TextUtil.isNullOrEmpty(target.ruleConditionTag) && conditionStateMap != null) {- RuleConditionState triggerState = conditionStateMap.get(target.ruleConditionTag);+ if (!TextUtil.isNullOrEmpty(target.conditionAssets) && conditionStateMap != null) {+ RuleConditionState triggerState = conditionStateMap.get(target.conditionAssets);if (!useUnmatched) {return triggerState != null ? triggerState.getMatchedAssetIds() : Collections.emptyList();}@@ -995,7 +1012,7 @@ public class JsonRulesBuilder extends RulesBuilder {return facts.matchAssetState(target.matchedAssets).map(AssetState::getId).distinct()- .filter(matchedAssetId -> compareAssetIds.indexOf(matchedAssetId) >= 0)+ .filter(compareAssetIds::contains).collect(Collectors.toList());}@@ -1006,6 +1023,10 @@ public class JsonRulesBuilder extends RulesBuilder {if (target.users != null) {return getUserIds(usersFacade, target.users);}++ if (target.custom != null) {+ return Collections.singleton(target.custom);+ }}if (conditionStateMap != null) {diff --git a/model/src/main/java/org/openremote/model/notification/Notification.java b/model/src/main/java/org/openremote/model/notification/Notification.javaindex 32447e6dc..a3855fab8 100644--- a/model/src/main/java/org/openremote/model/notification/Notification.java+++ b/model/src/main/java/org/openremote/model/notification/Notification.java@@ -48,7 +48,7 @@ public class Notification {protected String id;@JsonCreator- public Target(@JsonProperty("type") TargetType type, @JsonProperty("id")String id) {+ public Target(@JsonProperty("type") TargetType type, @JsonProperty("id") String id) {this.type = type;this.id = id;}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.javaindex 02a0ebdcc..7c0b38d67 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@@ -27,14 +27,17 @@ import org.openremote.model.query.UserQuery;* none of the options are supplied then the default behaviour is to use all {@link org.openremote.model.asset.Asset}s* that caused the rule to trigger. The precedence is:* <ol>- * <li>{@link #ruleConditionTag}</li>+ * <li>{@link #conditionAssets} - Assets that matched a specific when condition</li>+ * <li>{@link #matchedAssets} - Assets that matched with additional {@link AssetQuery} applied</li>* <li>{@link #assets}</li>* <li>{@link #users}</li>+ * <li>{@link #custom} - A custom string that the Rule Action interprets to generate targets</li>* </ol>*/public class RuleActionTarget {- public String ruleConditionTag;+ public String conditionAssets;public AssetQuery matchedAssets;public AssetQuery assets;public UserQuery users;+ public String custom;}diff --git a/ui/app/or-app/src/or-header.ts b/ui/app/or-app/src/or-header.tsindex 6c4d94b14..bdfbb8e41 100644--- a/ui/app/or-app/src/or-header.ts+++ b/ui/app/or-app/src/or-header.ts@@ -1,6 +1,5 @@import {css, customElement, html, LitElement, property, query, TemplateResult, unsafeCSS} from "lit-element";import {until} from "lit-html/directives/until";-import {ifDefined} from "lit-html/directives/if-defined.js";import manager, {DefaultBoxShadowBottom,DefaultColor1,diff --git a/ui/app/or-app/src/pages/page-rules.ts b/ui/app/or-app/src/pages/page-rules.tsindex 72ffb60b9..25e23f0f6 100644--- a/ui/app/or-app/src/pages/page-rules.ts+++ b/ui/app/or-app/src/pages/page-rules.ts@@ -1,6 +1,6 @@import {css, customElement, html, property} from "lit-element";import "@openremote/or-rules";-import {RulesConfig} from "@openremote/or-rules";+import {RulesConfig, ActionTargetType, AllowedActionTargetTypes, ActionType} from "@openremote/or-rules";import {AssetType, NotificationTargetType, RulesetLang} from "@openremote/model";import {EnhancedStore} from "@reduxjs/toolkit";import {AppStateKeyed} from "../app";@@ -27,12 +27,17 @@ export function pageRulesProvider<S extends AppStateKeyed>(store: EnhancedStore<}export const PAGE_RULES_CONFIG_DEFAULT: PageRulesConfig = {+rules: {controls: {allowedLanguages: [RulesetLang.JSON, RulesetLang.FLOW, RulesetLang.GROOVY],- hideNotificationTargetType: {- email: [NotificationTargetType.TENANT, NotificationTargetType.ASSET],- push: [NotificationTargetType.TENANT, NotificationTargetType.CUSTOM],+ allowedActionTargetTypes: {+ actions: {+ wait: [],+ attribute: [],+ email: [ActionTargetType.USER, ActionTargetType.CUSTOM],+ push: [NotificationTargetType.USER, NotificationTargetType.ASSET],+ }}},descriptors: {diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.tsindex 21765a66c..b327268b7 100644--- a/ui/component/core/src/util.ts+++ b/ui/component/core/src/util.ts@@ -14,7 +14,8 @@ import {AttributeDescriptor,MetaItemType,MetaItemDescriptor,- AttributeValueDescriptor+ AttributeValueDescriptor,+ AssetDescriptor} from "@openremote/model";import i18next from "i18next";import Qs from "qs";@@ -146,8 +147,8 @@ function addPushNotificationsFromRuleAction(ruleAction: RuleActionUnion, geoPredif (ruleAction.notification && ruleAction.notification.message && ruleAction.notification.message.type === "push") {// Find applicable targetsconst target = ruleAction.target;- if (target && target.ruleConditionTag) {- const geoNotifications = geoPredicateMap.get(target.ruleConditionTag);+ if (target && target.conditionAssets) {+ const geoNotifications = geoPredicateMap.get(target.conditionAssets);if (geoNotifications) {geoNotifications.forEach((geoNotification) => {geoNotification.notification = ruleAction.notification!.message as PushNotificationMessage;@@ -269,6 +270,16 @@ export function stringMatch(needle: string, haystack: string): boolean {return false;}+export function capitaliseFirstLetter(str: string | undefined) {+ if (!str) {+ return;+ }+ if (str.length == 1) {+ return str.toUpperCase();+ }+ return str.charAt(0).toUpperCase() + str.slice(1);+}+export function enumContains(enm: object, val: string): boolean {return enm && Object.values(enm).includes(val);}@@ -363,6 +374,16 @@ export function getMetaItemLabel(urn: string): string {return i18next.t(["metaItemType." + urn, urn], {nsSeparator: "@"});}+export function getAssetTypeLabel(type: string | AssetDescriptor | undefined): string {+ if (typeof type === "string") {+ type = AssetModelUtil.getAssetDescriptor(type);+ }+ if (!type) {+ return "";+ }+ return i18next.t("assetType." + type.type, {nsSeparator: "@", defaultValue: capitaliseFirstLetter(type.name!.toLowerCase())});+}+export function getAttributeValueFormat(attribute: Attribute | undefined, descriptor: AttributeDescriptor | undefined, valueDescriptor: AttributeValueDescriptor | undefined): string | undefined {let format = getMetaValue(MetaItemType.FORMAT, attribute, descriptor, valueDescriptor) as string;if (!format) {diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.tsindex 00152f8d3..945e4f3a9 100644--- a/ui/component/or-rules/src/index.ts+++ b/ui/component/or-rules/src/index.ts@@ -50,11 +50,13 @@ export const enum ConditionType {export const enum ActionType {WAIT = "wait",- NOTIFICATION = "notification",+ EMAIL = "email",PUSH_NOTIFICATION = "push",ATTRIBUTE = "attribute"}+export import ActionTargetType = NotificationTargetType;+export enum AssetQueryOperator {VALUE_EMPTY = "empty",VALUE_NOT_EMPTY = "notEmpty",@@ -92,8 +94,9 @@ export interface AssetTypeAttributeName {assetType: string;attributeName: string;}-export interface NotificationActionTargetType {- [messageType: string]: NotificationTargetType[]+export interface AllowedActionTargetTypes {+ default?: ActionTargetType[];+ actions?: {[actionType in ActionType]: ActionTargetType[]};}export interface RulesConfig {@@ -103,7 +106,7 @@ export interface RulesConfig {allowedActionTypes?: ActionType[];allowedAssetQueryOperators?: Map<AssetTypeAttributeName | AttributeDescriptor | AttributeValueDescriptor | ValueType, AssetQueryOperator[]>;allowedRecurrenceOptions?: RecurrenceOption[];- hideNotificationTargetType?: NotificationActionTargetType;+ allowedActionTargetTypes?: AllowedActionTargetTypes;hideActionTypeOptions?: boolean;hideActionTargetOptions?: boolean;hideActionUpdateOptions?: boolean;@@ -646,6 +649,7 @@ export class OrRules extends translate(i18next)(LitElement) {(ruleset as TenantRuleset).realm = realm;}this._activeRuleset = ruleset;+ this.selectedIds = undefined;}protected _onRequestCopy(e: OrRulesRequestCopyEvent) {@@ -710,8 +714,12 @@ export class OrRules extends translate(i18next)(LitElement) {}protected _onRuleSelectionChanged(event: OrRulesSelectionChangedEvent) {- this._activeRuleset = event.detail.length === 1 ? {...event.detail[0]} : undefined;- this.selectedIds = event.detail.length === 1 ? [event.detail[0].id!] : undefined;+ const isNewRule = this._activeRuleset && !this._activeRuleset.id;++ if (!isNewRule || event.detail.length !== 0) {+ this._activeRuleset = event.detail.length === 1 ? {...event.detail[0]} : undefined;+ }+ this.selectedIds = event.detail.length === 1 && event.detail[0].id ? [event.detail[0].id!] : undefined;}protected _onRuleSaveStart(event: OrRulesSaveStartEvent) {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 30c6abb67..c4e1a4000 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,26 +1,22 @@-import {customElement, html, LitElement, property, css, PropertyValues} from "lit-element";-import {RulesConfig, getAssetTypeFromQuery} from "../index";+import {css, customElement, html, LitElement, property, TemplateResult} from "lit-element";+import {until} from "lit-html/directives/until";+import {ActionTargetType, ActionType, OrRulesRuleUnsupportedEvent, RulesConfig} from "../index";import {- RuleActionNotification,- EmailNotificationMessageRecipient,- EmailNotificationMessage,AssetDescriptor,+ AssetQuery,AssetQueryOrderBy$Property,- Asset,- NotificationTargetType,- User,- Tenant,- UserQuery,- AssetQuery+ JsonRule,+ RuleAction,+ RuleActionNotification} from "@openremote/model";import {InputType, OrInputChangedEvent} from "@openremote/or-input";-import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";+import {getTargetTypeMap, OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";import "./modals/or-rule-notification-modal";import "./forms/or-rule-form-message";import "./forms/or-rule-form-push-notification";import "./or-rule-action-attribute";-import { i18next } from "@openremote/or-translate";-import manager from "@openremote/core";+import {i18next} from "@openremote/or-translate";+import manager, {Util} from "@openremote/core";// language=CSSconst style = css`@@ -41,9 +37,15 @@ export class OrRuleActionNotification extends LitElement {return style;}+ @property({type: Object, attribute: false})+ public rule!: JsonRule;+@property({type: Object, attribute: false})public action!: RuleActionNotification;+ @property({type: String, attribute: false})+ public actionType!: ActionType;+public readonly?: boolean;@property({type: Object})@@ -52,85 +54,209 @@ export class OrRuleActionNotification extends LitElement {@property({type: Object})public config?: RulesConfig;- @property({type: Array, attribute: false})- protected _listItems?: Asset[] | User[];+ protected static getActionTargetTemplate(targetTypeMap: [string, string?][], action: RuleAction, actionType: ActionType, readonly: boolean, config: RulesConfig | undefined, baseAssetQuery: AssetQuery | undefined, onTargetTypeChangedCallback: (type: ActionTargetType) => void, onTargetChangedCallback: (type: ActionTargetType, value: string | undefined) => void): PromiseLike<TemplateResult> | undefined {- @property({type: String})- public type?: NotificationTargetType;+ let allowedTargetTypes: [ActionTargetType, string][] = [+ [ActionTargetType.USER, i18next.t("user_plural")],+ [ActionTargetType.ASSET, i18next.t("asset_plural")],+ [ActionTargetType.TENANT, i18next.t("tenant_plural")],+ [ActionTargetType.CUSTOM, i18next.t("custom")]+ ];- protected render() {- let value: string = "";- const message = this.action.notification && this.action.notification.message ? this.action.notification.message : undefined;- const messageType = message && message.type ? message.type : undefined;- let valueTemplate;- let targetTypeTemplate;- const idOptions: [string, string] [] = [];- let targetTypes = [[NotificationTargetType.USER, i18next.t("user_plural")], [NotificationTargetType.ASSET, i18next.t("asset_plural")], [NotificationTargetType.TENANT, i18next.t("tenant_plural")], [NotificationTargetType.CUSTOM, i18next.t("custom")]];-- const hideNotificationTargetType = this.config && this.config.controls ? this.config.controls.hideNotificationTargetType: {};- if(hideNotificationTargetType && messageType && messageType in hideNotificationTargetType) {- const hideTargets = hideNotificationTargetType[messageType];- if(hideTargets) {- targetTypes = targetTypes.filter(target => {- const nTarget = target[0] as NotificationTargetType;- return !hideTargets.includes(nTarget)- });+ if (config && config.controls && config.controls.allowedActionTargetTypes) {+ let configTypes: string[] | undefined;++ if (config.controls.allowedActionTargetTypes.actions) {+ configTypes = (config.controls.allowedActionTargetTypes.actions as any)[actionType] as ActionTargetType[];+ } else {+ configTypes = config.controls.allowedActionTargetTypes.default;+ }++ if (configTypes) {+ allowedTargetTypes = allowedTargetTypes.filter((allowedType) => configTypes?.includes(allowedType[0]));}}- if(this.type === NotificationTargetType.ASSET) {- idOptions.push(["*", i18next.t("matched")]);- if(this._listItems) this._listItems.forEach((asset: Asset) => idOptions.push([asset.id!, asset.name!] as [string, string]));+ if (allowedTargetTypes.length === 0) {+ console.warn("Rule action config doesn't allow any action target types for this type of action");+ return;}- if(this.type === NotificationTargetType.TENANT) {- if(this._listItems) this._listItems.forEach((tenant: Tenant) => idOptions.push([tenant.id!, tenant.displayName!] as [string, string]));+ let targetType: ActionTargetType | undefined = ActionTargetType.ASSET;++ if (action.target) {+ if (action.target.users && !action.target.conditionAssets && !action.target.matchedAssets && !action.target.assets) {+ targetType = ActionTargetType.USER;+ } else if (action.target.custom !== undefined && !action.target.conditionAssets && !action.target.matchedAssets && !action.target.assets) {+ targetType = ActionTargetType.CUSTOM;+ }}-- if(this.type === NotificationTargetType.USER) {- if(this._listItems) this._listItems.forEach((user: User) => idOptions.push([user.id!, user.username ? user.username : user.email] as [string, string]));-++ let targetValueTemplate: PromiseLike<TemplateResult>;++ if (!allowedTargetTypes.find((allowedTargetType) => allowedTargetType[0] === targetType)) {+ targetType = undefined;}- if(this.type){- targetTypeTemplate = html`<or-input type="${InputType.SELECT}"- .options="${targetTypes}"- value="${this.type}"- label="${i18next.t("recipients")}"- @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationType(e.detail.value)}"- ?readonly="${this.readonly}"></or-input>- `;- } else if(targetTypes.length > 0 ){- targetTypeTemplate = html`<or-input type="${InputType.SELECT}"- .options="${targetTypes}"- label="${i18next.t("recipients")}"- @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationType(e.detail.value)}"- ?readonly="${this.readonly}"></or-input>++ if (targetType === ActionTargetType.CUSTOM) {++ const template = html`+ <or-input .type="${InputType.TEXT}" @or-input-changed="${(e: OrInputChangedEvent) => onTargetChangedCallback(targetType!, e.detail.value)}" ?readonly="${readonly}" .value="${action.target!.custom}" ></or-input>`;+ targetValueTemplate = Promise.resolve(template);++ } else {++ let targetValuesGenerator: PromiseLike<[string, string][]>;+ let label: string | undefined;+ let value: string | undefined;++ if (targetType === ActionTargetType.USER) {+ targetValuesGenerator = manager.rest.api.UserResource.getAll(manager.displayRealm).then(+ (usersResponse) => usersResponse.data.map((user) => [user.id!, user.username!])+ );+ label = i18next.t("user_plural");++ const userQuery = action.target!.users!;++ if ((userQuery.ids && userQuery.ids.length > 1)+ || userQuery.usernames+ || userQuery.assetPredicate+ || userQuery.limit+ || userQuery.pathPredicate+ || userQuery.tenantPredicate) {+ console.warn("Rule action user target query is unsupported: " + JSON.stringify(userQuery, null, 2));+ return;+ }++ if (userQuery.ids && userQuery.ids.length === 1) {+ value = userQuery.ids[0];+ }+ } else {+ const assetQuery = baseAssetQuery ? {...baseAssetQuery} : {};+ assetQuery.select = {+ excludeAttributeTimestamp: true,+ excludeAttributeValue: true,+ excludeParentInfo: true,+ excludePath: true+ };+ assetQuery.orderBy = {+ property: AssetQueryOrderBy$Property.NAME+ };++ targetValuesGenerator = manager.rest.api.AssetResource.queryAssets(assetQuery).then(+ (response) => response.data.map((asset) => [asset.id!, asset.name! + " (" + asset.id! + ")"])+ );+ label = i18next.t("asset_plural");+ if (!action.target) {+ value = "allMatched";+ } else {+ if (action.target.conditionAssets) {+ console.warn("Rule action asset target, conditionAssets is unsupported: " + JSON.stringify(action.target, null, 2));+ return;+ }+ if (action.target.matchedAssets) {+ if (action.target.matchedAssets.types && action.target.matchedAssets.types.length > 1) {+ console.warn("Rule action asset target, matchedAssets query unsupported: " + JSON.stringify(action.target, null, 2));+ return;+ }+ if (action.target.matchedAssets.types && action.target.matchedAssets.types.length === 1) {+ value = action.target.matchedAssets.types[0].value;+ }+ } else if (action.target.assets) {+ if (action.target.assets.ids && action.target.assets.ids.length > 1) {+ console.warn("Rule action asset target, assets query unsupported: " + JSON.stringify(action.target, null, 2));+ return;+ }+ if (action.target.assets.ids && action.target.assets.ids.length === 1) {+ value = action.target.assets.ids[0];+ }+ }+ }+ }++ targetValueTemplate = targetValuesGenerator.then((values) => {++ // Add additional options for assets+ if (targetType === ActionTargetType.ASSET) {+ const additionalValues: [string, string][] = [["allMatched", i18next.t("matched")]];+ if (targetTypeMap && targetTypeMap.length > 1) {+ targetTypeMap.forEach((typeAndTag) => {+ if (!additionalValues.find((av) => av[0] === typeAndTag[0])) {+ additionalValues.push([typeAndTag[0], i18next.t("matchedOfType", {type: Util.getAssetTypeLabel(typeAndTag[0])})]);+ }+ });+ }+ values = [...additionalValues, ...values];+ }++ return html`+ <or-input type="${InputType.SELECT}"+ .options="${values}"+ .label="${label}"+ .value="${value}"+ @or-input-changed="${(e: OrInputChangedEvent) => onTargetChangedCallback(targetType!, e.detail.value)}"+ ?readonly="${readonly}"></or-input>+ `;+ });}- if(idOptions.length > 0 && this._listItems) {- valueTemplate = html`+ targetValueTemplate = targetValueTemplate.then((valueTemplate) => {+ return html`<or-input type="${InputType.SELECT}"- .options="${idOptions}"- label="${this.type ? i18next.t(this.type.toLowerCase()+"_plural") : ""}"- .value="${this.getNotificationTargetId()}"- @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationValue(e.detail.value)}"- ?readonly="${this.readonly}"></or-input>+ .options="${allowedTargetTypes}"+ .value="${targetType}"+ .label="${i18next.t("recipients")}"+ @or-input-changed="${(e: OrInputChangedEvent) => onTargetTypeChangedCallback(e.detail.value as ActionTargetType)}"+ ?readonly="${readonly}"></or-input>+ ${valueTemplate}`;+ });++ return targetValueTemplate;+ }++ protected render() {++ if (!this.action.notification || !this.action.notification.message) {+ return html``;}- if(this.type === NotificationTargetType.CUSTOM) {- if(messageType === "email" && message) {- const emailMessage:EmailNotificationMessage = message;- value = message && emailMessage.to ? emailMessage.to.map(t => t.address).join(';') : "";+ const message = this.action.notification.message;+ const messageType = message.type!;+ let baseAssetQuery: AssetQuery;++ if (messageType === "push") {+ baseAssetQuery = {+ types: [+ {+ predicateType: "string",+ value: "urn:openremote:asset:console"+ }+ ]};+ } else {+ baseAssetQuery = {+ attributes: {+ items: [+ {+ name: { "predicateType": "string", "value": "email" },+ value: { "predicateType": "value-not-empty" }+ }+ ]+ }}+ }- valueTemplate = html`<or-input .type="${InputType.TEXT}" @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value)}" ?readonly="${this.readonly}" .value="${value}" ></or-input>`+ let targetTemplate = OrRuleActionNotification.getActionTargetTemplate(getTargetTypeMap(this.rule), this.action, this.actionType, !!this.readonly, this.config, baseAssetQuery,(type) => this._onTargetTypeChanged(type), (type, value) => this._onTargetChanged(type, value));+ let modalTemplate: TemplateResult | string = ``;++ if (!targetTemplate) {+ this.dispatchEvent(new OrRulesRuleUnsupportedEvent());+ return ``;}- let modalTemplate = html``;- if(message) {- if(messageType === "push") {+ 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>@@ -138,7 +264,7 @@ export class OrRuleActionNotification extends LitElement {`;}- if(messageType === "email") {+ if (messageType === "email") {modalTemplate = html`<or-rule-notification-modal title="email" .action="${this.action}"><or-rule-form-message .action="${this.action}"></or-rule-form-message>@@ -147,209 +273,64 @@ export class OrRuleActionNotification extends LitElement {}}- return html`- ${targetTypeTemplate}- ${valueTemplate}- ${modalTemplate}- `;- }-- protected _getAssetType() {- if (!this.action.target) {- return;- }- const query = this.action.target.assets ? this.action.target.assets : this.action.target.matchedAssets ? this.action.target.matchedAssets : undefined;- return query ? getAssetTypeFromQuery(query) : undefined;- }+ targetTemplate = targetTemplate.then((targetTemplate) =>+ html`+ ${targetTemplate}+ ${modalTemplate}+ `+ );- getNotificationTargetType() {- if(this.action.target) {- if(this.action.target.assets || this.action.target.matchedAssets) return NotificationTargetType.ASSET;- if(this.action.target.users) return NotificationTargetType.USER;- } else if(this.action.notification) {- if(this.action.notification.message && this.action.notification.message.type === "email") return NotificationTargetType.CUSTOM;- } else {- return;- }-+ return html`${until(targetTemplate,html``)}`;}-- getNotificationTargetId() {- if(!this.action.target) return-- switch (this.type) {- case NotificationTargetType.ASSET:- if( this.action.target.matchedAssets) {- return "*";- }-- const assets = this.action.target.assets- if(assets && assets.ids) {- return assets.ids[0]+ protected _onTargetTypeChanged(targetType: ActionTargetType) {+ if (targetType === ActionTargetType.ASSET) {+ delete this.action.target;+ } else if (targetType === ActionTargetType.USER) {+ this.action.target = {+ users: {+ ids: []}- break;- case NotificationTargetType.USER:- const users = this.action.target.users- if(users && users.ids) {- return users.ids[0]- }- break;- case NotificationTargetType.TENANT:- break;- case NotificationTargetType.CUSTOM:- break;+ };+ } else if (targetType === ActionTargetType.CUSTOM) {+ this.action.target = {+ custom: ""+ }}- }- protected clearMessageTo() {- if(this.action.notification && this.action.notification.message){- const message:EmailNotificationMessage = this.action.notification.message- delete message.to- }- }- protected setActionNotificationType(type: NotificationTargetType) {- this.type = type;- this.loadTypeData(type);+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ this.requestUpdate();}- protected setActionNotificationValue(value: string) {- this.clearMessageTo();- switch (this.type) {- case NotificationTargetType.ASSET:- if (value === "*") {- const assetType = this._getAssetType();- if(this.action.target){- this.action.target.assets = undefined;- }+ protected _onTargetChanged(targetType: ActionTargetType, value: string | undefined) {+ switch (targetType) {+ case ActionTargetType.ASSET:+ if (!value || value === "allMatched") {+ delete this.action.target;+ } else if (value.startsWith("urn:")) {+ // This is an asset typethis.action.target = {matchedAssets: {types: [{predicateType: "string",- value: assetType+ value: value}]}};} else {- const assets:AssetQuery = {ids: [value]}- this.action.target = {assets: assets}+ this.action.target = {+ assets: {+ ids: [+ value+ ]+ }+ };}break;- case NotificationTargetType.USER:- const users:UserQuery = {ids: [value]}- this.action.target = {users: users}- break;- case NotificationTargetType.TENANT:- break;- case NotificationTargetType.CUSTOM:- break;}- this.dispatchEvent(new OrRulesJsonRuleChangedEvent());- }- protected firstUpdated(_changedProperties: PropertyValues): void {- if(_changedProperties.has('action')) {- const type = this.getNotificationTargetType();- if(type) {- this.setActionNotificationType(type);- }- }- }-- protected loadTypeData(type: string | undefined) {- if(this.action && this.action.notification) {- switch (type) {- case NotificationTargetType.ASSET:-- const messageType = this.action.notification.message ? this.action.notification.message.type : undefined- if(messageType === "push") {- const query = {- types: [- {- predicateType: "string",- value: "urn:openremote:asset:console"- }- ]};- this.loadAssets(query)- } else {- const query = {- attributes: {- items: [- {- name: { "predicateType": "string", "value": "email" },- value: { "predicateType": "value-not-empty" }- }- ]- }- }- this.loadAssets(query)- }- break;- case NotificationTargetType.USER:- this.loadUsers()- break;- case NotificationTargetType.TENANT:- this.loadTenants()- break;- case NotificationTargetType.CUSTOM:- break;- default:- break;- }- }- }-- protected setActionNotificationName(emails: string | undefined) {- delete this.action.target;- if(emails && this.action.notification && this.action.notification.message){-- const arrayOfEmails = emails.split(';');- const message:EmailNotificationMessage = this.action.notification.message;- message.to = [];- arrayOfEmails.forEach(email => {- const messageRecipient:EmailNotificationMessageRecipient = {- address: email,- name: email- };-- if(message && message.to){- message.to.push(messageRecipient);- }- });-- this.action.notification.message = message;- }this.dispatchEvent(new OrRulesJsonRuleChangedEvent());- this.requestUpdate();- }--- protected loadTenants() {- manager.rest.api.TenantResource.getAll().then((response) => this._listItems = response.data);- }-- protected loadUsers() {- manager.rest.api.UserResource.getAll(manager.displayRealm).then((response) => this._listItems = response.data).then(() => {- this.requestUpdate();- });- }-- protected loadAssets(query: object) {- const baseQuery = {- select: {- excludeAttributeTimestamp: true,- excludeAttributeValue: true,- excludeParentInfo: true,- excludePath: true- },- orderBy: {- property: AssetQueryOrderBy$Property.NAME- }- };- const assetQuery = {...query, ...baseQuery};-- manager.rest.api.AssetResource.queryAssets(assetQuery).then((response) => this._listItems = response.data);}-}\ No newline at end of file+}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 3a00239bb..5f493d4e9 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@@ -45,6 +45,40 @@ declare global {}}+function getTypeAndTagsFromGroup(group: LogicGroup<RuleCondition>): [string, string?][] {+ if (!group) {+ return [];+ }++ let typesAndTags: [string, string?][] = [];++ if (group.items) {+ for (const condition of group.items) {+ const type = getAssetTypeFromQuery(condition.assets);+ if (type) {+ typesAndTags.push([type, condition.tag]);+ }+ }+ }++ if (group.groups) {+ for (const condition of group.groups) {+ typesAndTags = typesAndTags.concat(getTypeAndTagsFromGroup(condition));+ }+ }++ return typesAndTags;+}++export function getTargetTypeMap(rule: JsonRule): [string, string?][] {+ if (!rule.when) {+ return [];+ }++ return getTypeAndTagsFromGroup(rule.when);+}++const style = css`:host {display: flex;@@ -159,7 +193,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsreturn html``;}- const targetTypeMap = this.getTargetTypeMap();+ const targetTypeMap = getTargetTypeMap(this._rule);return html`<div class="section-container"><or-rule-when .rule="${this._rule}" .config="${this.config}" .assetDescriptors="${this._whenAssetDescriptors}" ?readonly="${this.readonly}"></or-rule-when>@@ -194,39 +228,6 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements})}- protected getTargetTypeMap(): [string, string?][] {- if (!this._rule.when) {- return [];- }-- return this.getTypeAndTagsFromGroup(this._rule.when);- }-- protected getTypeAndTagsFromGroup(group: LogicGroup<RuleCondition>): [string, string?][] {- if (!group) {- return [];- }-- let typesAndTags: [string, string?][] = [];-- if (group.items) {- for (const condition of group.items) {- const type = getAssetTypeFromQuery(condition.assets);- if (type) {- typesAndTags.push([type, condition.tag]);- }- }- }-- if (group.groups) {- for (const condition of group.groups) {- typesAndTags = typesAndTags.concat(this.getTypeAndTagsFromGroup(condition));- }- }-- return typesAndTags;- }-public beforeSave() {if (!this._rule) {return;@@ -353,7 +354,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsreturn true;}- if (!target.assets && !target.ruleConditionTag) {+ if (!target.assets && !target.conditionAssets) {return false;}@@ -365,8 +366,8 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsreturn this._validateAssetQuery(target.matchedAssets, false, true);}- const typesAndTags = this.getTypeAndTagsFromGroup(rule.when!);- if (typesAndTags.findIndex((typeAndTag) => target.ruleConditionTag === typeAndTag[1]) < 0) {+ const typesAndTags = getTypeAndTagsFromGroup(rule.when!);+ if (typesAndTags.findIndex((typeAndTag) => target.conditionAssets === typeAndTag[1]) < 0) {return false;}@@ -437,4 +438,4 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsreturn false;}}-}\ No newline at end of file+}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 1298ed96b..0306863de 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@@ -32,7 +32,7 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescriif (config && config.controls && config.controls.allowedActionTypes) {addAssetTypes = config.controls.allowedActionTypes.indexOf(ActionType.ATTRIBUTE) >= 0;addWait = config.controls.allowedActionTypes.indexOf(ActionType.WAIT) >= 0;- addNotification = config.controls.allowedActionTypes.indexOf(ActionType.NOTIFICATION) >= 0;+ addNotification = config.controls.allowedActionTypes.indexOf(ActionType.EMAIL) >= 0;addPushNotification = config.controls.allowedActionTypes.indexOf(ActionType.PUSH_NOTIFICATION) >= 0;}@@ -59,7 +59,7 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescrimenu.push({text: i18next.t("email"),icon: "email",- value: ActionType.NOTIFICATION,+ value: ActionType.EMAIL,styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}} as MenuItem);}@@ -193,6 +193,9 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {return style;}+ @property({type: Array, attribute: false})+ public targetTypeMap!: [string, string?][];+@property({type: Object, attribute: false})public rule!: JsonRule;@@ -267,14 +270,14 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {let buttonColor = "inherit";if (action.action) {- switch (action.action as ActionType) {+ switch (action.action) {case ActionType.WAIT:buttonIcon = "timer";buttonColor = WAIT_COLOR;break;- case ActionType.NOTIFICATION:+ case "notification":action = action as RuleActionNotification- if(type === "push") {+ if (type === "push") {buttonIcon = "cellphone-message";buttonColor = NOTIFICATION_COLOR;} else {@@ -313,14 +316,13 @@ 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" .action="${action}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-notification>`;+ template = html`<or-rule-action-notification id="push-notification" .rule="${this.rule}" .action="${action}" .actionType="${ActionType.PUSH_NOTIFICATION}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-notification>`;break;- case ActionType.NOTIFICATION:- case "email":- template = html`<or-rule-action-notification id="email-notification" .action="${action}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-notification>`;+ case ActionType.EMAIL:+ template = html`<or-rule-action-notification id="email-notification" .rule="${this.rule}" .action="${action}" .actionType="${ActionType.EMAIL}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-notification>`;break;default:- template = html`<or-rule-action-attribute .action="${action}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-attribute>`;+ template = html`<or-rule-action-attribute .action="${action}" .targetTypeMap="${this.targetTypeMap}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-attribute>`;break;}}@@ -435,7 +437,7 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {if (value === ActionType.WAIT) {action.action = "wait";- } else if (value === ActionType.NOTIFICATION) {+ } else if (value === ActionType.EMAIL) {action = action as RuleActionNotification;action.action = "notification";action.notification = {diff --git a/ui/component/or-rules/src/json-viewer/or-rule-when.ts b/ui/component/or-rules/src/json-viewer/or-rule-when.tsindex 0a03aafb7..7b62dcb5c 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-when.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-when.ts@@ -223,6 +223,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {// Check this is a rule compatible with this editorif (!OrRuleWhen._isRuleWhenCompatible(this.rule.when)) {this.rule = undefined;+ this.dispatchEvent(new OrRulesRuleUnsupportedEvent());}}}@@ -251,7 +252,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {getWhenTypesMenu(this.config, this.assetDescriptors),undefined,(values: string[] | string) => this.addGroup(this.rule!.when!, values as string))}- <strong>${i18next.t(this.rule.when.groups == undefined || (this.rule.when.groups && this.rule.when.groups.length === 0) ? "when" : "orWhen")}...</strong>+ <strong>${i18next.t(!this.rule.when.groups || this.rule.when.groups.length === 0 ? "when" : "orWhen")}...</strong></span></or-panel>`}