diff --git a/AGENTS.md b/AGENTS.md index 6ac738d51f..a5c524c0c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,12 +30,24 @@ 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`. Spock snapshots are stored under `model/src/test/resources/snapshots`. Rewrite them with `./gradlew :model:test -PupdateSnapshots` and review the resulting diff, since a mismatch is only reported as a test failure otherwise. +## 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 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..048a5f4af0 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,87 @@ 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. 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") + @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. 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 + @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 and, where known, the location within the template. + */ + @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. 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( + 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 and failureLocation, where known, the attribute, metadata item and parameter", + 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..215de70ed0 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfiguration.java @@ -0,0 +1,42 @@ +/* + * 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 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 + * 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 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() { + 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..00b59a076a --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationSummary.java @@ -0,0 +1,27 @@ +/* + * 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 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 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 new file mode 100644 index 0000000000..51056c2dc1 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/AttributeConfigurationTypeMismatch.java @@ -0,0 +1,31 @@ +/* + * 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 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 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/asset/ConfigurationTemplate.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java new file mode 100644 index 0000000000..334af7e7c9 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplate.java @@ -0,0 +1,66 @@ +/* + * 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; +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( + int version, String assetType, 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..eb3a7aaafe --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportFailure.java @@ -0,0 +1,47 @@ +/* + * 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, + + /** 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, + + /** The submitted draft no longer identifies the persisted target asset. */ + DRAFT_MISMATCH +} 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 new file mode 100644 index 0000000000..5493ed887d --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportPreview.java @@ -0,0 +1,119 @@ +/* + * 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; +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 + * 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 = "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; + + @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 = + "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.") + protected AttributeMap patchedAttributes; + + @JsonCreator + public ConfigurationTemplateImportPreview( + ConfigurationTemplateImportFailure failure, + ConfigurationTemplateImportFailureLocation failureLocation, + 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; + } + + public static ConfigurationTemplateImportPreview failed( + ConfigurationTemplateImportFailure failure) { + return failed(failure, null); + } + + public static ConfigurationTemplateImportPreview failed( + ConfigurationTemplateImportFailure failure, + ConfigurationTemplateImportFailureLocation failureLocation) { + return new ConfigurationTemplateImportPreview( + failure, failureLocation, List.of(), List.of(), List.of(), List.of(), null); + } + + public ConfigurationTemplateImportFailure getFailure() { + return failure; + } + + public ConfigurationTemplateImportFailureLocation getFailureLocation() { + return failureLocation; + } + + public List getImportableAttributes() { + return importableAttributes; + } + + public List getMissingAttributes() { + return missingAttributes; + } + + 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/asset/ConfigurationTemplateImportRequest.java b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java new file mode 100644 index 0000000000..dc4c6189f3 --- /dev/null +++ b/model/src/main/java/org/openremote/model/asset/ConfigurationTemplateImportRequest.java @@ -0,0 +1,52 @@ +/* + * 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; +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(Asset draft, 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/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 new file mode 100644 index 0000000000..79cd80b15e --- /dev/null +++ b/model/src/main/java/org/openremote/model/util/ConfigurationTemplateUtil.java @@ -0,0 +1,410 @@ +/* + * 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 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 jakarta.validation.ConstraintViolation; +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.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; +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; +import org.openremote.model.attribute.MetaItem; +import org.openremote.model.attribute.MetaMap; + +/** + * 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 { + + /** + * 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()); + + /** 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() {} + + /** + * Builds the export document of an asset, holding the type and metadata of every attribute that + * 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 -> { + MetaMap meta = withoutAssetBoundMeta(attribute.getMeta()); + + if (!meta.isEmpty()) { + attributes.put( + attribute.getName(), new AttributeConfiguration(typeName(attribute), meta)); + } + }); + } + + 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, except for {@link #ASSET_BOUND_META_ITEMS}, + * 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 + * agent link. + */ + 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); + } + + 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 (!version.isIntegralNumber() || version.asInt() != ConfigurationTemplate.CURRENT_VERSION) { + return ConfigurationTemplateImportPreview.failed(UNSUPPORTED_VERSION); + } + if (!assetType.isTextual() || assetType.asText().isBlank()) { + return failed(MISSING_REQUIRED_FIELD, null, null, "assetType"); + } + if (!attributes.isObject()) { + 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()) { + 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 failed(MALFORMED_ATTRIBUTE_ENTRY, attribute, null, "type"); + } + if (meta == null || !meta.isObject()) { + return failed(MALFORMED_ATTRIBUTE_ENTRY, attribute, null, "meta"); + } + + try { + imported.put(attribute, new AttributeConfiguration(type.asText(), readMeta(meta))); + } catch (InvalidMetaItemException e) { + return failed(INVALID_META_ITEM, attribute, e.metaItem, e.parameter); + } + } + + AttributeMap targetAttributes = + draft.getAttributes() != null ? draft.getAttributes() : new AttributeMap(); + 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) -> { + Optional> target = targetAttributes.get(name); + + if (target.isEmpty()) { + missing.add(new AttributeConfigurationSummary(name, configuration.type())); + 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)) { + typeMismatches.add( + new AttributeConfigurationTypeMismatch(name, configuration.type(), targetType)); + return; + } + + importable.add(new AttributeConfigurationSummary(name, configuration.type())); + }); + + // Report what was skipped even when that leaves nothing to import + if (importable.isEmpty()) { + return new ConfigurationTemplateImportPreview( + NO_IMPORTABLE_ATTRIBUTES, null, importable, missing, typeMismatches, custom, null); + } + + Asset patchedDraft = ValueUtil.clone(draft); + importable.forEach( + summary -> { + Attribute patched = patchedDraft.getAttributes().get(summary.name()).orElseThrow(); + MetaMap meta = imported.get(summary.name()).getMeta(); + + if (patched.getMeta() != null) { + ASSET_BOUND_META_ITEMS.forEach( + name -> patched.getMeta().get(name).ifPresent(item -> meta.addOrReplace(item))); + } + patched.setMeta(meta); + }); + + Set importableNames = + importable.stream().map(AttributeConfigurationSummary::name).collect(Collectors.toSet()); + Optional rejected = + rejectedOnSave(draft, patchedDraft, importableNames); + + return rejected.orElseGet( + () -> + new ConfigurationTemplateImportPreview( + null, + null, + importable, + missing, + typeMismatches, + custom, + 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( + ConfigurationTemplateImportFailure failure, + String attribute, + String metaItem, + String parameter) { + return ConfigurationTemplateImportPreview.failed( + failure, new ConfigurationTemplateImportFailureLocation(attribute, metaItem, parameter)); + } + + private static boolean isAbsent(JsonNode node) { + return node == null || node.isNull(); + } + + private static MetaMap withoutAssetBoundMeta(MetaMap meta) { + MetaMap result = meta != null ? new MetaMap(meta) : new MetaMap(); + ASSET_BOUND_META_ITEMS.forEach(result::remove); + 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 + * must hold a value of its type that meets the constraints of that type. + */ + private static MetaMap readMeta(JsonNode node) throws InvalidMetaItemException { + ObjectNode items = node.deepCopy(); + items.remove(ASSET_BOUND_META_ITEMS); + MetaMap meta; + + 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); + } + + for (MetaItem item : meta.values()) { + Optional violation = + ValueUtil.validate(item).stream() + .map(constraintViolation -> constraintViolation.getPropertyPath().toString()) + .sorted() + .findFirst(); + + if (violation.isPresent()) { + throw new InvalidMetaItemException(item.getName(), valueParameter(violation.get())); + } + + Object value = item.getValue().orElse(null); + + 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(List references) { + StringBuilder path = new StringBuilder(); + + for (JsonMappingException.Reference reference : references) { + if (reference.getFieldName() != null) { + path.append(path.isEmpty() ? "" : ".").append(reference.getFieldName()); + } else if (reference.getIndex() >= 0) { + path.append('[').append(reference.getIndex()).append(']'); + } + } + return path.isEmpty() ? null : path.toString(); + } + + /** + * 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. + */ + private 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()); + } + + 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/attribute/MetaMapTest.groovy b/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy new file mode 100644 index 0000000000..6e4a681f43 --- /dev/null +++ b/model/src/test/groovy/org/openremote/model/attribute/MetaMapTest.groovy @@ -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.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 new file mode 100644 index 0000000000..cdc08dc272 --- /dev/null +++ b/model/src/test/groovy/org/openremote/model/util/ConfigurationTemplateUtilTest.groovy @@ -0,0 +1,396 @@ +/* + * 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.asset.impl.WeatherAsset +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 + +import static org.openremote.model.asset.ConfigurationTemplateImportFailure.* + +class ConfigurationTemplateUtilTest extends Specification { + + def setupSpec() { + ValueUtil.initialise(null) + } + + /** 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 + } + + 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(",")}}" + } + + 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 = weatherAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", unknownMetaItem: [nested: 1]]), + rainfall : attribute("rainfall", ValueType.POSITIVE_NUMBER) + ]) + + 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 == 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 + exported.attributes.temperature.type == ValueType.NUMBER.name + 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"() { + given: "an asset with two configured attributes" + def asset = weatherAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature"]), + 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 = weatherAsset([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"}}}']) + 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 = 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" + 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 = 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" + 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 = weatherAsset([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" + 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"() { + expect: "the rejection holds no location" + ConfigurationTemplateUtil.preview(weatherAsset(), 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 = weatherAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.ACCESS_PUBLIC_WRITE.name): true]), + rainfall : attribute("rainfall", ValueType.POSITIVE_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.keySet() == [MetaItemType.LABEL.name] as Set + + 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 = 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, [ + temperature: '{"type": "number", "meta": {"label": "Imported", "accessPublicWrite": true, "attributeLinks": []}}' + ])) + + then: "the other metadata is 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) + !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"() { + given: "an asset without the imported attribute" + 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, [ + 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 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 = 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, [ + 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 = 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, [ + 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 = 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, [ + 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 = weatherAsset([ + temperature: attribute("temperature", ValueType.NUMBER, [(MetaItemType.LABEL.name): "Temperature", (MetaItemType.READ_ONLY.name): true]), + 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"]}}', + notes : '{"type": "text", "meta": {"label": "Notes"}}' + ])) + + then: "the imported metadata replaces the existing metadata entirely" + 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("notes").get().getMetaValue(MetaItemType.LABEL).orElse(null) == "Notes" + + and: "the type and the value of the attribute are untouched" + 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) + !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 = 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, [ + 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().getMetaValue(MetaItemType.LABEL).orElse(null) == "Imported" + } +} 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..16a867b665 --- /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.AttributeDescriptor; +import org.openremote.model.value.ValueConstraint; +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 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 { + + 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))), + new Attribute<>(PumpAsset.ERROR_CODE) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Error code"), + new MetaItem<>(RULE_STATE, true), + new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(simulator1AgentId))), + new Attribute<>(PumpAsset.SERIAL_NUMBER) + .addOrReplaceMeta( + new MetaItem<>(LABEL, "Serial number"), + new MetaItem<>(READ_ONLY, true), + 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<>(PumpAsset.ERROR_CODE), new Attribute<>(PumpAsset.SERIAL_NUMBER)); + assetStorageService.merge(bare); + + // 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); + assetStorageService.merge(partial); + + // 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<>("running", BOOLEAN)); + assetStorageService.merge(otherType); + + // One attribute per agent link type; "(requirements)" marks links with fields that must be set + AgentLinksAsset agentLinks = new AgentLinksAsset("Agent links (all types)"); + agentLinks.setRealm(MASTER_REALM); + agentLinks.addOrReplaceAttributes( + linked( + AgentLinksAsset.BLUETOOTH_MESH, + "Bluetooth mesh (requirements)", + new BluetoothMeshAgentLink(bluetoothMeshAgentId, 0, "0002", "GenericOnOffServer")), + linked(AgentLinksAsset.DEFAULT, "Default", new DefaultAgentLink(tcpAgentId)), + linked(AgentLinksAsset.HTTP, "HTTP (requirements)", new HTTPAgentLink(httpAgentId)), + linked( + AgentLinksAsset.KNX, + "KNX (requirements)", + new KNXAgentLink(knxAgentId, "1.001", "1/0/1", "1/0/2")), + linked(AgentLinksAsset.MAIL, "Mail", new MailAgentLink(mailAgentId)), + linked(AgentLinksAsset.MODBUS, "Modbus", new ModbusAgentLink(modbusAgentId)), + linked(AgentLinksAsset.MQTT, "MQTT", new MQTTAgentLink(mqttAgentId)), + linked( + AgentLinksAsset.OPEN_WEATHER_MAP, + "OpenWeatherMap (requirements)", + new OpenWeatherMapAgentLink(openWeatherMapAgentId) + .setWeatherProperty(OpenWeatherMapProperty.TEMPERATURE)), + linked(AgentLinksAsset.SIMULATOR, "Simulator", new SimulatorAgentLink(simulator1AgentId)), + linked( + AgentLinksAsset.SNMP, + "SNMP (requirements)", + new SNMPAgentLink(snmpAgentId, "1.3.6.1.2.1.1.3.0")), + linked( + AgentLinksAsset.VELBUS, + "Velbus (requirements)", + new VelbusAgentLink(velbusAgentId, 48, "CH1")), + linked(AgentLinksAsset.WEBSOCKET, "Websocket", new WebsocketAgentLink(websocketAgentId)), + linked(AgentLinksAsset.Z_WAVE, "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( + 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/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/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/ui/component/or-map/src/controls/styles.ts b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java similarity index 69% rename from ui/component/or-map/src/controls/styles.ts rename to setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java index 97067430b5..62c670e154 100644 --- a/ui/component/or-map/src/controls/styles.ts +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/ConfigTemplateAssetModelProvider.java @@ -16,14 +16,15 @@ * * SPDX-License-Identifier: AGPL-3.0-or-later */ -import { css } from "lit"; +package org.openremote.setup.configtemplate.model; -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); +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/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 new file mode 100644 index 0000000000..e31ec1034d --- /dev/null +++ b/setup/src/config-template/java/org/openremote/setup/configtemplate/model/PumpAsset.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.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); + // 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); + + /** 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 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..fe7903ef24 --- /dev/null +++ b/test/src/test/groovy/org/openremote/test/assets/ConfigurationTemplateTest.groovy @@ -0,0 +1,385 @@ +/* + * 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.UserAssetLink +import org.openremote.model.asset.impl.LightAsset +import org.openremote.model.asset.impl.RoomAsset +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.Shared +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 { + + @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()) + keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class) + managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class) + def buildingRealm = keycloakTestSetup.realmBuilding.name + + 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) + + // 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) + + // 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 LightAsset("Configuration source") + .setRealm(keycloakTestSetup.realmMaster.name) + .addOrReplaceAttributes( + 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")) + )) + def target = adminResource.create(null, new LightAsset("Configuration target") + .setRealm(keycloakTestSetup.realmMaster.name) + .addOrReplaceAttributes( + 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 that the asset type defines and that hold metadata are exported, with their type and metadata" + document.version == 1 + 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, ["brightness"]) + + then: "only the requested attribute is exported" + subset.attributes.keySet() == ["brightness"] as Set + + when: "only an attribute without metadata is selected" + adminResource.exportConfigurationTemplate(null, source.id, ["onOff"]) + + 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: "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: "both attributes are importable and nothing is skipped" + preview.failure == null + 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("brightness").get() + patched.getMetaValue(MetaItemType.LABEL).orElse(null) == "Source brightness" + patched.getMetaValue(MetaItemType.READ_ONLY).orElse(false) + 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("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, + 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 a configuration item that breaks a constraint is imported" + adminResource.previewConfigurationTemplateImport(null, target.id, + 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() + 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 == "brightness" + assert rejected.failureLocation.metaItem == MetaItemType.FORECAST.name + assert rejected.failureLocation.parameter == "pastCount" + 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": "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() + 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 == "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": "LightAsset", "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: "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())) + + 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" + adminResource.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 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(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, []) + + 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", "colourTemperature"] as Set + + when: "the same user previews an import" + readOnlyUserResource.previewConfigurationTemplateImport(null, asset.id, + new ConfigurationTemplateImportRequest( + readOnlyUserResource.get(null, asset.id), + 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: "a document, which is never read as access is checked first" + def document = '{"version": 1, "assetType": "RoomAsset", "attributes": {}}' + def buildingRealm = keycloakTestSetup.realmBuilding.name + + 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)) + + then: "access is forbidden" + WebApplicationException otherRealm = thrown() + otherRealm.response.withCloseable { r -> + assert r.status == FORBIDDEN.statusCode + return true + } + + 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)) + + 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/AGENTS.md b/ui/AGENTS.md index 50e980b10b..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. @@ -95,6 +99,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`. 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 @@ -108,6 +114,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 new file mode 100644 index 0000000000..2573cf2a68 --- /dev/null +++ b/ui/app/manager/test/configuration-template.test.ts @@ -0,0 +1,278 @@ +/* + * 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, 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, + pumpTemplate, + 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(); + await expect(page.getByRole("dialog").getByRole("button", { name: "Select file" })).toHaveCount(0); +} + +/** + * @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 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 + * @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 + * @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/manager/test/fixtures/data/configuration-template.ts b/ui/app/manager/test/fixtures/data/configuration-template.ts new file mode 100644 index 0000000000..e030236556 --- /dev/null +++ b/ui/app/manager/test/fixtures/data/configuration-template.ts @@ -0,0 +1,109 @@ +/* + * 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" } }, + }, +}; + +/** 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/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json index 8acec2bd37..a667d71065 100644 --- a/ui/app/shared/locales/en/or.json +++ b/ui/app/shared/locales/en/or.json @@ -1336,5 +1336,47 @@ } } } + }, + "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", + "saveBeforeImport": "Save the asset before importing", + "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.", + "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": { + "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 a9a6459ab8..0c40efbfc3 100644 --- a/ui/app/shared/locales/nl/or.json +++ b/ui/app/shared/locales/nl/or.json @@ -1322,5 +1322,44 @@ } } } + }, + "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", + "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", + "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.", + "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": { + "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 new file mode 100644 index 0000000000..211d20bb77 --- /dev/null +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -0,0 +1,812 @@ +/* + * 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, 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"; +import { + AssetModelUtil, + ConfigurationTemplateImportFailure, + WellknownMetaItems, + type Asset, + type Attribute, + type ConfigurationTemplateImportFailureLocation, + 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 { showDialog, type OrVaadinDialog } from "@openremote/or-vaadin-components/or-vaadin-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 }; + +/** A configuration item of an attribute as the rows show it. */ +interface ConfigurationItemView { + 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` + +`; + +/** 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. 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())); +} + +/** 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 dialog: Ref = createRef(); + + // 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))); + update(); + }; + + const onTemplateNameChange = (name: string) => { + templateName = name; + update(); + }; + + 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()); +} + +/** + * 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` + + ${dialogStyle} ${getHeaderTemplate("configurationTemplate.importHeading", () => dialog?.close())} +
+ +
+
+ onFileSelected()} + /> + fileInput.value?.click()}> + + + + ${file ? file.name : i18next.t("configurationTemplate.noFileSelected")} + +
+
+
+
+ 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, onBack); + } +} + +/** 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: AssetAttributes = preview.patchedAttributes || {}; + const importable = preview.importableAttributes || []; + + const dialog = showDialog( + host, + html` + + ${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); + }} + > + + +
+
+ ` + ); +} + +/** + * 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; + } + + showConfirmDialog( + host, + html` + + ${getConfirmDialogContent( + "error tertiary", + "configurationTemplate.importHeading", + content, + "close", + html` + onBack()}> + + + ` + )} + + ` + ); +} + +/** + * 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 +): string | undefined { + if (!location?.attribute && !location?.parameter) { + return undefined; + } + const parts: string[] = []; + + if (location.attribute) { + const name = attributeName(asset, { name: location.attribute }); + parts.push(i18next.t("configurationTemplate.failureLocation.attribute", { name })); + } + if (location.metaItem) { + const name = Util.getMetaLabel(undefined, location.metaItem, asset.type, false); + parts.push(i18next.t("configurationTemplate.failureLocation.configurationItem", { name })); + } + // 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 { + return html` +
+

+ 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!), + ...(preview.customAttributes || []).map((attribute) => attribute.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(getTemplateMeta(attribute)).length} + + + +
+
+ ${getConfigurationItemViews(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 getConfigurationItemViews(asset: Asset, attribute: Attribute): ConfigurationItemView[] { + return Object.entries(getTemplateMeta(attribute)) + .map(([name, value]) => getConfigurationItemView(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 getConfigurationItemView(asset: Asset, name: string, value: unknown): ConfigurationItemView { + 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..71f2f5179c 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..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 @@ -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,50 @@ 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; + } + + // 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()} + > + + + + 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-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 { 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/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;