diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index b6d01d3342..287c50b84d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -39,9 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; -import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; -import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; -import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; +import org.thingsboard.server.service.iot_hub.DevicePackageService; +import org.thingsboard.server.service.iot_hub.DevicePackageRequest; +import org.thingsboard.server.service.iot_hub.DevicePackageResult; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallPlan; @@ -58,7 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService; public class IotHubController extends BaseController { private final IotHubService iotHubService; - private final DevicePackageUpdateService devicePackageUpdateService; + private final DevicePackageService devicePackageService; private final IotHubInstalledItemService iotHubInstalledItemService; private final DeviceConnectivityService deviceConnectivityService; private final SystemSecurityService systemSecurityService; @@ -103,21 +103,29 @@ public class IotHubController extends BaseController { return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/device/install") + @ResponseBody + public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException { + checkAllPermissions(); + return devicePackageService.install(getCurrentUser(), request); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") @ResponseBody public List checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); + return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/installedItems/{installedItemId}/deviceUpdate") @ResponseBody - public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, - @RequestBody DeviceUpdateRequest request) throws ThingsboardException { + public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId, + @RequestBody DevicePackageRequest request) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); + return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @@ -146,6 +154,25 @@ public class IotHubController extends BaseController { return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); } + /** + * The installed items with an update in IoT Hub. The body is what the browser got from IoT Hub on Check for updates: + * the published version id by item id. A POST, as the map of a tenant with many items doesn't fit in a URL. + */ + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/installedItems/withUpdates") + @ResponseBody + public PageData getInstalledItemsWithUpdates(@RequestParam int pageSize, + @RequestParam int page, + @RequestParam(required = false) String textSearch, + @RequestParam(required = false) String sortProperty, + @RequestParam(required = false) String sortOrder, + @RequestParam(required = false) List itemTypes, + @RequestBody Map publishedVersionIds) throws ThingsboardException { + checkAllPermissions(); + PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/count") @ResponseBody diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java similarity index 72% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java index f4604beea4..ac998aae5a 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java @@ -16,10 +16,13 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.GroupEntity; +import org.thingsboard.server.common.data.HasCustomerId; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasVersion; @@ -30,14 +33,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; @@ -66,6 +72,7 @@ import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -86,18 +93,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Applies an update of an installed device package in one transaction. The install wizard resolves the templates - * of the new version (the same way it installs them) and sends the entity of each step; this service checks the - * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a - * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a - * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, - * are written after commit too. + * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the + * templates of the version and sends the entity of each step; this service checks the plan, saves every entity + * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors, + * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control + * and the attributes, which aren't transactional, are written after commit too. */ @Service @TbCoreComponent @Slf4j @RequiredArgsConstructor -public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { +public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService { // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} private static final Map STEP_ALIASES = Map.of( @@ -110,7 +116,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i "DOWNLINK_CONVERTER", "downlinkConverter", "INTEGRATION", "integration"); private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); - private static final String UNEXPECTED_ERROR = "Failed to update the device package"; + private static final String UNEXPECTED_ERROR = "Failed to save the device package"; private final IotHubInstalledItemService installedItemService; private final IotHubRestClient iotHubRestClient; @@ -129,6 +135,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private final AttributesService attributesService; private final TelemetrySubscriptionService telemetryService; private final TransactionTemplate transactionTemplate; + private final ProjectInfo projectInfo; @Override public List check(SecurityUser user, IotHubInstalledItemId installedItemId) { @@ -162,33 +169,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } @Override - public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { + public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Installing device package version {}", tenantId, request.getVersionId()); + DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> { + if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) { + throw new IllegalArgumentException("Invalid install request"); + } + Placement placement = placement(tenantId, request); + JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + // The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation + DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor(); + validateInstallSteps(request); + validate(tenantId, previous, request); + return transactionTemplate.execute(status -> { + Applied applied = applySteps(tenantId, previous, request, null, placement); + IotHubInstalledItem installedItem = new IotHubInstalledItem(); + installedItem.setTenantId(tenantId); + installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText())); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setItemType("DEVICE"); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + reportInstall(user, request.getVersionId()); + log.info("[{}] Installed device package version {}", tenantId, request.getVersionId()); + } + return result; + } + + @Override + public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) { TenantId tenantId = user.getTenantId(); log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - Applied applied; - try { + DevicePackageResult result = apply(user, "update of " + installedItemId, () -> { DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { throw new IllegalArgumentException("The version belongs to another item"); } - validatePlan(devicePackage, request); - checkFeatures(tenantId, request); - validateIntegrations(tenantId, request); - applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); + validate(tenantId, devicePackage.descriptor(), request); + return transactionTemplate.execute(status -> { + IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); + Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + } + return result; + } + + /** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */ + private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) { + TenantId tenantId = user.getTenantId(); + Applied applied; + try { + applied = change.apply(); } catch (StepFailure e) { - log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); - return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); + log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause()); + return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey); } catch (RestClientException e) { - log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); - return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); + log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e); + return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null); } catch (Exception e) { - log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); - return DeviceUpdateResult.error(userMessage(e), null); + log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e); + return DevicePackageResult.error(userMessage(e), null); } afterCommit(user, tenantId, applied); - log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); + return DevicePackageResult.success(applied.descriptor(), applied.outputs()); + } + + /** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */ + private void reportInstall(SecurityUser user, String versionId) { + TenantId tenantId = user.getTenantId(); + try { + InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(), + projectInfo.getProjectVersion(), projectInfo.getProductType()); + iotHubRestClient.reportVersionInstalled(versionId, report); + } catch (Exception e) { + log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage()); + } + } + + /** + * At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or + * gateway is never overwritten: its credentials are what its firmware uses. + */ + private static void validateInstallSteps(DevicePackageRequest request) { + if (request.getSteps() == null) { + return; + } + for (DevicePackageRequest.Step step : request.getSteps()) { + boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); + if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution())) + || (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) { + throw new IllegalArgumentException("Invalid install step: " + step.getName()); + } + } + } + + /** + * The customer and the device group the install was opened from; each must be the tenant's. The group's own + * permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources. + */ + private Placement placement(TenantId tenantId, DevicePackageRequest request) { + CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId()) + ? new CustomerId(request.getCustomerId()) : null; + if (customerId != null && !isTenantsCustomer(tenantId, customerId)) { + throw new IllegalArgumentException("Invalid install request"); + } + if (request.getEntityGroupId() == null) { + return new Placement(customerId, customerId, null); + } + EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId())); + EntityId owner = group != null ? group.getOwnerId() : null; + boolean tenants = owner != null && (tenantId.equals(owner) + || (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId())))); + if (group == null || group.getType() != EntityType.DEVICE || !tenants) { + throw new IllegalArgumentException("Invalid install request"); + } + // As a device saved into a group: with no customer given, a new one goes to the group's customer + CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId; + return new Placement(customerId, deviceCustomerId, group); + } + + private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) { + Customer customer = customerService.findCustomerById(tenantId, customerId); + return customer != null && tenantId.equals(customer.getTenantId()); + } + + /** + * Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without + * a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale. + */ + private static void assignCustomer(GroupEntity entity, CustomerId customerId, GroupEntity current, DevicePackageRequest.Step step) { + if (customerId != null) { + entity.setOwnerId(customerId); + } + if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) { + throw new IllegalArgumentException(step.getName() + " belongs to another owner"); + } + } + + /** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */ + private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception { + validatePlan(ownedIds(previous), request); + checkFeatures(tenantId, request); + validateIntegrations(tenantId, request); } private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { @@ -201,50 +343,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** - * The update may only change what the package owns, or what the user confirmed. The device and the gateway, + * The device package may only change what it owns, or what the user confirmed. Its own device and gateway, * whose credentials the firmware uses, are never changed. */ - private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { + private void validatePlan(Set ownedIds, DevicePackageRequest request) { if (request.getSteps() == null || request.getSteps().isEmpty()) { - throw new IllegalArgumentException("The update has no steps"); + throw new IllegalArgumentException("The device package has no steps"); } - Set ownedIds = ownedIds(devicePackage.descriptor()); // A form's values are saved under its key too, so an entity step may not share it Set stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { - throw new IllegalArgumentException("Invalid update step: " + step.getName()); + throw new IllegalArgumentException("Invalid step: " + step.getName()); } if (!stateKeys.add(step.stateKey())) { - throw new IllegalArgumentException("Duplicate update step: " + step.stateKey()); + throw new IllegalArgumentException("Duplicate step: " + step.stateKey()); } boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); switch (step.getAction()) { case KEEP, OVERWRITE -> { if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { - throw new IllegalArgumentException("No entity for update step: " + step.getName()); + throw new IllegalArgumentException("No entity for step: " + step.getName()); } boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && !owned && !step.isConfirmed() && !"GATEWAY_CONNECTOR".equals(step.getType())) { throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); } - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway && owned) { throw new IllegalArgumentException("The device and its credentials don't change on update"); } } case CREATE -> { } } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { - throw new IllegalArgumentException("No entity data for update step: " + step.getName()); + if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { + throw new IllegalArgumentException("No entity data for step: " + step.getName()); } } } /** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ - private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { - boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP + private void checkFeatures(TenantId tenantId, DevicePackageRequest request) { + boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); if (savesIntegrations) { subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); @@ -252,13 +393,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** The configuration of an integration is checked by a remote call, so before the transaction. */ - private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { - for (DeviceUpdateRequest.Step step : request.getSteps()) { - if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { + private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception { + for (DevicePackageRequest.Step step : request.getSteps()) { + if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) { continue; } ObjectNode body = step.getEntity().deepCopy(); - // Converters this update creates have no id yet; the configuration doesn't depend on them + // Converters the request creates have no id yet; the configuration doesn't depend on them body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); Integration integration = JacksonUtil.treeToValue(body, Integration.class); integration.setTenantId(tenantId); @@ -274,9 +415,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { - IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); - DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + /** + * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the + * same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null. + */ + private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId, + Placement placement) { Set ownedIds = ownedIds(previous); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); @@ -291,21 +435,22 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i List stepEntityIds = new ArrayList<>(); Map usedExistingIds = usedExistingIds(previous); List saved = new ArrayList<>(); - List connectorSteps = new ArrayList<>(); + List grouped = new ArrayList<>(); + List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); DashboardId dashboardId = null; - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { try { if ("GATEWAY_CONNECTOR".equals(step.getType())) { // A connector lives in the gateway's attributes, which aren't transactional: saved after commit - if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() != DevicePackageRequest.Action.KEEP) { connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); } continue; } JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; - StepResult result = applyStep(tenantId, step, entity); + StepResult result = applyStep(tenantId, step, entity, placement); ObjectNode output = result.output(); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); outputs.put(step.stateKey(), output); @@ -317,7 +462,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i state.put("resolution", resolution); // A kept entity keeps the checksum of what the package left: the current one would take the // user's changes for the package's, and the next update would overwrite them without a warning - String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); + String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); if (checksum != null) { state.put("checksum", checksum); } @@ -343,8 +488,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (result.saved() != null) { saved.add(result.saved()); } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { - // As at install, the step's attributes go with the entity it saved; written after commit + if (placement.entityGroup() != null && result.saved() != null && result.saved().created() + && result.entityId().getEntityType() == EntityType.DEVICE) { + entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId()); + grouped.add(result.saved()); + } + // The step's attributes go with the entity it saved; at install also onto an entity the user chose to + // use, as the install always did. Written after commit + boolean install = installedVersionId == null; + if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) { attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); } } catch (StepFailure e) { @@ -356,7 +508,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i // An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps // it changes: the other steps and the forms keep their install state - if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) { + if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) { previous.getInstallState().forEach((key, value) -> { if (value instanceof ObjectNode state) { installState.putIfAbsent(key, state); @@ -376,15 +528,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i carryMetadataStates(previous, tracked, state); descriptor.setInstallState(state); - installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); - installedItem.setItemName(versionInfo.get("name").asText()); - installedItem.setVersion(versionInfo.get("version").asText()); - installedItem.setDescriptor(descriptor); - installedItemService.save(tenantId, installedItem); // Resolved once every entity is saved: attributes may refer to a later step's entity List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); - return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); + return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped); } /** The checksums the installed device packages recorded, by entity. */ @@ -422,7 +569,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then * fails: the plan was made for the version installed before. Without it both would create the new entities. */ - private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { + private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest request) { IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) @@ -432,11 +579,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return installedItem; } - private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) throws ThingsboardException { return switch (step.getType()) { case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); - case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); - case "DASHBOARD" -> saveDashboard(tenantId, step, entity); + case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement); + case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement); case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); case "INTEGRATION" -> saveIntegration(tenantId, step, entity); @@ -444,16 +591,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }; } - private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); profile.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(profile, id, current, step); // The tenant's default profile stays the default one @@ -466,31 +613,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; Device device; boolean created = false; - if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { + if (step.getAction() == DevicePackageRequest.Action.CREATE) { Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); template.setId(null); template.setVersion(null); + assignCustomer(template, placement.deviceCustomerId(), null, step); device = deviceService.saveDevice(template); created = true; } else { Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; device = existing(tenantId, current, step); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { - // Another device the user chose to overwrite; the package's own device never changes + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { + // On update, another device the user chose to overwrite; it keeps its credentials. The package's own + // device never changes, and an install never overwrites one Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); prepareOverwrite(template, id, current, step); + assignCustomer(template, placement.customerId(), current, step); device = deviceService.saveDevice(template); created = true; } } DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); - if (created && step.getCredentials() != null && step.getCredentials().isObject()) { + if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) { credentials = applyCredentials(tenantId, credentials, step.getCredentials()); } ObjectNode output = output(device.getId(), device.getName()); @@ -500,7 +650,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if ("GATEWAY".equals(step.getType())) { output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); } - SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; + SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null; return new StepResult(device.getId(), output, null, saved); } @@ -520,16 +670,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); } - private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getTitle()); } Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); dashboard.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(dashboard, id, current, step); // The dashboard keeps its owner and the customers it is assigned to @@ -537,25 +687,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i dashboard.setCustomerId(current.getCustomerId()); } dashboard.setAssignedCustomers(current.getAssignedCustomers()); + assignCustomer(dashboard, placement.customerId(), current, step); } else { dashboard.setId(null); dashboard.setVersion(null); + assignCustomer(dashboard, placement.customerId(), null, step); } Dashboard result = dashboardService.saveDashboard(dashboard); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); } - private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) throws ThingsboardException { RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); ruleChain.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(ruleChain, id, current, step); // A rule chain the tenant made its root one stays the root @@ -578,17 +730,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } Converter converter = JacksonUtil.treeToValue(entity, Converter.class); converter.setTenantId(tenantId); converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(converter, id, current, step); } else { @@ -599,10 +751,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); Integration merged = withMergedMetadata(current, step.getMetadata()); if (merged != null) { @@ -613,7 +765,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } Integration integration = JacksonUtil.treeToValue(entity, Integration.class); integration.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(integration, id, current, step); // The devices keep sending to the same endpoint @@ -668,7 +820,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i /** * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. - * A copy: the integration may be the cache's own instance, which a rolled back update must not change. + * A copy: the integration may be the cache's own instance, which a rolled back install or update must not change. */ private static Integration withMergedMetadata(Integration integration, JsonNode entries) { if (entries == null || !entries.isObject() || entries.isEmpty()) { @@ -698,7 +850,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * The overwritten entity keeps its id and its current name (the user may have renamed it). The version the * user reviewed makes the save fail if someone changed the entity since. */ - private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { + private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.Step step) { switch (entity) { case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } @@ -715,9 +867,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i ((HasVersion) entity).setVersion(currentVersion); } - private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { + private T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) { if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { - throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); + throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again."); } return current; } @@ -745,9 +897,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with * its metadata, which isn't cached. */ - private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { + private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.Step step, ObjectNode output) { String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); - return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); + return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE)); } private static ObjectNode output(EntityId id, String name) { @@ -775,7 +927,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */ + /** Replaces ${.} of entities the request has saved, e.g. the id of a converter it created. */ static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) { if (node == null) { return null; @@ -834,17 +986,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; } - /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ + /** + * What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install + * or update. + */ private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { for (SavedEntity saved : applied.saved()) { try { - logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), + CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null; + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId, saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); if (saved.id().getEntityType() != EntityType.DEVICE) { autoCommit(user, saved.id()); } } catch (Exception e) { - log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); + log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e); + } + } + for (SavedEntity saved : applied.grouped()) { + try { + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(), + ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName()); + } catch (Exception e) { + log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e); } } for (StepAttributes step : applied.attributes()) { @@ -855,7 +1019,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); } } - for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { + for (DevicePackageRequest.Step step : applied.connectorSteps()) { try { saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); } catch (Exception e) { @@ -905,7 +1069,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i */ static String userMessage(Throwable e) { if (e instanceof EntityVersionMismatchException) { - return "Someone changed it while you were reviewing the update. Check the update again."; + return "Someone changed it meanwhile. Check the package again."; } if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException || e instanceof SubscriptionException) { @@ -961,8 +1125,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return ids; } - private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { - DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); + private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) { + DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class); if (entity != null) { copy.setEntity(entity); } @@ -972,6 +1136,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { } + @FunctionalInterface + private interface PackageChange { + Applied apply() throws Exception; + } + private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { } @@ -982,8 +1151,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, - List connectorSteps, List attributes, - Map aliasOutputs) { + List connectorSteps, List attributes, + Map aliasOutputs, EntityGroup entityGroup, List grouped) { + } + + /** + * Where an install opened from a customer's or a device group's page puts its entities. A new device follows the + * group's customer when no customer is given, as a device saved into a group does; an update has none. + */ + private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) { + static final Placement NONE = new Placement(null, null, null); } /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 86b9c5580a..8337d9c550 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.stereotype.Service; import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; @@ -49,6 +50,7 @@ import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescript import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.subscription.SubscriptionException; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -97,8 +99,10 @@ import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.stream.Stream; @Service @TbCoreComponent @@ -429,7 +433,7 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); if ("DEVICE".equals(itemType)) { - // Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService + // Updated in one transaction from the install wizard of the new version, see DevicePackageService throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); @@ -748,7 +752,9 @@ public class DefaultIotHubService implements IotHubService { /** * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package, - * and the ones the user had before and the package took as they were (use existing). + * and the ones the user had before and the package took as they were (use existing). A device profile that devices + * still use stays too, e.g. with the devices a LoRaWAN integration created, and any kept profile keeps what it refers + * to: TB deletes neither. * A kept integration loses the metadata entries the package added. */ private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, @@ -765,22 +771,42 @@ public class DefaultIotHubService implements IotHubService { List ordered = new ArrayList<>(createdEntityIds); Collections.reverse(ordered); ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size()))); + // What a kept profile refers to: its default rule chain and dashboard, which come after it in the order + Set referencedByKeptProfiles = new HashSet<>(); for (EntityId entityId : ordered) { if (usedExisting.contains(entityId.getId())) { log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); continue; } Set usedBy = usedByOtherPackages.get(entityId.getId()); if (usedBy != null) { log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); + continue; + } + if (referencedByKeptProfiles.contains(entityId.getId())) { + log.info("[{}] Kept {} {}: a kept device profile refers to it", tenantId, entityId.getEntityType(), entityId.getId()); + continue; + } + // The package's own devices are deleted by now; the ones left came from elsewhere, e.g. a LoRaWAN integration + long devices = countProfileDevices(tenantId, entityId, Set.of()); + if (devices > 0) { + log.info("[{}] Kept device profile {}: devices use it ({})", tenantId, entityId.getId(), devices); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); continue; } try { deleteDevicePackageEntity(tenantId, entityId, user); } catch (Exception e) { - log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); + // A reference the package doesn't know of, e.g. a profile the user made later with the package's rule chain + if (ExceptionUtils.indexOfType(e, DataValidationException.class) >= 0) { + log.info("[{}] Kept {} {}: {}", tenantId, entityId.getEntityType(), entityId.getId(), ExceptionUtils.getRootCauseMessage(e)); + } else { + log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); + } } } } @@ -839,18 +865,26 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item not found"); } List kept = new ArrayList<>(); + List referenced = new ArrayList<>(); Set usedByItems = new HashSet<>(); int usedExistingCount = 0; if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { Set usedExisting = usedExistingIds(dd); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); + // The delete removes these before the profiles, so they don't keep a profile; a kept device does + Set deletedDevices = new HashSet<>(); + dd.getCreatedEntityIds().stream() + .filter(id -> id.getEntityType() == EntityType.DEVICE && !usedExisting.contains(id.getId()) && !usedByOtherPackages.containsKey(id.getId())) + .forEach(id -> deletedDevices.add(id.getId())); + Set created = new HashSet<>(); + dd.getCreatedEntityIds().forEach(id -> created.add(id.getId())); + Set keptIds = new HashSet<>(); for (EntityId entityId : dd.getCreatedEntityIds()) { Set usedBy = usedByOtherPackages.get(entityId.getId()); boolean taken = usedExisting.contains(entityId.getId()); if (usedBy != null || taken) { - String name = findDevicePackageEntity(tenantId, entityId) != null - ? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null; - kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, name)); + kept.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); } if (usedBy != null) { usedByItems.addAll(usedBy); @@ -859,8 +893,65 @@ public class DefaultIotHubService implements IotHubService { usedExistingCount++; } } + for (EntityId entityId : dd.getCreatedEntityIds()) { + if (!keptIds.contains(entityId.getId()) && countProfileDevices(tenantId, entityId, deletedDevices) > 0) { + referenced.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); + } + } + // A kept profile, for whatever reason, keeps what it refers to + for (EntityId entityId : dd.getCreatedEntityIds()) { + if (!keptIds.contains(entityId.getId())) { + continue; + } + for (EntityId reference : profileReferences(tenantId, entityId)) { + if (created.contains(reference.getId()) && keptIds.add(reference.getId())) { + referenced.add(keptEntity(tenantId, reference)); + } + } + } + } + return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, referenced); + } + + private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) { + String name = findDevicePackageEntity(tenantId, entityId) != null + ? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null; + return new InstalledItemKeptEntities.KeptEntity(entityId, name); + } + + /** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */ + private List profileReferences(TenantId tenantId, EntityId profileId) { + List references = new ArrayList<>(); + if (profileId.getEntityType() != EntityType.DEVICE_PROFILE) { + return references; + } + DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId())); + if (profile != null) { + Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId()) + .filter(Objects::nonNull) + .forEach(references::add); + } + return references; + } + + /** + * How many devices use the device profile {@code entityId}, apart from {@code excludedDevices}; 0 for another entity. + * TB doesn't delete a profile that devices use. + */ + private long countProfileDevices(TenantId tenantId, EntityId entityId, Set excludedDevices) { + if (entityId.getEntityType() != EntityType.DEVICE_PROFILE) { + return 0; + } + DeviceProfileId profileId = new DeviceProfileId(entityId.getId()); + long count = deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(tenantId, profileId, new PageLink(1)).getTotalElements(); + for (UUID deviceId : excludedDevices) { + Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId)); + if (device != null && profileId.equals(device.getDeviceProfileId())) { + count--; + } } - return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount); + return Math.max(count, 0); } /** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */ diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java similarity index 67% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java index a62f556c57..f79f023672 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java @@ -10,28 +10,33 @@ import java.util.Map; import java.util.UUID; /** - * The update of an installed device package as the install wizard planned it: the entity of each install step - * of the new version, already resolved from its template, and what to do with it. The server applies all of it - * in one transaction, together with the new version of the installed item, or nothing. + * The install or update of a device package as the install wizard planned it: the entity of each install step + * of the version being installed, already resolved from its template, and what to do with it. The server applies + * all of it in one transaction, together with the installed item, or nothing. */ @Data -public class DeviceUpdateRequest { +public class DevicePackageRequest { private String versionId; - // The version installed when the wizard planned the update; the update fails if the package changed since + // Update only: the version installed when the wizard planned the update, which fails if the package changed since private UUID fromVersionId; - // The install method of the new version's steps; the installed one when not set + // The install method of the steps; an update without it keeps the installed one private String selectedInstallMethod; // The form values of the install state, by step: the server adds the entities to it private Map installState; + // Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard + // go to, and the group the created device or gateway is added to. An update ignores them + private UUID customerId; + private UUID entityGroupId; private List steps; public enum Action { - // Taken as it is: the new version doesn't change it, or the user kept an entity they had + // Taken as it is: an update's new version doesn't change it, or the user kept an entity they had KEEP, // Takes the entity from the step OVERWRITE, - // A new entity: new in this version, deleted since install, or a copy next to one with the same name + // A new entity: one the package installs, a step new in this version or deleted since install, or a copy + // next to one with the same name CREATE } @@ -51,13 +56,13 @@ public class DeviceUpdateRequest { private Long expectedVersion; // The user confirmed overwriting an entity of another package or one they didn't install with this package private boolean confirmed; - // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity this - // update creates is left for the server, which knows its id only once it is created. + // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity the + // request creates is left for the server, which knows its id only once it is created. private JsonNode entity; // DEVICE and GATEWAY: the credentials template, if any private JsonNode credentials; // OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity, - // they may keep ${.} of an entity this update creates. + // they may keep ${.} of an entity the request creates. private JsonNode serverAttributes; private JsonNode sharedAttributes; // The resolution the install state records for it @@ -65,7 +70,8 @@ public class DeviceUpdateRequest { // INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the // integration, e.g. one the package took as it was; null removes an entry private JsonNode metadata; - // UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check + // UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later + // update checks that converter against ThingsBoard's default one private boolean defaultConverter; /** diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java similarity index 70% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java index 5c8ec6e8d7..d07a51d839 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java @@ -17,7 +17,7 @@ import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor -public class DeviceUpdateResult { +public class DevicePackageResult { private boolean success; private String errorMessage; @@ -26,12 +26,12 @@ public class DeviceUpdateResult { // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} private Map outputs; - public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { - return new DeviceUpdateResult(true, null, null, descriptor, outputs); + public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { + return new DevicePackageResult(true, null, null, descriptor, outputs); } - public static DeviceUpdateResult error(String errorMessage, String failedStep) { - return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); + public static DevicePackageResult error(String errorMessage, String failedStep) { + return new DevicePackageResult(false, errorMessage, failedStep, null, null); } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java similarity index 59% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java index 5688056c98..60103c6e01 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java @@ -7,13 +7,16 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; -/** Updates an installed device package to another version of its item. */ -public interface DevicePackageUpdateService { +/** Installs a device package, or updates an installed one to another version of its item. */ +public interface DevicePackageService { /** The package's entities as they are now: whether they still exist, changed since, or are shared. */ List check(SecurityUser user, IotHubInstalledItemId installedItemId); + /** Installs the version in one transaction, together with its installed item, or nothing. */ + DevicePackageResult install(SecurityUser user, DevicePackageRequest request); + /** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ - DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); + DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request); } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java index ad517c5327..7c3cfdbeb7 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -9,7 +9,10 @@ import org.thingsboard.server.common.data.id.EntityId; import java.util.List; -/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ +/** + * What deleting an installed item keeps: what other installed items use too, what the user had before it, and what other + * tenant entities refer to (a LoRaWAN integration creates its devices on the first uplink, not the package). + */ @Data @NoArgsConstructor @AllArgsConstructor @@ -20,6 +23,9 @@ public class InstalledItemKeptEntities { private int usedByItemsCount; // How many of the kept entities the user had before and the package took as they were (use existing) private int usedExistingCount; + // What other tenant entities refer to: the package's device profiles that devices use, and the default rule chains and + // dashboard of a kept profile. Apart from entities, which an update reads as shared with other packages + private List referencedEntities; @Data @NoArgsConstructor diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java similarity index 60% rename from application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java rename to application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java index 38595a0c71..16dc4c3f19 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -16,12 +17,17 @@ import org.mockito.quality.Strictness; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.client.RestClientException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; @@ -30,23 +36,29 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.subscription.PlatformFeature; @@ -54,6 +66,7 @@ import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.service.entitiy.TbLogEntityActionService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -62,20 +75,25 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.ExecutionException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class DefaultDevicePackageUpdateServiceTest { +class DefaultDevicePackageServiceTest { private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); private final SecurityUser user = mock(SecurityUser.class); @@ -119,18 +137,30 @@ class DefaultDevicePackageUpdateServiceTest { private TelemetrySubscriptionService telemetryService; @Mock private IotHubService iotHubService; + @Mock + private ProjectInfo projectInfo; + @Mock + private CustomerService customerService; + @Mock + private EntityGroupService entityGroupService; @InjectMocks - private DefaultDevicePackageUpdateService service; + private DefaultDevicePackageService service; private IotHubInstalledItem installedItem; // Set when the transaction callback threw, so the transaction would roll back private final List rolledBack = new ArrayList<>(); + private boolean inTransaction; + private final List savedInTransaction = new ArrayList<>(); + // What must run after commit: the audit log, the Hub install report and the attributes, each marked if it ran inside + private final List afterCommitCalls = new ArrayList<>(); @BeforeEach void setUp() { ReflectionTestUtils.setField(service, "entityService", entityService); ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); + ReflectionTestUtils.setField(service, "customerService", customerService); + ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService); when(user.getTenantId()).thenReturn(tenantId); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); @@ -158,11 +188,14 @@ class DefaultDevicePackageUpdateServiceTest { when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + inTransaction = true; try { return invocation.>getArgument(0).doInTransaction(null); } catch (RuntimeException e) { rolledBack.add(e); throw e; + } finally { + inTransaction = false; } }); when(packageEntities.checksum(any(), any())).thenReturn("checksum"); @@ -184,7 +217,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), keep("AM308", "DEVICE", deviceId), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); @@ -218,10 +251,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); + DevicePackageRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -237,10 +270,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); overview.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(overview)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -256,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -266,10 +299,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void useExistingOfAPackageEntity_staysThePackages() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -282,10 +315,10 @@ class DefaultDevicePackageUpdateServiceTest { // At install the user picked their own dashboard: the install adds it to createdEntityIds too ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -295,9 +328,9 @@ class DefaultDevicePackageUpdateServiceTest { @Test void overwritingAnEntityUsedAtInstall_needsAConfirmation() { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -308,7 +341,7 @@ class DefaultDevicePackageUpdateServiceTest { Dashboard shared = dashboard(9L); DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); - when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0)); + when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of())); // This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); @@ -327,10 +360,10 @@ class DefaultDevicePackageUpdateServiceTest { // v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -343,9 +376,9 @@ class DefaultDevicePackageUpdateServiceTest { DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); installed.setUsedExistingEntityIds(List.of(dashboardId)); installed.setInstallState(Map.of()); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -358,7 +391,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); @@ -377,13 +410,13 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setResolution("use-existing"); ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); entries.putNull("profile.milesight-iot-am308"); step.setMetadata(entries); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class); @@ -411,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest { integration.setId(integrationId); when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -438,11 +471,11 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); step.setResolution("use-existing"); step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -465,10 +498,10 @@ class DefaultDevicePackageUpdateServiceTest { configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); verify(integrationService, never()).saveIntegration(any()); @@ -476,12 +509,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsWithOneKey_areRejected() { - DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); first.setId("main-dashboard"); - DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); + DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId); second.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(first, second)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -489,25 +522,25 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsOfOneTypeAndName_areRejected() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: DASHBOARD:Dashboard"); verify(transactionTemplate, never()).execute(any()); } @Test void stepWithTheKeyOfAForm_isRejected() { - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setId("Settings"); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10)))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings"); verify(transactionTemplate, never()).execute(any()); } @@ -532,14 +565,14 @@ class DefaultDevicePackageUpdateServiceTest { legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"), "Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app")))); - DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); + DevicePackageRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); uplink.setDefaultConverter(true); - DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); + DevicePackageRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateRequest request = request(uplink, ttn); + DevicePackageRequest request = request(uplink, ttn); request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration"))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -563,7 +596,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); @@ -580,12 +613,12 @@ class DefaultDevicePackageUpdateServiceTest { void entityChangedSinceTheCheck_isAVersionConflict() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); - assertThat(result.getErrorMessage()).contains("Check the update again"); + assertThat(result.getErrorMessage()).contains("Check the package again"); verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); } @@ -608,7 +641,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); @@ -640,12 +673,12 @@ class DefaultDevicePackageUpdateServiceTest { IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); when(installedItemService.findByTenantId(any(), any(), any(), any())) .thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); - DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setConfirmed(true); step.setDefaultConverter(true); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink"); @@ -672,14 +705,14 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0"); when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo); // ThingsBoard's default converter changed: only the converter step is sent - DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setId("uplink"); step.setDefaultConverter(true); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setVersionId(installedVersionId.toString()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -697,7 +730,7 @@ class DefaultDevicePackageUpdateServiceTest { void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard"); @@ -707,7 +740,7 @@ class DefaultDevicePackageUpdateServiceTest { void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { DashboardId foreign = new DashboardId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -716,7 +749,7 @@ class DefaultDevicePackageUpdateServiceTest { @Test void theDeviceIsNeverOverwritten() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -729,7 +762,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isFalse(); verify(transactionTemplate, never()).execute(any()); @@ -743,7 +776,7 @@ class DefaultDevicePackageUpdateServiceTest { updated.setItemVersionId(UUID.fromString(versionId)); when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -754,10 +787,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void planOfAnotherInstalledVersion_isRejected() { - DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); + DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId)); request.setFromVersionId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -768,7 +801,7 @@ class DefaultDevicePackageUpdateServiceTest { doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) .when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -780,10 +813,10 @@ class DefaultDevicePackageUpdateServiceTest { void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); @@ -829,12 +862,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void userMessage_showsValidationMessagesAndHidesInternalOnes() { - assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) + assertThat(DefaultDevicePackageService.userMessage(new DataValidationException("Rule chains limit reached"))) .isEqualTo("Rule chains limit reached"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) - .contains("Check the update again"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) - .isEqualTo("Failed to update the device package"); + assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) + .contains("Check the package again"); + assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) + .isEqualTo("Failed to save the device package"); } @Test @@ -842,12 +875,431 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); - ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); + ObjectNode resolved = (ObjectNode) DefaultDevicePackageService.resolvePlaceholders(node, Map.of("device", device)); assertThat(resolved.get("a").asText()).isEqualTo("123"); assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); } + @Test + void installSavesTheEntitiesAndTheInstalledItemInOneTransaction() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("use-existing"); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + integrationStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + verify(transactionTemplate).execute(any()); + assertThat(savedInTransaction).containsExactly("DEVICE_PROFILE", "DASHBOARD", "INSTALLED_ITEM"); + ArgumentCaptor saved = ArgumentCaptor.forClass(IotHubInstalledItem.class); + verify(installedItemService).save(eq(tenantId), saved.capture()); + IotHubInstalledItem item = saved.getValue(); + assertThat(item.getTenantId()).isEqualTo(tenantId); + assertThat(item.getItemId()).isEqualTo(itemId); + assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(item.getVersion()).isEqualTo("1.0.1"); + assertThat(item.getItemName()).isEqualTo("AM308"); + assertThat(item.getItemType()).isEqualTo("DEVICE"); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) item.getDescriptor(); + assertThat(descriptor.getCreatedEntityIds()).containsExactly(profileId, integrationId, dashboardId); + assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(integrationId); + assertThat(descriptor.getDashboardId()).isEqualTo(dashboardId); + Map state = descriptor.getInstallState(); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("entityOutput").get("id").asText()).isEqualTo(profileId.getId().toString()); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("checksum").isTextual()).isTrue(); + assertThat(state.get("DASHBOARD:Dashboard").get("entityOutput").get("id").asText()).isEqualTo(dashboardId.getId().toString()); + assertThat(state.get("DASHBOARD:Dashboard").get("checksum").isTextual()).isTrue(); + assertThat(state.get("INTEGRATION:TTN").get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString()); + assertThat(state.get("INTEGRATION:TTN").get("resolution").asText()).isEqualTo("use-existing"); + assertThat(result.getDescriptor()).isSameAs(descriptor); + assertThat(result.getOutputs()).containsOnlyKeys("DEVICE_PROFILE:AM308 profile", "INTEGRATION:TTN", "DASHBOARD:Dashboard"); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installFailureOnALaterStepSavesNothing() { + mockInstall(); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); + assertThat(rolledBack).hasSize(1); + verify(installedItemService, never()).save(any(), any()); + verifyNoInteractions(logEntityActionService, telemetryService); + verify(iotHubRestClient, never()).reportVersionInstalled(any(), any()); + } + + @Test + void installOverwriteOfAnExistingEntityNeedsAConfirmation() { + mockInstall(); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + + DevicePackageResult result = service.install(user, request( + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Overwriting an entity of another package needs a confirmation: Dashboard"); + verify(transactionTemplate, never()).execute(any()); + verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWithBadIntegrationCredentialsSavesNothing() throws Exception { + mockInstall(); + doThrow(new ExecutionException(new IllegalStateException("Wrong API key"))) + .when(tbIntegrationService).validateIntegrationConfiguration(eq(tenantId), any()); + + DevicePackageResult result = service.install(user, request( + create("TTN", "INTEGRATION", JacksonUtil.newObjectNode().put("name", "TTN").put("type", "TTN")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("INTEGRATION:TTN"); + assertThat(result.getErrorMessage()).isEqualTo("Wrong API key"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWhenHubIsUnavailableSavesNothing() { + mockInstall(); + when(iotHubRestClient.getVersionInfo(versionId)).thenThrow(new RestClientException("Connection refused")); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("IoT Hub is unavailable. Try again later."); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installReportsToTheHubAfterCommitAndIgnoresAReportFailure() { + mockInstall(); + doAnswer(i -> { + recordAfterCommit("REPORT"); + throw new RestClientException("Connection refused"); + }).when(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + InOrder order = inOrder(installedItemService, logEntityActionService, iotHubRestClient); + order.verify(installedItemService).save(eq(tenantId), any()); + order.verify(logEntityActionService).logEntityAction(eq(tenantId), eq(dashboardId), any(), any(), eq(ActionType.ADDED), eq(user)); + order.verify(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + assertThat(afterCommitCalls).containsExactly("AUDIT", "REPORT"); + } + + @Test + void installRejectsAFromVersion() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setFromVersionId(installedVersionId); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installKeepStepMustUseExisting() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("created"); + + DevicePackageResult result = service.install(user, request(integrationStep)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: TTN"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installRejectsAMalformedVersionId() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setVersionId("not-a-uuid"); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(iotHubRestClient, never()).getVersionInfo(any()); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void installAssignsTheCustomerToTheDeviceAndTheDashboard() { + mockInstall(); + CustomerId customerId = customerOf(tenantId); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(customerId); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isEqualTo(customerId); + } + + @Test + void installAddsTheDeviceToTheEntityGroup() { + mockInstall(); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Warehouse sensors"); + group.setOwnerId(tenantId); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(entityGroupService, never()).addEntityToEntityGroup(any(), any(), eq(dashboardId)); + assertThat(savedInTransaction).contains("ENTITY_GROUP"); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), any(), eq(ActionType.ADDED_TO_ENTITY_GROUP), + eq(user), eq(deviceId.toString()), eq(group.getId().toString()), eq("Warehouse sensors")); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installRejectsACustomerOfAnotherTenant() { + mockInstall(); + CustomerId customerId = customerOf(TenantId.fromUUID(UUID.randomUUID())); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateIgnoresCustomerAndEntityGroup() { + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); + DevicePackageRequest request = request(overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(UUID.randomUUID()); + request.setEntityGroupId(UUID.randomUUID()); + + DevicePackageResult result = service.update(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isNull(); + verifyNoInteractions(customerService, entityGroupService); + } + + @Test + void updateOverwriteOfACustomerDeviceThatChangesItsOwnerFails() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + current.setCustomerId(customerOf(tenantId)); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DEVICE:AM308 spare"); + assertThat(result.getErrorMessage()).isEqualTo("AM308 spare belongs to another owner"); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateOverwriteOfAnotherDeviceKeepsItsCredentials() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> i.getArgument(0)); + DeviceCredentials credentials = new DeviceCredentials(); + credentials.setDeviceId(otherId); + credentials.setCredentialsId("existing-token"); + when(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, otherId)).thenReturn(credentials); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + step.setCredentials(JacksonUtil.newObjectNode().put("credentialsType", "ACCESS_TOKEN").put("credentialsId", "package-token")); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isTrue(); + verify(deviceService).saveDevice(any(Device.class)); + verify(deviceCredentialsService, never()).updateDeviceCredentials(any(), any()); + assertThat(result.getOutputs().get("DEVICE:AM308 spare").get("token").asText()).isEqualTo("existing-token"); + } + + @Test + void installRejectsAnOverwriteOfADeviceOrGateway() { + mockInstall(); + for (String type : new String[]{"DEVICE", "GATEWAY"}) { + DevicePackageRequest.Step step = overwrite("AM308", type, deviceId, 1L, JacksonUtil.newObjectNode().put("name", "AM308")); + step.setConfirmed(true); + + DevicePackageResult result = service.install(user, request(step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: AM308"); + } + verify(transactionTemplate, never()).execute(any()); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWritesStepAttributesOnAUsedExistingEntityAfterCommit() { + mockInstall(); + DevicePackageRequest.Step deviceStep = keep("AM308", "DEVICE", deviceId); + deviceStep.setResolution("use-existing"); + deviceStep.setServerAttributes(JacksonUtil.newObjectNode().put("model", "AM308")); + deviceStep.setSharedAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); + + DevicePackageResult result = service.install(user, request(deviceStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); + verify(telemetryService, times(2)).saveAttributes(saved.capture()); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getEntityId).containsOnly(deviceId); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getScope).containsExactly(AttributeScope.SERVER_SCOPE, AttributeScope.SHARED_SCOPE); + assertThat(saved.getAllValues().get(0).getEntries().get(0).getValueAsString()).isEqualTo("AM308"); + assertThat(saved.getAllValues().get(1).getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString()); + // The kept device isn't saved, so only the dashboard is audited + assertThat(afterCommitCalls).containsExactly("AUDIT", "ATTRIBUTES", "ATTRIBUTES", "REPORT"); + } + + @Test + void installIntoACustomerGroupGivesTheDeviceTheGroupsCustomer() { + mockInstall(); + CustomerId groupCustomer = customerOf(tenantId); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Customer sensors"); + group.setOwnerId(groupCustomer); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getOwnerId()).isEqualTo(tenantId); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), eq(groupCustomer), eq(ActionType.ADDED), eq(user)); + } + + private CustomerId customerOf(TenantId owner) { + Customer customer = new Customer(new CustomerId(UUID.randomUUID())); + customer.setTenantId(owner); + when(customerService.findCustomerById(tenantId, customer.getId())).thenReturn(customer); + return customer.getId(); + } + + /** The new entities get these ids; each save records that it ran inside the transaction. */ + private void mockInstall() { + when(user.getId()).thenReturn(new UserId(UUID.randomUUID())); + when(projectInfo.getProjectVersion()).thenReturn("4.4.1"); + when(projectInfo.getProductType()).thenReturn("PE"); + when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> { + recordSave("DEVICE_PROFILE"); + DeviceProfile profile = i.getArgument(0); + profile.setId(profileId); + return profile; + }); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> { + recordSave("DASHBOARD"); + Dashboard dashboard = i.getArgument(0); + dashboard.setId(dashboardId); + return dashboard; + }); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> { + recordSave("DEVICE"); + Device device = i.getArgument(0); + device.setId(deviceId); + return device; + }); + doAnswer(i -> { + recordSave("ENTITY_GROUP"); + return null; + }).when(entityGroupService).addEntityToEntityGroup(any(), any(), any()); + when(installedItemService.save(any(), any())).thenAnswer(i -> { + recordSave("INSTALLED_ITEM"); + return i.getArgument(1); + }); + Integration integration = new Integration(); + integration.setId(integrationId); + integration.setTenantId(tenantId); + integration.setName("TTN my-app"); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration); + doAnswer(i -> { + recordAfterCommit("AUDIT"); + return null; + }).when(logEntityActionService).logEntityAction(any(TenantId.class), any(EntityId.class), any(HasName.class), nullable(CustomerId.class), + any(ActionType.class), any(User.class), any(Object[].class)); + doAnswer(i -> { + recordAfterCommit("REPORT"); + return null; + }).when(iotHubRestClient).reportVersionInstalled(any(), any()); + doAnswer(i -> { + recordAfterCommit("ATTRIBUTES"); + return null; + }).when(telemetryService).saveAttributes(any(AttributesSaveRequest.class)); + } + + private void recordSave(String what) { + if (inTransaction) { + savedInTransaction.add(what); + } + } + + private void recordAfterCommit(String what) { + afterCommitCalls.add(inTransaction ? what + " in transaction" : what); + } + private IotHubInstalledItem otherPackage(Map installState) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setInstallState(installState); @@ -875,35 +1327,35 @@ class DefaultDevicePackageUpdateServiceTest { return dashboard; } - private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { - DeviceUpdateRequest request = new DeviceUpdateRequest(); + private DevicePackageRequest request(DevicePackageRequest.Step... steps) { + DevicePackageRequest request = new DevicePackageRequest(); request.setVersionId(versionId); request.setSteps(List.of(steps)); return request; } - private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); + private static DevicePackageRequest.Step keep(String name, String type, EntityId id) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.KEEP); step.setEntityId(id.getId()); return step; } - private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); + private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.OVERWRITE); step.setEntityId(id.getId()); step.setExpectedVersion(version); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); + private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.CREATE); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { - DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); + private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) { + DevicePackageRequest.Step step = new DevicePackageRequest.Step(); step.setName(name); step.setType(type); step.setAction(action); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 1ee06dc1b3..470e2e638d 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -3,6 +3,10 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; @@ -14,6 +18,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.cf.CalculatedField; @@ -37,6 +42,9 @@ import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor; @@ -58,10 +66,12 @@ import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService; import org.thingsboard.server.service.entitiy.converter.TbConverterService; import org.thingsboard.server.service.entitiy.device.TbDeviceService; import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService; +import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; import java.nio.charset.StandardCharsets; @@ -121,6 +131,10 @@ class DefaultIotHubServiceTest { private TbConverterService tbConverterService; @Mock private DevicePackageEntities devicePackageEntities; + @Mock + private RuleChainService ruleChainService; + @Mock + private TbRuleChainService tbRuleChainService; @Spy @InjectMocks @@ -649,6 +663,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + noDevices(profile.getId()); when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard); when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration); when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); @@ -923,6 +938,185 @@ class DefaultIotHubServiceTest { return integration; } + @Test + void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() { + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + profile.setTenantId(tenantId); + RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + ruleChain.setTenantId(tenantId); + RuleChainId ruleChainId = ruleChain.getId(); + Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); + dashboard.setTenantId(tenantId); + DashboardId dashboardId = dashboard.getId(); + profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultDashboardId(dashboardId); + // The user's, not the package's: not listed + profile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.randomUUID())); + Device packageDevice = new Device(new DeviceId(UUID.randomUUID())); + packageDevice.setDeviceProfileId(profile.getId()); + IotHubInstalledItem checked = devicePackage(ruleChainId, dashboardId, profile.getId(), packageDevice.getId()); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + // 3 devices on the profile: the package's own, which the delete removes first, and 2 the integration created + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())) + .thenReturn(new PageData<>(List.of(), 3, 3, true)); + when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + when(ruleChainService.findRuleChainById(tenantId, ruleChainId)).thenReturn(ruleChain); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); + when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr")); + when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR")); + when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet")); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + // An update reads entities as shared with other packages: the profile is not among them + assertThat(kept.getEntities()).isEmpty(); + assertThat(kept.getReferencedEntities()).containsExactly( + new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"), + new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR"), + new InstalledItemKeptEntities.KeptEntity(dashboardId, "Smartico L2-LR Fleet")); + } + + @Test + void findKeptEntities_devicePackage_aKeptDeviceKeepsItsProfile() { + DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID()); + DeviceId sharedDeviceId = new DeviceId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(profileId, sharedDeviceId); + IotHubInstalledItem other = devicePackage(sharedDeviceId); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + // The only device on the profile is the one another package uses: the delete keeps it, so it keeps the profile + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any())) + .thenReturn(new PageData<>(List.of(sharedDeviceId), 1, 1, false)); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId); + } + + @Test + void findKeptEntities_devicePackage_aSharedProfileKeepsWhatItRefersTo() { + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + RuleChainId edgeRuleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultEdgeRuleChainId(edgeRuleChainId); + IotHubInstalledItem checked = devicePackage(ruleChainId, edgeRuleChainId, profile.getId()); + IotHubInstalledItem other = devicePackage(profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profile.getId()); + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId) + .containsExactly(ruleChainId, edgeRuleChainId); + } + + @Test + void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndWhatItRefersTo() throws Exception { + mockTenant(); + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + DashboardId dashboardId = new DashboardId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultDashboardId(dashboardId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, dashboardId, profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())) + .thenReturn(new PageData<>(List.of(new DeviceId(UUID.randomUUID())), 1, 1, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceProfileService, never()).delete(any(), any()); + verify(tbRuleChainService, never()).delete(any(), any()); + verify(tbDashboardService, never()).delete(any(), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + } + + @Test + void deleteInstalledItem_devicePackage_aSharedProfileKeepsItsRuleChain() throws Exception { + mockTenant(); + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId()); + IotHubInstalledItem other = devicePackage(profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceProfileService, never()).delete(any(), any()); + verify(tbRuleChainService, never()).delete(any(), any()); + } + + @Test + void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays_loggedAsKept() throws Exception { + // A profile the user made after the install uses the package's rule chain + List logs = deleteRuleChainFailingWith( + new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!")); + + assertThat(logs).anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.INFO); + assertThat(event.getFormattedMessage()).contains("Kept RULE_CHAIN").contains("referenced by the device profiles"); + }); + assertThat(logs).noneMatch(event -> event.getLevel() == Level.ERROR); + } + + @Test + void deleteInstalledItem_devicePackage_aFailedDelete_staysAnError() throws Exception { + List logs = deleteRuleChainFailingWith(new RuntimeException("Database is down")); + + assertThat(logs).anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.ERROR); + assertThat(event.getFormattedMessage()).contains("Failed to delete device package entity"); + }); + } + + /** Deletes a package whose only entity is a rule chain that fails to delete with {@code failure}; the service's logs. */ + private List deleteRuleChainFailingWith(Exception failure) throws Exception { + mockTenant(); + RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + ruleChain.setTenantId(tenantId); + IotHubInstalledItem deleted = devicePackage(ruleChain.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain); + doThrow(failure).when(tbRuleChainService).delete(ruleChain, user); + Logger logger = (Logger) LoggerFactory.getLogger(DefaultIotHubService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + Level level = logger.getLevel(); + logger.setLevel(Level.INFO); + try { + service.deleteInstalledItem(user, deleted.getId()); + } finally { + logger.setLevel(level); + logger.detachAppender(appender); + } + // The delete goes on either way + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + return appender.list; + } + + private void noDevices(DeviceProfileId profileId) { + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any())) + .thenReturn(new PageData<>(List.of(), 0, 0, false)); + } + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index b99cf18981..7373a8fb81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id, not empty; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 072506dfca..17f3361738 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index d69060cd94..90fe24e0d6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -14,6 +14,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -49,6 +50,27 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink); } + @Override + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); + // Only the tenant's installed items, so the map can't outgrow the query's bind parameter limit; an item IoT Hub + // publishes no version of has nothing to update to + Map published = new HashMap<>(); + if (publishedVersionIds != null && !publishedVersionIds.isEmpty()) { + for (UUID itemId : iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId)) { + UUID versionId = publishedVersionIds.get(itemId); + if (versionId != null) { + published.put(itemId, versionId); + } + } + } + if (published.isEmpty()) { + return PageData.emptyPageData(); + } + return iotHubInstalledItemDao.findByTenantIdWithUpdates(tenantId, itemTypes, published, pageLink); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 693166b7e0..c09f8c12f5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -33,17 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId, @Param("itemIds") Collection itemIds); + /** + * The tenant's installed items, by type, item and text. With {@code updatesOnly}, only the items with an update: an item + * of {@code publishedItemIds} whose installed version is not among {@code publishedVersionIds} (version ids are unique, + * so: not the published version of its item). A flag, as Hibernate can't type {@code :uuids IS NULL}. + */ @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:updatesOnly = false + OR (item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds)) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); + Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("updatesOnly") boolean updatesOnly, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index d07d8f5dd4..4c91e5137b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -48,11 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { + return find(tenantId, itemTypes, itemId, null, pageLink); + } + + @Override + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + return find(tenantId, itemTypes, null, publishedVersionIds, pageLink); + } + + // Never matches: the query binds the published ids even when it doesn't filter by them + private static final Set NO_IDS = Set.of(new UUID(0, 0)); + + // One query for both lists, so the only-updates list filters and searches as the plain one does + private PageData find(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + boolean updatesOnly = publishedVersionIds != null; return DaoUtil.toPageData(repository.findByTenantId( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), + updatesOnly, + updatesOnly ? publishedVersionIds.keySet() : NO_IDS, + updatesOnly ? publishedVersionIds.values() : NO_IDS, toPageRequest(pageLink)) ); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java new file mode 100644 index 0000000000..65fe12ae2b --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.service; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +public class IotHubInstalledItemServiceTest extends AbstractServiceTest { + + @Autowired + IotHubInstalledItemService installedItemService; + + private final UUID trackerItemId = UUID.randomUUID(); + private final UUID sensorItemId = UUID.randomUUID(); + private final UUID unpublishedItemId = UUID.randomUUID(); + private final UUID trackerPublished = UUID.randomUUID(); + private final UUID sensorPublished = UUID.randomUUID(); + + private void install(String name, UUID itemId, UUID versionId) { + IotHubInstalledItem item = new IotHubInstalledItem(); + item.setTenantId(tenantId); + item.setItemId(itemId); + item.setItemVersionId(versionId); + item.setItemName(name); + item.setItemType("WIDGET"); + item.setVersion("1.0.0"); + item.setDescriptor(new WidgetInstalledItemDescriptor()); + installedItemService.save(tenantId, item); + } + + /** a and c are up to date, b and d have an update (d is a second install of a's item in an older version), e has no published version. */ + private void installFive() { + install("a", sensorItemId, sensorPublished); + install("b", trackerItemId, UUID.randomUUID()); + install("c", sensorItemId, sensorPublished); + install("d", sensorItemId, UUID.randomUUID()); + install("e", unpublishedItemId, UUID.randomUUID()); + } + + private Map published() { + return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished); + } + + private static List names(PageData page) { + return page.getData().stream().map(IotHubInstalledItem::getItemName).toList(); + } + + @Test + public void withUpdates_onlyTheItemsWithAnUpdate_inThePageSort() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.DESC)); + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), byName); + + assertThat(names(page)).containsExactly("d", "b"); + assertThat(page.getTotalElements()).isEqualTo(2); + } + + @Test + public void withUpdates_pagesAndTotal() { + installFive(); + SortOrder byName = new SortOrder("itemName", SortOrder.Direction.ASC); + + PageData first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 0, null, byName)); + PageData second = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 1, null, byName)); + + assertThat(names(first)).containsExactly("b"); + assertThat(names(second)).containsExactly("d"); + assertThat(first.getTotalElements()).isEqualTo(2); + assertThat(first.hasNext()).isTrue(); + assertThat(second.hasNext()).isFalse(); + } + + @Test + public void withUpdates_keepsTheSearchAndTheTypes() { + installFive(); + // "b" is in no item type or version, only in the name of b + PageLink search = new PageLink(10, 0, "b", new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("WIDGET"), published(), search))) + .containsExactly("b"); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("DEVICE"), published(), + new PageLink(10)).getData()).isEmpty(); + } + + @Test + public void plainList_sameQuery_isNotFiltered() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantId(tenantId, null, null, byName))).containsExactly("a", "b", "c", "d", "e"); + assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d"); + } + + @Test + public void withUpdates_ignoresItemsTheTenantHasNotInstalled() { + installFive(); + Map published = new HashMap<>(published()); + for (int i = 0; i < 20_000; i++) { + published.put(UUID.randomUUID(), UUID.randomUUID()); + } + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published, + new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC))); + + // 40k bind parameters would be over PostgreSQL's limit of 32767 + assertThat(names(page)).containsExactly("b", "d"); + } + + @Test + public void withUpdates_withoutPublishedVersions_isEmpty() { + installFive(); + Map unpublished = new HashMap<>(); + unpublished.put(unpublishedItemId, null); + + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, Map.of(), new PageLink(10)).getData()).isEmpty(); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, unpublished, new PageLink(10)).getData()).isEmpty(); + } + +} diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index fa040e8632..b9af2299f2 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -4,7 +4,8 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Store } from '@ngrx/store'; -import { Observable } from 'rxjs'; +import { forkJoin, Observable, of } from 'rxjs'; +import { map } from 'rxjs/operators'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { @@ -13,7 +14,7 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { DevicePackageEntityState, DevicePackageRequest, DevicePackageResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorConfig } from '@core/interceptors/interceptor-config'; @@ -50,6 +51,8 @@ export function iotHubResourceUrl(baseUrl: string, path: string): string { return `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`; } +const PUBLISHED_VERSIONS_CHUNK_SIZE = 100; + export interface IotHubRequestConfig { ignoreLoading?: boolean; ignoreErrors?: boolean; @@ -177,18 +180,6 @@ export class IotHubApiService { ); } - public registerDeviceInstall( - versionId: string, - descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig - ): Observable { - return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, - { type: 'DEVICE', ...descriptor }, - { params: this.buildParams(config) } - ); - } - public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable { return this.http.post( `/api/iot-hub/versions/${versionId}/install`, @@ -240,11 +231,7 @@ export class IotHubApiService { public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], itemId?: string, config?: IotHubRequestConfig): Observable> { - let query = pageLink.toQuery(); - if (itemTypes) { - const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; - types.forEach(t => query += `&itemTypes=${t}`); - } + let query = this.installedItemsQuery(pageLink, itemTypes); if (itemId) { query += `&itemId=${itemId}`; } @@ -254,6 +241,16 @@ export class IotHubApiService { ); } + /** Body: published version id by item id; returns items installed in a different version. */ + public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, + config?: IotHubRequestConfig): Observable> { + return this.http.post>( + `/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`, + publishedVersionIds, + { params: this.buildParams(config) } + ); + } + public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable { let url = '/api/iot-hub/installedItems/count'; if (itemType) { @@ -278,14 +275,23 @@ export class IotHubApiService { } /** Applies a device package update in one transaction: all of it, or nothing. */ - public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable { - return this.http.post( + public updateDevicePackage(installedItemId: string, request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, request, { params: this.buildParams(config) } ); } + /** Installs a device package in one transaction: all of its entities and the installed item, or nothing. */ + public installDevicePackage(request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/device/install`, + request, + { params: this.buildParams(config) } + ); + } + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { return this.http.get( `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, @@ -294,11 +300,18 @@ export class IotHubApiService { } public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { - return this.http.post( + if (!itemIds.length) { + return of([]); + } + const chunks: string[][] = []; + for (let i = 0; i < itemIds.length; i += PUBLISHED_VERSIONS_CHUNK_SIZE) { + chunks.push(itemIds.slice(i, i + PUBLISHED_VERSIONS_CHUNK_SIZE)); + } + return forkJoin(chunks.map(chunk => this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, - itemIds, + chunk, { params: this.buildParams(config) } - ); + ))).pipe(map(results => results.flat())); } public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable { @@ -308,6 +321,11 @@ export class IotHubApiService { ); } + private installedItemsQuery(pageLink: PageLink, itemTypes?: string | string[] | null): string { + const types = !itemTypes ? [] : Array.isArray(itemTypes) ? itemTypes : [itemTypes]; + return pageLink.toQuery() + types.map(t => `&itemTypes=${t}`).join(''); + } + private buildParams(config?: IotHubRequestConfig): HttpParams { return new InterceptorHttpParams( new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false) diff --git a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts index 05f6608ae5..15a710d325 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts @@ -787,9 +787,8 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa res = column.cellTooltipFunction(entity, column.key); res = isDefined(res) ? res : null; this.cellTooltipCache[index] = res; - } else { - return res !== null ? res : undefined; } + return res !== null ? res : undefined; } else { return undefined; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 23578f5490..cf6e9d0cca 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -62,93 +62,7 @@ } @case ('progress') { - @if (data.update) { - - } @else { -
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { - @if (i > 0) { -
- } - @if (ep.status === 'conflict' || ep.status === 'error') { -
-
-
- warning -
-
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - @if (ep.status === 'conflict') { - - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} - - } - @if (ep.status === 'error' && ep.errorMessage) { - {{ ep.errorMessage }} - } -
-
-
- @if (ep.status === 'conflict') { - @if (ep.conflictType === 'use-or-overwrite') { - - - } @else { - - - } - } - @if (ep.status === 'error') { - - } -
-
- } @else { -
-
- @switch (ep.status) { - @case ('pending') { -
{{ i + 1 }}
- } - @case ('running') { - - } - @case ('success') { - check_circle - } - } -
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - - @if (ep.status === 'success') { - {{ 'iot-hub.done' | translate }} - } - @if (ep.status === 'running') { - {{ 'iot-hub.in-progress' | translate }} - } - -
- } - } -
- } + } } @@ -156,18 +70,17 @@ - @let hint = textWithLink('iot-hub.device-update-modified'); - {{ hint.before }}{{ hint.link }}{{ hint.after }} + {{ modifiedHintText.before }}{{ modifiedHintText.link }}{{ modifiedHintText.after }} - - + +
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { + @for (ep of ws.entitySteps; track ep.step; let i = $index) { @if (i > 0) {
} - @let plan = updatePlanOf(ep); + @let plan = planOf(ep); @let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name); @if (ws.reviewing && plan && !plan.confirmed) {
@@ -182,7 +95,7 @@ } @if (plan.existing) { - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} + {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate), name: plan.existing.name } }} } @if (plan.shared) { @@ -198,19 +111,21 @@
@if (plan.existing) { @if (ep.step.type === 'DASHBOARD') { - } @else { - } - + @if (canOverwriteExisting(ep)) { + + } } @else { - } @@ -237,7 +152,7 @@ } @case ('success') { - check_circle + check_circle } @default {
{{ i + 1 }}
@@ -249,7 +164,8 @@ {{ label }} - @if (plan?.action === 'create' && plan.resolution !== 'use-existing') { + + @if (data.update && plan?.action === 'create' && plan.resolution !== 'use-existing') { {{ 'iot-hub.device-update-new' | translate }} }
@@ -274,10 +190,10 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ updateOutcomeOf(plan) | translate }} + {{ appliedOutcomeOf(plan) | translate }} } @case ('skipped') { - {{ 'iot-hub.device-update-skipped' | translate }} + {{ 'iot-hub.device-package-skipped' | translate }} } @default { @@ -335,7 +251,7 @@
- @for (ws of wizardSteps; track ws.label) { + @for (ws of wizardSteps; track ws) { @@ -359,8 +275,8 @@ done - @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -378,24 +294,24 @@ } - @if (data.update && currentWizardStep?.type === 'progress') { + @if (currentWizardStep?.type === 'progress') { @let step = currentWizardStep; - @if (hasUpdateError(step)) { -
+ @if (hasPackageError(step)) { +
error {{ step.progressError }}
- } @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { -
+ } @else if (step.reviewing && !step.checking && unconfirmedWarnings(step) > 0) { +
warning - {{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }} + {{ 'iot-hub.device-package-confirm-warnings' | translate:{ count: unconfirmedWarnings(step), action: (applyActionKey | translate) } }}
} } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -432,13 +348,13 @@ } @case ('progress') { - @if (data.update && (step.reviewing || step.updating || step.progressError)) { - @if (step.progressError && !step.updating) { - - + - } @else if (step.updating) { + } @else if (step.applying) { } - } @else if (step.progressError) { - - } @else if (step.progressDone && isLastWizardStep) { - } @else if (!step.progressError) { + } @else { -
+ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 63fa684164..41e586417b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +@import "../../../../../scss/constants"; + :host { display: block; max-width: 600px; @@ -13,6 +15,12 @@ letter-spacing: 0.1px; color: rgba(0, 0, 0, 0.87); margin: 0; + padding: 24px 24px 20px; + + // No baseline strut: the title keeps its own line height + &::before { + display: none; + } } .tb-iot-hub-delete-desc { @@ -23,3 +31,28 @@ color: rgba(0, 0, 0, 0.54); margin: 0; } + +.tb-iot-hub-kept-groups { + border: 1px solid color-mix(in srgb, var(--tb-primary-500) 40%, transparent); + + // Groups share the outer border; hide tb-image-references' own + ::ng-deep tb-image-references table.tb-entities-list-table { + padding: 0 10px 0 4px; + background: transparent; + + &:before { + display: none; + } + + // Narrow dialog: let type and name wrap + td.tb-entity-type { + @media #{$mat-xs} { + white-space: normal !important; + } + } + + td.tb-entity-name { + overflow-wrap: anywhere; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 88bdf96fff..32cd6324c6 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -7,7 +7,7 @@ import { Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; +import { IotHubInstalledItemKeptEntities, IotHubKeptEntity } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { ResourceReferences } from '@shared/models/resource.models'; @@ -30,10 +30,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent, @@ -46,13 +44,21 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); + const shared = kept?.entities ?? []; + const referenced = kept?.referencedEntities ?? []; + const references = (entities: IotHubKeptEntity[]): ResourceReferences => + entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); + if (shared.length) { // Kept because other packages use them, because the user had them before the package, or both const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; - this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length }); - this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length }); + this.keptGroups.push({ reason: this.translate.instant(reasonKey, { kept: shared.length }), references: references(shared) }); + } + if (referenced.length) { + this.keptGroups.push({ reason: this.translate.instant('iot-hub.remove-kept-referenced'), references: references(referenced) }); + } + if (this.keptGroups.length) { + this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + referenced.length }); } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 7f1dbac04e..a5a013b68d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -128,12 +128,16 @@ @if (!isLoading && dataSource.length === 0) {
-

{{ 'iot-hub.no-installed-items' | translate }}

-

{{ 'iot-hub.no-installed-items-text' | translate }}

- @if (hasActiveFilters()) { - + @if (loadFailed) { +

{{ 'iot-hub.unable-to-load' | translate }}

+

{{ 'iot-hub.unable-to-load-text' | translate }}

+ + } @else { +

{{ (onlyUpdates ? 'iot-hub.no-items-with-updates' : 'iot-hub.no-installed-items') | translate }}

+

{{ 'iot-hub.no-installed-items-text' | translate }}

+ @if (hasActiveFilters()) { + + } }
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3c196cdb66..4b50ad533a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -44,7 +44,7 @@ import { loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, forkJoin } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -82,6 +82,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; + updatesCheckFailed = false; + onlyUpdates = false; + // Totals, ignoring type filters and search + updatesCount: number | null = null; + installedCount = 0; + loadFailed = false; + private loadRun = 0; + private countRun = 0; private widgetResize$: ResizeObserver; @@ -127,10 +135,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngOnChanges(changes: SimpleChanges): void { if (changes.textSearch || changes.typeFilters) { if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) { - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } + this.setPageIndex(0); this.loadData(); } } @@ -138,8 +143,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngAfterViewInit(): void { this.sort.sortChange.subscribe(() => { - this.pageIndex = 0; - this.paginator.pageIndex = 0; + this.setPageIndex(0); this.loadData(); }); } @@ -161,7 +165,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, deleteItem(item: IotHubInstalledItem): void { this.iotHubActions.deleteItem(item).subscribe(deleted => { if (deleted) { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -191,7 +195,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { if (result === 'updated' || result === 'deleted') { - this.loadData(); + this.reloadAfterChange(); } }); }); @@ -241,18 +245,111 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + if (this.updatesChecked) { + // Only the count failed: recount, keeping the list as it is + this.loadUpdatesCount(); + return; + } + this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true })) + // Failure is shown next to the button, not as an error toast + switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - this.updatesChecked = true; + this.loadUpdatesCount(() => { + this.updatesChecked = true; + // No updates: stay on the full list (it also shows converter updates) + this.showOnlyUpdates(this.updatesCount > 0); + }); + }, + error: () => { this.isCheckingUpdates = false; - void this.checkConverterUpdates(); + this.updatesCheckFailed = true; + } + }); + } + + showOnlyUpdates(onlyUpdates: boolean): void { + this.onlyUpdates = onlyUpdates; + this.setPageIndex(0); + this.loadData(); + } + + private setPageIndex(pageIndex: number): void { + this.pageIndex = pageIndex; + if (this.paginator) { + this.paginator.pageIndex = pageIndex; + } + } + + private publishedVersionIds(): Record { + const ids: Record = {}; + this.publishedVersionMap.forEach((info, itemId) => { + if (info.publishedVersionId) { + ids[itemId] = info.publishedVersionId; + } + }); + return ids; + } + + retryLoad(): void { + this.loadData(); + if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { + this.loadUpdatesCount(); + } + } + + private reloadAfterChange(): void { + if (!this.updatesChecked || this.itemVersion) { + this.loadData(); + return; + } + this.loadUpdatesCount(() => { + if (this.onlyUpdates && this.updatesCount === 0) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }, () => { + // Count failed: fall back to the full list + if (this.onlyUpdates) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }); + } + + // Latest call wins; previous counts stay until it returns + private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { + const run = ++this.countRun; + const config = { ignoreLoading: true, ignoreErrors: true }; + forkJoin({ + withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), config), + installed: this.iotHubApiService.getInstalledItemsCount(undefined, config) + }).subscribe({ + next: ({ withUpdates, installed }) => { + if (run !== this.countRun) { + return; + } + this.updatesCount = withUpdates.totalElements; + this.installedCount = installed; + this.updatesCheckFailed = false; + this.isCheckingUpdates = false; + this.cd.markForCheck(); + onCounts?.(); }, error: () => { + if (run !== this.countRun) { + return; + } + this.updatesCount = null; + this.updatesCheckFailed = true; this.isCheckingUpdates = false; + this.cd.markForCheck(); + onError?.(); } }); } @@ -260,7 +357,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { if (result === 'updated') { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -341,18 +438,37 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}).subscribe({ + // The empty state shows a failure of the only-updates list; one item's versions page lists them all + const items$ = this.onlyUpdates && !this.itemVersion + ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true, ignoreErrors: true}) + : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); + const run = ++this.loadRun; + items$.subscribe({ next: (data) => { + if (run !== this.loadRun) { + return; + } + // The last page emptied after an update or a removal + if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { + this.setPageIndex(Math.ceil(data.totalElements / this.pageSize) - 1); + this.loadData(); + return; + } this.dataSource = data.data; this.totalElements = data.totalElements; + this.loadFailed = false; this.isLoading = false; - if (this.updatesChecked && !this.itemVersion) { + if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } }, error: () => { + if (run !== this.loadRun) { + return; + } this.dataSource = []; this.totalElements = 0; + this.loadFailed = true; this.isLoading = false; } }); diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss index 3e91fc24ac..32b040769c 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss @@ -15,7 +15,6 @@ padding: 0; } mat-cell.mat-column-name { - white-space: nowrap; .mat-mdc-icon-button { vertical-align: middle; margin-left: 8px; diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts index 4da08170a7..280fbfad07 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts @@ -95,22 +95,28 @@ export class CustomMenuTableComponent implements OnInit { this.customMenuTableConfig.entitiesDeleteEnabled = !readonly && authUser.authority !== Authority.SYS_ADMIN; this.customMenuTableConfig.addEntity = () => this.addCustomMenu(); - let mainColumnsWidth: string; + let nameColumnWidth: string; + let scopeColumnWidth: string; + let assigneeTypeColumnWidth: string; switch (authUser.authority) { case Authority.SYS_ADMIN: - mainColumnsWidth = '50%'; + nameColumnWidth = '60%'; + scopeColumnWidth = '20%'; break; case Authority.TENANT_ADMIN: - mainColumnsWidth = '33%'; + nameColumnWidth = '50%'; + scopeColumnWidth = '15%'; + assigneeTypeColumnWidth = '15%'; break; case Authority.CUSTOMER_USER: - mainColumnsWidth = '50%'; + nameColumnWidth = '60%'; + assigneeTypeColumnWidth = '20%'; break; } this.customMenuTableConfig.columns.push( new DateEntityTableColumn('createdTime', 'common.created-time', this.datePipe, '150px'), - new EntityTableColumn('name', 'custom-menu.name', mainColumnsWidth, + new EntityTableColumn('name', 'custom-menu.name', nameColumnWidth, entity => entity.name, _entity => ({}), true, () => ({}), () => undefined, false, { name: this.translate.instant('custom-menu.edit-name'), @@ -120,12 +126,12 @@ export class CustomMenuTableComponent implements OnInit { }) ); if (authUser.authority !== Authority.CUSTOMER_USER) { - this.customMenuTableConfig.columns.push(new EntityTableColumn('scope', 'custom-menu.scope', mainColumnsWidth, + this.customMenuTableConfig.columns.push(new EntityTableColumn('scope', 'custom-menu.scope', scopeColumnWidth, (menu) => this.translate.instant(cmScopeTranslations.get(menu.scope)))); } if (authUser.authority !== Authority.SYS_ADMIN) { this.customMenuTableConfig.columns.push(new EntityTableColumn('assigneeType', - 'custom-menu.assignee-type', mainColumnsWidth, + 'custom-menu.assignee-type', assigneeTypeColumnWidth, (menu) => this.translate.instant(cmAssigneeTypeTranslations(menu.assigneeType, menu.scope)))); } if (authUser.authority !== Authority.SYS_ADMIN) { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7591b1dc5a..8702709c3e 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -1,7 +1,8 @@
@@ -14,16 +15,38 @@

{{ 'iot-hub.installed-items' | translate }}

- @if (!updatesChecked) { - - } + + @if (!updatesChecked || updatesCheckFailed) { + + } + @if (updatesChecked) { + @if (onlyUpdates) { + + } @else if (updatesCount > 0) { + + } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts index 1af2d5ed2c..47aa3e5080 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; @@ -107,4 +108,24 @@ export class TbIotHubInstalledItemsComponent implements OnInit, OnDestroy { get updatesChecked(): boolean { return this.tableComponent?.updatesChecked || false; } + + get updatesCheckFailed(): boolean { + return this.tableComponent?.updatesCheckFailed || false; + } + + get onlyUpdates(): boolean { + return this.tableComponent?.onlyUpdates || false; + } + + get updatesCount(): number | null { + return this.tableComponent?.updatesCount ?? null; + } + + get installedCount(): number { + return this.tableComponent?.installedCount || 0; + } + + showOnlyUpdates(onlyUpdates: boolean): void { + this.tableComponent?.showOnlyUpdates(onlyUpdates); + } } diff --git a/ui-ngx/src/app/modules/home/pages/notification/sent/sent-notification-dialog.component.html b/ui-ngx/src/app/modules/home/pages/notification/sent/sent-notification-dialog.component.html index 78c8eaa400..b525ccc7e9 100644 --- a/ui-ngx/src/app/modules/home/pages/notification/sent/sent-notification-dialog.component.html +++ b/ui-ngx/src/app/modules/home/pages/notification/sent/sent-notification-dialog.component.html @@ -96,42 +96,42 @@ } } + @if (!isSysAdmin()) { +
+ +
+ notification.attach-report +
+
+ @if (notificationRequestForm.get('template.configuration.attachReport').value) { +
+ + {{'report-template.report-template-required' | translate}} + + + + + +
+ } +
+ } - @if (!isSysAdmin()) { -
- -
- notification.attach-report -
-
- @if (notificationRequestForm.get('template.configuration.attachReport').value) { -
- - {{'report-template.report-template-required' | translate}} - - - - - -
- } -
- } }
diff --git a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts index d204428919..abc023eb2c 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts @@ -355,10 +355,8 @@ export interface EntityStepOutput { baseUrl?: string; } -// skipped: a step of an update that failed, so nothing was changed -export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict' | 'skipped'; - -export type ConflictType = 'use-or-overwrite' | 'overwrite-or-copy'; +// skipped: a step of an install or update that failed, so nothing was changed +export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'skipped'; export interface EntityStepProgress { step: DeviceInstallStep; @@ -366,7 +364,5 @@ export interface EntityStepProgress { resolvedName?: string; entityOutput?: EntityStepOutput; errorMessage?: string; - existingEntity?: EntityStepOutput; - conflictType?: ConflictType; resolution?: string; } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 07fac4bf63..cbd684f927 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -48,8 +48,8 @@ export interface DevicePackageEntityState { shared: boolean; } -/** A step of a device package update, with its entity resolved from the template of the new version. */ -export interface DeviceUpdateStep { +/** A step of a device package install or update, with its entity resolved from the template of the version being installed. */ +export interface DevicePackageStep { name: string; type: string; action: 'KEEP' | 'OVERWRITE' | 'CREATE'; @@ -58,7 +58,7 @@ export interface DeviceUpdateStep { confirmed?: boolean; entity?: any; credentials?: any; - // OVERWRITE and CREATE: the attributes the saved entity gets, as at install + // OVERWRITE and CREATE: the attributes the saved entity gets serverAttributes?: any; sharedAttributes?: any; resolution?: string; @@ -71,18 +71,21 @@ export interface DeviceUpdateStep { defaultConverter?: boolean; } -export interface DeviceUpdateRequest { +export interface DevicePackageRequest { versionId: string; - // The version installed when the update was planned: the server refuses the update if the package changed since + // Update only: the version installed when the update was planned; the server refuses it if the package changed since fromVersionId?: string; - // The install method of the new version's steps + // The install method of the steps selectedInstallMethod?: string; installState: Record; - steps: DeviceUpdateStep[]; + steps: DevicePackageStep[]; + // Install only: the owner of the device, gateway and dashboard, and the group the created device joins + customerId?: string; + entityGroupId?: string; } -/** All of the update was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */ -export interface DeviceUpdateResult { +/** All of the request was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */ +export interface DevicePackageResult { success: boolean; errorMessage?: string; failedStep?: string; @@ -159,7 +162,7 @@ export interface ItemPublishedVersionInfo { publishedVersion: string; } -/** An entity that deleting an installed item keeps, because other installed items use it too. */ +/** An entity that deleting an installed item keeps. */ export interface IotHubKeptEntity { entityId: { id: string; entityType: string }; name: string; @@ -170,6 +173,8 @@ export interface IotHubInstalledItemKeptEntities { usedByItemsCount: number; // Of the kept entities, the ones the user had before and the package took as they were usedExistingCount: number; + // Absent from older backends + referencedEntities?: IotHubKeptEntity[]; } export interface IotHubInstalledItem extends BaseData<{id: string}> { diff --git a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json index 9d4a8f0645..c4cbd46269 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json +++ b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json @@ -6538,9 +6538,6 @@ "step-configuration": "التكوين", "step-provisioning": "التزويد", "device-install-step-error": "فشل", - "device-install-step-pending": "قيد الانتظار", - "device-install-step-running": "جارٍ الإنشاء...", - "device-install-step-success": "تم الإنشاء", "device-install-step-type-DASHBOARD": "لوحة المعلومات", "device-install-step-type-DEVICE": "جهاز", "device-install-step-type-DEVICE_PROFILE": "ملف تعريف الجهاز", @@ -6552,7 +6549,7 @@ "device-install-step-type-INTEGRATION": "التكامل", "use-secret": "استخدام سر", "use-plain-text": "استخدام نص عادي", - "device-install-conflict-exists": "يوجد {{type}} بهذا الاسم بالفعل", + "device-install-conflict-exists": "يوجد {{type}} بالاسم \"{{name}}\" بالفعل", "device-install-use-existing": "استخدام الموجود", "device-install-transport-host-step": "الاتصال", "device-install-thingsboard-connection": "الاتصال بمنصة ThingsBoard", @@ -6586,20 +6583,18 @@ "device-installing-title": "جارٍ تثبيت \"{{name}}\"", "device-update-title": "تحديث \"{{name}}\"", "device-update-step": "تحديث", - "device-update-no-conflicts": "لا توجد تعارضات", "device-update-new": "جديد", "device-update-shared": "تستخدمه حزم أخرى. يؤثر التحديث عليها.", "device-update-new-default-converter": "يتوفر في منصة ThingsBoard إصدار جديد من المحوّل الافتراضي الذي تستخدمه هذه الحزمة.", "device-update-modified": "يحتوي على تغييرات محلية. يمكنك تنزيل الإصدار الحالي من هنا.", "device-install-unexpected-error": "حدث خطأ ما. حاول مرة أخرى.", - "device-update-existing-use-existing": "موجود بالفعل. سيتم استخدام العنصر الموجود.", - "device-update-existing-overwrite": "موجود بالفعل. ستتم الكتابة فوقه.", - "device-update-existing-create-copy": "موجود بالفعل. سيتم إنشاء نسخة.", - "device-update-confirm-warnings": "أكّد {count, plural, one {تحذيرًا واحدًا} two {تحذيرين} few {# تحذيرات} many {# تحذيرًا} other {# تحذير} } لتمكين زر \"تحديث\"", - "device-update-skipped": "لم يتغير", - "device-update-updated": "تم التحديث", - "device-update-created": "تم الإنشاء", - "device-update-try-again": "إعادة المحاولة", + "device-package-will-create": "سيتم الإنشاء", + "device-install-nothing-installed": "لم يتم تثبيت أي شيء.", + "device-package-confirm-warnings": "أكّد {count, plural, one {تحذيرًا واحدًا} two {تحذيرين} few {# تحذيرات} many {# تحذيرًا} other {# تحذير} } لتمكين زر \"{action}\"", + "device-package-skipped": "لم يتغير", + "device-package-updated": "تم التحديث", + "device-package-created": "تم الإنشاء", + "device-package-try-again": "إعادة المحاولة", "done": "تم", "in-progress": "قيد التنفيذ", "item-detail": "عنصر IoT Hub", diff --git a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json index c0a5da79a5..ec5a7aa027 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json @@ -6540,9 +6540,6 @@ "step-configuration": "Configuració", "step-provisioning": "Aprovisionament", "device-install-step-error": "Ha fallat", - "device-install-step-pending": "Pendent", - "device-install-step-running": "S'està creant...", - "device-install-step-success": "Creat", "device-install-step-type-DASHBOARD": "Tauler", "device-install-step-type-DEVICE": "Dispositiu", "device-install-step-type-DEVICE_PROFILE": "Perfil de dispositiu", @@ -6554,7 +6551,7 @@ "device-install-step-type-INTEGRATION": "Integració", "use-secret": "Utilitza un secret", "use-plain-text": "Utilitza text pla", - "device-install-conflict-exists": "{{type}}: aquest nom ja existeix", + "device-install-conflict-exists": "{{type}}: el nom \"{{name}}\" ja existeix", "device-install-use-existing": "Utilitza l'existent", "device-install-transport-host-step": "Connexió", "device-install-thingsboard-connection": "Connexió amb ThingsBoard", @@ -6588,20 +6585,18 @@ "device-installing-title": "S'està instal·lant \"{{name}}\"", "device-update-title": "Actualitza \"{{name}}\"", "device-update-step": "Actualització", - "device-update-no-conflicts": "Sense conflictes", "device-update-new": "Nou", "device-update-shared": "L'utilitzen altres paquets. L'actualització els afecta.", "device-update-new-default-converter": "ThingsBoard té una versió nova del convertidor per defecte que utilitza aquest paquet.", "device-update-modified": "Té canvis locals. Podeu baixar la versió actual aquí.", "device-install-unexpected-error": "S'ha produït un error. Torneu-ho a provar.", - "device-update-existing-use-existing": "Ja existeix. S'utilitzarà l'existent.", - "device-update-existing-overwrite": "Ja existeix. Se sobreescriurà.", - "device-update-existing-create-copy": "Ja existeix. Se'n crearà una còpia.", - "device-update-confirm-warnings": "Confirmeu { count, plural, one {1 avís} other {# avisos} } per activar el botó Actualitza", - "device-update-skipped": "Sense canvis", - "device-update-updated": "Actualitzat", - "device-update-created": "Creat", - "device-update-try-again": "Torna-ho a provar", + "device-package-will-create": "Es crearà", + "device-install-nothing-installed": "No s'ha instal·lat res.", + "device-package-confirm-warnings": "Confirmeu { count, plural, one {1 avís} other {# avisos} } per activar el botó {action}", + "device-package-skipped": "Sense canvis", + "device-package-updated": "Actualitzat", + "device-package-created": "Creat", + "device-package-try-again": "Torna-ho a provar", "done": "Fet", "in-progress": "En curs", "item-detail": "Element de l'IoT Hub", diff --git a/ui-ngx/src/assets/locale/locale.constant-da_DK.json b/ui-ngx/src/assets/locale/locale.constant-da_DK.json index f00e849310..13e561fc14 100644 --- a/ui-ngx/src/assets/locale/locale.constant-da_DK.json +++ b/ui-ngx/src/assets/locale/locale.constant-da_DK.json @@ -6488,9 +6488,6 @@ "step-configuration": "Konfiguration", "step-provisioning": "Klargøring", "device-install-step-error": "Mislykket", - "device-install-step-pending": "Afventer", - "device-install-step-running": "Opretter...", - "device-install-step-success": "Oprettet", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Enhed", "device-install-step-type-DEVICE_PROFILE": "Enhedsprofil", diff --git a/ui-ngx/src/assets/locale/locale.constant-de_DE.json b/ui-ngx/src/assets/locale/locale.constant-de_DE.json index 84a60ef4a3..f3e6b6e961 100644 --- a/ui-ngx/src/assets/locale/locale.constant-de_DE.json +++ b/ui-ngx/src/assets/locale/locale.constant-de_DE.json @@ -6486,9 +6486,6 @@ "step-configuration": "Konfiguration", "step-provisioning": "Provisionierung", "device-install-step-error": "Fehlgeschlagen", - "device-install-step-pending": "Ausstehend", - "device-install-step-running": "Wird erstellt...", - "device-install-step-success": "Erstellt", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Gerät", "device-install-step-type-DEVICE_PROFILE": "Geräteprofil", diff --git a/ui-ngx/src/assets/locale/locale.constant-el_GR.json b/ui-ngx/src/assets/locale/locale.constant-el_GR.json index 6cb8c633e5..b357c5f111 100644 --- a/ui-ngx/src/assets/locale/locale.constant-el_GR.json +++ b/ui-ngx/src/assets/locale/locale.constant-el_GR.json @@ -6500,9 +6500,6 @@ "step-configuration": "Διαμόρφωση", "step-provisioning": "Παροχή", "device-install-step-error": "Αποτυχία", - "device-install-step-pending": "Σε εκκρεμότητα", - "device-install-step-running": "Δημιουργία...", - "device-install-step-success": "Δημιουργήθηκε", "device-install-step-type-DASHBOARD": "Πίνακας ελέγχου", "device-install-step-type-DEVICE": "Συσκευή", "device-install-step-type-DEVICE_PROFILE": "Προφίλ συσκευής", diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 1bb3ad848f..8868b2c777 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6452,6 +6452,7 @@ "remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }", "remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.", + "remove-kept-referenced": "Referenced by other tenant entities.", "remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", @@ -6497,6 +6498,11 @@ "install-partial-desc": "'{{name}}' was installed, but some required items were missing.", "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", + "check-for-updates-failed": "Couldn't check for updates", + "items-with-update": "Updates available for {{count}} of {{total}}", + "no-newer-versions": "No newer versions in IoT Hub", + "show-all-items": "Show all items", + "show-only-updates": "Show only updates", "updates": "Updates", "up-to-date": "Up to date", "new-converter-available": "New converter available", @@ -6528,6 +6534,7 @@ "installed-date": "Installed", "no-installed-items": "No installed items found", "no-installed-items-text": "Try adjusting your search or filters.", + "no-items-with-updates": "No items with updates match your filters", "remove-installed-item-title": "Remove Installed Item", "remove-installed-item-text": "Are you sure you want to remove '{{name}}'? The installed entity will also be removed.", "installed-item-removed": "'{{name}}' has been removed", @@ -6544,9 +6551,6 @@ "step-configuration": "Configuration", "step-provisioning": "Provisioning", "device-install-step-error": "Failed", - "device-install-step-pending": "Pending", - "device-install-step-running": "Creating...", - "device-install-step-success": "Created", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Device", "device-install-step-type-DEVICE_PROFILE": "Device Profile", @@ -6558,7 +6562,7 @@ "device-install-step-type-INTEGRATION": "Integration", "use-secret": "Use Secret", "use-plain-text": "Use plain text", - "device-install-conflict-exists": "{{type}} with this name already exists", + "device-install-conflict-exists": "{{type}} named \"{{name}}\" already exists", "device-install-use-existing": "Use existing", "device-install-transport-host-step": "Connection", "device-install-thingsboard-connection": "ThingsBoard connection", @@ -6593,7 +6597,7 @@ "device-update-title": "Update \"{{name}}\"", "device-update-step": "Update", "device-update-will-update": "Will be updated", - "device-update-will-create": "Will be created", + "device-package-will-create": "Will be created", "device-update-no-changes": "No changes", "device-update-new": "New", "device-update-shared": "Used by other packages. The update affects them.", @@ -6603,11 +6607,12 @@ "device-update-modified": "Has local changes. You can download the current version here.", "device-install-unexpected-error": "Something went wrong. Try again.", "device-install-duplicate-step": "Two install steps of this device package have the same key: {{key}}. Report it to the package's creator.", - "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", - "device-update-skipped": "Unchanged", - "device-update-updated": "Updated", - "device-update-created": "Created", - "device-update-try-again": "Try again", + "device-install-nothing-installed": "Nothing was installed.", + "device-package-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable {action}", + "device-package-skipped": "Unchanged", + "device-package-updated": "Updated", + "device-package-created": "Created", + "device-package-try-again": "Try again", "done": "Done", "in-progress": "In progress", "item-detail": "IoT Hub item", diff --git a/ui-ngx/src/assets/locale/locale.constant-es_ES.json b/ui-ngx/src/assets/locale/locale.constant-es_ES.json index aa4741bd7a..a3681b6a18 100644 --- a/ui-ngx/src/assets/locale/locale.constant-es_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-es_ES.json @@ -6486,9 +6486,6 @@ "step-configuration": "Configuración", "step-provisioning": "Aprovisionamiento", "device-install-step-error": "Fallido", - "device-install-step-pending": "Pendiente", - "device-install-step-running": "Creando...", - "device-install-step-success": "Creado", "device-install-step-type-DASHBOARD": "Tablero", "device-install-step-type-DEVICE": "Dispositivo", "device-install-step-type-DEVICE_PROFILE": "Perfil de dispositivo", diff --git a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json index 73528b2a47..63f0fe85cf 100644 --- a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json +++ b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json @@ -6486,9 +6486,6 @@ "step-configuration": "Configuration", "step-provisioning": "Provisionnement", "device-install-step-error": "Échoué", - "device-install-step-pending": "En attente", - "device-install-step-running": "Création...", - "device-install-step-success": "Créé", "device-install-step-type-DASHBOARD": "Tableau de bord", "device-install-step-type-DEVICE": "Appareil", "device-install-step-type-DEVICE_PROFILE": "Profil d’appareil", diff --git a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json index 720818d17d..1c5ddda58c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json +++ b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json @@ -6526,9 +6526,6 @@ "step-configuration": "कॉन्फ़िगरेशन", "step-provisioning": "प्रोविज़निंग", "device-install-step-error": "विफल", - "device-install-step-pending": "लंबित", - "device-install-step-running": "बनाया जा रहा है...", - "device-install-step-success": "बनाया गया", "device-install-step-type-DASHBOARD": "डैशबोर्ड", "device-install-step-type-DEVICE": "डिवाइस", "device-install-step-type-DEVICE_PROFILE": "डिवाइस प्रोफ़ाइल", diff --git a/ui-ngx/src/assets/locale/locale.constant-it_IT.json b/ui-ngx/src/assets/locale/locale.constant-it_IT.json index 8372c35279..69861c2894 100644 --- a/ui-ngx/src/assets/locale/locale.constant-it_IT.json +++ b/ui-ngx/src/assets/locale/locale.constant-it_IT.json @@ -6486,9 +6486,6 @@ "step-configuration": "Configurazione", "step-provisioning": "Provisioning", "device-install-step-error": "Non riuscito", - "device-install-step-pending": "In attesa", - "device-install-step-running": "Creazione in corso...", - "device-install-step-success": "Creato", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Dispositivo", "device-install-step-type-DEVICE_PROFILE": "Profilo dispositivo", diff --git a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json index 1bfd8e7fe4..1f22ff8978 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json +++ b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json @@ -6486,9 +6486,6 @@ "step-configuration": "設定", "step-provisioning": "プロビジョニング", "device-install-step-error": "失敗", - "device-install-step-pending": "待機中", - "device-install-step-running": "作成中...", - "device-install-step-success": "作成済み", "device-install-step-type-DASHBOARD": "ダッシュボード", "device-install-step-type-DEVICE": "デバイス", "device-install-step-type-DEVICE_PROFILE": "デバイスプロファイル", diff --git a/ui-ngx/src/assets/locale/locale.constant-ko_KR.json b/ui-ngx/src/assets/locale/locale.constant-ko_KR.json index ef15b5a1fb..f28a6256a5 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ko_KR.json +++ b/ui-ngx/src/assets/locale/locale.constant-ko_KR.json @@ -6518,9 +6518,6 @@ "step-configuration": "구성", "step-provisioning": "프로비저닝", "device-install-step-error": "실패", - "device-install-step-pending": "대기 중", - "device-install-step-running": "생성 중...", - "device-install-step-success": "생성됨", "device-install-step-type-DASHBOARD": "대시보드", "device-install-step-type-DEVICE": "장치", "device-install-step-type-DEVICE_PROFILE": "장치 프로필", diff --git a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json index a841c8ebde..41b89f8e0b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json +++ b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json @@ -6526,9 +6526,6 @@ "step-configuration": "Konfigūracija", "step-provisioning": "Paruošimas", "device-install-step-error": "Nepavyko", - "device-install-step-pending": "Laukiama", - "device-install-step-running": "Kuriama...", - "device-install-step-success": "Sukurta", "device-install-step-type-DASHBOARD": "Skydelis", "device-install-step-type-DEVICE": "Įrenginys", "device-install-step-type-DEVICE_PROFILE": "Įrenginio profilis", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_BE.json b/ui-ngx/src/assets/locale/locale.constant-nl_BE.json index 818c258f6b..e9c6d9dd71 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_BE.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_BE.json @@ -6526,9 +6526,6 @@ "step-configuration": "Configuratie", "step-provisioning": "Provisioning", "device-install-step-error": "Mislukt", - "device-install-step-pending": "In afwachting", - "device-install-step-running": "Aanmaken...", - "device-install-step-success": "Aangemaakt", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Apparaat", "device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json index a732821c84..ae281e0ac6 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json @@ -6486,9 +6486,6 @@ "step-configuration": "Configuratie", "step-provisioning": "Provisioning", "device-install-step-error": "Mislukt", - "device-install-step-pending": "In afwachting", - "device-install-step-running": "Aanmaken...", - "device-install-step-success": "Aangemaakt", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Apparaat", "device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel", diff --git a/ui-ngx/src/assets/locale/locale.constant-no_NO.json b/ui-ngx/src/assets/locale/locale.constant-no_NO.json index caa59dfb9b..50cd07ab9c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-no_NO.json +++ b/ui-ngx/src/assets/locale/locale.constant-no_NO.json @@ -6500,9 +6500,6 @@ "step-configuration": "Konfigurasjon", "step-provisioning": "Klargjøring", "device-install-step-error": "Mislyktes", - "device-install-step-pending": "Venter", - "device-install-step-running": "Oppretter...", - "device-install-step-success": "Opprettet", "device-install-step-type-DASHBOARD": "Dashbord", "device-install-step-type-DEVICE": "Enhet", "device-install-step-type-DEVICE_PROFILE": "Enhetsprofil", diff --git a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json index ab805d2ea3..4adf0ece21 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json +++ b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json @@ -6526,9 +6526,6 @@ "step-configuration": "Konfiguracja", "step-provisioning": "Aprowizacja", "device-install-step-error": "Niepowodzenie", - "device-install-step-pending": "Oczekuje", - "device-install-step-running": "Tworzenie...", - "device-install-step-success": "Utworzono", "device-install-step-type-DASHBOARD": "Pulpit", "device-install-step-type-DEVICE": "Urządzenie", "device-install-step-type-DEVICE_PROFILE": "Profil urządzenia", diff --git a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json index 57a7bc2b4d..4c18d03c04 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json +++ b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json @@ -6486,9 +6486,6 @@ "step-configuration": "Configuração", "step-provisioning": "Provisionamento", "device-install-step-error": "Falhou", - "device-install-step-pending": "Pendente", - "device-install-step-running": "Criando...", - "device-install-step-success": "Criado", "device-install-step-type-DASHBOARD": "Dashboard", "device-install-step-type-DEVICE": "Dispositivo", "device-install-step-type-DEVICE_PROFILE": "Perfil do dispositivo", diff --git a/ui-ngx/src/assets/locale/locale.constant-sl_SI.json b/ui-ngx/src/assets/locale/locale.constant-sl_SI.json index 8069af8f59..acd805dcc6 100644 --- a/ui-ngx/src/assets/locale/locale.constant-sl_SI.json +++ b/ui-ngx/src/assets/locale/locale.constant-sl_SI.json @@ -6516,9 +6516,6 @@ "step-configuration": "Konfiguracija", "step-provisioning": "Priprava", "device-install-step-error": "Ni uspelo", - "device-install-step-pending": "Na čakanju", - "device-install-step-running": "Ustvarjanje...", - "device-install-step-success": "Ustvarjeno", "device-install-step-type-DASHBOARD": "Nadzorna plošča", "device-install-step-type-DEVICE": "Naprava", "device-install-step-type-DEVICE_PROFILE": "Profil naprave", diff --git a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json index 36484511dc..5e532eb6b8 100644 --- a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json +++ b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json @@ -6488,9 +6488,6 @@ "step-configuration": "Yapılandırma", "step-provisioning": "Sağlama", "device-install-step-error": "Başarısız", - "device-install-step-pending": "Beklemede", - "device-install-step-running": "Oluşturuluyor...", - "device-install-step-success": "Oluşturuldu", "device-install-step-type-DASHBOARD": "Pano", "device-install-step-type-DEVICE": "Cihaz", "device-install-step-type-DEVICE_PROFILE": "Cihaz profili", diff --git a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json index 602efa034b..46bfc5d92a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json +++ b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json @@ -6486,9 +6486,6 @@ "step-configuration": "Конфігурація", "step-provisioning": "Реєстрація", "device-install-step-error": "Не вдалося", - "device-install-step-pending": "Очікує", - "device-install-step-running": "Створення...", - "device-install-step-success": "Створено", "device-install-step-type-DASHBOARD": "Дашборд", "device-install-step-type-DEVICE": "Пристрій", "device-install-step-type-DEVICE_PROFILE": "Профіль пристрою", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json index c52ba1e0c1..36660e7908 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json @@ -6488,9 +6488,6 @@ "step-configuration": "配置", "step-provisioning": "预配", "device-install-step-error": "失败", - "device-install-step-pending": "等待中", - "device-install-step-running": "正在创建...", - "device-install-step-success": "已创建", "device-install-step-type-DASHBOARD": "仪表板", "device-install-step-type-DEVICE": "设备", "device-install-step-type-DEVICE_PROFILE": "设备配置", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_TW.json b/ui-ngx/src/assets/locale/locale.constant-zh_TW.json index d0abb60ed6..f9bd5c4bd7 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_TW.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_TW.json @@ -9357,9 +9357,6 @@ "step-configuration": "設定", "step-provisioning": "佈建", "device-install-step-error": "失敗", - "device-install-step-pending": "等待中", - "device-install-step-running": "正在建立…", - "device-install-step-success": "已建立", "device-install-step-type-DASHBOARD": "儀表板", "device-install-step-type-DEVICE": "裝置", "device-install-step-type-DEVICE_PROFILE": "裝置設定檔",