Browse Source

Merge pull request #16657 from pinkevmladchy/fix/iot-hub-installed-items-updates-first

IoT Hub: made Installed items show only the items with an update after Check for updates
pull/16749/head
Viacheslav Klimov 2 weeks ago
committed by GitHub
parent
commit
0ec565ded1
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 19
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 4
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java
  3. 4
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java
  4. 22
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java
  5. 14
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java
  6. 19
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java
  7. 136
      dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java
  8. 39
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  9. 16
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  10. 146
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  11. 43
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html
  12. 23
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts
  13. 6
      ui-ngx/src/assets/locale/locale.constant-en_US.json

19
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<IotHubInstalledItem> getInstalledItemsWithUpdates(@RequestParam int pageSize,
@RequestParam int page,
@RequestParam(required = false) String textSearch,
@RequestParam(required = false) String sortProperty,
@RequestParam(required = false) String sortOrder,
@RequestParam(required = false) List<String> itemTypes,
@RequestBody Map<UUID, UUID> publishedVersionIds) throws ThingsboardException {
checkAllPermissions();
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/count")
@ResponseBody

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

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

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

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

22
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java

@ -14,6 +14,7 @@ import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity;
import 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<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink) {
validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES);
// Only the tenant's installed items, so the map can't outgrow the query's bind parameter limit; an item IoT Hub
// publishes no version of has nothing to update to
Map<UUID, UUID> published = new HashMap<>();
if (publishedVersionIds != null && !publishedVersionIds.isEmpty()) {
for (UUID itemId : iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId)) {
UUID versionId = publishedVersionIds.get(itemId);
if (versionId != null) {
published.put(itemId, versionId);
}
}
}
if (published.isEmpty()) {
return PageData.emptyPageData();
}
return iotHubInstalledItemDao.findByTenantIdWithUpdates(tenantId, itemTypes, published, pageLink);
}
@Override
public List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId) {
return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId);

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

@ -33,17 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository<IotHubInstalledIte
List<UUID> findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId,
@Param("itemIds") Collection<UUID> itemIds);
/**
* The tenant's installed items, by type, item and text. With {@code updatesOnly}, only the items with an update: an item
* of {@code publishedItemIds} whose installed version is not among {@code publishedVersionIds} (version ids are unique,
* so: not the published version of its item). A flag, as Hibernate can't type {@code :uuids IS NULL}.
*/
@Query("""
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<IotHubInstalledItemEntity> findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable);
Page<IotHubInstalledItemEntity> findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> itemTypes,
@Param("itemId") UUID itemId, @Param("textSearch") String textSearch,
@Param("updatesOnly") boolean updatesOnly,
@Param("publishedItemIds") Collection<UUID> publishedItemIds,
@Param("publishedVersionIds") Collection<UUID> publishedVersionIds,
Pageable pageable);
@Query("""
SELECT COUNT(item) FROM IotHubInstalledItemEntity item

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

@ -48,11 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao<IotHubInstalledItemEntity
@Override
public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
return find(tenantId, itemTypes, itemId, null, pageLink);
}
@Override
public PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink) {
return find(tenantId, itemTypes, null, publishedVersionIds, pageLink);
}
// Never matches: the query binds the published ids even when it doesn't filter by them
private static final Set<UUID> NO_IDS = Set.of(new UUID(0, 0));
// One query for both lists, so the only-updates list filters and searches as the plain one does
private PageData<IotHubInstalledItem> find(TenantId tenantId, List<String> itemTypes, UUID itemId,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink) {
boolean updatesOnly = publishedVersionIds != null;
return DaoUtil.toPageData(repository.findByTenantId(
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))
);
}

136
dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java

@ -0,0 +1,136 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.service;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.SortOrder;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@DaoSqlTest
public class IotHubInstalledItemServiceTest extends AbstractServiceTest {
@Autowired
IotHubInstalledItemService installedItemService;
private final UUID trackerItemId = UUID.randomUUID();
private final UUID sensorItemId = UUID.randomUUID();
private final UUID unpublishedItemId = UUID.randomUUID();
private final UUID trackerPublished = UUID.randomUUID();
private final UUID sensorPublished = UUID.randomUUID();
private void install(String name, UUID itemId, UUID versionId) {
IotHubInstalledItem item = new IotHubInstalledItem();
item.setTenantId(tenantId);
item.setItemId(itemId);
item.setItemVersionId(versionId);
item.setItemName(name);
item.setItemType("WIDGET");
item.setVersion("1.0.0");
item.setDescriptor(new WidgetInstalledItemDescriptor());
installedItemService.save(tenantId, item);
}
/** a and c are up to date, b and d have an update (d is a second install of a's item in an older version), e has no published version. */
private void installFive() {
install("a", sensorItemId, sensorPublished);
install("b", trackerItemId, UUID.randomUUID());
install("c", sensorItemId, sensorPublished);
install("d", sensorItemId, UUID.randomUUID());
install("e", unpublishedItemId, UUID.randomUUID());
}
private Map<UUID, UUID> published() {
return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished);
}
private static List<String> names(PageData<IotHubInstalledItem> page) {
return page.getData().stream().map(IotHubInstalledItem::getItemName).toList();
}
@Test
public void withUpdates_onlyTheItemsWithAnUpdate_inThePageSort() {
installFive();
PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.DESC));
PageData<IotHubInstalledItem> page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), byName);
assertThat(names(page)).containsExactly("d", "b");
assertThat(page.getTotalElements()).isEqualTo(2);
}
@Test
public void withUpdates_pagesAndTotal() {
installFive();
SortOrder byName = new SortOrder("itemName", SortOrder.Direction.ASC);
PageData<IotHubInstalledItem> first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(),
new PageLink(1, 0, null, byName));
PageData<IotHubInstalledItem> second = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(),
new PageLink(1, 1, null, byName));
assertThat(names(first)).containsExactly("b");
assertThat(names(second)).containsExactly("d");
assertThat(first.getTotalElements()).isEqualTo(2);
assertThat(first.hasNext()).isTrue();
assertThat(second.hasNext()).isFalse();
}
@Test
public void withUpdates_keepsTheSearchAndTheTypes() {
installFive();
// "b" is in no item type or version, only in the name of b
PageLink search = new PageLink(10, 0, "b", new SortOrder("itemName", SortOrder.Direction.ASC));
assertThat(names(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("WIDGET"), published(), search)))
.containsExactly("b");
assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("DEVICE"), published(),
new PageLink(10)).getData()).isEmpty();
}
@Test
public void plainList_sameQuery_isNotFiltered() {
installFive();
PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC));
assertThat(names(installedItemService.findByTenantId(tenantId, null, null, byName))).containsExactly("a", "b", "c", "d", "e");
assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d");
}
@Test
public void withUpdates_ignoresItemsTheTenantHasNotInstalled() {
installFive();
Map<UUID, UUID> published = new HashMap<>(published());
for (int i = 0; i < 20_000; i++) {
published.put(UUID.randomUUID(), UUID.randomUUID());
}
PageData<IotHubInstalledItem> page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published,
new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)));
// 40k bind parameters would be over PostgreSQL's limit of 32767
assertThat(names(page)).containsExactly("b", "d");
}
@Test
public void withUpdates_withoutPublishedVersions_isEmpty() {
installFive();
Map<UUID, UUID> unpublished = new HashMap<>();
unpublished.put(unpublishedItemId, null);
assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, Map.of(), new PageLink(10)).getData()).isEmpty();
assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, unpublished, new PageLink(10)).getData()).isEmpty();
}
}

39
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<PageData<IotHubInstalledItem>> {
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<string, string>,
config?: IotHubRequestConfig): Observable<PageData<IotHubInstalledItem>> {
return this.http.post<PageData<IotHubInstalledItem>>(
`/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`,
publishedVersionIds,
{ params: this.buildParams(config) }
);
}
public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable<number> {
let url = '/api/iot-hub/installedItems/count';
if (itemType) {
@ -294,11 +303,18 @@ export class IotHubApiService {
}
public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable<ItemPublishedVersionInfo[]> {
return this.http.post<ItemPublishedVersionInfo[]>(
if (!itemIds.length) {
return of([]);
}
const chunks: string[][] = [];
for (let i = 0; i < itemIds.length; i += PUBLISHED_VERSIONS_CHUNK_SIZE) {
chunks.push(itemIds.slice(i, i + PUBLISHED_VERSIONS_CHUNK_SIZE));
}
return forkJoin(chunks.map(chunk => this.http.post<ItemPublishedVersionInfo[]>(
`${this.baseUrl}/api/versions/publishedVersions`,
itemIds,
chunk,
{ params: this.buildParams(config) }
);
))).pipe(map(results => results.flat()));
}
public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable<CreatorView> {
@ -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)

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

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

146
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<string, string> {
const ids: Record<string, string> = {};
this.publishedVersionMap.forEach((info, itemId) => {
if (info.publishedVersionId) {
ids[itemId] = info.publishedVersionId;
}
});
return ids;
}
retryLoad(): void {
this.loadData();
if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) {
this.loadUpdatesCount();
}
}
private reloadAfterChange(): void {
if (!this.updatesChecked || this.itemVersion) {
this.loadData();
return;
}
this.loadUpdatesCount(() => {
if (this.onlyUpdates && this.updatesCount === 0) {
this.showOnlyUpdates(false);
} else {
this.loadData();
}
}, () => {
// Count failed: fall back to the full list
if (this.onlyUpdates) {
this.showOnlyUpdates(false);
} else {
this.loadData();
}
});
}
// Latest call wins; previous counts stay until it returns
private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void {
const run = ++this.countRun;
const config = { ignoreLoading: true, ignoreErrors: true };
forkJoin({
withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), config),
installed: this.iotHubApiService.getInstalledItemsCount(undefined, config)
}).subscribe({
next: ({ withUpdates, installed }) => {
if (run !== this.countRun) {
return;
}
this.updatesCount = withUpdates.totalElements;
this.installedCount = installed;
this.updatesCheckFailed = false;
this.isCheckingUpdates = false;
this.cd.markForCheck();
onCounts?.();
},
error: () => {
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;
}
});

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

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

23
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-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);
}
}

6
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",

Loading…
Cancel
Save