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..332a95242b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -146,6 +146,25 @@ public class IotHubController extends BaseController { return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); } + /** + * The installed items with an update in IoT Hub. The body is what the browser got from IoT Hub on Check for updates: + * the published version id by item id. A POST, as the map of a tenant with many items doesn't fit in a URL. + */ + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/installedItems/withUpdates") + @ResponseBody + public PageData getInstalledItemsWithUpdates(@RequestParam int pageSize, + @RequestParam int page, + @RequestParam(required = false) String textSearch, + @RequestParam(required = false) String sortProperty, + @RequestParam(required = false) String sortOrder, + @RequestParam(required = false) List itemTypes, + @RequestBody Map publishedVersionIds) throws ThingsboardException { + checkAllPermissions(); + PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/count") @ResponseBody diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index b99cf18981..7373a8fb81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id, not empty; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 072506dfca..17f3361738 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index d69060cd94..90fe24e0d6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -14,6 +14,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -49,6 +50,27 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink); } + @Override + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); + // Only the tenant's installed items, so the map can't outgrow the query's bind parameter limit; an item IoT Hub + // publishes no version of has nothing to update to + Map published = new HashMap<>(); + if (publishedVersionIds != null && !publishedVersionIds.isEmpty()) { + for (UUID itemId : iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId)) { + UUID versionId = publishedVersionIds.get(itemId); + if (versionId != null) { + published.put(itemId, versionId); + } + } + } + if (published.isEmpty()) { + return PageData.emptyPageData(); + } + return iotHubInstalledItemDao.findByTenantIdWithUpdates(tenantId, itemTypes, published, pageLink); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 693166b7e0..c09f8c12f5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -33,17 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId, @Param("itemIds") Collection itemIds); + /** + * The tenant's installed items, by type, item and text. With {@code updatesOnly}, only the items with an update: an item + * of {@code publishedItemIds} whose installed version is not among {@code publishedVersionIds} (version ids are unique, + * so: not the published version of its item). A flag, as Hibernate can't type {@code :uuids IS NULL}. + */ @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:updatesOnly = false + OR (item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds)) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); + Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("updatesOnly") boolean updatesOnly, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index d07d8f5dd4..4c91e5137b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -48,11 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { + return find(tenantId, itemTypes, itemId, null, pageLink); + } + + @Override + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + return find(tenantId, itemTypes, null, publishedVersionIds, pageLink); + } + + // Never matches: the query binds the published ids even when it doesn't filter by them + private static final Set NO_IDS = Set.of(new UUID(0, 0)); + + // One query for both lists, so the only-updates list filters and searches as the plain one does + private PageData find(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + boolean updatesOnly = publishedVersionIds != null; return DaoUtil.toPageData(repository.findByTenantId( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), + updatesOnly, + updatesOnly ? publishedVersionIds.keySet() : NO_IDS, + updatesOnly ? publishedVersionIds.values() : NO_IDS, toPageRequest(pageLink)) ); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java new file mode 100644 index 0000000000..65fe12ae2b --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.service; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +public class IotHubInstalledItemServiceTest extends AbstractServiceTest { + + @Autowired + IotHubInstalledItemService installedItemService; + + private final UUID trackerItemId = UUID.randomUUID(); + private final UUID sensorItemId = UUID.randomUUID(); + private final UUID unpublishedItemId = UUID.randomUUID(); + private final UUID trackerPublished = UUID.randomUUID(); + private final UUID sensorPublished = UUID.randomUUID(); + + private void install(String name, UUID itemId, UUID versionId) { + IotHubInstalledItem item = new IotHubInstalledItem(); + item.setTenantId(tenantId); + item.setItemId(itemId); + item.setItemVersionId(versionId); + item.setItemName(name); + item.setItemType("WIDGET"); + item.setVersion("1.0.0"); + item.setDescriptor(new WidgetInstalledItemDescriptor()); + installedItemService.save(tenantId, item); + } + + /** a and c are up to date, b and d have an update (d is a second install of a's item in an older version), e has no published version. */ + private void installFive() { + install("a", sensorItemId, sensorPublished); + install("b", trackerItemId, UUID.randomUUID()); + install("c", sensorItemId, sensorPublished); + install("d", sensorItemId, UUID.randomUUID()); + install("e", unpublishedItemId, UUID.randomUUID()); + } + + private Map published() { + return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished); + } + + private static List names(PageData page) { + return page.getData().stream().map(IotHubInstalledItem::getItemName).toList(); + } + + @Test + public void withUpdates_onlyTheItemsWithAnUpdate_inThePageSort() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.DESC)); + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), byName); + + assertThat(names(page)).containsExactly("d", "b"); + assertThat(page.getTotalElements()).isEqualTo(2); + } + + @Test + public void withUpdates_pagesAndTotal() { + installFive(); + SortOrder byName = new SortOrder("itemName", SortOrder.Direction.ASC); + + PageData first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 0, null, byName)); + PageData second = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 1, null, byName)); + + assertThat(names(first)).containsExactly("b"); + assertThat(names(second)).containsExactly("d"); + assertThat(first.getTotalElements()).isEqualTo(2); + assertThat(first.hasNext()).isTrue(); + assertThat(second.hasNext()).isFalse(); + } + + @Test + public void withUpdates_keepsTheSearchAndTheTypes() { + installFive(); + // "b" is in no item type or version, only in the name of b + PageLink search = new PageLink(10, 0, "b", new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("WIDGET"), published(), search))) + .containsExactly("b"); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("DEVICE"), published(), + new PageLink(10)).getData()).isEmpty(); + } + + @Test + public void plainList_sameQuery_isNotFiltered() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantId(tenantId, null, null, byName))).containsExactly("a", "b", "c", "d", "e"); + assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d"); + } + + @Test + public void withUpdates_ignoresItemsTheTenantHasNotInstalled() { + installFive(); + Map published = new HashMap<>(published()); + for (int i = 0; i < 20_000; i++) { + published.put(UUID.randomUUID(), UUID.randomUUID()); + } + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published, + new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC))); + + // 40k bind parameters would be over PostgreSQL's limit of 32767 + assertThat(names(page)).containsExactly("b", "d"); + } + + @Test + public void withUpdates_withoutPublishedVersions_isEmpty() { + installFive(); + Map unpublished = new HashMap<>(); + unpublished.put(unpublishedItemId, null); + + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, Map.of(), new PageLink(10)).getData()).isEmpty(); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, unpublished, new PageLink(10)).getData()).isEmpty(); + } + +} diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index fa040e8632..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 @@ -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; @@ -240,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}`; } @@ -254,6 +253,16 @@ export class IotHubApiService { ); } + /** Body: published version id by item id; returns items installed in a different version. */ + public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, + config?: IotHubRequestConfig): Observable> { + return this.http.post>( + `/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`, + publishedVersionIds, + { params: this.buildParams(config) } + ); + } + public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable { let url = '/api/iot-hub/installedItems/count'; if (itemType) { @@ -294,11 +303,18 @@ export class IotHubApiService { } public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { - return this.http.post( + if (!itemIds.length) { + return of([]); + } + const chunks: string[][] = []; + for (let i = 0; i < itemIds.length; i += PUBLISHED_VERSIONS_CHUNK_SIZE) { + chunks.push(itemIds.slice(i, i + PUBLISHED_VERSIONS_CHUNK_SIZE)); + } + return forkJoin(chunks.map(chunk => this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, - itemIds, + chunk, { params: this.buildParams(config) } - ); + ))).pipe(map(results => results.flat())); } public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable { @@ -308,6 +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 7f1dbac04e..a5a013b68d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -128,12 +128,16 @@ @if (!isLoading && dataSource.length === 0) {
-

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

-

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

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

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

+

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

+ + } @else { +

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

+

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

+ @if (hasActiveFilters()) { + + } }
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3c196cdb66..4b50ad533a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -44,7 +44,7 @@ import { loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, forkJoin } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -82,6 +82,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; + updatesCheckFailed = false; + onlyUpdates = false; + // Totals, ignoring type filters and search + updatesCount: number | null = null; + installedCount = 0; + loadFailed = false; + private loadRun = 0; + private countRun = 0; private widgetResize$: ResizeObserver; @@ -127,10 +135,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngOnChanges(changes: SimpleChanges): void { if (changes.textSearch || changes.typeFilters) { if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) { - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } + this.setPageIndex(0); this.loadData(); } } @@ -138,8 +143,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngAfterViewInit(): void { this.sort.sortChange.subscribe(() => { - this.pageIndex = 0; - this.paginator.pageIndex = 0; + this.setPageIndex(0); this.loadData(); }); } @@ -161,7 +165,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, deleteItem(item: IotHubInstalledItem): void { this.iotHubActions.deleteItem(item).subscribe(deleted => { if (deleted) { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -191,7 +195,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { if (result === 'updated' || result === 'deleted') { - this.loadData(); + this.reloadAfterChange(); } }); }); @@ -241,18 +245,111 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + if (this.updatesChecked) { + // Only the count failed: recount, keeping the list as it is + this.loadUpdatesCount(); + return; + } + this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true })) + // Failure is shown next to the button, not as an error toast + switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - this.updatesChecked = true; + this.loadUpdatesCount(() => { + this.updatesChecked = true; + // No updates: stay on the full list (it also shows converter updates) + this.showOnlyUpdates(this.updatesCount > 0); + }); + }, + error: () => { this.isCheckingUpdates = false; - void this.checkConverterUpdates(); + this.updatesCheckFailed = true; + } + }); + } + + showOnlyUpdates(onlyUpdates: boolean): void { + this.onlyUpdates = onlyUpdates; + this.setPageIndex(0); + this.loadData(); + } + + private setPageIndex(pageIndex: number): void { + this.pageIndex = pageIndex; + if (this.paginator) { + this.paginator.pageIndex = pageIndex; + } + } + + private publishedVersionIds(): Record { + const ids: Record = {}; + this.publishedVersionMap.forEach((info, itemId) => { + if (info.publishedVersionId) { + ids[itemId] = info.publishedVersionId; + } + }); + return ids; + } + + retryLoad(): void { + this.loadData(); + if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { + this.loadUpdatesCount(); + } + } + + private reloadAfterChange(): void { + if (!this.updatesChecked || this.itemVersion) { + this.loadData(); + return; + } + this.loadUpdatesCount(() => { + if (this.onlyUpdates && this.updatesCount === 0) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }, () => { + // Count failed: fall back to the full list + if (this.onlyUpdates) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }); + } + + // Latest call wins; previous counts stay until it returns + private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { + const run = ++this.countRun; + const config = { ignoreLoading: true, ignoreErrors: true }; + forkJoin({ + withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), config), + installed: this.iotHubApiService.getInstalledItemsCount(undefined, config) + }).subscribe({ + next: ({ withUpdates, installed }) => { + if (run !== this.countRun) { + return; + } + this.updatesCount = withUpdates.totalElements; + this.installedCount = installed; + this.updatesCheckFailed = false; + this.isCheckingUpdates = false; + this.cd.markForCheck(); + onCounts?.(); }, error: () => { + if (run !== this.countRun) { + return; + } + this.updatesCount = null; + this.updatesCheckFailed = true; this.isCheckingUpdates = false; + this.cd.markForCheck(); + onError?.(); } }); } @@ -260,7 +357,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { if (result === 'updated') { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -341,18 +438,37 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}).subscribe({ + // The empty state shows a failure of the only-updates list; one item's versions page lists them all + const items$ = this.onlyUpdates && !this.itemVersion + ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true, ignoreErrors: true}) + : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); + const run = ++this.loadRun; + items$.subscribe({ next: (data) => { + if (run !== this.loadRun) { + return; + } + // The last page emptied after an update or a removal + if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { + this.setPageIndex(Math.ceil(data.totalElements / this.pageSize) - 1); + this.loadData(); + return; + } this.dataSource = data.data; this.totalElements = data.totalElements; + this.loadFailed = false; this.isLoading = false; - if (this.updatesChecked && !this.itemVersion) { + if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } }, error: () => { + if (run !== this.loadRun) { + return; + } this.dataSource = []; this.totalElements = 0; + this.loadFailed = true; this.isLoading = false; } }); diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7591b1dc5a..8702709c3e 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -1,7 +1,8 @@
@@ -14,16 +15,38 @@

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

- @if (!updatesChecked) { - - } + + @if (!updatesChecked || updatesCheckFailed) { + + } + @if (updatesChecked) { + @if (onlyUpdates) { + + } @else if (updatesCount > 0) { + + } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts index 1af2d5ed2c..47aa3e5080 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; @@ -107,4 +108,24 @@ export class TbIotHubInstalledItemsComponent implements OnInit, OnDestroy { get updatesChecked(): boolean { return this.tableComponent?.updatesChecked || false; } + + get updatesCheckFailed(): boolean { + return this.tableComponent?.updatesCheckFailed || false; + } + + get onlyUpdates(): boolean { + return this.tableComponent?.onlyUpdates || false; + } + + get updatesCount(): number | null { + return this.tableComponent?.updatesCount ?? null; + } + + get installedCount(): number { + return this.tableComponent?.installedCount || 0; + } + + showOnlyUpdates(onlyUpdates: boolean): void { + this.tableComponent?.showOnlyUpdates(onlyUpdates); + } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 1bb3ad848f..2c4282cc75 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6497,6 +6497,11 @@ "install-partial-desc": "'{{name}}' was installed, but some required items were missing.", "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", + "check-for-updates-failed": "Couldn't check for updates", + "items-with-update": "Updates available for {{count}} of {{total}}", + "no-newer-versions": "No newer versions in IoT Hub", + "show-all-items": "Show all items", + "show-only-updates": "Show only updates", "updates": "Updates", "up-to-date": "Up to date", "new-converter-available": "New converter available", @@ -6528,6 +6533,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",