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
Improve configuration item rendering (#2382)
Koenf6266f702f7c
diff --git a/model/src/main/java/org/openremote/model/util/ValueUtil.java b/model/src/main/java/org/openremote/model/util/ValueUtil.javaindex 6337f6a55..236bf45be 100644--- a/model/src/main/java/org/openremote/model/util/ValueUtil.java+++ b/model/src/main/java/org/openremote/model/util/ValueUtil.java@@ -162,8 +162,8 @@ public class ValueUtil {protected static Map<String, Class<? extends AgentLink<?>>> agentTypeMap = new HashMap<>();protected static Map<String, MetaItemDescriptor<?>> metaItemDescriptors = new HashMap<>();protected static Map<String, ValueDescriptor<?>> valueDescriptors = new HashMap<>();- protected static Map<String, ObjectNode> valueDescriptorSchemas = new HashMap<>();- protected static Map<String, String> valueDescriptorSchemaHashes = new HashMap<>();+ protected static Map<String, ObjectNode> valueDescriptorSchemas = new ConcurrentHashMap<>();+ protected static Map<String, String> valueDescriptorSchemaHashes = new ConcurrentHashMap<>();protected static Validator validator;protected static SchemaGenerator generator;protected static MessageDigest md;@@ -952,14 +952,8 @@ public class ValueUtil {Map<String, MetaItemDescriptor<?>> metaItems = getMetaItemDescriptors();valueDescriptorSchemas.putAll(metaItems.values().stream().map(AbstractNameValueDescriptorHolder::getType)- .filter(v -> {- String jsonType = v.getJsonType();- return jsonType.equals("array") || jsonType.equals("object");- })- .collect(Collectors.toMap(- ValueDescriptor::getName,- vd -> (ObjectNode) getSchema(vd.getType())- )));+ .filter(v -> v.getJsonType().equals("object") || v.getArrayDimensions() != null && v.getArrayDimensions() > 0)+ .collect(Collectors.toMap(ValueDescriptor::getName, vd -> (ObjectNode) getSchema(vd.getType()))));valueDescriptorSchemaHashes.putAll(valueDescriptorSchemas.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,v -> hash(v.getValue().toString())diff --git a/ui/app/manager/test/assets.test.ts b/ui/app/manager/test/assets.test.tsindex 646c3bf54..1005746a1 100644--- a/ui/app/manager/test/assets.test.ts+++ b/ui/app/manager/test/assets.test.ts@@ -1,193 +1,142 @@import { expect } from "@openremote/test";import { test, userStatePath } from "./fixtures/manager.js";-import assets, { assetMap, assetPatches, thing } from "./fixtures/data/assets.js";-import {WellknownMetaItems} from "@openremote/model";+import assets, { assetMap, assetPatches, commonAttrs, thing } from "./fixtures/data/assets.js";+import { AssetModelUtil, WellknownMetaItems } from "@openremote/model";+// `@openremote/core` depends on or-icon and isn't supported in nodejsimport * as Util from "@openremote/core/lib/util";test.use({ storageState: userStatePath });assets.forEach(({ type, name, attributes }) => {- const { attribute1, attribute2, attribute3, value1, value2, value3, x, y } =- assetPatches[name as keyof typeof assetPatches];-- /**- * @given Logged in to OpenRemote "smartcity" realm as "smartcity"- * @when Navigating to the "asset" tab- * @and Creating an asset of a specific type with the given name- * @and Opening the asset's detail page- * @and Switching to modify mode- * @and Setting values for specified attributes- * @and Saving the changes- * @then The asset with the given name should be visible in the UI- */- test(`Add new ${name} asset and configure its attributes`, async ({ page, manager, assetsPage, assetViewer }) => {- await manager.goToRealmStartPage("smartcity");- await assetsPage.goto();- await assetsPage.addAsset(assetMap[name!], name!);- await page.click(`#list-container >> text=${name}`);- await assetViewer.switchMode("modify");- await assetViewer.setAttributeValue(attribute1, value1);- await assetViewer.setAttributeValue(attribute2, value2);- const saveBtn = page.getByRole("button", { name: "Save" });- await saveBtn.click();- await expect(saveBtn).toBeDisabled();- await expect(page.locator(`text=${name}`)).toHaveCount(1);- });-- /**- * @given Assets are set up in the "smartcity" realm- * @when Logging in to the OpenRemote "smartcity" realm- * @and Navigating to the "asset" tab- * @and Selecting an asset by name- * @and Updating a specific attribute with a new value and type- * @and Switching to modify mode- * @and Updating the asset's location via map click- * @and Saving the changes- * @then The updated asset is saved and changes are persisted- */- test(`Update a ${name} asset's attributes and location`, async ({ page, manager, assetViewer }) => {- await manager.setup("smartcity", { assets });- await manager.goToRealmStartPage("smartcity");- await manager.navigateToTab("asset");- await page.click(`text=${name}`);-- const type = attributes[attribute3 as keyof typeof attributes].type;- const item = page.locator(`#field-${attribute3} input[type="${type}"]`);- if (await item.isEditable()) {- await item.fill(value3);- await page.click(`#field-${attribute3} #send-btn span`);- }-- await assetViewer.switchMode("modify");- await assetViewer.getAttributeLocator("location").getByRole("button").click();- await page.mouse.click(x, y, { delay: 1000 });- await page.getByRole("button", { name: "OK" }).click();-- const saveBtn = page.getByRole("button", { name: "Save" });- await saveBtn.click();- await expect(saveBtn).toBeDisabled();- });-- /**- * @given Assets are set up in the "smartcity" realm- * @when Logging in to the OpenRemote "smartcity" realm- * @and Navigating to the "asset" tab- * @and Selecting the asset by name- * @and Switching to modify mode- * @and Toggling read-only status for two attributes- * @and Saving the changes- * @and Navigating to the asset's view panel- * @then The correct read-only indicators should be present for the attributes- */- test(`Toggle read-only for two attributes on a ${name} asset`, async ({ page, manager, assetViewer }) => {- await manager.setup("smartcity", { assets });- await manager.goToRealmStartPage("smartcity");- await manager.navigateToTab("asset");- await page.click(`text=${name}`);-- await assetViewer.switchMode("modify");- await page.getByRole("button", { name: "Expand all" }).click();-- await assetViewer.getAttributeLocator(attribute1).click();- await assetViewer.getConfigurationItemLocator(attribute1, "Read only").locator("label").click();-- await assetViewer.getAttributeLocator(attribute2).click();- await assetViewer.getConfigurationItemLocator(attribute2, "Read only").locator("label").click();-- const saveBtn = page.getByRole("button", { name: "Save" });- await saveBtn.click();- await expect(saveBtn).toBeDisabled();-- await page.getByRole("button", { name: "View" }).click();- await expect(page.getByRole("button", { name: "Modify" })).toBeVisible();-- await expect(page.locator(`#field-${attribute1} #send-btn`)).toBeVisible();- await expect(page.locator(`#field-${attribute2} #send-btn`)).not.toBeVisible();- });-- /**- * @given Assets are set up in the "smartcity" realm- * @when Logging in to the OpenRemote "smartcity" realm- * @and Navigating to the "asset" tab- * @and Selecting the asset by name- * @and Switching to modify mode- * @and Selecting configuration items like "ruleState" and "storeDataPoints" for two attributes- * @and Saving the changes- * @then The configuration items are persisted correctly- */- test(`Set "ruleState" and "storeDataPoints" for ${name} asset attributes`, async ({ page, manager, assetViewer }) => {- await manager.setup("smartcity", { assets });- await manager.goToRealmStartPage("smartcity");- await manager.navigateToTab("asset");- await page.click(`text=${name}`);+ const { attribute1, attribute2, attribute3, value1, value2, value3, x, y } =+ assetPatches[name as keyof typeof assetPatches];- await assetViewer.switchMode("modify");- await page.getByRole("button", { name: "Expand all" }).click();+ /**+ * @given Logged in to OpenRemote "smartcity" realm as "smartcity"+ * @when Navigating to the "asset" tab+ * @and Creating an asset of a specific type with the given name+ * @and Opening the asset's detail page+ * @and Switching to modify mode+ * @and Setting values for specified attributes+ * @and Saving the changes+ * @then The asset with the given name should be visible in the UI+ */+ test(`Add new ${name} asset and configure its attributes`, async ({ page, manager, assetsPage, assetViewer }) => {+ await manager.goToRealmStartPage("smartcity");+ await assetsPage.goto();+ await assetsPage.addAsset(assetMap[name!], name!);+ await page.click(`#list-container >> text=${name}`);+ await assetViewer.switchMode("modify");+ await assetViewer.setAttributeValue(attribute1, value1);+ await assetViewer.setAttributeValue(attribute2, value2);+ const saveBtn = page.getByRole("button", { name: "Save" });+ await saveBtn.click();+ await expect(saveBtn).toBeDisabled();+ await expect(page.locator(`text=${name}`)).toHaveCount(1);+ });- await assetViewer.addConfigurationItems(attribute1, "ruleState", "storeDataPoints");- await assetViewer.addConfigurationItems(attribute2, "ruleState", "storeDataPoints");+ /**+ * @given Assets are set up in the "smartcity" realm+ * @when Logging in to the OpenRemote "smartcity" realm+ * @and Navigating to the "asset" tab+ * @and Selecting an asset by name+ * @and Updating a specific attribute with a new value and type+ * @and Switching to modify mode+ * @and Updating the asset's location via map click+ * @and Saving the changes+ * @then The updated asset is saved and changes are persisted+ */+ test(`Update a ${name} asset's attributes and location`, async ({ page, manager, assetViewer }) => {+ await manager.setup("smartcity", { assets });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("asset");+ await page.click(`text=${name}`);- const saveBtn = page.getByRole("button", { name: "Save" });- await saveBtn.click();- await expect(saveBtn).toBeDisabled();- });-});+ const type = attributes[attribute3 as keyof typeof attributes].type;+ const item = page.locator(`#field-${attribute3} input[type="${type}"]`);+ if (await item.isEditable()) {+ await item.fill(value3);+ await page.click(`#field-${attribute3} #send-btn span`);+ }-/**- * @given Assets are set up in the "smartcity" realm- * @when Login to OpenRemote "smartcity" realm as "smartcity"- * @and Modifying thing asset- * @and Adding primitive configuration items- * @then The configuration items to be visible- */-test("Add all primitive configuration items", async ({ page, manager, assetViewer }) => {- await manager.setup("smartcity", { assets: [thing] });- await manager.goToRealmStartPage("smartcity");- await manager.navigateToTab("Assets");- await page.getByText("Thing").click();- await assetViewer.switchMode("modify");- await page.getByRole("button", { name: "Expand all" }).click();- const items: [`${WellknownMetaItems}`, any][] = [- ["ruleState", true],- ["hasPredictedDataPoints", true],- ["storeDataPoints", true],- ["label", "test"],- ["showOnDashboard", true],- ["readOnly", true],- ["multiline", true],- ["accessPublicWrite", true],- ["momentary", true],- ["accessRestrictedRead", true],- ["dataPointsMaxAgeDays", 7],- ["accessRestrictedWrite", true],- ["secret", true],- ["ruleResetImmediate", true],- ["userConnected", "test"],- ["accessPublicRead", true],- ];- await assetViewer.addConfigurationItems("notes", ...items.map(([item]) => item));- for (const [item, value] of items) {- const itemLocator = assetViewer.getConfigurationItemLocator("notes");- const options = { name: Util.camelCaseToSentenceCase(item) };- if (typeof value === "string") {- const input = itemLocator.getByRole("textbox", options);- await input.fill(value);- await expect(input).toHaveValue(value);- } else if (typeof value === "number") {- const input = itemLocator.getByRole("spinbutton", options);- await input.fill(`${value}`);- await expect(input).toHaveValue(`${value}`);- } else if (value) {- await expect(itemLocator.getByRole("checkbox", options)).toBeChecked();- } else {- await expect(itemLocator.getByRole("checkbox", options)).not.toBeChecked();- }- }-});+ await assetViewer.switchMode("modify");+ await assetViewer.getAttributeLocator("location").getByRole("button").click();+ await page.mouse.click(x, y, { delay: 1000 });+ await page.getByRole("button", { name: "OK" }).click();++ const saveBtn = page.getByRole("button", { name: "Save" });+ await saveBtn.click();+ await expect(saveBtn).toBeDisabled();+ });++ /**+ * @given Assets are set up in the "smartcity" realm+ * @when Logging in to the OpenRemote "smartcity" realm+ * @and Navigating to the "asset" tab+ * @and Selecting the asset by name+ * @and Switching to modify mode+ * @and Toggling read-only status for two attributes+ * @and Saving the changes+ * @and Navigating to the asset's view panel+ * @then The correct read-only indicators should be present for the attributes+ */+ test(`Toggle read-only for two attributes on a ${name} asset`, async ({ page, manager, assetViewer }) => {+ await manager.setup("smartcity", { assets });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("asset");+ await page.click(`text=${name}`);-// TODO: Add test for the "Load more" button, by modifying the LIMIT variable in or-asset-tree+ await assetViewer.switchMode("modify");+ await page.getByRole("button", { name: "Expand all" }).click();-test.fixme("Add all complex configuration items", async ({ page, manager, shared }) => {});+ await assetViewer.getAttributeLocator(attribute1).click();+ await assetViewer.getConfigurationItemLocator(attribute1, "Read only").locator("label").click();++ await assetViewer.getAttributeLocator(attribute2).click();+ await assetViewer.getConfigurationItemLocator(attribute2, "Read only").locator("label").click();++ const saveBtn = page.getByRole("button", { name: "Save" });+ await saveBtn.click();+ await expect(saveBtn).toBeDisabled();++ await page.getByRole("button", { name: "View" }).click();+ await expect(page.getByRole("button", { name: "Modify" })).toBeVisible();++ await expect(page.locator(`#field-${attribute1} #send-btn`)).toBeVisible();+ await expect(page.locator(`#field-${attribute2} #send-btn`)).not.toBeVisible();+ });++ /**+ * @given Assets are set up in the "smartcity" realm+ * @when Logging in to the OpenRemote "smartcity" realm+ * @and Navigating to the "asset" tab+ * @and Selecting the asset by name+ * @and Switching to modify mode+ * @and Selecting configuration items like "ruleState" and "storeDataPoints" for two attributes+ * @and Saving the changes+ * @then The configuration items are persisted correctly+ */+ test(`Set "ruleState" and "storeDataPoints" for ${name} asset attributes`, async ({+ page,+ manager,+ assetViewer,+ }) => {+ await manager.setup("smartcity", { assets });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("asset");+ await page.click(`text=${name}`);++ await assetViewer.switchMode("modify");+ await page.getByRole("button", { name: "Expand all" }).click();++ await assetViewer.addConfigurationItems(attribute1, "ruleState", "storeDataPoints");+ await assetViewer.addConfigurationItems(attribute2, "ruleState", "storeDataPoints");++ const saveBtn = page.getByRole("button", { name: "Save" });+ await saveBtn.click();+ await expect(saveBtn).toBeDisabled();+ });+});/*** @given Assets are set up in the "smartcity" realm@@ -198,16 +147,298 @@ test.fixme("Add all complex configuration items", async ({ page, manager, shared* @and The asset column should appear empty (showing "Console")*/test("Delete specified assets and verify they are removed", async ({ page, manager, assetsPage }) => {- await manager.setup("smartcity", { assets });- await manager.goToRealmStartPage("smartcity");- await manager.navigateToTab("Assets");- await assetsPage.deleteSelectedAsset(manager, "Battery");- await assetsPage.deleteSelectedAsset(manager, "Solar Panel");- await expect(page.locator("text=Console")).toHaveCount(1);- await expect(page.locator("text=Solar Panel")).toHaveCount(0);- await expect(page.locator("text=Battery")).toHaveCount(0);+ await manager.setup("smartcity", { assets });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Assets");+ await assetsPage.deleteSelectedAsset(manager, "Battery");+ await assetsPage.deleteSelectedAsset(manager, "Solar Panel");+ await expect(page.locator("text=Console")).toHaveCount(1);+ await expect(page.locator("text=Solar Panel")).toHaveCount(0);+ await expect(page.locator("text=Battery")).toHaveCount(0);+});++test.describe("Parent asset", () => {+ test.beforeEach(async ({ manager }) => {+ await manager.setup("smartcity", {+ assets: [+ {+ name: "Parent",+ type: "ThingAsset",+ realm: "smartcity",+ attributes: { ...commonAttrs },+ },+ ],+ });+ await manager.goToRealmStartPage("smartcity");+ });++ /**+ * @given A thing (and parent) asset is set up in the "smartcity" realm+ * @when Login to OpenRemote "smartcity" realm as "smartcity"+ * @and Go to the asset page+ * @and Modify the thing asset+ * @and Add a parent asset called "Parent"+ * @then The parent name should be set+ */+ test("can be added", async ({ manager, page, assetViewer }) => {+ await manager.createAsset(thing);+ await manager.navigateToTab("Assets");+ await page.getByText("Thing").click();+ await assetViewer.switchMode("modify");++ await page.getByText("Parent Edit").getByRole("button").click();+ await page.getByLabel("Select parent asset").getByText("Parent").click();+ await page.getByLabel("Select parent asset").getByRole("button", { name: "OK" }).click();+ await page.getByRole("button", { name: "Save" }).click();++ await expect(page.getByRole("textbox", { name: "Parent" })).toHaveValue("Parent");+ });++ /**+ * @given A thing (with parent) asset is set up in the "smartcity" realm+ * @when Login to OpenRemote "smartcity" realm as "smartcity"+ * @and Go to the asset page+ * @and Modify the thing asset+ * @and Remove the "Parent" parent asset+ * @then The parent name should not be set+ */+ test("can be removed", async ({ manager, page, assetViewer, assetTree }) => {+ await manager.createAsset({ ...thing, parentId: manager.assets[0].id });+ await manager.navigateToTab("Assets");+ await assetTree.getFilterInput().fill("Thing");+ await assetViewer.switchMode("modify");++ await page.getByText("Parent Edit").getByRole("button").click();+ await page.getByLabel("Select parent asset").getByRole("button", { name: "NONE" }).click();+ await page.getByRole("button", { name: "Save" }).click();++ await expect(page.getByRole("textbox", { name: "Parent" })).toBeEmpty();+ });+});++test.describe("Attributes", () => {+ /**+ * @given A thing asset is set up in the "smartcity" realm+ * @when Login to OpenRemote "smartcity" realm as "smartcity"+ * @and Go to the asset page+ * @and Modify the thing asset+ * @and Add an attribute called "test"+ * @then The attribute should be visible+ * @and be of type "Integer"+ */+ test("can be added", async ({ page, mwcInput, assetViewer, manager }) => {+ await manager.setup("smartcity", { assets: [thing] });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Assets");+ await page.getByText("Thing").click();+ await assetViewer.switchMode("modify");++ await page.getByRole("button", { name: "Add attribute" }).click();++ const dialog = page.getByLabel("Add attribute");+ await dialog.locator("label").filter({ hasText: "Name" }).fill("test");+ await dialog.getByRole("button", { name: "Value type" }).click();+ await mwcInput.getSelectInputOption("Integer", dialog).click();+ await dialog.getByRole("button", { name: "Add" }).click();+ await page.getByRole("button", { name: "Save" }).click();++ await expect(assetViewer.getAttributeLocator("test")).toBeVisible();+ await expect(assetViewer.getAttributeLocator("test")).toContainText(/Integer/);+ await expect(assetViewer.getAttributeLocator("test").getByRole("spinbutton")).toBeVisible();+ });++ /**+ * @given A thing asset is set up in the "smartcity" realm+ * @when Login to OpenRemote "smartcity" realm as "smartcity"+ * @and Go to the asset page+ * @and Modify the thing asset+ * @and Remove the attribute called "test"+ * @then The attribute should not be visible+ */+ test("can be removed", async ({ page, assetViewer, manager }) => {+ await manager.setup("smartcity");+ await manager.createAsset({+ name: "Thing",+ type: "ThingAsset",+ realm: "smartcity",+ attributes: { ...commonAttrs, test: { name: "test", type: "integer" } },+ });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Assets");+ await page.getByText("Thing").click();+ await assetViewer.switchMode("modify");++ const attribute = assetViewer.getAttributeLocator("test");+ await expect(attribute).toBeVisible();+ await attribute.getByRole("button").last().click();+ await page.getByRole("button", { name: "Save" }).click();++ await expect(attribute).not.toBeVisible();+ });+});++test.describe("Configuration items", () => {+ test.beforeEach(async ({ manager }) => {+ await manager.initAssetModel();+ });++ /**+ * @given A thing asset is set up in the "smartcity" realm+ * @when Login to OpenRemote "smartcity" realm as "smartcity"+ * @and Go to the asset page+ * @and Modify the thing asset+ * @and Adding configuration items+ * @then The configuration items to be visible+ */+ test("can be added", async ({ page, assetViewer, manager }) => {+ await manager.setup("smartcity", { assets: [thing] });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Assets");+ await page.getByText("Thing").click();+ await assetViewer.switchMode("modify");++ const configurationItems = AssetModelUtil.getMetaItemDescriptors().map(+ ({ name }) => name as `${WellknownMetaItems}`+ );+ await assetViewer.addConfigurationItems("notes", ...configurationItems);+ for (const item of configurationItems) {+ await expect(+ assetViewer.getConfigurationItemLocator("notes", Util.camelCaseToSentenceCase(item))+ ).toBeVisible();+ }+ });++ test.describe(() => {+ let primitiveItemsWithValues: [`${WellknownMetaItems}`, unknown][];+ // let complexItemsWithValues: [`${WellknownMetaItems}`, unknown][];++ function valueForType(+ type: unknown,+ dimensions = 0,+ { string, number, boolean, object } = { string: "", number: 0, boolean: false, object: {} }+ ): unknown {+ if (dimensions > 0) {+ return [valueForType(type, 0, { string, number, boolean, object })];+ }+ switch (type) {+ case "string":+ return string;+ case "bigint":+ case "number":+ return number;+ case "boolean":+ return boolean;+ case "object":+ return object;+ }+ }++ /**+ * @given A thing asset is set up in the "smartcity" realm with all meta items+ * @when Login to OpenRemote "smartcity" realm as "smartcity"+ * @and Go to the asset page+ * @and Modify the thing asset+ */+ test.beforeEach(async ({ assetViewer, manager, page }) => {+ // We can safely ascribe defaults inline with their json type as these descriptors are primitives without format+ primitiveItemsWithValues = Util.getPrimitiveMetaItems().map((m) => {+ const { jsonType } = AssetModelUtil.getValueDescriptor(m.type)!;+ return [m.name, valueForType(jsonType, 0, { boolean: true, number: 0, string: "", object: {} })];+ }) as [`${WellknownMetaItems}`, any][];+ // TODO: resolve complex meta item values through their JSON Schema+ // complexItemsWithValues = Util.getComplexMetaItems().map((m) => {+ // const { jsonType, arrayDimensions } = AssetModelUtil.getValueDescriptor(m.type)!;+ // return [m.name, valueForType(jsonType, arrayDimensions)];+ // }) as [`${WellknownMetaItems}`, any][];+ await manager.setup("smartcity");+ await manager.createAsset({+ name: "Thing",+ type: "ThingAsset",+ realm: "smartcity",+ attributes: {+ ...commonAttrs,+ notes: { meta: Object.fromEntries([...primitiveItemsWithValues /*, ...complexItemsWithValues */]) },+ },+ });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Assets");+ await page.getByText("Thing").click();+ await assetViewer.switchMode("modify");+ });++ /**+ * @when Modifying configuration items+ * @then The configuration items should be visible+ */+ test("can be modified", async ({ page, assetViewer }) => {+ const updatedPrimitivesWithValues = Util.getPrimitiveMetaItems().map((m) => {+ const { jsonType } = AssetModelUtil.getValueDescriptor(m.type)!;+ return [m.name, valueForType(jsonType, 0, { boolean: false, number: 7, string: "test", object: {} })];+ }) as [`${WellknownMetaItems}`, any][];+ await assetViewer.expandAttribute("notes");++ // Modify primitive configuration items+ for (const [item, value] of updatedPrimitivesWithValues) {+ const itemLocator = assetViewer.getConfigurationItemLocator("notes");+ const options = { name: Util.camelCaseToSentenceCase(item) };+ if (typeof value === "string") {+ await itemLocator.getByRole("textbox", options).fill(value);+ } else if (typeof value === "number") {+ await itemLocator.getByRole("spinbutton", options).fill(`${value}`);+ } else if (value) {+ await itemLocator.getByRole("checkbox", options).uncheck();+ } else {+ await itemLocator.getByRole("checkbox", options).check();+ }+ }++ await page.getByRole("button", { name: "Save" }).click();++ for (const [item, value] of updatedPrimitivesWithValues) {+ const itemLocator = assetViewer.getConfigurationItemLocator("notes");+ const options = { name: Util.camelCaseToSentenceCase(item) };+ if (typeof value === "string") {+ await expect(itemLocator.getByRole("textbox", options)).toHaveValue(value);+ } else if (typeof value === "number") {+ await expect(itemLocator.getByRole("spinbutton", options)).toHaveValue(`${value}`);+ } else if (value) {+ await expect(itemLocator.getByRole("checkbox", options)).not.toBeChecked();+ } else {+ await expect(itemLocator.getByRole("checkbox", options)).toBeChecked();+ }+ }+ // Modify complex configuration items+ // jsonForms.walkForm();+ });++ /**+ * @when Removing configuration items+ * @then The configuration items should not be visible+ */+ test("can be removed", async ({ page, assetViewer }) => {+ // Remove primitive configuration items+ await assetViewer.removeConfigurationItems("notes", ...primitiveItemsWithValues.map(([item]) => item));+ // Remove complex configuration items+ // await assetViewer.removeConfigurationItems("notes", ...complexItemsWithValues.map(([item]) => item));++ await page.getByRole("button", { name: "Save" }).click();++ const configurationItems = AssetModelUtil.getMetaItemDescriptors().map(+ ({ name }) => name as `${WellknownMetaItems}`+ );+ for (const item of configurationItems) {+ await expect(+ assetViewer.getConfigurationItemLocator("notes", Util.camelCaseToSentenceCase(item))+ ).not.toBeVisible();+ }+ });++ test.afterEach(async ({ manager }) => {+ await manager.cleanUp();+ });+ });});test.afterEach(async ({ manager }) => {- await manager.cleanUp();+ await manager.cleanUp();});diff --git a/ui/app/manager/test/fixtures/manager.ts b/ui/app/manager/test/fixtures/manager.tsindex ae6be811c..cbf1688bc 100644--- a/ui/app/manager/test/fixtures/manager.ts+++ b/ui/app/manager/test/fixtures/manager.ts@@ -6,11 +6,20 @@ import type { DefaultAssets } from "./data/assets";const { admin, smartcity } = users;import { UserModel } from "../../src/pages/page-users";-import { Asset, ManagerAppConfig, ManagerConfig, Role } from "@openremote/model";-import { test as base, expect, type Page, type SharedComponentTestFixtures, type Shared, withPage } from "@openremote/test";+import { Asset, AssetModelUtil, ManagerAppConfig, Role } from "@openremote/model";+import {+ test as base,+ expect,+ type Page,+ type SharedComponentTestFixtures,+ type Shared,+ type TestFixture,+ withPage,+} from "@openremote/test";import { AssetsPage, 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";import { JsonForms } from "../../../../component/or-json-forms/test/fixtures";import { AssetTree } from "../../../../component/or-asset-tree/test/fixtures";import { type AxiosRequestConfig } from "axios";@@ -19,447 +28,463 @@ export const adminStatePath = path.join(__dirname, "data/.auth/admin.json");export const userStatePath = path.join(__dirname, "data/.auth/user.json");export class Manager {- private readonly clientId = "openremote";- private readonly managerHost: String;- readonly api: RestApi["api"];- readonly axios: RestApi["_axiosInstance"];-- public realm?: string;- public user?: UserModel;- public role?: Role;- public assets: Asset[] = [];- public rules: number[] = [];-- constructor(readonly page: Page, readonly baseURL: string) {- this.managerHost = process.env.managerUrl || "http://localhost:8080";- rest.initialise(`${this.managerHost}/api/master/`);- this.api = rest.api;- this.axios = rest.axiosInstance;- }-- /**- * Fulfill the `manager_config.json` response with a custom app config.- * @param config The manager app config to merge with the default.- */- async configureAppConfig(config: ManagerAppConfig) {- const realms = {- default: {- appTitle: "OpenRemote Manager Test",- language: "en"- }+ private readonly clientId = "openremote";+ private readonly managerHost: String;+ readonly api: RestApi["api"];+ readonly axios: RestApi["_axiosInstance"];++ public realm?: string;+ public user?: UserModel;+ public role?: Role;+ public assets: Asset[] = [];+ public rules: number[] = [];++ constructor(readonly page: Page, readonly baseURL: string) {+ this.managerHost = process.env.managerUrl || "http://localhost:8080";+ rest.initialise(`${this.managerHost}/api/master/`);+ this.api = rest.api;+ this.axios = rest.axiosInstance;}- await this.page.route("/api/master/configuration/manager",- async (route) => await route.fulfill({ json: { realms, ...config } })- );- }-- async goToRealmStartPage(realm: string) {- await this.page.goto(this.getAppUrl(realm));- }-- /**- * Navigate to a settings page inside the manager using the settings menu at the top right- * @param setting Name of the setting menu item- */- async navigateToMenuItem(setting: string) {- await this.page.click("button#menu-btn-desktop");- const menu = this.page.locator("#menu > #list > li").filter({ hasText: setting });- await menu.waitFor({ state: "visible" });- await menu.click();- }-- /**- * Switch to a realm using the realm picker- * @param name Name of the realm- */- async switchToRealmByRealmPicker(realm: string) {- await this.page.click("#realm-picker");- await this.page.locator("#desktop-right li", { hasText: realm }).click();- }-- /**- * Navigate to a certain tab page- * @param tab Tab name- */- async navigateToTab(tab: string) {- await this.page.click(`#desktop-left a:has-text("${tab}")`);- }-- /**- * Login as user, waits for username and password fields to be visible.- * @param user Username (admin or other)- */- async login(user: Usernames) {- const username = this.page.getByRole("textbox", { name: "Username or email" });- const password = this.page.getByRole("textbox", { name: "Password" });- await username.waitFor();- if ((await username.isVisible()) && (await password.isVisible())) {- await username.fill(user);- await password.fill(users[user].password);- await this.page.keyboard.press("Enter");++ /**+ * Init {@link AssetModelUtil} with asset infos, meta items and value descriptors.+ */+ async initAssetModel() {+ const assetInfosResponse = await this.api.AssetModelResource.getAssetInfos();+ const metaItemDescriptorResponse = await this.api.AssetModelResource.getMetaItemDescriptors();+ const valueDescriptorResponse = await this.api.AssetModelResource.getValueDescriptors();++ AssetModelUtil._assetTypeInfos = assetInfosResponse.data;+ AssetModelUtil._metaItemDescriptors = Object.values(metaItemDescriptorResponse.data);+ AssetModelUtil._valueDescriptors = Object.values(valueDescriptorResponse.data);}- }-- /**- * Logout from the manager.- *- * After logout waits until redirection finished.- */- async logout() {- if (await this.page.isVisible("#menu-btn-desktop")) {- await this.page.click("#menu-btn-desktop");- await this.page.locator("#menu > #list > li").filter({ hasText: "Log out" }).click();++ /**+ * Fulfill the `manager_config.json` response with a custom app config.+ * @param config The manager app config to merge with the default.+ */+ async configureAppConfig(config: ManagerAppConfig) {+ const realms = {+ default: {+ appTitle: "OpenRemote Manager Test",+ language: "en",+ },+ };+ await this.page.route(+ "/api/master/configuration/manager",+ async (route) => await route.fulfill({ json: { realms, ...config } })+ );}- // Wait for navigation to login page to prevent simultaneous navigation- await this.page.waitForURL("**/auth/realms/**");- }-- async getAccessToken(realm: string, username: Usernames, password: string) {- const data = new URLSearchParams();- data.append("client_id", this.clientId);- data.append("username", username);- data.append("password", password);- data.append("grant_type", "password");- const { access_token } = (- await this.axios.post(`${this.managerHost}/auth/realms/${realm}/protocol/openid-connect/token`, data, {- headers: {- "Content-Type": "application/x-www-form-urlencoded",- },- })- ).data;- return access_token;- }-- /**- * When an application initialises a WebSocket this will assign that instance to the `window.ws` object.- *- * Must only be used inside a `await page.addInitScript` before the WebSocket gets initialised.- */- hijackWebSocket() {- return () => {- const OriginalWS = WebSocket;- window.WebSocket = function (url: string | URL, protocols?: string | string[]) {- return (window as any).ws = new OriginalWS(url, protocols);- } as any;++ async goToRealmStartPage(realm: string) {+ await this.page.goto(this.getAppUrl(realm));}- }-- /**- * Send a WebSocket event to the server using an existing WebSocket connection.- *- * You must add `await page.addInitScript(manager.hijackWebSocket())`- *- * @param payload The playload to send to WebSocket server.- * @see {@link hijackWebSocket}- */- async sendWebSocketEvent(payload: any) {- await this.page.evaluate((message) => {- if ("ws" in window) {- const ws = window.ws as WebSocket;- if (ws && ws.readyState === ws.OPEN) {- return ws.send(message);- }- }- console.warn('No active WebSocket found.');- }, `EVENT:${JSON.stringify(payload)}`);- }-- /**- * Get the roles of the current realm- *- * Expects a realm to be configured- * @param config The axios request config- */- async getClientRoles(config?: AxiosRequestConfig<any>) {- try {- const response = await rest.api.UserResource.getClientRoles(this.realm!, this.clientId, config);- expect(response.status).toBe(200);- return response.data;- } catch (e) {- console.error("Failed to get roles", e.response.status);++ /**+ * Navigate to a settings page inside the manager using the settings menu at the top right+ * @param setting Name of the setting menu item+ */+ async navigateToMenuItem(setting: string) {+ await this.page.click("button#menu-btn-desktop");+ const menu = this.page.locator("#menu > #list > li").filter({ hasText: setting });+ await menu.waitFor({ state: "visible" });+ await menu.click();}- }-- /**- * Create an new role- *- * The `compositeRoleIds` are mapped by name to the corresponding role id.- *- * Expects a realm to be configured- * @param newRole The role to create- * @param roles The current stored roles to add the new role to- * @param config The axios request config- */- async createRole(newRole: Role, roles: Role[], config?: AxiosRequestConfig<any>) {- if (newRole.compositeRoleIds) {- newRole.compositeRoleIds = newRole.compositeRoleIds- .map((name) => roles.find((r) => r.name === name)?.id)- .filter(Boolean) as string[];++ /**+ * Switch to a realm using the realm picker+ * @param name Name of the realm+ */+ async switchToRealmByRealmPicker(realm: string) {+ await this.page.click("#realm-picker");+ await this.page.locator("#desktop-right li", { hasText: realm }).click();}- roles.push(newRole);- try {- const response = await rest.api.UserResource.updateRoles(this.realm!, roles, config);- expect(response.status).toBe(204);- this.role = newRole;- } catch (e) {- console.error("Failed to create role", e.response.status);++ /**+ * Navigate to a certain tab page+ * @param tab Tab name+ */+ async navigateToTab(tab: string) {+ await this.page.click(`#desktop-left a:has-text("${tab}")`);}- }-- /**- * Create an new user- *- * Expects a realm to be configured- * @param user The user to create- * @param config The axios request config- */- async createUser(user: UserModel, config?: AxiosRequestConfig<any>) {- try {- const response = await rest.api.UserResource.create(this.realm!, user, config);- expect(response.status).toBe(200);- this.user = response.data;- } catch (e) {- console.error("Failed to create user", e.response.status);++ /**+ * Login as user, waits for username and password fields to be visible.+ * @param user Username (admin or other)+ */+ async login(user: Usernames) {+ const username = this.page.getByRole("textbox", { name: "Username or email" });+ const password = this.page.getByRole("textbox", { name: "Password" });+ await username.waitFor();+ if ((await username.isVisible()) && (await password.isVisible())) {+ await username.fill(user);+ await password.fill(users[user].password);+ await this.page.keyboard.press("Enter");+ }}- }-- /**- * Add a role to the current user- *- * Expects a realm and user to be configured- * @param roles A list of roles to add to the user- * @param config The axios request config- */- async addUserRoles(roles: string[], config?: AxiosRequestConfig<any>) {- try {- const response = await rest.api.UserResource.updateUserClientRoles(- this.realm!,- this.user!.id!,- this.clientId,- roles,- config- );- expect(response.status).toBe(204);- } catch (e) {- console.error("Failed to update users' roles", e.response.status);++ /**+ * Logout from the manager.+ *+ * After logout waits until redirection finished.+ */+ async logout() {+ if (await this.page.isVisible("#menu-btn-desktop")) {+ await this.page.click("#menu-btn-desktop");+ await this.page.locator("#menu > #list > li").filter({ hasText: "Log out" }).click();+ }+ // Wait for navigation to login page to prevent simultaneous navigation+ await this.page.waitForURL("**/auth/realms/**");}- }-- /**- * Reset the user password with the smartcity users' password- *- * Expects a realm and user to be configured- * @param config The axios request config- */- async resetUserPassword(config?: AxiosRequestConfig<any>) {- try {- const response = await rest.api.UserResource.resetPassword(- this.realm!,- this.user!.id!,- { value: smartcity.password },- config- );- expect(response.status).toBe(204);- } catch (e) {- console.error("Failed to reset user password", e.response.status);++ async getAccessToken(realm: string, username: Usernames, password: string) {+ const data = new URLSearchParams();+ data.append("client_id", this.clientId);+ data.append("username", username);+ data.append("password", password);+ data.append("grant_type", "password");+ const { access_token } = (+ await this.axios.post(`${this.managerHost}/auth/realms/${realm}/protocol/openid-connect/token`, data, {+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ })+ ).data;+ return access_token;}- }-- /**- * Create an asset- * @param asset The asset to create- * @param config The axios request config- */- async createAsset(asset: Asset, config?: AxiosRequestConfig<any>) {- if(!config) {- const access_token = await this.getAccessToken("master", "admin", users.admin.password!);- config = { headers: { Authorization: `Bearer ${access_token}` } };++ /**+ * When an application initialises a WebSocket this will assign that instance to the `window.ws` object.+ *+ * Must only be used inside a `await page.addInitScript` before the WebSocket gets initialised.+ */+ hijackWebSocket() {+ return () => {+ const OriginalWS = WebSocket;+ window.WebSocket = function (url: string | URL, protocols?: string | string[]) {+ return ((window as any).ws = new OriginalWS(url, protocols));+ } as any;+ };}- await rest.api.AssetResource.create(asset, config)- .then((response) => {- expect(response.status).toBe(200);- this.assets.push(response.data);- })- .catch((e) => {- expect(e.response.status, { message: "Failed to create asset" }).toBe(409);- });- }-- /**- * Updates an asset- * @param asset The asset to update- * @param config The axios request config- */- async updateAsset(asset: Asset, config?: AxiosRequestConfig<any>) {- if(!config) {- const access_token = await this.getAccessToken("master", "admin", users.admin.password!);- config = { ...(config || {}), headers: { Authorization: `Bearer ${access_token}` } };- }- await rest.api.AssetResource.update(asset.id!, asset, config)- .then((response) => {- expect(response.status).toBe(200);- this.assets = [...this.assets.filter(a => a.id !== response.data.id), response.data as Asset];- })- .catch((e) => {- expect(e.response.status, { message: "Failed to update asset" }).toBe(409);- });++ /**+ * Send a WebSocket event to the server using an existing WebSocket connection.+ *+ * You must add `await page.addInitScript(manager.hijackWebSocket())`+ *+ * @param payload The playload to send to WebSocket server.+ * @see {@link hijackWebSocket}+ */+ async sendWebSocketEvent(payload: any) {+ await this.page.evaluate((message) => {+ if ("ws" in window) {+ const ws = window.ws as WebSocket;+ if (ws && ws.readyState === ws.OPEN) {+ return ws.send(message);+ }+ }+ console.warn("No active WebSocket found.");+ }, `EVENT:${JSON.stringify(payload)}`);}- /**- * Setup the testing environment by giving the realm name and additional parameters- * @param realm Realm to create- * @param [options] - Optional parameters for setup- * @param [options.user] - The user to create within the realm- * @param [options.role] - The role to assign or create- * @param [options.assets] - Assets to create for the realm- */- async setup(- realm: string,- { user, role, assets }: { user?: UserModel; role?: Role; assets?: Asset[] | DefaultAssets } = {}- ) {- const access_token = await this.getAccessToken("master", admin.username, admin.password);- const config = { headers: { Authorization: `Bearer ${access_token}` } };-- this.realm = realm;-- // Provision role- if (role) {- const roles = await this.getClientRoles(config);- if (roles) {- await this.createRole(role, roles, config);- }+ /**+ * Get the roles of the current realm+ *+ * Expects a realm to be configured+ * @param config The axios request config+ */+ async getClientRoles(config?: AxiosRequestConfig<any>) {+ try {+ const response = await rest.api.UserResource.getClientRoles(this.realm!, this.clientId, config);+ expect(response.status).toBe(200);+ return response.data;+ } catch (e) {+ console.error("Failed to get roles", e.response.status);+ }}- // Provision user- if (user) {- await this.createUser(user, config);- await this.addUserRoles(user.roles!, config);- await this.resetUserPassword(config);+ /**+ * Create an new role+ *+ * The `compositeRoleIds` are mapped by name to the corresponding role id.+ *+ * Expects a realm to be configured+ * @param newRole The role to create+ * @param roles The current stored roles to add the new role to+ * @param config The axios request config+ */+ async createRole(newRole: Role, roles: Role[], config?: AxiosRequestConfig<any>) {+ if (newRole.compositeRoleIds) {+ newRole.compositeRoleIds = newRole.compositeRoleIds+ .map((name) => roles.find((r) => r.name === name)?.id)+ .filter(Boolean) as string[];+ }+ roles.push(newRole);+ try {+ const response = await rest.api.UserResource.updateRoles(this.realm!, roles, config);+ expect(response.status).toBe(204);+ this.role = newRole;+ } catch (e) {+ console.error("Failed to create role", e.response.status);+ }}- // Provision assets- if (assets) {- this.assets = [];- for (const asset of assets) {- await this.createAsset(asset, config);- }+ /**+ * Create an new user+ *+ * Expects a realm to be configured+ * @param user The user to create+ * @param config The axios request config+ */+ async createUser(user: UserModel, config?: AxiosRequestConfig<any>) {+ try {+ const response = await rest.api.UserResource.create(this.realm!, user, config);+ expect(response.status).toBe(200);+ this.user = response.data;+ } catch (e) {+ console.error("Failed to create user", e.response.status);+ }}- }-- /**- * Deletes rules in the active realm- * @param config The axios request config- */- async deleteRealmRulesets(config?: AxiosRequestConfig<any>) {- for (const [i, id] of this.rules.entries()) {- try {- const response = await rest.api.RulesResource.deleteRealmRuleset(id!, config);- expect(response.status).toBe(204);- this.rules.splice(i);- } catch (e) {- console.warn("Could not delete realm rule: ", id);- }++ /**+ * Add a role to the current user+ *+ * Expects a realm and user to be configured+ * @param roles A list of roles to add to the user+ * @param config The axios request config+ */+ async addUserRoles(roles: string[], config?: AxiosRequestConfig<any>) {+ try {+ const response = await rest.api.UserResource.updateUserClientRoles(+ this.realm!,+ this.user!.id!,+ this.clientId,+ roles,+ config+ );+ expect(response.status).toBe(204);+ } catch (e) {+ console.error("Failed to update users' roles", e.response.status);+ }}- }-- /**- * Deletes assets- * @param config The axios request config- */- async deleteAssets(config?: AxiosRequestConfig<any>) {- const assetIds = this.assets.map(({ id }) => id!);- try {- const response = await rest.api.AssetResource.delete({ assetId: assetIds }, config);- expect(response.status).toBe(204);- this.assets = [];- } catch (e) {- console.warn("Could not delete asset(s): ", assetIds);++ /**+ * Reset the user password with the smartcity users' password+ *+ * Expects a realm and user to be configured+ * @param config The axios request config+ */+ async resetUserPassword(config?: AxiosRequestConfig<any>) {+ try {+ const response = await rest.api.UserResource.resetPassword(+ this.realm!,+ this.user!.id!,+ { value: smartcity.password },+ config+ );+ expect(response.status).toBe(204);+ } catch (e) {+ console.error("Failed to reset user password", e.response.status);+ }}- }-- /**- * Delete role- *- * Expects a realm to be configured- * @param roles The stored roles- * @param config The axios request config- */- async deleteRole(roles: Role[], config) {- roles = roles.filter((r) => r.id !== this.role!.id);- try {- const response = await rest.api.UserResource.updateRoles(this.realm!, roles, config);- expect(response.status).toBe(204);- delete this.role;- } catch (e) {- console.warn("Could not update roles: ", this.role);++ /**+ * Create an asset+ * @param asset The asset to create+ * @param config The axios request config+ */+ async createAsset(asset: Asset, config?: AxiosRequestConfig<any>) {+ if (!config) {+ const access_token = await this.getAccessToken("master", "admin", users.admin.password!);+ config = { headers: { Authorization: `Bearer ${access_token}` } };+ }+ await rest.api.AssetResource.create(asset, config)+ .then((response) => {+ expect(response.status).toBe(200);+ this.assets.push(response.data);+ })+ .catch((e) => {+ expect(e.response.status, { message: "Failed to create asset" }).toBe(409);+ });+ }++ /**+ * Updates an asset+ * @param asset The asset to update+ * @param config The axios request config+ */+ async updateAsset(asset: Asset, config?: AxiosRequestConfig<any>) {+ if (!config) {+ const access_token = await this.getAccessToken("master", "admin", users.admin.password!);+ config = { headers: { Authorization: `Bearer ${access_token}` } };+ }+ await rest.api.AssetResource.update(asset.id!, asset, config)+ .then((response) => {+ expect(response.status).toBe(200);+ this.assets = [...this.assets.filter((a) => a.id !== response.data.id), response.data as Asset];+ })+ .catch((e) => {+ expect(e.response.status, { message: "Failed to update asset" }).toBe(409);+ });}- }- /**- * Clean up the environment- */- async cleanUp() {- const access_token = await this.getAccessToken("master", "admin", users.admin.password!);- const config = { headers: { Authorization: `Bearer ${access_token}` } };+ /**+ * Setup the testing environment by giving the realm name and additional parameters+ * @param realm Realm to create+ * @param [options] - Optional parameters for setup+ * @param [options.user] - The user to create within the realm+ * @param [options.role] - The role to assign or create+ * @param [options.assets] - Assets to create for the realm+ */+ async setup(+ realm: string,+ { user, role, assets }: { user?: UserModel; role?: Role; assets?: Asset[] | DefaultAssets } = {}+ ) {+ const access_token = await this.getAccessToken("master", admin.username, admin.password);+ const config = { headers: { Authorization: `Bearer ${access_token}` } };++ this.realm = realm;++ // Provision role+ if (role) {+ const roles = await this.getClientRoles(config);+ if (roles) {+ await this.createRole(role, roles, config);+ }+ }++ // Provision user+ if (user) {+ await this.createUser(user, config);+ await this.addUserRoles(user.roles!, config);+ await this.resetUserPassword(config);+ }- if (this.rules.length > 0) {- await this.deleteRealmRulesets(config);+ // Provision assets+ if (assets) {+ this.assets = [];+ for (const asset of assets) {+ await this.createAsset(asset, config);+ }+ }}- if (this.assets.length > 0) {- await this.deleteAssets(config);+ /**+ * Deletes rules in the active realm+ * @param config The axios request config+ */+ async deleteRealmRulesets(config?: AxiosRequestConfig<any>) {+ for (const [i, id] of this.rules.entries()) {+ try {+ const response = await rest.api.RulesResource.deleteRealmRuleset(id!, config);+ expect(response.status).toBe(204);+ this.rules.splice(i);+ } catch (e) {+ console.warn("Could not delete realm rule: ", id);+ }+ }}- if (this.role && this.realm) {- const roles = await this.getClientRoles(config);- if (roles) {- await this.deleteRole(roles, config);- }+ /**+ * Deletes assets+ * @param config The axios request config+ */+ async deleteAssets(config?: AxiosRequestConfig<any>) {+ const assetIds = this.assets.map(({ id }) => id!);+ try {+ const response = await rest.api.AssetResource.delete({ assetId: assetIds }, config);+ expect(response.status).toBe(204);+ this.assets = [];+ } catch (e) {+ console.warn("Could not delete asset(s): ", assetIds);+ }}- }- getAppUrl(realm: string) {- return `${new URL(this.baseURL).origin}/manager/?realm=${realm}`;- }+ /**+ * Delete role+ *+ * Expects a realm to be configured+ * @param roles The stored roles+ * @param config The axios request config+ */+ async deleteRole(roles: Role[], config) {+ roles = roles.filter((r) => r.id !== this.role!.id);+ try {+ const response = await rest.api.UserResource.updateRoles(this.realm!, roles, config);+ expect(response.status).toBe(204);+ delete this.role;+ } catch (e) {+ console.warn("Could not update roles: ", this.role);+ }+ }++ /**+ * Clean up the environment+ */+ async cleanUp() {+ const access_token = await this.getAccessToken("master", "admin", users.admin.password!);+ const config = { headers: { Authorization: `Bearer ${access_token}` } };++ if (this.rules.length > 0) {+ await this.deleteRealmRulesets(config);+ }++ if (this.assets.length > 0) {+ await this.deleteAssets(config);+ }++ if (this.role && this.realm) {+ const roles = await this.getClientRoles(config);+ if (roles) {+ await this.deleteRole(roles, config);+ }+ }+ }++ getAppUrl(realm: string) {+ return `${new URL(this.baseURL).origin}/manager/?realm=${realm}`;+ }}function withManager<R>(managerPage: Function): TestFixture<R, { page: Page; shared: Shared; manager: Manager }> {- return async ({ page: basePage, shared, manager }, use) => {- expect(manager).toBeInstanceOf(Manager);- await use(new (managerPage.bind(null, basePage, shared, manager))());- };+ return async ({ page: basePage, shared, manager }, use) => {+ expect(manager).toBeInstanceOf(Manager);+ await use(new (managerPage.bind(null, basePage, shared, manager))());+ };}interface PageFixtures {- assetsPage: AssetsPage;- realmsPage: RealmsPage;- rolesPage: RolesPage;- rulesPage: RulesPage;- usersPage: UsersPage;+ assetsPage: AssetsPage;+ realmsPage: RealmsPage;+ rolesPage: RolesPage;+ rulesPage: RulesPage;+ usersPage: UsersPage;}interface ComponentFixtures extends SharedComponentTestFixtures {- assetViewer: AssetViewer;- assetTree: AssetTree;- collapsiblePanel: CollapsiblePanel;- jsonForms: JsonForms;+ assetViewer: AssetViewer;+ assetTree: AssetTree;+ collapsiblePanel: CollapsiblePanel;+ jsonForms: JsonForms;+ mwcInput: MwcInput;}interface Fixtures extends PageFixtures, ComponentFixtures {- manager: Manager;+ manager: Manager;}export const test = base.extend<Fixtures>({- manager: async ({ page, baseURL }, use) => await use(new Manager(page, baseURL!)),- // Pages- assetsPage: withManager(AssetsPage),- realmsPage: withManager(RealmsPage),- rolesPage: withManager(RolesPage),- rulesPage: withManager(RulesPage),- usersPage: withManager(UsersPage),- // Components- assetViewer: withPage(AssetViewer),- assetTree: withPage(AssetTree),- collapsiblePanel: withPage(CollapsiblePanel),- jsonForms: withPage(JsonForms),+ manager: async ({ page, baseURL }, use) => await use(new Manager(page, baseURL!)),+ // Pages+ assetsPage: withManager(AssetsPage),+ realmsPage: withManager(RealmsPage),+ rolesPage: withManager(RolesPage),+ rulesPage: withManager(RulesPage),+ usersPage: withManager(UsersPage),+ // Components+ assetViewer: withPage(AssetViewer),+ assetTree: withPage(AssetTree),+ collapsiblePanel: withPage(CollapsiblePanel),+ jsonForms: withPage(JsonForms),+ mwcInput: withPage(MwcInput),});diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.tsindex 063e2809e..af497d89f 100644--- a/ui/component/core/src/util.ts+++ b/ui/component/core/src/util.ts@@ -1,5 +1,6 @@import {Asset,+ AssetModelUtil,AssetDescriptor,Attribute,AttributeDescriptor,@@ -22,11 +23,9 @@ import {AbstractNameValueDescriptorHolder,MetaItemDescriptor,ValueFormatStyleRepresentation,- Role,} from "@openremote/model";import i18next from "i18next";import Qs from "qs";-import {AssetModelUtil} from "@openremote/model";import moment from "moment";import DateTimeFormatOptions = Intl.DateTimeFormatOptions;import {transform} from "lodash";@@ -222,11 +221,7 @@ export function isObject(object: any): boolean {return false;}-export function isFunction(object: any): boolean {- return !!(object && object.constructor && object.call && object.apply);-}--export function objectsEqual(obj1?: any, obj2?: any, deep: boolean = true): boolean {+export function objectsEqual(obj1?: any, obj2?: any, deep = true): boolean {if (obj1 === null || obj1 === undefined || obj2 === null || obj2 === undefined) {return obj1 === obj2;}@@ -384,14 +379,8 @@ export function capitaliseFirstLetter(str: string | undefined) {return str.charAt(0).toUpperCase() + str.slice(1);}-export function enumContains(enm: object, val: string): boolean {- return enm && Object.values(enm).includes(val);-}--export function getEnumKeyAsString(enm: object, val: string): string {- // @ts-ignore- const key = Object.keys(enm).find((k) => enm[k] === val);- return key!;+export function getEnumKeyAsString(enm: object, val: string): string | undefined {+ return Object.keys(enm).find((k) => enm[k as keyof object] === val);}/* For a given date, get the ISO week number@@ -496,7 +485,7 @@ export function dateToCronString(date: Date): string {* Input for example would be `0 00 11 * * ? *` for every day at 11am.* If the input is '*', it will be replaced by 1. (month parameter of '*' becomes January)*/-export function cronStringToISOString(cronString: String, isUTC: boolean): string | undefined {+export function cronStringToISOString(cronString: string, isUTC: boolean): string | undefined {const splStr = cronString.split(" ");if(!Number.isNaN(Number(splStr[0])) && !Number.isNaN(Number(splStr[1])) && !Number.isNaN(Number(splStr[2])) && (!Number.isNaN(Number(splStr[3])) || splStr[3] == '*')) {const year: string = (!Number.isNaN(Number(splStr[6])) ? splStr[6] : new Date().getFullYear()).toString();@@ -522,8 +511,6 @@ export function cronStringToISOString(cronString: String, isUTC: boolean): strinreturn undefined;}--export function getMetaValue(name: string | NameHolder, attribute: Attribute<any> | undefined, descriptor?: ValueDescriptorHolder | ValueDescriptor | string): any | undefined {const metaName = typeof name === "string" ? name : (name as NameHolder).name!;@@ -550,6 +537,22 @@ export function hasMetaItem(name: string | NameHolder, attribute: Attribute<any>return false;}+export function isPrimitiveMetaItem(descriptor: ValueDescriptor | undefined): boolean {+ return !isComplexMetaItem(descriptor);+}++export function isComplexMetaItem(descriptor: ValueDescriptor | undefined): boolean {+ return Boolean(descriptor?.jsonType === "object" || descriptor?.arrayDimensions && descriptor.arrayDimensions > 0);+}++export function getPrimitiveMetaItems(): MetaItemDescriptor[] {+ return AssetModelUtil.getMetaItemDescriptors().filter(m => isPrimitiveMetaItem(AssetModelUtil.getValueDescriptor(m.type)));+}++export function getComplexMetaItems(): MetaItemDescriptor[] {+ return AssetModelUtil.getMetaItemDescriptors().filter(m => isComplexMetaItem(AssetModelUtil.getValueDescriptor(m.type)));+}+export function getAssetTypeLabel(type: string | AssetDescriptor | undefined): string {if (typeof type === "string") {type = AssetModelUtil.getAssetDescriptor(type);diff --git a/ui/component/or-app/src/or-header.ts b/ui/component/or-app/src/or-header.tsindex 51b6c2a67..6232ca824 100644--- a/ui/component/or-app/src/or-header.ts+++ b/ui/component/or-app/src/or-header.ts@@ -62,7 +62,7 @@ function hasRequiredRole(option: HeaderItem): boolean {return option.roles.some((r) => manager.hasRole(r));}- if (Util.isFunction(option.roles)) {+ if (typeof option.roles === "function") {return (option.roles as () => boolean)();}diff --git a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts b/ui/component/or-asset-viewer/src/or-edit-asset-panel.tsindex c40d0116f..29e65d09c 100644--- a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts+++ b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts@@ -331,6 +331,7 @@ export class OrEditAssetPanel extends LitElement {const deleteAttribute = () => {delete this.asset.attributes![attribute.name!];this._onModified();+ this.requestUpdate();};const descriptor = AssetModelUtil.getAttributeDescriptor(attribute.name!, assetType);@@ -392,7 +393,6 @@ export class OrEditAssetPanel extends LitElement {protected _onModified() {this.dispatchEvent(new OrEditAssetModifiedEvent(this.validate()));- this.requestUpdate();}public validate(): ValidatorResult[] {@@ -461,6 +461,7 @@ export class OrEditAssetPanel extends LitElement {const removeMetaItem = () => {delete attribute.meta![metaItem.name!];this._onModified();+ this.requestUpdate();};const template = html`@@ -523,6 +524,7 @@ export class OrEditAssetPanel extends LitElement {if (!isDisabled(attr)) {this.asset.attributes![attr.name!] = attr;this._onModified();+ this.requestUpdate();}},content: html`<or-mwc-input id="add-btn" .type="${InputType.BUTTON}" disabled label="add"></or-mwc-input>`@@ -593,6 +595,7 @@ export class OrEditAssetPanel extends LitElement {if (descriptor) {attribute.meta![descriptor.name!] = (descriptor.type === 'boolean') ? true : null;this._onModified();+ this.requestUpdate();}});}@@ -604,7 +607,6 @@ export class OrEditAssetPanel extends LitElement {}protected _getParentTemplate() {- const viewer = this;let dialog: OrMwcDialog;const setParent = () => {diff --git a/ui/component/or-asset-viewer/test/fixtures/index.ts b/ui/component/or-asset-viewer/test/fixtures/index.tsindex a35f797a4..9b20e4178 100644--- a/ui/component/or-asset-viewer/test/fixtures/index.ts+++ b/ui/component/or-asset-viewer/test/fixtures/index.ts@@ -1,80 +1,107 @@-import type { Locator, Page } from "@openremote/test";+import { expect, type Locator, type Page } from "@openremote/test";import type { WellknownMetaItems } from "@openremote/model";import * as Util from "@openremote/core/lib/util";export class AssetViewer {- constructor(private readonly page: Page) {}+ constructor(private readonly page: Page) {}- /**- * Switch between modify mode and view mode.- * @param targetMode The mode to switch to- */- async switchMode(targetMode: "modify" | "view") {- const selector = this.page.getByRole("button", { name: targetMode });- await selector.waitFor({ state: "visible" });- await selector.click();- }+ /**+ * Switch between modify mode and view mode.+ * @param targetMode The mode to switch to+ */+ async switchMode(targetMode: "modify" | "view") {+ const selector = this.page.getByRole("button", { name: targetMode });+ await selector.waitFor({ state: "visible" });+ await selector.click();+ }- /**- * Get a locator to the asset header.- * @param assetName The asset name- */- getHeaderLocator(assetName: string) {- return this.page.locator(`#asset-header`, { hasText: assetName });- }+ /**+ * Get a locator to the asset header.+ * @param assetName The asset name+ */+ getHeaderLocator(assetName: string) {+ return this.page.locator(`#asset-header`, { hasText: assetName });+ }- /**- * Get a locator to an attribute.- * @param attribute The attribute name- */- getAttributeLocator(attribute: string): Locator {- return this.page.getByRole("row", { name: new RegExp(`\\b${attribute}\\b`, "i") });- }+ /**+ * Get a locator to an attribute.+ * @param attribute The attribute name+ */+ getAttributeLocator(attribute: string): Locator {+ return this.page.getByRole("row", { name: new RegExp(`\\b${attribute}\\b`, "i") });+ }- /**- * Set a value for a given attribute.- * @param attribute The attribute name- * @param value The value to set- */- async setAttributeValue(attribute: string, value: string) {- await this.getAttributeLocator(attribute).locator("input").fill(value);- }+ /**+ * Set a value for a given attribute.+ * @param attribute The attribute name+ * @param value The value to set+ */+ async setAttributeValue(attribute: string, value: string) {+ await this.getAttributeLocator(attribute).locator("input").fill(value);+ }- /**- * Add configuration items to an attribute by its name.- * @param attribute The attribute's name- * @param items The configuration items to add- */- async addConfigurationItems(attribute: string, ...items: `${WellknownMetaItems}`[]) {- const locator = this.getAttributeLocator(attribute);- // TODO: handle expanded and non expand configuration items programmatically- // if (await this.page.getByRole("button", { name: "Expand all" }).isVisible()) {- // await locator.getByRole("cell", { name: new RegExp(`\\b${attribute}\\b`, "i") }).click();- // }- await locator.locator("+ tr").getByRole("button", { name: "Add configuration items" }).click();- for (const item of items) {- await this.page- .locator("li")- .filter({ hasText: Util.camelCaseToSentenceCase(item) })- .check();+ /**+ * Add configuration items to an attribute by its name.+ * @param attribute The attribute's name+ * @param items The configuration items to add+ */+ async addConfigurationItems(attribute: string, ...items: `${WellknownMetaItems}`[]) {+ const configItemLocator = await this.expandAttribute(attribute);+ await configItemLocator.getByRole("button", { name: "Add configuration items" }).click();+ for (const item of items) {+ await this.page+ .locator("li", { has: this.page.getByText(Util.camelCaseToSentenceCase(item), { exact: true }) })+ .check();+ }+ await this.page.getByRole("button", { name: "Add", exact: true }).click();}- await this.page.getByRole("button", { name: "Add", exact: true }).click();- // // close attribute menu- // await this.page.click(`td:has-text("${attr}") >> nth=0`);- }- /**- * Gets the locator of the attribute configuration item row.- *- * If an item is supplied the locator will be narrowed down to the item.- *- * @param attribute The attribute name- * @param item The configuration item to narrow down to- */- getConfigurationItemLocator(attribute: string, item?: string): Locator {- return item- ? // match the sibling row i.e. the configuration items row of the attribute- this.getAttributeLocator(attribute).locator("+ tr", { hasText: new RegExp(`\\b${item}\\b`, "i") })- : this.getAttributeLocator(attribute).locator("+ tr");- }+ /**+ * Remove configuration items to an attribute by its name.+ * @param attribute The attribute's name+ * @param items The configuration items to remove+ */+ async removeConfigurationItems(attribute: string, ...items: `${WellknownMetaItems}`[]) {+ const configItemLocator = await this.expandAttribute(attribute);+ for (const item of items) {+ const byText = this.page.getByText(Util.camelCaseToSentenceCase(item), { exact: true });+ await expect(configItemLocator.filter({ has: byText })).toBeVisible();+ const removeButton = configItemLocator+ .locator("[class=meta-item-wrapper]", { has: byText })+ .locator("button:last-child");+ await removeButton.hover({ force: true });+ await removeButton.click({ force: true });+ await expect(configItemLocator.filter({ has: byText })).not.toBeVisible();+ }+ }++ /**+ * Gets the locator of the attribute configuration item row.+ *+ * If an item is supplied the locator will be narrowed down to the item.+ *+ * @param attribute The attribute name+ * @param item The configuration item to narrow down to+ */+ getConfigurationItemLocator(attribute: string, item?: string): Locator {+ return item+ ? // match the sibling row i.e. the configuration items row of the attribute+ this.getAttributeLocator(attribute).locator("+ tr", { hasText: new RegExp(`\\b${item}\\b`, "i") })+ : this.getAttributeLocator(attribute).locator("+ tr");+ }++ /**+ * Ensure that the attribute is expanded+ * @param attribute The attribute name to ensure to expand.+ * @returns The config item locator that belongs to the attribute.+ */+ async expandAttribute(attribute: string): Promise<Locator> {+ const attributeLocator = this.getAttributeLocator(attribute);+ const configItemLocator = attributeLocator.locator("+ tr");+ if (!(await configItemLocator.getAttribute("class"))?.includes("expanded")) {+ await attributeLocator.getByRole("cell", { name: new RegExp(`\\b${attribute}\\b`, "i") }).click();+ await expect(configItemLocator).toHaveClass(/expanded/);+ }+ return configItemLocator;+ }}diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.tsindex e5e5fec90..a56a03f41 100644--- a/ui/component/or-attribute-input/src/index.ts+++ b/ui/component/or-attribute-input/src/index.ts@@ -120,7 +120,7 @@ let valueDescriptorSchemaHashes: Record<string, string>const schemas = new Map<string, any>()export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => ValueInputProviderGenerator = (fallback) => (assetDescriptor, valueHolder, valueHolderDescriptor, valueDescriptor, valueChangeNotifier, options) => {- if (valueDescriptor.jsonType === "object" || valueDescriptor.arrayDimensions && valueDescriptor.arrayDimensions > 0) {+ if (Util.isComplexMetaItem(valueDescriptor)) {const disabled = !!(options && options.disabled);const readonly = !!(options && options.readonly);const label = options.label;@@ -135,16 +135,16 @@ export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => Vlet prevValue: any;const onChanged = (dataAndErrors: {errors: ErrorObject[] | undefined, data: any}) => {- if (!initialised) {- return- };-- if (!Util.objectsEqual(dataAndErrors.data, prevValue)) {- prevValue = dataAndErrors.data;- valueChangeNotifier({- value: dataAndErrors.data- });- }+ if (!initialised) {+ return+ };++ if (!Util.objectsEqual(dataAndErrors.data, prevValue)) {+ prevValue = dataAndErrors.data;+ valueChangeNotifier({+ value: dataAndErrors.data+ });+ }};const doLoad = async (data: any) => {@@ -154,8 +154,8 @@ export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => Vinitialised = true;if (!valueDescriptorSchemaHashes) {- const response = await manager.rest.api.StatusResource.getInfo();- valueDescriptorSchemaHashes = response.data.valueDescriptorSchemaHashes;+ const response = await manager.rest.api.StatusResource.getInfo();+ valueDescriptorSchemaHashes = response.data.valueDescriptorSchemaHashes;}const descriptor = valueDescriptor.name + "[]".repeat(valueDescriptor.arrayDimensions ?? 0);diff --git a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.tsindex c3be8c42a..369363d1e 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts@@ -823,18 +823,16 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {case AssetQueryOperator.LESS_THAN:case AssetQueryOperator.LESS_EQUALS:case AssetQueryOperator.BETWEEN:- const key = Util.getEnumKeyAsString(AssetQueryOperator, value);-if (valueDescriptor.jsonType === "number") {predicate = {predicateType: "number",- operator: key as AQO+ operator: Util.getEnumKeyAsString(AssetQueryOperator, value) as AQO};} else {// Assume datetimepredicate = {predicateType: "datetime",- operator: key as AQO+ operator: Util.getEnumKeyAsString(AssetQueryOperator, value) as AQO};}break;diff --git a/ui/test/fixtures/index.ts b/ui/test/fixtures/index.tsindex 272c33c51..3cf483e62 100644--- a/ui/test/fixtures/index.ts+++ b/ui/test/fixtures/index.ts@@ -40,4 +40,5 @@ export const ctFixtures: Fixtures<PlaywrightTestArgs & PlaywrightTestOptions & Sshared: withPage(CtShared),};-export { test as ct, type ComponentTestType, type Shared, type BasePage, type Page, type Locator, type Project };+export const ct = test;+export type { BasePage, ComponentTestType, Locator, Page, Project, Shared, TestFixture };