From 2bd0b1a081b7efd101f86f2460d699acd9babe11 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Thu, 1 Oct 2026 15:29:22 +0200 Subject: [PATCH 01/21] Add asset attribute configuration import and export --- .../manager/asset/AssetResourceImpl.java | 74 ++ .../openremote/model/asset/AssetResource.java | 80 ++ .../model/asset/AttributeConfiguration.java | 55 ++ .../asset/AttributeConfigurationSummary.java | 49 ++ .../AttributeConfigurationTypeMismatch.java | 61 ++ .../model/asset/ConfigurationTemplate.java | 69 ++ .../ConfigurationTemplateImportFailure.java | 44 + .../ConfigurationTemplateImportPreview.java | 94 +++ .../ConfigurationTemplateImportRequest.java | 54 ++ .../model/util/ConfigurationTemplateUtil.java | 235 ++++++ .../util/ConfigurationTemplateUtilTest.groovy | 232 ++++++ .../assets/ConfigurationTemplateTest.groovy | 302 +++++++ ui/app/shared/locales/en/or.json | 30 + ui/app/shared/locales/nl/or.json | 30 + .../src/configuration-template.ts | 763 ++++++++++++++++++ ui/component/or-asset-viewer/src/index.ts | 10 +- .../src/or-edit-asset-panel.ts | 55 +- ui/component/or-asset-viewer/src/style.ts | 10 + ui/component/or-map/src/controls/legend.ts | 4 +- .../or-map/src/controls/preset-filter.ts | 27 +- ui/component/or-map/src/controls/styles.ts | 29 - .../theme/src/components/or-vaadin-badge.css | 13 +- ui/component/theme/src/default.css | 2 + 23 files changed, 2271 insertions(+), 51 deletions(-) create mode 100644 model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java create mode 100644 model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java create mode 100644 model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java create mode 100644 model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java create mode 100644 model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java create mode 100644 model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java create mode 100644 model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java create mode 100644 model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java create mode 100644 model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy create mode 100644 test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy create mode 100644 ui/component/or-asset-viewer/src/configuration-template.ts delete mode 100644 ui/component/or-map/src/controls/styles.ts diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java index 316f9baf1b..f948083dcd 100644 --- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java +++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java @@ -47,12 +47,17 @@ import org.openremote.model.asset.Asset; import org.openremote.model.asset.AssetResource; import org.openremote.model.asset.AssetTree; +import org.openremote.model.asset.ConfigurationTemplate; +import org.openremote.model.asset.ConfigurationTemplateImportFailure; +import org.openremote.model.asset.ConfigurationTemplateImportPreview; +import org.openremote.model.asset.ConfigurationTemplateImportRequest; import org.openremote.model.asset.UserAssetLink; import org.openremote.model.attribute.*; import org.openremote.model.http.RequestParams; import org.openremote.model.query.AssetQuery; import org.openremote.model.query.filter.RealmPredicate; import org.openremote.model.security.ClientRole; +import org.openremote.model.util.ConfigurationTemplateUtil; import org.openremote.model.util.TextUtil; import org.openremote.model.util.ValueUtil; @@ -466,6 +471,75 @@ public Asset update(RequestParams requestParams, String assetId, Asset ass } } + @Override + public ConfigurationTemplate exportConfigurationTemplate( + RequestParams requestParams, String assetId, List attributeNames) { + // Reuses the read access rules of #get, including the protected view for a restricted user + ConfigurationTemplate document = + ConfigurationTemplateUtil.export(get(requestParams, assetId), attributeNames); + + if (document.getAttributes() == null || document.getAttributes().isEmpty()) { + throw new WebApplicationException("No configuration items to export", BAD_REQUEST); + } + return document; + } + + @Override + public ConfigurationTemplateImportPreview previewConfigurationTemplateImport( + RequestParams requestParams, String assetId, ConfigurationTemplateImportRequest request) { + + Asset storageAsset = assetStorageService.find(assetId, true); + + if (storageAsset == null) { + LOG.fine("Asset not found: assetID=" + assetId); + throw new WebApplicationException(NOT_FOUND); + } + + throwIfNotRealmActiveAndAccessible(storageAsset.getRealm()); + + if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), assetId)) { + LOG.fine( + "Forbidden access for restricted user: username=" + + getUsername() + + ", assetID=" + + assetId); + throw new WebApplicationException(FORBIDDEN); + } + + if (request == null || request.getDraft() == null) { + throw new WebApplicationException("An asset draft is required", BAD_REQUEST); + } + + Asset draft = request.getDraft(); + + if (!Objects.equals(assetId, draft.getId()) + || !Objects.equals(storageAsset.getRealm(), draft.getRealm()) + || !Objects.equals(storageAsset.getType(), draft.getType())) { + throw importFailure( + ConfigurationTemplateImportPreview.failed( + ConfigurationTemplateImportFailure.DRAFT_MISMATCH)); + } + + ConfigurationTemplateImportPreview preview = + ConfigurationTemplateUtil.preview(draft, request.getDocument()); + + if (preview.getFailure() != null) { + throw importFailure(preview); + } + + return preview; + } + + protected WebApplicationException importFailure(ConfigurationTemplateImportPreview preview) { + Response.Status status = + preview.getFailure() == ConfigurationTemplateImportFailure.DRAFT_MISMATCH + ? CONFLICT + : BAD_REQUEST; + + return new WebApplicationException( + Response.status(status).entity(preview).type(MediaType.APPLICATION_JSON_TYPE).build()); + } + @Override public AttributeWriteResult writeAttributeValue( RequestParams requestParams, String assetId, String attributeName, Object value) { diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java index db616548b8..3ab1aa16ea 100644 --- a/model/src/main/java/org/openremote/model/asset/AssetResource.java +++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java @@ -344,6 +344,86 @@ Asset update( value = ASSET_UPDATE))) Asset asset); + /** + * Retrieve a configuration template of the asset: a user editable document holding the type and + * metadata of every attribute that has metadata. Repeat the attributeName query parameter to + * export a subset of them. Access follows the same rules as {@link #get}. A 400 status is + * returned if nothing is left to export. + */ + @GET + @Path("{assetId}/configurationTemplate") + @Produces(APPLICATION_JSON) + @RolesAllowed({Constants.READ_ASSETS_ROLE}) + @Operation( + operationId = "exportConfigurationTemplate", + summary = "Export a configuration template of an asset", + description = + "Returns a versioned document holding the type and metadata of each attribute that has metadata, limited to the requested attribute names when any are given. Attributes without metadata are never included. Exporting nothing is rejected.") + @OpenApiResponses.Ok + @OpenApiResponses.Authenticated + @OpenApiResponses.BadRequest + @OpenApiResponses.NotFound + ConfigurationTemplate exportConfigurationTemplate( + @BeanParam RequestParams requestParams, + @Parameter(description = ASSET_ID, example = EXAMPLE_ASSET_ID) @PathParam("assetId") + String assetId, + @Parameter( + description = + "Attribute names to export. Repeat the query parameter for multiple attributes, omit it to export all attributes that have metadata.", + style = ParameterStyle.FORM, + explode = Explode.TRUE) + @QueryParam("attributeName") + List attributeNames); + + /** + * Validate a configuration template against an asset draft and report what importing it would do, + * without storing anything. The returned patched attributes are for the client to apply to the + * draft once the user confirms, so the same access as {@link #update} is required. A 400 status + * is returned if no draft is given or the template cannot be imported, and a 409 status if the + * draft no longer identifies the persisted asset. A rejected template is answered with the + * preview, whose failure names the reason. + */ + @POST + @Path("{assetId}/configurationTemplate/import") + @Consumes(APPLICATION_JSON) + @Produces(APPLICATION_JSON) + @RolesAllowed({Constants.WRITE_ASSETS_ROLE}) + @Operation( + operationId = "previewConfigurationTemplateImport", + summary = "Preview a configuration template import", + description = + "Validates the document, matches its attributes against the draft by name and type, and returns the compatibility report together with the draft attributes holding the imported metadata. Nothing is stored; the client applies the patch after the user confirms.") + @OpenApiResponses.Ok + @OpenApiResponses.Authenticated + @ApiResponse( + responseCode = "400", + description = + "The draft is missing, or the document cannot be imported; a rejected document is answered with the preview, whose failure names the reason", + content = { + @Content( + mediaType = APPLICATION_JSON, + schema = @Schema(implementation = ConfigurationTemplateImportPreview.class)), + @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class)) + }) + @OpenApiResponses.NotFound + @ApiResponse( + responseCode = "409", + description = + "The draft no longer identifies the persisted asset; the preview failure is DRAFT_MISMATCH", + content = + @Content( + mediaType = APPLICATION_JSON, + schema = @Schema(implementation = ConfigurationTemplateImportPreview.class))) + ConfigurationTemplateImportPreview previewConfigurationTemplateImport( + @BeanParam RequestParams requestParams, + @Parameter(description = ASSET_ID, example = EXAMPLE_ASSET_ID) @PathParam("assetId") + String assetId, + @RequestBody( + required = true, + description = + "The asset draft being edited and the contents of the selected configuration file.") + @NotNull ConfigurationTemplateImportRequest request); + /** * Updates an attribute of an asset. Regular users can only update assets in their authenticated * realm, the superuser can update assets in other (all) realms. A 403 status is returned if a diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java new file mode 100644 index 0000000000..d54f7681c7 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java @@ -0,0 +1,55 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * The configuration of a single {@link org.openremote.model.attribute.Attribute} within an {@link + * ConfigurationTemplate}. The attribute name is the document map key, so it is not repeated here. + */ +@Schema( + description = + "Configuration of a single attribute; the attribute name is the key within the document.") +public class AttributeConfiguration { + + @Schema(description = "Value descriptor name of the attribute, e.g. number.") + protected String type; + + @Schema(description = "Metadata keyed by meta-item name, exactly as stored on the attribute.") + protected ObjectNode meta; + + @JsonCreator + public AttributeConfiguration( + @JsonProperty("type") String type, @JsonProperty("meta") ObjectNode meta) { + this.type = type; + this.meta = meta; + } + + public String getType() { + return type; + } + + public ObjectNode getMeta() { + return meta; + } +} diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java new file mode 100644 index 0000000000..18c8f3879c --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java @@ -0,0 +1,49 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; + +/** An attribute of a {@link ConfigurationTemplate} as reported to the user. */ +@Schema(description = "Name and type of an attribute within an imported document.") +public class AttributeConfigurationSummary { + + @Schema(description = "Attribute name.") + protected String name; + + @Schema(description = "Value descriptor name of the attribute, e.g. number.") + protected String type; + + @JsonCreator + public AttributeConfigurationSummary( + @JsonProperty("name") String name, @JsonProperty("type") String type) { + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public String getType() { + return type; + } +} diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java new file mode 100644 index 0000000000..7271391d72 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java @@ -0,0 +1,61 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * An attribute that cannot be imported because the target attribute holds a different value type. + */ +@Schema(description = "Attribute skipped on import because the target type differs.") +public class AttributeConfigurationTypeMismatch { + + @Schema(description = "Attribute name.") + protected String name; + + @Schema(description = "Value descriptor name within the imported document.") + protected String importedType; + + @Schema(description = "Value descriptor name of the target attribute.") + protected String targetType; + + @JsonCreator + public AttributeConfigurationTypeMismatch( + @JsonProperty("name") String name, + @JsonProperty("importedType") String importedType, + @JsonProperty("targetType") String targetType) { + this.name = name; + this.importedType = importedType; + this.targetType = targetType; + } + + public String getName() { + return name; + } + + public String getImportedType() { + return importedType; + } + + public String getTargetType() { + return targetType; + } +} diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java new file mode 100644 index 0000000000..e46b77de55 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java @@ -0,0 +1,69 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.Map; + +/** + * A configuration template: a user editable document holding the configuration of the {@link + * org.openremote.model.attribute.Attribute}s of an {@link Asset}. Attributes are keyed by attribute + * name. + */ +@Schema( + description = + "Versioned configuration template holding the attribute configuration of an asset, keyed by attribute name.") +public class ConfigurationTemplate { + + /** The only document version this release can read and write. */ + public static final int CURRENT_VERSION = 1; + + @Schema(description = "Document format version.", example = "1") + protected int version; + + @Schema(description = "Asset type the template was exported from.") + protected String assetType; + + @Schema(description = "Attribute configuration keyed by attribute name.") + protected Map attributes; + + @JsonCreator + public ConfigurationTemplate( + @JsonProperty("version") int version, + @JsonProperty("assetType") String assetType, + @JsonProperty("attributes") Map attributes) { + this.version = version; + this.assetType = assetType; + this.attributes = attributes; + } + + public int getVersion() { + return version; + } + + public String getAssetType() { + return assetType; + } + + public Map getAttributes() { + return attributes; + } +} diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java new file mode 100644 index 0000000000..fdccd1d8c6 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java @@ -0,0 +1,44 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +/** Reason why a {@link ConfigurationTemplate} cannot be imported. */ +public enum ConfigurationTemplateImportFailure { + + /** The document is not parsable JSON or is not a JSON object. */ + INVALID_JSON, + + /** The document version is not {@link ConfigurationTemplate#CURRENT_VERSION}. */ + UNSUPPORTED_VERSION, + + /** The version, asset type or attributes field is absent. */ + MISSING_REQUIRED_FIELD, + + /** The attributes field or one of its entries does not hold a type and a metadata object. */ + MALFORMED_ATTRIBUTE_ENTRY, + + /** A metadata item does not hold a value of its type, or the value breaks its constraints. */ + INVALID_META_ITEM, + + /** No attribute of the document exists on the target asset with the same type. */ + NO_IMPORTABLE_ATTRIBUTES, + + /** The submitted draft no longer identifies the persisted target asset. */ + DRAFT_MISMATCH +} diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java new file mode 100644 index 0000000000..ef0b3d46eb --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java @@ -0,0 +1,94 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; + +/** + * What importing a {@link ConfigurationTemplate} into an asset draft would do, for the user to + * confirm or cancel. With a {@link #failure} nothing can be imported and there are no patched + * attributes, but the other fields still hold what could be worked out, such as the skipped + * attributes. + */ +@Schema( + description = + "Outcome of validating a configuration template against an asset draft, with the patched attributes to apply on confirmation.") +public class ConfigurationTemplateImportPreview { + + @Schema(description = "Why the document cannot be imported; absent when it can.") + protected ConfigurationTemplateImportFailure failure; + + @Schema(description = "Attributes whose metadata will be replaced.") + protected List importableAttributes; + + @Schema(description = "Attributes skipped because the target asset does not have them.") + protected List missingAttributes; + + @Schema(description = "Attributes skipped because the target attribute has a different type.") + protected List typeMismatches; + + @Schema( + description = + "The submitted draft attributes with the metadata of every importable attribute replaced, keyed by attribute name.") + protected ObjectNode patchedAttributes; + + @JsonCreator + public ConfigurationTemplateImportPreview( + @JsonProperty("failure") ConfigurationTemplateImportFailure failure, + @JsonProperty("importableAttributes") + List importableAttributes, + @JsonProperty("missingAttributes") List missingAttributes, + @JsonProperty("typeMismatches") List typeMismatches, + @JsonProperty("patchedAttributes") ObjectNode patchedAttributes) { + this.failure = failure; + this.importableAttributes = importableAttributes; + this.missingAttributes = missingAttributes; + this.typeMismatches = typeMismatches; + this.patchedAttributes = patchedAttributes; + } + + public static ConfigurationTemplateImportPreview failed( + ConfigurationTemplateImportFailure failure) { + return new ConfigurationTemplateImportPreview(failure, List.of(), List.of(), List.of(), null); + } + + public ConfigurationTemplateImportFailure getFailure() { + return failure; + } + + public List getImportableAttributes() { + return importableAttributes; + } + + public List getMissingAttributes() { + return missingAttributes; + } + + public List getTypeMismatches() { + return typeMismatches; + } + + public ObjectNode getPatchedAttributes() { + return patchedAttributes; + } +} diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java new file mode 100644 index 0000000000..6c7d9d3a09 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; + +/** + * A {@link ConfigurationTemplate} to import, together with the asset draft it is imported into. The + * document is submitted as text so that unparsable files are reported like any other invalid + * document. + */ +@Schema(description = "A configuration template to validate against an asset draft, as file text.") +public class ConfigurationTemplateImportRequest { + + @Schema(description = "The asset draft currently being edited, including unsaved changes.") + @NotNull protected Asset draft; + + @Schema(description = "Contents of the selected configuration template file.") + @NotNull protected String document; + + @JsonCreator + public ConfigurationTemplateImportRequest( + @JsonProperty("draft") Asset draft, @JsonProperty("document") String document) { + this.draft = draft; + this.document = document; + } + + public Asset getDraft() { + return draft; + } + + public String getDocument() { + return document; + } +} diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java new file mode 100644 index 0000000000..cbc379afcd --- /dev/null +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -0,0 +1,235 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.util; + +import static org.openremote.model.asset.ConfigurationTemplateImportFailure.*; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.TreeMap; +import org.openremote.model.asset.Asset; +import org.openremote.model.asset.AttributeConfiguration; +import org.openremote.model.asset.AttributeConfigurationSummary; +import org.openremote.model.asset.AttributeConfigurationTypeMismatch; +import org.openremote.model.asset.ConfigurationTemplate; +import org.openremote.model.asset.ConfigurationTemplateImportPreview; +import org.openremote.model.attribute.Attribute; +import org.openremote.model.attribute.AttributeMap; +import org.openremote.model.value.MetaItemDescriptor; + +/** + * Reads and writes {@link ConfigurationTemplate}s. Callers are responsible for enforcing realm + * authorization and for persisting, or discarding, the patched attributes. + */ +public final class ConfigurationTemplateUtil { + + private ConfigurationTemplateUtil() {} + + /** + * Builds the export document of an asset, holding the type and metadata of every attribute that + * has metadata. A null or empty selection exports all of them. + */ + public static ConfigurationTemplate export(Asset asset, Collection attributeNames) { + boolean selectAll = attributeNames == null || attributeNames.isEmpty(); + Map attributes = new TreeMap<>(); + + if (asset.getAttributes() != null) { + asset.getAttributes().values().stream() + .filter(attribute -> attribute.getMeta() != null && !attribute.getMeta().isEmpty()) + .filter(attribute -> selectAll || attributeNames.contains(attribute.getName())) + .forEach( + attribute -> + attributes.put( + attribute.getName(), + new AttributeConfiguration( + typeName(attribute), toObjectNode(attribute.getMeta())))); + } + + return new ConfigurationTemplate( + ConfigurationTemplate.CURRENT_VERSION, asset.getType(), attributes); + } + + /** + * Validates a document against an asset draft and works out what importing it would do, without + * changing the draft. The returned {@link + * ConfigurationTemplateImportPreview#getPatchedAttributes()} holds the draft attributes with the + * metadata of every importable attribute replaced. + */ + public static ConfigurationTemplateImportPreview preview(Asset draft, String document) { + JsonNode root; + + try { + root = ValueUtil.JSON.readTree(document); + } catch (JsonProcessingException | IllegalArgumentException e) { + return ConfigurationTemplateImportPreview.failed(INVALID_JSON); + } + + if (root == null || !root.isObject()) { + return ConfigurationTemplateImportPreview.failed(INVALID_JSON); + } + + JsonNode version = root.get("version"); + JsonNode assetType = root.get("assetType"); + JsonNode attributes = root.get("attributes"); + + if (isAbsent(version) || isAbsent(assetType) || isAbsent(attributes)) { + return ConfigurationTemplateImportPreview.failed(MISSING_REQUIRED_FIELD); + } + if (!version.isIntegralNumber() || version.asInt() != ConfigurationTemplate.CURRENT_VERSION) { + return ConfigurationTemplateImportPreview.failed(UNSUPPORTED_VERSION); + } + if (!assetType.isTextual() || assetType.asText().isBlank()) { + return ConfigurationTemplateImportPreview.failed(MISSING_REQUIRED_FIELD); + } + if (!attributes.isObject()) { + return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); + } + + // The map key is the attribute name, so an entry's own name field, if any, is ignored + Map imported = new LinkedHashMap<>(); + for (Map.Entry entry : attributes.properties()) { + JsonNode type = entry.getValue().isObject() ? entry.getValue().get("type") : null; + JsonNode meta = entry.getValue().isObject() ? entry.getValue().get("meta") : null; + + if (type == null || !type.isTextual() || type.asText().isBlank()) { + return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); + } + if (meta == null || !meta.isObject()) { + return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); + } + + ObjectNode importedMeta = ((ObjectNode) meta).deepCopy(); + + if (!isValidMeta(importedMeta)) { + return ConfigurationTemplateImportPreview.failed(INVALID_META_ITEM); + } + + imported.put(entry.getKey(), new AttributeConfiguration(type.asText(), importedMeta)); + } + + AttributeMap targetAttributes = + draft.getAttributes() != null ? draft.getAttributes() : new AttributeMap(); + List importable = new ArrayList<>(); + List missing = new ArrayList<>(); + List typeMismatches = new ArrayList<>(); + + imported.forEach( + (name, configuration) -> { + Optional> target = targetAttributes.get(name); + + if (target.isEmpty()) { + missing.add(new AttributeConfigurationSummary(name, configuration.getType())); + return; + } + + String targetType = typeName(target.get()); + + if (!Objects.equals(configuration.getType(), targetType)) { + typeMismatches.add( + new AttributeConfigurationTypeMismatch(name, configuration.getType(), targetType)); + return; + } + + importable.add(new AttributeConfigurationSummary(name, configuration.getType())); + }); + + // Report what was skipped even when that leaves nothing to import + if (importable.isEmpty()) { + return new ConfigurationTemplateImportPreview( + NO_IMPORTABLE_ATTRIBUTES, importable, missing, typeMismatches, null); + } + + ObjectNode patchedAttributes = toObjectNode(targetAttributes); + importable.forEach( + attribute -> + ((ObjectNode) patchedAttributes.get(attribute.getName())) + .set("meta", imported.get(attribute.getName()).getMeta())); + + return new ConfigurationTemplateImportPreview( + null, importable, missing, typeMismatches, patchedAttributes); + } + + protected static boolean isAbsent(JsonNode node) { + return node == null || node.isNull(); + } + + /** + * Whether every metadata item with a known descriptor holds a value of its type that meets the + * bean constraints of that type. Unknown metadata items are taken as they are. + */ + protected static boolean isValidMeta(ObjectNode meta) { + for (Map.Entry item : meta.properties()) { + Optional> descriptor = ValueUtil.getMetaItemDescriptor(item.getKey()); + + if (descriptor.isEmpty() || item.getValue().isNull()) { + continue; + } + try { + Object value = + ValueUtil.JSON.treeToValue(item.getValue(), descriptor.get().getType().getType()); + + if (value != null + && (!ValueUtil.validate(value).isEmpty() || changesType(item.getValue(), value))) { + return false; + } + } catch (JsonProcessingException | IllegalArgumentException e) { + return false; + } + } + return true; + } + + /** + * Whether a value that names its subtype was read as another one, as happens to an agent link of + * a type that is not installed, which falls back to the default agent link. + */ + protected static boolean changesType(JsonNode node, Object value) { + JsonNode type = node.get("type"); + + if (type == null || !type.isTextual()) { + return false; + } + JsonNode readType = ValueUtil.JSON.valueToTree(value).get("type"); + return readType != null && !type.asText().equals(readType.asText()); + } + + protected static String typeName(Attribute attribute) { + return attribute.getType() != null ? attribute.getType().getName() : null; + } + + /** + * Serializes through text rather than a token buffer, so that attribute values held as raw JSON + * are materialized into the returned tree. + */ + protected static ObjectNode toObjectNode(Object value) { + try { + return (ObjectNode) ValueUtil.JSON.readTree(ValueUtil.JSON.writeValueAsString(value)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot serialize attribute configuration", e); + } + } +} diff --git a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy new file mode 100644 index 0000000000..6b5ad8491c --- /dev/null +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -0,0 +1,232 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.util + +import org.openremote.model.asset.ConfigurationTemplate +import org.openremote.model.asset.impl.RoomAsset +import org.openremote.model.asset.impl.ThingAsset +import org.openremote.model.attribute.Attribute +import org.openremote.model.attribute.MetaItem +import org.openremote.model.value.MetaItemType +import org.openremote.model.value.ValueDescriptor +import org.openremote.model.value.ValueType +import spock.lang.Specification + +import static org.openremote.model.asset.ConfigurationTemplateImportFailure.* + +class ConfigurationTemplateUtilTest extends Specification { + + def setupSpec() { + ValueUtil.initialise(null) + } + + static def thingAsset(Map> attributes = [:]) { + def asset = new ThingAsset("Test Thing") + attributes.each { name, attribute -> asset.getAttributes().put(name, attribute) } + return asset + } + + static def attribute(String name, ValueDescriptor type, Map meta = null) { + def attribute = new Attribute<>(name, type) + meta?.each { metaName, value -> attribute.addMeta(new MetaItem<>(metaName, null, value)) } + return attribute + } + + static String document(String assetType = ThingAsset.DESCRIPTOR.name, Map entries = [:], Integer version = 1) { + def attributes = entries.collect { name, entry -> "\"${name}\": ${entry}" }.join(",") + def fields = [] + if (version != null) { + fields.add("\"version\": ${version}") + } + if (assetType != null) { + fields.add("\"assetType\": \"${assetType}\"") + } + fields.add("\"attributes\": {${attributes}}") + return "{${fields.join(",")}}" + } + + def "export holds the type and metadata of attributes that have metadata"() { + given: "an asset with configured and unconfigured attributes" + def asset = thingAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", unknownMetaItem: [nested: 1]]), + plain : attribute("plain", ValueType.TEXT) + ]) + + when: "the configuration is exported" + def exported = ConfigurationTemplateUtil.export(asset, null) + + then: "the document is of the supported version and holds the asset type" + exported.version == ConfigurationTemplate.CURRENT_VERSION + exported.assetType == ThingAsset.DESCRIPTOR.name + + and: "only the attribute with metadata is held, with its type and its metadata as stored" + exported.attributes.keySet() == ["temperature"] as Set + exported.attributes.temperature.type == ValueType.NUMBER.name + exported.attributes.temperature.meta.get(MetaItemType.LABEL.name).asText() == "Temperature" + exported.attributes.temperature.meta.get("unknownMetaItem").get("nested").asInt() == 1 + } + + def "export limited to a selection holds only the selected attributes"() { + given: "an asset with two configured attributes" + def asset = thingAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"]), + humidity : attribute("humidity", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Humidity"]) + ]) + + expect: "the selection is exported" + ConfigurationTemplateUtil.export(asset, ["humidity"]).attributes.keySet() == ["humidity"] as Set + } + + def "a document that cannot be read is rejected with #failure"() { + given: "an asset with a configured attribute" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + + expect: "the import is rejected" + ConfigurationTemplateUtil.preview(asset, documentText).failure == failure + + where: + failure | documentText + INVALID_JSON | "not json at all" + INVALID_JSON | "[]" + INVALID_JSON | null + MISSING_REQUIRED_FIELD | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {}}'], null) + MISSING_REQUIRED_FIELD | document(null, [temperature: '{"type": "number", "meta": {}}']) + MISSING_REQUIRED_FIELD | '{"version": 1, "assetType": "ThingAsset"}' + UNSUPPORTED_VERSION | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {}}'], 2) + UNSUPPORTED_VERSION | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {}}'], 0) + MALFORMED_ATTRIBUTE_ENTRY | '{"version": 1, "assetType": "ThingAsset", "attributes": 5}' + MALFORMED_ATTRIBUTE_ENTRY | document(ThingAsset.DESCRIPTOR.name, [temperature: '5']) + MALFORMED_ATTRIBUTE_ENTRY | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"meta": {}}']) + MALFORMED_ATTRIBUTE_ENTRY | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number"}']) + MALFORMED_ATTRIBUTE_ENTRY | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": 5}']) + INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"readOnly": {"not": "a boolean"}}}']) + INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"constraints": [{"type": "noSuchConstraint"}]}}']) + INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"agentLink": {"type": "NoSuchAgentLink", "id": "agentId"}}}']) + NO_IMPORTABLE_ATTRIBUTES | document(ThingAsset.DESCRIPTOR.name, [:]) + } + + def "an attribute missing on the target asset is skipped and reported"() { + given: "an asset without the imported attribute" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + + when: "a document holding a known and an unknown attribute is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"label": "Imported"}}', + humidity : '{"type": "number", "meta": {"label": "Imported"}}' + ])) + + then: "the unknown attribute is reported as missing and is not patched" + preview.failure == null + preview.missingAttributes*.name == ["humidity"] + preview.importableAttributes*.name == ["temperature"] + !preview.patchedAttributes.has("humidity") + } + + def "an attribute whose type differs is skipped and reported"() { + given: "an asset holding the imported attribute as text" + def asset = thingAsset([temperature: attribute("temperature", ValueType.TEXT, [(MetaItemType.LABEL.name): "Temperature"])]) + + when: "a document holding the attribute as a number is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"label": "Imported"}}' + ])) + + then: "nothing can be imported, with the mismatch reported" + preview.failure == NO_IMPORTABLE_ATTRIBUTES + preview.typeMismatches*.name == ["temperature"] + preview.typeMismatches*.importedType == [ValueType.NUMBER.name] + preview.typeMismatches*.targetType == [ValueType.TEXT.name] + } + + def "type comparison is case sensitive"() { + given: "an asset holding a number attribute" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + + when: "a document spelling the same type differently is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "Number", "meta": {"label": "Imported"}}', + humidity : '{"type": "number", "meta": {"label": "Imported"}}' + ])) + + then: "the differently spelled type is a mismatch rather than a match" + preview.typeMismatches*.name == ["temperature"] + preview.typeMismatches*.importedType == ["Number"] + preview.typeMismatches*.targetType == [ValueType.NUMBER.name] + } + + def "a document exported from another asset type can still be imported"() { + given: "a thing asset holding a configured attribute" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + + when: "a document exported from a room asset is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(RoomAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"label": "Imported"}}' + ])) + + then: "the attribute is importable" + preview.failure == null + preview.importableAttributes*.name == ["temperature"] + } + + def "the metadata of an importable attribute is replaced as a whole"() { + given: "an asset whose attribute holds metadata that the document does not" + def asset = thingAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.READ_ONLY.name): true]), + plain : attribute("plain", ValueType.TEXT) + ]) + asset.getAttributes().get("temperature").get().setValue(21.5d) + + when: "a document holding other metadata for that attribute is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"unitType": ["celsius"]}}', + plain : '{"type": "text", "meta": {"label": "Plain"}}' + ])) + + then: "the imported metadata replaces the existing metadata entirely" + def patchedTemperature = preview.patchedAttributes.get("temperature") + patchedTemperature.get("meta").get("unitType").get(0).asText() == "celsius" + !patchedTemperature.get("meta").has(MetaItemType.LABEL.name) + !patchedTemperature.get("meta").has(MetaItemType.READ_ONLY.name) + + and: "an attribute without metadata gets the imported metadata added" + preview.patchedAttributes.get("plain").get("meta").get("label").asText() == "Plain" + + and: "the type and the value of the attribute are untouched" + patchedTemperature.get("type").asText() == ValueType.NUMBER.name + patchedTemperature.get("value").asDouble() == 21.5d + + and: "the asset itself is not modified" + asset.getAttributes().get("temperature").get().getMeta().has(MetaItemType.LABEL.name) + !asset.getAttributes().get("plain").get().getMeta().has("label") + } + + def "an internal name field within an entry is ignored"() { + given: "an asset holding a configured attribute" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + + when: "a document whose entry names another attribute is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"name": "somethingElse", "type": "number", "meta": {"label": "Imported"}}' + ])) + + then: "the map key decides which attribute is imported" + preview.importableAttributes*.name == ["temperature"] + preview.patchedAttributes.get("temperature").get("meta").get("label").asText() == "Imported" + } +} diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy new file mode 100644 index 0000000000..f168dfaf17 --- /dev/null +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -0,0 +1,302 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.test.assets + +import jakarta.ws.rs.ForbiddenException +import jakarta.ws.rs.WebApplicationException +import org.openremote.manager.setup.SetupService +import org.openremote.model.asset.AssetResource +import org.openremote.model.asset.ConfigurationTemplateImportPreview +import org.openremote.model.asset.ConfigurationTemplateImportRequest +import org.openremote.model.asset.impl.RoomAsset +import org.openremote.model.asset.impl.ThingAsset +import org.openremote.model.attribute.Attribute +import org.openremote.model.attribute.MetaItem +import org.openremote.model.util.ValueUtil +import org.openremote.model.value.MetaItemType +import org.openremote.model.value.ValueType +import org.openremote.setup.integration.KeycloakTestSetup +import org.openremote.setup.integration.ManagerTestSetup +import org.openremote.test.ManagerContainerTrait +import spock.lang.Specification + +import static jakarta.ws.rs.core.Response.Status.BAD_REQUEST +import static jakarta.ws.rs.core.Response.Status.CONFLICT +import static jakarta.ws.rs.core.Response.Status.FORBIDDEN +import static jakarta.ws.rs.core.Response.Status.NOT_FOUND +import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD +import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT +import static org.openremote.model.Constants.* +import static org.openremote.model.asset.ConfigurationTemplateImportFailure.* +import static org.openremote.model.util.MapAccess.getString + +class ConfigurationTemplateTest extends Specification implements ManagerContainerTrait { + + def "Export and import a configuration template as superuser"() { + given: "the server container is started" + def container = startContainer(defaultConfig(), defaultServices()) + def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) + + and: "an authenticated admin user" + def accessToken = authenticate( + container, + MASTER_REALM, + KEYCLOAK_CLIENT_ID, + MASTER_REALM_ADMIN_USER, + getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT) + ) + + and: "the asset resource" + def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class) + + and: "a configured source asset and a target asset of the same type" + def source = assetResource.create(null, new ThingAsset("Configuration source") + .setRealm(keycloakTestSetup.realmMaster.name) + .addOrReplaceAttributes( + new Attribute<>("temperature", ValueType.NUMBER) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source temperature")) + .addMeta(new MetaItem<>(MetaItemType.READ_ONLY, true)), + new Attribute<>("customValue", ValueType.TEXT) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source custom value")), + new Attribute<>("plain", ValueType.TEXT) + )) + def target = assetResource.create(null, new ThingAsset("Configuration target") + .setRealm(keycloakTestSetup.realmMaster.name) + .addOrReplaceAttributes( + new Attribute<>("temperature", ValueType.NUMBER, 21.5d) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Target temperature")), + new Attribute<>("customValue", ValueType.NUMBER), + new Attribute<>("plain", ValueType.TEXT) + )) + + when: "a configuration template of the source asset is exported" + def document = assetResource.exportConfigurationTemplate(null, source.id, []) + + then: "only the attributes holding metadata are exported, with their type and metadata" + document.version == 1 + document.assetType == ThingAsset.DESCRIPTOR.name + document.attributes.keySet() == ["temperature", "customValue"] as Set + document.attributes.temperature.type == ValueType.NUMBER.name + document.attributes.temperature.meta.get(MetaItemType.LABEL.name).asText() == "Source temperature" + document.attributes.temperature.meta.get(MetaItemType.READ_ONLY.name).asBoolean() + + when: "a subset of the attributes is exported" + def subset = assetResource.exportConfigurationTemplate(null, source.id, ["temperature"]) + + then: "only the requested attribute is exported" + subset.attributes.keySet() == ["temperature"] as Set + + when: "only an attribute without metadata is selected" + assetResource.exportConfigurationTemplate(null, source.id, ["plain"]) + + then: "the export is rejected as there is nothing to export" + WebApplicationException nothingToExport = thrown() + nothingToExport.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + return true + } + + when: "the exported document is imported into the target asset" + def preview = assetResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(target, ValueUtil.asJSON(document).orElseThrow())) + + then: "the attribute with a matching type is importable and the one with another type is reported" + preview.failure == null + preview.importableAttributes*.name == ["temperature"] + preview.typeMismatches*.name == ["customValue"] + preview.typeMismatches*.importedType == [ValueType.TEXT.name] + preview.typeMismatches*.targetType == [ValueType.NUMBER.name] + + and: "the patched attributes hold the imported metadata, keeping the attribute value" + def patched = preview.patchedAttributes.get("temperature") + patched.get("meta").get(MetaItemType.LABEL.name).asText() == "Source temperature" + patched.get("meta").get(MetaItemType.READ_ONLY.name).asBoolean() + patched.get("value").asDouble() == 21.5d + + and: "the attributes that are not imported are returned untouched" + preview.patchedAttributes.get("customValue").get("type").asText() == ValueType.NUMBER.name + + and: "the target asset is not stored by the preview" + assetResource.get(null, target.id).getAttribute("temperature").get().getMeta() + .getValue(MetaItemType.LABEL.name, String.class).orElse(null) == "Target temperature" + + when: "a document of an unsupported version is imported" + assetResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(target, '{"version": 2, "assetType": "ThingAsset", "attributes": {}}')) + + then: "the import is rejected with the reason" + WebApplicationException ex = thrown() + ex.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + assert r.readEntity(ConfigurationTemplateImportPreview.class).failure == UNSUPPORTED_VERSION + return true + } + + when: "a document holding no attribute of the target asset is imported" + assetResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"absent": {"type": "text", "meta": {"label": "Absent"}}}}')) + + then: "the import is rejected and the skipped attribute is reported" + WebApplicationException noneImportable = thrown() + noneImportable.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + def rejected = r.readEntity(ConfigurationTemplateImportPreview.class) + assert rejected.failure == NO_IMPORTABLE_ATTRIBUTES + assert rejected.missingAttributes*.name == ["absent"] + return true + } + + when: "the draft of another asset is submitted" + assetResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(source, ValueUtil.asJSON(document).orElseThrow())) + + then: "the import conflicts with the target asset" + WebApplicationException draftMismatch = thrown() + draftMismatch.response.withCloseable { r -> + assert r.status == CONFLICT.statusCode + assert r.readEntity(ConfigurationTemplateImportPreview.class).failure == DRAFT_MISMATCH + return true + } + + when: "no draft is submitted" + assetResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(null, ValueUtil.asJSON(document).orElseThrow())) + + then: "the request is rejected as invalid rather than as a conflict" + WebApplicationException noDraft = thrown() + noDraft.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + return true + } + } + + def "Configuration template import requires asset write access"() { + given: "the server container is started" + def container = startContainer(defaultConfig(), defaultServices()) + def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class) + def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) + + and: "an authenticated user that can read but not write assets" + def accessToken = authenticate( + container, + keycloakTestSetup.realmBuilding.name, + KEYCLOAK_CLIENT_ID, + "testuser2", + "testuser2" + ) + + and: "the asset resource" + def assetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken) + .proxy(AssetResource.class) + + when: "a configuration template of an asset of the authenticated realm is exported" + def document = assetResource.exportConfigurationTemplate(null, managerTestSetup.apartment1LivingroomId, []) + + then: "the configuration is returned" + document.version == 1 + !document.attributes.isEmpty() + + when: "the same user previews an import" + assetResource.previewConfigurationTemplateImport(null, managerTestSetup.apartment1LivingroomId, + new ConfigurationTemplateImportRequest( + assetResource.get(null, managerTestSetup.apartment1LivingroomId), + ValueUtil.asJSON(document).orElseThrow())) + + then: "access is forbidden" + ForbiddenException forbidden = thrown() + forbidden.response.withCloseable { r -> + assert r.status == FORBIDDEN.statusCode + return true + } + } + + def "Configuration template import is rejected for assets the user cannot access"() { + given: "the server container is started" + def container = startContainer(defaultConfig(), defaultServices()) + def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class) + def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) + def buildingRealm = keycloakTestSetup.realmBuilding.name + + and: "a document, which is never read as access is checked first" + def document = '{"version": 1, "assetType": "RoomAsset", "attributes": {}}' + + and: "a master realm user that can write assets" + def masterUserToken = authenticate( + container, + MASTER_REALM, + KEYCLOAK_CLIENT_ID, + "testuser1", + "testuser1" + ) + def masterUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, masterUserToken) + .proxy(AssetResource.class) + + and: "a restricted building realm user that can write the assets linked to it" + def restrictedUserToken = authenticate( + container, + buildingRealm, + KEYCLOAK_CLIENT_ID, + "testuser3", + "testuser3" + ) + def restrictedUserResource = getClientApiTarget(serverUri(serverPort), buildingRealm, restrictedUserToken) + .proxy(AssetResource.class) + + when: "the master realm user previews an import into an asset of the building realm" + def otherRealmAssetId = managerTestSetup.apartment1LivingroomId + masterUserResource.previewConfigurationTemplateImport(null, otherRealmAssetId, + new ConfigurationTemplateImportRequest(draft(otherRealmAssetId, buildingRealm), document)) + + then: "access is forbidden" + WebApplicationException otherRealm = thrown() + otherRealm.response.withCloseable { r -> + assert r.status == FORBIDDEN.statusCode + return true + } + + when: "the restricted user previews an import into an asset that is not linked to it" + def unlinkedAssetId = managerTestSetup.apartment2LivingroomId + restrictedUserResource.previewConfigurationTemplateImport(null, unlinkedAssetId, + new ConfigurationTemplateImportRequest(draft(unlinkedAssetId, buildingRealm), document)) + + then: "access is forbidden" + WebApplicationException unlinked = thrown() + unlinked.response.withCloseable { r -> + assert r.status == FORBIDDEN.statusCode + return true + } + + when: "an import into an asset that does not exist is previewed" + def unknownAssetId = "unknownAssetId00000001" + masterUserResource.previewConfigurationTemplateImport(null, unknownAssetId, + new ConfigurationTemplateImportRequest(draft(unknownAssetId, MASTER_REALM), document)) + + then: "the asset is not found" + WebApplicationException unknown = thrown() + unknown.response.withCloseable { r -> + assert r.status == NOT_FOUND.statusCode + return true + } + } + + /** A draft that identifies the asset, so only access decides the outcome. */ + protected static RoomAsset draft(String id, String realm) { + return new RoomAsset("Living room").setId(id).setRealm(realm) + } +} diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json index 8acec2bd37..a3ea6c7841 100644 --- a/ui/app/shared/locales/en/or.json +++ b/ui/app/shared/locales/en/or.json @@ -1336,5 +1336,35 @@ } } } + }, + "configurationTemplate": { + "import": "Import", + "export": "Export", + "exportHeading": "Export configuration template", + "exportDescription": "Save the configuration items as a template, so you can reproduce the configuration on another instance.", + "templateName": "Template name", + "selectAttributes": "Select what to include in the template", + "selectAll": "Select all", + "nothingToExport": "None of the attributes of this asset have configuration items to export", + "saveBeforeExport": "Save or revert your changes before exporting", + "importHeading": "Import configuration template", + "selectFileDescription": "Select a JSON file to import attribute configuration data", + "noFileSelected": "no file selected", + "overwriteWarning": "You are about to import the following attribute configuration data. This will overwrite existing metadata for matched attributes in your current draft.", + "matchedAttributes": "Matched attributes", + "skippedAttributes": "Attribute name or type not found (these will not be imported)", + "back": "Back", + "next": "Next", + "json": "JSON", + "forbidden": "You are not allowed to import a configuration template into this asset.", + "failure": { + "INVALID_JSON": "The selected file does not hold valid JSON.", + "UNSUPPORTED_VERSION": "The selected file holds an unsupported configuration template version.", + "MISSING_REQUIRED_FIELD": "The selected file is missing a required field.", + "MALFORMED_ATTRIBUTE_ENTRY": "The selected file holds a malformed attribute entry.", + "INVALID_META_ITEM": "The selected file holds a configuration item whose value does not fit its type.", + "NO_IMPORTABLE_ATTRIBUTES": "None of the attributes in the selected file can be imported into this asset.", + "DRAFT_MISMATCH": "This asset has changed since you opened it; refresh it and try again." + } } } diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json index a9a6459ab8..82c32c92b4 100644 --- a/ui/app/shared/locales/nl/or.json +++ b/ui/app/shared/locales/nl/or.json @@ -1322,5 +1322,35 @@ } } } + }, + "configurationTemplate": { + "import": "Importeren", + "export": "Exporteren", + "exportHeading": "Configuratie template exporteren", + "exportDescription": "Sla de configuratie items op als template, zodat je de configuratie op een andere instantie kunt reproduceren.", + "templateName": "Template naam", + "selectAttributes": "Selecteer wat je in de template opneemt", + "selectAll": "Alles selecteren", + "nothingToExport": "Geen van de attributen van dit asset heeft configuratie items om te exporteren", + "saveBeforeExport": "Sla je wijzigingen op of maak ze ongedaan voordat je exporteert", + "importHeading": "Configuratie template importeren", + "selectFileDescription": "Selecteer een JSON-bestand om attribuutconfiguratie te importeren", + "noFileSelected": "geen bestand geselecteerd", + "overwriteWarning": "Je staat op het punt de volgende attribuutconfiguratie te importeren. Dit overschrijft de bestaande metadata van overeenkomende attributen in je huidige concept.", + "matchedAttributes": "Overeenkomende attributen", + "skippedAttributes": "Attribuutnaam of type niet gevonden (deze worden niet geïmporteerd)", + "back": "Terug", + "next": "Volgende", + "json": "JSON", + "forbidden": "Je hebt geen rechten om een configuratie template in dit asset te importeren.", + "failure": { + "INVALID_JSON": "Het geselecteerde bestand bevat geen geldige JSON.", + "UNSUPPORTED_VERSION": "Het geselecteerde bestand bevat een niet-ondersteunde versie van het configuratie template.", + "MISSING_REQUIRED_FIELD": "In het geselecteerde bestand ontbreekt een verplicht veld.", + "MALFORMED_ATTRIBUTE_ENTRY": "Het geselecteerde bestand bevat een ongeldige attribuutvermelding.", + "INVALID_META_ITEM": "Het geselecteerde bestand bevat een configuratie item waarvan de waarde niet bij het type past.", + "NO_IMPORTABLE_ATTRIBUTES": "Geen van de attributen in het geselecteerde bestand kan in dit asset worden geïmporteerd.", + "DRAFT_MISMATCH": "Dit asset is gewijzigd sinds je het opende; ververs het en probeer het opnieuw." + } } } diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts new file mode 100644 index 0000000000..be8f578e97 --- /dev/null +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -0,0 +1,763 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import { html, type TemplateResult } from "lit"; +import { createRef, ref, type Ref } from "lit/directives/ref.js"; +import { live } from "lit/directives/live.js"; +import manager, { Util } from "@openremote/core"; +import { + AssetModelUtil, + WellknownMetaItems, + type Asset, + type Attribute, + type ConfigurationTemplateImportPreview, + type ValueConstraint, + type ValueFormat, +} from "@openremote/model"; +import { i18next } from "@openremote/or-translate"; +import "@openremote/or-icon"; +import "@openremote/or-translate"; +import type { OrIcon } from "@openremote/or-icon"; +import "@openremote/or-vaadin-components/or-vaadin-badge"; +import "@openremote/or-vaadin-components/or-vaadin-button"; +import "@openremote/or-vaadin-components/or-vaadin-checkbox"; +import "@openremote/or-vaadin-components/or-vaadin-dialog"; +import "@openremote/or-vaadin-components/or-vaadin-text-field"; +import type { OrVaadinButton } from "@openremote/or-vaadin-components/or-vaadin-button"; +import type { OrVaadinCheckbox } from "@openremote/or-vaadin-components/or-vaadin-checkbox"; +import { + dialogFooterRenderer, + dialogHeaderRenderer, + dialogRenderer, + showDialog, +} from "@openremote/or-vaadin-components/or-vaadin-dialog"; +import { showErrorDialog } from "@openremote/or-vaadin-components/or-vaadin-confirm-dialog"; +import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar"; + +export type AssetAttributes = { [index: string]: Attribute }; + +/** A configuration item of an attribute as the rows show it. */ +interface ConfigurationItem { + label: string; + /** The value in short, if it has one. */ + value?: string; + /** The value as formatted JSON, for a value that is an object. */ + json?: string; +} + +const DIALOG_WIDTH = "550px"; + +// language=CSS +const dialogStyle = html` + +`; + +/** The attributes holding configuration items for a template, which are the attributes that can be exported. */ +export function getConfigurableAttributes(asset: Asset): Attribute[] { + return Object.entries(asset.attributes || {}) + .filter(([, attribute]) => Object.keys(attribute.meta || {}).length > 0) + .map(([name, attribute]) => ({ ...attribute, name })) + .sort(Util.sortByString((attribute) => attribute.name!.toUpperCase())); +} + +/** Lets the user pick the attributes to export, then downloads the configuration template. */ +export function showExportConfigurationTemplateDialog(host: Node, asset: Asset) { + const attributes = getConfigurableAttributes(asset); + + if (attributes.length === 0) { + showSnackbar(undefined, "configurationTemplate.nothingToExport"); + return; + } + + const selected = new Set(attributes.map((attribute) => attribute.name!)); + let templateName = `${asset.name}-configuration-template.json`; + const exportBtn: Ref = createRef(); + + const updateExportBtn = () => { + if (exportBtn.value) { + exportBtn.value.disabled = selected.size === 0 || templateName.trim() === ""; + } + }; + + const onToggle = (names: string[], checked: boolean) => { + names.forEach((name) => (checked ? selected.add(name) : selected.delete(name))); + updateExportBtn(); + dialog?.requestContentUpdate(); + }; + + const onTemplateNameChange = (name: string) => { + templateName = name; + updateExportBtn(); + }; + + const dialog = showDialog( + host, + html` + getHeaderTemplate("configurationTemplate.exportHeading", () => dialog?.close()))} + ${dialogRenderer( + () => html` + ${dialogStyle} +
+ +
+ ) => onTemplateNameChange(ev.detail.value)} + > +
+
+ + 0 && selected.size < attributes.length)} + @change=${(ev: Event) => + onToggle( + attributes.map((attribute) => attribute.name!), + (ev.currentTarget as OrVaadinCheckbox).checked + )} + > +
+ ${attributes.map((attribute) => + getAttributeRowTemplate( + asset, + attribute, + html` + + onToggle([attribute.name!], (ev.currentTarget as OrVaadinCheckbox).checked)} + > + + + ` + ) + )} +
+
+
+ ` + )} + ${dialogFooterRenderer( + () => html` +
+ dialog?.close()}> + + + { + dialog?.close(); + downloadConfigurationTemplate(asset, Array.from(selected), templateName); + }} + > + + +
+ ` + )} + >
+ ` + ); +} + +/** + * Lets the user pick a configuration file, reports what importing it would do and, once confirmed, + * hands the patched attributes to the caller to apply to the asset draft. + */ +export function showImportConfigurationTemplateDialog( + host: Node, + asset: Asset, + onImported: (attributes: AssetAttributes) => void, + selectedFile?: File +) { + let file = selectedFile; + const fileName: Ref = createRef(); + const fileInput: Ref = createRef(); + const nextBtn: Ref = createRef(); + + const onFileSelected = () => { + file = fileInput.value?.files?.[0]; + if (fileName.value) { + fileName.value.textContent = file ? file.name : i18next.t("configurationTemplate.noFileSelected"); + fileName.value.classList.toggle("ac-placeholder", !file); + } + if (nextBtn.value) { + nextBtn.value.disabled = !file; + } + }; + + const onNext = async () => { + if (!file) { + return; + } + + const selected = file; + const configuration = await selected.text(); + dialog?.close(); + + previewImport(host, asset, selected.name, configuration, onImported, () => + showImportConfigurationTemplateDialog(host, asset, onImported, selected) + ); + }; + + const dialog = showDialog( + host, + html` + getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close()))} + ${dialogRenderer( + () => html` + ${dialogStyle} +
+ +
+
+ onFileSelected()} + /> + fileInput.value?.click()}> + + + + ${file ? file.name : i18next.t("configurationTemplate.noFileSelected")} + +
+
+
+ ` + )} + ${dialogFooterRenderer( + () => html` +
+ dialog?.close()}> + + + onNext()}> + + +
+ ` + )} + >
+ ` + ); +} + +/** Asks the server what importing the configuration would do, and reports it. */ +async function previewImport( + host: Node, + asset: Asset, + fileName: string, + configuration: string, + onImported: (attributes: AssetAttributes) => void, + onBack: () => void +) { + try { + const response = await manager.rest.api.AssetResource.previewConfigurationTemplateImport(asset.id!, { + draft: asset, + document: configuration, + }); + showImportPreviewDialog(host, asset, fileName, configuration, response.data, onImported, onBack); + } catch (error) { + showImportFailureDialog(host, asset, configuration, error); + } +} + +/** Reports what the import would change and warns that it overwrites the metadata of matched attributes. */ +function showImportPreviewDialog( + host: Node, + asset: Asset, + fileName: string, + configuration: string, + preview: ConfigurationTemplateImportPreview, + onImported: (attributes: AssetAttributes) => void, + onBack: () => void +) { + const patchedAttributes = (preview.patchedAttributes || {}) as AssetAttributes; + const importable = preview.importableAttributes || []; + + const dialog = showDialog( + host, + html` + getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close()))} + ${dialogRenderer( + () => html` + ${dialogStyle} +
+ ${fileName} +
+ + +
+
+ +
+ ${importable.map((summary) => { + const attribute = { ...patchedAttributes[summary.name!], name: summary.name }; + return getAttributeRowTemplate( + asset, + attribute, + html` + + ${getAttributeNameTemplate(asset, attribute)} + ` + ); + })} +
+
+ ${getSkippedTemplate(asset, preview, configuration)} +
+ ` + )} + ${dialogFooterRenderer( + () => html` +
+ { + dialog?.close(); + onBack(); + }} + > + + + { + dialog?.close(); + onImported(patchedAttributes); + }} + > + + +
+ ` + )} + >
+ ` + ); +} + +/** Reports a document that cannot be imported, with whatever the server could tell about it. */ +function showImportFailureDialog(host: Node, asset: Asset, configuration: string, error: unknown) { + const preview = getFailurePreview(error); + const forbidden = (error as { response?: { status?: number } })?.response?.status === 403; + const message = preview + ? i18next.t(`configurationTemplate.failure.${preview.failure}`) + : i18next.t(forbidden ? "configurationTemplate.forbidden" : "errorOccurred"); + + showErrorDialog( + host, + html`${dialogStyle} +
+ ${message} + ${preview ? getSkippedTemplate(asset, preview, configuration) : ``} +
`, + "configurationTemplate.importHeading" + ); +} + +function getHeaderTemplate(titleKey: string, onClose: () => void): TemplateResult { + return html` + ${dialogStyle} +
+

+ onClose()}> + + +
+ `; +} + +/** The attributes of the file that are not imported, as the file holds them. */ +function getSkippedTemplate( + asset: Asset, + preview: ConfigurationTemplateImportPreview, + configuration: string +): TemplateResult | string { + const skipped = [ + ...(preview.missingAttributes || []).map((attribute) => attribute.name!), + ...(preview.typeMismatches || []).map((mismatch) => mismatch.name!), + ]; + + if (skipped.length === 0) { + return ``; + } + + const fileAttributes = getFileAttributes(configuration); + + return html` +
+ +
+ ${skipped.map((name) => { + const attribute = { ...fileAttributes[name], name }; + return getAttributeRowTemplate( + asset, + attribute, + html` + + ${getAttributeNameTemplate(asset, attribute)} + ` + ); + })} +
+
+ `; +} + +/** An attribute with its configuration items, which the row expands to show. */ +function getAttributeRowTemplate(asset: Asset, attribute: Attribute, lead: TemplateResult): TemplateResult { + return html` +
+
+ ${lead} + ${Object.keys(attribute.meta || {}).length} + + + +
+
+ ${getConfigurationItems(asset, attribute).map( + (item) => html` +
+
+ ${item.label} + ${ + item.json + ? html` + + + + ` + : `` + } +
+ ${ + item.value !== undefined + ? html`${item.value}` + : `` + } + ${item.json ? html`
${item.json}
` : ``} +
+ ` + )} +
+
+ `; +} + +/** Expands or collapses the section of the clicked header. */ +function toggleExpanded(ev: Event) { + const header = ev.currentTarget as HTMLElement; + const section = header.parentElement; + const icon = header.querySelector(".ac-expander or-icon") as OrIcon | null; + + // A checkbox in the header only toggles itself + if (!section || (ev.target as Element).closest("or-vaadin-checkbox")) { + return; + } + + section.classList.toggle("ac-expanded"); + + if (icon) { + icon.icon = section.classList.contains("ac-expanded") ? "chevron-up" : "chevron-down"; + } +} + +async function downloadConfigurationTemplate(asset: Asset, attributeNames: string[], templateName: string) { + try { + const response = await manager.rest.api.AssetResource.exportConfigurationTemplate(asset.id!, { + attributeName: attributeNames, + }); + const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: "application/json" }); + const url = window.URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + const fileName = templateName.trim(); + link.setAttribute("download", fileName.toLowerCase().endsWith(".json") ? fileName : `${fileName}.json`); + document.body.appendChild(link); + link.click(); + link.remove(); + window.URL.revokeObjectURL(url); + } catch (error) { + console.error("Failed to export the configuration template", error); + showSnackbar(undefined, "errorOccurred"); + } +} + +/** The report the server sends along with a rejected import, if this is one. */ +function getFailurePreview(error: unknown): ConfigurationTemplateImportPreview | undefined { + const data = (error as { response?: { data?: ConfigurationTemplateImportPreview } })?.response?.data; + return data?.failure ? data : undefined; +} + +/** The attributes of a configuration file keyed by name, or none if it cannot be read. */ +function getFileAttributes(configuration: string): AssetAttributes { + try { + const attributes = JSON.parse(configuration)?.attributes; + return attributes && typeof attributes === "object" ? (attributes as AssetAttributes) : {}; + } catch { + return {}; + } +} + +/** The attribute label, which truncates when it does not fit, followed by its value type, which stays visible. */ +function getAttributeNameTemplate(asset: Asset, attribute: Attribute): TemplateResult { + return html` + ${attributeName(asset, attribute)} + (${Util.getValueDescriptorLabel(attribute.type)}) + `; +} + +/** The attribute label with its value type, as the Figma dialogs show it, e.g. "Model (Text)". */ +function attributeLabel(asset: Asset, attribute: Attribute): string { + return `${attributeName(asset, attribute)} (${Util.getValueDescriptorLabel(attribute.type)})`; +} + +function attributeName(asset: Asset, attribute: Attribute): string { + const descriptor = AssetModelUtil.getAttributeDescriptor(attribute.name!, asset.type!); + return Util.getAttributeLabel(attribute, descriptor, asset.type, false); +} + +/** The configuration items of an attribute that a template holds, sorted by label. */ +function getConfigurationItems(asset: Asset, attribute: Attribute): ConfigurationItem[] { + return Object.entries(attribute.meta || {}) + .map(([name, value]) => getConfigurationItem(asset, name, value)) + .sort((a, b) => a.label.localeCompare(b.label)); +} + +/** + * A configuration item with its value in short: a plain value as it is, labeled with its value type, an item that has a + * short form as that, and any other list of plain values comma separated. Any other value only shows as formatted JSON, + * through its JSON button, which a short form has as well. + */ +function getConfigurationItem(asset: Asset, name: string, value: unknown): ConfigurationItem { + const label = Util.getMetaLabel(undefined, name, asset.type, false); + + if (value === null || typeof value !== "object") { + const type = AssetModelUtil.getMetaItemDescriptor(name)?.type; + return { label: type ? `${label} (${Util.getValueDescriptorLabel(type)})` : label, value: String(value) }; + } + const json = JSON.stringify(value, null, 2); + const shortValue = SHORT_VALUES[name]?.(value); + + if (shortValue) { + return { label, value: shortValue, json }; + } + if (Array.isArray(value) && value.every((item) => item === null || typeof item !== "object")) { + return { label, value: value.join(", ") }; + } + return { label, json }; +} + +/** The short forms of configuration items, by item name. */ +const SHORT_VALUES: { [name: string]: (value: any) => string | undefined } = { + [WellknownMetaItems.AGENTLINK]: getAgentLinkShortValue, + [WellknownMetaItems.CONSTRAINTS]: (constraints: ValueConstraint[]) => getNames(constraints.map(({ type }) => type)), + [WellknownMetaItems.FORMAT]: (format: ValueFormat) => getNames(Object.keys(format)), + [WellknownMetaItems.UNITS]: (units: string[]) => Util.resolveUnits(units), +}; + +/** An agent link as its type and agent id, e.g. "SimulatorAgentLink (5Bg0X…)". */ +function getAgentLinkShortValue(link: { type?: unknown; id?: unknown }): string | undefined { + if (typeof link.type !== "string") { + return undefined; + } + return link.id ? `${link.type} (${String(link.id)})` : link.type; +} + +/** Names in sentence case, comma separated, e.g. "Not blank, Size". */ +function getNames(names: string[]): string { + return names.map((name) => Util.camelCaseToSentenceCase(name)).join(", "); +} + +/** Shows or hides the formatted JSON of a configuration item. */ +function toggleJson(ev: Event) { + (ev.currentTarget as HTMLElement).closest(".ac-item")?.classList.toggle("ac-json-shown"); +} diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.ts index 0d17bbb35a..b6783b51a7 100644 --- a/ui/component/or-asset-viewer/src/index.ts +++ b/ui/component/or-asset-viewer/src/index.ts @@ -324,7 +324,12 @@ declare global { } } -export function getPanel(id: string, panelConfig: PanelConfig, content: TemplateResult | undefined) { +export function getPanel( + id: string, + panelConfig: PanelConfig, + content: TemplateResult | undefined, + actions?: TemplateResult +) { if (!content) { return; } @@ -338,6 +343,7 @@ export function getPanel(id: string, panelConfig: PanelConfig, content: Template
+ ${actions ? html`
${actions}
` : ``}
${content}
@@ -1481,7 +1487,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(OrEleme if (editMode) { content = html`
- +
`; 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.ts index 2c74c8d5b2..fcee588e22 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 @@ -40,6 +40,11 @@ import { showDialog, type OrVaadinDialog } from "@openremote/or-vaadin-component import type { OrVaadinCheckboxGroup } from "@openremote/or-vaadin-components/or-vaadin-checkbox-group"; import type { OrVaadinButton } from "@openremote/or-vaadin-components/or-vaadin-button"; import "./or-add-attribute-panel"; +import { + type AssetAttributes, + showExportConfigurationTemplateDialog, + showImportConfigurationTemplateDialog, +} from "./configuration-template"; import { getField, getPanel, getPropertyTemplate } from "./index"; import type { OrAddAttributePanelAttributeChangedEvent } from "./or-add-attribute-panel"; import { panelStyles } from "./style"; @@ -211,6 +216,10 @@ export class OrEditAssetPanel extends OrElement { @property({ attribute: false }) protected asset!: Asset; + /** Whether the draft holds unsaved changes, which blocks exporting a configuration template. */ + @property({ type: Boolean }) + public modified = false; + protected attributeTemplatesAndValidators: TemplateAndValidator[] = []; protected changedAttributes: string[] = []; @@ -380,7 +389,14 @@ export class OrEditAssetPanel extends OrElement { return html`
${getPanel("0", { type: "info", title: "properties" }, html`${properties}`) || ``} - ${getPanel("1", { type: "info", title: "attribute_plural" }, html`${attributes}`) || ``} + ${ + getPanel( + "1", + { type: "info", title: "attribute_plural" }, + html`${attributes}`, + this._getConfigurationActionsTemplate() + ) || `` + }
`; } @@ -479,6 +495,43 @@ export class OrEditAssetPanel extends OrElement { }; } + /** Import and Export, left out on agents as those are configured through attribute values. */ + protected _getConfigurationActionsTemplate(): TemplateResult | undefined { + if (AssetModelUtil.getAssetDescriptor(this.asset.type)?.descriptorType === "agent") { + return undefined; + } + + return html` + this._importConfiguration()}> + + + + showExportConfigurationTemplateDialog(this.shadowRoot!, this.asset)} + > + + + + `; + } + + protected _importConfiguration() { + showImportConfigurationTemplateDialog(this.shadowRoot!, this.asset, (attributes) => + this._onConfigurationImported(attributes) + ); + } + + protected async _onConfigurationImported(attributes: AssetAttributes) { + this.asset.attributes = attributes; + + // Render the imported metadata before validating it + this.requestUpdate(); + await this.updateComplete; + this._onModified(); + } + protected _onModified() { this.dispatchEvent(new OrEditAssetModifiedEvent(this.validate())); } diff --git a/ui/component/or-asset-viewer/src/style.ts b/ui/component/or-asset-viewer/src/style.ts index 34207eed91..ab31723cd4 100644 --- a/ui/component/or-asset-viewer/src/style.ts +++ b/ui/component/or-asset-viewer/src/style.ts @@ -61,6 +61,8 @@ export const panelStyles = css` } .panel-title { + display: flex; + align-items: center; font-size: 18px; font-weight: bold; color: var(--internal-or-asset-viewer-title-text-color); @@ -68,6 +70,14 @@ export const panelStyles = css` flex: 0 0 auto; } + .panel-title-actions { + display: flex; + gap: 8px; + margin-left: auto; + font-size: initial; + font-weight: initial; + } + .field { margin: 10px 0; width: 100%; diff --git a/ui/component/or-map/src/controls/legend.ts b/ui/component/or-map/src/controls/legend.ts index 7eaf3be99f..e4658c9ddf 100644 --- a/ui/component/or-map/src/controls/legend.ts +++ b/ui/component/or-map/src/controls/legend.ts @@ -18,7 +18,6 @@ */ import { css, type CSSResultGroup, html, type PropertyValues, type TemplateResult } from "lit"; import { OrElement } from "@openremote/or-element"; -import { countBadgeStyle } from "./styles"; import { customElement, property, state } from "lit/decorators.js"; import { AssetModelUtil } from "@openremote/model"; import { formatCount, getMarkerIconAndColorFromAssetType } from "../util"; @@ -53,7 +52,6 @@ declare global { export class OrMapLegend extends OrElement { static get styles(): CSSResultGroup { return [ - countBadgeStyle, css` :host { display: block; @@ -201,7 +199,7 @@ export class OrMapLegend extends OrElement { ${this._assetTypesInfo[assetType].label} - ${formatCount(this.assetCounts[assetType] ?? 0)} { export class OrMapPresetFilter extends OrElement { static get styles() { return [ - countBadgeStyle, css` :host { display: block; @@ -173,26 +171,25 @@ export class OrMapPresetFilter extends OrElement { return html` ${options.map( @@ -203,7 +200,7 @@ export class OrMapPresetFilter extends OrElement { >${opt.warning ? "âš  " : ""}${opt.label} ${opt.warning ? html`${opt.warning}` : nothing} - ${formatCount(opt.count)} + ${formatCount(opt.count)} ` @@ -221,7 +218,7 @@ export class OrMapPresetFilter extends OrElement { ${selectRenderer(this._renderFilterOptions, [this.filters, this.assets])} @change="${this._onChange}" > - ${formatCount(currentCount)} + ${formatCount(currentCount)} `; } diff --git a/ui/component/or-map/src/controls/styles.ts b/ui/component/or-map/src/controls/styles.ts deleted file mode 100644 index 97067430b5..0000000000 --- a/ui/component/or-map/src/controls/styles.ts +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2026, OpenRemote Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - * - * SPDX-License-Identifier: AGPL-3.0-or-later - */ -import { css } from "lit"; - -export const countBadgeStyle = css` - or-vaadin-badge { - --vaadin-badge-background: var(--shades-contrast-10, #3a463a0d); - border-radius: calc(var(--lumo-border-radius-m) + 2px); - font-size: 12px; - color: var(--lumo-secondary-text-color); - padding: 0 calc(var(--lumo-space-m) - 4px); - } -`; diff --git a/ui/component/theme/src/components/or-vaadin-badge.css b/ui/component/theme/src/components/or-vaadin-badge.css index a1b0d30f86..2a68d7afe7 100644 --- a/ui/component/theme/src/components/or-vaadin-badge.css +++ b/ui/component/theme/src/components/or-vaadin-badge.css @@ -18,8 +18,19 @@ */ @import "@vaadin/vaadin-lumo-styles/components/badge.css"; +@media lumo_badge_counter { + /* A count next to a label */ + :host([theme~="counter"]) { + --vaadin-badge-background: var(--lumo-contrast-10pct); + --vaadin-badge-text-color: var(--lumo-secondary-text-color); + --vaadin-badge-font-size: var(--lumo-font-size-xxs); + --vaadin-badge-font-weight: 400; + --vaadin-badge-padding: 0 10px; + } +} + :root::before, :host::before { --_lumo-vaadin-badge-inject: 1; - --_lumo-vaadin-badge-inject-modules: lumo_components_badge; + --_lumo-vaadin-badge-inject-modules: lumo_components_badge, lumo_badge_counter; } diff --git a/ui/component/theme/src/default.css b/ui/component/theme/src/default.css index e16b4ced03..492efc4a0a 100644 --- a/ui/component/theme/src/default.css +++ b/ui/component/theme/src/default.css @@ -176,6 +176,8 @@ --lumo-font-family: "Inter", -apple-system, BlinkMacSystemFont, "Roboto", "Segoe UI", Helvetica, Arial, sans-serif; --lumo-border-radius-m: 0.5em; --lumo-border-radius-l: 0.75em; + /* Not --lumo-border-radius-m, which is em based and shrinks with the smaller text of badges */ + --vaadin-badge-border-radius: 0.5rem; --vaadin-field-default-width: 100%; --vaadin-button-margin: 0; --lumo-clickable-cursor: pointer; From f91f4933e657232b9d60ffb81391a2e4e5263ace Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Tue, 10 Nov 2026 14:01:36 +0100 Subject: [PATCH 02/21] Keep access and attribute link meta items with the asset --- .../openremote/model/asset/AssetResource.java | 11 ++-- .../model/util/ConfigurationTemplateUtil.java | 55 +++++++++++++++---- .../util/ConfigurationTemplateUtilTest.groovy | 36 ++++++++++++ .../src/configuration-template.ts | 22 +++++++- 4 files changed, 106 insertions(+), 18 deletions(-) diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java index 3ab1aa16ea..1e727fed48 100644 --- a/model/src/main/java/org/openremote/model/asset/AssetResource.java +++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java @@ -346,9 +346,10 @@ Asset update( /** * Retrieve a configuration template of the asset: a user editable document holding the type and - * metadata of every attribute that has metadata. Repeat the attributeName query parameter to - * export a subset of them. Access follows the same rules as {@link #get}. A 400 status is - * returned if nothing is left to export. + * metadata of every attribute that has metadata. Metadata that grants access or links attributes + * stays with the asset. Repeat the attributeName query parameter to export a subset of them. + * Access follows the same rules as {@link #get}. A 400 status is returned if nothing is left to + * export. */ @GET @Path("{assetId}/configurationTemplate") @@ -358,7 +359,7 @@ Asset update( operationId = "exportConfigurationTemplate", summary = "Export a configuration template of an asset", description = - "Returns a versioned document holding the type and metadata of each attribute that has metadata, limited to the requested attribute names when any are given. Attributes without metadata are never included. Exporting nothing is rejected.") + "Returns a versioned document holding the type and metadata of each attribute that has metadata, limited to the requested attribute names when any are given. Metadata that grants access or links attributes stays with the asset, and attributes without other metadata are never included. Exporting nothing is rejected.") @OpenApiResponses.Ok @OpenApiResponses.Authenticated @OpenApiResponses.BadRequest @@ -392,7 +393,7 @@ ConfigurationTemplate exportConfigurationTemplate( operationId = "previewConfigurationTemplateImport", summary = "Preview a configuration template import", description = - "Validates the document, matches its attributes against the draft by name and type, and returns the compatibility report together with the draft attributes holding the imported metadata. Nothing is stored; the client applies the patch after the user confirms.") + "Validates the document, matches its attributes against the draft by name and type, and returns the compatibility report together with the draft attributes holding the imported metadata. Metadata that grants access or links attributes is ignored, and the draft keeps its own. Nothing is stored; the client applies the patch after the user confirms.") @OpenApiResponses.Ok @OpenApiResponses.Authenticated @ApiResponse( diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index cbc379afcd..be86ae0fad 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -19,6 +19,7 @@ package org.openremote.model.util; import static org.openremote.model.asset.ConfigurationTemplateImportFailure.*; +import static org.openremote.model.value.MetaItemType.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; @@ -30,6 +31,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.TreeMap; import org.openremote.model.asset.Asset; import org.openremote.model.asset.AttributeConfiguration; @@ -39,6 +41,7 @@ import org.openremote.model.asset.ConfigurationTemplateImportPreview; import org.openremote.model.attribute.Attribute; import org.openremote.model.attribute.AttributeMap; +import org.openremote.model.attribute.MetaMap; import org.openremote.model.value.MetaItemDescriptor; /** @@ -47,11 +50,24 @@ */ public final class ConfigurationTemplateUtil { + /** + * Metadata that stays with an asset rather than travel in a document, as it grants access or + * links attributes by asset id. Export leaves it out and import keeps that of the target. + */ + public static final Set ASSET_BOUND_META_ITEMS = + Set.of( + ACCESS_PUBLIC_READ.getName(), + ACCESS_PUBLIC_WRITE.getName(), + ACCESS_RESTRICTED_READ.getName(), + ACCESS_RESTRICTED_WRITE.getName(), + ATTRIBUTE_LINKS.getName()); + private ConfigurationTemplateUtil() {} /** * Builds the export document of an asset, holding the type and metadata of every attribute that - * has metadata. A null or empty selection exports all of them. + * has metadata other than {@link #ASSET_BOUND_META_ITEMS}. A null or empty selection exports all + * of them. */ public static ConfigurationTemplate export(Asset asset, Collection attributeNames) { boolean selectAll = attributeNames == null || attributeNames.isEmpty(); @@ -59,14 +75,16 @@ public static ConfigurationTemplate export(Asset asset, Collection at if (asset.getAttributes() != null) { asset.getAttributes().values().stream() - .filter(attribute -> attribute.getMeta() != null && !attribute.getMeta().isEmpty()) .filter(attribute -> selectAll || attributeNames.contains(attribute.getName())) .forEach( - attribute -> + attribute -> { + ObjectNode meta = withoutAssetBoundMeta(attribute.getMeta()); + + if (!meta.isEmpty()) { attributes.put( - attribute.getName(), - new AttributeConfiguration( - typeName(attribute), toObjectNode(attribute.getMeta())))); + attribute.getName(), new AttributeConfiguration(typeName(attribute), meta)); + } + }); } return new ConfigurationTemplate( @@ -77,7 +95,8 @@ public static ConfigurationTemplate export(Asset asset, Collection at * Validates a document against an asset draft and works out what importing it would do, without * changing the draft. The returned {@link * ConfigurationTemplateImportPreview#getPatchedAttributes()} holds the draft attributes with the - * metadata of every importable attribute replaced. + * metadata of every importable attribute replaced, except for {@link #ASSET_BOUND_META_ITEMS}, + * which keep the values of the draft. */ public static ConfigurationTemplateImportPreview preview(Asset draft, String document) { JsonNode root; @@ -123,6 +142,7 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String } ObjectNode importedMeta = ((ObjectNode) meta).deepCopy(); + importedMeta.remove(ASSET_BOUND_META_ITEMS); if (!isValidMeta(importedMeta)) { return ConfigurationTemplateImportPreview.failed(INVALID_META_ITEM); @@ -165,9 +185,18 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String ObjectNode patchedAttributes = toObjectNode(targetAttributes); importable.forEach( - attribute -> - ((ObjectNode) patchedAttributes.get(attribute.getName())) - .set("meta", imported.get(attribute.getName()).getMeta())); + attribute -> { + ObjectNode patched = (ObjectNode) patchedAttributes.get(attribute.getName()); + ObjectNode meta = imported.get(attribute.getName()).getMeta(); + JsonNode targetMeta = patched.get("meta"); + + if (targetMeta != null && targetMeta.isObject()) { + ASSET_BOUND_META_ITEMS.stream() + .filter(targetMeta::has) + .forEach(name -> meta.set(name, targetMeta.get(name))); + } + patched.set("meta", meta); + }); return new ConfigurationTemplateImportPreview( null, importable, missing, typeMismatches, patchedAttributes); @@ -177,6 +206,12 @@ protected static boolean isAbsent(JsonNode node) { return node == null || node.isNull(); } + protected static ObjectNode withoutAssetBoundMeta(MetaMap meta) { + ObjectNode node = meta != null ? toObjectNode(meta) : ValueUtil.JSON.createObjectNode(); + node.remove(ASSET_BOUND_META_ITEMS); + return node; + } + /** * Whether every metadata item with a known descriptor holds a value of its type that meets the * bean constraints of that type. Unknown metadata items are taken as they are. diff --git a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy index 6b5ad8491c..d8ad5b5293 100644 --- a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -121,6 +121,42 @@ class ConfigurationTemplateUtilTest extends Specification { NO_IMPORTABLE_ATTRIBUTES | document(ThingAsset.DESCRIPTOR.name, [:]) } + def "export leaves out metadata that grants access or links attributes"() { + given: "an asset whose attributes hold access and attribute link metadata" + def asset = thingAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.ACCESS_PUBLIC_WRITE.name): true]), + linked: attribute("linked", ValueType.NUMBER, [(MetaItemType.ACCESS_RESTRICTED_READ.name): true, (MetaItemType.ATTRIBUTE_LINKS.name): []]) + ]) + + when: "the configuration is exported" + def exported = ConfigurationTemplateUtil.export(asset, null) + + then: "that metadata is left out" + exported.attributes.temperature.meta.fieldNames().toList() == [MetaItemType.LABEL.name] + + and: "an attribute holding no other metadata is left out entirely" + exported.attributes.keySet() == ["temperature"] as Set + } + + def "import keeps the access and attribute link metadata of the asset and ignores that of the document"() { + given: "an asset whose attribute is publicly readable" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.ACCESS_PUBLIC_READ.name): true])]) + + when: "a document granting public write access is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"label": "Imported", "accessPublicWrite": true, "attributeLinks": []}}' + ])) + + then: "the other metadata is imported" + def meta = preview.patchedAttributes.get("temperature").get("meta") + meta.get(MetaItemType.LABEL.name).asText() == "Imported" + + and: "the access and attribute link metadata of the document is ignored and that of the asset kept" + !meta.has(MetaItemType.ACCESS_PUBLIC_WRITE.name) + !meta.has(MetaItemType.ATTRIBUTE_LINKS.name) + meta.get(MetaItemType.ACCESS_PUBLIC_READ.name).asBoolean() + } + def "an attribute missing on the target asset is skipped and reported"() { given: "an asset without the imported attribute" def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index be8f578e97..7fb3769920 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -224,10 +224,26 @@ const dialogStyle = html` `; +/** Configuration items that stay with an asset rather than travel in a template, as they grant access or link attributes. */ +const ASSET_BOUND_META_ITEMS: string[] = [ + WellknownMetaItems.ACCESSPUBLICREAD, + WellknownMetaItems.ACCESSPUBLICWRITE, + WellknownMetaItems.ACCESSRESTRICTEDREAD, + WellknownMetaItems.ACCESSRESTRICTEDWRITE, + WellknownMetaItems.ATTRIBUTELINKS, +]; + +/** The configuration items of an attribute that a template holds. */ +function getTemplateMeta(attribute: Attribute | undefined): { [name: string]: unknown } { + return Object.fromEntries( + Object.entries(attribute?.meta || {}).filter(([name]) => !ASSET_BOUND_META_ITEMS.includes(name)) + ); +} + /** The attributes holding configuration items for a template, which are the attributes that can be exported. */ export function getConfigurableAttributes(asset: Asset): Attribute[] { return Object.entries(asset.attributes || {}) - .filter(([, attribute]) => Object.keys(attribute.meta || {}).length > 0) + .filter(([, attribute]) => Object.keys(getTemplateMeta(attribute)).length > 0) .map(([name, attribute]) => ({ ...attribute, name })) .sort(Util.sortByString((attribute) => attribute.name!.toUpperCase())); } @@ -597,7 +613,7 @@ function getAttributeRowTemplate(asset: Asset, attribute: Attribute, lead:
${lead} - ${Object.keys(attribute.meta || {}).length} + ${Object.keys(getTemplateMeta(attribute)).length} @@ -707,7 +723,7 @@ function attributeName(asset: Asset, attribute: Attribute): string { /** The configuration items of an attribute that a template holds, sorted by label. */ function getConfigurationItems(asset: Asset, attribute: Attribute): ConfigurationItem[] { - return Object.entries(attribute.meta || {}) + return Object.entries(getTemplateMeta(attribute)) .map(([name, value]) => getConfigurationItem(asset, name, value)) .sort((a, b) => a.label.localeCompare(b.label)); } From 70f712526f6b041cbe05d0d9bd2410ce4a86d9e5 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Mon, 9 Nov 2026 16:45:45 +0100 Subject: [PATCH 03/21] Add config-template setup --- setup/build.gradle | 7 + .../ManagerConfigTemplateSetup.java | 243 ++++++++++++++++++ .../setup/configtemplate/SetupTasks.java | 32 +++ .../ConfigTemplateAssetModelProvider.java | 30 +++ .../setup/configtemplate/model/PumpAsset.java | 50 ++++ .../org.openremote.model.AssetModelProvider | 1 + .../org.openremote.model.setup.SetupTasks | 1 + 7 files changed, 364 insertions(+) create mode 100644 setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java create mode 100644 setup/src/config-template/java/org/openremote/setup/configtemplate/SetupTasks.java create mode 100644 setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java create mode 100644 setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java create mode 100644 setup/src/config-template/resources/META-INF/services/org.openremote.model.AssetModelProvider create mode 100644 setup/src/config-template/resources/META-INF/services/org.openremote.model.setup.SetupTasks diff --git a/setup/build.gradle b/setup/build.gradle index 09c58f1dd0..d94440f904 100644 --- a/setup/build.gradle +++ b/setup/build.gradle @@ -10,6 +10,7 @@ base { sourceSets { clustering + create("config-template") datetime demo integration @@ -21,6 +22,7 @@ sourceSets { // dependencies declaration configurations { clusteringImplementation.extendsFrom(implementation) + configTemplateImplementation.extendsFrom(implementation) datetimeImplementation.extendsFrom(implementation) demoImplementation.extendsFrom(implementation) integrationImplementation.extendsFrom(implementation) @@ -46,6 +48,11 @@ tasks.register('clusteringJar', Jar) { from sourceSets.clustering.output } +tasks.register('config-templateJar', Jar) { + archiveBaseName.set("openremote-config-template-${project.name}") + from sourceSets.getByName("config-template").output +} + tasks.register('datetimeJar', Jar) { archiveBaseName.set("openremote-datetime-${project.name}") from sourceSets.datetime.output diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java new file mode 100644 index 0000000000..f976cfd2a5 --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java @@ -0,0 +1,243 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.setup.configtemplate; + +import static org.openremote.model.Constants.*; +import static org.openremote.model.value.MetaItemType.*; +import static org.openremote.model.value.ValueType.*; + +import org.openremote.agent.protocol.bluetooth.mesh.BluetoothMeshAgent; +import org.openremote.agent.protocol.bluetooth.mesh.BluetoothMeshAgentLink; +import org.openremote.agent.protocol.http.HTTPAgent; +import org.openremote.agent.protocol.http.HTTPAgentLink; +import org.openremote.agent.protocol.knx.KNXAgent; +import org.openremote.agent.protocol.knx.KNXAgentLink; +import org.openremote.agent.protocol.mail.MailAgent; +import org.openremote.agent.protocol.mail.MailAgentLink; +import org.openremote.agent.protocol.modbus.ModbusAgentLink; +import org.openremote.agent.protocol.modbus.ModbusAgentLink.ModbusDataType; +import org.openremote.agent.protocol.modbus.ModbusAgentLink.ReadMemoryArea; +import org.openremote.agent.protocol.modbus.ModbusTcpAgent; +import org.openremote.agent.protocol.mqtt.MQTTAgent; +import org.openremote.agent.protocol.mqtt.MQTTAgentLink; +import org.openremote.agent.protocol.openweathermap.OpenWeatherMapAgent; +import org.openremote.agent.protocol.openweathermap.OpenWeatherMapAgentLink; +import org.openremote.agent.protocol.openweathermap.OpenWeatherMapProperty; +import org.openremote.agent.protocol.simulator.SimulatorAgent; +import org.openremote.agent.protocol.simulator.SimulatorAgentLink; +import org.openremote.agent.protocol.snmp.SNMPAgent; +import org.openremote.agent.protocol.snmp.SNMPAgentLink; +import org.openremote.agent.protocol.tcp.TCPAgent; +import org.openremote.agent.protocol.velbus.VelbusAgentLink; +import org.openremote.agent.protocol.velbus.VelbusTCPAgent; +import org.openremote.agent.protocol.websocket.WebsocketAgent; +import org.openremote.agent.protocol.websocket.WebsocketAgentLink; +import org.openremote.agent.protocol.zwave.ZWaveAgent; +import org.openremote.agent.protocol.zwave.ZWaveAgentLink; +import org.openremote.manager.setup.ManagerSetup; +import org.openremote.model.Constants; +import org.openremote.model.Container; +import org.openremote.model.asset.agent.Agent; +import org.openremote.model.asset.agent.AgentLink; +import org.openremote.model.asset.agent.DefaultAgentLink; +import org.openremote.model.asset.impl.ThingAsset; +import org.openremote.model.attribute.Attribute; +import org.openremote.model.attribute.MetaItem; +import org.openremote.model.value.ValueConstraint; +import org.openremote.model.value.ValueDescriptor; +import org.openremote.setup.configtemplate.model.PumpAsset; + +/** + * Seeds one configured pump and three targets to copy its configuration onto, so exporting and + * importing a configuration template can be tried end to end. Every target shows a different + * outcome: a full import, an import that skips attributes, and an import from another asset type. + * The pump's agent links follow the template parameter concept: three Modbus links share an agent + * and two of them a unit id, and two simulator links use different agents. A separate asset holds + * one attribute per agent link type, and another holds every agent. + */ +public class ManagerConfigTemplateSetup extends ManagerSetup { + + protected ThingAsset agentsParent; + + public ManagerConfigTemplateSetup(Container container) { + super(container); + } + + @Override + public void onStart() throws Exception { + super.onStart(); + + // Not a group asset, as those only hold one asset type + agentsParent = new ThingAsset("Agents"); + agentsParent.setRealm(MASTER_REALM); + agentsParent = assetStorageService.merge(agentsParent); + + // Two simulator agents, so the import asks for the agent of each simulator link separately + String simulator1AgentId = store(new SimulatorAgent("Pump Agent 1 (Simulator)")); + String simulator2AgentId = store(new SimulatorAgent("Pump Agent 2 (Simulator)")); + + // An agent of every other agent link type, disabled so none of them connects + String bluetoothMeshAgentId = storeDisabled(new BluetoothMeshAgent("Bluetooth Mesh Agent")); + String httpAgentId = storeDisabled(new HTTPAgent("HTTP Agent")); + String knxAgentId = storeDisabled(new KNXAgent("KNX Agent")); + String mailAgentId = storeDisabled(new MailAgent("Mail Agent")); + String modbusAgentId = storeDisabled(new ModbusTcpAgent("Modbus TCP Agent")); + String mqttAgentId = storeDisabled(new MQTTAgent("MQTT Agent")); + String openWeatherMapAgentId = storeDisabled(new OpenWeatherMapAgent("OpenWeatherMap Agent")); + String snmpAgentId = storeDisabled(new SNMPAgent("SNMP Agent")); + String tcpAgentId = storeDisabled(new TCPAgent("TCP Agent")); + String velbusAgentId = storeDisabled(new VelbusTCPAgent("Velbus TCP Agent")); + String websocketAgentId = storeDisabled(new WebsocketAgent("Websocket Agent")); + String zWaveAgentId = storeDisabled(new ZWaveAgent("Z-Wave Agent")); + + // The pump to export from; every attribute holds configuration items worth copying + PumpAsset configured = new PumpAsset("Pump 1 (configured)"); + configured.setRealm(MASTER_REALM); + configured.addOrReplaceAttributes( + new Attribute<>(PumpAsset.FLOW_RATE) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Flow rate"), + new MetaItem<>( + UNITS, Constants.units(UNITS_METRE, UNITS_CUBED, UNITS_PER, UNITS_HOUR)), + new MetaItem<>(READ_ONLY, true), + new MetaItem<>(STORE_DATA_POINTS, true), + new MetaItem<>(RULE_STATE, true), + new MetaItem<>( + AGENT_LINK, + modbusLink(modbusAgentId, 1, ReadMemoryArea.HOLDING, ModbusDataType.REAL, 1))), + new Attribute<>(PumpAsset.PRESSURE) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Pressure"), + new MetaItem<>(UNITS, Constants.units(UNITS_BAR)), + new MetaItem<>( + CONSTRAINTS, + ValueConstraint.constraints( + new ValueConstraint.Min(0), new ValueConstraint.Max(16))), + new MetaItem<>(STORE_DATA_POINTS, true), + new MetaItem<>( + AGENT_LINK, + modbusLink(modbusAgentId, 1, ReadMemoryArea.HOLDING, ModbusDataType.REAL, 3))), + new Attribute<>(PumpAsset.RUNNING) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Running"), + new MetaItem<>(ACCESS_PUBLIC_READ, true), + new MetaItem<>( + AGENT_LINK, + modbusLink(modbusAgentId, 2, ReadMemoryArea.COIL, ModbusDataType.BOOL, 1))), + // Not a descriptor attribute, so a target asset can be missing it + new Attribute<>("errorCode", TEXT) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Error code"), + new MetaItem<>(RULE_STATE, true), + new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(simulator1AgentId))), + // Not a descriptor attribute, so a target asset can hold it with another value type + new Attribute<>("serialNumber", TEXT) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Serial number"), + new MetaItem<>(READ_ONLY, true), + new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(simulator2AgentId)))); + assetStorageService.merge(configured); + + // Holds every attribute of the configured pump, so the whole configuration can be imported + PumpAsset bare = new PumpAsset("Pump 2 (import target)"); + bare.setRealm(MASTER_REALM); + bare.addOrReplaceAttributes( + new Attribute<>("errorCode", TEXT), new Attribute<>("serialNumber", TEXT)); + assetStorageService.merge(bare); + + // Misses errorCode and holds serialNumber as a number, so the import reports both as skipped + PumpAsset partial = new PumpAsset("Pump 3 (partially compatible)"); + partial.setRealm(MASTER_REALM); + partial.addOrReplaceAttributes(new Attribute<>("serialNumber", NUMBER)); + assetStorageService.merge(partial); + + // Another asset type, sharing only some attributes with the pump + ThingAsset otherType = new ThingAsset("Mixer 1 (other asset type)"); + otherType.setRealm(MASTER_REALM); + otherType.addOrReplaceAttributes( + new Attribute<>("flowRate", NUMBER), new Attribute<>("pressure", NUMBER)); + assetStorageService.merge(otherType); + + // One attribute per agent link type; "(requirements)" marks links with fields that must be set + ThingAsset agentLinks = new ThingAsset("Agent links (all types)"); + agentLinks.setRealm(MASTER_REALM); + agentLinks.addOrReplaceAttributes( + linked( + "bluetoothMesh", + BOOLEAN, + "Bluetooth mesh (requirements)", + new BluetoothMeshAgentLink(bluetoothMeshAgentId, 0, "0002", "GenericOnOffServer")), + linked("default", TEXT, "Default", new DefaultAgentLink(tcpAgentId)), + linked("http", TEXT, "HTTP (requirements)", new HTTPAgentLink(httpAgentId)), + linked( + "knx", + BOOLEAN, + "KNX (requirements)", + new KNXAgentLink(knxAgentId, "1.001", "1/0/1", "1/0/2")), + linked("mail", TEXT, "Mail", new MailAgentLink(mailAgentId)), + linked("modbus", NUMBER, "Modbus", new ModbusAgentLink(modbusAgentId)), + linked("mqtt", TEXT, "MQTT", new MQTTAgentLink(mqttAgentId)), + linked( + "openWeatherMap", + NUMBER, + "OpenWeatherMap (requirements)", + new OpenWeatherMapAgentLink(openWeatherMapAgentId) + .setWeatherProperty(OpenWeatherMapProperty.TEMPERATURE)), + linked("simulator", NUMBER, "Simulator", new SimulatorAgentLink(simulator1AgentId)), + linked( + "snmp", + TEXT, + "SNMP (requirements)", + new SNMPAgentLink(snmpAgentId, "1.3.6.1.2.1.1.3.0")), + linked( + "velbus", + BOOLEAN, + "Velbus (requirements)", + new VelbusAgentLink(velbusAgentId, 48, "CH1")), + linked("websocket", TEXT, "Websocket", new WebsocketAgentLink(websocketAgentId)), + linked("zWave", BOOLEAN, "Z-Wave", new ZWaveAgentLink(zWaveAgentId, 2, 0, "Basic"))); + assetStorageService.merge(agentLinks); + } + + protected String store(Agent agent) { + agent.setParent(agentsParent); + return assetStorageService.merge(agent).getId(); + } + + protected String storeDisabled(Agent agent) { + agent.setDisabled(true); + return store(agent); + } + + protected static ModbusAgentLink modbusLink( + String agentId, int unitId, ReadMemoryArea area, ModbusDataType type, int address) { + ModbusAgentLink link = new ModbusAgentLink(agentId); + link.setUnitId(unitId); + link.setReadMemoryArea(area); + link.setReadValueType(type); + link.setReadAddress(address); + return link; + } + + protected static Attribute linked( + String name, ValueDescriptor type, String label, AgentLink agentLink) { + return new Attribute<>(name, type) + .addOrReplaceMeta(new MetaItem<>(LABEL, label), new MetaItem<>(AGENT_LINK, agentLink)); + } +} diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/SetupTasks.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/SetupTasks.java new file mode 100644 index 0000000000..2ca980ffba --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/SetupTasks.java @@ -0,0 +1,32 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.setup.configtemplate; + +import java.util.List; +import org.openremote.model.Container; +import org.openremote.model.setup.Setup; + +/** Setup tasks of the config template demo. */ +public class SetupTasks implements org.openremote.model.setup.SetupTasks { + + @Override + public List createTasks(Container container, String setupType, boolean keycloakEnabled) { + return List.of(new ManagerConfigTemplateSetup(container)); + } +} diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java new file mode 100644 index 0000000000..62c670e154 --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java @@ -0,0 +1,30 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.setup.configtemplate.model; + +import org.openremote.model.AssetModelProvider; + +/** Adds the asset types of this source set to the asset model. */ +public class ConfigTemplateAssetModelProvider implements AssetModelProvider { + + @Override + public boolean useAutoScan() { + return true; + } +} diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java new file mode 100644 index 0000000000..3a021ebb30 --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java @@ -0,0 +1,50 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.setup.configtemplate.model; + +import jakarta.persistence.Entity; +import org.openremote.model.asset.Asset; +import org.openremote.model.asset.AssetDescriptor; +import org.openremote.model.value.AttributeDescriptor; +import org.openremote.model.value.ValueType; + +/** + * Asset type of the config template demo. The descriptors deliberately carry no metadata, so a new + * pump starts without configuration items and is an empty target for an import. + */ +@Entity +public class PumpAsset extends Asset { + + public static final AttributeDescriptor FLOW_RATE = + new AttributeDescriptor<>("flowRate", ValueType.NUMBER); + public static final AttributeDescriptor PRESSURE = + new AttributeDescriptor<>("pressure", ValueType.NUMBER); + public static final AttributeDescriptor RUNNING = + new AttributeDescriptor<>("running", ValueType.BOOLEAN); + + public static final AssetDescriptor DESCRIPTOR = + new AssetDescriptor<>("water-pump", "1565c0", PumpAsset.class); + + /** For use by hydrators (i.e. JPA/Jackson) */ + protected PumpAsset() {} + + public PumpAsset(String name) { + super(name); + } +} diff --git a/setup/src/config-template/resources/META-INF/services/org.openremote.model.AssetModelProvider b/setup/src/config-template/resources/META-INF/services/org.openremote.model.AssetModelProvider new file mode 100644 index 0000000000..4110715f93 --- /dev/null +++ b/setup/src/config-template/resources/META-INF/services/org.openremote.model.AssetModelProvider @@ -0,0 +1 @@ +org.openremote.setup.configtemplate.model.ConfigTemplateAssetModelProvider diff --git a/setup/src/config-template/resources/META-INF/services/org.openremote.model.setup.SetupTasks b/setup/src/config-template/resources/META-INF/services/org.openremote.model.setup.SetupTasks new file mode 100644 index 0000000000..40fcf9fdd2 --- /dev/null +++ b/setup/src/config-template/resources/META-INF/services/org.openremote.model.setup.SetupTasks @@ -0,0 +1 @@ +org.openremote.setup.configtemplate.SetupTasks From 4f785084e5f2af9cbb96acc932d99d9bf5ab111c Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Wed, 11 Nov 2026 11:45:47 +0100 Subject: [PATCH 04/21] Add side padding to configuration item cards --- ui/component/or-asset-viewer/src/configuration-template.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 7fb3769920..50915de691 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -149,7 +149,7 @@ const dialogStyle = html` min-width: 0; background-color: var(--lumo-base-color); border-radius: var(--lumo-border-radius-s); - padding: var(--lumo-space-s); + padding: var(--lumo-space-s) var(--lumo-space-m); } .ac-item-header { display: flex; From f2352b471514163b61de0f69983c1470eecb29b8 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 11:20:18 +0100 Subject: [PATCH 05/21] Add model and test guidelines to AGENTS.md --- AGENTS.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index d2fe54b17f..793f3d4027 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,10 +30,22 @@ ex.response.withCloseable { r -> } ``` +Start the container in `setupSpec`, not in each feature method, and remove any test-specific resources in `cleanup`. The container is reused, but starting it still costs a couple of seconds per method. + ### Running tests When running integration tests, part of the stack (PostgreSQL and Keycloak) must be running. Start it with `docker compose -f profile/dev-testing.yml -p openremote up -d --no-build`. +## Model and JSON + +Don't put `@JsonProperty` on `@JsonCreator` parameters whose name already matches the property; the build compiles with `-parameters` and registers `ParameterNamesModule`. Add it only when the names differ. + +Keep Jackson types (`JsonNode`, `ObjectNode`) out of model fields and public signatures; they are an implementation dependency. Use the typed model instead: `AttributeMap`, `MetaMap`, `NamedMap`, or the DTO itself. + +Bind a request body to its model class and validate it with JSR-380 (`@NotNull`, `@NotBlank`, `@Min`, ...), so each violation carries its path; see `AssetValidator`. Read a JSON tree only where each kind of defect needs its own error, and keep the tree inside the method that reads it. + +`NamedMap`, so `AttributeMap` and `MetaMap`, is unordered. Use `LinkedHashMap` to keep an order that already carries meaning, and `TreeMap` only when a sorted, stable serialization is the goal. + ## REST resources ### Endpoint roles From 00782b9ca8b752c05b473437cea05e54c8f0b671 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 11:54:26 +0100 Subject: [PATCH 06/21] Drop redundant @JsonProperty annotations --- .../model/asset/AttributeConfigurationSummary.java | 4 +--- .../model/asset/AttributeConfigurationTypeMismatch.java | 6 +----- .../org/openremote/model/asset/ConfigurationTemplate.java | 5 +---- .../model/asset/ConfigurationTemplateImportRequest.java | 4 +--- 4 files changed, 4 insertions(+), 15 deletions(-) diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java index 18c8f3879c..75fc6ee114 100644 --- a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java @@ -19,7 +19,6 @@ package org.openremote.model.asset; import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; /** An attribute of a {@link ConfigurationTemplate} as reported to the user. */ @@ -33,8 +32,7 @@ public class AttributeConfigurationSummary { protected String type; @JsonCreator - public AttributeConfigurationSummary( - @JsonProperty("name") String name, @JsonProperty("type") String type) { + public AttributeConfigurationSummary(String name, String type) { this.name = name; this.type = type; } diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java index 7271391d72..664539e79d 100644 --- a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java @@ -19,7 +19,6 @@ package org.openremote.model.asset; import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; /** @@ -38,10 +37,7 @@ public class AttributeConfigurationTypeMismatch { protected String targetType; @JsonCreator - public AttributeConfigurationTypeMismatch( - @JsonProperty("name") String name, - @JsonProperty("importedType") String importedType, - @JsonProperty("targetType") String targetType) { + public AttributeConfigurationTypeMismatch(String name, String importedType, String targetType) { this.name = name; this.importedType = importedType; this.targetType = targetType; diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java index e46b77de55..334af7e7c9 100644 --- a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java @@ -19,7 +19,6 @@ package org.openremote.model.asset; import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import java.util.Map; @@ -47,9 +46,7 @@ public class ConfigurationTemplate { @JsonCreator public ConfigurationTemplate( - @JsonProperty("version") int version, - @JsonProperty("assetType") String assetType, - @JsonProperty("attributes") Map attributes) { + int version, String assetType, Map attributes) { this.version = version; this.assetType = assetType; this.attributes = attributes; diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java index 6c7d9d3a09..dc4c6189f3 100644 --- a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java @@ -19,7 +19,6 @@ package org.openremote.model.asset; import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; @@ -38,8 +37,7 @@ public class ConfigurationTemplateImportRequest { @NotNull protected String document; @JsonCreator - public ConfigurationTemplateImportRequest( - @JsonProperty("draft") Asset draft, @JsonProperty("document") String document) { + public ConfigurationTemplateImportRequest(Asset draft, String document) { this.draft = draft; this.document = document; } From 5a05f41e4fd49ae680ff6a03368849fc7ccd35f8 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 12:10:26 +0100 Subject: [PATCH 07/21] Use MetaMap and AttributeMap in configuration templates --- .../model/asset/AttributeConfiguration.java | 14 +-- .../ConfigurationTemplateImportPreview.java | 18 ++-- .../model/util/ConfigurationTemplateUtil.java | 101 ++++++++---------- .../util/ConfigurationTemplateUtilTest.groovy | 32 +++--- .../assets/ConfigurationTemplateTest.groovy | 14 +-- .../src/configuration-template.ts | 2 +- 6 files changed, 85 insertions(+), 96 deletions(-) diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java index d54f7681c7..0a9a57c5a0 100644 --- a/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java @@ -19,9 +19,9 @@ package org.openremote.model.asset; import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.v3.oas.annotations.media.Schema; +import org.openremote.model.attribute.MetaMap; +import org.openremote.model.value.MetaHolder; /** * The configuration of a single {@link org.openremote.model.attribute.Attribute} within an {@link @@ -30,17 +30,16 @@ @Schema( description = "Configuration of a single attribute; the attribute name is the key within the document.") -public class AttributeConfiguration { +public class AttributeConfiguration implements MetaHolder { @Schema(description = "Value descriptor name of the attribute, e.g. number.") protected String type; @Schema(description = "Metadata keyed by meta-item name, exactly as stored on the attribute.") - protected ObjectNode meta; + protected MetaMap meta; @JsonCreator - public AttributeConfiguration( - @JsonProperty("type") String type, @JsonProperty("meta") ObjectNode meta) { + public AttributeConfiguration(String type, MetaMap meta) { this.type = type; this.meta = meta; } @@ -49,7 +48,8 @@ public String getType() { return type; } - public ObjectNode getMeta() { + @Override + public MetaMap getMeta() { return meta; } } diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java index ef0b3d46eb..7a813247d0 100644 --- a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java @@ -19,10 +19,9 @@ package org.openremote.model.asset; import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.v3.oas.annotations.media.Schema; import java.util.List; +import org.openremote.model.attribute.AttributeMap; /** * What importing a {@link ConfigurationTemplate} into an asset draft would do, for the user to @@ -50,16 +49,15 @@ public class ConfigurationTemplateImportPreview { @Schema( description = "The submitted draft attributes with the metadata of every importable attribute replaced, keyed by attribute name.") - protected ObjectNode patchedAttributes; + protected AttributeMap patchedAttributes; @JsonCreator public ConfigurationTemplateImportPreview( - @JsonProperty("failure") ConfigurationTemplateImportFailure failure, - @JsonProperty("importableAttributes") - List importableAttributes, - @JsonProperty("missingAttributes") List missingAttributes, - @JsonProperty("typeMismatches") List typeMismatches, - @JsonProperty("patchedAttributes") ObjectNode patchedAttributes) { + ConfigurationTemplateImportFailure failure, + List importableAttributes, + List missingAttributes, + List typeMismatches, + AttributeMap patchedAttributes) { this.failure = failure; this.importableAttributes = importableAttributes; this.missingAttributes = missingAttributes; @@ -88,7 +86,7 @@ public List getTypeMismatches() { return typeMismatches; } - public ObjectNode getPatchedAttributes() { + public AttributeMap getPatchedAttributes() { return patchedAttributes; } } diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index be86ae0fad..648df34b89 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -41,8 +41,8 @@ import org.openremote.model.asset.ConfigurationTemplateImportPreview; import org.openremote.model.attribute.Attribute; import org.openremote.model.attribute.AttributeMap; +import org.openremote.model.attribute.MetaItem; import org.openremote.model.attribute.MetaMap; -import org.openremote.model.value.MetaItemDescriptor; /** * Reads and writes {@link ConfigurationTemplate}s. Callers are responsible for enforcing realm @@ -78,7 +78,7 @@ public static ConfigurationTemplate export(Asset asset, Collection at .filter(attribute -> selectAll || attributeNames.contains(attribute.getName())) .forEach( attribute -> { - ObjectNode meta = withoutAssetBoundMeta(attribute.getMeta()); + MetaMap meta = withoutAssetBoundMeta(attribute.getMeta()); if (!meta.isEmpty()) { attributes.put( @@ -97,6 +97,9 @@ public static ConfigurationTemplate export(Asset asset, Collection at * ConfigurationTemplateImportPreview#getPatchedAttributes()} holds the draft attributes with the * metadata of every importable attribute replaced, except for {@link #ASSET_BOUND_META_ITEMS}, * which keep the values of the draft. + * + *

The document is read as a JSON tree, as binding it cannot tell a malformed entry from an + * invalid metadata item. */ public static ConfigurationTemplateImportPreview preview(Asset draft, String document) { JsonNode root; @@ -141,14 +144,13 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); } - ObjectNode importedMeta = ((ObjectNode) meta).deepCopy(); - importedMeta.remove(ASSET_BOUND_META_ITEMS); + Optional importedMeta = readMeta((ObjectNode) meta); - if (!isValidMeta(importedMeta)) { + if (importedMeta.isEmpty()) { return ConfigurationTemplateImportPreview.failed(INVALID_META_ITEM); } - imported.put(entry.getKey(), new AttributeConfiguration(type.asText(), importedMeta)); + imported.put(entry.getKey(), new AttributeConfiguration(type.asText(), importedMeta.get())); } AttributeMap targetAttributes = @@ -183,66 +185,67 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String NO_IMPORTABLE_ATTRIBUTES, importable, missing, typeMismatches, null); } - ObjectNode patchedAttributes = toObjectNode(targetAttributes); + AttributeMap patchedAttributes = ValueUtil.clone(targetAttributes); importable.forEach( - attribute -> { - ObjectNode patched = (ObjectNode) patchedAttributes.get(attribute.getName()); - ObjectNode meta = imported.get(attribute.getName()).getMeta(); - JsonNode targetMeta = patched.get("meta"); - - if (targetMeta != null && targetMeta.isObject()) { - ASSET_BOUND_META_ITEMS.stream() - .filter(targetMeta::has) - .forEach(name -> meta.set(name, targetMeta.get(name))); + summary -> { + Attribute patched = patchedAttributes.get(summary.getName()).orElseThrow(); + MetaMap meta = imported.get(summary.getName()).getMeta(); + + if (patched.getMeta() != null) { + ASSET_BOUND_META_ITEMS.forEach( + name -> patched.getMeta().get(name).ifPresent(item -> meta.addOrReplace(item))); } - patched.set("meta", meta); + patched.setMeta(meta); }); return new ConfigurationTemplateImportPreview( null, importable, missing, typeMismatches, patchedAttributes); } - protected static boolean isAbsent(JsonNode node) { + private static boolean isAbsent(JsonNode node) { return node == null || node.isNull(); } - protected static ObjectNode withoutAssetBoundMeta(MetaMap meta) { - ObjectNode node = meta != null ? toObjectNode(meta) : ValueUtil.JSON.createObjectNode(); - node.remove(ASSET_BOUND_META_ITEMS); - return node; + private static MetaMap withoutAssetBoundMeta(MetaMap meta) { + MetaMap result = meta != null ? new MetaMap(meta) : new MetaMap(); + ASSET_BOUND_META_ITEMS.forEach(result::remove); + return result; } /** - * Whether every metadata item with a known descriptor holds a value of its type that meets the - * bean constraints of that type. Unknown metadata items are taken as they are. + * Reads the metadata of a document entry without the {@link #ASSET_BOUND_META_ITEMS}, or nothing + * if an item with a known descriptor does not hold a value of its type that meets the bean + * constraints of that type. Unknown metadata items are taken as they are. */ - protected static boolean isValidMeta(ObjectNode meta) { - for (Map.Entry item : meta.properties()) { - Optional> descriptor = ValueUtil.getMetaItemDescriptor(item.getKey()); + private static Optional readMeta(ObjectNode node) { + ObjectNode items = node.deepCopy(); + items.remove(ASSET_BOUND_META_ITEMS); + MetaMap meta; - if (descriptor.isEmpty() || item.getValue().isNull()) { - continue; - } - try { - Object value = - ValueUtil.JSON.treeToValue(item.getValue(), descriptor.get().getType().getType()); - - if (value != null - && (!ValueUtil.validate(value).isEmpty() || changesType(item.getValue(), value))) { - return false; - } - } catch (JsonProcessingException | IllegalArgumentException e) { - return false; + try { + meta = ValueUtil.JSON.treeToValue(items, MetaMap.class); + } catch (JsonProcessingException | IllegalArgumentException e) { + return Optional.empty(); + } + + for (MetaItem item : meta.values()) { + Object value = item.getValue().orElse(null); + + if (item.getType() != null + && value != null + && (!ValueUtil.validate(value).isEmpty() + || changesType(items.get(item.getName()), value))) { + return Optional.empty(); } } - return true; + return Optional.of(meta); } /** * Whether a value that names its subtype was read as another one, as happens to an agent link of * a type that is not installed, which falls back to the default agent link. */ - protected static boolean changesType(JsonNode node, Object value) { + private static boolean changesType(JsonNode node, Object value) { JsonNode type = node.get("type"); if (type == null || !type.isTextual()) { @@ -252,19 +255,7 @@ protected static boolean changesType(JsonNode node, Object value) { return readType != null && !type.asText().equals(readType.asText()); } - protected static String typeName(Attribute attribute) { + private static String typeName(Attribute attribute) { return attribute.getType() != null ? attribute.getType().getName() : null; } - - /** - * Serializes through text rather than a token buffer, so that attribute values held as raw JSON - * are materialized into the returned tree. - */ - protected static ObjectNode toObjectNode(Object value) { - try { - return (ObjectNode) ValueUtil.JSON.readTree(ValueUtil.JSON.writeValueAsString(value)); - } catch (JsonProcessingException e) { - throw new IllegalStateException("Cannot serialize attribute configuration", e); - } - } } diff --git a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy index d8ad5b5293..35c1184240 100644 --- a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -78,8 +78,8 @@ class ConfigurationTemplateUtilTest extends Specification { and: "only the attribute with metadata is held, with its type and its metadata as stored" exported.attributes.keySet() == ["temperature"] as Set exported.attributes.temperature.type == ValueType.NUMBER.name - exported.attributes.temperature.meta.get(MetaItemType.LABEL.name).asText() == "Temperature" - exported.attributes.temperature.meta.get("unknownMetaItem").get("nested").asInt() == 1 + exported.attributes.temperature.getMetaValue(MetaItemType.LABEL).orElse(null) == "Temperature" + exported.attributes.temperature.meta.getValue("unknownMetaItem", Map).orElse(null) == [nested: 1] } def "export limited to a selection holds only the selected attributes"() { @@ -132,7 +132,7 @@ class ConfigurationTemplateUtilTest extends Specification { def exported = ConfigurationTemplateUtil.export(asset, null) then: "that metadata is left out" - exported.attributes.temperature.meta.fieldNames().toList() == [MetaItemType.LABEL.name] + exported.attributes.temperature.meta.keySet() == [MetaItemType.LABEL.name] as Set and: "an attribute holding no other metadata is left out entirely" exported.attributes.keySet() == ["temperature"] as Set @@ -148,13 +148,13 @@ class ConfigurationTemplateUtilTest extends Specification { ])) then: "the other metadata is imported" - def meta = preview.patchedAttributes.get("temperature").get("meta") - meta.get(MetaItemType.LABEL.name).asText() == "Imported" + def meta = preview.patchedAttributes.get("temperature").get().meta + meta.getValue(MetaItemType.LABEL).orElse(null) == "Imported" and: "the access and attribute link metadata of the document is ignored and that of the asset kept" - !meta.has(MetaItemType.ACCESS_PUBLIC_WRITE.name) - !meta.has(MetaItemType.ATTRIBUTE_LINKS.name) - meta.get(MetaItemType.ACCESS_PUBLIC_READ.name).asBoolean() + !meta.has(MetaItemType.ACCESS_PUBLIC_WRITE) + !meta.has(MetaItemType.ATTRIBUTE_LINKS) + meta.getValue(MetaItemType.ACCESS_PUBLIC_READ).orElse(false) } def "an attribute missing on the target asset is skipped and reported"() { @@ -235,17 +235,17 @@ class ConfigurationTemplateUtilTest extends Specification { ])) then: "the imported metadata replaces the existing metadata entirely" - def patchedTemperature = preview.patchedAttributes.get("temperature") - patchedTemperature.get("meta").get("unitType").get(0).asText() == "celsius" - !patchedTemperature.get("meta").has(MetaItemType.LABEL.name) - !patchedTemperature.get("meta").has(MetaItemType.READ_ONLY.name) + def patchedTemperature = preview.patchedAttributes.get("temperature").get() + patchedTemperature.meta.getValue("unitType", List).orElse(null) == ["celsius"] + !patchedTemperature.hasMeta(MetaItemType.LABEL) + !patchedTemperature.hasMeta(MetaItemType.READ_ONLY) and: "an attribute without metadata gets the imported metadata added" - preview.patchedAttributes.get("plain").get("meta").get("label").asText() == "Plain" + preview.patchedAttributes.get("plain").get().getMetaValue(MetaItemType.LABEL).orElse(null) == "Plain" and: "the type and the value of the attribute are untouched" - patchedTemperature.get("type").asText() == ValueType.NUMBER.name - patchedTemperature.get("value").asDouble() == 21.5d + patchedTemperature.type == ValueType.NUMBER + patchedTemperature.value.orElse(null) == 21.5d and: "the asset itself is not modified" asset.getAttributes().get("temperature").get().getMeta().has(MetaItemType.LABEL.name) @@ -263,6 +263,6 @@ class ConfigurationTemplateUtilTest extends Specification { then: "the map key decides which attribute is imported" preview.importableAttributes*.name == ["temperature"] - preview.patchedAttributes.get("temperature").get("meta").get("label").asText() == "Imported" + preview.patchedAttributes.get("temperature").get().getMetaValue(MetaItemType.LABEL).orElse(null) == "Imported" } } diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy index f168dfaf17..2d61958aa9 100644 --- a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -93,8 +93,8 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine document.assetType == ThingAsset.DESCRIPTOR.name document.attributes.keySet() == ["temperature", "customValue"] as Set document.attributes.temperature.type == ValueType.NUMBER.name - document.attributes.temperature.meta.get(MetaItemType.LABEL.name).asText() == "Source temperature" - document.attributes.temperature.meta.get(MetaItemType.READ_ONLY.name).asBoolean() + document.attributes.temperature.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source temperature" + document.attributes.temperature.getMetaValue(MetaItemType.READ_ONLY).orElse(false) when: "a subset of the attributes is exported" def subset = assetResource.exportConfigurationTemplate(null, source.id, ["temperature"]) @@ -124,13 +124,13 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine preview.typeMismatches*.targetType == [ValueType.NUMBER.name] and: "the patched attributes hold the imported metadata, keeping the attribute value" - def patched = preview.patchedAttributes.get("temperature") - patched.get("meta").get(MetaItemType.LABEL.name).asText() == "Source temperature" - patched.get("meta").get(MetaItemType.READ_ONLY.name).asBoolean() - patched.get("value").asDouble() == 21.5d + def patched = preview.patchedAttributes.get("temperature").get() + patched.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source temperature" + patched.getMetaValue(MetaItemType.READ_ONLY).orElse(false) + patched.value.orElse(null) == 21.5d and: "the attributes that are not imported are returned untouched" - preview.patchedAttributes.get("customValue").get("type").asText() == ValueType.NUMBER.name + preview.patchedAttributes.get("customValue").get().type == ValueType.NUMBER and: "the target asset is not stored by the preview" assetResource.get(null, target.id).getAttribute("temperature").get().getMeta() diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 50915de691..26032bd5d0 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -472,7 +472,7 @@ function showImportPreviewDialog( onImported: (attributes: AssetAttributes) => void, onBack: () => void ) { - const patchedAttributes = (preview.patchedAttributes || {}) as AssetAttributes; + const patchedAttributes: AssetAttributes = preview.patchedAttributes || {}; const importable = preview.importableAttributes || []; const dialog = showDialog( From 9d3aed16b30781bbcb7e8a5cd2e698f95c380291 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 12:10:41 +0100 Subject: [PATCH 08/21] Explain why exported attributes are sorted --- .../org/openremote/model/util/ConfigurationTemplateUtil.java | 1 + 1 file changed, 1 insertion(+) diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index 648df34b89..2cf4034d31 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -71,6 +71,7 @@ private ConfigurationTemplateUtil() {} */ public static ConfigurationTemplate export(Asset asset, Collection attributeNames) { boolean selectAll = attributeNames == null || attributeNames.isEmpty(); + // Sorted by name, as the attributes of an asset have no order of their own Map attributes = new TreeMap<>(); if (asset.getAttributes() != null) { From 90d54e1f2c1e770ad09ff1150d2d69443087ca32 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 12:10:47 +0100 Subject: [PATCH 09/21] Start the container once in ConfigurationTemplateTest --- .../assets/ConfigurationTemplateTest.groovy | 140 +++++++++--------- 1 file changed, 68 insertions(+), 72 deletions(-) diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy index 2d61958aa9..4160a81e01 100644 --- a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -34,6 +34,7 @@ import org.openremote.model.value.ValueType import org.openremote.setup.integration.KeycloakTestSetup import org.openremote.setup.integration.ManagerTestSetup import org.openremote.test.ManagerContainerTrait +import spock.lang.Shared import spock.lang.Specification import static jakarta.ws.rs.core.Response.Status.BAD_REQUEST @@ -48,25 +49,64 @@ import static org.openremote.model.util.MapAccess.getString class ConfigurationTemplateTest extends Specification implements ManagerContainerTrait { - def "Export and import a configuration template as superuser"() { - given: "the server container is started" + @Shared + static KeycloakTestSetup keycloakTestSetup + + @Shared + static ManagerTestSetup managerTestSetup + + @Shared + static AssetResource adminResource + + @Shared + static AssetResource readOnlyUserResource + + @Shared + static AssetResource masterUserResource + + @Shared + static AssetResource restrictedUserResource + + /** Assets created by a feature, removed again in cleanup. */ + List createdAssetIds = [] + + def setupSpec() { def container = startContainer(defaultConfig(), defaultServices()) - def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) + keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) + managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class) + def buildingRealm = keycloakTestSetup.realmBuilding.name - and: "an authenticated admin user" - def accessToken = authenticate( + def adminAccessToken = authenticate( container, MASTER_REALM, KEYCLOAK_CLIENT_ID, MASTER_REALM_ADMIN_USER, getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT) ) + adminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(AssetResource.class) - and: "the asset resource" - def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class) + // A building realm user that can read but not write assets + def readOnlyUserToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "testuser2", "testuser2") + readOnlyUserResource = getClientApiTarget(serverUri(serverPort), buildingRealm, readOnlyUserToken).proxy(AssetResource.class) - and: "a configured source asset and a target asset of the same type" - def source = assetResource.create(null, new ThingAsset("Configuration source") + // A master realm user that can write assets + def masterUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "testuser1", "testuser1") + masterUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, masterUserToken).proxy(AssetResource.class) + + // A restricted building realm user that can write the assets linked to it + def restrictedUserToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "testuser3", "testuser3") + restrictedUserResource = getClientApiTarget(serverUri(serverPort), buildingRealm, restrictedUserToken).proxy(AssetResource.class) + } + + def cleanup() { + if (!createdAssetIds.isEmpty()) { + adminResource.delete(null, createdAssetIds) + } + } + + def "Export and import a configuration template as superuser"() { + given: "a configured source asset and a target asset of the same type" + def source = adminResource.create(null, new ThingAsset("Configuration source") .setRealm(keycloakTestSetup.realmMaster.name) .addOrReplaceAttributes( new Attribute<>("temperature", ValueType.NUMBER) @@ -76,7 +116,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source custom value")), new Attribute<>("plain", ValueType.TEXT) )) - def target = assetResource.create(null, new ThingAsset("Configuration target") + def target = adminResource.create(null, new ThingAsset("Configuration target") .setRealm(keycloakTestSetup.realmMaster.name) .addOrReplaceAttributes( new Attribute<>("temperature", ValueType.NUMBER, 21.5d) @@ -84,9 +124,10 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine new Attribute<>("customValue", ValueType.NUMBER), new Attribute<>("plain", ValueType.TEXT) )) + createdAssetIds.addAll([source.id, target.id]) when: "a configuration template of the source asset is exported" - def document = assetResource.exportConfigurationTemplate(null, source.id, []) + def document = adminResource.exportConfigurationTemplate(null, source.id, []) then: "only the attributes holding metadata are exported, with their type and metadata" document.version == 1 @@ -97,13 +138,13 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine document.attributes.temperature.getMetaValue(MetaItemType.READ_ONLY).orElse(false) when: "a subset of the attributes is exported" - def subset = assetResource.exportConfigurationTemplate(null, source.id, ["temperature"]) + def subset = adminResource.exportConfigurationTemplate(null, source.id, ["temperature"]) then: "only the requested attribute is exported" subset.attributes.keySet() == ["temperature"] as Set when: "only an attribute without metadata is selected" - assetResource.exportConfigurationTemplate(null, source.id, ["plain"]) + adminResource.exportConfigurationTemplate(null, source.id, ["plain"]) then: "the export is rejected as there is nothing to export" WebApplicationException nothingToExport = thrown() @@ -113,7 +154,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } when: "the exported document is imported into the target asset" - def preview = assetResource.previewConfigurationTemplateImport(null, target.id, + def preview = adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(target, ValueUtil.asJSON(document).orElseThrow())) then: "the attribute with a matching type is importable and the one with another type is reported" @@ -133,11 +174,11 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine preview.patchedAttributes.get("customValue").get().type == ValueType.NUMBER and: "the target asset is not stored by the preview" - assetResource.get(null, target.id).getAttribute("temperature").get().getMeta() + adminResource.get(null, target.id).getAttribute("temperature").get().getMeta() .getValue(MetaItemType.LABEL.name, String.class).orElse(null) == "Target temperature" when: "a document of an unsupported version is imported" - assetResource.previewConfigurationTemplateImport(null, target.id, + adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(target, '{"version": 2, "assetType": "ThingAsset", "attributes": {}}')) then: "the import is rejected with the reason" @@ -149,7 +190,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } when: "a document holding no attribute of the target asset is imported" - assetResource.previewConfigurationTemplateImport(null, target.id, + adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"absent": {"type": "text", "meta": {"label": "Absent"}}}}')) then: "the import is rejected and the skipped attribute is reported" @@ -163,7 +204,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } when: "the draft of another asset is submitted" - assetResource.previewConfigurationTemplateImport(null, target.id, + adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(source, ValueUtil.asJSON(document).orElseThrow())) then: "the import conflicts with the target asset" @@ -175,7 +216,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } when: "no draft is submitted" - assetResource.previewConfigurationTemplateImport(null, target.id, + adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(null, ValueUtil.asJSON(document).orElseThrow())) then: "the request is rejected as invalid rather than as a conflict" @@ -187,35 +228,17 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } def "Configuration template import requires asset write access"() { - given: "the server container is started" - def container = startContainer(defaultConfig(), defaultServices()) - def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class) - def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) - - and: "an authenticated user that can read but not write assets" - def accessToken = authenticate( - container, - keycloakTestSetup.realmBuilding.name, - KEYCLOAK_CLIENT_ID, - "testuser2", - "testuser2" - ) - - and: "the asset resource" - def assetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken) - .proxy(AssetResource.class) - - when: "a configuration template of an asset of the authenticated realm is exported" - def document = assetResource.exportConfigurationTemplate(null, managerTestSetup.apartment1LivingroomId, []) + when: "a user that can read but not write assets exports a configuration template of an asset of its realm" + def document = readOnlyUserResource.exportConfigurationTemplate(null, managerTestSetup.apartment1LivingroomId, []) then: "the configuration is returned" document.version == 1 !document.attributes.isEmpty() when: "the same user previews an import" - assetResource.previewConfigurationTemplateImport(null, managerTestSetup.apartment1LivingroomId, + readOnlyUserResource.previewConfigurationTemplateImport(null, managerTestSetup.apartment1LivingroomId, new ConfigurationTemplateImportRequest( - assetResource.get(null, managerTestSetup.apartment1LivingroomId), + readOnlyUserResource.get(null, managerTestSetup.apartment1LivingroomId), ValueUtil.asJSON(document).orElseThrow())) then: "access is forbidden" @@ -227,38 +250,11 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } def "Configuration template import is rejected for assets the user cannot access"() { - given: "the server container is started" - def container = startContainer(defaultConfig(), defaultServices()) - def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class) - def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) - def buildingRealm = keycloakTestSetup.realmBuilding.name - - and: "a document, which is never read as access is checked first" + given: "a document, which is never read as access is checked first" def document = '{"version": 1, "assetType": "RoomAsset", "attributes": {}}' + def buildingRealm = keycloakTestSetup.realmBuilding.name - and: "a master realm user that can write assets" - def masterUserToken = authenticate( - container, - MASTER_REALM, - KEYCLOAK_CLIENT_ID, - "testuser1", - "testuser1" - ) - def masterUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, masterUserToken) - .proxy(AssetResource.class) - - and: "a restricted building realm user that can write the assets linked to it" - def restrictedUserToken = authenticate( - container, - buildingRealm, - KEYCLOAK_CLIENT_ID, - "testuser3", - "testuser3" - ) - def restrictedUserResource = getClientApiTarget(serverUri(serverPort), buildingRealm, restrictedUserToken) - .proxy(AssetResource.class) - - when: "the master realm user previews an import into an asset of the building realm" + when: "a master realm user previews an import into an asset of the building realm" def otherRealmAssetId = managerTestSetup.apartment1LivingroomId masterUserResource.previewConfigurationTemplateImport(null, otherRealmAssetId, new ConfigurationTemplateImportRequest(draft(otherRealmAssetId, buildingRealm), document)) @@ -270,7 +266,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine return true } - when: "the restricted user previews an import into an asset that is not linked to it" + when: "a restricted user previews an import into an asset that is not linked to it" def unlinkedAssetId = managerTestSetup.apartment2LivingroomId restrictedUserResource.previewConfigurationTemplateImport(null, unlinkedAssetId, new ConfigurationTemplateImportRequest(draft(unlinkedAssetId, buildingRealm), document)) From fba05fdfc358c2ea2301f46e40b8868ca93c508d Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 14:36:50 +0100 Subject: [PATCH 10/21] Report where a configuration template fails to import --- .../openremote/model/asset/AssetResource.java | 4 +- ...gurationTemplateImportFailureLocation.java | 65 ++++++++ .../ConfigurationTemplateImportPreview.java | 18 ++- .../model/util/ConfigurationTemplateUtil.java | 140 +++++++++++++----- .../util/ConfigurationTemplateUtilTest.groovy | 40 +++++ .../assets/ConfigurationTemplateTest.groovy | 16 ++ ui/app/shared/locales/en/or.json | 7 + ui/app/shared/locales/nl/or.json | 7 + .../src/configuration-template.ts | 36 +++++ 9 files changed, 293 insertions(+), 40 deletions(-) create mode 100644 model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailureLocation.java diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java index 1e727fed48..048a5f4af0 100644 --- a/model/src/main/java/org/openremote/model/asset/AssetResource.java +++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java @@ -382,7 +382,7 @@ ConfigurationTemplate exportConfigurationTemplate( * draft once the user confirms, so the same access as {@link #update} is required. A 400 status * is returned if no draft is given or the template cannot be imported, and a 409 status if the * draft no longer identifies the persisted asset. A rejected template is answered with the - * preview, whose failure names the reason. + * preview, whose failure names the reason and, where known, the location within the template. */ @POST @Path("{assetId}/configurationTemplate/import") @@ -399,7 +399,7 @@ ConfigurationTemplate exportConfigurationTemplate( @ApiResponse( responseCode = "400", description = - "The draft is missing, or the document cannot be imported; a rejected document is answered with the preview, whose failure names the reason", + "The draft is missing, or the document cannot be imported; a rejected document is answered with the preview, whose failure names the reason and failureLocation, where known, the attribute, metadata item and parameter", content = { @Content( mediaType = APPLICATION_JSON, diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailureLocation.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailureLocation.java new file mode 100644 index 0000000000..6b7e6fd282 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailureLocation.java @@ -0,0 +1,65 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.asset; + +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * Where a {@link ConfigurationTemplate} cannot be imported, from the attribute entry down to the + * parameter of a metadata item. A part is absent when the failure lies above it, so a parameter + * without an attribute is a field of the document itself. + */ +@Schema( + description = + "Where a configuration template cannot be imported; a part is absent when the failure lies above it.") +public class ConfigurationTemplateImportFailureLocation { + + @Schema(description = "Attribute name of the entry.", example = "temperature") + protected String attribute; + + @Schema(description = "Name of the metadata item within the entry.", example = "forecast") + protected String metaItem; + + @Schema( + description = + "Path of the parameter within the metadata item, or of the field within the entry or the document.", + example = "pastCount") + protected String parameter; + + @JsonCreator + public ConfigurationTemplateImportFailureLocation( + String attribute, String metaItem, String parameter) { + this.attribute = attribute; + this.metaItem = metaItem; + this.parameter = parameter; + } + + public String getAttribute() { + return attribute; + } + + public String getMetaItem() { + return metaItem; + } + + public String getParameter() { + return parameter; + } +} diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java index 7a813247d0..4df2fdd8a9 100644 --- a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java @@ -37,6 +37,9 @@ public class ConfigurationTemplateImportPreview { @Schema(description = "Why the document cannot be imported; absent when it can.") protected ConfigurationTemplateImportFailure failure; + @Schema(description = "Where the document cannot be imported; absent when that is not known.") + protected ConfigurationTemplateImportFailureLocation failureLocation; + @Schema(description = "Attributes whose metadata will be replaced.") protected List importableAttributes; @@ -54,11 +57,13 @@ public class ConfigurationTemplateImportPreview { @JsonCreator public ConfigurationTemplateImportPreview( ConfigurationTemplateImportFailure failure, + ConfigurationTemplateImportFailureLocation failureLocation, List importableAttributes, List missingAttributes, List typeMismatches, AttributeMap patchedAttributes) { this.failure = failure; + this.failureLocation = failureLocation; this.importableAttributes = importableAttributes; this.missingAttributes = missingAttributes; this.typeMismatches = typeMismatches; @@ -67,13 +72,24 @@ public ConfigurationTemplateImportPreview( public static ConfigurationTemplateImportPreview failed( ConfigurationTemplateImportFailure failure) { - return new ConfigurationTemplateImportPreview(failure, List.of(), List.of(), List.of(), null); + return failed(failure, null); + } + + public static ConfigurationTemplateImportPreview failed( + ConfigurationTemplateImportFailure failure, + ConfigurationTemplateImportFailureLocation failureLocation) { + return new ConfigurationTemplateImportPreview( + failure, failureLocation, List.of(), List.of(), List.of(), null); } public ConfigurationTemplateImportFailure getFailure() { return failure; } + public ConfigurationTemplateImportFailureLocation getFailureLocation() { + return failureLocation; + } + public List getImportableAttributes() { return importableAttributes; } diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index 2cf4034d31..c892d3b4e3 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -22,8 +22,8 @@ import static org.openremote.model.value.MetaItemType.*; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; @@ -38,6 +38,8 @@ import org.openremote.model.asset.AttributeConfigurationSummary; import org.openremote.model.asset.AttributeConfigurationTypeMismatch; import org.openremote.model.asset.ConfigurationTemplate; +import org.openremote.model.asset.ConfigurationTemplateImportFailure; +import org.openremote.model.asset.ConfigurationTemplateImportFailureLocation; import org.openremote.model.asset.ConfigurationTemplateImportPreview; import org.openremote.model.attribute.Attribute; import org.openremote.model.attribute.AttributeMap; @@ -115,43 +117,50 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String return ConfigurationTemplateImportPreview.failed(INVALID_JSON); } + for (String field : List.of("version", "assetType", "attributes")) { + if (isAbsent(root.get(field))) { + return failed(MISSING_REQUIRED_FIELD, null, null, field); + } + } + JsonNode version = root.get("version"); JsonNode assetType = root.get("assetType"); JsonNode attributes = root.get("attributes"); - if (isAbsent(version) || isAbsent(assetType) || isAbsent(attributes)) { - return ConfigurationTemplateImportPreview.failed(MISSING_REQUIRED_FIELD); - } if (!version.isIntegralNumber() || version.asInt() != ConfigurationTemplate.CURRENT_VERSION) { return ConfigurationTemplateImportPreview.failed(UNSUPPORTED_VERSION); } if (!assetType.isTextual() || assetType.asText().isBlank()) { - return ConfigurationTemplateImportPreview.failed(MISSING_REQUIRED_FIELD); + return failed(MISSING_REQUIRED_FIELD, null, null, "assetType"); } if (!attributes.isObject()) { - return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); + return failed(MALFORMED_ATTRIBUTE_ENTRY, null, null, "attributes"); } // The map key is the attribute name, so an entry's own name field, if any, is ignored Map imported = new LinkedHashMap<>(); for (Map.Entry entry : attributes.properties()) { - JsonNode type = entry.getValue().isObject() ? entry.getValue().get("type") : null; - JsonNode meta = entry.getValue().isObject() ? entry.getValue().get("meta") : null; + String attribute = entry.getKey(); + + if (!entry.getValue().isObject()) { + return failed(MALFORMED_ATTRIBUTE_ENTRY, attribute, null, null); + } + + JsonNode type = entry.getValue().get("type"); + JsonNode meta = entry.getValue().get("meta"); if (type == null || !type.isTextual() || type.asText().isBlank()) { - return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); + return failed(MALFORMED_ATTRIBUTE_ENTRY, attribute, null, "type"); } if (meta == null || !meta.isObject()) { - return ConfigurationTemplateImportPreview.failed(MALFORMED_ATTRIBUTE_ENTRY); + return failed(MALFORMED_ATTRIBUTE_ENTRY, attribute, null, "meta"); } - Optional importedMeta = readMeta((ObjectNode) meta); - - if (importedMeta.isEmpty()) { - return ConfigurationTemplateImportPreview.failed(INVALID_META_ITEM); + try { + imported.put(attribute, new AttributeConfiguration(type.asText(), readMeta(meta))); + } catch (InvalidMetaItemException e) { + return failed(INVALID_META_ITEM, attribute, e.metaItem, e.parameter); } - - imported.put(entry.getKey(), new AttributeConfiguration(type.asText(), importedMeta.get())); } AttributeMap targetAttributes = @@ -183,7 +192,7 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String // Report what was skipped even when that leaves nothing to import if (importable.isEmpty()) { return new ConfigurationTemplateImportPreview( - NO_IMPORTABLE_ATTRIBUTES, importable, missing, typeMismatches, null); + NO_IMPORTABLE_ATTRIBUTES, null, importable, missing, typeMismatches, null); } AttributeMap patchedAttributes = ValueUtil.clone(targetAttributes); @@ -200,7 +209,16 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String }); return new ConfigurationTemplateImportPreview( - null, importable, missing, typeMismatches, patchedAttributes); + null, null, importable, missing, typeMismatches, patchedAttributes); + } + + private static ConfigurationTemplateImportPreview failed( + ConfigurationTemplateImportFailure failure, + String attribute, + String metaItem, + String parameter) { + return ConfigurationTemplateImportPreview.failed( + failure, new ConfigurationTemplateImportFailureLocation(attribute, metaItem, parameter)); } private static boolean isAbsent(JsonNode node) { @@ -214,32 +232,68 @@ private static MetaMap withoutAssetBoundMeta(MetaMap meta) { } /** - * Reads the metadata of a document entry without the {@link #ASSET_BOUND_META_ITEMS}, or nothing - * if an item with a known descriptor does not hold a value of its type that meets the bean - * constraints of that type. Unknown metadata items are taken as they are. + * Reads the metadata of a document entry without the {@link #ASSET_BOUND_META_ITEMS}. An item + * with a known descriptor must hold a value of its type that meets the bean constraints of that + * type; unknown metadata items are taken as they are. */ - private static Optional readMeta(ObjectNode node) { - ObjectNode items = node.deepCopy(); - items.remove(ASSET_BOUND_META_ITEMS); - MetaMap meta; + private static MetaMap readMeta(JsonNode node) throws InvalidMetaItemException { + MetaMap meta = new MetaMap(); - try { - meta = ValueUtil.JSON.treeToValue(items, MetaMap.class); - } catch (JsonProcessingException | IllegalArgumentException e) { - return Optional.empty(); + for (Map.Entry entry : node.properties()) { + String name = entry.getKey(); + + if (ASSET_BOUND_META_ITEMS.contains(name)) { + continue; + } + + // One item at a time, so that a failure names its item + MetaMap read; + try { + read = + ValueUtil.JSON.treeToValue( + ValueUtil.JSON.createObjectNode().set(name, entry.getValue()), MetaMap.class); + } catch (JsonMappingException e) { + throw new InvalidMetaItemException(name, path(e)); + } catch (JsonProcessingException | IllegalArgumentException e) { + throw new InvalidMetaItemException(name, null); + } + + for (MetaItem item : read.values()) { + Object value = item.getValue().orElse(null); + + if (item.getType() != null && value != null) { + Optional violation = + ValueUtil.validate(value).stream() + .map(constraintViolation -> constraintViolation.getPropertyPath().toString()) + .sorted() + .findFirst(); + + if (violation.isPresent()) { + throw new InvalidMetaItemException( + name, violation.get().isEmpty() ? null : violation.get()); + } + if (changesType(entry.getValue(), value)) { + throw new InvalidMetaItemException(name, "type"); + } + } + meta.addOrReplace(item); + } } + return meta; + } - for (MetaItem item : meta.values()) { - Object value = item.getValue().orElse(null); + /** The path of a binding failure within the value read, or null for the value itself. */ + private static String path(JsonMappingException e) { + StringBuilder path = new StringBuilder(); - if (item.getType() != null - && value != null - && (!ValueUtil.validate(value).isEmpty() - || changesType(items.get(item.getName()), value))) { - return Optional.empty(); + for (JsonMappingException.Reference reference : e.getPath()) { + if (reference.getFieldName() != null) { + path.append(path.isEmpty() ? "" : ".").append(reference.getFieldName()); + } else if (reference.getIndex() >= 0) { + path.append('[').append(reference.getIndex()).append(']'); } } - return Optional.of(meta); + return path.isEmpty() ? null : path.toString(); } /** @@ -259,4 +313,16 @@ private static boolean changesType(JsonNode node, Object value) { private static String typeName(Attribute attribute) { return attribute.getType() != null ? attribute.getType().getName() : null; } + + /** A metadata item that cannot be read, with the parameter within it where that is known. */ + private static final class InvalidMetaItemException extends Exception { + private final String metaItem; + private final String parameter; + + private InvalidMetaItemException(String metaItem, String parameter) { + super(null, null, false, false); + this.metaItem = metaItem; + this.parameter = parameter; + } + } } diff --git a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy index 35c1184240..1e78135e67 100644 --- a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -61,6 +61,10 @@ class ConfigurationTemplateUtilTest extends Specification { return "{${fields.join(",")}}" } + static String forecastEntry(String pastCount) { + return """{"type": "number", "meta": {"forecast": {"type": "wea", "pastPeriod": "P1D", "pastCount": ${pastCount}, "forecastPeriod": "PT1H", "forecastCount": 1}}}""" + } + def "export holds the type and metadata of attributes that have metadata"() { given: "an asset with configured and unconfigured attributes" def asset = thingAsset([ @@ -118,9 +122,45 @@ class ConfigurationTemplateUtilTest extends Specification { INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"readOnly": {"not": "a boolean"}}}']) INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"constraints": [{"type": "noSuchConstraint"}]}}']) INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"agentLink": {"type": "NoSuchAgentLink", "id": "agentId"}}}']) + INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: forecastEntry("0")]) NO_IMPORTABLE_ATTRIBUTES | document(ThingAsset.DESCRIPTOR.name, [:]) } + def "a rejected document names where it fails: #attribute, #metaItem, #parameter"() { + given: "an asset with a configured attribute" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + + when: "the document is previewed" + def location = ConfigurationTemplateUtil.preview(asset, documentText).failureLocation + + then: "the location holds the attribute, metadata item and parameter as far as they apply" + location.attribute == attribute + location.metaItem == metaItem + location.parameter == parameter + + where: + documentText | attribute | metaItem | parameter + document(ThingAsset.DESCRIPTOR.name, [:], null) | null | null | "version" + '{"version": 1, "assetType": 5, "attributes": {}}' | null | null | "assetType" + '{"version": 1, "assetType": "ThingAsset", "attributes": 5}' | null | null | "attributes" + document(ThingAsset.DESCRIPTOR.name, [temperature: '5']) | "temperature" | null | null + document(ThingAsset.DESCRIPTOR.name, [temperature: '{"meta": {}}']) | "temperature" | null | "type" + document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": 5}']) | "temperature" | null | "meta" + document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"readOnly": {"not": "a boolean"}}}']) | "temperature" | "readOnly" | null + document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"constraints": [{"type": "noSuchConstraint"}]}}']) | "temperature" | "constraints" | "[0]" + document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"agentLink": {"type": "NoSuchAgentLink", "id": "agentId"}}}']) | "temperature" | "agentLink" | "type" + document(ThingAsset.DESCRIPTOR.name, [temperature: forecastEntry('"many"')]) | "temperature" | "forecast" | "pastCount" + document(ThingAsset.DESCRIPTOR.name, [temperature: forecastEntry("0")]) | "temperature" | "forecast" | "pastCount" + } + + def "a document rejected as a whole has no location"() { + expect: "the rejection holds no location" + ConfigurationTemplateUtil.preview(thingAsset(), documentText).failureLocation == null + + where: + documentText << ["not json at all", "[]", document(ThingAsset.DESCRIPTOR.name, [:], 2)] + } + def "export leaves out metadata that grants access or links attributes"() { given: "an asset whose attributes hold access and attribute link metadata" def asset = thingAsset([ diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy index 4160a81e01..1a654de21d 100644 --- a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -189,6 +189,22 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine return true } + when: "a document holding a configuration item that breaks a constraint is imported" + adminResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"temperature": {"type": "number", "meta": {"forecast": {"type": "wea", "pastPeriod": "P1D", "pastCount": 0, "forecastPeriod": "PT1H", "forecastCount": 1}}}}}')) + + then: "the import is rejected with the reason and where it fails" + WebApplicationException invalidMetaItem = thrown() + invalidMetaItem.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + def rejected = r.readEntity(ConfigurationTemplateImportPreview.class) + assert rejected.failure == INVALID_META_ITEM + assert rejected.failureLocation.attribute == "temperature" + assert rejected.failureLocation.metaItem == MetaItemType.FORECAST.name + assert rejected.failureLocation.parameter == "pastCount" + return true + } + when: "a document holding no attribute of the target asset is imported" adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"absent": {"type": "text", "meta": {"label": "Absent"}}}}')) diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json index a3ea6c7841..8c6961c6ce 100644 --- a/ui/app/shared/locales/en/or.json +++ b/ui/app/shared/locales/en/or.json @@ -1365,6 +1365,13 @@ "INVALID_META_ITEM": "The selected file holds a configuration item whose value does not fit its type.", "NO_IMPORTABLE_ATTRIBUTES": "None of the attributes in the selected file can be imported into this asset.", "DRAFT_MISMATCH": "This asset has changed since you opened it; refresh it and try again." + }, + "failureLocation": { + "field": "On field '{{parameter}}'.", + "attribute": "On attribute '{{attribute}}'.", + "attributeField": "On field '{{parameter}}' of attribute '{{attribute}}'.", + "configurationItem": "On configuration item '{{item}}' of attribute '{{attribute}}'.", + "configurationItemParameter": "On parameter '{{parameter}}' of configuration item '{{item}}' of attribute '{{attribute}}'." } } } diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json index 82c32c92b4..d63b5a4871 100644 --- a/ui/app/shared/locales/nl/or.json +++ b/ui/app/shared/locales/nl/or.json @@ -1351,6 +1351,13 @@ "INVALID_META_ITEM": "Het geselecteerde bestand bevat een configuratie item waarvan de waarde niet bij het type past.", "NO_IMPORTABLE_ATTRIBUTES": "Geen van de attributen in het geselecteerde bestand kan in dit asset worden geïmporteerd.", "DRAFT_MISMATCH": "Dit asset is gewijzigd sinds je het opende; ververs het en probeer het opnieuw." + }, + "failureLocation": { + "field": "Bij veld '{{parameter}}'.", + "attribute": "Bij attribuut '{{attribute}}'.", + "attributeField": "Bij veld '{{parameter}}' van attribuut '{{attribute}}'.", + "configurationItem": "Bij configuratie item '{{item}}' van attribuut '{{attribute}}'.", + "configurationItemParameter": "Bij parameter '{{parameter}}' van configuratie item '{{item}}' van attribuut '{{attribute}}'." } } } diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 26032bd5d0..5a5b663f8c 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -25,6 +25,7 @@ import { WellknownMetaItems, type Asset, type Attribute, + type ConfigurationTemplateImportFailureLocation, type ConfigurationTemplateImportPreview, type ValueConstraint, type ValueFormat, @@ -546,18 +547,53 @@ function showImportFailureDialog(host: Node, asset: Asset, configuration: string const message = preview ? i18next.t(`configurationTemplate.failure.${preview.failure}`) : i18next.t(forbidden ? "configurationTemplate.forbidden" : "errorOccurred"); + const location = getFailureLocation(asset, preview?.failureLocation); showErrorDialog( host, html`${dialogStyle}

${message} + ${location ? html`${location}` : ``} ${preview ? getSkippedTemplate(asset, preview, configuration) : ``}
`, "configurationTemplate.importHeading" ); } +/** Where a rejected template fails, from the attribute down to the parameter, or nothing if that is not known. */ +function getFailureLocation( + asset: Asset, + location: ConfigurationTemplateImportFailureLocation | undefined +): string | undefined { + if (!location?.attribute && !location?.parameter) { + return undefined; + } + const values = { + attribute: location.attribute ? attributeName(asset, { name: location.attribute }) : undefined, + item: location.metaItem ? Util.getMetaLabel(undefined, location.metaItem, asset.type, false) : undefined, + parameter: location.parameter, + }; + + if (!location.attribute) { + return i18next.t("configurationTemplate.failureLocation.field", values); + } + if (!location.metaItem) { + return i18next.t( + location.parameter + ? "configurationTemplate.failureLocation.attributeField" + : "configurationTemplate.failureLocation.attribute", + values + ); + } + return i18next.t( + location.parameter + ? "configurationTemplate.failureLocation.configurationItemParameter" + : "configurationTemplate.failureLocation.configurationItem", + values + ); +} + function getHeaderTemplate(titleKey: string, onClose: () => void): TemplateResult { return html` ${dialogStyle} From 22f3bf96dc6c1e82750fc380fb376f3f3ccb194b Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 16:27:17 +0100 Subject: [PATCH 11/21] Validate imported templates as saving the asset does Name the metadata item in deserialization error paths, so the import reads metadata at once, and show where an import fails as a list of parts. --- .../ConfigurationTemplateImportFailure.java | 3 + .../openremote/model/attribute/Attribute.java | 7 +- .../openremote/model/attribute/MetaMap.java | 8 +- .../model/util/ConfigurationTemplateUtil.java | 149 ++++++++++++------ .../model/attribute/MetaMapTest.groovy | 67 ++++++++ .../util/ConfigurationTemplateUtilTest.groovy | 35 ++++ .../assets/ConfigurationTemplateTest.groovy | 14 ++ ui/app/shared/locales/en/or.json | 14 +- ui/app/shared/locales/nl/or.json | 11 +- .../src/configuration-template.ts | 43 ++--- 10 files changed, 271 insertions(+), 80 deletions(-) create mode 100644 model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java index fdccd1d8c6..eb3a7aaafe 100644 --- a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java @@ -36,6 +36,9 @@ public enum ConfigurationTemplateImportFailure { /** A metadata item does not hold a value of its type, or the value breaks its constraints. */ INVALID_META_ITEM, + /** The current value of an importable attribute does not meet the imported metadata. */ + VALUE_VIOLATES_CONSTRAINTS, + /** No attribute of the document exists on the target asset with the same type. */ NO_IMPORTABLE_ATTRIBUTES, diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.java index ceb28ef935..2ff501882d 100644 --- a/model/src/main/java/org/openremote/model/attribute/Attribute.java +++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @@ -135,7 +136,11 @@ public Attribute deserialize(JsonParser jp, DeserializationContext ctxt) thro if (metaDeserialiser == null) { metaDeserialiser = ctxt.findNonContextualValueDeserializer(META_MAP_TYPE); } - attribute.meta = (MetaMap) metaDeserialiser.deserialize(jp, ctxt); + try { + attribute.meta = (MetaMap) metaDeserialiser.deserialize(jp, ctxt); + } catch (JsonMappingException e) { + throw JsonMappingException.wrapWithPath(e, Attribute.class, "meta"); + } } case "name" -> { String name = jp.getValueAsString(); diff --git a/model/src/main/java/org/openremote/model/attribute/MetaMap.java b/model/src/main/java/org/openremote/model/attribute/MetaMap.java index e6bd34b7c6..98cd42e692 100644 --- a/model/src/main/java/org/openremote/model/attribute/MetaMap.java +++ b/model/src/main/java/org/openremote/model/attribute/MetaMap.java @@ -94,8 +94,12 @@ public static List> deserialiseMetaMap( metaItem = new MetaItem(metaItemName); } - metaItem.setValue( - Attribute.AttributeDeserializer.deserialiseValue(metaItem.getType(), jp, ctxt)); + try { + metaItem.setValue( + Attribute.AttributeDeserializer.deserialiseValue(metaItem.getType(), jp, ctxt)); + } catch (JsonMappingException e) { + throw JsonMappingException.wrapWithPath(e, MetaMap.class, metaItemName); + } list.add(metaItem); } diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index c892d3b4e3..e204566242 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -24,6 +24,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.validation.ConstraintViolation; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; @@ -33,6 +35,8 @@ import java.util.Optional; import java.util.Set; import java.util.TreeMap; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.openremote.model.asset.Asset; import org.openremote.model.asset.AttributeConfiguration; import org.openremote.model.asset.AttributeConfigurationSummary; @@ -64,6 +68,10 @@ public final class ConfigurationTemplateUtil { ACCESS_RESTRICTED_WRITE.getName(), ATTRIBUTE_LINKS.getName()); + /** A violation path on an attribute: its name, then the metadata item and the rest, if any. */ + private static final Pattern ATTRIBUTE_VIOLATION_PATH = + Pattern.compile("attributes\\[([^\\]]+)\\](?:\\.meta\\[([^\\]]+)\\])?(?:\\.(.*))?"); + private ConfigurationTemplateUtil() {} /** @@ -99,10 +107,12 @@ public static ConfigurationTemplate export(Asset asset, Collection at * changing the draft. The returned {@link * ConfigurationTemplateImportPreview#getPatchedAttributes()} holds the draft attributes with the * metadata of every importable attribute replaced, except for {@link #ASSET_BOUND_META_ITEMS}, - * which keep the values of the draft. + * which keep the values of the draft. A document that the patched draft would fail validation on + * when saved is rejected too. * - *

The document is read as a JSON tree, as binding it cannot tell a malformed entry from an - * invalid metadata item. + *

The document is read as a JSON tree, so that its fields are checked as written: binding + * reads a version of 1.5 as 1, and an agent link of a type that is not installed as a default + * agent link. */ public static ConfigurationTemplateImportPreview preview(Asset draft, String document) { JsonNode root; @@ -195,10 +205,10 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String NO_IMPORTABLE_ATTRIBUTES, null, importable, missing, typeMismatches, null); } - AttributeMap patchedAttributes = ValueUtil.clone(targetAttributes); + Asset patchedDraft = ValueUtil.clone(draft); importable.forEach( summary -> { - Attribute patched = patchedAttributes.get(summary.getName()).orElseThrow(); + Attribute patched = patchedDraft.getAttributes().get(summary.getName()).orElseThrow(); MetaMap meta = imported.get(summary.getName()).getMeta(); if (patched.getMeta() != null) { @@ -208,8 +218,48 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String patched.setMeta(meta); }); - return new ConfigurationTemplateImportPreview( - null, null, importable, missing, typeMismatches, patchedAttributes); + Set importableNames = + importable.stream().map(AttributeConfigurationSummary::getName).collect(Collectors.toSet()); + Optional rejected = + rejectedOnSave(draft, patchedDraft, importableNames); + + return rejected.orElseGet( + () -> + new ConfigurationTemplateImportPreview( + null, null, importable, missing, typeMismatches, patchedDraft.getAttributes())); + } + + /** + * The rejection for a violation that patching adds to an importable attribute, as saving the + * patched draft would fail on it. Violations the draft already has are not the document's. + */ + private static Optional rejectedOnSave( + Asset draft, Asset patchedDraft, Set importableNames) { + Set existing = + ValueUtil.validate(draft).stream() + .map(ConfigurationTemplateUtil::describe) + .collect(Collectors.toSet()); + + return ValueUtil.validate(patchedDraft).stream() + .filter(violation -> !existing.contains(describe(violation))) + .map(violation -> violation.getPropertyPath().toString()) + .sorted() + .map(ATTRIBUTE_VIOLATION_PATH::matcher) + .filter(matcher -> matcher.matches() && importableNames.contains(matcher.group(1))) + .findFirst() + .map( + matcher -> + matcher.group(2) != null + ? failed( + INVALID_META_ITEM, + matcher.group(1), + matcher.group(2), + valueParameter(matcher.group(3))) + : failed(VALUE_VIOLATES_CONSTRAINTS, matcher.group(1), null, null)); + } + + private static String describe(ConstraintViolation violation) { + return violation.getPropertyPath() + " " + violation.getMessageTemplate(); } private static ConfigurationTemplateImportPreview failed( @@ -232,61 +282,68 @@ private static MetaMap withoutAssetBoundMeta(MetaMap meta) { } /** - * Reads the metadata of a document entry without the {@link #ASSET_BOUND_META_ITEMS}. An item - * with a known descriptor must hold a value of its type that meets the bean constraints of that - * type; unknown metadata items are taken as they are. + * Reads the metadata of a document entry without the {@link #ASSET_BOUND_META_ITEMS}. Each item + * must pass bean validation as it does when an asset is saved, so an item with a known descriptor + * must hold a value of its type that meets the constraints of that type. */ private static MetaMap readMeta(JsonNode node) throws InvalidMetaItemException { - MetaMap meta = new MetaMap(); + ObjectNode items = node.deepCopy(); + items.remove(ASSET_BOUND_META_ITEMS); + MetaMap meta; - for (Map.Entry entry : node.properties()) { - String name = entry.getKey(); + try { + meta = ValueUtil.JSON.treeToValue(items, MetaMap.class); + } catch (JsonMappingException e) { + // The path starts at the item, the rest lies within its value + List path = e.getPath(); + throw new InvalidMetaItemException( + path.isEmpty() ? null : path.get(0).getFieldName(), + path.isEmpty() ? null : path(path.subList(1, path.size()))); + } catch (JsonProcessingException | IllegalArgumentException e) { + throw new InvalidMetaItemException(null, null); + } - if (ASSET_BOUND_META_ITEMS.contains(name)) { - continue; - } + for (MetaItem item : meta.values()) { + Optional violation = + ValueUtil.validate(item).stream() + .map(constraintViolation -> constraintViolation.getPropertyPath().toString()) + .sorted() + .findFirst(); - // One item at a time, so that a failure names its item - MetaMap read; - try { - read = - ValueUtil.JSON.treeToValue( - ValueUtil.JSON.createObjectNode().set(name, entry.getValue()), MetaMap.class); - } catch (JsonMappingException e) { - throw new InvalidMetaItemException(name, path(e)); - } catch (JsonProcessingException | IllegalArgumentException e) { - throw new InvalidMetaItemException(name, null); + if (violation.isPresent()) { + throw new InvalidMetaItemException(item.getName(), valueParameter(violation.get())); } - for (MetaItem item : read.values()) { - Object value = item.getValue().orElse(null); - - if (item.getType() != null && value != null) { - Optional violation = - ValueUtil.validate(value).stream() - .map(constraintViolation -> constraintViolation.getPropertyPath().toString()) - .sorted() - .findFirst(); + Object value = item.getValue().orElse(null); - if (violation.isPresent()) { - throw new InvalidMetaItemException( - name, violation.get().isEmpty() ? null : violation.get()); - } - if (changesType(entry.getValue(), value)) { - throw new InvalidMetaItemException(name, "type"); - } - } - meta.addOrReplace(item); + if (item.getType() != null + && value != null + && changesType(items.get(item.getName()), value)) { + throw new InvalidMetaItemException(item.getName(), "type"); } } return meta; } + /** + * The parameter that the violation path of a metadata item names within its value, e.g. pastCount + * for value.pastCount; null when the path names the item or its value as a whole. + */ + private static String valueParameter(String path) { + if (path != null && path.startsWith("value.")) { + return path.substring("value.".length()); + } + if (path != null && path.startsWith("value[")) { + return path.substring("value".length()); + } + return null; + } + /** The path of a binding failure within the value read, or null for the value itself. */ - private static String path(JsonMappingException e) { + private static String path(List references) { StringBuilder path = new StringBuilder(); - for (JsonMappingException.Reference reference : e.getPath()) { + for (JsonMappingException.Reference reference : references) { if (reference.getFieldName() != null) { path.append(path.isEmpty() ? "" : ".").append(reference.getFieldName()); } else if (reference.getIndex() >= 0) { diff --git a/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy b/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy new file mode 100644 index 0000000000..28fe274a73 --- /dev/null +++ b/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy @@ -0,0 +1,67 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.model.attribute + +import com.fasterxml.jackson.core.JsonParseException +import com.fasterxml.jackson.databind.JsonMappingException +import org.openremote.model.asset.Asset +import org.openremote.model.util.ValueUtil +import spock.lang.Specification + +class MetaMapTest extends Specification { + + def setupSpec() { + ValueUtil.initialise(null) + } + + static String path(JsonMappingException e) { + return e.path.collect { it.fieldName != null ? ".${it.fieldName}" : "[${it.index}]" }.join("").replaceFirst(/^\./, "") + } + + def "a metadata value that cannot be read names its item in the error path: #expectedPath"() { + when: "metadata holding a value that does not fit its item is read" + ValueUtil.JSON.readValue(json, MetaMap) + + then: "the error path starts at the item" + JsonMappingException e = thrown() + path(e) == expectedPath + + where: + json | expectedPath + '{"label": "L", "readOnly": {"not": "a boolean"}}' | "readOnly" + '{"label": "L", "constraints": [{"type": "noSuchConstraint"}]}' | "constraints[0]" + } + + def "an asset holding a metadata value that cannot be read names the attribute, meta and item in the error path"() { + when: "the asset is read" + ValueUtil.JSON.readValue('{"name": "Thing", "type": "ThingAsset", "attributes": {"temperature": {"name": "temperature", "type": "number", "meta": {"label": "T", "readOnly": "not a boolean"}}}}', Asset) + + then: "the error path leads to the item" + JsonMappingException e = thrown() + path(e) == "attributes.temperature.meta.readOnly" + } + + def "a syntax error within metadata is reported as it is"() { + when: "metadata that is not valid JSON is read" + ValueUtil.JSON.readValue('{"label": }', MetaMap) + + then: "the parse error is not wrapped" + thrown(JsonParseException) + } +} diff --git a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy index 1e78135e67..36251a8886 100644 --- a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -24,6 +24,7 @@ import org.openremote.model.asset.impl.ThingAsset import org.openremote.model.attribute.Attribute import org.openremote.model.attribute.MetaItem import org.openremote.model.value.MetaItemType +import org.openremote.model.value.ValueConstraint import org.openremote.model.value.ValueDescriptor import org.openremote.model.value.ValueType import spock.lang.Specification @@ -123,9 +124,42 @@ class ConfigurationTemplateUtilTest extends Specification { INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"constraints": [{"type": "noSuchConstraint"}]}}']) INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"agentLink": {"type": "NoSuchAgentLink", "id": "agentId"}}}']) INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: forecastEntry("0")]) + INVALID_META_ITEM | document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"my-item": 1}}']) NO_IMPORTABLE_ATTRIBUTES | document(ThingAsset.DESCRIPTOR.name, [:]) } + def "a document whose constraints the current value breaks is rejected"() { + given: "an asset whose attribute holds a value" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + asset.getAttributes().get("temperature").get().setValue(21.5d) + + when: "a document holding a minimum above that value is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"constraints": [{"type": "min", "min": 30}]}}' + ])) + + then: "the import is rejected for that attribute, as saving the asset would fail" + preview.failure == VALUE_VIOLATES_CONSTRAINTS + preview.failureLocation.attribute == "temperature" + preview.failureLocation.metaItem == null + preview.patchedAttributes == null + } + + def "a value that already breaks its constraints does not reject an import that keeps them"() { + given: "an asset whose attribute value already breaks its minimum" + def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.CONSTRAINTS.name): [new ValueConstraint.Min(30)] as ValueConstraint[]])]) + asset.getAttributes().get("temperature").get().setValue(21.5d) + + when: "a document holding the same minimum and a label is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ + temperature: '{"type": "number", "meta": {"label": "Imported", "constraints": [{"type": "min", "min": 30}]}}' + ])) + + then: "the import is not rejected, as the violation is not the document's" + preview.failure == null + preview.importableAttributes*.name == ["temperature"] + } + def "a rejected document names where it fails: #attribute, #metaItem, #parameter"() { given: "an asset with a configured attribute" def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) @@ -151,6 +185,7 @@ class ConfigurationTemplateUtilTest extends Specification { document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"agentLink": {"type": "NoSuchAgentLink", "id": "agentId"}}}']) | "temperature" | "agentLink" | "type" document(ThingAsset.DESCRIPTOR.name, [temperature: forecastEntry('"many"')]) | "temperature" | "forecast" | "pastCount" document(ThingAsset.DESCRIPTOR.name, [temperature: forecastEntry("0")]) | "temperature" | "forecast" | "pastCount" + document(ThingAsset.DESCRIPTOR.name, [temperature: '{"type": "number", "meta": {"my-item": 1}}']) | "temperature" | "my-item" | null } def "a document rejected as a whole has no location"() { diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy index 1a654de21d..822aec7b7b 100644 --- a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -205,6 +205,20 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine return true } + when: "a document holding a minimum above the current value of the target attribute is imported" + adminResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"temperature": {"type": "number", "meta": {"constraints": [{"type": "min", "min": 30}]}}}}')) + + then: "the import is rejected, as saving the asset would fail" + WebApplicationException valueViolatesConstraints = thrown() + valueViolatesConstraints.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + def rejected = r.readEntity(ConfigurationTemplateImportPreview.class) + assert rejected.failure == VALUE_VIOLATES_CONSTRAINTS + assert rejected.failureLocation.attribute == "temperature" + return true + } + when: "a document holding no attribute of the target asset is imported" adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"absent": {"type": "text", "meta": {"label": "Absent"}}}}')) diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json index 8c6961c6ce..e2a7c08cf5 100644 --- a/ui/app/shared/locales/en/or.json +++ b/ui/app/shared/locales/en/or.json @@ -1363,15 +1363,19 @@ "MISSING_REQUIRED_FIELD": "The selected file is missing a required field.", "MALFORMED_ATTRIBUTE_ENTRY": "The selected file holds a malformed attribute entry.", "INVALID_META_ITEM": "The selected file holds a configuration item whose value does not fit its type.", + "VALUE_VIOLATES_CONSTRAINTS": "The current value of an attribute does not meet the constraints in the selected file.", "NO_IMPORTABLE_ATTRIBUTES": "None of the attributes in the selected file can be imported into this asset.", "DRAFT_MISMATCH": "This asset has changed since you opened it; refresh it and try again." }, "failureLocation": { - "field": "On field '{{parameter}}'.", - "attribute": "On attribute '{{attribute}}'.", - "attributeField": "On field '{{parameter}}' of attribute '{{attribute}}'.", - "configurationItem": "On configuration item '{{item}}' of attribute '{{attribute}}'.", - "configurationItemParameter": "On parameter '{{parameter}}' of configuration item '{{item}}' of attribute '{{attribute}}'." + "attribute": "attribute '{{name}}'", + "configurationItem": "configuration item '{{name}}'", + "field": "field '{{name}}'", + "parameter": "parameter '{{name}}'", + "entry_ordinal_one": "{{count}}st entry", + "entry_ordinal_two": "{{count}}nd entry", + "entry_ordinal_few": "{{count}}rd entry", + "entry_ordinal_other": "{{count}}th entry" } } } diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json index d63b5a4871..d15adac0d9 100644 --- a/ui/app/shared/locales/nl/or.json +++ b/ui/app/shared/locales/nl/or.json @@ -1349,15 +1349,16 @@ "MISSING_REQUIRED_FIELD": "In het geselecteerde bestand ontbreekt een verplicht veld.", "MALFORMED_ATTRIBUTE_ENTRY": "Het geselecteerde bestand bevat een ongeldige attribuutvermelding.", "INVALID_META_ITEM": "Het geselecteerde bestand bevat een configuratie item waarvan de waarde niet bij het type past.", + "VALUE_VIOLATES_CONSTRAINTS": "De huidige waarde van een attribuut voldoet niet aan de beperkingen in het geselecteerde bestand.", "NO_IMPORTABLE_ATTRIBUTES": "Geen van de attributen in het geselecteerde bestand kan in dit asset worden geïmporteerd.", "DRAFT_MISMATCH": "Dit asset is gewijzigd sinds je het opende; ververs het en probeer het opnieuw." }, "failureLocation": { - "field": "Bij veld '{{parameter}}'.", - "attribute": "Bij attribuut '{{attribute}}'.", - "attributeField": "Bij veld '{{parameter}}' van attribuut '{{attribute}}'.", - "configurationItem": "Bij configuratie item '{{item}}' van attribuut '{{attribute}}'.", - "configurationItemParameter": "Bij parameter '{{parameter}}' van configuratie item '{{item}}' van attribuut '{{attribute}}'." + "attribute": "attribuut '{{name}}'", + "configurationItem": "configuratie item '{{name}}'", + "field": "veld '{{name}}'", + "parameter": "parameter '{{name}}'", + "entry_ordinal_other": "{{count}}e element" } } } diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 5a5b663f8c..d612e8a43e 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -561,7 +561,10 @@ function showImportFailureDialog(host: Node, asset: Asset, configuration: string ); } -/** Where a rejected template fails, from the attribute down to the parameter, or nothing if that is not known. */ +/** + * Where a rejected template fails, as its parts from the attribute down to the parameter, with list positions counted + * from one, or nothing if that is not known. + */ function getFailureLocation( asset: Asset, location: ConfigurationTemplateImportFailureLocation | undefined @@ -569,29 +572,27 @@ function getFailureLocation( if (!location?.attribute && !location?.parameter) { return undefined; } - const values = { - attribute: location.attribute ? attributeName(asset, { name: location.attribute }) : undefined, - item: location.metaItem ? Util.getMetaLabel(undefined, location.metaItem, asset.type, false) : undefined, - parameter: location.parameter, - }; + const parts: string[] = []; - if (!location.attribute) { - return i18next.t("configurationTemplate.failureLocation.field", values); + if (location.attribute) { + const name = attributeName(asset, { name: location.attribute }); + parts.push(i18next.t("configurationTemplate.failureLocation.attribute", { name })); } - if (!location.metaItem) { - return i18next.t( - location.parameter - ? "configurationTemplate.failureLocation.attributeField" - : "configurationTemplate.failureLocation.attribute", - values - ); + if (location.metaItem) { + const name = Util.getMetaLabel(undefined, location.metaItem, asset.type, false); + parts.push(i18next.t("configurationTemplate.failureLocation.configurationItem", { name })); } - return i18next.t( - location.parameter - ? "configurationTemplate.failureLocation.configurationItemParameter" - : "configurationTemplate.failureLocation.configurationItem", - values - ); + // A parameter path holds names and list positions, e.g. valueFilters[1].path + for (const [, name, index] of (location.parameter ?? "").matchAll(/([^.[\]]+)|\[(\d+)]/g)) { + if (index !== undefined) { + parts.push(i18next.t("configurationTemplate.failureLocation.entry", { count: Number(index) + 1, ordinal: true })); + } else if (location.metaItem) { + parts.push(i18next.t("configurationTemplate.failureLocation.parameter", { name })); + } else { + parts.push(i18next.t("configurationTemplate.failureLocation.field", { name })); + } + } + return `${Util.capitaliseFirstLetter(parts.join(", "))}.`; } function getHeaderTemplate(titleKey: string, onClose: () => void): TemplateResult { From ed33802ad785cfa9bc205f75ca2e9b9d6a3077c0 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Fri, 13 Nov 2026 16:32:12 +0100 Subject: [PATCH 12/21] Fix spotless issue --- .../groovy/org/openremote/model/attribute/MetaMapTest.groovy | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy b/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy index 28fe274a73..6e4a681f43 100644 --- a/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy +++ b/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy @@ -31,7 +31,9 @@ class MetaMapTest extends Specification { } static String path(JsonMappingException e) { - return e.path.collect { it.fieldName != null ? ".${it.fieldName}" : "[${it.index}]" }.join("").replaceFirst(/^\./, "") + return e.path.collect { + it.fieldName != null ? ".${it.fieldName}" : "[${it.index}]" + }.join("").replaceFirst(/^\./, "") } def "a metadata value that cannot be read names its item in the error path: #expectedPath"() { From f9c2e69f2f50eeb11228281e51c2967235d3a8d8 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Mon, 16 Nov 2026 14:24:18 +0100 Subject: [PATCH 13/21] Change AttributeConfiguration classes into records --- .../model/asset/AttributeConfiguration.java | 23 +++--------- .../asset/AttributeConfigurationSummary.java | 26 ++------------ .../AttributeConfigurationTypeMismatch.java | 36 +++---------------- .../model/util/ConfigurationTemplateUtil.java | 14 ++++---- 4 files changed, 20 insertions(+), 79 deletions(-) diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java index 0a9a57c5a0..215de70ed0 100644 --- a/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java @@ -18,7 +18,6 @@ */ package org.openremote.model.asset; -import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.v3.oas.annotations.media.Schema; import org.openremote.model.attribute.MetaMap; import org.openremote.model.value.MetaHolder; @@ -30,23 +29,11 @@ @Schema( description = "Configuration of a single attribute; the attribute name is the key within the document.") -public class AttributeConfiguration implements MetaHolder { - - @Schema(description = "Value descriptor name of the attribute, e.g. number.") - protected String type; - - @Schema(description = "Metadata keyed by meta-item name, exactly as stored on the attribute.") - protected MetaMap meta; - - @JsonCreator - public AttributeConfiguration(String type, MetaMap meta) { - this.type = type; - this.meta = meta; - } - - public String getType() { - return type; - } +public record AttributeConfiguration( + @Schema(description = "Value descriptor name of the attribute, e.g. number.") String type, + @Schema(description = "Metadata keyed by meta-item name, exactly as stored on the attribute.") + MetaMap meta) + implements MetaHolder { @Override public MetaMap getMeta() { diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java index 75fc6ee114..00b59a076a 100644 --- a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java @@ -18,30 +18,10 @@ */ package org.openremote.model.asset; -import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.v3.oas.annotations.media.Schema; /** An attribute of a {@link ConfigurationTemplate} as reported to the user. */ @Schema(description = "Name and type of an attribute within an imported document.") -public class AttributeConfigurationSummary { - - @Schema(description = "Attribute name.") - protected String name; - - @Schema(description = "Value descriptor name of the attribute, e.g. number.") - protected String type; - - @JsonCreator - public AttributeConfigurationSummary(String name, String type) { - this.name = name; - this.type = type; - } - - public String getName() { - return name; - } - - public String getType() { - return type; - } -} +public record AttributeConfigurationSummary( + @Schema(description = "Attribute name.") String name, + @Schema(description = "Value descriptor name of the attribute, e.g. number.") String type) {} diff --git a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java index 664539e79d..51056c2dc1 100644 --- a/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java @@ -18,40 +18,14 @@ */ package org.openremote.model.asset; -import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.v3.oas.annotations.media.Schema; /** * An attribute that cannot be imported because the target attribute holds a different value type. */ @Schema(description = "Attribute skipped on import because the target type differs.") -public class AttributeConfigurationTypeMismatch { - - @Schema(description = "Attribute name.") - protected String name; - - @Schema(description = "Value descriptor name within the imported document.") - protected String importedType; - - @Schema(description = "Value descriptor name of the target attribute.") - protected String targetType; - - @JsonCreator - public AttributeConfigurationTypeMismatch(String name, String importedType, String targetType) { - this.name = name; - this.importedType = importedType; - this.targetType = targetType; - } - - public String getName() { - return name; - } - - public String getImportedType() { - return importedType; - } - - public String getTargetType() { - return targetType; - } -} +public record AttributeConfigurationTypeMismatch( + @Schema(description = "Attribute name.") String name, + @Schema(description = "Value descriptor name within the imported document.") + String importedType, + @Schema(description = "Value descriptor name of the target attribute.") String targetType) {} diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index e204566242..15bbd43dde 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -184,19 +184,19 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String Optional> target = targetAttributes.get(name); if (target.isEmpty()) { - missing.add(new AttributeConfigurationSummary(name, configuration.getType())); + missing.add(new AttributeConfigurationSummary(name, configuration.type())); return; } String targetType = typeName(target.get()); - if (!Objects.equals(configuration.getType(), targetType)) { + if (!Objects.equals(configuration.type(), targetType)) { typeMismatches.add( - new AttributeConfigurationTypeMismatch(name, configuration.getType(), targetType)); + new AttributeConfigurationTypeMismatch(name, configuration.type(), targetType)); return; } - importable.add(new AttributeConfigurationSummary(name, configuration.getType())); + importable.add(new AttributeConfigurationSummary(name, configuration.type())); }); // Report what was skipped even when that leaves nothing to import @@ -208,8 +208,8 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String Asset patchedDraft = ValueUtil.clone(draft); importable.forEach( summary -> { - Attribute patched = patchedDraft.getAttributes().get(summary.getName()).orElseThrow(); - MetaMap meta = imported.get(summary.getName()).getMeta(); + Attribute patched = patchedDraft.getAttributes().get(summary.name()).orElseThrow(); + MetaMap meta = imported.get(summary.name()).getMeta(); if (patched.getMeta() != null) { ASSET_BOUND_META_ITEMS.forEach( @@ -219,7 +219,7 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String }); Set importableNames = - importable.stream().map(AttributeConfigurationSummary::getName).collect(Collectors.toSet()); + importable.stream().map(AttributeConfigurationSummary::name).collect(Collectors.toSet()); Optional rejected = rejectedOnSave(draft, patchedDraft, importableNames); From 0bd0e094b8038fa023b9055e768da6c23092bd63 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Mon, 16 Nov 2026 15:28:36 +0100 Subject: [PATCH 14/21] Disable configuration template import on unsaved assets --- .../test/configuration-template.test.ts | 37 +++++++++++++++++++ ui/app/shared/locales/en/or.json | 1 + ui/app/shared/locales/nl/or.json | 1 + .../src/or-edit-asset-panel.ts | 9 ++++- 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 ui/app/manager/test/configuration-template.test.ts diff --git a/ui/app/manager/test/configuration-template.test.ts b/ui/app/manager/test/configuration-template.test.ts new file mode 100644 index 0000000000..3c21e4f07c --- /dev/null +++ b/ui/app/manager/test/configuration-template.test.ts @@ -0,0 +1,37 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import { expect } from "@openremote/test"; +import { test, userStatePath } from "./fixtures/manager.js"; + +test.use({ storageState: userStatePath }); + +/** + * @given Logged in to the "smartcity" realm in modify mode + * @when Adding an asset without saving it + * @then Import is disabled until the asset is saved + */ +test("should disable import on an asset that is not saved yet", async ({ page, manager, assetsPage }) => { + await page.goto(`${manager.getAppUrl("smartcity")}#/assets/true`); + await assetsPage.addAsset("Weather Asset", "Unsaved weather"); + + const importButton = page.getByRole("button", { name: "Import", exact: true }); + // Import used to be enabled here and fail with a generic error, as an import is checked against the stored asset + await expect(importButton).toBeDisabled(); + await expect(importButton).toHaveAttribute("title", "Save the asset before importing"); +}); diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json index e2a7c08cf5..a667d71065 100644 --- a/ui/app/shared/locales/en/or.json +++ b/ui/app/shared/locales/en/or.json @@ -1347,6 +1347,7 @@ "selectAll": "Select all", "nothingToExport": "None of the attributes of this asset have configuration items to export", "saveBeforeExport": "Save or revert your changes before exporting", + "saveBeforeImport": "Save the asset before importing", "importHeading": "Import configuration template", "selectFileDescription": "Select a JSON file to import attribute configuration data", "noFileSelected": "no file selected", diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json index d15adac0d9..0c40efbfc3 100644 --- a/ui/app/shared/locales/nl/or.json +++ b/ui/app/shared/locales/nl/or.json @@ -1333,6 +1333,7 @@ "selectAll": "Alles selecteren", "nothingToExport": "Geen van de attributen van dit asset heeft configuratie items om te exporteren", "saveBeforeExport": "Sla je wijzigingen op of maak ze ongedaan voordat je exporteert", + "saveBeforeImport": "Sla het asset op voordat je importeert", "importHeading": "Configuratie template importeren", "selectFileDescription": "Selecteer een JSON-bestand om attribuutconfiguratie te importeren", "noFileSelected": "geen bestand geselecteerd", 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.ts index fcee588e22..694ac7d13f 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 @@ -501,8 +501,15 @@ export class OrEditAssetPanel extends OrElement { return undefined; } + // An import is checked against the stored asset, which a new asset does not have yet + const saved = !!this.asset.id; + return html` - this._importConfiguration()}> + this._importConfiguration()} + > From 390cd4bdd7d5ebd3d223333f008e2e60cc3590f3 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Mon, 16 Nov 2026 16:23:32 +0100 Subject: [PATCH 15/21] Leave custom attributes out of configuration templates --- .../ConfigurationTemplateImportPreview.java | 13 +- .../model/util/ConfigurationTemplateUtil.java | 37 +++++- .../util/ConfigurationTemplateUtilTest.groovy | 103 ++++++++++++---- .../ManagerConfigTemplateSetup.java | 76 ++++++------ .../configtemplate/model/AgentLinksAsset.java | 70 +++++++++++ .../configtemplate/model/MixerAsset.java | 51 ++++++++ .../setup/configtemplate/model/PumpAsset.java | 5 + .../assets/ConfigurationTemplateTest.groovy | 112 +++++++++++------- .../src/configuration-template.ts | 7 +- 9 files changed, 363 insertions(+), 111 deletions(-) create mode 100644 setup/src/config-template/java/org/openremote/setup/configtemplate/model/AgentLinksAsset.java create mode 100644 setup/src/config-template/java/org/openremote/setup/configtemplate/model/MixerAsset.java diff --git a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java index 4df2fdd8a9..5493ed887d 100644 --- a/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java @@ -49,6 +49,11 @@ public class ConfigurationTemplateImportPreview { @Schema(description = "Attributes skipped because the target attribute has a different type.") protected List typeMismatches; + @Schema( + description = + "Attributes skipped because they were added to the target asset rather than defined by its asset type.") + protected List customAttributes; + @Schema( description = "The submitted draft attributes with the metadata of every importable attribute replaced, keyed by attribute name.") @@ -61,12 +66,14 @@ public ConfigurationTemplateImportPreview( List importableAttributes, List missingAttributes, List typeMismatches, + List customAttributes, AttributeMap patchedAttributes) { this.failure = failure; this.failureLocation = failureLocation; this.importableAttributes = importableAttributes; this.missingAttributes = missingAttributes; this.typeMismatches = typeMismatches; + this.customAttributes = customAttributes; this.patchedAttributes = patchedAttributes; } @@ -79,7 +86,7 @@ public static ConfigurationTemplateImportPreview failed( ConfigurationTemplateImportFailure failure, ConfigurationTemplateImportFailureLocation failureLocation) { return new ConfigurationTemplateImportPreview( - failure, failureLocation, List.of(), List.of(), List.of(), null); + failure, failureLocation, List.of(), List.of(), List.of(), List.of(), null); } public ConfigurationTemplateImportFailure getFailure() { @@ -102,6 +109,10 @@ public List getTypeMismatches() { return typeMismatches; } + public List getCustomAttributes() { + return customAttributes; + } + public AttributeMap getPatchedAttributes() { return patchedAttributes; } diff --git a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java index 15bbd43dde..79cd80b15e 100644 --- a/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -76,16 +76,19 @@ private ConfigurationTemplateUtil() {} /** * Builds the export document of an asset, holding the type and metadata of every attribute that - * has metadata other than {@link #ASSET_BOUND_META_ITEMS}. A null or empty selection exports all - * of them. + * its asset type defines and that has metadata other than {@link #ASSET_BOUND_META_ITEMS}. + * Attributes added to the asset alone are left out, so a configuration to reuse belongs in an + * asset type. A null or empty selection exports all of them. */ public static ConfigurationTemplate export(Asset asset, Collection attributeNames) { boolean selectAll = attributeNames == null || attributeNames.isEmpty(); + Set definedNames = definedAttributeNames(asset.getType()); // Sorted by name, as the attributes of an asset have no order of their own Map attributes = new TreeMap<>(); if (asset.getAttributes() != null) { asset.getAttributes().values().stream() + .filter(attribute -> definedNames.contains(attribute.getName())) .filter(attribute -> selectAll || attributeNames.contains(attribute.getName())) .forEach( attribute -> { @@ -107,8 +110,9 @@ public static ConfigurationTemplate export(Asset asset, Collection at * changing the draft. The returned {@link * ConfigurationTemplateImportPreview#getPatchedAttributes()} holds the draft attributes with the * metadata of every importable attribute replaced, except for {@link #ASSET_BOUND_META_ITEMS}, - * which keep the values of the draft. A document that the patched draft would fail validation on - * when saved is rejected too. + * which keep the values of the draft. Attributes added to the draft alone, rather than defined by + * its asset type, are skipped as export leaves them out. A document that the patched draft would + * fail validation on when saved is rejected too. * *

The document is read as a JSON tree, so that its fields are checked as written: binding * reads a version of 1.5 as 1, and an agent link of a type that is not installed as a default @@ -178,6 +182,8 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String List importable = new ArrayList<>(); List missing = new ArrayList<>(); List typeMismatches = new ArrayList<>(); + List custom = new ArrayList<>(); + Set definedNames = definedAttributeNames(draft.getType()); imported.forEach( (name, configuration) -> { @@ -188,6 +194,12 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String return; } + // An attribute added to the asset alone takes no configuration, as export leaves it out + if (!definedNames.contains(name)) { + custom.add(new AttributeConfigurationSummary(name, configuration.type())); + return; + } + String targetType = typeName(target.get()); if (!Objects.equals(configuration.type(), targetType)) { @@ -202,7 +214,7 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String // Report what was skipped even when that leaves nothing to import if (importable.isEmpty()) { return new ConfigurationTemplateImportPreview( - NO_IMPORTABLE_ATTRIBUTES, null, importable, missing, typeMismatches, null); + NO_IMPORTABLE_ATTRIBUTES, null, importable, missing, typeMismatches, custom, null); } Asset patchedDraft = ValueUtil.clone(draft); @@ -226,7 +238,13 @@ public static ConfigurationTemplateImportPreview preview(Asset draft, String return rejected.orElseGet( () -> new ConfigurationTemplateImportPreview( - null, null, importable, missing, typeMismatches, patchedDraft.getAttributes())); + null, + null, + importable, + missing, + typeMismatches, + custom, + patchedDraft.getAttributes())); } /** @@ -281,6 +299,13 @@ private static MetaMap withoutAssetBoundMeta(MetaMap meta) { return result; } + /** The names of the attributes an asset type defines, none for a type that is not installed. */ + private static Set definedAttributeNames(String assetType) { + return ValueUtil.getAssetInfo(assetType) + .map(info -> info.getAttributeDescriptors().keySet()) + .orElse(Set.of()); + } + /** * Reads the metadata of a document entry without the {@link #ASSET_BOUND_META_ITEMS}. Each item * must pass bean validation as it does when an asset is saved, so an item with a known descriptor diff --git a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy index 36251a8886..cdc08dc272 100644 --- a/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -21,6 +21,7 @@ package org.openremote.model.util import org.openremote.model.asset.ConfigurationTemplate import org.openremote.model.asset.impl.RoomAsset import org.openremote.model.asset.impl.ThingAsset +import org.openremote.model.asset.impl.WeatherAsset import org.openremote.model.attribute.Attribute import org.openremote.model.attribute.MetaItem import org.openremote.model.value.MetaItemType @@ -37,8 +38,10 @@ class ConfigurationTemplateUtilTest extends Specification { ValueUtil.initialise(null) } - static def thingAsset(Map> attributes = [:]) { - def asset = new ThingAsset("Test Thing") + /** A weather asset holding only the given attributes, so a test sees no attributes it did not add. */ + static def weatherAsset(Map> attributes = [:]) { + def asset = new WeatherAsset("Test Weather") + asset.getAttributes().clear() attributes.each { name, attribute -> asset.getAttributes().put(name, attribute) } return asset } @@ -68,9 +71,9 @@ class ConfigurationTemplateUtilTest extends Specification { def "export holds the type and metadata of attributes that have metadata"() { given: "an asset with configured and unconfigured attributes" - def asset = thingAsset([ + def asset = weatherAsset([ temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", unknownMetaItem: [nested: 1]]), - plain : attribute("plain", ValueType.TEXT) + rainfall : attribute("rainfall", ValueType.POSITIVE_NUMBER) ]) when: "the configuration is exported" @@ -78,7 +81,7 @@ class ConfigurationTemplateUtilTest extends Specification { then: "the document is of the supported version and holds the asset type" exported.version == ConfigurationTemplate.CURRENT_VERSION - exported.assetType == ThingAsset.DESCRIPTOR.name + exported.assetType == WeatherAsset.DESCRIPTOR.name and: "only the attribute with metadata is held, with its type and its metadata as stored" exported.attributes.keySet() == ["temperature"] as Set @@ -89,18 +92,30 @@ class ConfigurationTemplateUtilTest extends Specification { def "export limited to a selection holds only the selected attributes"() { given: "an asset with two configured attributes" - def asset = thingAsset([ + def asset = weatherAsset([ temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"]), - humidity : attribute("humidity", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Humidity"]) + humidity : attribute("humidity", ValueType.POSITIVE_INTEGER, [(MetaItemType.LABEL.name): "Humidity"]) ]) expect: "the selection is exported" ConfigurationTemplateUtil.export(asset, ["humidity"]).attributes.keySet() == ["humidity"] as Set } + def "export leaves out attributes that the asset type does not define"() { + given: "an asset with a configured attribute of its type and a configured attribute of its own" + def asset = weatherAsset([ + temperature : attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"]), + serialNumber: attribute("serialNumber", ValueType.TEXT, [(MetaItemType.LABEL.name): "Serial number"]) + ]) + + expect: "only the attribute of the asset type is exported, also when the other one is selected" + ConfigurationTemplateUtil.export(asset, null).attributes.keySet() == ["temperature"] as Set + ConfigurationTemplateUtil.export(asset, ["serialNumber"]).attributes.isEmpty() + } + def "a document that cannot be read is rejected with #failure"() { given: "an asset with a configured attribute" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) expect: "the import is rejected" ConfigurationTemplateUtil.preview(asset, documentText).failure == failure @@ -130,7 +145,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "a document whose constraints the current value breaks is rejected"() { given: "an asset whose attribute holds a value" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) asset.getAttributes().get("temperature").get().setValue(21.5d) when: "a document holding a minimum above that value is previewed" @@ -147,7 +162,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "a value that already breaks its constraints does not reject an import that keeps them"() { given: "an asset whose attribute value already breaks its minimum" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.CONSTRAINTS.name): [new ValueConstraint.Min(30)] as ValueConstraint[]])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.CONSTRAINTS.name): [new ValueConstraint.Min(30)] as ValueConstraint[]])]) asset.getAttributes().get("temperature").get().setValue(21.5d) when: "a document holding the same minimum and a label is previewed" @@ -162,7 +177,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "a rejected document names where it fails: #attribute, #metaItem, #parameter"() { given: "an asset with a configured attribute" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) when: "the document is previewed" def location = ConfigurationTemplateUtil.preview(asset, documentText).failureLocation @@ -190,7 +205,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "a document rejected as a whole has no location"() { expect: "the rejection holds no location" - ConfigurationTemplateUtil.preview(thingAsset(), documentText).failureLocation == null + ConfigurationTemplateUtil.preview(weatherAsset(), documentText).failureLocation == null where: documentText << ["not json at all", "[]", document(ThingAsset.DESCRIPTOR.name, [:], 2)] @@ -198,9 +213,9 @@ class ConfigurationTemplateUtilTest extends Specification { def "export leaves out metadata that grants access or links attributes"() { given: "an asset whose attributes hold access and attribute link metadata" - def asset = thingAsset([ + def asset = weatherAsset([ temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.ACCESS_PUBLIC_WRITE.name): true]), - linked: attribute("linked", ValueType.NUMBER, [(MetaItemType.ACCESS_RESTRICTED_READ.name): true, (MetaItemType.ATTRIBUTE_LINKS.name): []]) + rainfall : attribute("rainfall", ValueType.POSITIVE_NUMBER, [(MetaItemType.ACCESS_RESTRICTED_READ.name): true, (MetaItemType.ATTRIBUTE_LINKS.name): []]) ]) when: "the configuration is exported" @@ -215,7 +230,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "import keeps the access and attribute link metadata of the asset and ignores that of the document"() { given: "an asset whose attribute is publicly readable" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.ACCESS_PUBLIC_READ.name): true])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.ACCESS_PUBLIC_READ.name): true])]) when: "a document granting public write access is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ @@ -234,7 +249,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "an attribute missing on the target asset is skipped and reported"() { given: "an asset without the imported attribute" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) when: "a document holding a known and an unknown attribute is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ @@ -249,9 +264,47 @@ class ConfigurationTemplateUtilTest extends Specification { !preview.patchedAttributes.has("humidity") } + def "an attribute that the asset type does not define is skipped and reported as custom"() { + given: "an asset holding an attribute of its type and one added to the asset alone" + def asset = weatherAsset([ + temperature : attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"]), + serialNumber: attribute("serialNumber", ValueType.TEXT) + ]) + + when: "a document holding both is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(WeatherAsset.DESCRIPTOR.name, [ + temperature : '{"type": "number", "meta": {"label": "Imported"}}', + serialNumber: '{"type": "text", "meta": {"label": "Imported"}}' + ])) + + then: "only the attribute of the asset type is importable and the other one is reported as custom" + preview.failure == null + preview.importableAttributes*.name == ["temperature"] + preview.customAttributes*.name == ["serialNumber"] + !preview.missingAttributes + !preview.typeMismatches + + and: "the custom attribute keeps its metadata" + !preview.patchedAttributes.get("serialNumber").get().hasMeta(MetaItemType.LABEL) + } + + def "a document holding only custom attributes of the asset is rejected"() { + given: "an asset holding an attribute added to the asset alone" + def asset = weatherAsset([serialNumber: attribute("serialNumber", ValueType.TEXT)]) + + when: "a document holding that attribute is previewed" + def preview = ConfigurationTemplateUtil.preview(asset, document(WeatherAsset.DESCRIPTOR.name, [ + serialNumber: '{"type": "text", "meta": {"label": "Imported"}}' + ])) + + then: "nothing can be imported, with the custom attribute reported" + preview.failure == NO_IMPORTABLE_ATTRIBUTES + preview.customAttributes*.name == ["serialNumber"] + } + def "an attribute whose type differs is skipped and reported"() { given: "an asset holding the imported attribute as text" - def asset = thingAsset([temperature: attribute("temperature", ValueType.TEXT, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.TEXT, [(MetaItemType.LABEL.name): "Temperature"])]) when: "a document holding the attribute as a number is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ @@ -267,7 +320,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "type comparison is case sensitive"() { given: "an asset holding a number attribute" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) when: "a document spelling the same type differently is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ @@ -283,7 +336,7 @@ class ConfigurationTemplateUtilTest extends Specification { def "a document exported from another asset type can still be imported"() { given: "a thing asset holding a configured attribute" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) when: "a document exported from a room asset is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(RoomAsset.DESCRIPTOR.name, [ @@ -297,16 +350,16 @@ class ConfigurationTemplateUtilTest extends Specification { def "the metadata of an importable attribute is replaced as a whole"() { given: "an asset whose attribute holds metadata that the document does not" - def asset = thingAsset([ + def asset = weatherAsset([ temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.READ_ONLY.name): true]), - plain : attribute("plain", ValueType.TEXT) + notes : attribute("notes", ValueType.TEXT) ]) asset.getAttributes().get("temperature").get().setValue(21.5d) when: "a document holding other metadata for that attribute is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ temperature: '{"type": "number", "meta": {"unitType": ["celsius"]}}', - plain : '{"type": "text", "meta": {"label": "Plain"}}' + notes : '{"type": "text", "meta": {"label": "Notes"}}' ])) then: "the imported metadata replaces the existing metadata entirely" @@ -316,7 +369,7 @@ class ConfigurationTemplateUtilTest extends Specification { !patchedTemperature.hasMeta(MetaItemType.READ_ONLY) and: "an attribute without metadata gets the imported metadata added" - preview.patchedAttributes.get("plain").get().getMetaValue(MetaItemType.LABEL).orElse(null) == "Plain" + preview.patchedAttributes.get("notes").get().getMetaValue(MetaItemType.LABEL).orElse(null) == "Notes" and: "the type and the value of the attribute are untouched" patchedTemperature.type == ValueType.NUMBER @@ -324,12 +377,12 @@ class ConfigurationTemplateUtilTest extends Specification { and: "the asset itself is not modified" asset.getAttributes().get("temperature").get().getMeta().has(MetaItemType.LABEL.name) - !asset.getAttributes().get("plain").get().getMeta().has("label") + !asset.getAttributes().get("notes").get().getMeta().has("label") } def "an internal name field within an entry is ignored"() { given: "an asset holding a configured attribute" - def asset = thingAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) + def asset = weatherAsset([temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"])]) when: "a document whose entry names another attribute is previewed" def preview = ConfigurationTemplateUtil.preview(asset, document(ThingAsset.DESCRIPTOR.name, [ diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java index f976cfd2a5..16a867b665 100644 --- a/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/ManagerConfigTemplateSetup.java @@ -59,17 +59,22 @@ import org.openremote.model.asset.impl.ThingAsset; import org.openremote.model.attribute.Attribute; import org.openremote.model.attribute.MetaItem; +import org.openremote.model.value.AttributeDescriptor; import org.openremote.model.value.ValueConstraint; -import org.openremote.model.value.ValueDescriptor; +import org.openremote.setup.configtemplate.model.AgentLinksAsset; +import org.openremote.setup.configtemplate.model.MixerAsset; import org.openremote.setup.configtemplate.model.PumpAsset; /** * Seeds one configured pump and three targets to copy its configuration onto, so exporting and * importing a configuration template can be tried end to end. Every target shows a different - * outcome: a full import, an import that skips attributes, and an import from another asset type. - * The pump's agent links follow the template parameter concept: three Modbus links share an agent - * and two of them a unit id, and two simulator links use different agents. A separate asset holds - * one attribute per agent link type, and another holds every agent. + * outcome: a full import, an import that skips missing attributes, and an import into another asset + * type that also skips an attribute of another value type and a custom attribute. Custom + * attributes, added to an asset rather than defined by its asset type, take no part in a template, + * so the pump's maintenance note is not exported. The pump's agent links follow the template + * parameter concept: three Modbus links share an agent and two of them a unit id, and two simulator + * links use different agents. A separate asset holds one attribute per agent link type, and another + * holds every agent. */ public class ManagerConfigTemplateSetup extends ManagerSetup { @@ -140,78 +145,73 @@ public void onStart() throws Exception { new MetaItem<>( AGENT_LINK, modbusLink(modbusAgentId, 2, ReadMemoryArea.COIL, ModbusDataType.BOOL, 1))), - // Not a descriptor attribute, so a target asset can be missing it - new Attribute<>("errorCode", TEXT) + new Attribute<>(PumpAsset.ERROR_CODE) .addOrReplaceMeta( new MetaItem<>(LABEL, "Error code"), new MetaItem<>(RULE_STATE, true), new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(simulator1AgentId))), - // Not a descriptor attribute, so a target asset can hold it with another value type - new Attribute<>("serialNumber", TEXT) + new Attribute<>(PumpAsset.SERIAL_NUMBER) .addOrReplaceMeta( new MetaItem<>(LABEL, "Serial number"), new MetaItem<>(READ_ONLY, true), - new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(simulator2AgentId)))); + new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(simulator2AgentId))), + // A custom attribute, so it takes no part in a template + new Attribute<>("maintenanceNote", TEXT) + .addOrReplaceMeta(new MetaItem<>(LABEL, "Maintenance note"))); assetStorageService.merge(configured); // Holds every attribute of the configured pump, so the whole configuration can be imported PumpAsset bare = new PumpAsset("Pump 2 (import target)"); bare.setRealm(MASTER_REALM); bare.addOrReplaceAttributes( - new Attribute<>("errorCode", TEXT), new Attribute<>("serialNumber", TEXT)); + new Attribute<>(PumpAsset.ERROR_CODE), new Attribute<>(PumpAsset.SERIAL_NUMBER)); assetStorageService.merge(bare); - // Misses errorCode and holds serialNumber as a number, so the import reports both as skipped + // Misses the optional errorCode and serialNumber, so the import reports both as skipped PumpAsset partial = new PumpAsset("Pump 3 (partially compatible)"); partial.setRealm(MASTER_REALM); - partial.addOrReplaceAttributes(new Attribute<>("serialNumber", NUMBER)); assetStorageService.merge(partial); - // Another asset type, sharing only some attributes with the pump - ThingAsset otherType = new ThingAsset("Mixer 1 (other asset type)"); + // Another asset type, sharing flowRate and pressure with the pump and holding serialNumber as a + // number; running is a custom attribute of the mixer, so the import skips both + MixerAsset otherType = new MixerAsset("Mixer 1 (other asset type)"); otherType.setRealm(MASTER_REALM); - otherType.addOrReplaceAttributes( - new Attribute<>("flowRate", NUMBER), new Attribute<>("pressure", NUMBER)); + otherType.addOrReplaceAttributes(new Attribute<>("running", BOOLEAN)); assetStorageService.merge(otherType); // One attribute per agent link type; "(requirements)" marks links with fields that must be set - ThingAsset agentLinks = new ThingAsset("Agent links (all types)"); + AgentLinksAsset agentLinks = new AgentLinksAsset("Agent links (all types)"); agentLinks.setRealm(MASTER_REALM); agentLinks.addOrReplaceAttributes( linked( - "bluetoothMesh", - BOOLEAN, + AgentLinksAsset.BLUETOOTH_MESH, "Bluetooth mesh (requirements)", new BluetoothMeshAgentLink(bluetoothMeshAgentId, 0, "0002", "GenericOnOffServer")), - linked("default", TEXT, "Default", new DefaultAgentLink(tcpAgentId)), - linked("http", TEXT, "HTTP (requirements)", new HTTPAgentLink(httpAgentId)), + linked(AgentLinksAsset.DEFAULT, "Default", new DefaultAgentLink(tcpAgentId)), + linked(AgentLinksAsset.HTTP, "HTTP (requirements)", new HTTPAgentLink(httpAgentId)), linked( - "knx", - BOOLEAN, + AgentLinksAsset.KNX, "KNX (requirements)", new KNXAgentLink(knxAgentId, "1.001", "1/0/1", "1/0/2")), - linked("mail", TEXT, "Mail", new MailAgentLink(mailAgentId)), - linked("modbus", NUMBER, "Modbus", new ModbusAgentLink(modbusAgentId)), - linked("mqtt", TEXT, "MQTT", new MQTTAgentLink(mqttAgentId)), + linked(AgentLinksAsset.MAIL, "Mail", new MailAgentLink(mailAgentId)), + linked(AgentLinksAsset.MODBUS, "Modbus", new ModbusAgentLink(modbusAgentId)), + linked(AgentLinksAsset.MQTT, "MQTT", new MQTTAgentLink(mqttAgentId)), linked( - "openWeatherMap", - NUMBER, + AgentLinksAsset.OPEN_WEATHER_MAP, "OpenWeatherMap (requirements)", new OpenWeatherMapAgentLink(openWeatherMapAgentId) .setWeatherProperty(OpenWeatherMapProperty.TEMPERATURE)), - linked("simulator", NUMBER, "Simulator", new SimulatorAgentLink(simulator1AgentId)), + linked(AgentLinksAsset.SIMULATOR, "Simulator", new SimulatorAgentLink(simulator1AgentId)), linked( - "snmp", - TEXT, + AgentLinksAsset.SNMP, "SNMP (requirements)", new SNMPAgentLink(snmpAgentId, "1.3.6.1.2.1.1.3.0")), linked( - "velbus", - BOOLEAN, + AgentLinksAsset.VELBUS, "Velbus (requirements)", new VelbusAgentLink(velbusAgentId, 48, "CH1")), - linked("websocket", TEXT, "Websocket", new WebsocketAgentLink(websocketAgentId)), - linked("zWave", BOOLEAN, "Z-Wave", new ZWaveAgentLink(zWaveAgentId, 2, 0, "Basic"))); + linked(AgentLinksAsset.WEBSOCKET, "Websocket", new WebsocketAgentLink(websocketAgentId)), + linked(AgentLinksAsset.Z_WAVE, "Z-Wave", new ZWaveAgentLink(zWaveAgentId, 2, 0, "Basic"))); assetStorageService.merge(agentLinks); } @@ -236,8 +236,8 @@ protected static ModbusAgentLink modbusLink( } protected static Attribute linked( - String name, ValueDescriptor type, String label, AgentLink agentLink) { - return new Attribute<>(name, type) + AttributeDescriptor descriptor, String label, AgentLink agentLink) { + return new Attribute<>(descriptor) .addOrReplaceMeta(new MetaItem<>(LABEL, label), new MetaItem<>(AGENT_LINK, agentLink)); } } diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/model/AgentLinksAsset.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/AgentLinksAsset.java new file mode 100644 index 0000000000..340f119172 --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/AgentLinksAsset.java @@ -0,0 +1,70 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.setup.configtemplate.model; + +import jakarta.persistence.Entity; +import org.openremote.model.asset.Asset; +import org.openremote.model.asset.AssetDescriptor; +import org.openremote.model.value.AttributeDescriptor; +import org.openremote.model.value.ValueType; + +/** + * Asset type of the config template demo with an attribute for every agent link type, so a template + * can hold a link of each type. + */ +@Entity +public class AgentLinksAsset extends Asset { + + public static final AttributeDescriptor BLUETOOTH_MESH = + new AttributeDescriptor<>("bluetoothMesh", ValueType.BOOLEAN); + public static final AttributeDescriptor DEFAULT = + new AttributeDescriptor<>("default", ValueType.TEXT); + public static final AttributeDescriptor HTTP = + new AttributeDescriptor<>("http", ValueType.TEXT); + public static final AttributeDescriptor KNX = + new AttributeDescriptor<>("knx", ValueType.BOOLEAN); + public static final AttributeDescriptor MAIL = + new AttributeDescriptor<>("mail", ValueType.TEXT); + public static final AttributeDescriptor MODBUS = + new AttributeDescriptor<>("modbus", ValueType.NUMBER); + public static final AttributeDescriptor MQTT = + new AttributeDescriptor<>("mqtt", ValueType.TEXT); + public static final AttributeDescriptor OPEN_WEATHER_MAP = + new AttributeDescriptor<>("openWeatherMap", ValueType.NUMBER); + public static final AttributeDescriptor SIMULATOR = + new AttributeDescriptor<>("simulator", ValueType.NUMBER); + public static final AttributeDescriptor SNMP = + new AttributeDescriptor<>("snmp", ValueType.TEXT); + public static final AttributeDescriptor VELBUS = + new AttributeDescriptor<>("velbus", ValueType.BOOLEAN); + public static final AttributeDescriptor WEBSOCKET = + new AttributeDescriptor<>("websocket", ValueType.TEXT); + public static final AttributeDescriptor Z_WAVE = + new AttributeDescriptor<>("zWave", ValueType.BOOLEAN); + + public static final AssetDescriptor DESCRIPTOR = + new AssetDescriptor<>("link-variant", "607d8b", AgentLinksAsset.class); + + /** For use by hydrators (i.e. JPA/Jackson) */ + protected AgentLinksAsset() {} + + public AgentLinksAsset(String name) { + super(name); + } +} diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/model/MixerAsset.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/MixerAsset.java new file mode 100644 index 0000000000..211758b765 --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/MixerAsset.java @@ -0,0 +1,51 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.setup.configtemplate.model; + +import jakarta.persistence.Entity; +import org.openremote.model.asset.Asset; +import org.openremote.model.asset.AssetDescriptor; +import org.openremote.model.value.AttributeDescriptor; +import org.openremote.model.value.ValueType; + +/** + * Second asset type of the config template demo, sharing some attribute names with the pump. The + * descriptors carry no metadata, so a new mixer starts without configuration items. + */ +@Entity +public class MixerAsset extends Asset { + + public static final AttributeDescriptor FLOW_RATE = + new AttributeDescriptor<>("flowRate", ValueType.NUMBER); + public static final AttributeDescriptor PRESSURE = + new AttributeDescriptor<>("pressure", ValueType.NUMBER); + // A number, where the pump holds text + public static final AttributeDescriptor SERIAL_NUMBER = + new AttributeDescriptor<>("serialNumber", ValueType.NUMBER); + + public static final AssetDescriptor DESCRIPTOR = + new AssetDescriptor<>("blender", "6d4c41", MixerAsset.class); + + /** For use by hydrators (i.e. JPA/Jackson) */ + protected MixerAsset() {} + + public MixerAsset(String name) { + super(name); + } +} diff --git a/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java index 3a021ebb30..e31ec1034d 100644 --- a/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.java @@ -37,6 +37,11 @@ public class PumpAsset extends Asset { new AttributeDescriptor<>("pressure", ValueType.NUMBER); public static final AttributeDescriptor RUNNING = new AttributeDescriptor<>("running", ValueType.BOOLEAN); + // Optional, so a pump can be missing them + public static final AttributeDescriptor ERROR_CODE = + new AttributeDescriptor<>("errorCode", ValueType.TEXT).withOptional(true); + public static final AttributeDescriptor SERIAL_NUMBER = + new AttributeDescriptor<>("serialNumber", ValueType.TEXT).withOptional(true); public static final AssetDescriptor DESCRIPTOR = new AssetDescriptor<>("water-pump", "1565c0", PumpAsset.class); diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy index 822aec7b7b..7cf0f610f4 100644 --- a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -24,8 +24,8 @@ import org.openremote.manager.setup.SetupService import org.openremote.model.asset.AssetResource import org.openremote.model.asset.ConfigurationTemplateImportPreview import org.openremote.model.asset.ConfigurationTemplateImportRequest +import org.openremote.model.asset.impl.LightAsset import org.openremote.model.asset.impl.RoomAsset -import org.openremote.model.asset.impl.ThingAsset import org.openremote.model.attribute.Attribute import org.openremote.model.attribute.MetaItem import org.openremote.model.util.ValueUtil @@ -106,45 +106,45 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine def "Export and import a configuration template as superuser"() { given: "a configured source asset and a target asset of the same type" - def source = adminResource.create(null, new ThingAsset("Configuration source") + def source = adminResource.create(null, new LightAsset("Configuration source") .setRealm(keycloakTestSetup.realmMaster.name) .addOrReplaceAttributes( - new Attribute<>("temperature", ValueType.NUMBER) - .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source temperature")) + new Attribute<>(LightAsset.BRIGHTNESS) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source brightness")) .addMeta(new MetaItem<>(MetaItemType.READ_ONLY, true)), + new Attribute<>(LightAsset.COLOUR_TEMPERATURE) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source colour temperature")), new Attribute<>("customValue", ValueType.TEXT) - .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source custom value")), - new Attribute<>("plain", ValueType.TEXT) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Source custom value")) )) - def target = adminResource.create(null, new ThingAsset("Configuration target") + def target = adminResource.create(null, new LightAsset("Configuration target") .setRealm(keycloakTestSetup.realmMaster.name) .addOrReplaceAttributes( - new Attribute<>("temperature", ValueType.NUMBER, 21.5d) - .addMeta(new MetaItem<>(MetaItemType.LABEL, "Target temperature")), - new Attribute<>("customValue", ValueType.NUMBER), - new Attribute<>("plain", ValueType.TEXT) + new Attribute<>(LightAsset.BRIGHTNESS, 50) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Target brightness")), + new Attribute<>("customValue", ValueType.NUMBER) )) createdAssetIds.addAll([source.id, target.id]) when: "a configuration template of the source asset is exported" def document = adminResource.exportConfigurationTemplate(null, source.id, []) - then: "only the attributes holding metadata are exported, with their type and metadata" + then: "only the attributes that the asset type defines and that hold metadata are exported, with their type and metadata" document.version == 1 - document.assetType == ThingAsset.DESCRIPTOR.name - document.attributes.keySet() == ["temperature", "customValue"] as Set - document.attributes.temperature.type == ValueType.NUMBER.name - document.attributes.temperature.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source temperature" - document.attributes.temperature.getMetaValue(MetaItemType.READ_ONLY).orElse(false) + document.assetType == LightAsset.DESCRIPTOR.name + document.attributes.keySet() == ["brightness", "colourTemperature"] as Set + document.attributes.brightness.type == ValueType.POSITIVE_INTEGER.name + document.attributes.brightness.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source brightness" + document.attributes.brightness.getMetaValue(MetaItemType.READ_ONLY).orElse(false) when: "a subset of the attributes is exported" - def subset = adminResource.exportConfigurationTemplate(null, source.id, ["temperature"]) + def subset = adminResource.exportConfigurationTemplate(null, source.id, ["brightness"]) then: "only the requested attribute is exported" - subset.attributes.keySet() == ["temperature"] as Set + subset.attributes.keySet() == ["brightness"] as Set when: "only an attribute without metadata is selected" - adminResource.exportConfigurationTemplate(null, source.id, ["plain"]) + adminResource.exportConfigurationTemplate(null, source.id, ["onOff"]) then: "the export is rejected as there is nothing to export" WebApplicationException nothingToExport = thrown() @@ -153,29 +153,38 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine return true } + when: "only an attribute that the asset type does not define is selected" + adminResource.exportConfigurationTemplate(null, source.id, ["customValue"]) + + then: "the export is rejected as there is nothing to export" + WebApplicationException customOnly = thrown() + customOnly.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + return true + } + when: "the exported document is imported into the target asset" def preview = adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(target, ValueUtil.asJSON(document).orElseThrow())) - then: "the attribute with a matching type is importable and the one with another type is reported" + then: "both attributes are importable and nothing is skipped" preview.failure == null - preview.importableAttributes*.name == ["temperature"] - preview.typeMismatches*.name == ["customValue"] - preview.typeMismatches*.importedType == [ValueType.TEXT.name] - preview.typeMismatches*.targetType == [ValueType.NUMBER.name] + preview.importableAttributes*.name == ["brightness", "colourTemperature"] + !preview.missingAttributes + !preview.typeMismatches and: "the patched attributes hold the imported metadata, keeping the attribute value" - def patched = preview.patchedAttributes.get("temperature").get() - patched.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source temperature" + def patched = preview.patchedAttributes.get("brightness").get() + patched.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source brightness" patched.getMetaValue(MetaItemType.READ_ONLY).orElse(false) - patched.value.orElse(null) == 21.5d + patched.value.orElse(null) == 50 and: "the attributes that are not imported are returned untouched" preview.patchedAttributes.get("customValue").get().type == ValueType.NUMBER and: "the target asset is not stored by the preview" - adminResource.get(null, target.id).getAttribute("temperature").get().getMeta() - .getValue(MetaItemType.LABEL.name, String.class).orElse(null) == "Target temperature" + adminResource.get(null, target.id).getAttribute("brightness").get().getMeta() + .getValue(MetaItemType.LABEL.name, String.class).orElse(null) == "Target brightness" when: "a document of an unsupported version is imported" adminResource.previewConfigurationTemplateImport(null, target.id, @@ -191,7 +200,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine when: "a document holding a configuration item that breaks a constraint is imported" adminResource.previewConfigurationTemplateImport(null, target.id, - new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"temperature": {"type": "number", "meta": {"forecast": {"type": "wea", "pastPeriod": "P1D", "pastCount": 0, "forecastPeriod": "PT1H", "forecastCount": 1}}}}}')) + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "LightAsset", "attributes": {"brightness": {"type": "positiveInteger", "meta": {"forecast": {"type": "wea", "pastPeriod": "P1D", "pastCount": 0, "forecastPeriod": "PT1H", "forecastCount": 1}}}}}')) then: "the import is rejected with the reason and where it fails" WebApplicationException invalidMetaItem = thrown() @@ -199,7 +208,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine assert r.status == BAD_REQUEST.statusCode def rejected = r.readEntity(ConfigurationTemplateImportPreview.class) assert rejected.failure == INVALID_META_ITEM - assert rejected.failureLocation.attribute == "temperature" + assert rejected.failureLocation.attribute == "brightness" assert rejected.failureLocation.metaItem == MetaItemType.FORECAST.name assert rejected.failureLocation.parameter == "pastCount" return true @@ -207,7 +216,7 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine when: "a document holding a minimum above the current value of the target attribute is imported" adminResource.previewConfigurationTemplateImport(null, target.id, - new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"temperature": {"type": "number", "meta": {"constraints": [{"type": "min", "min": 30}]}}}}')) + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "LightAsset", "attributes": {"brightness": {"type": "positiveInteger", "meta": {"constraints": [{"type": "min", "min": 60}]}}}}')) then: "the import is rejected, as saving the asset would fail" WebApplicationException valueViolatesConstraints = thrown() @@ -215,13 +224,13 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine assert r.status == BAD_REQUEST.statusCode def rejected = r.readEntity(ConfigurationTemplateImportPreview.class) assert rejected.failure == VALUE_VIOLATES_CONSTRAINTS - assert rejected.failureLocation.attribute == "temperature" + assert rejected.failureLocation.attribute == "brightness" return true } when: "a document holding no attribute of the target asset is imported" adminResource.previewConfigurationTemplateImport(null, target.id, - new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "ThingAsset", "attributes": {"absent": {"type": "text", "meta": {"label": "Absent"}}}}')) + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "LightAsset", "attributes": {"absent": {"type": "text", "meta": {"label": "Absent"}}}}')) then: "the import is rejected and the skipped attribute is reported" WebApplicationException noneImportable = thrown() @@ -233,6 +242,20 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine return true } + when: "a document holding only an attribute that the target asset type does not define is imported" + adminResource.previewConfigurationTemplateImport(null, target.id, + new ConfigurationTemplateImportRequest(target, '{"version": 1, "assetType": "LightAsset", "attributes": {"customValue": {"type": "number", "meta": {"label": "Custom"}}}}')) + + then: "the import is rejected and the attribute is reported as custom" + WebApplicationException customImport = thrown() + customImport.response.withCloseable { r -> + assert r.status == BAD_REQUEST.statusCode + def rejected = r.readEntity(ConfigurationTemplateImportPreview.class) + assert rejected.failure == NO_IMPORTABLE_ATTRIBUTES + assert rejected.customAttributes*.name == ["customValue"] + return true + } + when: "the draft of another asset is submitted" adminResource.previewConfigurationTemplateImport(null, target.id, new ConfigurationTemplateImportRequest(source, ValueUtil.asJSON(document).orElseThrow())) @@ -258,17 +281,26 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } def "Configuration template import requires asset write access"() { - when: "a user that can read but not write assets exports a configuration template of an asset of its realm" - def document = readOnlyUserResource.exportConfigurationTemplate(null, managerTestSetup.apartment1LivingroomId, []) + given: "a configured asset in the realm of a user that can read but not write assets" + def asset = adminResource.create(null, new LightAsset("Configured light") + .setRealm(keycloakTestSetup.realmBuilding.name) + .addOrReplaceAttributes( + new Attribute<>(LightAsset.BRIGHTNESS) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Brightness")) + )) + createdAssetIds.add(asset.id) + + when: "that user exports a configuration template of the asset" + def document = readOnlyUserResource.exportConfigurationTemplate(null, asset.id, []) then: "the configuration is returned" document.version == 1 - !document.attributes.isEmpty() + document.attributes.keySet() == ["brightness"] as Set when: "the same user previews an import" - readOnlyUserResource.previewConfigurationTemplateImport(null, managerTestSetup.apartment1LivingroomId, + readOnlyUserResource.previewConfigurationTemplateImport(null, asset.id, new ConfigurationTemplateImportRequest( - readOnlyUserResource.get(null, managerTestSetup.apartment1LivingroomId), + readOnlyUserResource.get(null, asset.id), ValueUtil.asJSON(document).orElseThrow())) then: "access is forbidden" diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index d612e8a43e..a3f9ecc467 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -241,9 +241,13 @@ function getTemplateMeta(attribute: Attribute | undefined): { [name: string ); } -/** The attributes holding configuration items for a template, which are the attributes that can be exported. */ +/** + * The attributes holding configuration items for a template, which are the attributes that can be exported. Attributes + * that the asset type does not define are left out, so a configuration to reuse belongs in an asset type. + */ export function getConfigurableAttributes(asset: Asset): Attribute[] { return Object.entries(asset.attributes || {}) + .filter(([name]) => !!AssetModelUtil.getAttributeDescriptor(name, asset.type!)) .filter(([, attribute]) => Object.keys(getTemplateMeta(attribute)).length > 0) .map(([name, attribute]) => ({ ...attribute, name })) .sort(Util.sortByString((attribute) => attribute.name!.toUpperCase())); @@ -616,6 +620,7 @@ function getSkippedTemplate( const skipped = [ ...(preview.missingAttributes || []).map((attribute) => attribute.name!), ...(preview.typeMismatches || []).map((mismatch) => mismatch.name!), + ...(preview.customAttributes || []).map((attribute) => attribute.name!), ]; if (skipped.length === 0) { From b8c7acd521f0fe553787829e124898fc9b0915c1 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Mon, 16 Nov 2026 16:25:50 +0100 Subject: [PATCH 16/21] Add configuration template UI tests --- ui/AGENTS.md | 4 + .../test/configuration-template.test.ts | 208 +++++++++++++++++- .../fixtures/data/configuration-template.ts | 100 +++++++++ .../or-asset-viewer/test/fixtures/index.ts | 25 +++ 4 files changed, 336 insertions(+), 1 deletion(-) create mode 100644 ui/app/manager/test/fixtures/data/configuration-template.ts diff --git a/ui/AGENTS.md b/ui/AGENTS.md index 50e980b10b..3a455f9dbf 100644 --- a/ui/AGENTS.md +++ b/ui/AGENTS.md @@ -95,6 +95,8 @@ Stories call `getORStorybookHelpers(tagName)` (from `ui/component/storybook-util - **Test Naming:** `test.describe` blocks describe a feature. Tests should be named starting with "should ...". - **Test Structure:** Keep tests flat by default. Omit top-level `test.describe` blocks. If grouping is needed, target a specific feature (e.g., filtering notifications) rather than a parent concept like the whole page. Example: `test.describe("Filter Notifications", ...)` instead of `test.describe("Notifications", ...)`. - **Regression Tests:** Every bug fix ships with a test that fails without it. Name it after the behaviour that should hold rather than the defect, and record what used to go wrong in a comment on the assertion that catches it. +- **Dialogs:** A Vaadin dialog renders its overlay in the top layer, so the `role="dialog"` host itself never counts as visible; assert on elements inside it, or use `toHaveCount`. Confirm dialogs have the role `alertdialog`. +- **Translated text:** `getByText` cannot find text rendered by `or-translate`; locate the element with a `hasText` filter instead, or use role names, which do include it. ### Fixtures @@ -108,6 +110,8 @@ Stories call `getORStorybookHelpers(tagName)` (from `ui/component/storybook-util - **Location:** Define tests in `ui/app//test/`. Define fixtures in `ui/app//test/fixtures/`. - **Comments:** Add scenario comments above tests (`@given`, `@when`, `@then`, `@and`) based on the acceptance criteria. - **Auth State:** Select correct `storageState` for the task to be tested. Use `adminStatePath` for master/admin tasks. Use `userStatePath` for regular realm user tasks. +- **Downloads:** Check the content of a downloaded file through the response it is built from (`page.waitForResponse`), and its name through the `download` event. Do not read it from disk; `download.path()` throws when the browser + runs remotely. ### Component testing diff --git a/ui/app/manager/test/configuration-template.test.ts b/ui/app/manager/test/configuration-template.test.ts index 3c21e4f07c..18beb44fd0 100644 --- a/ui/app/manager/test/configuration-template.test.ts +++ b/ui/app/manager/test/configuration-template.test.ts @@ -16,11 +16,217 @@ * * SPDX-License-Identifier: AGPL-3.0-or-later */ -import { expect } from "@openremote/test"; +import { expect, type Page } from "@openremote/test"; +import type { AssetViewer } from "../../../component/or-asset-viewer/test/fixtures"; import { test, userStatePath } from "./fixtures/manager.js"; +import { agent } from "./fixtures/data/assets.js"; +import { + configuredLight, + lightTemplate, + partlyImportableTemplate, + targetLight, +} from "./fixtures/data/configuration-template.js"; test.use({ storageState: userStatePath }); +test.afterEach(async ({ manager }) => { + await manager.cleanUp(); +}); + +/** + * Select a configuration template file for the asset open in modify mode and continue to what importing it would do. + * @param page The page showing the asset + * @param assetViewer The asset viewer fixture + * @param name The file name + * @param content The file content + */ +async function selectTemplateFile(page: Page, assetViewer: AssetViewer, name: string, content: string) { + await page.getByRole("button", { name: "Import", exact: true }).click(); + await assetViewer + .getConfigurationTemplateFileInput() + .setInputFiles({ name, mimeType: "application/json", buffer: Buffer.from(content) }); + await page.getByRole("dialog").getByRole("button", { name: "Next" }).click(); +} + +/** + * @given A configured light is set up in the "smartcity" realm + * @when Opening the export dialog of the light in modify mode + * @then The configured attributes that the asset type defines are listed and selected + * @and The attribute of the light alone is not listed + * @and The template is named after the light + */ +test("should list the configured attributes of the asset type for export", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [configuredLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await page.getByRole("button", { name: "Export", exact: true }).click(); + + const dialog = page.getByRole("dialog"); + await expect(dialog.getByLabel("Template name")).toHaveValue("Light 1 (configured)-configuration-template.json"); + await expect(dialog.getByRole("checkbox", { name: "Select all" })).toBeChecked(); + for (const label of ["Dimmer", "Power", "White tone"]) { + await expect(dialog.getByRole("checkbox", { name: new RegExp(`^${label}`) })).toBeChecked(); + } + await expect(assetViewer.getConfigurationTemplateAttribute(dialog, "Maintenance note")).toHaveCount(0); +}); + +/** + * @given A configured light is set up in the "smartcity" realm + * @when Exporting all but one of its attributes under another template name + * @then A file of that name downloads, holding the type and configuration items of the selected attributes + * @and Configuration items that grant access are left out + */ +test("should download the selected attributes as a configuration template", async ({ page, manager, assetsPage }) => { + await manager.setup("smartcity", { assets: [configuredLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await page.getByRole("button", { name: "Export", exact: true }).click(); + + const dialog = page.getByRole("dialog"); + await dialog.getByRole("checkbox", { name: /^Power/ }).uncheck(); + await expect(dialog.getByRole("checkbox", { name: "Select all" })).not.toBeChecked(); + await dialog.getByLabel("Template name").fill("lights"); + const responsePromise = page.waitForResponse( + (response) => + response.request().method() === "GET" && new URL(response.url()).pathname.endsWith("/configurationTemplate") + ); + const downloadPromise = page.waitForEvent("download"); + await dialog.getByRole("button", { name: "Export", exact: true }).click(); + const template = await (await responsePromise).json(); + + expect((await downloadPromise).suggestedFilename()).toBe("lights.json"); + expect(template).toMatchObject({ version: 1, assetType: "LightAsset" }); + expect(Object.keys(template.attributes).sort()).toEqual(["brightness", "colourTemperature"]); + expect(template.attributes.brightness).toEqual(lightTemplate.attributes.brightness); + expect(template.attributes.colourTemperature).toMatchObject(lightTemplate.attributes.colourTemperature); +}); + +/** + * @given A light to import into is set up in the "smartcity" realm + * @when Importing the configuration template of another light in modify mode + * @then The matched attributes are listed with a warning that their configuration items are overwritten + * @when Confirming the import + * @then The light has unsaved changes, so export is disabled + * @when Saving the light + * @then The configuration items of the template are stored, apart from those that grant access, which the light keeps + */ +test("should apply an imported configuration template to the draft until it is saved", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [targetLight] }); + const id = manager.assets[0].id!; + await assetsPage.gotoAssetId("smartcity", id, true); + await selectTemplateFile(page, assetViewer, "lights.json", JSON.stringify(lightTemplate)); + + const matched = assetViewer.getConfigurationTemplateSection("Matched attributes"); + // getByText cannot match text that or-translate renders straight into its shadow root, so locate the element + await expect( + page.getByRole("dialog").locator("or-translate", { hasText: "This will overwrite existing metadata" }) + ).toBeVisible(); + for (const label of ["Dimmer", "Power", "White tone"]) { + await expect(assetViewer.getConfigurationTemplateAttribute(matched, label)).toBeVisible(); + } + await page.getByRole("dialog").getByRole("button", { name: "Import", exact: true }).click(); + + const saveButton = page.getByRole("button", { name: "Save" }); + const exportButton = page.getByRole("button", { name: "Export", exact: true }); + await expect(saveButton).toBeEnabled(); + await expect(exportButton).toBeDisabled(); + await expect(exportButton).toHaveAttribute("title", "Save or revert your changes before exporting"); + + await saveButton.click(); + await expect(saveButton).toBeDisabled(); + await expect(exportButton).toBeEnabled(); + + const { data: light } = await manager.api.AssetResource.get(id, await manager.adminConfig()); + expect(light.attributes!.brightness).toMatchObject({ value: 40, meta: lightTemplate.attributes.brightness.meta }); + expect(light.attributes!.onOff.meta).toEqual({ label: "Power", accessRestrictedRead: true }); +}); + +/** + * @given A light to import into is set up in the "smartcity" realm + * @when Importing a template holding an attribute the light misses and one of another value type + * @then Those attributes are listed as not imported, next to the matched attribute + */ +test("should list the attributes of a template that cannot be imported", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [targetLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await selectTemplateFile(page, assetViewer, "edited.json", JSON.stringify(partlyImportableTemplate)); + + const matched = assetViewer.getConfigurationTemplateSection("Matched attributes"); + const skipped = assetViewer.getConfigurationTemplateSection("Attribute name or type not found"); + await expect(assetViewer.getConfigurationTemplateAttribute(matched, "Dimmer")).toBeVisible(); + await expect(assetViewer.getConfigurationTemplateAttribute(skipped, "Dim level")).toBeVisible(); + await expect(assetViewer.getConfigurationTemplateAttribute(skipped, "White tone")).toBeVisible(); + await expect(assetViewer.getConfigurationTemplateAttribute(matched, "White tone")).toHaveCount(0); +}); + +/** + * @given A light to import into is set up in the "smartcity" realm + * @when Going back from what an import would do and cancelling it + * @then The light has no unsaved changes + */ +test("should leave the draft unchanged when an import is cancelled", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [targetLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await selectTemplateFile(page, assetViewer, "lights.json", JSON.stringify(lightTemplate)); + + await page.getByRole("dialog").getByRole("button", { name: "Back" }).click(); + await expect(page.getByRole("dialog").getByRole("button", { name: "Select file" })).toBeVisible(); + await page.getByRole("dialog").getByRole("button", { name: "Cancel" }).click(); + + await expect(page.getByRole("dialog")).toHaveCount(0); + await expect(page.getByRole("button", { name: "Save" })).toBeDisabled(); +}); + +/** + * @given A light to import into is set up in the "smartcity" realm + * @when Importing a file that does not hold JSON + * @then The import is rejected with the reason + */ +test("should reject a file that is not a configuration template", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [targetLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await selectTemplateFile(page, assetViewer, "notes.json", "not a template"); + + await expect(page.getByText("The selected file does not hold valid JSON.")).toBeVisible(); +}); + +/** + * @given An agent is set up in the "smartcity" realm + * @when Opening the agent in modify mode + * @then Import and export are not offered + */ +test("should not offer import and export on agents", async ({ page, manager, assetsPage }) => { + await manager.setup("smartcity", { assets: [agent] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + + await expect(page.getByRole("button", { name: "Save" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Import", exact: true })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Export", exact: true })).toHaveCount(0); +}); + /** * @given Logged in to the "smartcity" realm in modify mode * @when Adding an asset without saving it diff --git a/ui/app/manager/test/fixtures/data/configuration-template.ts b/ui/app/manager/test/fixtures/data/configuration-template.ts new file mode 100644 index 0000000000..f2bca3dc3b --- /dev/null +++ b/ui/app/manager/test/fixtures/data/configuration-template.ts @@ -0,0 +1,100 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import type { Asset } from "@openremote/model"; +import { commonAttrs } from "./assets"; + +/** + * A light whose attributes hold configuration items to copy, as the config template setup seeds its configured pump. + * Maintenance note is an attribute of the asset alone, which the asset type does not define. + */ +export const configuredLight: Asset = { + name: "Light 1 (configured)", + realm: "smartcity", + type: "LightAsset", + attributes: { + ...commonAttrs, + onOff: { name: "onOff", type: "boolean", meta: { label: "Power", accessPublicRead: true } }, + brightness: { + name: "brightness", + type: "positiveInteger", + meta: { label: "Dimmer", readOnly: true, storeDataPoints: true, ruleState: true }, + }, + colourRGB: { name: "colourRGB", type: "colourRGB" }, + colourTemperature: { + name: "colourTemperature", + type: "positiveInteger", + meta: { + label: "White tone", + constraints: [ + { type: "min", min: 2000 }, + { type: "max", max: 6500 }, + ], + }, + }, + maintenanceNote: { name: "maintenanceNote", type: "text", meta: { label: "Maintenance note" } }, + }, +}; + +/** A light of the same type to import into, holding access metadata of its own and a label to replace. */ +export const targetLight: Asset = { + name: "Light 2 (import target)", + realm: "smartcity", + type: "LightAsset", + attributes: { + ...commonAttrs, + onOff: { name: "onOff", type: "boolean", meta: { accessRestrictedRead: true } }, + brightness: { name: "brightness", type: "positiveInteger", value: 40, meta: { label: "Old label" } }, + colourRGB: { name: "colourRGB", type: "colourRGB" }, + colourTemperature: { name: "colourTemperature", type: "positiveInteger", value: 3000 }, + }, +}; + +/** The configuration template of {@link configuredLight}. */ +export const lightTemplate = { + version: 1, + assetType: "LightAsset", + attributes: { + brightness: { + type: "positiveInteger", + meta: { label: "Dimmer", readOnly: true, storeDataPoints: true, ruleState: true }, + }, + colourTemperature: { + type: "positiveInteger", + meta: { + label: "White tone", + constraints: [ + { type: "min", min: 2000 }, + { type: "max", max: 6500 }, + ], + }, + }, + onOff: { type: "boolean", meta: { label: "Power" } }, + }, +}; + +/** A hand edited template with an attribute that a light misses and one of another value type. */ +export const partlyImportableTemplate = { + version: 1, + assetType: "LightAsset", + attributes: { + brightness: { type: "positiveInteger", meta: { label: "Dimmer" } }, + colourTemperature: { type: "text", meta: { label: "White tone" } }, + dimLevel: { type: "number", meta: { label: "Dim level" } }, + }, +}; diff --git a/ui/component/or-asset-viewer/test/fixtures/index.ts b/ui/component/or-asset-viewer/test/fixtures/index.ts index 32ceba5199..9b9a3a6b4e 100644 --- a/ui/component/or-asset-viewer/test/fixtures/index.ts +++ b/ui/component/or-asset-viewer/test/fixtures/index.ts @@ -129,6 +129,31 @@ export class AssetViewer { } return configItemLocator; } + + /** + * Get a locator to the hidden file input of the configuration template import dialog. + */ + getConfigurationTemplateFileInput(): Locator { + return this.page.getByRole("dialog").locator("input[type=file]"); + } + + /** + * Get a locator to a section of a configuration template dialog by its title. + * @param title The section title, e.g. "Matched attributes" + */ + getConfigurationTemplateSection(title: string): Locator { + return this.page.getByRole("dialog").locator(".ac-card", { hasText: title }); + } + + /** + * Get a locator to an attribute row of a configuration template dialog by its label. + * @param section The section holding the row + * @param label The attribute label + */ + getConfigurationTemplateAttribute(section: Locator, label: string): Locator { + // The name carries the label and value type as its title, e.g. "Dimmer (Positive integer)" + return section.getByTitle(new RegExp(`^${label} \\(`)); + } } interface ComponentFixtures extends SharedComponentTestFixtures { From 0ac06766d9edc5826f95529e2014ac8485651b22 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Mon, 16 Nov 2026 16:27:12 +0100 Subject: [PATCH 17/21] Go back to the file selection from a rejected template --- .../test/configuration-template.test.ts | 34 ++++++++++++ .../fixtures/data/configuration-template.ts | 9 ++++ .../src/configuration-template.ts | 52 ++++++++++++++----- 3 files changed, 83 insertions(+), 12 deletions(-) diff --git a/ui/app/manager/test/configuration-template.test.ts b/ui/app/manager/test/configuration-template.test.ts index 18beb44fd0..9d5773d768 100644 --- a/ui/app/manager/test/configuration-template.test.ts +++ b/ui/app/manager/test/configuration-template.test.ts @@ -24,6 +24,7 @@ import { configuredLight, lightTemplate, partlyImportableTemplate, + pumpTemplate, targetLight, } from "./fixtures/data/configuration-template.js"; @@ -213,6 +214,39 @@ test("should reject a file that is not a configuration template", async ({ await expect(page.getByText("The selected file does not hold valid JSON.")).toBeVisible(); }); +/** + * @given A light to import into is set up in the "smartcity" realm + * @when Importing a template that shares no attribute with the light + * @then The import is rejected with the reason + * @when Going back + * @then Another file can be selected and previewed + */ +test("should go back to the file selection from a template that cannot be imported", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [targetLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await selectTemplateFile(page, assetViewer, "pumps.json", JSON.stringify(pumpTemplate)); + await expect( + page.getByText("None of the attributes in the selected file can be imported into this asset.") + ).toBeVisible(); + + // A rejected file used to offer only Close, so another file meant starting the import over + await page.getByRole("button", { name: "Back" }).click(); + await assetViewer.getConfigurationTemplateFileInput().setInputFiles({ + name: "lights.json", + mimeType: "application/json", + buffer: Buffer.from(JSON.stringify(lightTemplate)), + }); + await page.getByRole("dialog").getByRole("button", { name: "Next" }).click(); + + const matched = assetViewer.getConfigurationTemplateSection("Matched attributes"); + await expect(assetViewer.getConfigurationTemplateAttribute(matched, "Dimmer")).toBeVisible(); +}); + /** * @given An agent is set up in the "smartcity" realm * @when Opening the agent in modify mode diff --git a/ui/app/manager/test/fixtures/data/configuration-template.ts b/ui/app/manager/test/fixtures/data/configuration-template.ts index f2bca3dc3b..e030236556 100644 --- a/ui/app/manager/test/fixtures/data/configuration-template.ts +++ b/ui/app/manager/test/fixtures/data/configuration-template.ts @@ -98,3 +98,12 @@ export const partlyImportableTemplate = { dimLevel: { type: "number", meta: { label: "Dim level" } }, }, }; + +/** A template of another asset type, which shares no attribute with a light. */ +export const pumpTemplate = { + version: 1, + assetType: "PumpAsset", + attributes: { + flowRate: { type: "number", meta: { label: "Flow rate" } }, + }, +}; diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index a3f9ecc467..847ddff4d8 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -22,6 +22,7 @@ import { live } from "lit/directives/live.js"; import manager, { Util } from "@openremote/core"; import { AssetModelUtil, + ConfigurationTemplateImportFailure, WellknownMetaItems, type Asset, type Attribute, @@ -47,7 +48,11 @@ import { dialogRenderer, showDialog, } from "@openremote/or-vaadin-components/or-vaadin-dialog"; -import { showErrorDialog } from "@openremote/or-vaadin-components/or-vaadin-confirm-dialog"; +import { + getConfirmDialogContent, + showConfirmDialog, + showErrorDialog, +} from "@openremote/or-vaadin-components/or-vaadin-confirm-dialog"; import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar"; export type AssetAttributes = { [index: string]: Attribute }; @@ -463,7 +468,7 @@ async function previewImport( }); showImportPreviewDialog(host, asset, fileName, configuration, response.data, onImported, onBack); } catch (error) { - showImportFailureDialog(host, asset, configuration, error); + showImportFailureDialog(host, asset, configuration, error, onBack); } } @@ -544,24 +549,47 @@ function showImportPreviewDialog( ); } -/** Reports a document that cannot be imported, with whatever the server could tell about it. */ -function showImportFailureDialog(host: Node, asset: Asset, configuration: string, error: unknown) { +/** + * Reports a document that cannot be imported, with whatever the server could tell about it. A rejected file can be + * swapped for another one by going back. + */ +function showImportFailureDialog(host: Node, asset: Asset, configuration: string, error: unknown, onBack: () => void) { const preview = getFailurePreview(error); const forbidden = (error as { response?: { status?: number } })?.response?.status === 403; const message = preview ? i18next.t(`configurationTemplate.failure.${preview.failure}`) : i18next.t(forbidden ? "configurationTemplate.forbidden" : "errorOccurred"); const location = getFailureLocation(asset, preview?.failureLocation); + const content = html`${dialogStyle} +

+ ${message} + ${location ? html`${location}` : ``} + ${preview ? getSkippedTemplate(asset, preview, configuration) : ``} +
`; + + // Only a rejected file is helped by picking another one, not a changed asset, denied access or another error + if (!preview || preview.failure === ConfigurationTemplateImportFailure.DRAFT_MISMATCH) { + showErrorDialog(host, content, "configurationTemplate.importHeading"); + return; + } - showErrorDialog( + showConfirmDialog( host, - html`${dialogStyle} -
- ${message} - ${location ? html`${location}` : ``} - ${preview ? getSkippedTemplate(asset, preview, configuration) : ``} -
`, - "configurationTemplate.importHeading" + html` + + ${getConfirmDialogContent( + "error tertiary", + "configurationTemplate.importHeading", + content, + "close", + html` + onBack()}> + + + ` + )} + + ` ); } From 0a1e682b50bfbf1b368a69db8de816377dc5e9b7 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Tue, 17 Nov 2026 11:32:06 +0100 Subject: [PATCH 18/21] Wait for file step to close dialog in config template tests --- ui/AGENTS.md | 2 +- ui/app/manager/test/configuration-template.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ui/AGENTS.md b/ui/AGENTS.md index 3a455f9dbf..fe898e852d 100644 --- a/ui/AGENTS.md +++ b/ui/AGENTS.md @@ -95,7 +95,7 @@ Stories call `getORStorybookHelpers(tagName)` (from `ui/component/storybook-util - **Test Naming:** `test.describe` blocks describe a feature. Tests should be named starting with "should ...". - **Test Structure:** Keep tests flat by default. Omit top-level `test.describe` blocks. If grouping is needed, target a specific feature (e.g., filtering notifications) rather than a parent concept like the whole page. Example: `test.describe("Filter Notifications", ...)` instead of `test.describe("Notifications", ...)`. - **Regression Tests:** Every bug fix ships with a test that fails without it. Name it after the behaviour that should hold rather than the defect, and record what used to go wrong in a comment on the assertion that catches it. -- **Dialogs:** A Vaadin dialog renders its overlay in the top layer, so the `role="dialog"` host itself never counts as visible; assert on elements inside it, or use `toHaveCount`. Confirm dialogs have the role `alertdialog`. +- **Dialogs:** A Vaadin dialog renders its overlay in the top layer, so the `role="dialog"` host itself never counts as visible; assert on elements inside it, or use `toHaveCount`. A closed dialog stays in the page until its closing animation ends, so wait for it to go before locating a dialog again. Confirm dialogs have the role `alertdialog`. - **Translated text:** `getByText` cannot find text rendered by `or-translate`; locate the element with a `hasText` filter instead, or use role names, which do include it. ### Fixtures diff --git a/ui/app/manager/test/configuration-template.test.ts b/ui/app/manager/test/configuration-template.test.ts index 9d5773d768..2573cf2a68 100644 --- a/ui/app/manager/test/configuration-template.test.ts +++ b/ui/app/manager/test/configuration-template.test.ts @@ -47,6 +47,7 @@ async function selectTemplateFile(page: Page, assetViewer: AssetViewer, name: st .getConfigurationTemplateFileInput() .setInputFiles({ name, mimeType: "application/json", buffer: Buffer.from(content) }); await page.getByRole("dialog").getByRole("button", { name: "Next" }).click(); + await expect(page.getByRole("dialog").getByRole("button", { name: "Select file" })).toHaveCount(0); } /** From 317846dfd5e7c08abff087d733e0896ec663e1f8 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Wed, 18 Nov 2026 17:35:56 +0100 Subject: [PATCH 19/21] Rename ConfigurationItem to ConfigurationItemView --- .../or-asset-viewer/src/configuration-template.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 847ddff4d8..76c14c626f 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -58,7 +58,7 @@ import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar"; export type AssetAttributes = { [index: string]: Attribute }; /** A configuration item of an attribute as the rows show it. */ -interface ConfigurationItem { +interface ConfigurationItemView { label: string; /** The value in short, if it has one. */ value?: string; @@ -689,7 +689,7 @@ function getAttributeRowTemplate(asset: Asset, attribute: Attribute, lead:
- ${getConfigurationItems(asset, attribute).map( + ${getConfigurationItemViews(asset, attribute).map( (item) => html`
@@ -792,9 +792,9 @@ function attributeName(asset: Asset, attribute: Attribute): string { } /** The configuration items of an attribute that a template holds, sorted by label. */ -function getConfigurationItems(asset: Asset, attribute: Attribute): ConfigurationItem[] { +function getConfigurationItemViews(asset: Asset, attribute: Attribute): ConfigurationItemView[] { return Object.entries(getTemplateMeta(attribute)) - .map(([name, value]) => getConfigurationItem(asset, name, value)) + .map(([name, value]) => getConfigurationItemView(asset, name, value)) .sort((a, b) => a.label.localeCompare(b.label)); } @@ -803,7 +803,7 @@ function getConfigurationItems(asset: Asset, attribute: Attribute): Configu * short form as that, and any other list of plain values comma separated. Any other value only shows as formatted JSON, * through its JSON button, which a short form has as well. */ -function getConfigurationItem(asset: Asset, name: string, value: unknown): ConfigurationItem { +function getConfigurationItemView(asset: Asset, name: string, value: unknown): ConfigurationItemView { const label = Util.getMetaLabel(undefined, name, asset.type, false); if (value === null || typeof value !== "object") { From 87ee78edbee556019e4f821395575057959fa18b Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Wed, 18 Nov 2026 17:42:00 +0100 Subject: [PATCH 20/21] Test export and import by a restricted user --- .../assets/ConfigurationTemplateTest.groovy | 35 ++++++++++++++++--- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy index 7cf0f610f4..fe7903ef24 100644 --- a/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -24,6 +24,7 @@ import org.openremote.manager.setup.SetupService import org.openremote.model.asset.AssetResource import org.openremote.model.asset.ConfigurationTemplateImportPreview import org.openremote.model.asset.ConfigurationTemplateImportRequest +import org.openremote.model.asset.UserAssetLink import org.openremote.model.asset.impl.LightAsset import org.openremote.model.asset.impl.RoomAsset import org.openremote.model.attribute.Attribute @@ -280,22 +281,46 @@ class ConfigurationTemplateTest extends Specification implements ManagerContaine } } - def "Configuration template import requires asset write access"() { - given: "a configured asset in the realm of a user that can read but not write assets" + def "Configuration template export and import follow the asset access of the user"() { + given: "a configured asset in the building realm, linked to a restricted user that can read and write only its brightness" + def buildingRealm = keycloakTestSetup.realmBuilding.name def asset = adminResource.create(null, new LightAsset("Configured light") - .setRealm(keycloakTestSetup.realmBuilding.name) + .setRealm(buildingRealm) .addOrReplaceAttributes( new Attribute<>(LightAsset.BRIGHTNESS) .addMeta(new MetaItem<>(MetaItemType.LABEL, "Brightness")) + .addMeta(new MetaItem<>(MetaItemType.ACCESS_RESTRICTED_READ, true)) + .addMeta(new MetaItem<>(MetaItemType.ACCESS_RESTRICTED_WRITE, true)), + new Attribute<>(LightAsset.COLOUR_TEMPERATURE) + .addMeta(new MetaItem<>(MetaItemType.LABEL, "Colour temperature")) )) createdAssetIds.add(asset.id) + adminResource.createUserAssetLinks(null, [new UserAssetLink(buildingRealm, keycloakTestSetup.testuser3Id, asset.id)]) + + when: "the restricted user exports a configuration template of the asset" + def restrictedDocument = restrictedUserResource.exportConfigurationTemplate(null, asset.id, []) - when: "that user exports a configuration template of the asset" + then: "only the attribute it can read is exported, without its access metadata" + restrictedDocument.attributes.keySet() == ["brightness"] as Set + restrictedDocument.attributes.brightness.getMetaValue(MetaItemType.LABEL).orElse(null) == "Brightness" + restrictedDocument.attributes.brightness.getMetaValue(MetaItemType.ACCESS_RESTRICTED_READ).isEmpty() + + when: "the restricted user previews an import of that template into the asset" + def preview = restrictedUserResource.previewConfigurationTemplateImport(null, asset.id, + new ConfigurationTemplateImportRequest( + restrictedUserResource.get(null, asset.id), + ValueUtil.asJSON(restrictedDocument).orElseThrow())) + + then: "the attribute is importable" + preview.failure == null + preview.importableAttributes*.name == ["brightness"] + + when: "a user that can read but not write assets exports a configuration template of the asset" def document = readOnlyUserResource.exportConfigurationTemplate(null, asset.id, []) then: "the configuration is returned" document.version == 1 - document.attributes.keySet() == ["brightness"] as Set + document.attributes.keySet() == ["brightness", "colourTemperature"] as Set when: "the same user previews an import" readOnlyUserResource.previewConfigurationTemplateImport(null, asset.id, From 5c8f81e33f379b0023484c1e9c2f5048e633d749 Mon Sep 17 00:00:00 2001 From: Ekhorn Date: Wed, 18 Nov 2026 17:42:56 +0100 Subject: [PATCH 21/21] Use slotted dialog content and attribute bindings in config templates - Replace the deprecated dialog renderer directives with slotted content - Bind checked, indeterminate and modified as boolean attributes, and the template name as an attribute - Document template bindings in ui/AGENTS.md --- ui/AGENTS.md | 4 + .../src/configuration-template.ts | 333 ++++++++---------- ui/component/or-asset-viewer/src/index.ts | 2 +- 3 files changed, 153 insertions(+), 186 deletions(-) diff --git a/ui/AGENTS.md b/ui/AGENTS.md index fe898e852d..8d965d9528 100644 --- a/ui/AGENTS.md +++ b/ui/AGENTS.md @@ -26,6 +26,10 @@ Own Lit components extend `OrElement` from `@openremote/or-element` instead of ` A state change should re-render only the part it affects. Re-rendering a whole page, or a large component such as a table, flickers and discards the state that component holds: sort order, pagination, selection, scroll position. Keep those children mounted and update their properties. +## Template bindings + +Lit and Vaadin elements read their attributes into properties, so bind to the attribute: `?name=${...}` for a boolean, `name=${...}` or `name="..."` for a string or number. Bind `.name=${...}` only for objects, arrays, functions and properties without an attribute. Native form controls are the exception, as their `value` and `checked` attributes only set the initial state. + ## Spacing Avoid negative margins that cancel a container's padding. They repeat a value the container owns, so they break silently when it changes. Keep the content inside the padding, or add a theme variant to the container that turns it off. diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 76c14c626f..211d20bb77 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -16,7 +16,7 @@ * * SPDX-License-Identifier: AGPL-3.0-or-later */ -import { html, type TemplateResult } from "lit"; +import { html, render, type TemplateResult } from "lit"; import { createRef, ref, type Ref } from "lit/directives/ref.js"; import { live } from "lit/directives/live.js"; import manager, { Util } from "@openremote/core"; @@ -42,12 +42,7 @@ import "@openremote/or-vaadin-components/or-vaadin-dialog"; import "@openremote/or-vaadin-components/or-vaadin-text-field"; import type { OrVaadinButton } from "@openremote/or-vaadin-components/or-vaadin-button"; import type { OrVaadinCheckbox } from "@openremote/or-vaadin-components/or-vaadin-checkbox"; -import { - dialogFooterRenderer, - dialogHeaderRenderer, - dialogRenderer, - showDialog, -} from "@openremote/or-vaadin-components/or-vaadin-dialog"; +import { showDialog, type OrVaadinDialog } from "@openremote/or-vaadin-components/or-vaadin-dialog"; import { getConfirmDialogContent, showConfirmDialog, @@ -269,99 +264,88 @@ export function showExportConfigurationTemplateDialog(host: Node, asset: Asset) const selected = new Set(attributes.map((attribute) => attribute.name!)); let templateName = `${asset.name}-configuration-template.json`; - const exportBtn: Ref = createRef(); + const dialog: Ref = createRef(); - const updateExportBtn = () => { - if (exportBtn.value) { - exportBtn.value.disabled = selected.size === 0 || templateName.trim() === ""; + // Renders the dialog again into the container that showDialog made for it + const update = () => { + if (dialog.value?.parentElement) { + render(getDialogTemplate(), dialog.value.parentElement); } }; const onToggle = (names: string[], checked: boolean) => { names.forEach((name) => (checked ? selected.add(name) : selected.delete(name))); - updateExportBtn(); - dialog?.requestContentUpdate(); + update(); }; const onTemplateNameChange = (name: string) => { templateName = name; - updateExportBtn(); + update(); }; - const dialog = showDialog( - host, - html` - getHeaderTemplate("configurationTemplate.exportHeading", () => dialog?.close()))} - ${dialogRenderer( - () => html` - ${dialogStyle} -
- -
- ) => onTemplateNameChange(ev.detail.value)} - > -
-
- - 0 && selected.size < attributes.length)} - @change=${(ev: Event) => - onToggle( - attributes.map((attribute) => attribute.name!), - (ev.currentTarget as OrVaadinCheckbox).checked - )} - > -
- ${attributes.map((attribute) => - getAttributeRowTemplate( - asset, - attribute, - html` - - onToggle([attribute.name!], (ev.currentTarget as OrVaadinCheckbox).checked)} - > - - - ` - ) - )} -
-
-
- ` - )} - ${dialogFooterRenderer( - () => html` -
- dialog?.close()}> - - - { - dialog?.close(); - downloadConfigurationTemplate(asset, Array.from(selected), templateName); - }} - > - - -
- ` - )} - >
- ` - ); + const getDialogTemplate = () => html` + + ${dialogStyle} ${getHeaderTemplate("configurationTemplate.exportHeading", () => dialog.value?.close())} +
+ +
+ ) => onTemplateNameChange(ev.detail.value)} + > +
+
+ + 0 && selected.size < attributes.length)} + @change=${(ev: Event) => + onToggle( + attributes.map((attribute) => attribute.name!), + (ev.currentTarget as OrVaadinCheckbox).checked + )} + > +
+ ${attributes.map((attribute) => + getAttributeRowTemplate( + asset, + attribute, + html` + + onToggle([attribute.name!], (ev.currentTarget as OrVaadinCheckbox).checked)} + > + + + ` + ) + )} +
+
+
+
+ dialog.value?.close()}> + + + { + dialog.value?.close(); + downloadConfigurationTemplate(asset, Array.from(selected), templateName); + }} + > + + +
+
+ `; + + showDialog(host, getDialogTemplate()); } /** @@ -407,47 +391,37 @@ export function showImportConfigurationTemplateDialog( const dialog = showDialog( host, html` - getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close()))} - ${dialogRenderer( - () => html` - ${dialogStyle} -
- -
-
- onFileSelected()} - /> - fileInput.value?.click()}> - - - - ${file ? file.name : i18next.t("configurationTemplate.noFileSelected")} - -
-
-
- ` - )} - ${dialogFooterRenderer( - () => html` -
- dialog?.close()}> - - - onNext()}> - + + ${dialogStyle} ${getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close())} +
+ +
+
+ onFileSelected()} + /> + fileInput.value?.click()}> + + + ${file ? file.name : i18next.t("configurationTemplate.noFileSelected")} +
- ` - )} - > +
+
+
+ dialog?.close()}> + + + onNext()}> + + +
+
` ); } @@ -488,63 +462,53 @@ function showImportPreviewDialog( const dialog = showDialog( host, html` - getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close()))} - ${dialogRenderer( - () => html` - ${dialogStyle} -
- ${fileName} -
- - -
-
- -
- ${importable.map((summary) => { - const attribute = { ...patchedAttributes[summary.name!], name: summary.name }; - return getAttributeRowTemplate( - asset, - attribute, - html` - - ${getAttributeNameTemplate(asset, attribute)} - ` - ); - })} -
-
- ${getSkippedTemplate(asset, preview, configuration)} -
- ` - )} - ${dialogFooterRenderer( - () => html` -
- { - dialog?.close(); - onBack(); - }} - > - - - { - dialog?.close(); - onImported(patchedAttributes); - }} - > - - + + ${dialogStyle} ${getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close())} +
+ ${fileName} +
+ + +
+
+ +
+ ${importable.map((summary) => { + const attribute = { ...patchedAttributes[summary.name!], name: summary.name }; + return getAttributeRowTemplate( + asset, + attribute, + html` + + ${getAttributeNameTemplate(asset, attribute)} + ` + ); + })}
- ` - )} - > +
+ ${getSkippedTemplate(asset, preview, configuration)} +
+
+ { + dialog?.close(); + onBack(); + }} + > + + + { + dialog?.close(); + onImported(patchedAttributes); + }} + > + + +
+
` ); } @@ -629,8 +593,7 @@ function getFailureLocation( function getHeaderTemplate(titleKey: string, onClose: () => void): TemplateResult { return html` - ${dialogStyle} -
+

onClose()}> diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.ts index b6783b51a7..71f2f5179c 100644 --- a/ui/component/or-asset-viewer/src/index.ts +++ b/ui/component/or-asset-viewer/src/index.ts @@ -1487,7 +1487,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(OrEleme if (editMode) { content = html`
- +
`;