Browse Source

Merge pull request #16647 from ShvaykaD/fix/iot-hub-device-package-step-keys

IoT Hub device packages: install state keyed by step type and name; update step shows what each step will do
pull/16652/head
Viacheslav Klimov 3 weeks ago
committed by GitHub
parent
commit
d8488dbff9
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 28
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  2. 11
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  3. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
  4. 97
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  5. 32
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  6. 14
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  7. 33
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  8. 180
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  9. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  10. 1
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  11. 9
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html
  12. 12
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  13. 2
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  14. 6
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  15. 19
      ui-ngx/src/assets/locale/locale.constant-en_US.json

28
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java

@ -177,8 +177,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
validateIntegrations(tenantId, request);
applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo));
} catch (StepFailure e) {
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName);
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey);
} catch (RestClientException e) {
log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e);
return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null);
@ -209,14 +209,14 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
throw new IllegalArgumentException("The update has no steps");
}
Set<UUID> ownedIds = ownedIds(devicePackage.descriptor());
Set<String> stateKeys = new HashSet<>();
// 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<>();
for (DeviceUpdateRequest.Step step : request.getSteps()) {
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) {
throw new IllegalArgumentException("Invalid update step: " + step.getName());
}
// The key of the step's install state
if (!stateKeys.add(step.getId() != null ? step.getId() : step.getName())) {
throw new IllegalArgumentException("Duplicate update step: " + step.getName());
if (!stateKeys.add(step.stateKey())) {
throw new IllegalArgumentException("Duplicate update step: " + step.stateKey());
}
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
switch (step.getAction()) {
@ -267,9 +267,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} catch (ExecutionException e) {
// What the integration reports, e.g. wrong credentials, is what the user has to fix
Throwable cause = e.getCause() != null ? e.getCause() : e;
throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause));
throw new StepFailure(step.stateKey(), new IllegalArgumentException(cause.getMessage(), cause));
} catch (TimeoutException e) {
throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration"));
throw new StepFailure(step.stateKey(), new IllegalStateException("Timeout to validate the integration configuration"));
}
}
}
@ -308,7 +308,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
StepResult result = applyStep(tenantId, step, entity);
ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.getName(), output);
outputs.put(step.stateKey(), output);
ObjectNode state = JacksonUtil.newObjectNode();
state.set("entityOutput", output);
// The package's own entity stays the package's, whatever the request says, so later versions update it
@ -328,7 +328,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if (metadata != null) {
state.set("metadata", metadata);
}
installState.put(step.getId() != null ? step.getId() : step.getName(), state);
installState.put(step.stateKey(), state);
// As at install, an entity used as it was is listed too, so a delete removes the metadata entries the
// package added to it; usedExistingEntityIds keeps it the user's
if (!stepEntityIds.contains(result.entityId())) {
@ -350,7 +350,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} catch (StepFailure e) {
throw e;
} catch (Exception e) {
throw new StepFailure(step.getName(), e);
throw new StepFailure(step.stateKey(), e);
}
}
@ -989,11 +989,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */
private static class StepFailure extends RuntimeException {
private final String stepName;
private final String stepKey;
StepFailure(String stepName, Throwable cause) {
StepFailure(String stepKey, Throwable cause) {
super(cause.getMessage(), cause);
this.stepName = stepName;
this.stepKey = stepKey;
}
}

11
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java

@ -38,7 +38,8 @@ public class DeviceUpdateRequest {
@Data
public static class Step {
private String name;
// The package step's id, which keys its install state; the name when not set
// The package step's stable id, so that a next version can rename the step. It is also the step's install state
// key when set, which the default converter update relies on to write the state back under the stored key
private String id;
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
@ -66,6 +67,14 @@ public class DeviceUpdateRequest {
private JsonNode metadata;
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
private boolean defaultConverter;
/**
* The key of the step's install state: its id, or else its type and name, so that two steps of an install
* method never share it. The install wizard keys the steps of an install the same way.
*/
public String stateKey() {
return id != null ? id : type + ":" + name;
}
}
}

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java

@ -12,7 +12,7 @@ import java.util.Map;
/**
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep
* names the step that failed, if one did.
* is the install state key of the step that failed, if one did.
*/
@Data
@NoArgsConstructor
@ -23,7 +23,7 @@ public class DeviceUpdateResult {
private String errorMessage;
private String failedStep;
private DeviceInstalledItemDescriptor descriptor;
// By step name: 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;
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {

97
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -206,7 +206,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
// Of the saved dashboard, not read back by id: inside the transaction that may come from the cache
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText())
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("checksum").asText())
.isEqualTo(EntityChecksum.of(savedDashboard.getValue()));
assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId);
}
@ -225,7 +225,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@ -245,7 +245,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview");
assertThat(descriptor.getInstallState()).containsOnlyKeys("main-dashboard");
}
@Test
@ -260,7 +260,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse();
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").has("checksum")).isFalse();
}
@Test
@ -273,7 +273,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getInstallState().get("DASHBOARD:Overview").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId);
}
@ -289,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing");
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("resolution").asText()).isEqualTo("use-existing");
}
@Test
@ -334,7 +334,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("resolution").asText()).isEqualTo("created");
}
@Test
@ -395,7 +395,7 @@ class DefaultDevicePackageUpdateServiceTest {
// A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit
assertThat(saved.getValue()).isNotSameAs(current);
assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN");
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("INTEGRATION:TTN");
assertThat(state.get("resolution").asText()).isEqualTo("use-existing");
// The entries the step added, which a delete of the package removes; not the one it removed
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
@ -450,7 +450,7 @@ class DefaultDevicePackageUpdateServiceTest {
// entries from it (DefaultIotHubServiceTest#deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheIntegrationItTookAsItWas)
assertThat(descriptor.getCreatedEntityIds()).containsOnlyOnce(tenantsIntegrationId);
assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(tenantsIntegrationId);
JsonNode state = descriptor.getInstallState().get("TTN");
JsonNode state = descriptor.getInstallState().get("INTEGRATION:TTN");
assertThat(state.get("resolution").asText()).isEqualTo("use-existing");
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
}
@ -487,6 +487,75 @@ class DefaultDevicePackageUpdateServiceTest {
verify(installedItemService, never()).save(any(), any());
}
@Test
void twoStepsOfOneTypeAndName_areRejected() {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard");
verify(transactionTemplate, never()).execute(any());
}
@Test
void stepWithTheKeyOfAForm_isRejected() {
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setId("Settings");
DeviceUpdateRequest request = request(step);
request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10))));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings");
verify(transactionTemplate, never()).execute(any());
}
@Test
void stepsOfOneNameAndAnotherType_eachKeepTheirOwnState() {
// Installed when the state was keyed by name: the integration's state replaced the converter's
ConverterId converterId = new ConverterId(UUID.randomUUID());
Converter converter = new Converter(converterId);
converter.setTenantId(tenantId);
converter.setName("TTN my-app");
when(converterService.findConverterById(tenantId, converterId)).thenReturn(converter);
Integration integration = new Integration(integrationId);
integration.setTenantId(tenantId);
integration.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
integration.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration);
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setCreatedEntityIds(List.of(profileId, deviceId, converterId, integrationId));
ObjectNode legacy = stateOf(integrationId, "created").put("checksum", "installed");
legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app"))));
DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId);
uplink.setDefaultConverter(true);
DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId);
ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceUpdateRequest request = request(uplink, ttn);
request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration")));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
// The state under the name is gone: each step's is under its own key now
assertThat(state).containsOnlyKeys("Configuration", "UPLINK_CONVERTER:${integrationName}", "INTEGRATION:${integrationName}");
JsonNode converterState = state.get("UPLINK_CONVERTER:${integrationName}");
assertThat(converterState.get("entityOutput").get("id").asText()).isEqualTo(converterId.getId().toString());
assertThat(converterState.get("defaultConverter").asBoolean()).isTrue();
JsonNode integrationState = state.get("INTEGRATION:${integrationName}");
assertThat(integrationState.get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString());
assertThat(integrationState.get("checksum").asText()).isEqualTo("installed");
assertThat(integrationState.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
assertThat(result.getOutputs().get("UPLINK_CONVERTER:${integrationName}").get("id").asText()).isEqualTo(converterId.getId().toString());
assertThat(result.getOutputs().get("INTEGRATION:${integrationName}").get("id").asText()).isEqualTo(integrationId.getId().toString());
}
@Test
void failedStep_rollsBackAndReportsTheStep() {
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308"));
@ -499,7 +568,7 @@ class DefaultDevicePackageUpdateServiceTest {
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached");
assertThat(rolledBack).hasSize(1);
verify(installedItemService, never()).save(any(), any());
@ -515,7 +584,7 @@ class DefaultDevicePackageUpdateServiceTest {
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).contains("Check the update again");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@ -550,7 +619,7 @@ class DefaultDevicePackageUpdateServiceTest {
// The devices keep sending to the same endpoint
assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key");
assertThat(saved.getValue().getName()).isEqualTo("TTN my-app");
assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key");
assertThat(result.getOutputs().get("INTEGRATION:TTN").get("routingKey").asText()).isEqualTo("routing-key");
}
@Test
@ -579,7 +648,7 @@ class DefaultDevicePackageUpdateServiceTest {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink");
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink");
assertThat(state.get("defaultConverter").asBoolean()).isTrue();
// The other packages keep what they recorded: check() takes the checksum of any installed package
assertThat(created.get("checksum").asText()).isEqualTo("before");
@ -631,7 +700,7 @@ class DefaultDevicePackageUpdateServiceTest {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("Dashboard");
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard");
}
@Test

32
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -599,6 +599,38 @@ class DefaultIotHubServiceTest {
verify(integrationService, never()).deleteIntegration(any(), any());
}
@Test
void deleteInstalledItem_devicePackageInstalledWithStateByName_deletesTheConverterWhoseStateWasReplaced() throws Exception {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
IotHubInstalledItem deleted = devicePackage(converter.getId(), integrationId);
// The converter and the integration steps shared the name: the integration's state replaced the converter's
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", "use-existing");
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", integrationId.getId().toString()));
state.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) deleted.getDescriptor();
descriptor.setInstallState(Map.of("${integrationName}", state));
descriptor.setUsedExistingEntityIds(List.of(integrationId));
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(integrationService.findIntegrationById(tenantId, integrationId))
.thenReturn(integration(integrationId, Map.of("profile.milesight-iot-am308", "AM308", "profile.added-by-user", "Mine")));
service.deleteInstalledItem(user, deleted.getId());
// Found by createdEntityIds, not by the install state
verify(tbConverterService).delete(converter, user);
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
verify(integrationService, never()).deleteIntegration(any(), any());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
assertThat(metadata.get("profile.added-by-user").asText()).isEqualTo("Mine");
}
@Test
void findKeptEntities_devicePackage_namesTheSharedEntitiesAndCountsTheOtherPackages() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());

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

@ -237,7 +237,7 @@
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success">check_circle</mat-icon>
<mat-icon class="tb-progress-success tb-update-reveal">check_circle</mat-icon>
}
@default {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
@ -258,9 +258,6 @@
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-existing-' + plan.resolution | translate }}</span>
}
@if (plan.shared) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-shared' | translate }}</span>
}
@ -277,14 +274,17 @@
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
@case ('success') {
<span class="tb-progress-status-done">{{ updateOutcomeOf(plan) | translate }}</span>
<span class="tb-progress-status-done tb-update-reveal">{{ updateOutcomeOf(plan) | translate }}</span>
}
@case ('skipped') {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-skipped' | translate }}</span>
}
@default {
@if (ws.reviewing && plan) {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-no-conflicts' | translate }}</span>
<!-- A resolved name conflict shows the choice: Use existing, Overwrite or Create copy -->
@if (ws.reviewing && plan?.existing && plan.confirmed) {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-install-' + plan.resolution | translate }}</span>
} @else if (ws.reviewing && plan) {
<span class="tb-progress-status-progress">{{ plannedOutcomeOf(plan) | translate }}</span>
}
}
}

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

@ -25,6 +25,12 @@
flex-direction: column;
max-height: 90vh;
// The content takes the height left by the header and the actions, so a long form scrolls inside it
.mat-mdc-dialog-content {
flex: 1 1 auto;
min-height: 0;
}
@media #{$mat-lt-md} {
max-height: 100%;
height: 100%;
@ -49,8 +55,10 @@
flex: 1;
padding: 0;
}
// The current step fills the content area and scrolls itself: the stepper may give it overflow: hidden
.mat-horizontal-stepper-content.mat-horizontal-stepper-content-current {
height: 100%;
overflow-y: auto;
}
.mat-horizontal-stepper-header.mat-step-header {
padding: 0 12px;
@ -329,8 +337,8 @@
font-weight: 500;
line-height: 16px;
letter-spacing: 0.4px;
color: #305680;
background: rgba(48, 86, 128, 0.08);
color: var(--tb-primary-500);
background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent);
border-radius: 4px;
padding: 2px 8px;
}
@ -348,6 +356,27 @@
color: #198038;
}
// Update: the outcome of a row shows in when the row gets it
.tb-update-reveal {
display: inline-block;
animation: tb-update-reveal 200ms ease-out;
@media (prefers-reduced-motion: reduce) {
animation: none;
}
}
@keyframes tb-update-reveal {
from {
opacity: 0;
transform: scale(0.6);
}
to {
opacity: 1;
transform: scale(1);
}
}
.tb-progress-status-progress {
color: rgba(0, 0, 0, 0.54);
}

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

@ -68,7 +68,8 @@ export interface DeviceInstallDialogData {
item: MpItemVersionView;
reviewMode?: boolean;
selectedInstallMethod?: string;
installState?: Record<string, any>;
// Review mode: the installed package, whose install state the wizard shows
reviewed?: DeviceInstalledItemDescriptor;
entityGroupId?: string;
customerId?: string;
// Set when the wizard updates an installed package to the item version
@ -197,7 +198,7 @@ export interface WizardStep {
formFields?: FormFieldDefinition[];
// Fields the dialog adds on top of the package's form file
extraFormFields?: FormFieldDefinition[];
// Key of the step's form values in the install state; the label when not set
// Form: the key of its values in the install state
stateKey?: string;
// Update: the keys of the form's fields the installed version didn't have
newFieldKeys?: Set<string>;
@ -224,6 +225,8 @@ export interface ConnectionCheck {
}
const ENTITY_STEP_MIN_DELAY = 2000;
// Update: the rows show the outcome of the one request one after another, this far apart
const UPDATE_REVEAL_INTERVAL = 150;
// Where the wizard keeps the converter it builds for a step with "default": true, as if the package had that file
const DEFAULT_CONVERTER_PATH = 'tb-default-converter/';
const DEFAULT_RANDOM_SIZE = 20;
@ -462,10 +465,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
console.error('Failed to fetch connectivity settings', _e);
}
// Review mode: restore state and start wizard with stored values
if (this.data.reviewMode && this.data.installState && this.data.selectedInstallMethod) {
if (this.data.reviewMode && this.data.reviewed?.installState && this.data.selectedInstallMethod) {
this.reviewMode = true;
this.selectedInstallMethod = this.data.selectedInstallMethod;
this.restoreInstallState(this.data.installState);
this.restoreInstallState();
this.startWizard();
// After startWizard: the transport fields it adds take part in resolving the file
this.resolveGatewayDockerCompose();
@ -1049,24 +1052,21 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// --- Private ---
/** withFormValues false: only the entity outputs, e.g. to keep the values the user has just entered. */
private restoreInstallState(installState: Record<string, any>, withFormValues = true): void {
for (const [stepName, data] of Object.entries(installState)) {
if (withFormValues && data.formValues) {
Object.assign(this.formValues, data.formValues);
}
if (data.entityOutput) {
// Find the step type alias from the raw steps to set the correct entity output key
const rawSteps = this.packageInfo.installSteps[this.selectedInstallMethod] || [];
const matchingStep = rawSteps.find(s => this.stateKeysOf(s).includes(stepName)) ??
// Update: a step the new version renamed or gave an id
(this.data.update ? rawSteps.find(s => this.storedStateOf(s)?.key === stepName) : undefined);
if (matchingStep) {
const alias = stepTypeAliasMap[matchingStep.type];
if (alias) {
this.entityOutputs.set(alias, data.entityOutput);
}
}
/**
* Takes the installed package's form values and the outputs of its entity steps, by alias.
* withFormValues false: only the entity outputs, e.g. to keep the values the user has just entered.
*/
private restoreInstallState(withFormValues = true): void {
if (withFormValues) {
for (const state of Object.values(this.installedDescriptor?.installState ?? {})) {
Object.assign(this.formValues, state?.formValues);
}
}
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] || []) {
const alias = stepTypeAliasMap[step.type];
const output = alias ? this.storedStateOf(step)?.state.entityOutput : undefined;
if (output) {
this.entityOutputs.set(alias, output);
}
}
}
@ -1088,7 +1088,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
if (this.data.update) {
// The instructions before the Update step refer to the installed entities, e.g. ${device.token}
this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false);
this.restoreInstallState(false);
}
this.buildWizardSteps();
this.wizardStarted = true;
@ -1159,7 +1159,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.wizardSteps.push({
type: 'form',
label: step.name,
stateKey: step.id,
stateKey: this.stateKeyOf(step),
rawSteps: [step],
completed: this.reviewMode
});
@ -1302,7 +1302,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// except the transport fields, which take the current Device connectivity settings; otherwise use defaults
let storedValues: Record<string, any> | undefined;
if (this.reviewMode) {
storedValues = this.data.installState?.[ws.stateKey ?? ws.label]?.formValues;
storedValues = this.installedDescriptor.installState[ws.stateKey]?.formValues;
} else if (this.data.update && ws.stateKey !== TRANSPORT_STEP_STATE_KEY && ws.rawSteps[0]) {
// Also when the new version renamed the step
storedValues = this.storedStateOf(ws.rawSteps[0])?.state.formValues;
@ -1462,15 +1462,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private showCompletedEntitySteps(ws: WizardStep): void {
ws.entitySteps = ws.rawSteps.map(s => {
const alias = stepTypeAliasMap[s.type];
const output = alias ? this.entityOutputs.get(alias) : null;
const key = this.stateKeysOf(s).find(k => this.data.installState?.[k]);
const storedState = key ? this.data.installState[key] : undefined;
const storedState = this.storedStateOf(s)?.state;
return {
step: s,
status: 'success' as const,
resolvedName: this.resolveVariables(s.name),
entityOutput: output || undefined,
entityOutput: storedState?.entityOutput,
resolution: storedState?.resolution || 'created'
};
});
@ -1507,6 +1504,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
private async runEntitySteps(ws: WizardStep): Promise<void> {
const duplicateKey = this.duplicateStateKey();
if (duplicateKey) {
ws.progressError = this.translate.instant('iot-hub.device-install-duplicate-step', { key: duplicateKey });
this.cdr.detectChanges();
return;
}
for (const ep of ws.entitySteps) {
if (ep.status === 'success') {
continue;
@ -1943,7 +1946,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
/** The metadata entries resolved with the form values the package was installed with, as the text-only update has no forms. */
private metadataWithInstalledValues(step: DeviceInstallStep): Record<string, string | null> | undefined {
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
this.restoreInstallState();
try {
return this.integrationMetadataOf(step);
} finally {
@ -2121,12 +2124,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
}
/** Update: what the update will do with the entity of a row; the same as updateOutcomeOf says once it succeeded. */
plannedOutcomeOf(plan: EntityStepPlan): string {
return { update: 'iot-hub.device-update-will-update', create: 'iot-hub.device-update-will-create',
keep: 'iot-hub.device-update-no-changes' }[this.outcomeOf(plan)];
}
/** Update: what the update did with the entity of a row, once it succeeded. */
updateOutcomeOf(plan: EntityStepPlan | undefined): string {
return { update: 'iot-hub.device-update-updated', create: 'iot-hub.device-update-created',
keep: 'iot-hub.device-update-skipped' }[this.outcomeOf(plan)];
}
/**
* Update: an entity kept or used as it is counts as not changed, even an integration the server adds the step's
* metadata entries to; one a name conflict resolves to overwrite counts as updated.
*/
private outcomeOf(plan: EntityStepPlan | undefined): 'update' | 'create' | 'keep' {
if (!plan || plan.action === 'keep' || plan.resolution === 'use-existing') {
return 'iot-hub.done';
return 'keep';
}
return plan.action === 'overwrite' || plan.resolution === 'overwrite' ? 'iot-hub.device-update-updated' : 'iot-hub.device-update-created';
return plan.action === 'create' && plan.resolution !== 'overwrite' ? 'create' : 'update';
}
textWithLink(key: string): { before: string; link: string; after: string } {
@ -2152,7 +2170,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
/**
* Update: sends what the check planned to the server, which applies all of it in one transaction together with
* the new version of the installed item, or nothing. The rows run together: the request is one.
* the new version of the installed item, or nothing. The rows run together: the request is one. A success shows
* row by row, and the update counts as running until the last row shows it.
*/
async runUpdate(ws: WizardStep): Promise<void> {
ws.reviewing = false;
@ -2175,23 +2194,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} catch (e: any) {
result = { success: false, errorMessage: this.failureMessage(e) };
}
ws.updating = false;
if (!result.success) {
ws.updating = false;
// Nothing was changed: the transaction was rolled back
const message = readableMessage(result.errorMessage) ?? this.translate.instant('iot-hub.device-install-unexpected-error');
for (const ep of ws.entitySteps) {
const failed = ep.step.name === result.failedStep;
const failed = this.stateKeyOf(ep.step) === result.failedStep;
ep.status = failed ? 'error' : 'skipped';
ep.errorMessage = failed ? message : null;
}
ws.progressError = message;
// The steps refer to the installed entities again
this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false);
this.restoreInstallState(false);
this.cdr.detectChanges();
return;
}
for (const ep of ws.entitySteps) {
const output = result.outputs?.[ep.step.name];
const interval = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 0 : UPDATE_REVEAL_INTERVAL;
for (const [index, ep] of ws.entitySteps.entries()) {
if (index > 0 && interval) {
await this.delay(interval);
}
const output = result.outputs?.[this.stateKeyOf(ep.step)];
const plan = this.entityPlans.get(ep);
const resolution = plan?.previous?.resolution ?? plan?.resolution ?? 'created';
if (output) {
@ -2202,8 +2225,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.markEntityStepSuccess(ws, ep, entityOutput, resolution);
} else {
ep.status = 'success';
this.cdr.detectChanges();
}
}
ws.updating = false;
this.installRegistered = true;
ws.progressDone = true;
ws.completed = true;
@ -2215,7 +2240,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const state: Record<string, any> = {};
for (const ws of this.wizardSteps) {
if (ws.type === 'form' && ws.formGroup) {
state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() };
state[ws.stateKey] = { formValues: ws.formGroup.getRawValue() };
}
}
return state;
@ -2402,7 +2427,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
* the update shows that someone changed it.
*/
private async checkDefaultConverters(): Promise<void> {
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
this.restoreInstallState();
let ownDefaultConverterIds: Set<string> | undefined;
try {
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
@ -2446,7 +2471,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (!this.previousPackageInfo) {
return false;
}
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
this.restoreInstallState();
try {
return (this.packageInfo.installSteps[this.selectedInstallMethod] ?? []).every(step => {
if (step.type === InstallStepType.SHOW_FORM) {
@ -2491,7 +2516,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
const formValues = step.type === InstallStepType.SHOW_FORM ? this.storedStateOf(step)?.state.formValues : undefined;
if (formValues) {
formState[step.id ?? step.name] = { formValues };
formState[this.stateKeyOf(step)] = { formValues };
}
}
try {
@ -2576,25 +2601,62 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return !!descriptor?.createdEntityIds?.some(created => created.id === id) && !usedExisting;
}
/** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */
private stateKeysOf(step: DeviceInstallStep): string[] {
return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)];
/** The installed package: the one the wizard updates, or the one review mode shows. */
private get installedDescriptor(): DeviceInstalledItemDescriptor | undefined {
return this.data.update?.descriptor ?? this.data.reviewed;
}
/**
* The key of the step's install state: its id, or else its type and name, so that two steps of an install method
* never share it. A form without an id keeps its name, which no entity step's type-and-name key equals; a step id
* equal to a form's name is caught by the duplicate check on install, and by the server on update.
* The server keys the steps of an update the same way.
*/
private stateKeyOf(step: DeviceInstallStep): string {
return step.id ?? (step.type === InstallStepType.SHOW_FORM ? step.name : `${step.type}:${step.name}`);
}
/**
* Update: the install state of a step of the new version, under the key of the installed step it replaces.
* A key two steps of the install method share (forms included: a form's values are saved under its key too), so one's
* install state would overwrite the other's; null when none.
*/
private duplicateStateKey(): string | null {
const keys = new Set<string>();
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
if (step.type !== InstallStepType.SHOW_FORM && !ENTITY_STEP_TYPES.has(step.type)) {
continue;
}
const key = this.stateKeyOf(step);
if (keys.has(key)) {
return key;
}
keys.add(key);
}
return null;
}
/**
* The installed package's install state of a step; in an update, under the key of the installed step it replaces.
* Without the installed version's steps (e.g. it can't be downloaded any more), a step that has gained an id
* is also looked up under its own name, which the installed version keyed it by.
* is also looked up as the installed version had it, without the id.
*/
private storedStateOf(step: DeviceInstallStep): { key: string; state: any } | undefined {
const installState = this.data.update?.descriptor.installState ?? {};
const previousStep = this.findPreviousStep(step);
const keys = [...(previousStep ? this.stateKeysOf(previousStep) : []), ...this.stateKeysOf(step)];
if (!this.previousPackageInfo && step.id) {
keys.push(step.name, this.resolveVariables(step.name));
}
const key = keys.find(k => k && installState[k]);
return key ? { key, state: installState[key] } : undefined;
const installState = this.installedDescriptor?.installState ?? {};
const steps = [this.findPreviousStep(step), step,
this.data.update && !this.previousPackageInfo && step.id ? { ...step, id: undefined } : undefined]
.filter((s): s is DeviceInstallStep => !!s);
const key = steps.map(s => this.stateKeyOf(s)).find(k => installState[k]);
if (key) {
return { key, state: installState[key] };
}
// Legacy: an entity step without an id was keyed by its name, as written or resolved, so a later step of the same
// name overwrote its state. Such a state is the step's only when it records an entity of the step's type.
const entityType = this.stepTypeToEntityType(step.type);
const legacyKey = steps.filter(s => !s.id && s.type !== InstallStepType.SHOW_FORM)
.flatMap(s => [s.name, this.resolveVariables(s.name)])
.find(k => installState[k] && this.installedDescriptor.createdEntityIds?.some(
created => created.id === installState[k].entityOutput?.id && created.entityType === entityType));
return legacyKey ? { key: legacyKey, state: installState[legacyKey] } : undefined;
}
private formStepChanged(step: DeviceInstallStep): boolean {
@ -2651,7 +2713,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private async checkUpdate(ws: WizardStep): Promise<void> {
const run = ++this.updateCheckRun;
// Templates refer to the package's entities, e.g. ${deviceProfile.id}: until the steps run, the installed ones
this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false);
this.restoreInstallState(false);
ws.entitySteps = ws.rawSteps.map(s => ({
step: s,
status: 'pending' as const,
@ -2842,12 +2904,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const state: Record<string, any> = {};
for (const ws of this.wizardSteps) {
if (ws.type === 'form' && ws.formGroup) {
state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() };
state[ws.stateKey] = { formValues: ws.formGroup.getRawValue() };
} else if (ws.type === 'progress' && ws.entitySteps) {
for (const ep of ws.entitySteps) {
if (ep.status === 'success' && ep.entityOutput) {
const metadata = this.addedMetadataOf(ep.step);
state[ep.step.id ?? ep.step.name] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created',
state[this.stateKeyOf(ep.step)] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created',
...(ep.step.default ? { defaultConverter: true } : {}), ...(metadata ? { metadata } : {}) };
}
}

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

@ -239,7 +239,7 @@ export class IotHubActionsService {
return this.openDeviceInstallDialog(item, {
reviewMode: true,
selectedInstallMethod: deviceDescriptor.selectedInstallMethod,
installState: deviceDescriptor.installState
reviewed: deviceDescriptor
});
}
@ -265,7 +265,7 @@ export class IotHubActionsService {
}
private openDeviceInstallDialog(item: MpItemVersionView,
options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any;
options?: { reviewMode?: boolean; selectedInstallMethod?: string; reviewed?: DeviceInstalledItemDescriptor;
entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable<any> {
return this.dialog.open<TbDeviceInstallDialogComponent, DeviceInstallDialogData>(TbDeviceInstallDialogComponent, {
panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'],

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

@ -113,6 +113,7 @@ export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, ex
installState: {},
steps: [{
name: update.converter.name,
// The server keys the step's state by its id: the state stays under the key it has
id: update.stateKey,
type: 'UPLINK_CONVERTER',
action: 'OVERWRITE',

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

@ -9,7 +9,14 @@
<h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-delete-desc">{{ description }}</p>
@if (keptReferences) {
<tb-image-references [references]="keptReferences"></tb-image-references>
<div class="tb-form-hint tb-primary-fill">
<mat-icon>info_outline</mat-icon>
<div class="flex flex-col">
<div class="font-medium">{{ keptTitle }}</div>
<div>{{ keptReason }}</div>
<tb-image-references class="mt-3" [references]="keptReferences"></tb-image-references>
</div>
</div>
}
</div>
<div class="flex items-center justify-end gap-2 p-2">

12
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts

@ -32,6 +32,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
// A device package keeps the entities other installed packages use, and the dialog lists them before the user confirms
keptReferences: ResourceReferences | null = null;
keptTitle: string;
keptReason: string;
constructor(
protected store: Store<AppState>,
@ -42,15 +44,15 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
private translate: TranslateService
) {
super(store, router, dialogRef);
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
const kept = data.keptEntities;
if (kept?.entities.length) {
this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
// Kept because other packages use them, because the user had them before the package, or both
const key = !kept.usedExistingCount ? 'iot-hub.remove-desc-kept' :
!kept.usedByItemsCount ? 'iot-hub.remove-desc-kept-own' : 'iot-hub.remove-desc-kept-own-or-used';
this.description = this.translate.instant(key, { count: kept.usedByItemsCount, kept: kept.entities.length });
} else {
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' :
!kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used';
this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length });
this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length });
}
}

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

@ -216,7 +216,7 @@ export interface DeviceInstallStep {
type: InstallStepType;
name: string;
// Optional stable id of the step, unique within the install method: the key of the step's install state,
// so the next version can rename the step. Without it, the name is the key.
// so the next version can rename the step. Without it, the key is the type and the name; a form's is its name.
id?: string;
file?: string;
template?: string;

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

@ -62,7 +62,8 @@ export interface DeviceUpdateStep {
serverAttributes?: any;
sharedAttributes?: any;
resolution?: string;
// The package step's id, which keys its install state; the name when not set
// The package step's stable id, so that a next version can rename the step. When set it is also the step's install
// state key: the default converter update sends the stored key here to write the state back under it
id?: string;
// INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry
metadata?: Record<string, string | null>;
@ -80,12 +81,13 @@ export interface DeviceUpdateRequest {
steps: DeviceUpdateStep[];
}
/** All of the update was applied, or none of it: failedStep names the step that failed, if one did. */
/** All of the update was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */
export interface DeviceUpdateResult {
success: boolean;
errorMessage?: string;
failedStep?: string;
descriptor?: DeviceInstalledItemDescriptor;
// By install state key of the step
outputs?: Record<string, any>;
}

19
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -6445,10 +6445,11 @@
"install-success-desc": "'{{name}}' has been installed successfully",
"remove": "Remove",
"remove-confirm-title": "Remove '{{name}}'?",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant",
"remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:",
"remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant.",
"remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }",
"remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.",
"remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.",
"remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.",
"remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant",
"remove-anyway": "Remove anyway",
"select-entity-for-cf": "Select entity for calculated field '{{name}}'",
@ -6588,17 +6589,17 @@
"device-installing-title": "Installing \"{{name}}\"",
"device-update-title": "Update \"{{name}}\"",
"device-update-step": "Update",
"device-update-no-conflicts": "No conflicts",
"device-update-will-update": "Will be updated",
"device-update-will-create": "Will be created",
"device-update-no-changes": "No changes",
"device-update-new": "New",
"device-update-shared": "Used by other packages. The update affects them.",
"device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.",
"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-update-existing-use-existing": "Already exists. The existing one will be used.",
"device-update-existing-overwrite": "Already exists. It will be overwritten.",
"device-update-existing-create-copy": "Already exists. A copy will be created.",
"device-install-duplicate-step": "Two install steps of this device package have the same key: {{key}}. Report it to the package's creator.",
"device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update",
"device-update-skipped": "Not changed",
"device-update-skipped": "Unchanged",
"device-update-updated": "Updated",
"device-update-created": "Created",
"device-update-try-again": "Try again",

Loading…
Cancel
Save