Skip to content

armgit / core

Public Imported from GitHub
0

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

Add notifications to rules editor

Robin Dekkersfab030dd6675
diff --git a/ui/component/or-attribute-history/src/index.ts b/ui/component/or-attribute-history/src/index.ts
index 8f2a8064d..7d10077dd 100644
--- a/ui/component/or-attribute-history/src/index.ts
+++ b/ui/component/or-attribute-history/src/index.ts
@@ -715,9 +715,8 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {
this._loading = false;
return;
}
-
- const startOfPeriod = moment(this.fromTimestamp).startOf(this.period).toDate().getTime();
- const endOfPeriod = moment(this.fromTimestamp).endOf(this.period).toDate().getTime();
+ const startOfPeriod = moment(this.fromTimestamp).subtract(1, this.period).toDate().getTime();
+ const endOfPeriod = moment(this.fromTimestamp).toDate().getTime();
const response = await manager.rest.api.AssetDatapointResource.getDatapoints(
assetId,
diff --git a/ui/component/or-input/src/index.ts b/ui/component/or-input/src/index.ts
index ddcdcb2e8..c26a3223c 100644
--- a/ui/component/or-input/src/index.ts
+++ b/ui/component/or-input/src/index.ts
@@ -355,7 +355,7 @@ export class OrInput extends LitElement {
}
protected render() {
- const readonly = this.readonly || this.checkAssetWrite ? !manager.hasRole(ClientRole.WRITE_ASSETS) : false;
+ const readonly = this.checkAssetWrite ? !manager.hasRole(ClientRole.WRITE_ASSETS) || this.readonly : false;
if (this.type) {
diff --git a/ui/component/or-mwc-components/src/or-mwc-dialog.ts b/ui/component/or-mwc-components/src/or-mwc-dialog.ts
index c77f90318..a53038095 100644
--- a/ui/component/or-mwc-components/src/or-mwc-dialog.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-dialog.ts
@@ -119,7 +119,7 @@ export class OrMwcDialog extends LitElement {
<div class="mdc-dialog__surface">
<h2 class="mdc-dialog__title" id="dialog-title"><or-translate value="${this.dialogTitle}"></or-translate></h2>
<div class="dialog-container mdc-dialog__content" id="dialog-content">
- ${this.dialogContent ? this.dialogContent : html`<div></div>`}
+ ${this.dialogContent ? this.dialogContent : html`<slot></slot>`}
</div>
<footer class="mdc-dialog__actions">
${this.dialogActions ? this.dialogActions.map((action) => {
diff --git a/ui/component/or-rules/package.json b/ui/component/or-rules/package.json
index 4f75a3da0..d5ff551cd 100644
--- a/ui/component/or-rules/package.json
+++ b/ui/component/or-rules/package.json
@@ -20,6 +20,7 @@
"@openremote/or-input": "^1.1.0",
"@openremote/or-mwc-components": "^1.1.0",
"@openremote/or-panel": "^1.1.0",
+ "@openremote/or-map": "^1.1.0",
"@openremote/or-select": "^1.1.0",
"@openremote/or-translate": "^1.1.0",
"@openremote/rest": "^1.1.0",
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index a9a0a6cae..bffafaa4b 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -29,7 +29,8 @@ import {
TenantRuleset,
ValueType,
ClientRole,
- Asset
+ Asset,
+ NotificationTargetType
} from "@openremote/model";
import "@openremote/or-translate";
import "@openremote/or-mwc-components/dist/or-mwc-drawer";
@@ -49,6 +50,7 @@ export const enum ConditionType {
export const enum ActionType {
WAIT = "wait",
NOTIFICATION = "notification",
+ PUSH_NOTIFICATION = "push-notification",
ATTRIBUTE = "attribute"
}
@@ -89,6 +91,10 @@ export interface AssetTypeAttributeName {
assetType: string;
attributeName: string;
}
+export interface NotificationActionTargetType {
+ [messageType: string]: NotificationTargetType[]
+}
+
export interface RulesConfig {
controls?: {
@@ -97,6 +103,7 @@ export interface RulesConfig {
allowedActionTypes?: ActionType[];
allowedAssetQueryOperators?: Map<AssetTypeAttributeName | AttributeDescriptor | AttributeValueDescriptor | ValueType, AssetQueryOperator[]>;
allowedRecurrenceOptions?: RecurrenceOption[];
+ hideNotificationTargetType?: NotificationActionTargetType;
hideActionTypeOptions?: boolean;
hideActionTargetOptions?: boolean;
hideActionUpdateOptions?: boolean;
@@ -406,15 +413,15 @@ export class OrRulesRequestSelectEvent extends CustomEvent<RequestEventDetail<Ru
}
}
-export class OrRulesRequestAddEvent extends CustomEvent<RulesetLang> {
+export class OrRulesRequestAddEvent extends CustomEvent<RulesetUnion> {
public static readonly NAME = "or-rules-request-add";
- constructor(lang: RulesetLang) {
+ constructor(lang: RulesetLang, type:any) {
super(OrRulesRequestAddEvent.NAME, {
bubbles: true,
composed: true,
- detail: lang
+ detail: {lang, type}
});
}
}
@@ -615,7 +622,8 @@ export class OrRules extends translate(i18next)(LitElement) {
}
protected _onRequestAdd(e: OrRulesRequestAddEvent) {
- const lang = e.detail;
+ const lang = e.detail.lang;
+ const type = e.detail.type;
const shouldContinue = this._okToLeaveActiveRule();
if (!shouldContinue) {
@@ -624,15 +632,15 @@ export class OrRules extends translate(i18next)(LitElement) {
const name = this.config && this.config.rulesetName ? this.config.rulesetName : OrRules.DEFAULT_RULESET_NAME;
const realm = manager.isSuperUser() ? manager.displayRealm : manager.config.realm;
-
- const ruleset: TenantRuleset = {
+ const ruleset: RulesetUnion = {
id: 0,
- type: "tenant",
+ type: type,
name: name,
lang: lang,
realm: realm,
rules: undefined // View needs to populate this on load
};
+ console.log(ruleset)
this._activeRuleset = ruleset;
}
diff --git a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-message.ts b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-message.ts
new file mode 100644
index 000000000..9404b07aa
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-message.ts
@@ -0,0 +1,50 @@
+import {customElement, html, LitElement, css, property} from "lit-element";
+import "@openremote/or-input";
+import i18next from "i18next";
+import {translate} from "@openremote/or-translate";
+import "@openremote/or-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-input";import {
+ RuleActionNotification,
+ EmailNotificationMessage
+} from "@openremote/model";
+import { OrRulesJsonRuleChangedEvent } from "../or-rule-json-viewer";
+
+@customElement("or-rule-form-message")
+export class OrRuleFormMessage extends translate(i18next)(LitElement) {
+
+ @property({type: Object, attribute: false})
+ public action!: RuleActionNotification;
+
+
+ static get styles() {
+ return css`
+ or-input {
+ margin-bottom: 20px;
+ min-width: 420px;
+ width: 100%;
+ }
+ `
+ }
+
+ protected render() {
+ const message:EmailNotificationMessage | undefined = this.action.notification!.message;
+
+ return html`
+ <div style="display:grid">
+ <or-input value="${message && message.subject ? message.subject : ""}" @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "subject")}" .label="${i18next.t("subject")}" type="${InputType.TEXT}" required placeholder=" "></or-input>
+ <or-input value="${message && message.html ? message.html : ""}" @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "html")}" .label="${i18next.t("message")}" type="${InputType.TEXTAREA}" required placeholder=" " ></or-input>
+ </div>
+ `
+ }
+
+ 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};
+ }
+
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+}
\ No newline at end of file
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.ts
new file mode 100644
index 000000000..3e826d4d4
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-push-notification.ts
@@ -0,0 +1,96 @@
+import {customElement, html, LitElement, css, property} from "lit-element";
+import "@openremote/or-input";
+import i18next from "i18next";
+import {translate} from "@openremote/or-translate";
+import "@openremote/or-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-input";
+import {
+ RuleActionNotification,
+ PushNotificationMessage
+} from "@openremote/model";
+import { OrRulesJsonRuleChangedEvent } from "../or-rule-json-viewer";
+import set from "lodash-es/set";
+
+@customElement("or-rule-form-push-notification")
+export class OrRuleFormPushNotification extends translate(i18next)(LitElement) {
+
+ @property({type: Object, attribute: false})
+ public action!: RuleActionNotification;
+
+
+ static get styles() {
+ return css`
+ or-input {
+ margin-bottom: 20px;
+ min-width: 420px;
+ width: 100%;
+ }
+ `
+ }
+
+ protected render() {
+ const message:PushNotificationMessage | undefined = this.action.notification!.message;
+ 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 : "";
+ const buttons = message && message.buttons ? message.buttons : [];
+
+ return html`
+ <div style="display:grid">
+ <or-input value="${title}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "title")}"
+ .label="${i18next.t("subject")}"
+ type="${InputType.TEXT}"
+ required
+ placeholder=" "></or-input>
+
+ <or-input value="${body}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "body")}"
+ .label="${i18next.t("message")}"
+ type="${InputType.TEXTAREA}"
+ required
+ placeholder=" " ></or-input>
+ <or-input value="${actionUrl}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "action.url")}"
+ .label="${i18next.t("openWebsiteUrl")}"
+ type="${InputType.TEXT}"
+ required
+ placeholder=" "></or-input>
+
+ <or-input value="${buttons && buttons[0] && buttons[0].action && buttons[0].action.openInBrowser ? buttons[0].action.openInBrowser : ""}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "buttons.0.action.openInBrowser")}"
+ .label="${i18next.t("openInBrowser")}"
+ type="${InputType.SWITCH}"
+ required
+ placeholder=" "></or-input>
+
+ <or-input value="${buttons && buttons[0] && buttons[0].title ? buttons[0].title : ""}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "buttons.0.title")}"
+ .label="${i18next.t("buttonTextConfirm")}"
+ type="${InputType.TEXT}"
+ required
+ placeholder=" "></or-input>
+ <or-input value="${buttons && buttons[1] && buttons[1].title ? buttons[1].title : ""}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value, "buttons.1.title")}"
+ .label="${i18next.t("buttonTextDecline")}"
+ type="${InputType.TEXT}"
+ required
+ placeholder=" "></or-input>
+ </div>
+ `
+ }
+
+
+
+ protected setActionNotificationName(value: string | undefined, key?: string) {
+ if(key && this.action.notification && this.action.notification.message){
+ let message:any = this.action.notification.message;
+ message = set(message, key, value);
+ this.action.notification.message = {...message};
+ }
+
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+}
\ No newline at end of file
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.ts
new file mode 100644
index 000000000..150c8c15d
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/modals/or-rule-notification-modal.ts
@@ -0,0 +1,81 @@
+import {customElement, html, LitElement, property} from "lit-element";
+import {
+ RuleActionNotification,
+ AssetQuery,
+} from "@openremote/model";
+
+import "@openremote/or-input";
+import {InputType} from "@openremote/or-input";
+import i18next from "i18next";
+import {translate} from "@openremote/or-translate";
+
+import {DialogAction, OrMwcDialog, OrMwcDialogOpenedEvent} from "@openremote/or-mwc-components/dist/or-mwc-dialog";
+
+@customElement("or-rule-notification-modal")
+export class OrRuleNotificationModal extends translate(i18next)(LitElement) {
+
+ @property({type: Object, attribute: false})
+ public action!: RuleActionNotification;
+
+ @property({type: String})
+ public title = "message";
+
+ @property({type: Object})
+ public query?: AssetQuery;
+
+ constructor() {
+ super();
+ this.addEventListener(OrMwcDialogOpenedEvent.NAME, this.initDialog)
+ }
+
+ initDialog() {
+ const modal = this.shadowRoot!.getElementById('notification-modal');
+ if(!modal) return;
+ }
+
+ renderDialogHTML(action:RuleActionNotification) {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("notification-modal") as OrMwcDialog;
+ if(!this.shadowRoot) return
+
+ const slot = this.shadowRoot.getElementById('notification-form-slot');
+ if (dialog) {
+ dialog.dialogContent = html`${slot}`;
+ }
+ }
+
+ protected render() {
+ if(!this.action) return html``;
+
+
+ const notificationPickerModalActions: DialogAction[] = [
+ {
+ actionName: "cancel",
+ content: html`<or-input class="button" .type="${InputType.BUTTON}" .label="${i18next.t("cancel")}"></or-input>`,
+ action: () => {
+ // Nothing to do here
+ }
+ },
+ {
+ actionName: "ok",
+ content: html`<or-input class="button" .type="${InputType.BUTTON}" .label="${i18next.t("ok")}"></or-input>`,
+ action: () => {
+ }
+ }
+ ];
+
+
+ const notificationPickerModalOpen = () => {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("notification-modal") as OrMwcDialog;
+ if (dialog) {
+ dialog.open();
+ }
+ };
+
+ return html`
+ <or-input .type="${InputType.BUTTON}" .label="${i18next.t("message")}" @click="${notificationPickerModalOpen}"></or-input>
+ <or-mwc-dialog id="notification-modal" dialogTitle="${this.title}" .dialogActions="${notificationPickerModalActions}">
+ <slot id="notification-form-slot"></slot>
+ </or-mwc-dialog>
+ `
+ }
+}
\ No newline at end of file
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 c0c0e2674..246a9db3b 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,12 +1,26 @@
-import {customElement, html, LitElement, property, css} from "lit-element";
-import {RulesConfig} from "../index";
+import {customElement, html, LitElement, property, css, PropertyValues} from "lit-element";
+import {RulesConfig, getAssetTypeFromQuery} from "../index";
import {
RuleActionNotification,
EmailNotificationMessageRecipient,
- EmailNotificationMessage
+ EmailNotificationMessage,
+ AssetDescriptor,
+ AssetQueryOrderBy$Property,
+ Asset,
+ NotificationTargetType,
+ User,
+ Tenant,
+ UserQuery,
+ AssetQuery
} from "@openremote/model";
import {InputType, OrInputChangedEvent} from "@openremote/or-input";
import {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";
// language=CSS
const style = css`
@@ -32,47 +46,263 @@ export class OrRuleActionNotification extends LitElement {
public readonly?: boolean;
+ @property({type: Object})
+ public assetDescriptors?: AssetDescriptor[];
+
@property({type: Object})
public config?: RulesConfig;
+ @property({type: Array, attribute: false})
+ protected _listItems?: Asset[] | User[];
+
+ @property({type: String})
+ public type?: NotificationTargetType;
protected render() {
let value: string = "";
- if(this.action.notification && this.action.notification.message ){
- const message:EmailNotificationMessage = this.action.notification.message;
- if(message.to) {
- value = message.to.map(t => t.address).join(';');
+ 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(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(this.type === NotificationTargetType.TENANT) {
+ if(this._listItems) this._listItems.forEach((tenant: Tenant) => idOptions.push([tenant.id!, tenant.displayName!] as [string, string]));
+ }
+
+ if(this.type === NotificationTargetType.USER) {
+ if(this._listItems) this._listItems.forEach((user: User) => idOptions.push([user.id!, user.username!] as [string, string]));
+
+ }
+
+ if(this.type){
+ targetTypeTemplate = html`<or-input type="${InputType.SELECT}"
+ .options="${targetTypes}"
+ value="${this.type ? this.type : targetTypes[0]}"
+ label="${i18next.t("categories")}"
+ @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationType(e.detail.value)}"
+ ?readonly="${this.readonly}"></or-input>
+ `;
+ }
+
+ if(idOptions.length > 0 && this._listItems) {
+ valueTemplate = 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>
+ `;
+ }
+
+ if(this.type === NotificationTargetType.CUSTOM) {
+ if(messageType === "email" && message) {
+ const emailMessage:EmailNotificationMessage = message;
+ value = message && emailMessage.to ? emailMessage.to.map(t => t.address).join(';') : "";
+ }
+
+ 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 modalTemplate;
+ if(message) {
+ if(messageType === "push-notification") {
+ 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>
+ `;
+ }
+
+ 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>
+ </or-rule-notification-modal>
+ `;
}
}
return html`
- <or-input .type="${InputType.TEXT}" @or-input-changed="${(e: OrInputChangedEvent) => this.setActionNotificationName(e.detail.value)}" ?readonly="${this.readonly}" .value="${value}" ></or-input>
+ ${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;
+ }
+
+ getNotificationTargetType() {
+ if(!this.action.target) return NotificationTargetType.CUSTOM;
+
+ if(this.action.target.assets || this.action.target.matchedAssets) return NotificationTargetType.ASSET;
+ if(this.action.target.users) return NotificationTargetType.USER;
+ }
+
+
+ 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]
+ }
+ 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;
+ }
+ }
+ 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);
+ }
+ 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;
+ }
+ this.action.target = {
+ matchedAssets: {
+ types: [
+ {
+ predicateType: "string",
+ value: assetType
+ }
+ ]
+ }
+ };
+ } else {
+ const assets:AssetQuery = {ids: [value]}
+ this.action.target = {assets: assets}
+ }
+ break;
+ case NotificationTargetType.USER:
+ const users:UserQuery = {ids: [value]}
+ this.action.target = {users: users}
+ break;
+ case NotificationTargetType.TENANT:
+ break;
+ case NotificationTargetType.CUSTOM:
+ delete this.action.target;
+ break;
+ }
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
}
- protected setActionNotificationName(emails: string | undefined) {
- this.action.notification = {
- message: {
- type: "email",
- subject: "%RULESET_NAME%",
- html: "%TRIGGER_ASSETS%",
- from: {address:"[email protected]"},
- to: []
+ 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-notification") {
+ 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);
}
@@ -84,4 +314,29 @@ export class OrRuleActionNotification extends LitElement {
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);
+ }
+
+ 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-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
index 8bb867c3e..5f3f89e54 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
@@ -9,7 +9,7 @@ import {
JsonRule,
RuleActionUnion,
RuleRecurrence,
- RuleRecurrenceScope
+ RuleActionNotification
} from "@openremote/model";
import i18next from "i18next";
import {InputType} from "@openremote/or-input";
@@ -27,11 +27,13 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescri
let addAssetTypes = true;
let addWait = true;
let addNotification = true;
+ let addPushNotification = true;
if (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;
+ addPushNotification = config.controls.allowedActionTypes.indexOf(ActionType.PUSH_NOTIFICATION) >= 0;
}
@@ -61,6 +63,15 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescri
styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}
} as MenuItem);
}
+
+ if (addPushNotification) {
+ menu.push({
+ text: i18next.t("push-notification"),
+ icon: "cellphone-message",
+ value: ActionType.PUSH_NOTIFICATION,
+ styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}
+ } as MenuItem);
+ }
if (addWait) {
menu.push({
@@ -262,8 +273,14 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
buttonColor = WAIT_COLOR;
break;
case ActionType.NOTIFICATION:
- buttonIcon = "email";
- buttonColor = NOTIFICATION_COLOR;
+ action = action as RuleActionNotification
+ if(type === "push-notification") {
+ buttonIcon = "cellphone-message";
+ buttonColor = NOTIFICATION_COLOR;
+ } else {
+ buttonIcon = "email";
+ buttonColor = NOTIFICATION_COLOR;
+ }
break;
default:
const ad = AssetModelUtil.getAssetDescriptor(type);
@@ -295,8 +312,12 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case ActionType.WAIT:
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>`;
+ break;
case ActionType.NOTIFICATION:
- template = html`<or-rule-action-notification id="rule-notification" .action="${action}" .config="${this.config}" .readonly="${this.readonly}"></or-rule-action-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>`;
break;
default:
template = html`<or-rule-action-attribute .action="${action}" .config="${this.config}" .assetDescriptors="${this.assetDescriptors}" .readonly="${this.readonly}"></or-rule-action-attribute>`;
@@ -346,7 +367,8 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case "wait":
break;
case "notification":
- return action.action;
+ const type = action.notification && action.notification.message && action.notification.message.type ? action.notification.message.type : action.action;
+ return type;
break;
case "write-attribute":
case "update-attribute":
@@ -391,7 +413,6 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
protected setActionType(actions: RuleActionUnion[], action: RuleActionUnion, value: string) {
action.target = undefined;
-
switch (action.action) {
case "wait":
action.millis = undefined;
@@ -415,7 +436,23 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
if (value === ActionType.WAIT) {
action.action = "wait";
} else if (value === ActionType.NOTIFICATION) {
+ action = action as RuleActionNotification;
+ action.action = "notification";
+ action.notification = {
+ message: {
+ type: "email",
+ subject: "%RULESET_NAME%",
+ html: "%TRIGGER_ASSETS%"
+ }
+ };
+ } else if (value === ActionType.PUSH_NOTIFICATION) {
+ action = action as RuleActionNotification;
action.action = "notification";
+ action.notification = {
+ message: {
+ type: "push-notification"
+ }
+ };
} else {
action.action = "write-attribute";
action.target = {
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.ts
index e611e64a1..c68a6116d 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
@@ -7,7 +7,7 @@ import i18next from "i18next";
import {InputType} from "@openremote/or-input";
import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
import {getWhenTypesMenu, updateRuleConditionType} from "./or-rule-condition";
-import {getContentWithMenuTemplate, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";
import { translate } from "@openremote/or-translate";
enum ResetOption {
diff --git a/ui/component/or-rules/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.ts
index 10650970d..81a17ed85 100644
--- a/ui/component/or-rules/src/or-rule-list.ts
+++ b/ui/component/or-rules/src/or-rule-list.ts
@@ -3,7 +3,7 @@ import {CalendarEvent, ClientRole, RulesetLang, TenantRuleset} from "@openremote
import "@openremote/or-translate";
import manager, {EventCallback, OREvent} from "@openremote/core";
import "@openremote/or-input";
-import {InputType} from "@openremote/or-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-input";
import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";
import {
OrRulesRequestAddEvent,
@@ -48,6 +48,17 @@ const style = css`
padding-left: 10px;
}
+ .header-ruleset-type {
+ display: flex;
+ align-items: center;
+ height: var(--internal-or-asset-tree-header-height);
+ line-height: var(--internal-or-asset-tree-header-height);
+ color: var(--internal-or-asset-tree-header-text-color);
+ }
+ .header-ruleset-type p {
+ margin: 0 20px;
+ }
+
.node-status {
width: 10px;
height: 10px;
@@ -110,6 +121,9 @@ export class OrRuleList extends translate(i18next)(LitElement) {
@property({attribute: false})
protected _showLoading: boolean = true;
+ @property({type: Boolean})
+ protected _globalRulesets: boolean = false;
+
protected _selectedNodes: RulesetNode[] = [];
protected _initCallback?: EventCallback;
protected _ready = false;
@@ -131,7 +145,12 @@ export class OrRuleList extends translate(i18next)(LitElement) {
}
protected get _allowedLanguages(): RulesetLang[] | undefined {
- return this.config && this.config.controls && this.config.controls.allowedLanguages ? this.config.controls.allowedLanguages : OrRuleList.DEFAULT_ALLOWED_LANGUAGES;
+ const languages = this.config && this.config.controls && this.config.controls.allowedLanguages ? [...this.config.controls.allowedLanguages] : OrRuleList.DEFAULT_ALLOWED_LANGUAGES;
+ if(!manager.isSuperUser() || !this._globalRulesets) {
+ const index = languages.indexOf(RulesetLang.GROOVY);
+ if(index > 0) languages.splice(index)
+ }
+ return languages;
}
protected _updateLanguage() {
@@ -180,6 +199,11 @@ export class OrRuleList extends translate(i18next)(LitElement) {
this._updateLanguage();
}
+ if (_changedProperties.has("_globalRulesets")) {
+ this._updateLanguage();
+ this.refresh();
+ }
+
if (manager.ready) {
if (!this._nodes) {
this._loadRulesets();
@@ -221,7 +245,7 @@ export class OrRuleList extends translate(i18next)(LitElement) {
addTemplate = getContentWithMenuTemplate(
html`<or-input type="${InputType.BUTTON}" icon="plus"></or-input>`,
allowedLanguages.map((l) => {
- return {value: l, text: l} as MenuItem;
+ return {value: l, text: i18next.t(l)} as MenuItem;
}),
this.language,
(v) => this._onAddClicked(v as RulesetLang));
@@ -231,6 +255,18 @@ export class OrRuleList extends translate(i18next)(LitElement) {
}
return html`
<div id="wrapper" ?data-disabled="${this.disabled}">
+ ${manager.isSuperUser() ? html`
+ <div class="header-ruleset-type bg-grey">
+ <p>${i18next.t("realm rules")}</p>
+
+ <div style="flex: 1 1 0; display: flex;">
+ <or-input style="margin: auto;" type="${InputType.SWITCH}" @or-input-changed="${(evt: OrInputChangedEvent) => this._globalRulesets = evt.detail.value}"></or-input>
+ </div>
+
+ <p>${i18next.t("global rules")}</p>
+ </div>
+ ` : ``}
+
<div id="header">
<div id="title-container">
<or-translate id="title" value="rule_plural"></or-translate>
@@ -391,7 +427,8 @@ export class OrRuleList extends translate(i18next)(LitElement) {
}
protected _onAddClicked(lang: RulesetLang) {
- this.dispatchEvent(new OrRulesRequestAddEvent(lang));
+ const type = this._globalRulesets ? "global": "tenant";
+ this.dispatchEvent(new OrRulesRequestAddEvent(lang, type));
}
protected _onSearchClicked() {
@@ -425,18 +462,28 @@ export class OrRuleList extends translate(i18next)(LitElement) {
protected _loadRulesets() {
const sortFunction = this._getSortFunction();
- const params = {
- fullyPopulate: true,
- language: this._allowedLanguages
- }
-
- manager.rest.api.RulesResource.getTenantRulesets(this._getRealm() || manager.config.realm, params).then((response: any) => {
- if (response && response.data) {
- this._buildTreeNodes(response.data, sortFunction);
+
+ if(this._globalRulesets) {
+ manager.rest.api.RulesResource.getGlobalRulesets({fullyPopulate: true }).then((response: any) => {
+ if (response && response.data) {
+ this._buildTreeNodes(response.data, sortFunction);
+ }
+ }).catch((reason: any) => {
+ console.error("Error: " + reason);
+ });
+ } else {
+ const params = {
+ fullyPopulate: true,
+ language: this._allowedLanguages
}
- }).catch((reason: any) => {
- console.error("Error: " + reason);
- });
+ manager.rest.api.RulesResource.getTenantRulesets(this._getRealm() || manager.config.realm, params).then((response: any) => {
+ if (response && response.data) {
+ this._buildTreeNodes(response.data, sortFunction);
+ }
+ }).catch((reason: any) => {
+ console.error("Error: " + reason);
+ });
+ }
}
protected _buildTreeNodes(rulesets: TenantRuleset[], sortFunction: (a: RulesetNode, b: RulesetNode) => number) {
diff --git a/ui/component/or-rules/src/or-rule-text-viewer.ts b/ui/component/or-rules/src/or-rule-text-viewer.ts
index c86f69990..48493ea6f 100644
--- a/ui/component/or-rules/src/or-rule-text-viewer.ts
+++ b/ui/component/or-rules/src/or-rule-text-viewer.ts
@@ -81,34 +81,48 @@ export class OrRuleTextViewer extends LitElement implements RuleView {
}
protected render(): TemplateResult | void {
-
- if (!this._rules) {
- return html``;
- }
-
return html`
<div id="ace-editor"></div>
`;
}
+ protected refresh() {
+ this.destoryEditor()
+ this.initEditor();
+ }
+
+ protected destoryEditor() {
+ if (this._aceEditor) {
+ this._aceEditor.destroy();
+ this._aceEditor = undefined;
+ }
+ }
+
+ protected initEditor() {
+ if (this._aceElem) {
+ this._aceEditor = ace.edit(this._aceElem, {
+ mode: this._getMode(),
+ value: this._getRulesString(),
+ useSoftTabs: true,
+ tabSize: 2,
+ readOnly: this.readonly,
+ showPrintMargin: false
+ });
+ this._aceEditor.on("change", () => this._onEditorChanged());
+ this._aceEditor.renderer.attachToShadowRoot();
+ }
+ }
+
protected updated(_changedProperties: PropertyValues): void {
+ if(_changedProperties.has('_ruleset')){
+ this.refresh();
+ }
+
if (!this._aceElem) {
- if (this._aceEditor) {
- this._aceEditor.destroy();
- this._aceEditor = undefined;
- }
+ this.destoryEditor();
} else {
if (!this._aceEditor) {
- this._aceEditor = ace.edit(this._aceElem, {
- mode: this._getMode(),
- value: this._getRulesString(),
- useSoftTabs: true,
- tabSize: 2,
- readOnly: this.readonly,
- showPrintMargin: false
- });
- this._aceEditor.on("change", () => this._onEditorChanged());
- this._aceEditor.renderer.attachToShadowRoot();
+ this.initEditor();
}
}
}
diff --git a/ui/component/or-rules/src/or-rule-viewer.ts b/ui/component/or-rules/src/or-rule-viewer.ts
index 29b075d25..45079aec3 100644
--- a/ui/component/or-rules/src/or-rule-viewer.ts
+++ b/ui/component/or-rules/src/or-rule-viewer.ts
@@ -244,6 +244,31 @@ export class OrRuleViewer extends translate(i18next)(LitElement) {
this.dispatchEvent(new OrRulesSaveEndEvent(false));
});
}
+ } else if (this.ruleset.type === "global") {
+ if (this.ruleset.id) {
+ manager.rest.api.RulesResource.updateGlobalRuleset(this.ruleset.id!, this.ruleset).then((response) => {
+ this.disabled = false;
+ this.modified = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(true));
+ }).catch(reason => {
+ console.error("Failed to save ruleset: " + reason);
+ this.disabled = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(false));
+ });
+ } else {
+ manager.rest.api.RulesResource.createGlobalRuleset(this.ruleset).then((response) => {
+ if (this.ruleset) {
+ this.ruleset.id = response.data;
+ }
+ this.disabled = false;
+ this.modified = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(true));
+ }).catch(reason => {
+ console.error("Failed to save ruleset: " + reason);
+ this.disabled = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(false));
+ });
+ }
}
}
diff --git a/ui/component/or-rules/tsconfig.json b/ui/component/or-rules/tsconfig.json
index 62a355b75..71d03ee96 100644
--- a/ui/component/or-rules/tsconfig.json
+++ b/ui/component/or-rules/tsconfig.json
@@ -12,6 +12,7 @@
{ "path": "../core" },
{ "path": "../or-translate" },
{ "path": "../or-input" },
+ { "path": "../or-map" },
{ "path": "../or-attribute-input" },
{ "path": "../or-icon" },
{ "path": "../or-panel" },