From 5f5e3732e0fe679a63cca815612bb9885c977c4d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 13 Nov 2026 13:31:05 +0200 Subject: [PATCH 1/7] IoT Hub installed items: the items with an update come first after Check for updates (PROD-9326) --- .../server/controller/IotHubController.java | 7 +- .../service/iot_hub/DefaultIotHubService.java | 54 +++++++++ .../service/iot_hub/IotHubRestClient.java | 15 ++- .../server/service/iot_hub/IotHubService.java | 12 ++ .../iot_hub/DefaultIotHubServiceTest.java | 89 ++++++++++++++ .../dao/iot_hub/IotHubInstalledItemDao.java | 4 + .../iot_hub/IotHubInstalledItemService.java | 4 + .../IotHubInstalledItemServiceImpl.java | 7 ++ .../IotHubInstalledItemRepository.java | 31 +++++ .../iot_hub/JpaIotHubInstalledItemDao.java | 17 +++ .../IotHubInstalledItemServiceTest.java | 110 ++++++++++++++++++ .../src/app/core/http/iot-hub-api.service.ts | 9 +- ...iot-hub-installed-items-table.component.ts | 11 +- 13 files changed, 365 insertions(+), 5 deletions(-) create mode 100644 dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index b6d01d3342..56ed32b14e 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -140,9 +140,14 @@ public class IotHubController extends BaseController { @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder, @RequestParam(required = false) List itemTypes, - @RequestParam(required = false) UUID itemId) throws ThingsboardException { + @RequestParam(required = false) UUID itemId, + @RequestParam(required = false, defaultValue = "false") boolean updatesFirst) throws ThingsboardException { checkAllPermissions(); PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + if (updatesFirst) { + // The items installed in a version other than the one IoT Hub publishes now come first, sorted as asked + return iotHubService.findInstalledItemsUpdatesFirst(getTenantId(), itemTypes, itemId, pageLink); + } return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index ddbe8ec5d7..60f2391544 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -5,6 +5,9 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.google.common.collect.Lists; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -82,6 +85,7 @@ import org.thingsboard.server.service.security.permission.AccessControlService; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -138,6 +142,15 @@ public class DefaultIotHubService implements IotHubService { private final ProjectInfo projectInfo; private final DevicePackageEntities devicePackageEntities; + // How many item ids one request for their published versions takes + private static final int PUBLISHED_VERSIONS_CHUNK_SIZE = 100; + // The installed items list asks for these on every page while it shows the updates first, so IoT Hub is asked once + // a minute per tenant at most; an answer it failed to give is kept too, so a slow IoT Hub doesn't slow down every page + private final Cache> publishedVersionIdsCache = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMinutes(1)) + .maximumSize(10_000) + .build(); + // Field names of the marketplace version JSON payload. Both the install path and the // install-plan resolver parse the same shape, so the contract lives here in one place. private static final String FIELD_ID = "id"; @@ -803,6 +816,47 @@ public class DefaultIotHubService implements IotHubService { return keys; } + @Override + public PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { + Map publishedVersionIds = publishedVersionIdsCache.get(tenantId, this::findPublishedVersionIds); + return iotHubInstalledItemService.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); + } + + /** + * IoT Hub's published version id by item id, of the items the tenant has installed. Asked in chunks, as IoT Hub may limit + * the ids of one request. Empty when IoT Hub doesn't answer: the list then shows in the page's sort only. + */ + private Map findPublishedVersionIds(TenantId tenantId) { + List itemIds = iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId); + Map publishedVersionIds = new HashMap<>(); + try { + for (List chunk : Lists.partition(itemIds, PUBLISHED_VERSIONS_CHUNK_SIZE)) { + JsonNode published = iotHubRestClient.getPublishedVersions(chunk); + if (published != null && published.isArray()) { + published.forEach(info -> putPublishedVersionId(tenantId, info, publishedVersionIds)); + } + } + } catch (RuntimeException e) { + log.warn("[{}] Failed to get the published versions of the installed items from IoT Hub", tenantId, e); + return Map.of(); + } + return publishedVersionIds; + } + + /** An entry of an item with no published version, or one that is not a pair of ids, adds nothing. */ + private static void putPublishedVersionId(TenantId tenantId, JsonNode info, Map publishedVersionIds) { + String itemId = info.path("itemId").asText(null); + String versionId = info.path("publishedVersionId").asText(null); + if (itemId == null || versionId == null) { + return; + } + try { + publishedVersionIds.put(UUID.fromString(itemId), UUID.fromString(versionId)); + } catch (IllegalArgumentException e) { + log.debug("[{}] Skipping a published version from IoT Hub that is not a pair of ids: {}", tenantId, info); + } + } + /** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */ @Override public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) { diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java index a12470271f..11950d86c4 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; @@ -18,6 +19,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; +import java.util.Collection; +import java.util.UUID; @Component @TbCoreComponent @@ -69,6 +72,16 @@ public class IotHubRestClient { } } + /** + * IoT Hub's published version of each item: {@code itemId}, {@code publishedVersionId} and {@code publishedVersion}, + * the last two null for an item with no published version. + */ + public JsonNode getPublishedVersions(Collection itemIds) { + String url = baseUrl + "/api/versions/publishedVersions"; + log.debug("Fetching IoT Hub published versions of {} items: {}", itemIds.size(), url); + return restTemplate.postForObject(url, itemIds, JsonNode.class); + } + public byte[] getVersionFileData(String versionId) { String url = baseUrl + "/api/versions/" + versionId + "/fileData"; log.debug("Fetching IoT Hub version file data: {}", url); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index e1d0cd666b..dfb9e068c4 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -9,8 +9,14 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.service.security.model.SecurityUser; +import java.util.List; +import java.util.UUID; + public interface IotHubService { InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request); @@ -23,6 +29,12 @@ public interface IotHubService { InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); + /** + * The tenant's installed items, those with an update in IoT Hub first: installed in a version other than the item's + * published one. Without an answer from IoT Hub, in the page's sort only. + */ + PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + InstallPlan resolveInstallPlan(SecurityUser user, String versionId); InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index a81368450c..21b2f42c7d 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; @@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.device.DeviceProfileService; @@ -49,6 +51,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -744,4 +747,90 @@ class DefaultIotHubServiceTest { return item; } + @Test + void findInstalledItemsUpdatesFirst_passesThePublishedVersionOfEachInstalledItem() { + UUID tracker = UUID.randomUUID(); + UUID trackerPublished = UUID.randomUUID(); + UUID unpublished = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker, unpublished)); + ArrayNode published = JacksonUtil.newArrayNode(); + published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()).put("publishedVersion", "1.0.1"); + // An item IoT Hub publishes no version of: nothing to update to + published.addObject().put("itemId", unpublished.toString()).putNull("publishedVersionId").putNull("publishedVersion"); + when(iotHubRestClient.getPublishedVersions(List.of(tracker, unpublished))).thenReturn(published); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, List.of("DEVICE"), null, pageLink); + + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, List.of("DEVICE"), null, Map.of(tracker, trackerPublished), pageLink); + } + + @Test + void findInstalledItemsUpdatesFirst_withoutAnAnswerFromIotHub_listsInThePageSort() { + UUID tracker = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); + when(iotHubRestClient.getPublishedVersions(any())).thenThrow(new RuntimeException("IoT Hub is down")); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); + + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); + } + + @Test + void findInstalledItemsUpdatesFirst_nothingInstalled_doesNotAskIotHub() { + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of()); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); + + verify(iotHubRestClient, never()).getPublishedVersions(any()); + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); + } + + @Test + void findInstalledItemsUpdatesFirst_asksIotHubInChunksOf100() { + List itemIds = Stream.generate(UUID::randomUUID).limit(150).toList(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(itemIds); + when(iotHubRestClient.getPublishedVersions(any())).thenReturn(JacksonUtil.newArrayNode()); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); + + verify(iotHubRestClient).getPublishedVersions(itemIds.subList(0, 100)); + verify(iotHubRestClient).getPublishedVersions(itemIds.subList(100, 150)); + } + + @Test + void findInstalledItemsUpdatesFirst_nextPages_doNotAskIotHubAgain() { + UUID tracker = UUID.randomUUID(); + UUID trackerPublished = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); + ArrayNode published = JacksonUtil.newArrayNode(); + published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); + when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); + PageLink second = new PageLink(10, 1); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); + service.findInstalledItemsUpdatesFirst(tenantId, null, null, second); + + verify(iotHubRestClient).getPublishedVersions(any()); + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), second); + } + + @Test + void findInstalledItemsUpdatesFirst_skipsAnEntryThatIsNotAPairOfIds() { + UUID tracker = UUID.randomUUID(); + UUID trackerPublished = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); + ArrayNode published = JacksonUtil.newArrayNode(); + published.addObject().put("itemId", "not-an-id").put("publishedVersionId", UUID.randomUUID().toString()); + published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); + when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); + + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), pageLink); + } + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index b99cf18981..216f689b80 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first + PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 072506dfca..272d6ea6f1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first + PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index d69060cd94..86678f9acf 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -49,6 +49,13 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink); } + @Override + public PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); + return iotHubInstalledItemDao.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 693166b7e0..94f56a043f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -45,6 +45,37 @@ interface IotHubInstalledItemRepository extends JpaRepository findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); + /** + * As {@link #findByTenantId}, with the items that have an update first: an item of {@code publishedItemIds} whose + * installed version is not among {@code publishedVersionIds}. The page's sort applies within each of the two groups. + */ + @Query(value = """ + SELECT item FROM IotHubInstalledItemEntity item + WHERE item.tenantId = :tenantId + AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) + AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:textSearch IS NULL + OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) + ORDER BY CASE WHEN item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds THEN 0 ELSE 1 END + """, + countQuery = """ + SELECT COUNT(item) FROM IotHubInstalledItemEntity item + WHERE item.tenantId = :tenantId + AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) + AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:textSearch IS NULL + OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) + """) + Page findByTenantIdUpdatesFirst(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); + @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index d07d8f5dd4..40fbea4a7d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -57,6 +57,23 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + if (publishedVersionIds == null || publishedVersionIds.isEmpty()) { + return findByTenantId(tenantId, itemTypes, itemId, pageLink); + } + return DaoUtil.toPageData(repository.findByTenantIdUpdatesFirst( + tenantId.getId(), + itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, + itemId, + StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), + publishedVersionIds.keySet(), + publishedVersionIds.values(), + toPageRequest(pageLink)) + ); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return repository.findInstalledItemIdsByTenantId(tenantId.getId()); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java new file mode 100644 index 0000000000..b024b5a29d --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -0,0 +1,110 @@ +// 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.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +public class IotHubInstalledItemServiceTest extends AbstractServiceTest { + + @Autowired + IotHubInstalledItemService installedItemService; + + private final UUID trackerItemId = UUID.randomUUID(); + private final UUID sensorItemId = UUID.randomUUID(); + private final UUID unpublishedItemId = UUID.randomUUID(); + private final UUID trackerPublished = UUID.randomUUID(); + private final UUID sensorPublished = UUID.randomUUID(); + + private void install(String name, UUID itemId, UUID versionId) { + IotHubInstalledItem item = new IotHubInstalledItem(); + item.setTenantId(tenantId); + item.setItemId(itemId); + item.setItemVersionId(versionId); + item.setItemName(name); + item.setItemType("WIDGET"); + item.setVersion("1.0.0"); + item.setDescriptor(new WidgetInstalledItemDescriptor()); + installedItemService.save(tenantId, item); + } + + /** a and c are up to date, b and d have an update (d is a second install of a's item in an older version), e has no published version. */ + private void installFive() { + install("a", sensorItemId, sensorPublished); + install("b", trackerItemId, UUID.randomUUID()); + install("c", sensorItemId, sensorPublished); + install("d", sensorItemId, UUID.randomUUID()); + install("e", unpublishedItemId, UUID.randomUUID()); + } + + private Map published() { + return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished); + } + + private static List names(PageData page) { + return page.getData().stream().map(IotHubInstalledItem::getItemName).toList(); + } + + @Test + public void updatesFirst_itemsWithAnUpdateComeFirst_eachGroupInThePageSort() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), byName); + + assertThat(names(page)).containsExactly("b", "d", "a", "c", "e"); + assertThat(page.getTotalElements()).isEqualTo(5); + } + + @Test + public void updatesFirst_pagesKeepTheOrderAndTheTotal() { + installFive(); + SortOrder byNameDesc = new SortOrder("itemName", SortOrder.Direction.DESC); + + PageData first = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), + new PageLink(2, 0, null, byNameDesc)); + PageData second = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), + new PageLink(2, 1, null, byNameDesc)); + + assertThat(names(first)).containsExactly("d", "b"); + assertThat(names(second)).containsExactly("e", "c"); + assertThat(first.getTotalElements()).isEqualTo(5); + assertThat(first.hasNext()).isTrue(); + } + + @Test + public void updatesFirst_keepsTheFilters() { + 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)); + + PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, List.of("WIDGET"), null, published(), search); + + assertThat(names(page)).containsExactly("b"); + assertThat(page.getTotalElements()).isEqualTo(1); + } + + @Test + public void updatesFirst_withoutPublishedVersions_isThePageSortOnly() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), byName); + + assertThat(names(page)).containsExactly("a", "b", "c", "d", "e"); + } + +} diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index fa040e8632..b7f0f78287 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -238,8 +238,12 @@ export class IotHubApiService { ); } + /** + * updatesFirst: the items installed in a version other than the one IoT Hub publishes now come first, then the rest, + * each in the page's sort. + */ public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], - itemId?: string, config?: IotHubRequestConfig): Observable> { + itemId?: string, config?: IotHubRequestConfig, updatesFirst = false): Observable> { let query = pageLink.toQuery(); if (itemTypes) { const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; @@ -248,6 +252,9 @@ export class IotHubApiService { if (itemId) { query += `&itemId=${itemId}`; } + if (updatesFirst) { + query += '&updatesFirst=true'; + } return this.http.get>( `/api/iot-hub/installedItems${query}`, { params: this.buildParams(config) } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3c196cdb66..9202f5937f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -249,7 +249,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; - void this.checkConverterUpdates(); + // From the first page: the items with an update come first now, wherever their install date put them + this.pageIndex = 0; + if (this.paginator) { + this.paginator.pageIndex = 0; + } + this.loadData(); }, error: () => { this.isCheckingUpdates = false; @@ -341,7 +346,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}).subscribe({ + // Once the updates are checked, the items with one come first; the page of one item's versions keeps its sort + const updatesFirst = this.updatesChecked && !this.itemVersion; + this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}, updatesFirst).subscribe({ next: (data) => { this.dataSource = data.data; this.totalElements = data.totalElements; From a1e4e33b2bfcc4a7ed9877e8fe1be6057f1063b0 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 10:49:56 +0200 Subject: [PATCH 2/7] IoT Hub installed items: after Check for updates only the items with an update, no server cache (PROD-9326) --- .../server/controller/IotHubController.java | 26 +++-- .../service/iot_hub/DefaultIotHubService.java | 54 ---------- .../service/iot_hub/IotHubRestClient.java | 15 +-- .../server/service/iot_hub/IotHubService.java | 12 --- .../iot_hub/DefaultIotHubServiceTest.java | 89 --------------- .../dao/iot_hub/IotHubInstalledItemDao.java | 6 +- .../iot_hub/IotHubInstalledItemService.java | 6 +- .../IotHubInstalledItemServiceImpl.java | 19 +++- .../IotHubInstalledItemRepository.java | 30 ++---- .../iot_hub/JpaIotHubInstalledItemDao.java | 10 +- .../IotHubInstalledItemServiceTest.java | 50 ++++----- .../src/app/core/http/iot-hub-api.service.ts | 45 +++++--- ...t-hub-installed-items-table.component.html | 12 ++- ...iot-hub-installed-items-table.component.ts | 102 +++++++++++++++--- .../iot-hub-installed-items.component.html | 45 ++++++-- .../iot-hub-installed-items.component.scss | 29 +++++ .../iot-hub-installed-items.component.ts | 23 +++- .../assets/locale/locale.constant-en_US.json | 8 ++ 18 files changed, 309 insertions(+), 272 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 56ed32b14e..332a95242b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -140,17 +140,31 @@ public class IotHubController extends BaseController { @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder, @RequestParam(required = false) List itemTypes, - @RequestParam(required = false) UUID itemId, - @RequestParam(required = false, defaultValue = "false") boolean updatesFirst) throws ThingsboardException { + @RequestParam(required = false) UUID itemId) throws ThingsboardException { checkAllPermissions(); PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); - if (updatesFirst) { - // The items installed in a version other than the one IoT Hub publishes now come first, sorted as asked - return iotHubService.findInstalledItemsUpdatesFirst(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 getInstalledItemsWithUpdates(@RequestParam int pageSize, + @RequestParam int page, + @RequestParam(required = false) String textSearch, + @RequestParam(required = false) String sortProperty, + @RequestParam(required = false) String sortOrder, + @RequestParam(required = false) List itemTypes, + @RequestBody Map publishedVersionIds) throws ThingsboardException { + checkAllPermissions(); + PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/count") @ResponseBody diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 60f2391544..ddbe8ec5d7 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -5,9 +5,6 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.google.common.collect.Lists; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -85,7 +82,6 @@ import org.thingsboard.server.service.security.permission.AccessControlService; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -142,15 +138,6 @@ public class DefaultIotHubService implements IotHubService { private final ProjectInfo projectInfo; private final DevicePackageEntities devicePackageEntities; - // How many item ids one request for their published versions takes - private static final int PUBLISHED_VERSIONS_CHUNK_SIZE = 100; - // The installed items list asks for these on every page while it shows the updates first, so IoT Hub is asked once - // a minute per tenant at most; an answer it failed to give is kept too, so a slow IoT Hub doesn't slow down every page - private final Cache> publishedVersionIdsCache = Caffeine.newBuilder() - .expireAfterWrite(Duration.ofMinutes(1)) - .maximumSize(10_000) - .build(); - // Field names of the marketplace version JSON payload. Both the install path and the // install-plan resolver parse the same shape, so the contract lives here in one place. private static final String FIELD_ID = "id"; @@ -816,47 +803,6 @@ public class DefaultIotHubService implements IotHubService { return keys; } - @Override - public PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { - Map publishedVersionIds = publishedVersionIdsCache.get(tenantId, this::findPublishedVersionIds); - return iotHubInstalledItemService.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); - } - - /** - * IoT Hub's published version id by item id, of the items the tenant has installed. Asked in chunks, as IoT Hub may limit - * the ids of one request. Empty when IoT Hub doesn't answer: the list then shows in the page's sort only. - */ - private Map findPublishedVersionIds(TenantId tenantId) { - List itemIds = iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId); - Map publishedVersionIds = new HashMap<>(); - try { - for (List chunk : Lists.partition(itemIds, PUBLISHED_VERSIONS_CHUNK_SIZE)) { - JsonNode published = iotHubRestClient.getPublishedVersions(chunk); - if (published != null && published.isArray()) { - published.forEach(info -> putPublishedVersionId(tenantId, info, publishedVersionIds)); - } - } - } catch (RuntimeException e) { - log.warn("[{}] Failed to get the published versions of the installed items from IoT Hub", tenantId, e); - return Map.of(); - } - return publishedVersionIds; - } - - /** An entry of an item with no published version, or one that is not a pair of ids, adds nothing. */ - private static void putPublishedVersionId(TenantId tenantId, JsonNode info, Map publishedVersionIds) { - String itemId = info.path("itemId").asText(null); - String versionId = info.path("publishedVersionId").asText(null); - if (itemId == null || versionId == null) { - return; - } - try { - publishedVersionIds.put(UUID.fromString(itemId), UUID.fromString(versionId)); - } catch (IllegalArgumentException e) { - log.debug("[{}] Skipping a published version from IoT Hub that is not a pair of ids: {}", tenantId, info); - } - } - /** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */ @Override public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) { diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java index 11950d86c4..a12470271f 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java @@ -1,6 +1,5 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; @@ -19,8 +18,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; -import java.util.Collection; -import java.util.UUID; @Component @TbCoreComponent @@ -72,16 +69,6 @@ public class IotHubRestClient { } } - /** - * IoT Hub's published version of each item: {@code itemId}, {@code publishedVersionId} and {@code publishedVersion}, - * the last two null for an item with no published version. - */ - public JsonNode getPublishedVersions(Collection itemIds) { - String url = baseUrl + "/api/versions/publishedVersions"; - log.debug("Fetching IoT Hub published versions of {} items: {}", itemIds.size(), url); - return restTemplate.postForObject(url, itemIds, JsonNode.class); - } - public byte[] getVersionFileData(String versionId) { String url = baseUrl + "/api/versions/" + versionId + "/fileData"; log.debug("Fetching IoT Hub version file data: {}", url); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index dfb9e068c4..e1d0cd666b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -9,14 +9,8 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; -import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; -import org.thingsboard.server.common.data.page.PageData; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.service.security.model.SecurityUser; -import java.util.List; -import java.util.UUID; - public interface IotHubService { InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request); @@ -29,12 +23,6 @@ public interface IotHubService { InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); - /** - * The tenant's installed items, those with an update in IoT Hub first: installed in a version other than the item's - * published one. Without an answer from IoT Hub, in the page's sort only. - */ - PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); - InstallPlan resolveInstallPlan(SecurityUser user, String versionId); InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 21b2f42c7d..a81368450c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -4,7 +4,6 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; @@ -33,7 +32,6 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.page.PageData; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.device.DeviceProfileService; @@ -51,7 +49,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; -import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -747,90 +744,4 @@ class DefaultIotHubServiceTest { return item; } - @Test - void findInstalledItemsUpdatesFirst_passesThePublishedVersionOfEachInstalledItem() { - UUID tracker = UUID.randomUUID(); - UUID trackerPublished = UUID.randomUUID(); - UUID unpublished = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker, unpublished)); - ArrayNode published = JacksonUtil.newArrayNode(); - published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()).put("publishedVersion", "1.0.1"); - // An item IoT Hub publishes no version of: nothing to update to - published.addObject().put("itemId", unpublished.toString()).putNull("publishedVersionId").putNull("publishedVersion"); - when(iotHubRestClient.getPublishedVersions(List.of(tracker, unpublished))).thenReturn(published); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, List.of("DEVICE"), null, pageLink); - - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, List.of("DEVICE"), null, Map.of(tracker, trackerPublished), pageLink); - } - - @Test - void findInstalledItemsUpdatesFirst_withoutAnAnswerFromIotHub_listsInThePageSort() { - UUID tracker = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); - when(iotHubRestClient.getPublishedVersions(any())).thenThrow(new RuntimeException("IoT Hub is down")); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); - - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); - } - - @Test - void findInstalledItemsUpdatesFirst_nothingInstalled_doesNotAskIotHub() { - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of()); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); - - verify(iotHubRestClient, never()).getPublishedVersions(any()); - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); - } - - @Test - void findInstalledItemsUpdatesFirst_asksIotHubInChunksOf100() { - List itemIds = Stream.generate(UUID::randomUUID).limit(150).toList(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(itemIds); - when(iotHubRestClient.getPublishedVersions(any())).thenReturn(JacksonUtil.newArrayNode()); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); - - verify(iotHubRestClient).getPublishedVersions(itemIds.subList(0, 100)); - verify(iotHubRestClient).getPublishedVersions(itemIds.subList(100, 150)); - } - - @Test - void findInstalledItemsUpdatesFirst_nextPages_doNotAskIotHubAgain() { - UUID tracker = UUID.randomUUID(); - UUID trackerPublished = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); - ArrayNode published = JacksonUtil.newArrayNode(); - published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); - when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); - PageLink second = new PageLink(10, 1); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); - service.findInstalledItemsUpdatesFirst(tenantId, null, null, second); - - verify(iotHubRestClient).getPublishedVersions(any()); - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), second); - } - - @Test - void findInstalledItemsUpdatesFirst_skipsAnEntryThatIsNotAPairOfIds() { - UUID tracker = UUID.randomUUID(); - UUID trackerPublished = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); - ArrayNode published = JacksonUtil.newArrayNode(); - published.addObject().put("itemId", "not-an-id").put("publishedVersionId", UUID.randomUUID().toString()); - published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); - when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); - - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), pageLink); - } - } diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index 216f689b80..7373a8fb81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,9 +25,9 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); - // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first - PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id, not empty; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); List findInstalledItemIdsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 272d6ea6f1..17f3361738 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,9 +25,9 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); - // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first - PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); List findInstalledItemIdsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index 86678f9acf..89f7d636b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -14,6 +14,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -50,10 +51,22 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { } @Override - public PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink) { + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); - return iotHubInstalledItemDao.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); + // An item IoT Hub publishes no version of has nothing to update to + Map published = new HashMap<>(); + if (publishedVersionIds != null) { + publishedVersionIds.forEach((itemId, versionId) -> { + if (itemId != null && versionId != null) { + published.put(itemId, versionId); + } + }); + } + if (published.isEmpty()) { + return PageData.emptyPageData(); + } + return iotHubInstalledItemDao.findByTenantIdWithUpdates(tenantId, itemTypes, published, pageLink); } @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 94f56a043f..c86f7edadf 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -46,35 +46,25 @@ interface IotHubInstalledItemRepository extends JpaRepository findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); /** - * As {@link #findByTenantId}, with the items that have an update first: an item of {@code publishedItemIds} whose - * installed version is not among {@code publishedVersionIds}. The page's sort applies within each of the two groups. + * As {@link #findByTenantId}, only the items with an update: an item of {@code publishedItemIds} whose installed version + * is not among {@code publishedVersionIds}. Version ids are unique, so this is "not the published version of its item". */ - @Query(value = """ + @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId + AND item.itemId IN :publishedItemIds + AND item.itemVersionId NOT IN :publishedVersionIds AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) - AND (:itemId IS NULL OR item.itemId = :itemId) - AND (:textSearch IS NULL - OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) - ORDER BY CASE WHEN item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds THEN 0 ELSE 1 END - """, - countQuery = """ - SELECT COUNT(item) FROM IotHubInstalledItemEntity item - WHERE item.tenantId = :tenantId - AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) - AND (:itemId IS NULL OR item.itemId = :itemId) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantIdUpdatesFirst(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, - @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, - @Param("publishedItemIds") Collection publishedItemIds, - @Param("publishedVersionIds") Collection publishedVersionIds, - Pageable pageable); + Page findByTenantIdWithUpdates(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("textSearch") String textSearch, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index 40fbea4a7d..1d05081d99 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -58,15 +58,11 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink) { - if (publishedVersionIds == null || publishedVersionIds.isEmpty()) { - return findByTenantId(tenantId, itemTypes, itemId, pageLink); - } - return DaoUtil.toPageData(repository.findByTenantIdUpdatesFirst( + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + return DaoUtil.toPageData(repository.findByTenantIdWithUpdates( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, - itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), publishedVersionIds.keySet(), publishedVersionIds.values(), diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java index b024b5a29d..560b3cf0d0 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -11,6 +11,7 @@ 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; @@ -59,52 +60,53 @@ public class IotHubInstalledItemServiceTest extends AbstractServiceTest { } @Test - public void updatesFirst_itemsWithAnUpdateComeFirst_eachGroupInThePageSort() { + public void withUpdates_onlyTheItemsWithAnUpdate_inThePageSort() { installFive(); - PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.DESC)); - PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), byName); + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), byName); - assertThat(names(page)).containsExactly("b", "d", "a", "c", "e"); - assertThat(page.getTotalElements()).isEqualTo(5); + assertThat(names(page)).containsExactly("d", "b"); + assertThat(page.getTotalElements()).isEqualTo(2); } @Test - public void updatesFirst_pagesKeepTheOrderAndTheTotal() { + public void withUpdates_pagesAndTotal() { installFive(); - SortOrder byNameDesc = new SortOrder("itemName", SortOrder.Direction.DESC); + SortOrder byName = new SortOrder("itemName", SortOrder.Direction.ASC); - PageData first = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), - new PageLink(2, 0, null, byNameDesc)); - PageData second = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), - new PageLink(2, 1, null, byNameDesc)); + PageData first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 0, null, byName)); + PageData second = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 1, null, byName)); - assertThat(names(first)).containsExactly("d", "b"); - assertThat(names(second)).containsExactly("e", "c"); - assertThat(first.getTotalElements()).isEqualTo(5); + 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 updatesFirst_keepsTheFilters() { + 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)); - PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, List.of("WIDGET"), null, published(), search); - - assertThat(names(page)).containsExactly("b"); - assertThat(page.getTotalElements()).isEqualTo(1); + 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 updatesFirst_withoutPublishedVersions_isThePageSortOnly() { + public void withUpdates_withoutPublishedVersions_isEmpty() { installFive(); - PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); - - PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), byName); + Map unpublished = new HashMap<>(); + unpublished.put(unpublishedItemId, null); - assertThat(names(page)).containsExactly("a", "b", "c", "d", "e"); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, Map.of(), new PageLink(10)).getData()).isEmpty(); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, unpublished, new PageLink(10)).getData()).isEmpty(); } } diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index b7f0f78287..b9674e232c 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -4,7 +4,8 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Store } from '@ngrx/store'; -import { Observable } from 'rxjs'; +import { forkJoin, Observable, of } from 'rxjs'; +import { map } from 'rxjs/operators'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { @@ -50,6 +51,8 @@ export function iotHubResourceUrl(baseUrl: string, path: string): string { return `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`; } +const PUBLISHED_VERSIONS_CHUNK_SIZE = 100; + export interface IotHubRequestConfig { ignoreLoading?: boolean; ignoreErrors?: boolean; @@ -238,12 +241,8 @@ export class IotHubApiService { ); } - /** - * updatesFirst: the items installed in a version other than the one IoT Hub publishes now come first, then the rest, - * each in the page's sort. - */ public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], - itemId?: string, config?: IotHubRequestConfig, updatesFirst = false): Observable> { + itemId?: string, config?: IotHubRequestConfig): Observable> { let query = pageLink.toQuery(); if (itemTypes) { const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; @@ -252,15 +251,29 @@ export class IotHubApiService { if (itemId) { query += `&itemId=${itemId}`; } - if (updatesFirst) { - query += '&updatesFirst=true'; - } return this.http.get>( `/api/iot-hub/installedItems${query}`, { params: this.buildParams(config) } ); } + /** + * The installed items with an update: publishedVersionIds is IoT Hub's published version id by item id, as Check for + * updates got it. The server keeps the items installed in another version, with the page's sort, search and types. + */ + public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, + config?: IotHubRequestConfig): Observable> { + let query = pageLink.toQuery(); + if (itemTypes?.length) { + query += itemTypes.map(t => `&itemTypes=${t}`).join(''); + } + return this.http.post>( + `/api/iot-hub/installedItems/withUpdates${query}`, + publishedVersionIds, + { params: this.buildParams(config) } + ); + } + public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable { let url = '/api/iot-hub/installedItems/count'; if (itemType) { @@ -300,12 +313,20 @@ export class IotHubApiService { ); } + /** Asked in requests of 100 item ids at most, so a tenant with many items doesn't send IoT Hub one huge request. */ public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { - return this.http.post( + if (!itemIds.length) { + return of([]); + } + const chunks: string[][] = []; + for (let i = 0; i < itemIds.length; i += PUBLISHED_VERSIONS_CHUNK_SIZE) { + chunks.push(itemIds.slice(i, i + PUBLISHED_VERSIONS_CHUNK_SIZE)); + } + return forkJoin(chunks.map(chunk => this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, - itemIds, + chunk, { params: this.buildParams(config) } - ); + ))).pipe(map(results => results.flat())); } public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 7f1dbac04e..3af83f064f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -125,7 +125,17 @@ - @if (!isLoading && dataSource.length === 0) { + @if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) { + +
+
+

{{ 'iot-hub.all-items-up-to-date' | translate }}

+

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

+ +
+ } @else if (!isLoading && dataSource.length === 0) {

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

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 9202f5937f..f1bf82d05e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -44,7 +44,7 @@ import { loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, forkJoin } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -82,6 +82,15 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; + // IoT Hub didn't answer Check for updates: the page says so quietly, the list works without it + updatesCheckFailed = false; + // After Check for updates the list shows only the items with an update, until the user asks for all of them + onlyUpdates = false; + // How many installed items have an update, and how many there are, of all types and with no search; null while not known + updatesCount: number | null = null; + installedCount = 0; + // A later load (another page, mode, sort or search) wins over an earlier one that answers last + private loadRun = 0; private widgetResize$: ResizeObserver; @@ -161,7 +170,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, deleteItem(item: IotHubInstalledItem): void { this.iotHubActions.deleteItem(item).subscribe(deleted => { if (deleted) { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -191,7 +200,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { if (result === 'updated' || result === 'deleted') { - this.loadData(); + this.reloadAfterChange(); } }); }); @@ -241,31 +250,75 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true })) + // An IoT Hub that doesn't answer is not a page error: the page says so next to the button, the list works without it + switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; - // From the first page: the items with an update come first now, wherever their install date put them - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } - this.loadData(); + this.showOnlyUpdates(true); + this.loadUpdatesCount(); }, error: () => { this.isCheckingUpdates = false; + this.updatesCheckFailed = true; + } + }); + } + + /** Only the items with an update, or all of them; from the first page, as the list changes. */ + showOnlyUpdates(onlyUpdates: boolean): void { + this.onlyUpdates = onlyUpdates; + this.pageIndex = 0; + if (this.paginator) { + this.paginator.pageIndex = 0; + } + this.loadData(); + } + + /** IoT Hub's published version id by item id, of the items it publishes a version of. */ + private publishedVersionIds(): Record { + const ids: Record = {}; + this.publishedVersionMap.forEach((info, itemId) => { + if (info.publishedVersionId) { + ids[itemId] = info.publishedVersionId; } }); + return ids; + } + + /** After an item is updated or removed: the list and, once the updates are checked, the counts in the header. */ + private reloadAfterChange(): void { + this.loadData(); + if (this.updatesChecked && !this.itemVersion) { + this.loadUpdatesCount(); + } + } + + private loadUpdatesCount(): void { + this.updatesCount = null; + forkJoin({ + withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), + installed: this.iotHubApiService.getInstalledItemsCount(undefined, { ignoreLoading: true }) + }).subscribe({ + next: ({ withUpdates, installed }) => { + this.updatesCount = withUpdates.totalElements; + this.installedCount = installed; + this.cd.markForCheck(); + }, + // The header then shows only the buttons + error: () => this.cd.markForCheck() + }); } updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { if (result === 'updated') { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -346,18 +399,37 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - // Once the updates are checked, the items with one come first; the page of one item's versions keeps its sort - const updatesFirst = this.updatesChecked && !this.itemVersion; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}, updatesFirst).subscribe({ + // The page of one item's versions has its own published version and lists all of them + const items$ = this.onlyUpdates && !this.itemVersion + ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true}) + : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); + const run = ++this.loadRun; + items$.subscribe({ next: (data) => { + if (run !== this.loadRun) { + return; + } + // The last page emptied (its last item updated or removed): go to the page that is last now + if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { + this.pageIndex = Math.ceil(data.totalElements / this.pageSize) - 1; + if (this.paginator) { + this.paginator.pageIndex = this.pageIndex; + } + this.loadData(); + return; + } this.dataSource = data.data; this.totalElements = data.totalElements; this.isLoading = false; - if (this.updatesChecked && !this.itemVersion) { + // In the list of items with an update their version update shows, not the converter's + if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } }, error: () => { + if (run !== this.loadRun) { + return; + } this.dataSource = []; this.totalElements = 0; this.isLoading = false; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7591b1dc5a..f95bef69d7 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -1,7 +1,8 @@
@@ -15,14 +16,42 @@

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

@if (!updatesChecked) { - + +
+ } @else { + +
+ @if (updatesCount !== null) { + + @if (updatesCount > 0) { + arrow_circle_up + {{ (updatesCount === 1 ? 'iot-hub.item-with-update' : 'iot-hub.items-with-update') | translate:{ count: updatesCount, total: installedCount } }} + } @else { + check_circle + {{ 'iot-hub.all-items-up-to-date' | translate }} + } + + } + @if (onlyUpdates) { + + } @else if ((updatesCount ?? 0) > 0) { + + } +
}
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss index 1ade0222c5..eab61c2c2a 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss @@ -29,6 +29,35 @@ margin-bottom: 32px; } +// After Check for updates: "N items have an update" and Show all items / Show only updates +.tb-installed-updates-note { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 14px; + line-height: 20px; + letter-spacing: 0.2px; + color: rgba(0, 0, 0, 0.76); + + mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } + + .tb-installed-updates-available { + color: #f44336; + } + + .tb-installed-updates-none { + color: #198038; + } + + .tb-installed-updates-failed { + color: #f66716; + } +} + .tb-installed-title { font-size: 36px; font-weight: 500; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts index 1af2d5ed2c..47aa3e5080 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; @@ -107,4 +108,24 @@ export class TbIotHubInstalledItemsComponent implements OnInit, OnDestroy { get updatesChecked(): boolean { return this.tableComponent?.updatesChecked || false; } + + get updatesCheckFailed(): boolean { + return this.tableComponent?.updatesCheckFailed || false; + } + + get onlyUpdates(): boolean { + return this.tableComponent?.onlyUpdates || false; + } + + get updatesCount(): number | null { + return this.tableComponent?.updatesCount ?? null; + } + + get installedCount(): number { + return this.tableComponent?.installedCount || 0; + } + + showOnlyUpdates(onlyUpdates: boolean): void { + this.tableComponent?.showOnlyUpdates(onlyUpdates); + } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 88b545b9d2..c2c51b4632 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6494,6 +6494,14 @@ "install-partial-desc": "'{{name}}' was installed, but some required items were missing.", "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", + "check-for-updates-failed": "Couldn't check for updates", + "check-for-updates-try-again": "Try again", + "item-with-update": "1 of {{total}} items has an update", + "items-with-update": "{{count}} of {{total}} items have an update", + "all-items-up-to-date": "All items are up to date", + "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", + "show-all-items": "Show all items", + "show-only-updates": "Show only updates", "updates": "Updates", "up-to-date": "Up to date", "new-converter-available": "New converter available", From b5d1210cae86d2b9f7d0946e8915657bccf512f6 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 12:19:58 +0200 Subject: [PATCH 3/7] IoT Hub installed items: one query for both lists, a failed load is not 'up to date', one ICU plural (PROD-9326 review) --- .../IotHubInstalledItemRepository.java | 33 +++++++------------ .../iot_hub/JpaIotHubInstalledItemDao.java | 26 +++++++++------ .../IotHubInstalledItemServiceTest.java | 9 +++++ ...t-hub-installed-items-table.component.html | 11 ++++++- ...iot-hub-installed-items-table.component.ts | 4 +++ .../iot-hub-installed-items.component.html | 2 +- .../assets/locale/locale.constant-en_US.json | 4 +-- 7 files changed, 54 insertions(+), 35 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index c86f7edadf..c09f8c12f5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -33,38 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId, @Param("itemIds") Collection itemIds); - @Query(""" - SELECT item FROM IotHubInstalledItemEntity item - WHERE item.tenantId = :tenantId - AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) - AND (:itemId IS NULL OR item.itemId = :itemId) - AND (:textSearch IS NULL - OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) - """) - Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); - /** - * As {@link #findByTenantId}, only the items with an update: an item of {@code publishedItemIds} whose installed version - * is not among {@code publishedVersionIds}. Version ids are unique, so this is "not the published version of its item". + * The tenant's installed items, by type, item and text. With {@code updatesOnly}, only the items with an update: an item + * of {@code publishedItemIds} whose installed version is not among {@code publishedVersionIds} (version ids are unique, + * so: not the published version of its item). A flag, as Hibernate can't type {@code :uuids IS NULL}. */ @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId - AND item.itemId IN :publishedItemIds - AND item.itemVersionId NOT IN :publishedVersionIds AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) + AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:updatesOnly = false + OR (item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds)) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantIdWithUpdates(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, - @Param("textSearch") String textSearch, - @Param("publishedItemIds") Collection publishedItemIds, - @Param("publishedVersionIds") Collection publishedVersionIds, - Pageable pageable); + Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("updatesOnly") boolean updatesOnly, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index 1d05081d99..4c91e5137b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -48,24 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { - return DaoUtil.toPageData(repository.findByTenantId( - tenantId.getId(), - itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, - itemId, - StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), - toPageRequest(pageLink)) - ); + return find(tenantId, itemTypes, itemId, null, pageLink); } @Override public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, Map publishedVersionIds, PageLink pageLink) { - return DaoUtil.toPageData(repository.findByTenantIdWithUpdates( + return find(tenantId, itemTypes, null, publishedVersionIds, pageLink); + } + + // Never matches: the query binds the published ids even when it doesn't filter by them + private static final Set NO_IDS = Set.of(new UUID(0, 0)); + + // One query for both lists, so the only-updates list filters and searches as the plain one does + private PageData find(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + boolean updatesOnly = publishedVersionIds != null; + return DaoUtil.toPageData(repository.findByTenantId( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, + itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), - publishedVersionIds.keySet(), - publishedVersionIds.values(), + updatesOnly, + updatesOnly ? publishedVersionIds.keySet() : NO_IDS, + updatesOnly ? publishedVersionIds.values() : NO_IDS, toPageRequest(pageLink)) ); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java index 560b3cf0d0..8d7698d2ce 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -99,6 +99,15 @@ public class IotHubInstalledItemServiceTest extends AbstractServiceTest { 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_withoutPublishedVersions_isEmpty() { installFive(); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 3af83f064f..c871f0492e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -125,7 +125,16 @@ - @if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) { + @if (!isLoading && loadFailed && onlyUpdates) { + +
+
+

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

+ +
+ } @else if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) {
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index f1bf82d05e..073bbe8171 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -88,6 +88,8 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, onlyUpdates = false; // How many installed items have an update, and how many there are, of all types and with no search; null while not known updatesCount: number | null = null; + // The last load of the list failed: the list is empty, but not because nothing has an update + loadFailed = false; installedCount = 0; // A later load (another page, mode, sort or search) wins over an earlier one that answers last private loadRun = 0; @@ -420,6 +422,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.dataSource = data.data; this.totalElements = data.totalElements; + this.loadFailed = false; this.isLoading = false; // In the list of items with an update their version update shows, not the converter's if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { @@ -432,6 +435,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.dataSource = []; this.totalElements = 0; + this.loadFailed = true; this.isLoading = false; } }); diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index f95bef69d7..456fcdbd1f 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -39,7 +39,7 @@ @if (updatesCount > 0) { arrow_circle_up - {{ (updatesCount === 1 ? 'iot-hub.item-with-update' : 'iot-hub.items-with-update') | translate:{ count: updatesCount, total: installedCount } }} + {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} } @else { check_circle {{ 'iot-hub.all-items-up-to-date' | translate }} diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index c2c51b4632..44d86bf476 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6496,8 +6496,8 @@ "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", "check-for-updates-try-again": "Try again", - "item-with-update": "1 of {{total}} items has an update", - "items-with-update": "{{count}} of {{total}} items have an update", + "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", + "installed-items-load-failed": "Couldn't load the items with an update", "all-items-up-to-date": "All items are up to date", "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", "show-all-items": "Show all items", From 53aeba0875fd565cfa494cac91a22de75ee681fc Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 17:42:07 +0200 Subject: [PATCH 4/7] IoT Hub installed items: the full list when no newer versions, the map bounded by installed items, retry with the counts (PROD-9326 review) --- .../IotHubInstalledItemServiceImpl.java | 12 +++--- .../IotHubInstalledItemServiceTest.java | 15 +++++++ ...t-hub-installed-items-table.component.html | 41 +++++++------------ ...iot-hub-installed-items-table.component.ts | 38 +++++++++-------- .../iot-hub-installed-items.component.html | 28 ++++++------- .../iot-hub-installed-items.component.scss | 29 ------------- .../assets/locale/locale.constant-en_US.json | 3 +- 7 files changed, 72 insertions(+), 94 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index 89f7d636b2..90fe24e0d6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -54,14 +54,16 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, Map publishedVersionIds, PageLink pageLink) { validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); - // An item IoT Hub publishes no version of has nothing to update to + // Only the tenant's installed items, so the map can't outgrow the query's bind parameter limit; an item IoT Hub + // publishes no version of has nothing to update to Map published = new HashMap<>(); - if (publishedVersionIds != null) { - publishedVersionIds.forEach((itemId, versionId) -> { - if (itemId != null && versionId != null) { + 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(); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java index 8d7698d2ce..65fe12ae2b 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -108,6 +108,21 @@ public class IotHubInstalledItemServiceTest extends AbstractServiceTest { assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d"); } + @Test + public void withUpdates_ignoresItemsTheTenantHasNotInstalled() { + installFive(); + Map published = new HashMap<>(published()); + for (int i = 0; i < 20_000; i++) { + published.put(UUID.randomUUID(), UUID.randomUUID()); + } + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published, + new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC))); + + // 40k bind parameters would be over PostgreSQL's limit of 32767 + assertThat(names(page)).containsExactly("b", "d"); + } + @Test public void withUpdates_withoutPublishedVersions_isEmpty() { installFive(); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index c871f0492e..b24e8bb4cf 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -125,34 +125,23 @@ - @if (!isLoading && loadFailed && onlyUpdates) { - + @if (!isLoading && dataSource.length === 0) {
-

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

- -
- } @else if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) { - -
-
-

{{ 'iot-hub.all-items-up-to-date' | translate }}

-

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

- -
- } @else if (!isLoading && dataSource.length === 0) { -
-
-

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

-

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

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

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

+

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

+ + } @else if (onlyUpdates && !hasActiveFilters()) { +

{{ 'iot-hub.all-items-up-to-date' | translate }}

+

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

+ + } @else { +

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

+

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

+ @if (hasActiveFilters()) { + + } }
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 073bbe8171..3ada8afee5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -82,16 +82,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; - // IoT Hub didn't answer Check for updates: the page says so quietly, the list works without it updatesCheckFailed = false; - // After Check for updates the list shows only the items with an update, until the user asks for all of them onlyUpdates = false; - // How many installed items have an update, and how many there are, of all types and with no search; null while not known + // Of all types and with no search; null while not known updatesCount: number | null = null; - // The last load of the list failed: the list is empty, but not because nothing has an update - loadFailed = false; installedCount = 0; - // A later load (another page, mode, sort or search) wins over an earlier one that answers last + loadFailed = false; private loadRun = 0; private widgetResize$: ResizeObserver; @@ -262,8 +258,8 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; - this.showOnlyUpdates(true); - this.loadUpdatesCount(); + // No newer versions: the full list, where a new default converter still shows + this.loadUpdatesCount(() => this.showOnlyUpdates((this.updatesCount ?? 0) > 0)); }, error: () => { this.isCheckingUpdates = false; @@ -272,7 +268,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }); } - /** Only the items with an update, or all of them; from the first page, as the list changes. */ showOnlyUpdates(onlyUpdates: boolean): void { this.onlyUpdates = onlyUpdates; this.pageIndex = 0; @@ -282,7 +277,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.loadData(); } - /** IoT Hub's published version id by item id, of the items it publishes a version of. */ private publishedVersionIds(): Record { const ids: Record = {}; this.publishedVersionMap.forEach((info, itemId) => { @@ -293,7 +287,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, return ids; } - /** After an item is updated or removed: the list and, once the updates are checked, the counts in the header. */ + /** Retries a failed load, and the header counts if they failed with it. */ + retryLoad(): void { + this.loadData(); + if (this.updatesCount === null) { + this.loadUpdatesCount(); + } + } + private reloadAfterChange(): void { this.loadData(); if (this.updatesChecked && !this.itemVersion) { @@ -301,7 +302,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } } - private loadUpdatesCount(): void { + private loadUpdatesCount(then?: () => void): void { this.updatesCount = null; forkJoin({ withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), @@ -311,9 +312,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.updatesCount = withUpdates.totalElements; this.installedCount = installed; this.cd.markForCheck(); + then?.(); }, - // The header then shows only the buttons - error: () => this.cd.markForCheck() + error: () => { + this.cd.markForCheck(); + then?.(); + } }); } @@ -401,7 +405,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - // The page of one item's versions has its own published version and lists all of them + // One item's versions page lists them all const items$ = this.onlyUpdates && !this.itemVersion ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true}) : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); @@ -411,7 +415,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, if (run !== this.loadRun) { return; } - // The last page emptied (its last item updated or removed): go to the page that is last now + // The last page emptied after an update or a removal if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { this.pageIndex = Math.ceil(data.totalElements / this.pageSize) - 1; if (this.paginator) { @@ -424,7 +428,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.totalElements = data.totalElements; this.loadFailed = false; this.isLoading = false; - // In the list of items with an update their version update shows, not the converter's + // In the only-updates list the version update shows, not the converter's if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 456fcdbd1f..e70619ab4b 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -15,11 +15,11 @@

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

- @if (!updatesChecked) { -
+
+ @if (!updatesChecked) { @if (updatesCheckFailed) { - - warning + + warning {{ 'iot-hub.check-for-updates-failed' | translate }} } @@ -29,20 +29,18 @@ } @else { update } - {{ (updatesCheckFailed ? 'iot-hub.check-for-updates-try-again' : 'iot-hub.check-for-updates') | translate }} + {{ (updatesCheckFailed ? 'iot-hub.try-again' : 'iot-hub.check-for-updates') | translate }} -
- } @else { - -
+ } @else { @if (updatesCount !== null) { - + @if (updatesCount > 0) { - arrow_circle_up + arrow_circle_up {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} } @else { - check_circle - {{ 'iot-hub.all-items-up-to-date' | translate }} + + check_circle + {{ 'iot-hub.no-newer-versions' | translate }} } } @@ -51,8 +49,8 @@ } @else if ((updatesCount ?? 0) > 0) { } -
- } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss index eab61c2c2a..1ade0222c5 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss @@ -29,35 +29,6 @@ margin-bottom: 32px; } -// After Check for updates: "N items have an update" and Show all items / Show only updates -.tb-installed-updates-note { - display: inline-flex; - align-items: center; - gap: 8px; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - - mat-icon { - font-size: 20px; - width: 20px; - height: 20px; - } - - .tb-installed-updates-available { - color: #f44336; - } - - .tb-installed-updates-none { - color: #198038; - } - - .tb-installed-updates-failed { - color: #f66716; - } -} - .tb-installed-title { font-size: 36px; font-weight: 500; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 44d86bf476..899486594c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6495,10 +6495,9 @@ "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", - "check-for-updates-try-again": "Try again", "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", - "installed-items-load-failed": "Couldn't load the items with an update", "all-items-up-to-date": "All items are up to date", + "no-newer-versions": "No newer versions in IoT Hub", "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", "show-all-items": "Show all items", "show-only-updates": "Show only updates", From b03f29e5bec7b892655b4f5b7808c5bdfedd42c8 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 18:07:32 +0200 Subject: [PATCH 5/7] IoT Hub installed items: checked once the counts are in, counts keep the last value, one status note (PROD-9326 review) --- ...t-hub-installed-items-table.component.html | 4 -- ...iot-hub-installed-items-table.component.ts | 43 +++++++++++++------ .../iot-hub-installed-items.component.html | 30 ++++++------- .../assets/locale/locale.constant-en_US.json | 2 - 4 files changed, 45 insertions(+), 34 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index b24e8bb4cf..282e4a0f23 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -132,10 +132,6 @@

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

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

- } @else if (onlyUpdates && !hasActiveFilters()) { -

{{ 'iot-hub.all-items-up-to-date' | translate }}

-

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

- } @else {

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

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

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3ada8afee5..330fd635ef 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -89,6 +89,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, installedCount = 0; loadFailed = false; private loadRun = 0; + private countRun = 0; private widgetResize$: ResizeObserver; @@ -256,10 +257,16 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - this.updatesChecked = true; - this.isCheckingUpdates = false; - // No newer versions: the full list, where a new default converter still shows - this.loadUpdatesCount(() => this.showOnlyUpdates((this.updatesCount ?? 0) > 0)); + // Checked once the counts are in: the header shows them + this.loadUpdatesCount(() => { + this.updatesChecked = true; + this.isCheckingUpdates = false; + // No newer versions: the full list, where a new default converter still shows + this.showOnlyUpdates(this.updatesCount > 0); + }, () => { + this.isCheckingUpdates = false; + this.updatesCheckFailed = true; + }); }, error: () => { this.isCheckingUpdates = false; @@ -290,33 +297,45 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, /** Retries a failed load, and the header counts if they failed with it. */ retryLoad(): void { this.loadData(); - if (this.updatesCount === null) { + if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { this.loadUpdatesCount(); } } private reloadAfterChange(): void { - this.loadData(); - if (this.updatesChecked && !this.itemVersion) { - this.loadUpdatesCount(); + if (!this.updatesChecked || this.itemVersion) { + this.loadData(); + return; } + // The last update done: the full list, as after Check for updates + this.loadUpdatesCount( + () => this.onlyUpdates && this.updatesCount === 0 ? this.showOnlyUpdates(false) : this.loadData(), + () => this.loadData()); } - private loadUpdatesCount(then?: () => void): void { - this.updatesCount = null; + /** The header counts; the previous ones stay until the new ones arrive, and a later call wins. */ + private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { + const run = ++this.countRun; forkJoin({ withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), installed: this.iotHubApiService.getInstalledItemsCount(undefined, { ignoreLoading: true }) }).subscribe({ next: ({ withUpdates, installed }) => { + if (run !== this.countRun) { + return; + } this.updatesCount = withUpdates.totalElements; this.installedCount = installed; this.cd.markForCheck(); - then?.(); + onCounts?.(); }, error: () => { + if (run !== this.countRun) { + return; + } + this.updatesCount = null; this.cd.markForCheck(); - then?.(); + onError?.(); } }); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index e70619ab4b..7d4bbe52d0 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -16,13 +16,23 @@

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

- @if (!updatesChecked) { - @if (updatesCheckFailed) { - + + + @if (!updatesChecked) { + @if (updatesCheckFailed) { warning {{ 'iot-hub.check-for-updates-failed' | translate }} - + } + } @else if (updatesCount > 0) { + arrow_circle_up + {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} + } @else if (updatesCount === 0) { + + check_circle + {{ 'iot-hub.no-newer-versions' | translate }} } + + @if (!updatesChecked) { } @else { - @if (updatesCount !== null) { - - @if (updatesCount > 0) { - arrow_circle_up - {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} - } @else { - - check_circle - {{ 'iot-hub.no-newer-versions' | translate }} - } - - } @if (onlyUpdates) { } @else if ((updatesCount ?? 0) > 0) { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 899486594c..217b2e7919 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6496,9 +6496,7 @@ "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", - "all-items-up-to-date": "All items are up to date", "no-newer-versions": "No newer versions in IoT Hub", - "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", "show-all-items": "Show all items", "show-only-updates": "Show only updates", "updates": "Updates", From d67da9487c7d0ff1a0b483432f23c9c2cb836ded Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 17 Nov 2026 11:13:00 +0200 Subject: [PATCH 6/7] IoT Hub installed items: a failed count shows in the header with Try again, only-updates empty state, no double error toast, cleanup (PROD-9326 review) --- .../src/app/core/http/iot-hub-api.service.ts | 23 +++----- ...t-hub-installed-items-table.component.html | 2 +- ...iot-hub-installed-items-table.component.ts | 52 ++++++++----------- .../iot-hub-installed-items.component.html | 18 +++---- .../assets/locale/locale.constant-en_US.json | 3 +- 5 files changed, 42 insertions(+), 56 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index b9674e232c..fe8c2800e6 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -243,11 +243,7 @@ export class IotHubApiService { public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], itemId?: string, config?: IotHubRequestConfig): Observable> { - let query = pageLink.toQuery(); - if (itemTypes) { - const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; - types.forEach(t => query += `&itemTypes=${t}`); - } + let query = this.installedItemsQuery(pageLink, itemTypes); if (itemId) { query += `&itemId=${itemId}`; } @@ -257,18 +253,11 @@ export class IotHubApiService { ); } - /** - * The installed items with an update: publishedVersionIds is IoT Hub's published version id by item id, as Check for - * updates got it. The server keeps the items installed in another version, with the page's sort, search and types. - */ + /** publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come back. */ public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, config?: IotHubRequestConfig): Observable> { - let query = pageLink.toQuery(); - if (itemTypes?.length) { - query += itemTypes.map(t => `&itemTypes=${t}`).join(''); - } return this.http.post>( - `/api/iot-hub/installedItems/withUpdates${query}`, + `/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`, publishedVersionIds, { params: this.buildParams(config) } ); @@ -313,7 +302,6 @@ export class IotHubApiService { ); } - /** Asked in requests of 100 item ids at most, so a tenant with many items doesn't send IoT Hub one huge request. */ public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { if (!itemIds.length) { return of([]); @@ -336,6 +324,11 @@ export class IotHubApiService { ); } + private installedItemsQuery(pageLink: PageLink, itemTypes?: string | string[] | null): string { + const types = !itemTypes ? [] : Array.isArray(itemTypes) ? itemTypes : [itemTypes]; + return pageLink.toQuery() + types.map(t => `&itemTypes=${t}`).join(''); + } + private buildParams(config?: IotHubRequestConfig): HttpParams { return new InterceptorHttpParams( new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 282e4a0f23..a5a013b68d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -133,7 +133,7 @@

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

} @else { -

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

+

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

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

@if (hasActiveFilters()) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 330fd635ef..8204a42584 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -84,7 +84,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isCheckingUpdates = false; updatesCheckFailed = false; onlyUpdates = false; - // Of all types and with no search; null while not known + // Of all types and with no search updatesCount: number | null = null; installedCount = 0; loadFailed = false; @@ -135,10 +135,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngOnChanges(changes: SimpleChanges): void { if (changes.textSearch || changes.typeFilters) { if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) { - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } + this.setPageIndex(0); this.loadData(); } } @@ -146,8 +143,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngAfterViewInit(): void { this.sort.sortChange.subscribe(() => { - this.pageIndex = 0; - this.paginator.pageIndex = 0; + this.setPageIndex(0); this.loadData(); }); } @@ -257,16 +253,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - // Checked once the counts are in: the header shows them this.loadUpdatesCount(() => { this.updatesChecked = true; this.isCheckingUpdates = false; - // No newer versions: the full list, where a new default converter still shows + // The full list shows a new default converter, the only-updates list doesn't this.showOnlyUpdates(this.updatesCount > 0); - }, () => { - this.isCheckingUpdates = false; - this.updatesCheckFailed = true; - }); + }, () => this.isCheckingUpdates = false); }, error: () => { this.isCheckingUpdates = false; @@ -277,11 +269,15 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, showOnlyUpdates(onlyUpdates: boolean): void { this.onlyUpdates = onlyUpdates; - this.pageIndex = 0; + this.setPageIndex(0); + this.loadData(); + } + + private setPageIndex(pageIndex: number): void { + this.pageIndex = pageIndex; if (this.paginator) { - this.paginator.pageIndex = 0; + this.paginator.pageIndex = pageIndex; } - this.loadData(); } private publishedVersionIds(): Record { @@ -294,7 +290,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, return ids; } - /** Retries a failed load, and the header counts if they failed with it. */ retryLoad(): void { this.loadData(); if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { @@ -307,18 +302,19 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.loadData(); return; } - // The last update done: the full list, as after Check for updates + // Without counts the only-updates list can't be trusted, so the full list this.loadUpdatesCount( () => this.onlyUpdates && this.updatesCount === 0 ? this.showOnlyUpdates(false) : this.loadData(), - () => this.loadData()); + () => this.onlyUpdates ? this.showOnlyUpdates(false) : this.loadData()); } - /** The header counts; the previous ones stay until the new ones arrive, and a later call wins. */ + /** The previous counts stay until the new ones arrive, and a later call wins. A failure shows in the header with Try again. */ 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(), { ignoreLoading: true }), - installed: this.iotHubApiService.getInstalledItemsCount(undefined, { ignoreLoading: true }) + 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) { @@ -326,6 +322,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.updatesCount = withUpdates.totalElements; this.installedCount = installed; + this.updatesCheckFailed = false; this.cd.markForCheck(); onCounts?.(); }, @@ -334,6 +331,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, return; } this.updatesCount = null; + this.updatesCheckFailed = true; this.cd.markForCheck(); onError?.(); } @@ -424,9 +422,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - // One item's versions page lists them all + // 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}) + ? 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({ @@ -436,10 +434,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } // The last page emptied after an update or a removal if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { - this.pageIndex = Math.ceil(data.totalElements / this.pageSize) - 1; - if (this.paginator) { - this.paginator.pageIndex = this.pageIndex; - } + this.setPageIndex(Math.ceil(data.totalElements / this.pageSize) - 1); this.loadData(); return; } @@ -447,7 +442,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.totalElements = data.totalElements; this.loadFailed = false; this.isLoading = false; - // In the only-updates list the version update shows, not the converter's if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7d4bbe52d0..7a46195fa5 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -18,21 +18,18 @@
- @if (!updatesChecked) { - @if (updatesCheckFailed) { - warning - {{ 'iot-hub.check-for-updates-failed' | translate }} - } - } @else if (updatesCount > 0) { + @if (updatesCheckFailed) { + warning + {{ 'iot-hub.check-for-updates-failed' | translate }} + } @else if (updatesChecked && updatesCount > 0) { arrow_circle_up {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} - } @else if (updatesCount === 0) { - + } @else if (updatesChecked && updatesCount === 0) { check_circle {{ 'iot-hub.no-newer-versions' | translate }} } - @if (!updatesChecked) { + @if (!updatesChecked || updatesCheckFailed) { - } @else { + } + @if (updatesChecked) { @if (onlyUpdates) { } @else if ((updatesCount ?? 0) > 0) { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 217b2e7919..05b9d80811 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6495,7 +6495,7 @@ "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", - "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", + "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", @@ -6530,6 +6530,7 @@ "installed-date": "Installed", "no-installed-items": "No installed items found", "no-installed-items-text": "Try adjusting your search or filters.", + "no-items-with-updates": "No items with updates match your filters", "remove-installed-item-title": "Remove Installed Item", "remove-installed-item-text": "Are you sure you want to remove '{{name}}'? The installed entity will also be removed.", "installed-item-removed": "'{{name}}' has been removed", From 1ee42c985b778631f37af8c32b20a48dd22c7b23 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Tue, 17 Nov 2026 11:49:20 +0200 Subject: [PATCH 7/7] IoT Hub installed items: Try again after a failed count only recounts When updates were already checked and only the count failed, Try again now recounts instead of re-running the whole check: the header keeps the note with a spinner on the button, the user's list mode and page stay, and the checking state is cleared by whichever count finishes last, so a newer count from a reload can't leave the button spinning. Shorter comments and plain if/else in reloadAfterChange. --- .../src/app/core/http/iot-hub-api.service.ts | 2 +- ...iot-hub-installed-items-table.component.ts | 36 +++++++++++++------ .../iot-hub-installed-items.component.html | 2 +- 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index fe8c2800e6..e162ba1357 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -253,7 +253,7 @@ export class IotHubApiService { ); } - /** publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come back. */ + /** Body: published version id by item id; returns items installed in a different version. */ public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, config?: IotHubRequestConfig): Observable> { return this.http.post>( diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 8204a42584..4b50ad533a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -84,7 +84,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isCheckingUpdates = false; updatesCheckFailed = false; onlyUpdates = false; - // Of all types and with no search + // Totals, ignoring type filters and search updatesCount: number | null = null; installedCount = 0; loadFailed = false; @@ -245,9 +245,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + if (this.updatesChecked) { + // Only the count failed: recount, keeping the list as it is + this.loadUpdatesCount(); + return; + } this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - // An IoT Hub that doesn't answer is not a page error: the page says so next to the button, the list works without it + // Failure is shown next to the button, not as an error toast switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { @@ -255,10 +260,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.loadUpdatesCount(() => { this.updatesChecked = true; - this.isCheckingUpdates = false; - // The full list shows a new default converter, the only-updates list doesn't + // No updates: stay on the full list (it also shows converter updates) this.showOnlyUpdates(this.updatesCount > 0); - }, () => this.isCheckingUpdates = false); + }); }, error: () => { this.isCheckingUpdates = false; @@ -302,13 +306,23 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.loadData(); return; } - // Without counts the only-updates list can't be trusted, so the full list - this.loadUpdatesCount( - () => this.onlyUpdates && this.updatesCount === 0 ? this.showOnlyUpdates(false) : this.loadData(), - () => this.onlyUpdates ? this.showOnlyUpdates(false) : this.loadData()); + 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(); + } + }); } - /** The previous counts stay until the new ones arrive, and a later call wins. A failure shows in the header with Try again. */ + // 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 }; @@ -323,6 +337,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.updatesCount = withUpdates.totalElements; this.installedCount = installed; this.updatesCheckFailed = false; + this.isCheckingUpdates = false; this.cd.markForCheck(); onCounts?.(); }, @@ -332,6 +347,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.updatesCount = null; this.updatesCheckFailed = true; + this.isCheckingUpdates = false; this.cd.markForCheck(); onError?.(); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7a46195fa5..8702709c3e 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -42,7 +42,7 @@ @if (updatesChecked) { @if (onlyUpdates) { - } @else if ((updatesCount ?? 0) > 0) { + } @else if (updatesCount > 0) { } }