Browse Source

Merge public lts-4.4 into lts-4.4

pull/16844/head
dshvaika 2 weeks ago
parent
commit
ef6b6ee7e1
  1. 43
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 375
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
  3. 105
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  4. 30
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java
  5. 10
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
  6. 9
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java
  7. 8
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  8. 602
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
  9. 194
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  10. 4
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java
  11. 4
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java
  12. 22
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java
  13. 14
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java
  14. 19
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java
  15. 136
      dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java
  16. 66
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  17. 3
      ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts
  18. 169
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  19. 16
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  20. 992
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  21. 2
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  22. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  23. 39
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html
  24. 33
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss
  25. 22
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  26. 16
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  27. 146
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  28. 1
      ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss
  29. 20
      ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts
  30. 43
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html
  31. 23
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts
  32. 70
      ui-ngx/src/app/modules/home/pages/notification/sent/sent-notification-dialog.component.html
  33. 8
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  34. 25
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  35. 21
      ui-ngx/src/assets/locale/locale.constant-ar_AE.json
  36. 21
      ui-ngx/src/assets/locale/locale.constant-ca_ES.json
  37. 3
      ui-ngx/src/assets/locale/locale.constant-da_DK.json
  38. 3
      ui-ngx/src/assets/locale/locale.constant-de_DE.json
  39. 3
      ui-ngx/src/assets/locale/locale.constant-el_GR.json
  40. 25
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  41. 3
      ui-ngx/src/assets/locale/locale.constant-es_ES.json
  42. 3
      ui-ngx/src/assets/locale/locale.constant-fr_FR.json
  43. 3
      ui-ngx/src/assets/locale/locale.constant-hi_IN.json
  44. 3
      ui-ngx/src/assets/locale/locale.constant-it_IT.json
  45. 3
      ui-ngx/src/assets/locale/locale.constant-ja_JP.json
  46. 3
      ui-ngx/src/assets/locale/locale.constant-ko_KR.json
  47. 3
      ui-ngx/src/assets/locale/locale.constant-lt_LT.json
  48. 3
      ui-ngx/src/assets/locale/locale.constant-nl_BE.json
  49. 3
      ui-ngx/src/assets/locale/locale.constant-nl_NL.json
  50. 3
      ui-ngx/src/assets/locale/locale.constant-no_NO.json
  51. 3
      ui-ngx/src/assets/locale/locale.constant-pl_PL.json
  52. 3
      ui-ngx/src/assets/locale/locale.constant-pt_BR.json
  53. 3
      ui-ngx/src/assets/locale/locale.constant-sl_SI.json
  54. 3
      ui-ngx/src/assets/locale/locale.constant-tr_TR.json
  55. 3
      ui-ngx/src/assets/locale/locale.constant-uk_UA.json
  56. 3
      ui-ngx/src/assets/locale/locale.constant-zh_CN.json
  57. 3
      ui-ngx/src/assets/locale/locale.constant-zh_TW.json

43
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.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; import org.thingsboard.server.service.iot_hub.DevicePackageEntityState;
import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; import org.thingsboard.server.service.iot_hub.DevicePackageService;
import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; import org.thingsboard.server.service.iot_hub.DevicePackageRequest;
import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; import org.thingsboard.server.service.iot_hub.DevicePackageResult;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan; 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 { public class IotHubController extends BaseController {
private final IotHubService iotHubService; private final IotHubService iotHubService;
private final DevicePackageUpdateService devicePackageUpdateService; private final DevicePackageService devicePackageService;
private final IotHubInstalledItemService iotHubInstalledItemService; private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService; private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
@ -103,21 +103,29 @@ public class IotHubController extends BaseController {
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); 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')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody @ResponseBody
public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions(); checkAllPermissions();
return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/deviceUpdate") @PostMapping("/installedItems/{installedItemId}/deviceUpdate")
@ResponseBody @ResponseBody
public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId,
@RequestBody DeviceUpdateRequest request) throws ThingsboardException { @RequestBody DevicePackageRequest request) throws ThingsboardException {
checkAllPermissions(); checkAllPermissions();
return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@ -146,6 +154,25 @@ public class IotHubController extends BaseController {
return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); 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<IotHubInstalledItem> 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<String> itemTypes,
@RequestBody Map<UUID, UUID> publishedVersionIds) throws ThingsboardException {
checkAllPermissions();
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/count") @GetMapping("/installedItems/count")
@ResponseBody @ResponseBody

375
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java → 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.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.AttributeScope; 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.Dashboard;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType; 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.HasName;
import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.HasVersion; 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.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.ConverterId; 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.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId; 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.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId; 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.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; 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.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; 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.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
@ -86,18 +93,17 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* Applies an update of an installed device package in one transaction. The install wizard resolves the templates * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the
* of the new version (the same way it installs them) and sends the entity of each step; this service checks the * templates of the version and sends the entity of each step; this service checks the plan, saves every entity
* plan, saves every entity and the new version of the installed item together, and rolls all of it back on a * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors,
* failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control
* rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, * and the attributes, which aren't transactional, are written after commit too.
* are written after commit too.
*/ */
@Service @Service
@TbCoreComponent @TbCoreComponent
@Slf4j @Slf4j
@RequiredArgsConstructor @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} // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id}
private static final Map<String, String> STEP_ALIASES = Map.of( private static final Map<String, String> STEP_ALIASES = Map.of(
@ -110,7 +116,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
"DOWNLINK_CONVERTER", "downlinkConverter", "DOWNLINK_CONVERTER", "downlinkConverter",
"INTEGRATION", "integration"); "INTEGRATION", "integration");
private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); 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 IotHubInstalledItemService installedItemService;
private final IotHubRestClient iotHubRestClient; private final IotHubRestClient iotHubRestClient;
@ -129,6 +135,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private final AttributesService attributesService; private final AttributesService attributesService;
private final TelemetrySubscriptionService telemetryService; private final TelemetrySubscriptionService telemetryService;
private final TransactionTemplate transactionTemplate; private final TransactionTemplate transactionTemplate;
private final ProjectInfo projectInfo;
@Override @Override
public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) { public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) {
@ -162,33 +169,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
@Override @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(); TenantId tenantId = user.getTenantId();
log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId());
Applied applied; DevicePackageResult result = apply(user, "update of " + installedItemId, () -> {
try {
DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId);
JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId());
if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) {
throw new IllegalArgumentException("The version belongs to another item"); throw new IllegalArgumentException("The version belongs to another item");
} }
validatePlan(devicePackage, request); validate(tenantId, devicePackage.descriptor(), request);
checkFeatures(tenantId, request); return transactionTemplate.execute(status -> {
validateIntegrations(tenantId, request); IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); 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) { } catch (StepFailure e) {
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey);
} catch (RestClientException e) { } catch (RestClientException e) {
log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e);
return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null);
} catch (Exception e) { } catch (Exception e) {
log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e);
return DeviceUpdateResult.error(userMessage(e), null); return DevicePackageResult.error(userMessage(e), null);
} }
afterCommit(user, tenantId, applied); afterCommit(user, tenantId, applied);
log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); return DevicePackageResult.success(applied.descriptor(), applied.outputs());
return DeviceUpdateResult.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) { 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. * whose credentials the firmware uses, are never changed.
*/ */
private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { private void validatePlan(Set<UUID> ownedIds, DevicePackageRequest request) {
if (request.getSteps() == null || request.getSteps().isEmpty()) { 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<UUID> ownedIds = ownedIds(devicePackage.descriptor());
// A form's values are saved under its key too, so an entity step may not share it // A form's values are saved under its key too, so an entity step may not share it
Set<String> stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); Set<String> 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())) { 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())) { 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()); boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
switch (step.getAction()) { switch (step.getAction()) {
case KEEP, OVERWRITE -> { case KEEP, OVERWRITE -> {
if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { 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()); 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())) { && !"GATEWAY_CONNECTOR".equals(step.getType())) {
throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); 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"); throw new IllegalArgumentException("The device and its credentials don't change on update");
} }
} }
case CREATE -> { case CREATE -> {
} }
} }
if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) {
throw new IllegalArgumentException("No entity data for update step: " + step.getName()); 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. */ /** 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) { private void checkFeatures(TenantId tenantId, DevicePackageRequest request) {
boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP
&& ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER")));
if (savesIntegrations) { if (savesIntegrations) {
subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); 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. */ /** The configuration of an integration is checked by a remote call, so before the transaction. */
private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception {
for (DeviceUpdateRequest.Step step : request.getSteps()) { for (DevicePackageRequest.Step step : request.getSteps()) {
if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) {
continue; continue;
} }
ObjectNode body = step.getEntity().deepCopy(); 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")); body.remove(List.of("id", "defaultConverterId", "downlinkConverterId"));
Integration integration = JacksonUtil.treeToValue(body, Integration.class); Integration integration = JacksonUtil.treeToValue(body, Integration.class);
integration.setTenantId(tenantId); 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); * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the
DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); * 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<UUID> ownedIds = ownedIds(previous); Set<UUID> ownedIds = ownedIds(previous);
Map<String, ObjectNode> aliasOutputs = new HashMap<>(); Map<String, ObjectNode> aliasOutputs = new HashMap<>();
Map<String, ObjectNode> outputs = new LinkedHashMap<>(); Map<String, ObjectNode> outputs = new LinkedHashMap<>();
@ -291,21 +435,22 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
List<EntityId> stepEntityIds = new ArrayList<>(); List<EntityId> stepEntityIds = new ArrayList<>();
Map<UUID, EntityId> usedExistingIds = usedExistingIds(previous); Map<UUID, EntityId> usedExistingIds = usedExistingIds(previous);
List<SavedEntity> saved = new ArrayList<>(); List<SavedEntity> saved = new ArrayList<>();
List<DeviceUpdateRequest.Step> connectorSteps = new ArrayList<>(); List<SavedEntity> grouped = new ArrayList<>();
List<DevicePackageRequest.Step> connectorSteps = new ArrayList<>();
List<StepAttributes> attributes = new ArrayList<>(); List<StepAttributes> attributes = new ArrayList<>();
DashboardId dashboardId = null; DashboardId dashboardId = null;
for (DeviceUpdateRequest.Step step : request.getSteps()) { for (DevicePackageRequest.Step step : request.getSteps()) {
try { try {
if ("GATEWAY_CONNECTOR".equals(step.getType())) { if ("GATEWAY_CONNECTOR".equals(step.getType())) {
// A connector lives in the gateway's attributes, which aren't transactional: saved after commit // 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))); connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs)));
} }
continue; continue;
} }
JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; 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(); ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.stateKey(), output); outputs.put(step.stateKey(), output);
@ -317,7 +462,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
state.put("resolution", resolution); state.put("resolution", resolution);
// A kept entity keeps the checksum of what the package left: the current one would take the // 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 // 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) { if (checksum != null) {
state.put("checksum", checksum); state.put("checksum", checksum);
} }
@ -343,8 +488,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if (result.saved() != null) { if (result.saved() != null) {
saved.add(result.saved()); saved.add(result.saved());
} }
if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { if (placement.entityGroup() != null && result.saved() != null && result.saved().created()
// As at install, the step's attributes go with the entity it saved; written after commit && 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())); attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes()));
} }
} catch (StepFailure e) { } 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 // 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 // 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) -> { previous.getInstallState().forEach((key, value) -> {
if (value instanceof ObjectNode state) { if (value instanceof ObjectNode state) {
installState.putIfAbsent(key, state); installState.putIfAbsent(key, state);
@ -376,15 +528,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
carryMetadataStates(previous, tracked, state); carryMetadataStates(previous, tracked, state);
descriptor.setInstallState(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 // Resolved once every entity is saved: attributes may refer to a later step's entity
List<StepAttributes> resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), List<StepAttributes> resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(),
resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); 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. */ /** 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 * 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. * 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()); IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId());
UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId();
if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) if (installedItem == null || !planned.equals(installedItem.getItemVersionId())
@ -432,11 +579,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return installedItem; 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()) { return switch (step.getType()) {
case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity);
case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement);
case "DASHBOARD" -> saveDashboard(tenantId, step, entity); case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement);
case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity);
case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity);
case "INTEGRATION" -> saveIntegration(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; DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null;
DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : 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); existing(tenantId, current, step);
return kept(id, current.getName()); return kept(id, current.getName());
} }
DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class);
profile.setTenantId(tenantId); profile.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(profile, id, current, step); prepareOverwrite(profile, id, current, step);
// The tenant's default profile stays the default one // 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())); 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; DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null;
Device device; Device device;
boolean created = false; boolean created = false;
if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { if (step.getAction() == DevicePackageRequest.Action.CREATE) {
Device template = JacksonUtil.treeToValue(entity, Device.class); Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId); template.setTenantId(tenantId);
template.setId(null); template.setId(null);
template.setVersion(null); template.setVersion(null);
assignCustomer(template, placement.deviceCustomerId(), null, step);
device = deviceService.saveDevice(template); device = deviceService.saveDevice(template);
created = true; created = true;
} else { } else {
Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null;
device = existing(tenantId, current, step); device = existing(tenantId, current, step);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
// Another device the user chose to overwrite; the package's own device never changes // 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); Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId); template.setTenantId(tenantId);
prepareOverwrite(template, id, current, step); prepareOverwrite(template, id, current, step);
assignCustomer(template, placement.customerId(), current, step);
device = deviceService.saveDevice(template); device = deviceService.saveDevice(template);
created = true; created = true;
} }
} }
DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); 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()); credentials = applyCredentials(tenantId, credentials, step.getCredentials());
} }
ObjectNode output = output(device.getId(), device.getName()); ObjectNode output = output(device.getId(), device.getName());
@ -500,7 +650,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if ("GATEWAY".equals(step.getType())) { if ("GATEWAY".equals(step.getType())) {
output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); 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); return new StepResult(device.getId(), output, null, saved);
} }
@ -520,16 +670,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); 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; DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null;
Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : 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); existing(tenantId, current, step);
return kept(id, current.getTitle()); return kept(id, current.getTitle());
} }
Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class);
dashboard.setTenantId(tenantId); dashboard.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(dashboard, id, current, step); prepareOverwrite(dashboard, id, current, step);
// The dashboard keeps its owner and the customers it is assigned to // 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.setCustomerId(current.getCustomerId());
} }
dashboard.setAssignedCustomers(current.getAssignedCustomers()); dashboard.setAssignedCustomers(current.getAssignedCustomers());
assignCustomer(dashboard, placement.customerId(), current, step);
} else { } else {
dashboard.setId(null); dashboard.setId(null);
dashboard.setVersion(null); dashboard.setVersion(null);
assignCustomer(dashboard, placement.customerId(), null, step);
} }
Dashboard result = dashboardService.saveDashboard(dashboard); Dashboard result = dashboardService.saveDashboard(dashboard);
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); 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; RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null;
RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : 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); existing(tenantId, current, step);
return kept(id, current.getName()); return kept(id, current.getName());
} }
JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity;
RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class);
ruleChain.setTenantId(tenantId); ruleChain.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(ruleChain, id, current, step); prepareOverwrite(ruleChain, id, current, step);
// A rule chain the tenant made its root one stays the root // 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())); 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; ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null;
Converter current = id != null ? converterService.findConverterById(tenantId, id) : 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); existing(tenantId, current, step);
return kept(id, current.getName()); return kept(id, current.getName());
} }
Converter converter = JacksonUtil.treeToValue(entity, Converter.class); Converter converter = JacksonUtil.treeToValue(entity, Converter.class);
converter.setTenantId(tenantId); converter.setTenantId(tenantId);
converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); 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); existing(tenantId, current, step);
prepareOverwrite(converter, id, current, step); prepareOverwrite(converter, id, current, step);
} else { } else {
@ -599,10 +751,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); 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; IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null;
Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : 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); existing(tenantId, current, step);
Integration merged = withMergedMetadata(current, step.getMetadata()); Integration merged = withMergedMetadata(current, step.getMetadata());
if (merged != null) { if (merged != null) {
@ -613,7 +765,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
Integration integration = JacksonUtil.treeToValue(entity, Integration.class); Integration integration = JacksonUtil.treeToValue(entity, Integration.class);
integration.setTenantId(tenantId); integration.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(integration, id, current, step); prepareOverwrite(integration, id, current, step);
// The devices keep sending to the same endpoint // 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 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) { private static Integration withMergedMetadata(Integration integration, JsonNode entries) {
if (entries == null || !entries.isObject() || entries.isEmpty()) { 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 * 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. * 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) { switch (entity) {
case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); }
case Device d -> { d.setId((DeviceId) id); d.setName(((Device) 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); ((HasVersion) entity).setVersion(currentVersion);
} }
private <T> T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { private <T> T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) {
if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { 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; 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 * 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. * 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); 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) { private static ObjectNode output(EntityId id, String name) {
@ -775,7 +927,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
} }
/** Replaces ${<alias>.<property>} of entities this update has saved, e.g. the id of a converter it created. */ /** Replaces ${<alias>.<property>} of entities the request has saved, e.g. the id of a converter it created. */
static JsonNode resolvePlaceholders(JsonNode node, Map<String, ObjectNode> aliasOutputs) { static JsonNode resolvePlaceholders(JsonNode node, Map<String, ObjectNode> aliasOutputs) {
if (node == null) { if (node == null) {
return null; return null;
@ -834,17 +986,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; 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) { private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) {
for (SavedEntity saved : applied.saved()) { for (SavedEntity saved : applied.saved()) {
try { 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); saved.created() ? ActionType.ADDED : ActionType.UPDATED, user);
if (saved.id().getEntityType() != EntityType.DEVICE) { if (saved.id().getEntityType() != EntityType.DEVICE) {
autoCommit(user, saved.id()); autoCommit(user, saved.id());
} }
} catch (Exception e) { } 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()) { 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); 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 { try {
saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity());
} catch (Exception e) { } catch (Exception e) {
@ -905,7 +1069,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
*/ */
static String userMessage(Throwable e) { static String userMessage(Throwable e) {
if (e instanceof EntityVersionMismatchException) { 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 if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException
|| e instanceof SubscriptionException) { || e instanceof SubscriptionException) {
@ -961,8 +1125,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return ids; return ids;
} }
private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) {
DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class);
if (entity != null) { if (entity != null) {
copy.setEntity(entity); copy.setEntity(entity);
} }
@ -972,6 +1136,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { 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) { 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<String, ObjectNode> outputs, List<SavedEntity> saved, private record Applied(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs, List<SavedEntity> saved,
List<DeviceUpdateRequest.Step> connectorSteps, List<StepAttributes> attributes, List<DevicePackageRequest.Step> connectorSteps, List<StepAttributes> attributes,
Map<String, ObjectNode> aliasOutputs) { Map<String, ObjectNode> aliasOutputs, EntityGroup entityGroup, List<SavedEntity> 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. */ /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */

105
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 jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil; 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.SolutionTemplateInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.PageLink;
@ -97,8 +99,10 @@ import java.util.HexFormat;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Stream;
@Service @Service
@TbCoreComponent @TbCoreComponent
@ -429,7 +433,7 @@ public class DefaultIotHubService implements IotHubService {
String itemType = installedItem.getItemType(); String itemType = installedItem.getItemType();
if ("DEVICE".equals(itemType)) { 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"); throw new IllegalArgumentException("A device package is updated by the install wizard of the new version");
} }
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); 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 * 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, * 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. * A kept integration loses the metadata entries the package added.
*/ */
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
@ -765,22 +771,42 @@ public class DefaultIotHubService implements IotHubService {
List<EntityId> ordered = new ArrayList<>(createdEntityIds); List<EntityId> ordered = new ArrayList<>(createdEntityIds);
Collections.reverse(ordered); Collections.reverse(ordered);
ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size()))); 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<UUID> referencedByKeptProfiles = new HashSet<>();
for (EntityId entityId : ordered) { for (EntityId entityId : ordered) {
if (usedExisting.contains(entityId.getId())) { if (usedExisting.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId());
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue; continue;
} }
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId()); Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) { if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); 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; continue;
} }
try { try {
deleteDevicePackageEntity(tenantId, entityId, user); deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) { } 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"); throw new IllegalArgumentException("Installed item not found");
} }
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>(); List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
List<InstalledItemKeptEntities.KeptEntity> referenced = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>(); Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
int usedExistingCount = 0; int usedExistingCount = 0;
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
Set<UUID> usedExisting = usedExistingIds(dd); Set<UUID> usedExisting = usedExistingIds(dd);
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); Map<UUID, Set<IotHubInstalledItemId>> 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<UUID> 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<UUID> created = new HashSet<>();
dd.getCreatedEntityIds().forEach(id -> created.add(id.getId()));
Set<UUID> keptIds = new HashSet<>();
for (EntityId entityId : dd.getCreatedEntityIds()) { for (EntityId entityId : dd.getCreatedEntityIds()) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId()); Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
boolean taken = usedExisting.contains(entityId.getId()); boolean taken = usedExisting.contains(entityId.getId());
if (usedBy != null || taken) { if (usedBy != null || taken) {
String name = findDevicePackageEntity(tenantId, entityId) != null kept.add(keptEntity(tenantId, entityId));
? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null; keptIds.add(entityId.getId());
kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, name));
} }
if (usedBy != null) { if (usedBy != null) {
usedByItems.addAll(usedBy); usedByItems.addAll(usedBy);
@ -859,8 +893,65 @@ public class DefaultIotHubService implements IotHubService {
usedExistingCount++; 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<EntityId> profileReferences(TenantId tenantId, EntityId profileId) {
List<EntityId> 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<UUID> 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. */ /** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */

30
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java

@ -10,28 +10,33 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
/** /**
* The update of an installed device package as the install wizard planned it: the entity of each install step * The install or update of a 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 * of the version being installed, already resolved from its template, and what to do with it. The server applies
* in one transaction, together with the new version of the installed item, or nothing. * all of it in one transaction, together with the installed item, or nothing.
*/ */
@Data @Data
public class DeviceUpdateRequest { public class DevicePackageRequest {
private String versionId; 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; 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; private String selectedInstallMethod;
// The form values of the install state, by step: the server adds the entities to it // The form values of the install state, by step: the server adds the entities to it
private Map<String, JsonNode> installState; private Map<String, JsonNode> 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<Step> steps; private List<Step> steps;
public enum Action { 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, KEEP,
// Takes the entity from the step // Takes the entity from the step
OVERWRITE, 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 CREATE
} }
@ -51,13 +56,13 @@ public class DeviceUpdateRequest {
private Long expectedVersion; private Long expectedVersion;
// The user confirmed overwriting an entity of another package or one they didn't install with this package // The user confirmed overwriting an entity of another package or one they didn't install with this package
private boolean confirmed; private boolean confirmed;
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity this // OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity the
// update creates is left for the server, which knows its id only once it is created. // request creates is left for the server, which knows its id only once it is created.
private JsonNode entity; private JsonNode entity;
// DEVICE and GATEWAY: the credentials template, if any // DEVICE and GATEWAY: the credentials template, if any
private JsonNode credentials; private JsonNode credentials;
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity, // OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
// they may keep ${<alias>.<property>} of an entity this update creates. // they may keep ${<alias>.<property>} of an entity the request creates.
private JsonNode serverAttributes; private JsonNode serverAttributes;
private JsonNode sharedAttributes; private JsonNode sharedAttributes;
// The resolution the install state records for it // 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: 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 // integration, e.g. one the package took as it was; null removes an entry
private JsonNode metadata; 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; private boolean defaultConverter;
/** /**

10
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java

@ -17,7 +17,7 @@ import java.util.Map;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class DeviceUpdateResult { public class DevicePackageResult {
private boolean success; private boolean success;
private String errorMessage; 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} // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map<String, ObjectNode> outputs; private Map<String, ObjectNode> outputs;
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) { public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {
return new DeviceUpdateResult(true, null, null, descriptor, outputs); return new DevicePackageResult(true, null, null, descriptor, outputs);
} }
public static DeviceUpdateResult error(String errorMessage, String failedStep) { public static DevicePackageResult error(String errorMessage, String failedStep) {
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); return new DevicePackageResult(false, errorMessage, failedStep, null, null);
} }
} }

9
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java → 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; import java.util.List;
/** Updates an installed device package to another version of its item. */ /** Installs a device package, or updates an installed one to another version of its item. */
public interface DevicePackageUpdateService { public interface DevicePackageService {
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */ /** The package's entities as they are now: whether they still exist, changed since, or are shared. */
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId); List<DevicePackageEntityState> 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. */ /** 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);
} }

8
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; 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 @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@ -20,6 +23,9 @@ public class InstalledItemKeptEntities {
private int usedByItemsCount; private int usedByItemsCount;
// How many of the kept entities the user had before and the package took as they were (use existing) // How many of the kept entities the user had before and the package took as they were (use existing)
private int usedExistingCount; 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<KeptEntity> referencedEntities;
@Data @Data
@NoArgsConstructor @NoArgsConstructor

602
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java → 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.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
@ -16,12 +17,17 @@ import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.RestClientException;
import org.thingsboard.common.util.JacksonUtil; 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.Dashboard;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType; 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.AttributeScope;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; 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.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId; 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.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId; 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.integration.Integration;
import org.thingsboard.server.common.data.page.PageData; 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.SubscriptionErrorCode;
import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.dao.converter.ConverterService; 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.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceCredentialsService;
import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService; 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.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.subscription.PlatformFeature; 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.exception.DataValidationException;
import org.thingsboard.server.service.entitiy.TbLogEntityActionService; import org.thingsboard.server.service.entitiy.TbLogEntityActionService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; 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.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
@ -62,20 +75,25 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutionException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.ArgumentMatchers.eq; 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.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT) @MockitoSettings(strictness = Strictness.LENIENT)
class DefaultDevicePackageUpdateServiceTest { class DefaultDevicePackageServiceTest {
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
private final SecurityUser user = mock(SecurityUser.class); private final SecurityUser user = mock(SecurityUser.class);
@ -119,18 +137,30 @@ class DefaultDevicePackageUpdateServiceTest {
private TelemetrySubscriptionService telemetryService; private TelemetrySubscriptionService telemetryService;
@Mock @Mock
private IotHubService iotHubService; private IotHubService iotHubService;
@Mock
private ProjectInfo projectInfo;
@Mock
private CustomerService customerService;
@Mock
private EntityGroupService entityGroupService;
@InjectMocks @InjectMocks
private DefaultDevicePackageUpdateService service; private DefaultDevicePackageService service;
private IotHubInstalledItem installedItem; private IotHubInstalledItem installedItem;
// Set when the transaction callback threw, so the transaction would roll back // Set when the transaction callback threw, so the transaction would roll back
private final List<RuntimeException> rolledBack = new ArrayList<>(); private final List<RuntimeException> rolledBack = new ArrayList<>();
private boolean inTransaction;
private final List<String> 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<String> afterCommitCalls = new ArrayList<>();
@BeforeEach @BeforeEach
void setUp() { void setUp() {
ReflectionTestUtils.setField(service, "entityService", entityService); ReflectionTestUtils.setField(service, "entityService", entityService);
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService);
ReflectionTestUtils.setField(service, "customerService", customerService);
ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService);
when(user.getTenantId()).thenReturn(tenantId); when(user.getTenantId()).thenReturn(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
@ -158,11 +188,14 @@ class DefaultDevicePackageUpdateServiceTest {
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo);
when(transactionTemplate.execute(any())).thenAnswer(invocation -> { when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
inTransaction = true;
try { try {
return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null); return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null);
} catch (RuntimeException e) { } catch (RuntimeException e) {
rolledBack.add(e); rolledBack.add(e);
throw e; throw e;
} finally {
inTransaction = false;
} }
}); });
when(packageEntities.checksum(any(), any())).thenReturn("checksum"); when(packageEntities.checksum(any(), any())).thenReturn("checksum");
@ -184,7 +217,7 @@ class DefaultDevicePackageUpdateServiceTest {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard);
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); 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")), overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")),
keep("AM308", "DEVICE", deviceId), keep("AM308", "DEVICE", deviceId),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); 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())); dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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"); request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -237,10 +270,10 @@ class DefaultDevicePackageUpdateServiceTest {
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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"); 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(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -256,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest {
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -266,10 +299,10 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void useExistingOfAPackageEntity_staysThePackages() { void useExistingOfAPackageEntity_staysThePackages() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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"); 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(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); 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 // 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"))); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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"); 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(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -295,9 +328,9 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void overwritingAnEntityUsedAtInstall_needsAConfirmation() { void overwritingAnEntityUsedAtInstall_needsAConfirmation() {
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); ((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(); assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any()); verify(installedItemService, never()).save(any(), any());
@ -308,7 +341,7 @@ class DefaultDevicePackageUpdateServiceTest {
Dashboard shared = dashboard(9L); Dashboard shared = dashboard(9L);
DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null);
when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); 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 // 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"); ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it");
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); ((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 // v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of());
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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"); 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(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -343,9 +376,9 @@ class DefaultDevicePackageUpdateServiceTest {
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setUsedExistingEntityIds(List.of(dashboardId)); installed.setUsedExistingEntityIds(List.of(dashboardId));
installed.setInstallState(Map.of()); 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(); assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any()); verify(installedItemService, never()).save(any(), any());
@ -358,7 +391,7 @@ class DefaultDevicePackageUpdateServiceTest {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(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(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId);
@ -377,13 +410,13 @@ class DefaultDevicePackageUpdateServiceTest {
current.setConfiguration(configuration); current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); 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"); step.setResolution("use-existing");
ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge");
entries.putNull("profile.milesight-iot-am308"); entries.putNull("profile.milesight-iot-am308");
step.setMetadata(entries); 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(); assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class); ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
@ -411,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest {
integration.setId(integrationId); integration.setId(integrationId);
when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration)); 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(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -438,11 +471,11 @@ class DefaultDevicePackageUpdateServiceTest {
current.setConfiguration(configuration); current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current); when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); 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.setResolution("use-existing");
step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); 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(); assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -465,10 +498,10 @@ class DefaultDevicePackageUpdateServiceTest {
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
current.setConfiguration(configuration); current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); 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")); 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(); assertThat(result.isSuccess()).isTrue();
verify(integrationService, never()).saveIntegration(any()); verify(integrationService, never()).saveIntegration(any());
@ -476,12 +509,12 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void twoStepsWithOneKey_areRejected() { void twoStepsWithOneKey_areRejected() {
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
first.setId("main-dashboard"); first.setId("main-dashboard");
DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
second.setId("main-dashboard"); 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(); assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any()); verify(installedItemService, never()).save(any(), any());
@ -489,25 +522,25 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void twoStepsOfOneTypeAndName_areRejected() { 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))); keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isFalse(); 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()); verify(transactionTemplate, never()).execute(any());
} }
@Test @Test
void stepWithTheKeyOfAForm_isRejected() { void stepWithTheKeyOfAForm_isRejected() {
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setId("Settings"); 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)))); 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.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings"); assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings");
verify(transactionTemplate, never()).execute(any()); verify(transactionTemplate, never()).execute(any());
} }
@ -532,14 +565,14 @@ class DefaultDevicePackageUpdateServiceTest {
legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"), installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app")))); "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); 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")); 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"))); 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(); assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
@ -563,7 +596,7 @@ class DefaultDevicePackageUpdateServiceTest {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); 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("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
@ -580,12 +613,12 @@ class DefaultDevicePackageUpdateServiceTest {
void entityChangedSinceTheCheck_isAVersionConflict() { void entityChangedSinceTheCheck_isAVersionConflict() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); 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")))); overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse(); assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); 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)); 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); 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}")); 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")), create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")),
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); overwrite("TTN", "INTEGRATION", integrationId, 2L, integration)));
@ -640,12 +673,12 @@ class DefaultDevicePackageUpdateServiceTest {
IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting));
when(installedItemService.findByTenantId(any(), any(), any(), any())) when(installedItemService.findByTenantId(any(), any(), any(), any()))
.thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); .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 {};"))); JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setConfirmed(true); step.setConfirmed(true);
step.setDefaultConverter(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(); assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink"); 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"); ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0");
when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo); when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo);
// ThingsBoard's default converter changed: only the converter step is sent // 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 {};"))); JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setId("uplink"); step.setId("uplink");
step.setDefaultConverter(true); step.setDefaultConverter(true);
DeviceUpdateRequest request = request(step); DevicePackageRequest request = request(step);
request.setVersionId(installedVersionId.toString()); request.setVersionId(installedVersionId.toString());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue(); assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
@ -697,7 +730,7 @@ class DefaultDevicePackageUpdateServiceTest {
void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() { void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); 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(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard"); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard");
@ -707,7 +740,7 @@ class DefaultDevicePackageUpdateServiceTest {
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { void overwritingAnEntityOfAnotherPackage_needsAConfirmation() {
DashboardId foreign = new DashboardId(UUID.randomUUID()); 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")))); overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse(); assertThat(result.isSuccess()).isFalse();
@ -716,7 +749,7 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void theDeviceIsNeverOverwritten() { 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")))); overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d"))));
assertThat(result.isSuccess()).isFalse(); assertThat(result.isSuccess()).isFalse();
@ -729,7 +762,7 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString());
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); 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(); assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any()); verify(transactionTemplate, never()).execute(any());
@ -743,7 +776,7 @@ class DefaultDevicePackageUpdateServiceTest {
updated.setItemVersionId(UUID.fromString(versionId)); updated.setItemVersionId(UUID.fromString(versionId));
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); 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")))); create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse(); assertThat(result.isSuccess()).isFalse();
@ -754,10 +787,10 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void planOfAnotherInstalledVersion_isRejected() { void planOfAnotherInstalledVersion_isRejected() {
DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId));
request.setFromVersionId(UUID.randomUUID()); request.setFromVersionId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse(); assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any()); verify(installedItemService, never()).save(any(), any());
@ -768,7 +801,7 @@ class DefaultDevicePackageUpdateServiceTest {
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED))
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); .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")))); create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse(); assertThat(result.isSuccess()).isFalse();
@ -780,10 +813,10 @@ class DefaultDevicePackageUpdateServiceTest {
void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { void attributesOfAnOverwrittenEntity_areSavedAfterCommit() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); 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}")); 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(); assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
@ -829,12 +862,12 @@ class DefaultDevicePackageUpdateServiceTest {
@Test @Test
void userMessage_showsValidationMessagesAndHidesInternalOnes() { 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"); .isEqualTo("Rule chains limit reached");
assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null)))
.contains("Check the update again"); .contains("Check the package again");
assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]")))
.isEqualTo("Failed to update the device package"); .isEqualTo("Failed to save the device package");
} }
@Test @Test
@ -842,12 +875,431 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); ObjectNode device = JacksonUtil.newObjectNode().put("id", "123");
ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); 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("a").asText()).isEqualTo("123");
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); 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<IotHubInstalledItem> 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<String, JsonNode> 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> device = ArgumentCaptor.forClass(Device.class);
verify(deviceService).saveDevice(device.capture());
assertThat(device.getValue().getCustomerId()).isEqualTo(customerId);
ArgumentCaptor<Dashboard> 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> 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<AttributesSaveRequest> 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> device = ArgumentCaptor.forClass(Device.class);
verify(deviceService).saveDevice(device.capture());
assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer);
ArgumentCaptor<Dashboard> 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<String, JsonNode> installState) { private IotHubInstalledItem otherPackage(Map<String, JsonNode> installState) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setInstallState(installState); descriptor.setInstallState(installState);
@ -875,35 +1327,35 @@ class DefaultDevicePackageUpdateServiceTest {
return dashboard; return dashboard;
} }
private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { private DevicePackageRequest request(DevicePackageRequest.Step... steps) {
DeviceUpdateRequest request = new DeviceUpdateRequest(); DevicePackageRequest request = new DevicePackageRequest();
request.setVersionId(versionId); request.setVersionId(versionId);
request.setSteps(List.of(steps)); request.setSteps(List.of(steps));
return request; return request;
} }
private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { private static DevicePackageRequest.Step keep(String name, String type, EntityId id) {
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.KEEP);
step.setEntityId(id.getId()); step.setEntityId(id.getId());
return step; return step;
} }
private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) {
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.OVERWRITE);
step.setEntityId(id.getId()); step.setEntityId(id.getId());
step.setExpectedVersion(version); step.setExpectedVersion(version);
step.setEntity(entity); step.setEntity(entity);
return step; return step;
} }
private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) {
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.CREATE);
step.setEntity(entity); step.setEntity(entity);
return step; return step;
} }
private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) {
DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); DevicePackageRequest.Step step = new DevicePackageRequest.Step();
step.setName(name); step.setName(name);
step.setType(type); step.setType(type);
step.setAction(action); step.setAction(action);

194
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 // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub; 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.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
@ -14,6 +18,7 @@ import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.LoggerFactory;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.cf.CalculatedField; 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.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; 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.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor; 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.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService; 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.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService; import org.thingsboard.server.service.entitiy.converter.TbConverterService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService; import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService; 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 org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -121,6 +131,10 @@ class DefaultIotHubServiceTest {
private TbConverterService tbConverterService; private TbConverterService tbConverterService;
@Mock @Mock
private DevicePackageEntities devicePackageEntities; private DevicePackageEntities devicePackageEntities;
@Mock
private RuleChainService ruleChainService;
@Mock
private TbRuleChainService tbRuleChainService;
@Spy @Spy
@InjectMocks @InjectMocks
@ -649,6 +663,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); .thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
noDevices(profile.getId());
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard); when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration); when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration);
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
@ -923,6 +938,185 @@ class DefaultIotHubServiceTest {
return integration; 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<ILoggingEvent> 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<ILoggingEvent> 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<ILoggingEvent> 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<ILoggingEvent> 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) { private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds)); descriptor.setCreatedEntityIds(List.of(createdEntityIds));

4
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java

@ -25,6 +25,10 @@ public interface IotHubInstalledItemDao extends Dao<IotHubInstalledItem> {
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink); PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> 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<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId); List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);
List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection<UUID> itemIds); List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection<UUID> itemIds);

4
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java

@ -25,6 +25,10 @@ public interface IotHubInstalledItemService {
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink); PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
// publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version
PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId); List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);
List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection<UUID> itemIds); List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection<UUID> itemIds);

22
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 org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -49,6 +50,27 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService {
return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink); return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink);
} }
@Override
public PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> 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<UUID, UUID> 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 @Override
public List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId) { public List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId) {
return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId); return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId);

14
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java

@ -33,17 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository<IotHubInstalledIte
List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId, List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId,
@Param("itemIds") Collection<UUID> itemIds); @Param("itemIds") Collection<UUID> 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(""" @Query("""
SELECT item FROM IotHubInstalledItemEntity item SELECT item FROM IotHubInstalledItemEntity item
WHERE item.tenantId = :tenantId WHERE item.tenantId = :tenantId
AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) AND (:itemTypes IS NULL OR item.itemType IN :itemTypes)
AND (:itemId IS NULL OR item.itemId = :itemId) 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 AND (:textSearch IS NULL
OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true
OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true
OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true)
""") """)
Page<IotHubInstalledItemEntity> findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); Page<IotHubInstalledItemEntity> findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> itemTypes,
@Param("itemId") UUID itemId, @Param("textSearch") String textSearch,
@Param("updatesOnly") boolean updatesOnly,
@Param("publishedItemIds") Collection<UUID> publishedItemIds,
@Param("publishedVersionIds") Collection<UUID> publishedVersionIds,
Pageable pageable);
@Query(""" @Query("""
SELECT COUNT(item) FROM IotHubInstalledItemEntity item SELECT COUNT(item) FROM IotHubInstalledItemEntity item

19
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java

@ -48,11 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao<IotHubInstalledItemEntity
@Override @Override
public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) { public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
return find(tenantId, itemTypes, itemId, null, pageLink);
}
@Override
public PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> 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<UUID> 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<IotHubInstalledItem> find(TenantId tenantId, List<String> itemTypes, UUID itemId,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink) {
boolean updatesOnly = publishedVersionIds != null;
return DaoUtil.toPageData(repository.findByTenantId( return DaoUtil.toPageData(repository.findByTenantId(
tenantId.getId(), tenantId.getId(),
itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, itemTypes == null || itemTypes.isEmpty() ? null : itemTypes,
itemId, itemId,
StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null),
updatesOnly,
updatesOnly ? publishedVersionIds.keySet() : NO_IDS,
updatesOnly ? publishedVersionIds.values() : NO_IDS,
toPageRequest(pageLink)) toPageRequest(pageLink))
); );
} }

136
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<UUID, UUID> published() {
return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished);
}
private static List<String> names(PageData<IotHubInstalledItem> 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<IotHubInstalledItem> 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<IotHubInstalledItem> first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(),
new PageLink(1, 0, null, byName));
PageData<IotHubInstalledItem> 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<UUID, UUID> published = new HashMap<>(published());
for (int i = 0; i < 20_000; i++) {
published.put(UUID.randomUUID(), UUID.randomUUID());
}
PageData<IotHubInstalledItem> 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<UUID, UUID> 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();
}
}

66
ui-ngx/src/app/core/http/iot-hub-api.service.ts

@ -4,7 +4,8 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
import { Store } from '@ngrx/store'; 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 { PageData } from '@shared/models/page/page-data';
import { PageLink } from '@shared/models/page/page-link'; import { PageLink } from '@shared/models/page/page-link';
import { import {
@ -13,7 +14,7 @@ import {
MpItemVersionView MpItemVersionView
} from '@shared/models/iot-hub/iot-hub-version.models'; } from '@shared/models/iot-hub/iot-hub-version.models';
import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.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 { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params';
import { InterceptorConfig } from '@core/interceptors/interceptor-config'; import { InterceptorConfig } from '@core/interceptors/interceptor-config';
@ -50,6 +51,8 @@ export function iotHubResourceUrl(baseUrl: string, path: string): string {
return `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`; return `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`;
} }
const PUBLISHED_VERSIONS_CHUNK_SIZE = 100;
export interface IotHubRequestConfig { export interface IotHubRequestConfig {
ignoreLoading?: boolean; ignoreLoading?: boolean;
ignoreErrors?: 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<string, any> },
config?: IotHubRequestConfig
): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>(
`/api/iot-hub/device/register?versionId=${versionId}`,
{ type: 'DEVICE', ...descriptor },
{ params: this.buildParams(config) }
);
}
public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable<InstallItemVersionResult> { public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>( return this.http.post<InstallItemVersionResult>(
`/api/iot-hub/versions/${versionId}/install`, `/api/iot-hub/versions/${versionId}/install`,
@ -240,11 +231,7 @@ export class IotHubApiService {
public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[],
itemId?: string, config?: IotHubRequestConfig): Observable<PageData<IotHubInstalledItem>> { itemId?: string, config?: IotHubRequestConfig): Observable<PageData<IotHubInstalledItem>> {
let query = pageLink.toQuery(); let query = this.installedItemsQuery(pageLink, itemTypes);
if (itemTypes) {
const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes];
types.forEach(t => query += `&itemTypes=${t}`);
}
if (itemId) { if (itemId) {
query += `&itemId=${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<string, string>,
config?: IotHubRequestConfig): Observable<PageData<IotHubInstalledItem>> {
return this.http.post<PageData<IotHubInstalledItem>>(
`/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`,
publishedVersionIds,
{ params: this.buildParams(config) }
);
}
public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable<number> { public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable<number> {
let url = '/api/iot-hub/installedItems/count'; let url = '/api/iot-hub/installedItems/count';
if (itemType) { if (itemType) {
@ -278,14 +275,23 @@ export class IotHubApiService {
} }
/** Applies a device package update in one transaction: all of it, or nothing. */ /** Applies a device package update in one transaction: all of it, or nothing. */
public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable<DeviceUpdateResult> { public updateDevicePackage(installedItemId: string, request: DevicePackageRequest, config?: IotHubRequestConfig): Observable<DevicePackageResult> {
return this.http.post<DeviceUpdateResult>( return this.http.post<DevicePackageResult>(
`/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`,
request, request,
{ params: this.buildParams(config) } { 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<DevicePackageResult> {
return this.http.post<DevicePackageResult>(
`/api/iot-hub/device/install`,
request,
{ params: this.buildParams(config) }
);
}
public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> { public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> {
return this.http.get<IotHubInstalledItemKeptEntities>( return this.http.get<IotHubInstalledItemKeptEntities>(
`/api/iot-hub/installedItems/${installedItemId}/keptEntities`, `/api/iot-hub/installedItems/${installedItemId}/keptEntities`,
@ -294,11 +300,18 @@ export class IotHubApiService {
} }
public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable<ItemPublishedVersionInfo[]> { public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable<ItemPublishedVersionInfo[]> {
return this.http.post<ItemPublishedVersionInfo[]>( 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<ItemPublishedVersionInfo[]>(
`${this.baseUrl}/api/versions/publishedVersions`, `${this.baseUrl}/api/versions/publishedVersions`,
itemIds, chunk,
{ params: this.buildParams(config) } { params: this.buildParams(config) }
); ))).pipe(map(results => results.flat()));
} }
public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable<CreatorView> { public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable<CreatorView> {
@ -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 { private buildParams(config?: IotHubRequestConfig): HttpParams {
return new InterceptorHttpParams( return new InterceptorHttpParams(
new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false) new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false)

3
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 = column.cellTooltipFunction(entity, column.key);
res = isDefined(res) ? res : null; res = isDefined(res) ? res : null;
this.cellTooltipCache[index] = res; this.cellTooltipCache[index] = res;
} else {
return res !== null ? res : undefined;
} }
return res !== null ? res : undefined;
} else { } else {
return undefined; return undefined;
} }

169
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html

@ -62,93 +62,7 @@
} }
@case ('progress') { @case ('progress') {
@if (data.update) { <ng-container *ngTemplateOutlet="packageRows; context: { $implicit: ws }"></ng-container>
<ng-container *ngTemplateOutlet="updateRows; context: { $implicit: ws }"></ng-container>
} @else {
<div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@if (i > 0) {
<div class="tb-progress-divider"></div>
}
@if (ep.status === 'conflict' || ep.status === 'error') {
<div class="tb-progress-row tb-progress-row-alert">
<div class="flex min-w-0 flex-1 items-start gap-4">
<div class="tb-progress-icon">
<mat-icon class="tb-progress-warning">warning</mat-icon>
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">
{{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }}
</span>
@if (ep.status === 'conflict') {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }}
</span>
}
@if (ep.status === 'error' && ep.errorMessage) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ ep.errorMessage }}</span>
}
</div>
</div>
<div class="flex shrink-0 gap-2">
@if (ep.status === 'conflict') {
@if (ep.conflictType === 'use-or-overwrite') {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="resolveConflict(ws, ep, 'use-existing')">
{{ 'iot-hub.device-install-use-existing' | translate }}
</button>
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="resolveConflict(ws, ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="resolveConflict(ws, ep, 'create-copy')">
{{ 'iot-hub.device-install-create-copy' | translate }}
</button>
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="resolveConflict(ws, ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
}
@if (ep.status === 'error') {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="retryEntitySteps(ws)">
{{ 'action.retry' | translate }}
</button>
}
</div>
</div>
} @else {
<div class="tb-progress-row"
[class.tb-progress-row-active]="ep.status === 'running'">
<div class="tb-progress-icon">
@switch (ep.status) {
@case ('pending') {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
}
@case ('running') {
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success">check_circle</mat-icon>
}
}
</div>
<span class="tb-progress-label"
[class.tb-progress-label-active]="ep.status === 'running'"
[class.tb-progress-label-pending]="ep.status === 'pending'">
{{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }}
</span>
<span class="tb-progress-status">
@if (ep.status === 'success') {
<span class="tb-progress-status-done">{{ 'iot-hub.done' | translate }}</span>
}
@if (ep.status === 'running') {
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
</span>
</div>
}
}
</div>
}
} }
} }
</div> </div>
@ -156,18 +70,17 @@
<!-- Update: an entity someone changed since install, which the user can save before the update overwrites it --> <!-- Update: an entity someone changed since install, which the user can save before the update overwrites it -->
<ng-template #modifiedHint let-ep> <ng-template #modifiedHint let-ep>
@let hint = textWithLink('iot-hub.device-update-modified'); {{ modifiedHintText.before }}<a class="tb-progress-link" href="#" (click)="$event.preventDefault(); downloadCurrentEntity(ep)">{{ modifiedHintText.link }}</a>{{ modifiedHintText.after }}
{{ hint.before }}<a class="tb-progress-link" href="#" (click)="$event.preventDefault(); downloadCurrentEntity(ep)">{{ hint.link }}</a>{{ hint.after }}
</ng-template> </ng-template>
<!-- Update: the package's entities and what the update does with them --> <!-- The package's entities and what the install or update does with them; review mode shows them done -->
<ng-template #updateRows let-ws> <ng-template #packageRows let-ws>
<div class="flex flex-col p-6"> <div class="flex flex-col p-6">
@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) { @if (i > 0) {
<div class="tb-progress-divider"></div> <div class="tb-progress-divider"></div>
} }
@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); @let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name);
@if (ws.reviewing && plan && !plan.confirmed) { @if (ws.reviewing && plan && !plan.confirmed) {
<div class="tb-progress-row tb-progress-row-alert"> <div class="tb-progress-row tb-progress-row-alert">
@ -182,7 +95,7 @@
} }
@if (plan.existing) { @if (plan.existing) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning"> <span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ '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 } }}
</span> </span>
} }
@if (plan.shared) { @if (plan.shared) {
@ -198,19 +111,21 @@
<div class="flex shrink-0 gap-2"> <div class="flex shrink-0 gap-2">
@if (plan.existing) { @if (plan.existing) {
@if (ep.step.type === 'DASHBOARD') { @if (ep.step.type === 'DASHBOARD') {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'create-copy')"> <button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmWarning(ep, 'create-copy')">
{{ 'iot-hub.device-install-create-copy' | translate }} {{ 'iot-hub.device-install-create-copy' | translate }}
</button> </button>
} @else { } @else {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'use-existing')"> <button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmWarning(ep, 'use-existing')">
{{ 'iot-hub.device-install-use-existing' | translate }} {{ 'iot-hub.device-install-use-existing' | translate }}
</button> </button>
} }
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep, 'overwrite')"> @if (canOverwriteExisting(ep)) {
{{ 'iot-hub.device-install-overwrite' | translate }} <button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmWarning(ep, 'overwrite')">
</button> {{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
} @else { } @else {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep)"> <button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmWarning(ep)">
{{ 'iot-hub.device-install-overwrite' | translate }} {{ 'iot-hub.device-install-overwrite' | translate }}
</button> </button>
} }
@ -237,7 +152,7 @@
<mat-spinner diameter="24"></mat-spinner> <mat-spinner diameter="24"></mat-spinner>
} }
@case ('success') { @case ('success') {
<mat-icon class="tb-progress-success tb-update-reveal">check_circle</mat-icon> <mat-icon class="tb-progress-success tb-package-reveal">check_circle</mat-icon>
} }
@default { @default {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div> <div class="tb-progress-pending-circle">{{ i + 1 }}</div>
@ -249,7 +164,8 @@
<span class="tb-progress-label tb-progress-label-fit" <span class="tb-progress-label tb-progress-label-fit"
[class.tb-progress-label-active]="ep.status === 'running'" [class.tb-progress-label-active]="ep.status === 'running'"
[class.tb-progress-label-pending]="!ws.reviewing && (ep.status === 'pending' || ep.status === 'skipped')">{{ label }}</span> [class.tb-progress-label-pending]="!ws.reviewing && (ep.status === 'pending' || ep.status === 'skipped')">{{ label }}</span>
@if (plan?.action === 'create' && plan.resolution !== 'use-existing') { <!-- Update: an entity the installed version doesn't have; at install every entity is new -->
@if (data.update && plan?.action === 'create' && plan.resolution !== 'use-existing') {
<span class="tb-progress-new">{{ 'iot-hub.device-update-new' | translate }}</span> <span class="tb-progress-new">{{ 'iot-hub.device-update-new' | translate }}</span>
} }
</div> </div>
@ -274,10 +190,10 @@
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span> <span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
} }
@case ('success') { @case ('success') {
<span class="tb-progress-status-done tb-update-reveal">{{ updateOutcomeOf(plan) | translate }}</span> <span class="tb-progress-status-done tb-package-reveal">{{ appliedOutcomeOf(plan) | translate }}</span>
} }
@case ('skipped') { @case ('skipped') {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-skipped' | translate }}</span> <span class="tb-progress-status-progress">{{ 'iot-hub.device-package-skipped' | translate }}</span>
} }
@default { @default {
<!-- A resolved name conflict shows the choice: Use existing, Overwrite or Create copy --> <!-- A resolved name conflict shows the choice: Use existing, Overwrite or Create copy -->
@ -335,7 +251,7 @@
<!-- Review mode: tabs --> <!-- Review mode: tabs -->
<div mat-dialog-content> <div mat-dialog-content>
<mat-tab-group (selectedIndexChange)="onTabChanged($event)"> <mat-tab-group (selectedIndexChange)="onTabChanged($event)">
@for (ws of wizardSteps; track ws.label) { @for (ws of wizardSteps; track ws) {
<mat-tab [label]="ws.label"> <mat-tab [label]="ws.label">
<ng-template matTabContent> <ng-template matTabContent>
<ng-container *ngTemplateOutlet="stepContent; context: { $implicit: ws }"></ng-container> <ng-container *ngTemplateOutlet="stepContent; context: { $implicit: ws }"></ng-container>
@ -359,8 +275,8 @@
<mat-icon>done</mat-icon> <mat-icon>done</mat-icon>
</ng-template> </ng-template>
@for (ws of wizardSteps; track ws.label) { @for (ws of wizardSteps; track ws) {
<mat-step [editable]="true" <mat-step [editable]="!isBusy"
[completed]="ws.completed && !ws.formGroup?.invalid" [completed]="ws.completed && !ws.formGroup?.invalid"
[stepControl]="ws.type === 'form' ? ws.formGroup : null"> [stepControl]="ws.type === 'form' ? ws.formGroup : null">
<ng-template matStepLabel>{{ ws.label }}</ng-template> <ng-template matStepLabel>{{ ws.label }}</ng-template>
@ -378,24 +294,24 @@
} }
</ng-template> </ng-template>
@if (data.update && currentWizardStep?.type === 'progress') { @if (currentWizardStep?.type === 'progress') {
@let step = currentWizardStep; @let step = currentWizardStep;
@if (hasUpdateError(step)) { @if (hasPackageError(step)) {
<div class="tb-update-banner tb-update-banner-error"> <div class="tb-package-banner tb-package-banner-error">
<mat-icon>error</mat-icon> <mat-icon>error</mat-icon>
<span>{{ step.progressError }}</span> <span>{{ step.progressError }}</span>
</div> </div>
} @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { } @else if (step.reviewing && !step.checking && unconfirmedWarnings(step) > 0) {
<div class="tb-update-banner tb-update-banner-warning"> <div class="tb-package-banner tb-package-banner-warning">
<mat-icon>warning</mat-icon> <mat-icon>warning</mat-icon>
<span>{{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }}</span> <span>{{ 'iot-hub.device-package-confirm-warnings' | translate:{ count: unconfirmedWarnings(step), action: (applyActionKey | translate) } }}</span>
</div> </div>
} }
} }
<mat-dialog-actions> <mat-dialog-actions>
@if (!isFirstWizardStep) { @if (!isFirstWizardStep) {
<button mat-stroked-button [disabled]="connectionChecking(currentWizardStep) || isUpdating || currentWizardStep?.checking" (click)="previousStep()">{{ 'action.back' | translate }}</button> <button mat-stroked-button [disabled]="connectionChecking(currentWizardStep) || isBusy" (click)="previousStep()">{{ 'action.back' | translate }}</button>
} }
<span class="flex-1"></span> <span class="flex-1"></span>
@if (currentWizardStep; as step) { @if (currentWizardStep; as step) {
@ -432,13 +348,13 @@
</button> </button>
} }
@case ('progress') { @case ('progress') {
@if (data.update && (step.reviewing || step.updating || step.progressError)) { @if (step.reviewing || step.applying || step.progressError) {
@if (step.progressError && !step.updating) { @if (step.progressError && !step.applying) {
<button mat-button (click)="done()">{{ 'action.close' | translate }}</button> <button mat-button (click)="cancel()">{{ 'action.close' | translate }}</button>
<button mat-flat-button color="primary" (click)="retryUpdate(step)"> <button mat-flat-button color="primary" (click)="retry(step)">
{{ 'iot-hub.device-update-try-again' | translate }} {{ 'iot-hub.device-package-try-again' | translate }}
</button> </button>
} @else if (step.updating) { } @else if (step.applying) {
<button mat-button disabled>{{ 'action.cancel' | translate }}</button> <button mat-button disabled>{{ 'action.cancel' | translate }}</button>
<button mat-stroked-button color="primary" disabled> <button mat-stroked-button color="primary" disabled>
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}} {{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
@ -446,19 +362,14 @@
} @else { } @else {
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button> <button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="primary" <button mat-flat-button color="primary"
[disabled]="step.checking || unconfirmedUpdateWarnings(step) > 0" [disabled]="step.checking || unconfirmedWarnings(step) > 0"
(click)="runUpdate(step)"> (click)="apply(step)">
{{ 'action.update' | translate }} {{ applyActionKey | translate }}
</button> </button>
} }
} @else if (step.progressError) {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-flat-button color="primary" (click)="retryEntitySteps(step)">
{{ 'action.retry' | translate }}
</button>
} @else if (step.progressDone && isLastWizardStep) { } @else if (step.progressDone && isLastWizardStep) {
<ng-container *ngTemplateOutlet="finishActions"></ng-container> <ng-container *ngTemplateOutlet="finishActions"></ng-container>
} @else if (!step.progressError) { } @else {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container> <ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-stroked-button color="primary" [disabled]="!step.progressDone" (click)="nextStep()"> <button mat-stroked-button color="primary" [disabled]="!step.progressDone" (click)="nextStep()">
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}} {{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}

16
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss

@ -356,17 +356,17 @@
color: #198038; color: #198038;
} }
// Update: the outcome of a row shows in when the row gets it // The outcome of a row shows in when the row gets it
.tb-update-reveal { .tb-package-reveal {
display: inline-block; display: inline-block;
animation: tb-update-reveal 200ms ease-out; animation: tb-package-reveal 200ms ease-out;
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
animation: none; animation: none;
} }
} }
@keyframes tb-update-reveal { @keyframes tb-package-reveal {
from { from {
opacity: 0; opacity: 0;
transform: scale(0.6); transform: scale(0.6);
@ -392,8 +392,8 @@
color: rgba(0, 0, 0, 0.54); color: rgba(0, 0, 0, 0.54);
} }
// Update: above the actions, so the list doesn't move when it goes away // Above the actions, so the list doesn't move when it goes away
.tb-update-banner { .tb-package-banner {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 12px;
@ -411,7 +411,7 @@
height: 20px; height: 20px;
} }
&.tb-update-banner-warning { &.tb-package-banner-warning {
background: rgba(246, 103, 22, 0.08); background: rgba(246, 103, 22, 0.08);
color: #b5470b; color: #b5470b;
@ -420,7 +420,7 @@
} }
} }
&.tb-update-banner-error { &.tb-package-banner-error {
background: rgba(211, 47, 47, 0.06); background: rgba(211, 47, 47, 0.06);
color: #c62828; color: #c62828;
} }

992
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts

File diff suppressed because it is too large

2
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -212,7 +212,7 @@ export class IotHubActionsService {
if (!installedItem) { if (!installedItem) {
return of(false); return of(false);
} }
// A device package keeps what other installed packages use: the dialog opens with that already known // A device package keeps some entities: the dialog opens with them already known
const keptEntities$: Observable<IotHubInstalledItemKeptEntities | null> = installedItem.itemType === 'DEVICE' ? const keptEntities$: Observable<IotHubInstalledItemKeptEntities | null> = installedItem.itemType === 'DEVICE' ?
this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) : this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) :
of(null); of(null);

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -6,7 +6,7 @@ import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetT
import { IntegrationType } from '@shared/models/integration.models'; import { IntegrationType } from '@shared/models/integration.models';
import { ScriptLanguage } from '@shared/models/rule-node.models'; import { ScriptLanguage } from '@shared/models/rule-node.models';
import { isEqual } from '@core/utils'; import { isEqual } from '@core/utils';
import { DeviceInstalledItemDescriptor, DeviceUpdateRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { DeviceInstalledItemDescriptor, DevicePackageRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { PageLink } from '@shared/models/page/page-link'; import { PageLink } from '@shared/models/page/page-link';
import { PageData } from '@shared/models/page/page-data'; import { PageData } from '@shared/models/page/page-data';
@ -104,7 +104,7 @@ export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiServ
* the converter step: the server keeps the other steps, the forms and the integration's metadata as they are. * the converter step: the server keeps the other steps, the forms and the integration's metadata as they are.
* expectedVersion is the converter's version the user reviewed. * expectedVersion is the converter's version the user reviewed.
*/ */
export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DeviceUpdateRequest => { export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DevicePackageRequest => {
const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor; const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor;
return { return {
versionId: update.installedItem.itemVersionId, versionId: update.installedItem.itemVersionId,

39
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html

@ -5,21 +5,30 @@
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
--> -->
<div class="flex flex-col gap-5 p-6"> <h2 mat-dialog-title class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2> <mat-dialog-content class="!pt-0">
<p class="tb-iot-hub-delete-desc">{{ description }}</p> <div class="flex flex-col gap-5">
@if (keptReferences) { <p class="tb-iot-hub-delete-desc">{{ description }}</p>
<div class="tb-form-hint tb-primary-fill"> @if (keptGroups.length) {
<mat-icon>info_outline</mat-icon> <div class="tb-form-hint tb-primary-fill">
<div class="flex flex-col"> <mat-icon>info_outline</mat-icon>
<div class="font-medium">{{ keptTitle }}</div> <div class="flex min-w-0 flex-col">
<div>{{ keptReason }}</div> <div class="font-medium">{{ keptTitle }}</div>
<tb-image-references class="mt-3" [references]="keptReferences"></tb-image-references> <div class="tb-iot-hub-kept-groups mt-2 divide-y divide-solid divide-black/[.08] rounded bg-white">
@for (group of keptGroups; track group.reason) {
<div role="group" class="flex flex-col gap-1 border-0 py-2"
[attr.aria-labelledby]="'tb-iot-hub-kept-reason-' + $index">
<div class="px-3 pt-1 font-medium leading-4" [id]="'tb-iot-hub-kept-reason-' + $index">{{ group.reason }}</div>
<tb-image-references [references]="group.references"></tb-image-references>
</div>
}
</div>
</div>
</div> </div>
</div> }
} </div>
</div> </mat-dialog-content>
<div class="flex items-center justify-end gap-2 p-2"> <mat-dialog-actions align="end">
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button> <button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="warn" (click)="confirm()">{{ 'iot-hub.remove-anyway' | translate }}</button> <button mat-flat-button color="warn" (click)="confirm()">{{ 'iot-hub.remove-anyway' | translate }}</button>
</div> </mat-dialog-actions>

33
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: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
@import "../../../../../scss/constants";
:host { :host {
display: block; display: block;
max-width: 600px; max-width: 600px;
@ -13,6 +15,12 @@
letter-spacing: 0.1px; letter-spacing: 0.1px;
color: rgba(0, 0, 0, 0.87); color: rgba(0, 0, 0, 0.87);
margin: 0; margin: 0;
padding: 24px 24px 20px;
// No baseline strut: the title keeps its own line height
&::before {
display: none;
}
} }
.tb-iot-hub-delete-desc { .tb-iot-hub-delete-desc {
@ -23,3 +31,28 @@
color: rgba(0, 0, 0, 0.54); color: rgba(0, 0, 0, 0.54);
margin: 0; 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;
}
}
}

22
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 { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component'; 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 { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { ResourceReferences } from '@shared/models/resource.models'; import { ResourceReferences } from '@shared/models/resource.models';
@ -30,10 +30,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
description: string; description: string;
// A device package keeps the entities other installed packages use, and the dialog lists them before the user confirms keptGroups: { reason: string; references: ResourceReferences }[] = [];
keptReferences: ResourceReferences | null = null;
keptTitle: string; keptTitle: string;
keptReason: string;
constructor( constructor(
protected store: Store<AppState>, protected store: Store<AppState>,
@ -46,13 +44,21 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
super(store, router, dialogRef); super(store, router, dialogRef);
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc'); this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
const kept = data.keptEntities; const kept = data.keptEntities;
if (kept?.entities.length) { const shared = kept?.entities ?? [];
this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); 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 // 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' : const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' :
!kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-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.keptGroups.push({ reason: this.translate.instant(reasonKey, { kept: shared.length }), references: references(shared) });
this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length }); }
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 });
} }
} }

16
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) { @if (!isLoading && dataSource.length === 0) {
<div class="tb-iot-hub-empty-state flex flex-1 flex-col items-center justify-center text-center"> <div class="tb-iot-hub-empty-state flex flex-1 flex-col items-center justify-center text-center">
<div class="tb-no-data-bg"></div> <div class="tb-no-data-bg"></div>
<h3>{{ 'iot-hub.no-installed-items' | translate }}</h3> @if (loadFailed) {
<p>{{ 'iot-hub.no-installed-items-text' | translate }}</p> <h3>{{ 'iot-hub.unable-to-load' | translate }}</h3>
@if (hasActiveFilters()) { <p>{{ 'iot-hub.unable-to-load-text' | translate }}</p>
<button mat-flat-button color="primary" (click)="clearFilters.emit()"> <button mat-flat-button color="primary" (click)="retryLoad()">{{ 'iot-hub.try-again' | translate }}</button>
{{ 'iot-hub.clear-all-filters' | translate }} } @else {
</button> <h3>{{ (onlyUpdates ? 'iot-hub.no-items-with-updates' : 'iot-hub.no-installed-items') | translate }}</h3>
<p>{{ 'iot-hub.no-installed-items-text' | translate }}</p>
@if (hasActiveFilters()) {
<button mat-flat-button color="primary" (click)="clearFilters.emit()">{{ 'iot-hub.clear-all-filters' | translate }}</button>
}
} }
</div> </div>
} }

146
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts

@ -44,7 +44,7 @@ import {
loadDefaultUplinkConverter, loadDefaultUplinkConverter,
loadOwnDefaultConverterIds loadOwnDefaultConverterIds
} from '@home/components/iot-hub/iot-hub-default-converter'; } from '@home/components/iot-hub/iot-hub-default-converter';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom, forkJoin } from 'rxjs';
@Component({ @Component({
selector: 'tb-iot-hub-installed-items-table', selector: 'tb-iot-hub-installed-items-table',
@ -82,6 +82,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
private converterCheckRun = 0; private converterCheckRun = 0;
updatesChecked = false; updatesChecked = false;
isCheckingUpdates = 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; private widgetResize$: ResizeObserver;
@ -127,10 +135,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
if (changes.textSearch || changes.typeFilters) { if (changes.textSearch || changes.typeFilters) {
if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) { if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) {
this.pageIndex = 0; this.setPageIndex(0);
if (this.paginator) {
this.paginator.pageIndex = 0;
}
this.loadData(); this.loadData();
} }
} }
@ -138,8 +143,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
ngAfterViewInit(): void { ngAfterViewInit(): void {
this.sort.sortChange.subscribe(() => { this.sort.sortChange.subscribe(() => {
this.pageIndex = 0; this.setPageIndex(0);
this.paginator.pageIndex = 0;
this.loadData(); this.loadData();
}); });
} }
@ -161,7 +165,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
deleteItem(item: IotHubInstalledItem): void { deleteItem(item: IotHubInstalledItem): void {
this.iotHubActions.deleteItem(item).subscribe(deleted => { this.iotHubActions.deleteItem(item).subscribe(deleted => {
if (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.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => {
this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { this.iotHubActions.openItemDetail(versionView, item).subscribe(result => {
if (result === 'updated' || result === 'deleted') { if (result === 'updated' || result === 'deleted') {
this.loadData(); this.reloadAfterChange();
} }
}); });
}); });
@ -241,18 +245,111 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
checkForUpdates(): void { checkForUpdates(): void {
this.isCheckingUpdates = true; 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( 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({ ).subscribe({
next: (infos) => { next: (infos) => {
this.publishedVersionMap.clear(); this.publishedVersionMap.clear();
infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); 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; 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<string, string> {
const ids: Record<string, string> = {};
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: () => { error: () => {
if (run !== this.countRun) {
return;
}
this.updatesCount = null;
this.updatesCheckFailed = true;
this.isCheckingUpdates = false; this.isCheckingUpdates = false;
this.cd.markForCheck();
onError?.();
} }
}); });
} }
@ -260,7 +357,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void {
this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => {
if (result === 'updated') { 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 pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder);
const typeFilters = this.typeFilters?.length ? this.typeFilters : null; 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) => { 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.dataSource = data.data;
this.totalElements = data.totalElements; this.totalElements = data.totalElements;
this.loadFailed = false;
this.isLoading = false; this.isLoading = false;
if (this.updatesChecked && !this.itemVersion) { if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) {
void this.checkConverterUpdates(); void this.checkConverterUpdates();
} }
}, },
error: () => { error: () => {
if (run !== this.loadRun) {
return;
}
this.dataSource = []; this.dataSource = [];
this.totalElements = 0; this.totalElements = 0;
this.loadFailed = true;
this.isLoading = false; this.isLoading = false;
} }
}); });

1
ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss

@ -15,7 +15,6 @@
padding: 0; padding: 0;
} }
mat-cell.mat-column-name { mat-cell.mat-column-name {
white-space: nowrap;
.mat-mdc-icon-button { .mat-mdc-icon-button {
vertical-align: middle; vertical-align: middle;
margin-left: 8px; margin-left: 8px;

20
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.entitiesDeleteEnabled = !readonly && authUser.authority !== Authority.SYS_ADMIN;
this.customMenuTableConfig.addEntity = () => this.addCustomMenu(); this.customMenuTableConfig.addEntity = () => this.addCustomMenu();
let mainColumnsWidth: string; let nameColumnWidth: string;
let scopeColumnWidth: string;
let assigneeTypeColumnWidth: string;
switch (authUser.authority) { switch (authUser.authority) {
case Authority.SYS_ADMIN: case Authority.SYS_ADMIN:
mainColumnsWidth = '50%'; nameColumnWidth = '60%';
scopeColumnWidth = '20%';
break; break;
case Authority.TENANT_ADMIN: case Authority.TENANT_ADMIN:
mainColumnsWidth = '33%'; nameColumnWidth = '50%';
scopeColumnWidth = '15%';
assigneeTypeColumnWidth = '15%';
break; break;
case Authority.CUSTOMER_USER: case Authority.CUSTOMER_USER:
mainColumnsWidth = '50%'; nameColumnWidth = '60%';
assigneeTypeColumnWidth = '20%';
break; break;
} }
this.customMenuTableConfig.columns.push( this.customMenuTableConfig.columns.push(
new DateEntityTableColumn<CustomMenuInfo>('createdTime', 'common.created-time', this.datePipe, '150px'), new DateEntityTableColumn<CustomMenuInfo>('createdTime', 'common.created-time', this.datePipe, '150px'),
new EntityTableColumn<CustomMenuInfo>('name', 'custom-menu.name', mainColumnsWidth, new EntityTableColumn<CustomMenuInfo>('name', 'custom-menu.name', nameColumnWidth,
entity => entity.name, _entity => ({}), true, () => ({}), () => undefined, false, entity => entity.name, _entity => ({}), true, () => ({}), () => undefined, false,
{ {
name: this.translate.instant('custom-menu.edit-name'), name: this.translate.instant('custom-menu.edit-name'),
@ -120,12 +126,12 @@ export class CustomMenuTableComponent implements OnInit {
}) })
); );
if (authUser.authority !== Authority.CUSTOMER_USER) { if (authUser.authority !== Authority.CUSTOMER_USER) {
this.customMenuTableConfig.columns.push(new EntityTableColumn<CustomMenuInfo>('scope', 'custom-menu.scope', mainColumnsWidth, this.customMenuTableConfig.columns.push(new EntityTableColumn<CustomMenuInfo>('scope', 'custom-menu.scope', scopeColumnWidth,
(menu) => this.translate.instant(cmScopeTranslations.get(menu.scope)))); (menu) => this.translate.instant(cmScopeTranslations.get(menu.scope))));
} }
if (authUser.authority !== Authority.SYS_ADMIN) { if (authUser.authority !== Authority.SYS_ADMIN) {
this.customMenuTableConfig.columns.push(new EntityTableColumn<CustomMenuInfo>('assigneeType', this.customMenuTableConfig.columns.push(new EntityTableColumn<CustomMenuInfo>('assigneeType',
'custom-menu.assignee-type', mainColumnsWidth, 'custom-menu.assignee-type', assigneeTypeColumnWidth,
(menu) => this.translate.instant(cmAssigneeTypeTranslations(menu.assigneeType, menu.scope)))); (menu) => this.translate.instant(cmAssigneeTypeTranslations(menu.assigneeType, menu.scope))));
} }
if (authUser.authority !== Authority.SYS_ADMIN) { if (authUser.authority !== Authority.SYS_ADMIN) {

43
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html

@ -1,7 +1,8 @@
<!-- <!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors 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
--> -->
<div class="tb-installed-items-page flex h-full flex-col"> <div class="tb-installed-items-page flex h-full flex-col">
@ -14,16 +15,38 @@
<!-- Header --> <!-- Header -->
<div class="tb-installed-header"> <div class="tb-installed-header">
<h1 class="tb-installed-title">{{ 'iot-hub.installed-items' | translate }}</h1> <h1 class="tb-installed-title">{{ 'iot-hub.installed-items' | translate }}</h1>
@if (!updatesChecked) { <div class="flex items-center gap-4">
<button mat-flat-button color="primary" (click)="checkForUpdates()" [disabled]="isCheckingUpdates"> <!-- Always there, so a screen reader announces each change of the note -->
@if (isCheckingUpdates) { <span class="inline-flex items-center gap-2 text-sm leading-5 tracking-[0.2px] text-black/[.76]" role="status">
<mat-spinner matButtonIcon class="mr-2" diameter="18"></mat-spinner> @if (updatesCheckFailed) {
} @else { <mat-icon class="tb-mat-20 text-[#f66716]">warning</mat-icon>
<mat-icon matButtonIcon>update</mat-icon> {{ 'iot-hub.check-for-updates-failed' | translate }}
} @else if (updatesChecked && updatesCount > 0) {
<mat-icon class="tb-mat-20 text-[#f44336]">arrow_circle_up</mat-icon>
{{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }}
} @else if (updatesChecked && updatesCount === 0) {
<mat-icon class="tb-mat-20 text-[#198038]">check_circle</mat-icon>
{{ 'iot-hub.no-newer-versions' | translate }}
} }
{{ 'iot-hub.check-for-updates' | translate }} </span>
</button> @if (!updatesChecked || updatesCheckFailed) {
} <button mat-flat-button color="primary" (click)="checkForUpdates()" [disabled]="isCheckingUpdates">
@if (isCheckingUpdates) {
<mat-spinner matButtonIcon class="mr-2" diameter="18"></mat-spinner>
} @else {
<mat-icon matButtonIcon>update</mat-icon>
}
{{ (updatesCheckFailed ? 'iot-hub.try-again' : 'iot-hub.check-for-updates') | translate }}
</button>
}
@if (updatesChecked) {
@if (onlyUpdates) {
<button mat-stroked-button color="primary" (click)="showOnlyUpdates(false)">{{ 'iot-hub.show-all-items' | translate }}</button>
} @else if (updatesCount > 0) {
<button mat-stroked-button color="primary" (click)="showOnlyUpdates(true)">{{ 'iot-hub.show-only-updates' | translate }}</button>
}
}
</div>
</div> </div>
<!-- Filter + chips row --> <!-- Filter + chips row -->

23
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-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 { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
@ -107,4 +108,24 @@ export class TbIotHubInstalledItemsComponent implements OnInit, OnDestroy {
get updatesChecked(): boolean { get updatesChecked(): boolean {
return this.tableComponent?.updatesChecked || false; 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);
}
} }

70
ui-ngx/src/app/modules/home/pages/notification/sent/sent-notification-dialog.component.html

@ -96,42 +96,42 @@
} }
} }
</section> </section>
@if (!isSysAdmin()) {
<div class="tb-form-panel stroked no-padding-bottom no-gap mb-5">
<mat-slide-toggle class="toggle" formControlName="attachReport">
<div tb-hint-tooltip-icon="{{ 'notification.attach-report-hint' | translate }}" translate>
notification.attach-report
</div>
</mat-slide-toggle>
@if (notificationRequestForm.get('template.configuration.attachReport').value) {
<div class="tb-form-panel outlined">
<tb-report-template-autocomplete
required
appearance="outline"
[type]="ReportTemplateType.REPORT"
includeCustomers
showError
formControlName="reportTemplateId">
<span tb-error>{{'report-template.report-template-required' | translate}}</span>
</tb-report-template-autocomplete>
<tb-entity-autocomplete
appearance="outline"
required
useFullEntityId
[entityType]="entityType.USER"
formControlName="userId">
</tb-entity-autocomplete>
<tb-timezone-select
appearance="outline"
userTimezoneByDefault
required
formControlName="timezone">
</tb-timezone-select>
</div>
}
</div>
}
</section> </section>
@if (!isSysAdmin()) {
<div class="tb-form-panel stroked no-padding-bottom no-gap mb-5">
<mat-slide-toggle class="toggle" formControlName="attachReport">
<div tb-hint-tooltip-icon="{{ 'notification.attach-report-hint' | translate }}" translate>
notification.attach-report
</div>
</mat-slide-toggle>
@if (notificationRequestForm.get('template.configuration.attachReport').value) {
<div class="tb-form-panel outlined">
<tb-report-template-autocomplete
required
appearance="outline"
[type]="ReportTemplateType.REPORT"
includeCustomers
showError
formControlName="reportTemplateId">
<span tb-error>{{'report-template.report-template-required' | translate}}</span>
</tb-report-template-autocomplete>
<tb-entity-autocomplete
appearance="outline"
required
useFullEntityId
[entityType]="entityType.USER"
formControlName="userId">
</tb-entity-autocomplete>
<tb-timezone-select
appearance="outline"
userTimezoneByDefault
required
formControlName="timezone">
</tb-timezone-select>
</div>
}
</div>
}
</section> </section>
} }
</div> </div>

8
ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts

@ -355,10 +355,8 @@ export interface EntityStepOutput {
baseUrl?: string; baseUrl?: string;
} }
// skipped: a step of an update that failed, so nothing was changed // skipped: a step of an install or update that failed, so nothing was changed
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict' | 'skipped'; export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'skipped';
export type ConflictType = 'use-or-overwrite' | 'overwrite-or-copy';
export interface EntityStepProgress { export interface EntityStepProgress {
step: DeviceInstallStep; step: DeviceInstallStep;
@ -366,7 +364,5 @@ export interface EntityStepProgress {
resolvedName?: string; resolvedName?: string;
entityOutput?: EntityStepOutput; entityOutput?: EntityStepOutput;
errorMessage?: string; errorMessage?: string;
existingEntity?: EntityStepOutput;
conflictType?: ConflictType;
resolution?: string; resolution?: string;
} }

25
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -48,8 +48,8 @@ export interface DevicePackageEntityState {
shared: boolean; shared: boolean;
} }
/** A step of a device package update, with its entity resolved from the template of the new version. */ /** A step of a device package install or update, with its entity resolved from the template of the version being installed. */
export interface DeviceUpdateStep { export interface DevicePackageStep {
name: string; name: string;
type: string; type: string;
action: 'KEEP' | 'OVERWRITE' | 'CREATE'; action: 'KEEP' | 'OVERWRITE' | 'CREATE';
@ -58,7 +58,7 @@ export interface DeviceUpdateStep {
confirmed?: boolean; confirmed?: boolean;
entity?: any; entity?: any;
credentials?: 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; serverAttributes?: any;
sharedAttributes?: any; sharedAttributes?: any;
resolution?: string; resolution?: string;
@ -71,18 +71,21 @@ export interface DeviceUpdateStep {
defaultConverter?: boolean; defaultConverter?: boolean;
} }
export interface DeviceUpdateRequest { export interface DevicePackageRequest {
versionId: string; 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; fromVersionId?: string;
// The install method of the new version's steps // The install method of the steps
selectedInstallMethod?: string; selectedInstallMethod?: string;
installState: Record<string, any>; installState: Record<string, any>;
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. */ /** 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 DeviceUpdateResult { export interface DevicePackageResult {
success: boolean; success: boolean;
errorMessage?: string; errorMessage?: string;
failedStep?: string; failedStep?: string;
@ -159,7 +162,7 @@ export interface ItemPublishedVersionInfo {
publishedVersion: string; 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 { export interface IotHubKeptEntity {
entityId: { id: string; entityType: string }; entityId: { id: string; entityType: string };
name: string; name: string;
@ -170,6 +173,8 @@ export interface IotHubInstalledItemKeptEntities {
usedByItemsCount: number; usedByItemsCount: number;
// Of the kept entities, the ones the user had before and the package took as they were // Of the kept entities, the ones the user had before and the package took as they were
usedExistingCount: number; usedExistingCount: number;
// Absent from older backends
referencedEntities?: IotHubKeptEntity[];
} }
export interface IotHubInstalledItem extends BaseData<{id: string}> { export interface IotHubInstalledItem extends BaseData<{id: string}> {

21
ui-ngx/src/assets/locale/locale.constant-ar_AE.json

@ -6538,9 +6538,6 @@
"step-configuration": "التكوين", "step-configuration": "التكوين",
"step-provisioning": "التزويد", "step-provisioning": "التزويد",
"device-install-step-error": "فشل", "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-DASHBOARD": "لوحة المعلومات",
"device-install-step-type-DEVICE": "جهاز", "device-install-step-type-DEVICE": "جهاز",
"device-install-step-type-DEVICE_PROFILE": "ملف تعريف الجهاز", "device-install-step-type-DEVICE_PROFILE": "ملف تعريف الجهاز",
@ -6552,7 +6549,7 @@
"device-install-step-type-INTEGRATION": "التكامل", "device-install-step-type-INTEGRATION": "التكامل",
"use-secret": "استخدام سر", "use-secret": "استخدام سر",
"use-plain-text": "استخدام نص عادي", "use-plain-text": "استخدام نص عادي",
"device-install-conflict-exists": "يوجد {{type}} بهذا الاسم بالفعل", "device-install-conflict-exists": "يوجد {{type}} بالاسم \"{{name}}\" بالفعل",
"device-install-use-existing": "استخدام الموجود", "device-install-use-existing": "استخدام الموجود",
"device-install-transport-host-step": "الاتصال", "device-install-transport-host-step": "الاتصال",
"device-install-thingsboard-connection": "الاتصال بمنصة ThingsBoard", "device-install-thingsboard-connection": "الاتصال بمنصة ThingsBoard",
@ -6586,20 +6583,18 @@
"device-installing-title": "جارٍ تثبيت \"{{name}}\"", "device-installing-title": "جارٍ تثبيت \"{{name}}\"",
"device-update-title": "تحديث \"{{name}}\"", "device-update-title": "تحديث \"{{name}}\"",
"device-update-step": "تحديث", "device-update-step": "تحديث",
"device-update-no-conflicts": "لا توجد تعارضات",
"device-update-new": "جديد", "device-update-new": "جديد",
"device-update-shared": "تستخدمه حزم أخرى. يؤثر التحديث عليها.", "device-update-shared": "تستخدمه حزم أخرى. يؤثر التحديث عليها.",
"device-update-new-default-converter": "يتوفر في منصة ThingsBoard إصدار جديد من المحوّل الافتراضي الذي تستخدمه هذه الحزمة.", "device-update-new-default-converter": "يتوفر في منصة ThingsBoard إصدار جديد من المحوّل الافتراضي الذي تستخدمه هذه الحزمة.",
"device-update-modified": "يحتوي على تغييرات محلية. يمكنك تنزيل الإصدار الحالي <a>من هنا</a>.", "device-update-modified": "يحتوي على تغييرات محلية. يمكنك تنزيل الإصدار الحالي <a>من هنا</a>.",
"device-install-unexpected-error": "حدث خطأ ما. حاول مرة أخرى.", "device-install-unexpected-error": "حدث خطأ ما. حاول مرة أخرى.",
"device-update-existing-use-existing": "موجود بالفعل. سيتم استخدام العنصر الموجود.", "device-package-will-create": "سيتم الإنشاء",
"device-update-existing-overwrite": "موجود بالفعل. ستتم الكتابة فوقه.", "device-install-nothing-installed": "لم يتم تثبيت أي شيء.",
"device-update-existing-create-copy": "موجود بالفعل. سيتم إنشاء نسخة.", "device-package-confirm-warnings": "أكّد {count, plural, one {تحذيرًا واحدًا} two {تحذيرين} few {# تحذيرات} many {# تحذيرًا} other {# تحذير} } لتمكين زر \"{action}\"",
"device-update-confirm-warnings": "أكّد {count, plural, one {تحذيرًا واحدًا} two {تحذيرين} few {# تحذيرات} many {# تحذيرًا} other {# تحذير} } لتمكين زر \"تحديث\"", "device-package-skipped": "لم يتغير",
"device-update-skipped": "لم يتغير", "device-package-updated": "تم التحديث",
"device-update-updated": "تم التحديث", "device-package-created": "تم الإنشاء",
"device-update-created": "تم الإنشاء", "device-package-try-again": "إعادة المحاولة",
"device-update-try-again": "إعادة المحاولة",
"done": "تم", "done": "تم",
"in-progress": "قيد التنفيذ", "in-progress": "قيد التنفيذ",
"item-detail": "عنصر IoT Hub", "item-detail": "عنصر IoT Hub",

21
ui-ngx/src/assets/locale/locale.constant-ca_ES.json

@ -6540,9 +6540,6 @@
"step-configuration": "Configuració", "step-configuration": "Configuració",
"step-provisioning": "Aprovisionament", "step-provisioning": "Aprovisionament",
"device-install-step-error": "Ha fallat", "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-DASHBOARD": "Tauler",
"device-install-step-type-DEVICE": "Dispositiu", "device-install-step-type-DEVICE": "Dispositiu",
"device-install-step-type-DEVICE_PROFILE": "Perfil de dispositiu", "device-install-step-type-DEVICE_PROFILE": "Perfil de dispositiu",
@ -6554,7 +6551,7 @@
"device-install-step-type-INTEGRATION": "Integració", "device-install-step-type-INTEGRATION": "Integració",
"use-secret": "Utilitza un secret", "use-secret": "Utilitza un secret",
"use-plain-text": "Utilitza text pla", "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-use-existing": "Utilitza l'existent",
"device-install-transport-host-step": "Connexió", "device-install-transport-host-step": "Connexió",
"device-install-thingsboard-connection": "Connexió amb ThingsBoard", "device-install-thingsboard-connection": "Connexió amb ThingsBoard",
@ -6588,20 +6585,18 @@
"device-installing-title": "S'està instal·lant \"{{name}}\"", "device-installing-title": "S'està instal·lant \"{{name}}\"",
"device-update-title": "Actualitza \"{{name}}\"", "device-update-title": "Actualitza \"{{name}}\"",
"device-update-step": "Actualització", "device-update-step": "Actualització",
"device-update-no-conflicts": "Sense conflictes",
"device-update-new": "Nou", "device-update-new": "Nou",
"device-update-shared": "L'utilitzen altres paquets. L'actualització els afecta.", "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-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 <a>aquí</a>.", "device-update-modified": "Té canvis locals. Podeu baixar la versió actual <a>aquí</a>.",
"device-install-unexpected-error": "S'ha produït un error. Torneu-ho a provar.", "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-package-will-create": "Es crearà",
"device-update-existing-overwrite": "Ja existeix. Se sobreescriurà.", "device-install-nothing-installed": "No s'ha instal·lat res.",
"device-update-existing-create-copy": "Ja existeix. Se'n crearà una còpia.", "device-package-confirm-warnings": "Confirmeu { count, plural, one {1 avís} other {# avisos} } per activar el botó {action}",
"device-update-confirm-warnings": "Confirmeu { count, plural, one {1 avís} other {# avisos} } per activar el botó Actualitza", "device-package-skipped": "Sense canvis",
"device-update-skipped": "Sense canvis", "device-package-updated": "Actualitzat",
"device-update-updated": "Actualitzat", "device-package-created": "Creat",
"device-update-created": "Creat", "device-package-try-again": "Torna-ho a provar",
"device-update-try-again": "Torna-ho a provar",
"done": "Fet", "done": "Fet",
"in-progress": "En curs", "in-progress": "En curs",
"item-detail": "Element de l'IoT Hub", "item-detail": "Element de l'IoT Hub",

3
ui-ngx/src/assets/locale/locale.constant-da_DK.json

@ -6488,9 +6488,6 @@
"step-configuration": "Konfiguration", "step-configuration": "Konfiguration",
"step-provisioning": "Klargøring", "step-provisioning": "Klargøring",
"device-install-step-error": "Mislykket", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Enhed", "device-install-step-type-DEVICE": "Enhed",
"device-install-step-type-DEVICE_PROFILE": "Enhedsprofil", "device-install-step-type-DEVICE_PROFILE": "Enhedsprofil",

3
ui-ngx/src/assets/locale/locale.constant-de_DE.json

@ -6486,9 +6486,6 @@
"step-configuration": "Konfiguration", "step-configuration": "Konfiguration",
"step-provisioning": "Provisionierung", "step-provisioning": "Provisionierung",
"device-install-step-error": "Fehlgeschlagen", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Gerät", "device-install-step-type-DEVICE": "Gerät",
"device-install-step-type-DEVICE_PROFILE": "Geräteprofil", "device-install-step-type-DEVICE_PROFILE": "Geräteprofil",

3
ui-ngx/src/assets/locale/locale.constant-el_GR.json

@ -6500,9 +6500,6 @@
"step-configuration": "Διαμόρφωση", "step-configuration": "Διαμόρφωση",
"step-provisioning": "Παροχή", "step-provisioning": "Παροχή",
"device-install-step-error": "Αποτυχία", "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-DASHBOARD": "Πίνακας ελέγχου",
"device-install-step-type-DEVICE": "Συσκευή", "device-install-step-type-DEVICE": "Συσκευή",
"device-install-step-type-DEVICE_PROFILE": "Προφίλ συσκευής", "device-install-step-type-DEVICE_PROFILE": "Προφίλ συσκευής",

25
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-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-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-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-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-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", "remove-anyway": "Remove anyway",
@ -6497,6 +6498,11 @@
"install-partial-desc": "'{{name}}' was installed, but some required items were missing.", "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.", "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": "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", "updates": "Updates",
"up-to-date": "Up to date", "up-to-date": "Up to date",
"new-converter-available": "New converter available", "new-converter-available": "New converter available",
@ -6528,6 +6534,7 @@
"installed-date": "Installed", "installed-date": "Installed",
"no-installed-items": "No installed items found", "no-installed-items": "No installed items found",
"no-installed-items-text": "Try adjusting your search or filters.", "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-title": "Remove Installed Item",
"remove-installed-item-text": "Are you sure you want to remove '{{name}}'? The installed entity will also be removed.", "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", "installed-item-removed": "'{{name}}' has been removed",
@ -6544,9 +6551,6 @@
"step-configuration": "Configuration", "step-configuration": "Configuration",
"step-provisioning": "Provisioning", "step-provisioning": "Provisioning",
"device-install-step-error": "Failed", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Device", "device-install-step-type-DEVICE": "Device",
"device-install-step-type-DEVICE_PROFILE": "Device Profile", "device-install-step-type-DEVICE_PROFILE": "Device Profile",
@ -6558,7 +6562,7 @@
"device-install-step-type-INTEGRATION": "Integration", "device-install-step-type-INTEGRATION": "Integration",
"use-secret": "Use Secret", "use-secret": "Use Secret",
"use-plain-text": "Use plain text", "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-use-existing": "Use existing",
"device-install-transport-host-step": "Connection", "device-install-transport-host-step": "Connection",
"device-install-thingsboard-connection": "ThingsBoard connection", "device-install-thingsboard-connection": "ThingsBoard connection",
@ -6593,7 +6597,7 @@
"device-update-title": "Update \"{{name}}\"", "device-update-title": "Update \"{{name}}\"",
"device-update-step": "Update", "device-update-step": "Update",
"device-update-will-update": "Will be updated", "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-no-changes": "No changes",
"device-update-new": "New", "device-update-new": "New",
"device-update-shared": "Used by other packages. The update affects them.", "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 <a>here</a>.", "device-update-modified": "Has local changes. You can download the current version <a>here</a>.",
"device-install-unexpected-error": "Something went wrong. Try again.", "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-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-install-nothing-installed": "Nothing was installed.",
"device-update-skipped": "Unchanged", "device-package-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable {action}",
"device-update-updated": "Updated", "device-package-skipped": "Unchanged",
"device-update-created": "Created", "device-package-updated": "Updated",
"device-update-try-again": "Try again", "device-package-created": "Created",
"device-package-try-again": "Try again",
"done": "Done", "done": "Done",
"in-progress": "In progress", "in-progress": "In progress",
"item-detail": "IoT Hub item", "item-detail": "IoT Hub item",

3
ui-ngx/src/assets/locale/locale.constant-es_ES.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuración", "step-configuration": "Configuración",
"step-provisioning": "Aprovisionamiento", "step-provisioning": "Aprovisionamiento",
"device-install-step-error": "Fallido", "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-DASHBOARD": "Tablero",
"device-install-step-type-DEVICE": "Dispositivo", "device-install-step-type-DEVICE": "Dispositivo",
"device-install-step-type-DEVICE_PROFILE": "Perfil de dispositivo", "device-install-step-type-DEVICE_PROFILE": "Perfil de dispositivo",

3
ui-ngx/src/assets/locale/locale.constant-fr_FR.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuration", "step-configuration": "Configuration",
"step-provisioning": "Provisionnement", "step-provisioning": "Provisionnement",
"device-install-step-error": "Échoué", "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-DASHBOARD": "Tableau de bord",
"device-install-step-type-DEVICE": "Appareil", "device-install-step-type-DEVICE": "Appareil",
"device-install-step-type-DEVICE_PROFILE": "Profil d’appareil", "device-install-step-type-DEVICE_PROFILE": "Profil d’appareil",

3
ui-ngx/src/assets/locale/locale.constant-hi_IN.json

@ -6526,9 +6526,6 @@
"step-configuration": "कॉन्फ़िगरेशन", "step-configuration": "कॉन्फ़िगरेशन",
"step-provisioning": "प्रोविज़निंग", "step-provisioning": "प्रोविज़निंग",
"device-install-step-error": "विफल", "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-DASHBOARD": "डैशबोर्ड",
"device-install-step-type-DEVICE": "डिवाइस", "device-install-step-type-DEVICE": "डिवाइस",
"device-install-step-type-DEVICE_PROFILE": "डिवाइस प्रोफ़ाइल", "device-install-step-type-DEVICE_PROFILE": "डिवाइस प्रोफ़ाइल",

3
ui-ngx/src/assets/locale/locale.constant-it_IT.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configurazione", "step-configuration": "Configurazione",
"step-provisioning": "Provisioning", "step-provisioning": "Provisioning",
"device-install-step-error": "Non riuscito", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Dispositivo", "device-install-step-type-DEVICE": "Dispositivo",
"device-install-step-type-DEVICE_PROFILE": "Profilo dispositivo", "device-install-step-type-DEVICE_PROFILE": "Profilo dispositivo",

3
ui-ngx/src/assets/locale/locale.constant-ja_JP.json

@ -6486,9 +6486,6 @@
"step-configuration": "設定", "step-configuration": "設定",
"step-provisioning": "プロビジョニング", "step-provisioning": "プロビジョニング",
"device-install-step-error": "失敗", "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-DASHBOARD": "ダッシュボード",
"device-install-step-type-DEVICE": "デバイス", "device-install-step-type-DEVICE": "デバイス",
"device-install-step-type-DEVICE_PROFILE": "デバイスプロファイル", "device-install-step-type-DEVICE_PROFILE": "デバイスプロファイル",

3
ui-ngx/src/assets/locale/locale.constant-ko_KR.json

@ -6518,9 +6518,6 @@
"step-configuration": "구성", "step-configuration": "구성",
"step-provisioning": "프로비저닝", "step-provisioning": "프로비저닝",
"device-install-step-error": "실패", "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-DASHBOARD": "대시보드",
"device-install-step-type-DEVICE": "장치", "device-install-step-type-DEVICE": "장치",
"device-install-step-type-DEVICE_PROFILE": "장치 프로필", "device-install-step-type-DEVICE_PROFILE": "장치 프로필",

3
ui-ngx/src/assets/locale/locale.constant-lt_LT.json

@ -6526,9 +6526,6 @@
"step-configuration": "Konfigūracija", "step-configuration": "Konfigūracija",
"step-provisioning": "Paruošimas", "step-provisioning": "Paruošimas",
"device-install-step-error": "Nepavyko", "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-DASHBOARD": "Skydelis",
"device-install-step-type-DEVICE": "Įrenginys", "device-install-step-type-DEVICE": "Įrenginys",
"device-install-step-type-DEVICE_PROFILE": "Įrenginio profilis", "device-install-step-type-DEVICE_PROFILE": "Įrenginio profilis",

3
ui-ngx/src/assets/locale/locale.constant-nl_BE.json

@ -6526,9 +6526,6 @@
"step-configuration": "Configuratie", "step-configuration": "Configuratie",
"step-provisioning": "Provisioning", "step-provisioning": "Provisioning",
"device-install-step-error": "Mislukt", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Apparaat", "device-install-step-type-DEVICE": "Apparaat",
"device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel", "device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel",

3
ui-ngx/src/assets/locale/locale.constant-nl_NL.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuratie", "step-configuration": "Configuratie",
"step-provisioning": "Provisioning", "step-provisioning": "Provisioning",
"device-install-step-error": "Mislukt", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Apparaat", "device-install-step-type-DEVICE": "Apparaat",
"device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel", "device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel",

3
ui-ngx/src/assets/locale/locale.constant-no_NO.json

@ -6500,9 +6500,6 @@
"step-configuration": "Konfigurasjon", "step-configuration": "Konfigurasjon",
"step-provisioning": "Klargjøring", "step-provisioning": "Klargjøring",
"device-install-step-error": "Mislyktes", "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-DASHBOARD": "Dashbord",
"device-install-step-type-DEVICE": "Enhet", "device-install-step-type-DEVICE": "Enhet",
"device-install-step-type-DEVICE_PROFILE": "Enhetsprofil", "device-install-step-type-DEVICE_PROFILE": "Enhetsprofil",

3
ui-ngx/src/assets/locale/locale.constant-pl_PL.json

@ -6526,9 +6526,6 @@
"step-configuration": "Konfiguracja", "step-configuration": "Konfiguracja",
"step-provisioning": "Aprowizacja", "step-provisioning": "Aprowizacja",
"device-install-step-error": "Niepowodzenie", "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-DASHBOARD": "Pulpit",
"device-install-step-type-DEVICE": "Urządzenie", "device-install-step-type-DEVICE": "Urządzenie",
"device-install-step-type-DEVICE_PROFILE": "Profil urządzenia", "device-install-step-type-DEVICE_PROFILE": "Profil urządzenia",

3
ui-ngx/src/assets/locale/locale.constant-pt_BR.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuração", "step-configuration": "Configuração",
"step-provisioning": "Provisionamento", "step-provisioning": "Provisionamento",
"device-install-step-error": "Falhou", "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-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Dispositivo", "device-install-step-type-DEVICE": "Dispositivo",
"device-install-step-type-DEVICE_PROFILE": "Perfil do dispositivo", "device-install-step-type-DEVICE_PROFILE": "Perfil do dispositivo",

3
ui-ngx/src/assets/locale/locale.constant-sl_SI.json

@ -6516,9 +6516,6 @@
"step-configuration": "Konfiguracija", "step-configuration": "Konfiguracija",
"step-provisioning": "Priprava", "step-provisioning": "Priprava",
"device-install-step-error": "Ni uspelo", "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-DASHBOARD": "Nadzorna plošča",
"device-install-step-type-DEVICE": "Naprava", "device-install-step-type-DEVICE": "Naprava",
"device-install-step-type-DEVICE_PROFILE": "Profil naprave", "device-install-step-type-DEVICE_PROFILE": "Profil naprave",

3
ui-ngx/src/assets/locale/locale.constant-tr_TR.json

@ -6488,9 +6488,6 @@
"step-configuration": "Yapılandırma", "step-configuration": "Yapılandırma",
"step-provisioning": "Sağlama", "step-provisioning": "Sağlama",
"device-install-step-error": "Başarısız", "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-DASHBOARD": "Pano",
"device-install-step-type-DEVICE": "Cihaz", "device-install-step-type-DEVICE": "Cihaz",
"device-install-step-type-DEVICE_PROFILE": "Cihaz profili", "device-install-step-type-DEVICE_PROFILE": "Cihaz profili",

3
ui-ngx/src/assets/locale/locale.constant-uk_UA.json

@ -6486,9 +6486,6 @@
"step-configuration": "Конфігурація", "step-configuration": "Конфігурація",
"step-provisioning": "Реєстрація", "step-provisioning": "Реєстрація",
"device-install-step-error": "Не вдалося", "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-DASHBOARD": "Дашборд",
"device-install-step-type-DEVICE": "Пристрій", "device-install-step-type-DEVICE": "Пристрій",
"device-install-step-type-DEVICE_PROFILE": "Профіль пристрою", "device-install-step-type-DEVICE_PROFILE": "Профіль пристрою",

3
ui-ngx/src/assets/locale/locale.constant-zh_CN.json

@ -6488,9 +6488,6 @@
"step-configuration": "配置", "step-configuration": "配置",
"step-provisioning": "预配", "step-provisioning": "预配",
"device-install-step-error": "失败", "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-DASHBOARD": "仪表板",
"device-install-step-type-DEVICE": "设备", "device-install-step-type-DEVICE": "设备",
"device-install-step-type-DEVICE_PROFILE": "设备配置", "device-install-step-type-DEVICE_PROFILE": "设备配置",

3
ui-ngx/src/assets/locale/locale.constant-zh_TW.json

@ -9357,9 +9357,6 @@
"step-configuration": "設定", "step-configuration": "設定",
"step-provisioning": "佈建", "step-provisioning": "佈建",
"device-install-step-error": "失敗", "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-DASHBOARD": "儀表板",
"device-install-step-type-DEVICE": "裝置", "device-install-step-type-DEVICE": "裝置",
"device-install-step-type-DEVICE_PROFILE": "裝置設定檔", "device-install-step-type-DEVICE_PROFILE": "裝置設定檔",

Loading…
Cancel
Save