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
UI fixes for Insights page with inconsistencies in attribute order (#2420)
Martin Peetersb75f28e840a7
diff --git a/ui/app/manager/test/fixtures/data/assets.ts b/ui/app/manager/test/fixtures/data/assets.tsindex a38acb272..47d23dfe3 100644--- a/ui/app/manager/test/fixtures/data/assets.ts+++ b/ui/app/manager/test/fixtures/data/assets.ts@@ -75,6 +75,28 @@ export const preparedAssetsForRules = Object.values());+export const preparedAssetsForInsights: Asset[] = [+ {+ name: "Energy Asset 1",+ type: "ThingAsset",+ realm: "smartcity",+ attributes: {+ ...commonAttrs,+ energyLevel: {name: "energyLevel", type: "number", meta: {storeDataPoints: true}},+ power: {name: "power", type: "number", meta: {storeDataPoints: true}}+ }+ }, {+ name: "Energy Asset 2",+ type: "ThingAsset",+ realm: "smartcity",+ attributes: {+ ...commonAttrs,+ energyLevel: {name: "energyLevel", type: "number", meta: {storeDataPoints: true}},+ power: {name: "power", type: "number", meta: {storeDataPoints: true}}+ }+ }+];+type AssetNames = (typeof assets)[number]["name"];export const assetPatches: Record<diff --git a/ui/app/manager/test/fixtures/manager.ts b/ui/app/manager/test/fixtures/manager.tsindex cbf1688bc..a79603de4 100644--- a/ui/app/manager/test/fixtures/manager.ts+++ b/ui/app/manager/test/fixtures/manager.ts@@ -14,9 +14,9 @@ import {type SharedComponentTestFixtures,type Shared,type TestFixture,- withPage,+ withPage} from "@openremote/test";-import { AssetsPage, RealmsPage, RolesPage, RulesPage, UsersPage } from "./pages";+import {AssetsPage, InsightsPage, RealmsPage, RolesPage, RulesPage, UsersPage} from "./pages";import { AssetViewer } from "../../../../component/or-asset-viewer/test/fixtures";import { CollapsiblePanel } from "../../../../component/or-components/test/fixtures";import { MwcInput } from "../../../../component/or-mwc-components/test/fixtures";@@ -38,6 +38,7 @@ export class Manager {public role?: Role;public assets: Asset[] = [];public rules: number[] = [];+ public dashboards: string[] = [];constructor(readonly page: Page, readonly baseURL: string) {this.managerHost = process.env.managerUrl || "http://localhost:8080";@@ -369,6 +370,22 @@ export class Manager {}}+ /**+ * Deletes dashboards in the active realm+ * @param config The axios request config+ */+ async deleteDashboards(config?: AxiosRequestConfig<any>, realm = this.realm) {+ for (const [i, id] of this.dashboards.entries()) {+ try {+ const response = await rest.api.DashboardResource.delete(realm!, id, config);+ expect(response.status).toBe(204);+ this.dashboards.splice(i, 1);+ } catch (e) {+ console.warn("Could not delete dashboard: ", id, e);+ }+ }+ }+/*** Deletes rules in the active realm* @param config The axios request config@@ -378,9 +395,9 @@ export class Manager {try {const response = await rest.api.RulesResource.deleteRealmRuleset(id!, config);expect(response.status).toBe(204);- this.rules.splice(i);+ this.rules.splice(i, 1);} catch (e) {- console.warn("Could not delete realm rule: ", id);+ console.warn("Could not delete realm rule: ", id, e);}}}@@ -396,7 +413,7 @@ export class Manager {expect(response.status).toBe(204);this.assets = [];} catch (e) {- console.warn("Could not delete asset(s): ", assetIds);+ console.warn("Could not delete asset(s): ", assetIds, e);}}@@ -414,7 +431,7 @@ export class Manager {expect(response.status).toBe(204);delete this.role;} catch (e) {- console.warn("Could not update roles: ", this.role);+ console.warn("Could not update roles: ", this.role, e);}}@@ -425,6 +442,10 @@ export class Manager {const access_token = await this.getAccessToken("master", "admin", users.admin.password!);const config = { headers: { Authorization: `Bearer ${access_token}` } };+ if (this.dashboards.length > 0) {+ await this.deleteDashboards(config);+ }+if (this.rules.length > 0) {await this.deleteRealmRulesets(config);}@@ -455,6 +476,7 @@ function withManager<R>(managerPage: Function): TestFixture<R, { page: Page; shainterface PageFixtures {assetsPage: AssetsPage;+ insightsPage: InsightsPage;realmsPage: RealmsPage;rolesPage: RolesPage;rulesPage: RulesPage;@@ -477,6 +499,7 @@ export const test = base.extend<Fixtures>({manager: async ({ page, baseURL }, use) => await use(new Manager(page, baseURL!)),// PagesassetsPage: withManager(AssetsPage),+ insightsPage: withManager(InsightsPage),realmsPage: withManager(RealmsPage),rolesPage: withManager(RolesPage),rulesPage: withManager(RulesPage),diff --git a/ui/app/manager/test/fixtures/pages/index.ts b/ui/app/manager/test/fixtures/pages/index.tsindex 311fb6eab..d4c56ad7b 100644--- a/ui/app/manager/test/fixtures/pages/index.ts+++ b/ui/app/manager/test/fixtures/pages/index.ts@@ -1,4 +1,5 @@export { AssetsPage } from "./assets";+export { InsightsPage } from "./insights";export { RealmsPage } from "./realms";export { RolesPage } from "./roles";export { RulesPage } from "./rules";diff --git a/ui/app/manager/test/fixtures/pages/insights.ts b/ui/app/manager/test/fixtures/pages/insights.tsnew file mode 100644index 000000000..98c6c85cc--- /dev/null+++ b/ui/app/manager/test/fixtures/pages/insights.ts@@ -0,0 +1,84 @@+import {BasePage, expect, Page, Shared} from "@openremote/test";+import {Manager} from "../manager";++export class InsightsPage implements BasePage {+ constructor(private readonly page: Page, private readonly shared: Shared, private readonly manager: Manager) {}++ async goto() {+ return this.manager.navigateToTab("Insights");+ }++ getBuilder(options?: any) {+ return this.page.locator("or-dashboard-builder", options);+ }++ getDashboardListItems(options?: any) {+ return this.page.locator("or-dashboard-tree li", options);+ }++ getPreview(options?: any) {+ return this.page.locator("or-dashboard-preview", options);+ }++ getBrowser(options?: any) {+ return this.page.locator("or-dashboard-browser", options);+ }++ getWidgetSettings(options?: any) {+ return this.page.locator(".settings-container:has(or-dashboard-widgetsettings)", options);+ }++ getWidgetAttributes(options?: any) {+ return this.getWidgetSettings().locator("settings-panel .attribute-list-item", options);+ }++ getDashboardGrid(options?: any) {+ return this.page.locator("or-dashboard-preview #gridElement", options);+ }++ getWidgets(options?: any) {+ return this.getDashboardGrid().locator("or-dashboard-widget-container", options);+ }++ async dragAndDropWidget(type: string, location: [number, number] = [0,0], size: [number, number] = [2, 2]) {+ await expect(this.getBuilder()).toBeVisible();+ await expect(this.getPreview()).toBeVisible();+ await expect(this.getPreview()).toHaveJSProperty("isLoading", false);+ await expect(this.getDashboardGrid()).toBeVisible();++ // Verify the slot is empty+ const isEmpty = await this.getDashboardGrid().evaluate((el: any, args) =>+ el.gridstack.isAreaEmpty(args.loc[0], args.loc[1], args.size[0], args.size[1]),+ { loc: location, size: size }+ );+ expect(isEmpty).toBeTruthy();++ // Grab the X/Y browser coordinates+ const coordinates = await this.getDashboardGrid().evaluate((el: any, args) =>+ ([args.loc[0] * args.size[0] * el.gridstack.cellWidth(), args.loc[1] * args.size[1] * el.gridstack.getCellHeight()]),+ { loc: location, size: size }+ );+ expect(coordinates).toBeDefined();++ // Manual drag and drop+ const count = await this.getWidgets().count();+ await this.page.locator("#sidebar .ui-draggable", {hasText: type}).first().hover();+ await this.page.mouse.down();+ await this.page.mouse.move(-200, 0, { steps: 5 }); // Move tiny bit left, so the hover event is triggered+ await this.page.locator(".maingrid").hover({ position: { x: coordinates[0], y: coordinates[1] }});+ await this.page.mouse.up();+ await expect(this.getWidgets()).toHaveCount(count + 1);+ }++ async addAttributes(assetName: string, attributeNames: string[]) {+ await this.getWidgetSettings().getByRole("button", { name: "Attribute" }).click();+ const dialog = this.page.locator("#dialog");+ await expect(dialog.getByText(assetName)).toBeVisible();+ await dialog.getByText(assetName).click();+ for (const attributeName of attributeNames) {+ await expect(dialog.getByText(attributeName)).toBeVisible();+ await dialog.getByText(attributeName).click();+ }+ await dialog.getByRole("button", { name: "Add" }).click();+ }+}diff --git a/ui/app/manager/test/insights.test.ts b/ui/app/manager/test/insights.test.tsnew file mode 100644index 000000000..7f0a0506f--- /dev/null+++ b/ui/app/manager/test/insights.test.ts@@ -0,0 +1,78 @@+import {test, userStatePath} from "./fixtures/manager";+import {Dashboard} from "@openremote/model";+import {preparedAssetsForInsights as assets} from "./fixtures/data/assets.js";+import { expect } from "@openremote/test";++test.use({storageState: userStatePath});++test("Create a Line Chart widget", async ({manager, shared, page, insightsPage}) => {++ await shared.interceptResponse<Dashboard>("**/dashboard", (dashboard) => {+ if (dashboard) manager.dashboards.push(dashboard.id!);+ });++ await manager.setup("smartcity", {assets});+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Insights");++ // Drag and drop Line Chart widget+ await expect(insightsPage.getDashboardListItems()).toHaveCount(0);+ await page.click(".mdi-plus >> nth=0");+ await expect(insightsPage.getDashboardListItems()).toHaveCount(1);+ await expect(insightsPage.getWidgets()).toHaveCount(0);+ await insightsPage.dragAndDropWidget("Line Chart");+ await expect(insightsPage.getWidgets()).toHaveCount(1);++ // Make widget larger by resizing it using the handle+ const chartWidget = insightsPage.getWidgets({ hasText: "Line Chart" }).first();+ await expect(chartWidget).toBeVisible();+ chartWidget.hover();+ const handle = page.locator(".ui-resizable-handle.ui-resizable-se").first();+ await expect(handle).toBeVisible();+ await handle.hover();++ const box = await chartWidget.boundingBox();+ const startX = box!.x + box!.width - 4;+ const startY = box!.y + box!.height - 4;+ await page.mouse.down();+ await page.mouse.move(startX + (box!.width * 3), startY + (box!.height * 3), { steps: 10 });+ await page.mouse.up();+ await expect.poll(async () => (await chartWidget.boundingBox())!.width).toBeGreaterThan(box!.width * 3.95);+ await expect.poll(async () => (await chartWidget.boundingBox())!.height).toBeGreaterThan(box!.height * 3.95);+ await expect(insightsPage.getWidgets()).toHaveCount(1);++ // Select widget, and add attribute of Asset #2 and Asset #1+ const attrName = "Energy level";+ await chartWidget.click();+ await expect(insightsPage.getBrowser()).toBeHidden();+ await expect(insightsPage.getWidgetSettings({ hasText: "Line Chart" })).toBeVisible();+ await insightsPage.addAttributes(assets[1].name!, [attrName]);+ await expect(insightsPage.getWidgetAttributes().getByText(assets[1].name!).first()).toBeVisible();+ await expect(insightsPage.getWidgetAttributes().getByText(attrName)).toHaveCount(1);+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(1);+ await insightsPage.addAttributes(assets[0].name!, ["Power", attrName]);+ await expect(insightsPage.getWidgetAttributes().getByText(assets[0].name!).first()).toBeVisible();+ await expect(insightsPage.getWidgetAttributes().getByText(attrName)).toHaveCount(2);+ await expect(insightsPage.getWidgetAttributes().getByText("Power")).toHaveCount(1);+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(3);++ // Save the dashboard+ await shared.interceptResponse<Dashboard>("**/dashboard", async (_dashboard, _request, response) => {+ expect(response?.status()).toBe(200);+ expect(await response?.json()).toBeDefined();+ });+ await page.getByRole("button", { name: "Save" }).click();+ await expect(page.getByRole("button", { name: "Save" })).toBeDisabled();++ // Select the widget and do final checks+ await chartWidget.click();+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(3);+ await expect(insightsPage.getWidgetAttributes().first()).toContainText(assets[1].name!);+ await expect(insightsPage.getWidgetAttributes().first()).toContainText(attrName);+ await expect(insightsPage.getWidgetAttributes().last()).toContainText(assets[0].name!);+ await expect(insightsPage.getWidgetAttributes().last()).toContainText("Power");+});++test.afterEach(async ({manager}) => {+ await manager.cleanUp();+});diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.tsindex 807eb1674..e4cbe330e 100644--- a/ui/component/or-chart/src/index.ts+++ b/ui/component/or-chart/src/index.ts@@ -34,7 +34,8 @@ import {cache} from "lit/directives/cache.js";import {debounce} from "lodash";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";-import { when } from "lit/directives/when.js";+import {when} from "lit/directives/when.js";+import {map} from "lit/directives/map.js";import {createRef, Ref, ref } from "lit/directives/ref.js";echarts.use([GridComponent, TooltipComponent, DataZoomComponent, MarkLineComponent, LineChart, CanvasRenderer, UniversalTransition]);@@ -844,7 +845,7 @@ export class OrChart extends translate(i18next)(LitElement) {<span>${i18next.t('noAttributesConnected')}</span></div>` : undefined}- ${this.assetAttributes && this.assetAttributes.map(([assetIndex, attr], index) => {+ ${map(this.assetAttributes?.map(([assetIndex, attr], index) => {const asset: Asset | undefined = this.assets[assetIndex];const colourIndex = index % this.colors.length;const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attr.name)?.[1];@@ -852,21 +853,22 @@ export class OrChart extends translate(i18next)(LitElement) {const label = Util.getAttributeLabel(attr, descriptors[0], asset!.type, true);const axisNote = (this.attributeConfig.rightAxisAttributes?.find(ar => asset!.id === ar.id && attr.name === ar.name)) ? i18next.t('right') : undefined;const bgColor = (color ?? this.colors[colourIndex]) || "";- return html`- <div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}"- @mouseenter="${() => this._addDatasetHighlight({id: this.assets[assetIndex]!.id, name: attr.name})}"- @mouseleave="${()=> this._removeDatasetHighlights()}">- <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex]!.type!), undefined, undefined, bgColor.split('#')[1])}</span>- <div class="attribute-list-item-label ${this.denseLegend ? 'attribute-list-item-label-dense' : undefined}">- <div style="display: flex; gap: 4px;">- <span style="font-size:12px; ${this.denseLegend ? 'margin-right: 8px' : undefined}">${this.assets[assetIndex].name}</span>- ${when(axisNote, () => html`<span style="font-size:12px; color:grey">(${axisNote})</span>`)}- </div>- <span style="font-size:12px; color:grey;">${label}</span>+ return {assetIndex, attr, axisNote, bgColor, label};++ }).sort(Util.sortByString(x => x.label)), ({assetIndex, attr, axisNote, bgColor, label}) => html`+ <div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}"+ @mouseenter="${() => this._addDatasetHighlight({id: this.assets[assetIndex]!.id, name: attr.name})}"+ @mouseleave="${()=> this._removeDatasetHighlights()}">+ <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex]!.type!), undefined, undefined, bgColor.split('#')[1])}</span>+ <div class="attribute-list-item-label ${this.denseLegend ? 'attribute-list-item-label-dense' : undefined}">+ <div style="display: flex; gap: 4px;">+ <span style="font-size:12px; ${this.denseLegend ? 'margin-right: 8px' : undefined}">${this.assets[assetIndex].name}</span>+ ${when(axisNote, () => html`<span style="font-size:12px; color:grey">(${axisNote})</span>`)}</div>+ <span style="font-size:12px; color:grey;">${label}</span></div>- `- })}+ </div>+ `)}</div>` : undefined)}</div>diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.tsindex 195db1371..1e173aa9c 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts@@ -199,10 +199,10 @@ export class OrDashboardPreview extends LitElement {protected activePreset?: DashboardScreenPreset;@state()- private rerenderActive: boolean = false;+ protected rerenderActive: boolean = false;@state()- private isLoading: boolean = false;+ protected isLoading: boolean = false;protected grid?: GridStack;diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-panel.tsindex 278c2fc66..ef0a1c0c2 100644--- a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts+++ b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts@@ -267,12 +267,15 @@ export class AttributesPanel extends LitElement {<div id="attribute-list">${guard([this.attributeRefs, this.loadedAssets, this.attributeActionCallback, this.attributeLabelCallback], () => html`- ${map(this.attributeRefs, (attributeRef: AttributeRef) => {+ ${map(this.attributeRefs.map(attributeRef => {const asset = this.getLoadedAsset(attributeRef);- if (asset) {- const attribute = asset.attributes![attributeRef.name!];- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);- const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, true);+ const attribute = asset?.attributes?.[attributeRef.name!];+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset?.type, attributeRef.name, attribute);+ const label = Util.getAttributeLabel(attribute, descriptors[0], asset?.type, true);+ return { asset, attribute, attributeRef, label };++ }).sort(Util.sortByString(x => x.label)), ({asset, attribute, attributeRef, label}) => {+ if (asset && attribute && attributeRef && label) {return html`<div class="attribute-list-item"><div class="attribute-list-item-icon">diff --git a/ui/test/fixtures/shared.ts b/ui/test/fixtures/shared.tsindex 7f529b057..57dee096c 100644--- a/ui/test/fixtures/shared.ts+++ b/ui/test/fixtures/shared.ts@@ -1,5 +1,4 @@-import { type Page } from "@playwright/test";-+import type { Page, Request, Response } from "@playwright/test";export interface BasePage {goto(): Promise<void>;@@ -40,13 +39,13 @@ export class Shared {* @param url The URL to intercept* @param cb The callback to handle the response*/- async interceptResponse<T>(url: string, cb: (body?: T) => void) {+ async interceptResponse<T>(url: string, cb: (body?: T, request?: Request, response?: Response | null) => void) {await this.page.route(url,async (route, request) => {await route.continue();const response = await request.response();- cb(await response?.json());+ cb(await response?.json(), request, response);},{ times: 1 });