diff --git a/docs/decisions/2026-12-04-getfeedcounts-is-kept-for-collate.md b/docs/decisions/2026-12-04-getfeedcounts-is-kept-for-collate.md new file mode 100644 index 000000000000..e7eff6ffeb44 --- /dev/null +++ b/docs/decisions/2026-12-04-getfeedcounts-is-kept-for-collate.md @@ -0,0 +1,27 @@ +# `getFeedCounts` stays exported, in its callback form, until openmetadata-collate stops calling it + +- **Status:** Accepted +- **Revisions:** v1 2026-12-04 (initial) +- **Deciders:** harsh-vador +- **Guard:** `src/utils/FeedUtilsPure.getFeedCounts.test.ts` (openmetadata-ui) calls the callback form; `reviewer` for removal +- **Related:** #39791, open-metadata/openmetadata-collate#9240, open-metadata/openmetadata-collate#9311 + +## Context +#39791 moved every OpenMetadata entity page to `useEntityFeedCounts`. After it, nothing in this +repository calls `getFeedCounts` in `openmetadata-ui/.../utils/FeedUtilsPure.ts`. openmetadata-collate +still does: its Observability `PipelineDetails` reloads its counts with +`getFeedCounts(EntityType.PIPELINE, fqn, callback)`. Collate compiles against this repository's +`main` through a submodule, so deleting the export, or changing its signature, breaks the Collate +build, and nothing here would warn about it. + +## Decision +`getFeedCounts(entityType, entityFQN, callback)` stays exported from `utils/FeedUtilsPure.ts` with +that signature. It calls `callback` with a full `FeedCounts` built by the same fetchers the hook +uses, and shows the `server.entity-feed-fetch-error` toast on failure. The `domain` overload +removed in #39791 had no caller in either repository. + +## Consequences +New OpenMetadata code uses `useEntityFeedCounts`, never `getFeedCounts`. The export goes away in two +steps: +1. openmetadata-collate#9311 moves Collate's page to the hook. +2. An OpenMetadata PR deletes `getFeedCounts` and marks this record superseded. diff --git a/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.test.tsx index daa614a26021..ea490fe3e575 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.test.tsx @@ -91,8 +91,13 @@ jest.mock('../../../utils/useRequiredParams', () => ({ }), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../../utils/TablePureUtils', () => ({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.tsx b/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.tsx index a5a388da62fb..264d36be61a7 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/APIEndpoint/APIEndpointDetails/APIEndpointDetails.tsx @@ -15,11 +15,10 @@ import { Box, ButtonUtility, Tabs } from '@openmetadata/ui-core-components'; import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import { FQN_SEPARATOR_CHAR } from '../../../constants/char.constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { Tag } from '../../../generated/entity/classification/tag'; import { APIEndpoint } from '../../../generated/entity/data/apiEndpoint'; @@ -27,8 +26,8 @@ import { PageType } from '../../../generated/system/ui/page'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreApiEndPoint } from '../../../rest/apiEndpointsAPI'; import apiEndpointClassBase from '../../../utils/APIEndpoints/APIEndpointClassBase'; import { @@ -38,11 +37,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -81,9 +75,8 @@ const APIEndpointDetails: React.FC = ({ const { entityFqn: decodedApiEndpointFqn } = useFqn({ type: EntityType.API_ENDPOINT, }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.API_ENDPOINT, decodedApiEndpointFqn); const { customizedPage, isLoading } = useCustomPages(PageType.APIEndpoint); const [isTabExpanded, setIsTabExpanded] = useState(false); @@ -178,33 +171,6 @@ const APIEndpointDetails: React.FC = ({ return onApiEndpointUpdate(updatedApiEndpointDetails, 'tags'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts( - EntityType.API_ENDPOINT, - decodedApiEndpointFqn, - handleFeedCount - ); - - const fetchTaskCounts = useCallback(() => { - if (decodedApiEndpointFqn) { - fetchEntityTaskCountsInto(decodedApiEndpointFqn, setFeedCount); - } - }, [decodedApiEndpointFqn]); - - const fetchActivityCount = useCallback(() => { - if (decodedApiEndpointFqn) { - fetchEntityActivityCountInto( - EntityType.API_ENDPOINT, - decodedApiEndpointFqn, - setFeedCount - ); - } - }, [decodedApiEndpointFqn]); - // The endpoint FQN is service.collection.endpoint, so the positional // Service+Database parts yield the collection FQN when the loaded entity // doesn't carry its apiCollection reference. @@ -250,11 +216,6 @@ const APIEndpointDetails: React.FC = ({ }; }, [apiEndpointPermissions, deleted]); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [apiEndpointPermissions, decodedApiEndpointFqn]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); const tabs = apiEndpointClassBase.getAPIEndpointDetailPageTabs({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.test.tsx index f147bfc9a99f..99b60fd1ca41 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.test.tsx @@ -120,10 +120,13 @@ jest.mock('../../../utils/useRequiredParams', () => ({ }), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.tsx index 180b80df109b..1d5572560c76 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Chart/ChartDetails/ChartDetails.component.tsx @@ -18,7 +18,6 @@ import { AxiosError } from 'axios'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ResourceEntity } from '../../../enums/permissions.enum'; import { ServiceCategory } from '../../../enums/service.enum'; @@ -28,9 +27,9 @@ import { PageType } from '../../../generated/system/ui/page'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreChart } from '../../../rest/chartsAPI'; import chartDetailsClassBase from '../../../utils/ChartDetailsClassBase'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; @@ -41,11 +40,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; import { @@ -81,9 +75,6 @@ const ChartDetails = ({ const { customizedPage, isLoading } = useCustomPages('Chart' as PageType); const { entityFqn: decodedChartFQN } = useFqn({ type: EntityType.CHART }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const [isTabExpanded, setIsTabExpanded] = useState(false); const { followers = [], deleted } = useMemo(() => { @@ -122,33 +113,8 @@ const ChartDetails = ({ } }, [permissionsError]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.CHART, decodedChartFQN, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedChartFQN) { - fetchEntityTaskCountsInto(decodedChartFQN, setFeedCount); - } - }, [decodedChartFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedChartFQN) { - fetchEntityActivityCountInto( - EntityType.CHART, - decodedChartFQN, - setFeedCount - ); - } - }, [decodedChartFQN]); - - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [decodedChartFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.CHART, decodedChartFQN); const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.test.tsx index 36ace6939a9f..98f1ddabb491 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.test.tsx @@ -118,10 +118,13 @@ jest.mock('../../../utils/useRequiredParams', () => ({ }), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.tsx index 0c2429a5d8ab..6de3bf0a5e6a 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DashboardDetails/DashboardDetails.component.tsx @@ -18,7 +18,6 @@ import { AxiosError } from 'axios'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ResourceEntity } from '../../../enums/permissions.enum'; import { ServiceCategory } from '../../../enums/service.enum'; @@ -28,9 +27,9 @@ import { PageType } from '../../../generated/system/ui/uiCustomization'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreDashboard } from '../../../rest/dashboardAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -41,11 +40,6 @@ import { } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import dashboardDetailsClassBase from '../../../utils/DashboardDetailsClassBase'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; import { @@ -83,9 +77,8 @@ const DashboardDetails = ({ const { entityFqn: decodedDashboardFQN } = useFqn({ type: EntityType.DASHBOARD, }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.DASHBOARD, decodedDashboardFQN); const [isTabExpanded, setIsTabExpanded] = useState(false); const { @@ -133,34 +126,6 @@ const DashboardDetails = ({ } }, [permissionsError]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.DASHBOARD, decodedDashboardFQN, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedDashboardFQN) { - fetchEntityTaskCountsInto(decodedDashboardFQN, setFeedCount); - } - }, [decodedDashboardFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedDashboardFQN) { - fetchEntityActivityCountInto( - EntityType.DASHBOARD, - decodedDashboardFQN, - setFeedCount - ); - } - }, [decodedDashboardFQN]); - - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [decodedDashboardFQN]); - const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { navigate( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.test.tsx index 2ae9a34298a0..4f111676faa6 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.test.tsx @@ -86,10 +86,13 @@ jest.mock('../../../../utils/useRequiredParams', () => ({ }), })); -jest.mock('../../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.tsx index c9d99a90f74e..8dc578dc81a6 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Dashboard/DataModel/DataModels/DataModelDetails.component.tsx @@ -16,18 +16,17 @@ import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; import { isUndefined, toString } from 'lodash'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../../enums/entity.enum'; import { ServiceCategory } from '../../../../enums/service.enum'; import { Tag } from '../../../../generated/entity/classification/tag'; import { DashboardDataModel } from '../../../../generated/entity/data/dashboardDataModel'; import { PageType } from '../../../../generated/system/ui/page'; import { useCustomPages } from '../../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../../hooks/useFqn'; -import { FeedCounts } from '../../../../interface/feed.interface'; import { restoreDataModel } from '../../../../rest/dataModelsAPI'; import connectionsRouterClassBase from '../../../../utils/ConnectionsRouterClassBase'; import { @@ -38,11 +37,6 @@ import { } from '../../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import dashboardDataModelClassBase from '../../../../utils/DashboardDataModelClassBase'; import { getEntityName } from '../../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../../utils/PermissionDerivation'; import { @@ -79,13 +73,12 @@ const DataModelDetails = ({ PageType.DashboardDataModel ); const [isTabExpanded, setIsTabExpanded] = useState(false); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const { entityFqn: decodedDataModelFQN } = useFqn({ type: EntityType.DASHBOARD_DATA_MODEL, }); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.DASHBOARD_DATA_MODEL, decodedDataModelFQN); const { deleted, version } = useMemo(() => { return { @@ -94,41 +87,6 @@ const DataModelDetails = ({ }; }, [dataModelData]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts( - EntityType.DASHBOARD_DATA_MODEL, - decodedDataModelFQN, - handleFeedCount - ); - }; - - const fetchTaskCounts = useCallback(() => { - if (decodedDataModelFQN) { - fetchEntityTaskCountsInto(decodedDataModelFQN, setFeedCount); - } - }, [decodedDataModelFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedDataModelFQN) { - fetchEntityActivityCountInto( - EntityType.DASHBOARD_DATA_MODEL, - decodedDataModelFQN, - setFeedCount - ); - } - }, [decodedDataModelFQN]); - - useEffect(() => { - if (decodedDataModelFQN) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [decodedDataModelFQN]); - const handleUpdateDisplayName = async (data: EntityName) => { if (isUndefined(dataModelData)) { return; diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.test.tsx index ac8b55f534ca..61439c4c82e6 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.test.tsx @@ -49,6 +49,15 @@ const setMockPermissions = ( }); }; +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), +})); + jest.mock('../../../hooks/useEntityPermissions/useEntityPermissions', () => ({ useEntityPermissions: (...args: unknown[]) => mockUseEntityPermissions(...args), diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.tsx index 902f614b38f7..9eeb5215315b 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DataProducts/DataProductsDetailsPage/DataProductsDetailsPage.component.tsx @@ -34,7 +34,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useLocation, useNavigate } from 'react-router-dom'; import { ROUTES } from '../../../constants/constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityField } from '../../../constants/Feeds.constants'; import { LEARNING_PAGE_IDS } from '../../../constants/Learning.constants'; import { AssetsOfEntity } from '../../../enums/Assets.enum'; @@ -53,6 +52,7 @@ import { useEntityDataContract } from '../../../hooks/governance/dataContract/us import { useActiveAnnouncements } from '../../../hooks/useActiveAnnouncements'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { useEntityRules } from '../../../hooks/useEntityRules'; import { useFqn } from '../../../hooks/useFqn'; @@ -61,7 +61,6 @@ import { QueryVote, VotingDataProps, } from '../../../interface/entity/vote.interface'; -import { FeedCounts } from '../../../interface/feed.interface'; import { exportDataProductToODPSYaml, getDataProductPortsView, @@ -80,11 +79,6 @@ import entityUtilClassBase from '../../../utils/EntityUtilClassBase'; import { getEntityVersionByField } from '../../../utils/EntityVersionUtilsPure'; import { getEntityVoteStatus } from '../../../utils/EntityVoteUtils'; import { downloadFile } from '../../../utils/Export/ExportUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getEntityAvatarProps } from '../../../utils/IconUtils'; import { getDataProductDetailsPath, @@ -514,8 +508,9 @@ const DataProductsDetailsPage = ({ const [previewAsset, setPreviewAsset] = useState(); const [assetCount, setAssetCount] = useState(0); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA + const { feedCount, getEntityFeedCount } = useEntityFeedCounts( + EntityType.DATA_PRODUCT, + dataProduct.fullyQualifiedName ); const [isAnnouncementDrawerOpen, setIsAnnouncementDrawerOpen] = useState(false); @@ -532,32 +527,6 @@ const DataProductsDetailsPage = ({ ); const [inputPortsCount, setInputPortsCount] = useState(0); const [outputPortsCount, setOutputPortsCount] = useState(0); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts( - EntityType.DATA_PRODUCT, - dataProduct.fullyQualifiedName ?? '', - handleFeedCount - ); - }; - - const fetchTaskCounts = useCallback(() => { - const fqn = dataProduct.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityTaskCountsInto(fqn, setFeedCount); - } - }, [dataProduct.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - const fqn = dataProduct.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityActivityCountInto(EntityType.DATA_PRODUCT, fqn, setFeedCount); - } - }, [dataProduct.fullyQualifiedName]); - const openAssetDrawer = useCallback(() => { setIsAssetDrawerOpen(true); }, []); @@ -897,8 +866,6 @@ const DataProductsDetailsPage = ({ useEffect(() => { fetchDataProductAssets(); - fetchTaskCounts(); - fetchActivityCount(); fetchPortCounts(); }, [dataProductFqn, fetchPortCounts]); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.test.tsx index a84fa67a8ac1..4286964a3722 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.test.tsx @@ -121,10 +121,13 @@ jest.mock('../../../rest/announcementsAPI', () => ({ jest.mock('../../../rest/searchAPI', () => ({ searchQuery: jest.fn().mockResolvedValue({ hits: { total: { value: 0 } } }), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityTaskCountsInto: jest.fn(), - fetchEntityActivityCountInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../common/atoms/drawer', () => ({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.tsx index 80c82ef80f13..3188b9cb68ea 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Domain/DomainDetails/DomainDetails.component.tsx @@ -43,7 +43,6 @@ import { AssetsTabRef } from '../../../components/Glossary/GlossaryTerms/tabs/As import EntityNameModal from '../../../components/Modals/EntityNameModal/EntityNameModal.component'; import { FQN_SEPARATOR_CHAR } from '../../../constants/char.constants'; import { ERROR_MESSAGE, ROUTES } from '../../../constants/constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityField } from '../../../constants/Feeds.constants'; import { LEARNING_PAGE_IDS } from '../../../constants/Learning.constants'; import { usePermissionProvider } from '../../../context/PermissionProvider/PermissionProvider'; @@ -60,10 +59,10 @@ import { Style } from '../../../generated/type/tagLabel'; import { useActiveAnnouncements } from '../../../hooks/useActiveAnnouncements'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { useMarketplaceStore } from '../../../hooks/useMarketplaceStore'; import { VotingDataProps } from '../../../interface/entity/vote.interface'; -import { FeedCounts } from '../../../interface/feed.interface'; import { addDataProducts, patchDataProduct, @@ -89,11 +88,6 @@ import { getEntityName } from '../../../utils/EntityNameUtils'; import entityUtilClassBase from '../../../utils/EntityUtilClassBase'; import { getEntityVersionByField } from '../../../utils/EntityVersionUtilsPure'; import { getEntityVoteStatus } from '../../../utils/EntityVoteUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { setCreateEntityFieldError, submitAndClose, @@ -251,8 +245,9 @@ const DomainDetails = ({ const [assetCount, setAssetCount] = useState(0); const [dataProductsCount, setDataProductsCount] = useState(0); const [subDomainsCount, setSubDomainsCount] = useState(0); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA + const { feedCount, getEntityFeedCount } = useEntityFeedCounts( + EntityType.DOMAIN, + domain.fullyQualifiedName ); const [isAnnouncementDrawerOpen, setIsAnnouncementDrawerOpen] = useState(false); @@ -394,32 +389,6 @@ const DomainDetails = ({ setIsDeleting(false); }, [domain, onDelete]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts( - EntityType.DOMAIN, - domain.fullyQualifiedName ?? '', - handleFeedCount - ); - }; - - const fetchTaskCounts = useCallback(() => { - const fqn = domain.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityTaskCountsInto(fqn, setFeedCount); - } - }, [domain.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - const fqn = domain.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityActivityCountInto(EntityType.DOMAIN, fqn, setFeedCount); - } - }, [domain.fullyQualifiedName]); - const handleDataProductSubmit = useCallback( async (data: DomainFormValues) => { const formData = transformDomainFormData( @@ -973,8 +942,6 @@ const DomainDetails = ({ useEffect(() => { fetchDomainAssets(); fetchDataProducts(); - fetchTaskCounts(); - fetchActivityCount(); }, [domain.fullyQualifiedName]); useEffect(() => { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.test.tsx index 189c0dcedc61..da140f084d56 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.test.tsx @@ -19,8 +19,8 @@ import { Directory } from '../../../generated/entity/data/directory'; import { LabelType, State, TagSource } from '../../../generated/type/tagLabel'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { ENTITY_PERMISSIONS } from '../../../mocks/Permissions.mock'; import { restoreDriveAsset } from '../../../rest/driveAPI'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -34,22 +34,11 @@ jest.mock('../../../hooks/useCustomPages'); jest.mock('../../../hooks/useFqn'); jest.mock('../../../utils/useRequiredParams'); jest.mock('../../../rest/driveAPI'); -const mockGetFeedCounts = jest.fn(); -const mockFetchEntityTaskCountsInto = jest.fn(); -const mockFetchEntityActivityCountInto = jest.fn(); jest.mock('../../../utils/EntityDisplayPureUtils', () => ({ getEntityMissingError: jest.fn(), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: ( - ...args: [EntityType, string, (data: FeedCounts) => void] - ) => mockFetchEntityActivityCountInto(...args), - fetchEntityTaskCountsInto: (...args: [string, (data: FeedCounts) => void]) => - mockFetchEntityTaskCountsInto(...args), - getFeedCounts: (...args: [EntityType, string, (data: FeedCounts) => void]) => - mockGetFeedCounts(...args), -})); +jest.mock('../../../hooks/useEntityFeedCounts'); jest.mock('../../../utils/RouterUtils'); jest.mock('../../../utils/ToastUtils'); jest.mock('../../../utils/DirectoryClassBase', () => ({ @@ -138,6 +127,7 @@ const mockUseApplicationStore = useApplicationStore as jest.MockedFunction< typeof useApplicationStore >; const mockUseCustomPages = useCustomPages as jest.Mock; +const mockUseEntityFeedCounts = useEntityFeedCounts as jest.Mock; const mockUseFqn = useFqn as jest.Mock; const mockUseRequiredParams = useRequiredParams as jest.Mock; const mockRestoreDriveAsset = restoreDriveAsset as jest.Mock; @@ -259,8 +249,10 @@ describe('DirectoryDetails', () => { tab: EntityTabs.CHILDREN, }); - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(FEED_COUNT_INITIAL_DATA); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); mockGetEntityDetailsPath.mockReturnValue( @@ -336,14 +328,9 @@ describe('DirectoryDetails', () => { renderDirectoryDetails(); await waitFor(() => { - expect(mockFetchEntityTaskCountsInto).toHaveBeenCalledWith( - 'test-service.test-directory', - expect.any(Function) - ); - expect(mockFetchEntityActivityCountInto).toHaveBeenCalledWith( + expect(mockUseEntityFeedCounts).toHaveBeenCalledWith( EntityType.DIRECTORY, - 'test-service.test-directory', - expect.any(Function) + 'test-service.test-directory' ); }); }); @@ -585,8 +572,10 @@ describe('DirectoryDetails', () => { closedTaskCount: 3, }; - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(mockFeedCount); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: { ...FEED_COUNT_INITIAL_DATA, ...mockFeedCount }, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); renderDirectoryDetails(); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.tsx index d3933f4551df..58f1db253506 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Directory/DirectoryDetails.tsx @@ -16,17 +16,9 @@ import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; import { EntityTags } from 'Models'; -import { - lazy, - Suspense, - useCallback, - useEffect, - useMemo, - useState, -} from 'react'; +import { lazy, Suspense, useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ServiceCategory } from '../../../enums/service.enum'; import { Tag } from '../../../generated/entity/classification/tag'; @@ -37,8 +29,8 @@ import { TagLabel } from '../../../generated/type/tagLabel'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreDriveAsset } from '../../../rest/driveAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -50,11 +42,6 @@ import { import directoryClassBase from '../../../utils/DirectoryClassBase'; import { getEntityName } from '../../../utils/EntityNameUtils'; import { getEntityReferenceFromEntity } from '../../../utils/EntityReferenceUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -109,10 +96,6 @@ function DirectoryDetails({ type: EntityType.DIRECTORY, }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); - const { owners, deleted, @@ -270,28 +253,8 @@ function DirectoryDetails({ await onDirectoryUpdate(updatedDirectoryDetails, 'dataProducts'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.DIRECTORY, decodedDirectoryFQN, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedDirectoryFQN) { - fetchEntityTaskCountsInto(decodedDirectoryFQN, setFeedCount); - } - }, [decodedDirectoryFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedDirectoryFQN) { - fetchEntityActivityCountInto( - EntityType.DIRECTORY, - decodedDirectoryFQN, - setFeedCount - ); - } - }, [decodedDirectoryFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.DIRECTORY, decodedDirectoryFQN); const afterDeleteAction = useCallback( (isSoftDelete?: boolean) => @@ -321,11 +284,6 @@ function DirectoryDetails({ [directoryPermissions, deleted] ); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [directoryPermissions, decodedDirectoryFQN]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.test.tsx index 1e9cc2f84c89..fc1e619ba108 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.test.tsx @@ -19,6 +19,7 @@ import { File, FileType } from '../../../generated/entity/data/file'; import { LabelType, State, TagSource } from '../../../generated/type/tagLabel'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; import { ENTITY_PERMISSIONS } from '../../../mocks/Permissions.mock'; import { restoreDriveAsset } from '../../../rest/driveAPI'; @@ -33,20 +34,11 @@ jest.mock('../../../hooks/useCustomPages'); jest.mock('../../../hooks/useFqn'); jest.mock('../../../utils/useRequiredParams'); jest.mock('../../../rest/driveAPI'); -const mockGetFeedCounts = jest.fn(); -const mockFetchEntityTaskCountsInto = jest.fn(); -const mockFetchEntityActivityCountInto = jest.fn(); jest.mock('../../../utils/EntityDisplayPureUtils', () => ({ getEntityMissingError: jest.fn(), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: (...args: unknown[]) => - mockFetchEntityActivityCountInto(...args), - fetchEntityTaskCountsInto: (...args: unknown[]) => - mockFetchEntityTaskCountsInto(...args), - getFeedCounts: (...args: unknown[]) => mockGetFeedCounts(...args), -})); +jest.mock('../../../hooks/useEntityFeedCounts'); jest.mock('../../../utils/RouterUtils'); jest.mock('../../../utils/ToastUtils'); jest.mock('../../../utils/FileClassBase', () => ({ @@ -135,6 +127,7 @@ const mockUseApplicationStore = useApplicationStore as jest.MockedFunction< typeof useApplicationStore >; const mockUseCustomPages = useCustomPages as jest.Mock; +const mockUseEntityFeedCounts = useEntityFeedCounts as jest.Mock; const mockUseFqn = useFqn as jest.Mock; const mockUseRequiredParams = useRequiredParams as jest.Mock; const mockRestoreDriveAsset = restoreDriveAsset as jest.Mock; @@ -249,8 +242,10 @@ describe('FileDetails', () => { tab: EntityTabs.OVERVIEW, }); - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(FEED_COUNT_INITIAL_DATA); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); mockGetEntityDetailsPath.mockReturnValue( @@ -327,14 +322,9 @@ describe('FileDetails', () => { await waitFor( () => { - expect(mockFetchEntityTaskCountsInto).toHaveBeenCalledWith( - 'test-service.test-file.txt', - expect.any(Function) - ); - expect(mockFetchEntityActivityCountInto).toHaveBeenCalledWith( + expect(mockUseEntityFeedCounts).toHaveBeenCalledWith( EntityType.FILE, - 'test-service.test-file.txt', - expect.any(Function) + 'test-service.test-file.txt' ); }, { timeout: 3000 } @@ -621,8 +611,10 @@ describe('FileDetails', () => { closedTaskCount: 3, }; - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(mockFeedCount); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: { ...FEED_COUNT_INITIAL_DATA, ...mockFeedCount }, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); renderFileDetails(); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.tsx index 6f93d21c637a..d8b87eac8fbd 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/File/FileDetails.tsx @@ -14,17 +14,9 @@ import { Box, ButtonUtility, Tabs } from '@openmetadata/ui-core-components'; import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; -import { - lazy, - Suspense, - useCallback, - useEffect, - useMemo, - useState, -} from 'react'; +import { lazy, Suspense, useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ServiceCategory } from '../../../enums/service.enum'; import { Tag } from '../../../generated/entity/classification/tag'; @@ -33,8 +25,8 @@ import { PageType } from '../../../generated/system/ui/page'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreDriveAsset } from '../../../rest/driveAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -44,11 +36,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import fileClassBase from '../../../utils/FileClassBase'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; @@ -99,10 +86,6 @@ function FileDetails({ const { entityFqn: decodedFileFQN } = useFqn({ type: EntityType.FILE }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); - const { owners, deleted, @@ -190,28 +173,8 @@ function FileDetails({ return onFileUpdate(updatedFileDetails, 'tags'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.FILE, decodedFileFQN, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedFileFQN) { - fetchEntityTaskCountsInto(decodedFileFQN, setFeedCount); - } - }, [decodedFileFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedFileFQN) { - fetchEntityActivityCountInto( - EntityType.FILE, - decodedFileFQN, - setFeedCount - ); - } - }, [decodedFileFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.FILE, decodedFileFQN); const afterDeleteAction = useCallback( (isSoftDelete?: boolean) => @@ -238,11 +201,6 @@ function FileDetails({ [filePermissions, deleted] ); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [filePermissions, decodedFileFQN]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.test.tsx index 864403411510..a0eee2d46c36 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.test.tsx @@ -19,14 +19,10 @@ import { Spreadsheet } from '../../../generated/entity/data/spreadsheet'; import { LabelType, State, TagSource } from '../../../generated/type/tagLabel'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; import { ENTITY_PERMISSIONS } from '../../../mocks/Permissions.mock'; import { restoreDriveAsset } from '../../../rest/driveAPI'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; import { useRequiredParams } from '../../../utils/useRequiredParams'; import PageLayoutV1 from '../../PageLayoutV1/PageLayoutV1'; @@ -37,11 +33,7 @@ jest.mock('../../../hooks/useCustomPages'); jest.mock('../../../hooks/useFqn'); jest.mock('../../../utils/useRequiredParams'); jest.mock('../../../rest/driveAPI'); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - getFeedCounts: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - fetchEntityActivityCountInto: jest.fn(), -})); +jest.mock('../../../hooks/useEntityFeedCounts'); jest.mock('../../../utils/RouterUtils'); jest.mock('../../../utils/ToastUtils'); jest.mock('../../../utils/SpreadsheetClassBase', () => ({ @@ -124,13 +116,10 @@ const mockUseApplicationStore = useApplicationStore as jest.MockedFunction< typeof useApplicationStore >; const mockUseCustomPages = useCustomPages as jest.Mock; +const mockUseEntityFeedCounts = useEntityFeedCounts as jest.Mock; const mockUseFqn = useFqn as jest.Mock; const mockUseRequiredParams = useRequiredParams as jest.Mock; const mockRestoreDriveAsset = restoreDriveAsset as jest.Mock; -const mockGetFeedCounts = getFeedCounts as jest.Mock; -const mockFetchEntityTaskCountsInto = fetchEntityTaskCountsInto as jest.Mock; -const mockFetchEntityActivityCountInto = - fetchEntityActivityCountInto as jest.Mock; const mockGetEntityDetailsPath = getEntityDetailsPath as jest.Mock; const mockSpreadsheetDetails: Spreadsheet = { @@ -242,8 +231,10 @@ describe('SpreadsheetDetails', () => { tab: EntityTabs.WORKSHEETS, }); - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(FEED_COUNT_INITIAL_DATA); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); mockGetEntityDetailsPath.mockReturnValue( @@ -319,14 +310,9 @@ describe('SpreadsheetDetails', () => { renderSpreadsheetDetails(); await waitFor(() => { - expect(mockFetchEntityTaskCountsInto).toHaveBeenCalledWith( - 'test-service.test-spreadsheet', - expect.any(Function) - ); - expect(mockFetchEntityActivityCountInto).toHaveBeenCalledWith( + expect(mockUseEntityFeedCounts).toHaveBeenCalledWith( EntityType.SPREADSHEET, - 'test-service.test-spreadsheet', - expect.any(Function) + 'test-service.test-spreadsheet' ); }); }); @@ -542,8 +528,10 @@ describe('SpreadsheetDetails', () => { closedTaskCount: 3, }; - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(mockFeedCount); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: { ...FEED_COUNT_INITIAL_DATA, ...mockFeedCount }, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); renderSpreadsheetDetails(); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.tsx index 4be279a45dd6..2f39d5653137 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Spreadsheet/SpreadsheetDetails.tsx @@ -15,17 +15,9 @@ import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; import { EntityTags } from 'Models'; -import { - lazy, - Suspense, - useCallback, - useEffect, - useMemo, - useState, -} from 'react'; +import { lazy, Suspense, useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ServiceCategory } from '../../../enums/service.enum'; import { Tag } from '../../../generated/entity/classification/tag'; @@ -36,8 +28,8 @@ import { TagLabel } from '../../../generated/type/tagLabel'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreDriveAsset } from '../../../rest/driveAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -48,11 +40,6 @@ import { } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; import { getEntityReferenceFromEntity } from '../../../utils/EntityReferenceUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -103,10 +90,6 @@ function SpreadsheetDetails({ const { customizedPage, isLoading } = useCustomPages(PageType.Spreadsheet); const [isTabExpanded, setIsTabExpanded] = useState(false); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); - const { owners, deleted, @@ -248,32 +231,8 @@ function SpreadsheetDetails({ await onSpreadsheetUpdate(updatedSpreadsheetDetails, 'dataProducts'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts( - EntityType.SPREADSHEET, - decodedSpreadsheetFQN, - handleFeedCount - ); - - const fetchTaskCounts = useCallback(() => { - if (decodedSpreadsheetFQN) { - fetchEntityTaskCountsInto(decodedSpreadsheetFQN, setFeedCount); - } - }, [decodedSpreadsheetFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedSpreadsheetFQN) { - fetchEntityActivityCountInto( - EntityType.SPREADSHEET, - decodedSpreadsheetFQN, - setFeedCount - ); - } - }, [decodedSpreadsheetFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.SPREADSHEET, decodedSpreadsheetFQN); const afterDeleteAction = useCallback( (isSoftDelete?: boolean) => @@ -303,11 +262,6 @@ function SpreadsheetDetails({ [spreadsheetPermissions, deleted] ); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [spreadsheetPermissions, decodedSpreadsheetFQN]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.test.tsx index f9132b5fa458..8fce7d076bd7 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.test.tsx @@ -19,6 +19,7 @@ import { DataType, Worksheet } from '../../../generated/entity/data/worksheet'; import { LabelType, State, TagSource } from '../../../generated/type/tagLabel'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; import { ENTITY_PERMISSIONS } from '../../../mocks/Permissions.mock'; import { restoreDriveAsset } from '../../../rest/driveAPI'; @@ -33,20 +34,11 @@ jest.mock('../../../hooks/useCustomPages'); jest.mock('../../../hooks/useFqn'); jest.mock('../../../utils/useRequiredParams'); jest.mock('../../../rest/driveAPI'); -const mockGetFeedCounts = jest.fn(); -const mockFetchEntityTaskCountsInto = jest.fn(); -const mockFetchEntityActivityCountInto = jest.fn(); jest.mock('../../../utils/EntityDisplayPureUtils', () => ({ getEntityMissingError: jest.fn(), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: (...args: unknown[]) => - mockFetchEntityActivityCountInto(...args), - fetchEntityTaskCountsInto: (...args: unknown[]) => - mockFetchEntityTaskCountsInto(...args), - getFeedCounts: (...args: unknown[]) => mockGetFeedCounts(...args), -})); +jest.mock('../../../hooks/useEntityFeedCounts'); jest.mock('../../../utils/RouterUtils'); jest.mock('../../../utils/ToastUtils'); jest.mock('../../../utils/WorksheetClassBase', () => ({ @@ -129,6 +121,7 @@ const mockUseApplicationStore = useApplicationStore as jest.MockedFunction< typeof useApplicationStore >; const mockUseCustomPages = useCustomPages as jest.Mock; +const mockUseEntityFeedCounts = useEntityFeedCounts as jest.Mock; const mockUseFqn = useFqn as jest.Mock; const mockUseRequiredParams = useRequiredParams as jest.Mock; const mockRestoreDriveAsset = restoreDriveAsset as jest.Mock; @@ -267,8 +260,10 @@ describe('WorksheetDetails', () => { tab: EntityTabs.SCHEMA, }); - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(FEED_COUNT_INITIAL_DATA); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); mockGetEntityDetailsPath.mockReturnValue( @@ -345,14 +340,9 @@ describe('WorksheetDetails', () => { await waitFor( () => { - expect(mockFetchEntityTaskCountsInto).toHaveBeenCalledWith( - 'test-service.test-spreadsheet.test-worksheet', - expect.any(Function) - ); - expect(mockFetchEntityActivityCountInto).toHaveBeenCalledWith( + expect(mockUseEntityFeedCounts).toHaveBeenCalledWith( EntityType.WORKSHEET, - 'test-service.test-spreadsheet.test-worksheet', - expect.any(Function) + 'test-service.test-spreadsheet.test-worksheet' ); }, { timeout: 3000 } @@ -570,8 +560,10 @@ describe('WorksheetDetails', () => { closedTaskCount: 3, }; - mockGetFeedCounts.mockImplementation((_entityType, _fqn, callback) => { - callback(mockFeedCount); + mockUseEntityFeedCounts.mockReturnValue({ + feedCount: { ...FEED_COUNT_INITIAL_DATA, ...mockFeedCount }, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), }); renderWorksheetDetails(); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.tsx b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.tsx index dd6f4cdb3ca9..8865429f64fd 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/DriveService/Worksheet/WorksheetDetails.tsx @@ -15,17 +15,9 @@ import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; import { EntityTags } from 'Models'; -import { - lazy, - Suspense, - useCallback, - useEffect, - useMemo, - useState, -} from 'react'; +import { lazy, Suspense, useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ServiceCategory } from '../../../enums/service.enum'; import { Tag } from '../../../generated/entity/classification/tag'; @@ -36,7 +28,7 @@ import { TagLabel } from '../../../generated/type/tagLabel'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; -import { FeedCounts } from '../../../interface/feed.interface'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { restoreDriveAsset } from '../../../rest/driveAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -47,11 +39,6 @@ import { } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; import { getEntityReferenceFromEntity } from '../../../utils/EntityReferenceUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -103,10 +90,6 @@ function WorksheetDetails({ const { customizedPage, isLoading } = useCustomPages(PageType.Worksheet); const [isTabExpanded, setIsTabExpanded] = useState(false); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); - const { owners, deleted, @@ -248,31 +231,12 @@ function WorksheetDetails({ await onWorksheetUpdate(updatedWorksheetDetails, 'dataProducts'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts( + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts( EntityType.WORKSHEET, - worksheetDetails.fullyQualifiedName ?? '', - handleFeedCount + worksheetDetails.fullyQualifiedName ); - const fetchTaskCounts = useCallback(() => { - const fqn = worksheetDetails.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityTaskCountsInto(fqn, setFeedCount); - } - }, [worksheetDetails.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - const fqn = worksheetDetails.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityActivityCountInto(EntityType.WORKSHEET, fqn, setFeedCount); - } - }, [worksheetDetails.fullyQualifiedName]); - const afterDeleteAction = useCallback( (isSoftDelete?: boolean) => !isSoftDelete && @@ -304,13 +268,6 @@ function WorksheetDetails({ [worksheetPermissions, deleted] ); - useEffect(() => { - if (worksheetDetails.fullyQualifiedName) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [worksheetPermissions, worksheetDetails.fullyQualifiedName]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.component.tsx index 674268f9045f..3c959a90a53d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.component.tsx @@ -16,25 +16,19 @@ import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import classNames from 'classnames'; import { isEmpty, noop } from 'lodash'; -import { lazy, useCallback, useEffect, useMemo, useState } from 'react'; +import { lazy, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType } from '../../../enums/entity.enum'; import { PageType } from '../../../generated/system/ui/page'; import { useCustomPages } from '../../../hooks/useCustomPages'; -import type { FeedCounts } from '../../../interface/feed.interface'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { checkIfExpandViewSupported, getDetailsTabWithNewLabel, getRenderedActiveTab, getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getReviewTab } from '../../../utils/GlossaryUtils'; import { getGlossaryTermDetailsPath } from '../../../utils/RouterUtils'; import { useRequiredParams } from '../../../utils/useRequiredParams'; @@ -86,8 +80,9 @@ const GlossaryDetails = ({ const { t } = useTranslation(); const navigate = useNavigate(); const { activeGlossary: glossary } = useGlossaryStore(); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA + const { feedCount, getEntityFeedCount } = useEntityFeedCounts( + EntityType.GLOSSARY, + glossary.fullyQualifiedName ); const { onAddGlossaryTerm } = useGlossaryStore(); @@ -95,32 +90,6 @@ const GlossaryDetails = ({ const { tab: activeTab } = useRequiredParams<{ tab: EntityTabs }>(); const { customizedPage, isLoading } = useCustomPages(PageType.Glossary); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts( - EntityType.GLOSSARY, - glossary.fullyQualifiedName ?? '', - handleFeedCount - ); - }; - - const fetchTaskCounts = useCallback(() => { - const fqn = glossary.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityTaskCountsInto(fqn, setFeedCount); - } - }, [glossary.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - const fqn = glossary.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityActivityCountInto(EntityType.GLOSSARY, fqn, setFeedCount); - } - }, [glossary.fullyQualifiedName]); - const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { navigate( @@ -152,7 +121,7 @@ const GlossaryDetails = ({ entityFqn: glossary.fullyQualifiedName ?? '', name: tabLabelMap[EntityTabs.REVIEW], openTaskCount: feedCount.openTaskCount, - onTasksChange: fetchTaskCounts, + onTasksChange: getEntityFeedCount, }), { label: ( @@ -215,15 +184,11 @@ const GlossaryDetails = ({ // Activity and task reads resolve separately, and the tab body consumes // the complete count object as well as the total shown in its label. feedCount, - fetchTaskCounts, + getEntityFeedCount, activeTab, isVersionView, ]); - useEffect(() => { - Promise.all([fetchTaskCounts(), fetchActivityCount()]); - }, [glossary.fullyQualifiedName]); - const isExpandViewSupported = useMemo( () => checkIfExpandViewSupported(tabs[0], activeTab, PageType.Glossary), [tabs[0], activeTab] diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.test.tsx index 63498e38b26f..0c8c97f5ea62 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryDetails/GlossaryDetails.test.tsx @@ -20,6 +20,15 @@ import { } from '../../../mocks/Glossary.mock'; import GlossaryDetails from './GlossaryDetails.component'; +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), +})); + jest.mock('../GlossaryTermTab/GlossaryTermTab.component', () => { return jest.fn().mockReturnValue(

GlossaryTermTab.component

); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx index b5bee2d32ee3..0a6d3b14d17d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx @@ -17,7 +17,6 @@ import classNames from 'classnames'; import { lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityField } from '../../../constants/Feeds.constants'; import { AssetsOfEntity } from '../../../enums/Assets.enum'; import { EntityTabs, EntityType } from '../../../enums/entity.enum'; @@ -32,8 +31,8 @@ import { } from '../../../generated/entity/data/glossaryTerm'; import { PageType } from '../../../generated/system/ui/page'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { MOCK_GLOSSARY_NO_PERMISSIONS } from '../../../mocks/Glossary.mock'; import { searchQuery } from '../../../rest/searchAPI'; import { @@ -43,11 +42,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityVersionByField } from '../../../utils/EntityVersionUtilsPure'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import glossaryTermClassBase from '../../../utils/Glossary/GlossaryTermClassBase'; import { getQueryFilterToExcludeTerm } from '../../../utils/GlossaryPureUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; @@ -91,8 +85,10 @@ const GlossaryTermsV1 = ({ const navigate = useNavigate(); const assetTabRef = useRef(null); const [assetModalVisible, setAssetModalVisible] = useState(false); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA + const { feedCount, getEntityFeedCount } = useEntityFeedCounts( + EntityType.GLOSSARY_TERM, + glossaryTerm.fullyQualifiedName, + { enabled: !isVersionView } ); const [assetCount, setAssetCount] = useState(0); const [previewAsset, setPreviewAsset] = @@ -122,32 +118,6 @@ const GlossaryTermsV1 = ({ ); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts( - EntityType.GLOSSARY_TERM, - glossaryTerm.fullyQualifiedName ?? '', - handleFeedCount - ); - }; - - const fetchTaskCounts = useCallback(() => { - const fqn = glossaryTerm.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityTaskCountsInto(fqn, setFeedCount); - } - }, [glossaryTerm.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - const fqn = glossaryTerm.fullyQualifiedName ?? ''; - if (fqn) { - fetchEntityActivityCountInto(EntityType.GLOSSARY_TERM, fqn, setFeedCount); - } - }, [glossaryTerm.fullyQualifiedName]); - const fetchGlossaryTermAssets = async () => { if (glossaryTerm) { try { @@ -246,9 +216,6 @@ const GlossaryTermsV1 = ({ const assetCountTimer = setTimeout(() => { fetchGlossaryTermAssets(); }, 500); - if (!isVersionView) { - Promise.all([fetchTaskCounts(), fetchActivityCount()]); - } // A term left within the wait must not search for its assets afterwards. return () => clearTimeout(assetCountTimer); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.test.tsx index d4b872e22f65..44baf38454fc 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.test.tsx @@ -13,18 +13,15 @@ import { render, screen } from '@testing-library/react'; import { OperationPermission } from '../../../context/PermissionProvider/PermissionProvider.interface'; -import { EntityTabs } from '../../../enums/entity.enum'; +import { EntityTabs, EntityType } from '../../../enums/entity.enum'; import { EntityReference } from '../../../generated/entity/type'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { mockedGlossaryTerms, MOCK_ASSETS_DATA, MOCK_PERMISSIONS, } from '../../../mocks/Glossary.mock'; import { searchQuery } from '../../../rest/searchAPI'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, -} from '../../../utils/FeedUtilsPure'; import glossaryTermClassBase from '../../../utils/Glossary/GlossaryTermClassBase'; import { useRequiredParams } from '../../../utils/useRequiredParams'; import { useGenericContext } from '../../Customization/GenericProvider/GenericContext'; @@ -32,25 +29,14 @@ import GlossaryTerms from './GlossaryTermsV1.component'; const mockPush = jest.fn(); -jest.mock('../../../utils/FeedUtilsPure', () => { - const actual = jest.requireActual('../../../utils/FeedUtilsPure'); - - return { - ...actual, - fetchEntityTaskCountsInto: jest.fn(actual.fetchEntityTaskCountsInto), - fetchEntityActivityCountInto: jest.fn(actual.fetchEntityActivityCountInto), - }; -}); - -const restoreFeedCountFetchers = () => { - const actual = jest.requireActual('../../../utils/FeedUtilsPure'); - (fetchEntityTaskCountsInto as jest.Mock).mockImplementation( - actual.fetchEntityTaskCountsInto - ); - (fetchEntityActivityCountInto as jest.Mock).mockImplementation( - actual.fetchEntityActivityCountInto - ); -}; +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), +})); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), @@ -241,12 +227,6 @@ describe('Test Glossary-term component', () => { }); it('should fetch feed counts on mount when not in version view', async () => { - const fetchTaskCountsSpy = ( - fetchEntityTaskCountsInto as jest.Mock - ).mockImplementation(jest.fn()); - const fetchActivityCountSpy = ( - fetchEntityActivityCountInto as jest.Mock - ).mockImplementation(jest.fn()); const useRequiredParamsMock = useRequiredParams as jest.Mock; useRequiredParamsMock.mockReturnValue({ tab: EntityTabs.OVERVIEW, @@ -257,19 +237,14 @@ describe('Test Glossary-term component', () => { await screen.findByTestId('glossary-term'); - expect(fetchTaskCountsSpy).toHaveBeenCalled(); - expect(fetchActivityCountSpy).toHaveBeenCalled(); - - restoreFeedCountFetchers(); + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.GLOSSARY_TERM, + mockProps.glossaryTerm.fullyQualifiedName, + { enabled: true } + ); }); it('should not fetch feed counts when in version view', async () => { - const fetchTaskCountsSpy = ( - fetchEntityTaskCountsInto as jest.Mock - ).mockImplementation(jest.fn()); - const fetchActivityCountSpy = ( - fetchEntityActivityCountInto as jest.Mock - ).mockImplementation(jest.fn()); const useRequiredParamsMock = useRequiredParams as jest.Mock; useRequiredParamsMock.mockReturnValue({ tab: EntityTabs.OVERVIEW, @@ -280,10 +255,11 @@ describe('Test Glossary-term component', () => { await screen.findByTestId('glossary-term'); - expect(fetchTaskCountsSpy).not.toHaveBeenCalled(); - expect(fetchActivityCountSpy).not.toHaveBeenCalled(); - - restoreFeedCountFetchers(); + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.GLOSSARY_TERM, + mockProps.glossaryTerm.fullyQualifiedName, + { enabled: false } + ); }); it('searches for the term’s assets only while its page is open', () => { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.test.tsx index f4abd4a389f8..0f3d498830be 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.test.tsx @@ -120,10 +120,13 @@ jest.mock('../../../utils/KnowledgePageUtils', () => ({ updateKnowledgeCenterRecentViewed: jest.fn(), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityTaskCountsInto: jest.fn(), - fetchEntityActivityCountInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../../utils/TagClassBase', () => ({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.tsx b/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.tsx index a9f16e2a387e..5d6c7d828020 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageDetailComponent/KnowledgePageDetailComponent.tsx @@ -49,7 +49,6 @@ import { SHORT_DELAY, } from '../../../constants/constants'; import { CustomizeEntityType } from '../../../constants/Customize.constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { getKnowledgePageFields, isKnowledgePageFullWidthTab, @@ -66,12 +65,12 @@ import { useArticleDraftStore, } from '../../../hooks/useArticleDraftStore'; import useCustomLocation from '../../../hooks/useCustomLocation/useCustomLocation'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { QueryVoteType, VotingDataProps, } from '../../../interface/entity/vote.interface'; -import { FeedCounts } from '../../../interface/feed.interface'; import { ContentChangeState, KnowledgeCenterPageProps, @@ -88,11 +87,6 @@ import { import { stripPendingUploadNodes } from '../../../utils/BlockEditorPureUtils'; import contextCenterClassBase from '../../../utils/ContextCenterClassBase'; import { withExtractionState } from '../../../utils/discovery/context-center/memoryExtraction.utils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import i18n from '../../../utils/i18next/LocalUtil'; import { getKnowledgePageName } from '../../../utils/KnowledgePagePureUtils'; import { @@ -199,9 +193,6 @@ const KnowledgePageDetailComponent: FC = ({ const [activeTab, setActiveTab] = useState( tab ?? EntityTabs.OVERVIEW ); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const [threadLink, setThreadLink] = useState(''); const [contentChangeState, setContentChangeState] = @@ -837,35 +828,10 @@ const KnowledgePageDetailComponent: FC = ({ } }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - if (knowledgePage?.fullyQualifiedName) { - getFeedCounts( - EntityType.KNOWLEDGE_PAGE, - knowledgePage.fullyQualifiedName, - handleFeedCount - ); - } - }; - - const fetchTaskCounts = useCallback(() => { - if (knowledgePage?.fullyQualifiedName) { - fetchEntityTaskCountsInto(knowledgePage.fullyQualifiedName, setFeedCount); - } - }, [knowledgePage?.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - if (knowledgePage?.fullyQualifiedName) { - fetchEntityActivityCountInto( - EntityType.KNOWLEDGE_PAGE, - knowledgePage.fullyQualifiedName, - setFeedCount - ); - } - }, [knowledgePage?.fullyQualifiedName]); + const { feedCount, getEntityFeedCount } = useEntityFeedCounts( + EntityType.KNOWLEDGE_PAGE, + knowledgePage?.fullyQualifiedName + ); const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { @@ -1010,13 +976,6 @@ const KnowledgePageDetailComponent: FC = ({ } }, [fqn, hasViewPermission]); - useEffect(() => { - if (knowledgePage?.fullyQualifiedName) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [knowledgePage?.fullyQualifiedName]); - useEffect(() => { const handleBeforeUnload = (event: BeforeUnloadEvent) => { if (isContentUnsaved) { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.test.tsx index 5248d14bd63d..fc722f16d5ec 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.test.tsx @@ -98,10 +98,13 @@ jest.mock('../../../utils/useRequiredParams', () => ({ }), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.tsx index 93d02325d844..95f25812e928 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.tsx @@ -20,12 +20,11 @@ import { import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import { AxiosError } from 'axios'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import { ROUTES } from '../../../constants/constants'; import { CustomizeEntityType } from '../../../constants/Customize.constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { AssetsOfEntity } from '../../../enums/Assets.enum'; import { EntityTabs, EntityType } from '../../../enums/entity.enum'; import { Tag } from '../../../generated/entity/classification/tag'; @@ -34,9 +33,9 @@ import { PageType } from '../../../generated/system/ui/page'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; import { useMetricLinkedAssets } from '../../../hooks/useMetricLinkedAssets'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreMetric } from '../../../rest/metricsAPI'; import { checkIfExpandViewSupported, @@ -45,11 +44,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import metricDetailsClassBase from '../../../utils/MetricEntityUtils/MetricDetailsClassBase'; import { getMetricAssetSelectionQueryFilter } from '../../../utils/MetricEntityUtils/MetricPureUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; @@ -91,9 +85,8 @@ const MetricDetails: React.FC = ({ const { entityFqn: decodedMetricFqn } = useFqn({ type: EntityType.METRIC }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.METRIC, decodedMetricFqn); const { customizedPage, isLoading } = useCustomPages(PageType.Metric); const [isTabExpanded, setIsTabExpanded] = useState(false); const [isAssetModalOpen, setIsAssetModalOpen] = useState(false); @@ -204,29 +197,6 @@ const MetricDetails: React.FC = ({ return onMetricUpdate(updatedMetricDetails, 'tags'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.METRIC, decodedMetricFqn, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedMetricFqn) { - fetchEntityTaskCountsInto(decodedMetricFqn, setFeedCount); - } - }, [decodedMetricFqn]); - - const fetchActivityCount = useCallback(() => { - if (decodedMetricFqn) { - fetchEntityActivityCountInto( - EntityType.METRIC, - decodedMetricFqn, - setFeedCount - ); - } - }, [decodedMetricFqn]); - // A soft-deleted metric stays on this page, so it is shown as deleted as soon as the delete // job is accepted. If the job then fails, fetchMetricDetails restores the server's state. const afterDeleteAction = useCallback( @@ -288,11 +258,6 @@ const MetricDetails: React.FC = ({ } }, [refreshAssets, activeTab, decodedMetricFqn]); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [metricPermissions, decodedMetricFqn]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); const tabs = metricDetailsClassBase.getMetricDetailPageTabs({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.test.tsx index 6d04646568f2..2b3d823ce811 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.test.tsx @@ -254,10 +254,13 @@ jest.mock('../../../context/PermissionProvider/PermissionProvider', () => ({ })), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../AppRouter/withActivityFeed', () => ({ @@ -316,7 +319,7 @@ jest.mock('../../common/CustomPropertyTable/CustomPropertyTable', () => ({ // --- Additional mocks for the permission-conversion tests below, on top of the shared // mocks above. `useFqn`, `useCustomPages`, `useApplicationStore`, `useRequiredParams`, -// `DataAssetsHeader`, `GenericProvider`, `LimitWrapper` and `FeedUtilsPure` are already +// `DataAssetsHeader`, `GenericProvider`, `LimitWrapper` and `useEntityFeedCounts` are already // mocked above and reused as-is — re-registering them here would silently win (last // `jest.mock` call for a given path wins) and diverge from the suite below. In particular, // `useRequiredParams` must stay the dynamic `mockParams`-backed mock above: the suite below diff --git a/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.tsx index cd80953e95ae..41cbab13e18b 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/MlModel/MlModelDetail/MlModelDetail.component.tsx @@ -23,7 +23,6 @@ import { isEmpty } from 'lodash'; import { FC, useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ResourceEntity } from '../../../enums/permissions.enum'; import { ServiceCategory } from '../../../enums/service.enum'; @@ -34,9 +33,9 @@ import { PageType } from '../../../generated/system/ui/page'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../../hooks/useFqn'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restoreMlmodel } from '../../../rest/mlModelAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -46,11 +45,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import mlModelDetailsClassBase from '../../../utils/MlModel/MlModelClassBase'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -108,9 +102,6 @@ const MlModelDetail: FC = ({ const [isTabExpanded, setIsTabExpanded] = useState(false); const { entityFqn: decodedMlModelFqn } = useFqn({ type: EntityType.MLMODEL }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const mlModelName = useMemo( () => getEntityName(mlModelDetail), @@ -160,35 +151,13 @@ const MlModelDetail: FC = ({ }; }, [mlModelDetail, mlModelName]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const fetchEntityFeedCount = () => - getFeedCounts(EntityType.MLMODEL, decodedMlModelFqn, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedMlModelFqn) { - fetchEntityTaskCountsInto(decodedMlModelFqn, setFeedCount); - } - }, [decodedMlModelFqn]); - - const fetchActivityCount = useCallback(() => { - if (decodedMlModelFqn) { - fetchEntityActivityCountInto( - EntityType.MLMODEL, - decodedMlModelFqn, - setFeedCount - ); - } - }, [decodedMlModelFqn]); - - useEffect(() => { - if (hasViewAccess) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [hasViewAccess, decodedMlModelFqn]); + const { + feedCount, + getEntityFeedCount: fetchEntityFeedCount, + handleFeedCount, + } = useEntityFeedCounts(EntityType.MLMODEL, decodedMlModelFqn, { + enabled: hasViewAccess, + }); const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.component.tsx index 085d0bb8e5c1..ea3154b58725 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.component.tsx @@ -19,7 +19,6 @@ import { EntityTags } from 'Models'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ResourceEntity } from '../../../enums/permissions.enum'; import { ServiceCategory } from '../../../enums/service.enum'; @@ -29,8 +28,8 @@ import { PageType } from '../../../generated/system/ui/uiCustomization'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; -import { FeedCounts } from '../../../interface/feed.interface'; import { restorePipeline } from '../../../rest/pipelineAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -40,11 +39,6 @@ import { getTabLabelMapFromTabs, } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import pipelineClassBase from '../../../utils/PipelineClassBase'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -103,10 +97,6 @@ const PipelineDetails = ({ // local state variables const { customizedPage, isLoading } = useCustomPages(PageType.Pipeline); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); - // Single useEntityPermissions call, by id — no genuine cycle here (contrast // TableDetailsPageV1.tsx's two-call pattern): unlike a fetch-owning page, this // component already receives {@code pipelineDetails} (and therefore @@ -138,28 +128,8 @@ const PipelineDetails = ({ } }, [permissionsError]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.PIPELINE, pipelineFQN, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (pipelineFQN) { - fetchEntityTaskCountsInto(pipelineFQN, setFeedCount); - } - }, [pipelineFQN]); - - const fetchActivityCount = useCallback(() => { - if (pipelineFQN) { - fetchEntityActivityCountInto( - EntityType.PIPELINE, - pipelineFQN, - setFeedCount - ); - } - }, [pipelineFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.PIPELINE, pipelineFQN); const isFollowing = useMemo( () => followers.some(({ id }: { id: string }) => id === userID), @@ -272,11 +242,6 @@ const PipelineDetails = ({ [pipelineFQN] ); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [pipelineFQN]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.test.tsx index 76528c833e1e..7a76bc610843 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Pipeline/PipelineDetails/PipelineDetails.test.tsx @@ -199,8 +199,13 @@ jest.mock('../../common/CustomPropertyTable/CustomPropertyTable', () => ({ .mockReturnValue(

CustomPropertyTable.component

), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - getFeedCounts: jest.fn().mockReturnValue({}), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../../utils/TagsUtils', () => ({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.test.tsx index 39adf2e6350c..acf47f7fed86 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.test.tsx @@ -97,10 +97,13 @@ jest.mock('../../../utils/useRequiredParams', () => ({ }), })); -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../../utils/TableUtils', () => ({ diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.tsx index 5cbff1ccffbe..ebd0a4cac677 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Topic/TopicDetails/TopicDetails.component.tsx @@ -16,10 +16,9 @@ import { Collapse, Expand } from '@openmetadata/ui-core-components/icons'; import type { AxiosError } from 'axios'; import type { EntityTags } from 'Models'; -import { lazy, useCallback, useEffect, useMemo, useState } from 'react'; +import { lazy, useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../../enums/entity.enum'; import { ServiceCategory } from '../../../enums/service.enum'; import type { Tag } from '../../../generated/entity/classification/tag'; @@ -30,8 +29,8 @@ import type { TagLabel } from '../../../generated/type/schema'; import LimitWrapper from '../../../hoc/LimitWrapper'; import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useCustomPages } from '../../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useFqn } from '../../../hooks/useFqn'; -import type { FeedCounts } from '../../../interface/feed.interface'; import { restoreTopic } from '../../../rest/topicsAPI'; import connectionsRouterClassBase from '../../../utils/ConnectionsRouterClassBase'; import { @@ -42,11 +41,6 @@ import { } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../../utils/EntityNameUtils'; import { getEntityReferenceFromEntity } from '../../../utils/EntityReferenceUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; import { getEntityDetailsPath } from '../../../utils/RouterUtils'; @@ -157,9 +151,8 @@ const TopicDetails: React.FC = ({ const [isTabExpanded, setIsTabExpanded] = useState(false); const { entityFqn: decodedTopicFQN } = useFqn({ type: EntityType.TOPIC }); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.TOPIC, decodedTopicFQN); const { owners, @@ -309,29 +302,6 @@ const TopicDetails: React.FC = ({ await onTopicUpdate(updatedTopicDetails, 'dataProducts'); }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.TOPIC, decodedTopicFQN, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (decodedTopicFQN) { - fetchEntityTaskCountsInto(decodedTopicFQN, setFeedCount); - } - }, [decodedTopicFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedTopicFQN) { - fetchEntityActivityCountInto( - EntityType.TOPIC, - decodedTopicFQN, - setFeedCount - ); - } - }, [decodedTopicFQN]); - const afterDeleteAction = useCallback( (isSoftDelete?: boolean) => !isSoftDelete && @@ -381,11 +351,6 @@ const TopicDetails: React.FC = ({ }; }, [topicPermissions, deleted]); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [topicPermissions, decodedTopicFQN]); - const tabs = useMemo(() => { const tabLabelMap = getTabLabelMapFromTabs(customizedPage?.tabs); diff --git a/openmetadata-ui/src/main/resources/ui/src/hooks/useEntityFeedCounts.test.tsx b/openmetadata-ui/src/main/resources/ui/src/hooks/useEntityFeedCounts.test.tsx new file mode 100644 index 000000000000..e09db8d28eab --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/hooks/useEntityFeedCounts.test.tsx @@ -0,0 +1,176 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { ReactNode } from 'react'; +import { EntityType } from '../enums/entity.enum'; +import { getEntityActivityByFqn } from '../rest/activityAPI'; +import { listConversations } from '../rest/conversationsAPI'; +import { getTaskCounts } from '../rest/tasksAPI'; +import { showErrorToast } from '../utils/ToastUtils'; +import { useEntityFeedCounts } from './useEntityFeedCounts'; + +jest.mock('../rest/activityAPI', () => ({ + getEntityActivityByFqn: jest.fn(), +})); + +jest.mock('../rest/conversationsAPI', () => ({ + listConversations: jest.fn(), +})); + +jest.mock('../rest/tasksAPI', () => ({ + getTaskCounts: jest.fn(), +})); + +jest.mock('../utils/ToastUtils', () => ({ + showErrorToast: jest.fn(), +})); + +const mockTaskCounts = getTaskCounts as jest.Mock; +const mockActivity = getEntityActivityByFqn as jest.Mock; +const mockConversations = listConversations as jest.Mock; + +const FQN = 'svc.db.schema.orders'; + +const renderCounts = ( + fqn: string | undefined, + options?: Parameters[2] +) => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + + return renderHook(() => useEntityFeedCounts(EntityType.TABLE, fqn, options), { + wrapper, + }); +}; + +describe('useEntityFeedCounts', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockTaskCounts.mockResolvedValue({ total: 5, open: 2, completed: 3 }); + mockActivity.mockResolvedValue({ data: [], paging: { total: 4 } }); + mockConversations.mockResolvedValue({ data: [], paging: { total: 1 } }); + }); + + it('counts tasks, activity and conversations about the entity', async () => { + const { result } = renderCounts(FQN); + + await waitFor(() => expect(result.current.feedCount.totalCount).toBe(7)); + + expect(result.current.feedCount).toEqual({ + openTaskCount: 2, + closedTaskCount: 3, + totalTasksCount: 5, + activityCount: 4, + conversationCount: 1, + mentionCount: 0, + totalCount: 7, + }); + expect(mockTaskCounts).toHaveBeenCalledWith({ aboutEntity: FQN }); + expect(mockActivity).toHaveBeenCalledWith(EntityType.TABLE, FQN, { + days: 30, + limit: 0, + }); + expect(mockConversations).toHaveBeenCalledWith({ + entityLink: `<#E::table::${FQN}>`, + includeFields: true, + limit: 1, + }); + }); + + it.each([ + ['the page cannot read the entity yet', FQN, { enabled: false }], + ['there is no fqn', undefined, undefined], + ])('sends nothing while %s', async (_, fqn, options) => { + const { result } = renderCounts(fqn, options); + + await act(() => result.current.getEntityFeedCount()); + + expect(mockTaskCounts).not.toHaveBeenCalled(); + expect(mockActivity).not.toHaveBeenCalled(); + expect(result.current.feedCount.totalCount).toBe(0); + }); + + it('loads and reloads only the task counts without includeActivity', async () => { + const { result } = renderCounts(FQN, { includeActivity: false }); + + await waitFor(() => expect(result.current.feedCount.openTaskCount).toBe(2)); + await act(() => result.current.getEntityFeedCount()); + + expect(mockTaskCounts).toHaveBeenCalledTimes(2); + expect(mockActivity).not.toHaveBeenCalled(); + expect(mockConversations).not.toHaveBeenCalled(); + expect(result.current.feedCount.totalCount).toBe(2); + }); + + it('keeps the task counts and shows an error when the activity count fails', async () => { + const error = new Error('activity unavailable'); + mockActivity.mockRejectedValue(error); + + const { result } = renderCounts(FQN); + + await waitFor(() => + expect(showErrorToast).toHaveBeenCalledWith( + error, + 'server.entity-feed-fetch-error' + ) + ); + + expect(result.current.feedCount.openTaskCount).toBe(2); + expect(result.current.feedCount.activityCount).toBe(0); + }); + + it('reloads every count through getEntityFeedCount', async () => { + const { result } = renderCounts(FQN); + + await waitFor(() => expect(result.current.feedCount.totalCount).toBe(7)); + mockTaskCounts.mockResolvedValue({ total: 6, open: 3, completed: 3 }); + mockConversations.mockResolvedValue({ data: [], paging: { total: 2 } }); + await act(() => result.current.getEntityFeedCount()); + + await waitFor(() => expect(result.current.feedCount.totalCount).toBe(9)); + }); + + it('replaces the counts with the ones passed to handleFeedCount', async () => { + const { result } = renderCounts(FQN); + + await waitFor(() => expect(result.current.feedCount.totalCount).toBe(7)); + act(() => + result.current.handleFeedCount({ + openTaskCount: 1, + closedTaskCount: 0, + totalTasksCount: 1, + activityCount: 0, + conversationCount: 3, + mentionCount: 0, + totalCount: 4, + }) + ); + + await waitFor(() => + expect(result.current.feedCount).toEqual({ + openTaskCount: 1, + closedTaskCount: 0, + totalTasksCount: 1, + activityCount: 0, + conversationCount: 3, + mentionCount: 0, + totalCount: 4, + }) + ); + }); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/hooks/useEntityFeedCounts.ts b/openmetadata-ui/src/main/resources/ui/src/hooks/useEntityFeedCounts.ts new file mode 100644 index 000000000000..87b5ac6b0e12 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/hooks/useEntityFeedCounts.ts @@ -0,0 +1,117 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { AxiosError } from 'axios'; +import { useCallback, useEffect, useMemo } from 'react'; +import { useTranslation } from 'react-i18next'; +import { EntityType } from '../enums/entity.enum'; +import { FeedCounts } from '../interface/feed.interface'; +import { + buildFeedCounts, + fetchEntityActivityCounts, + fetchEntityTaskCounts, +} from '../utils/FeedUtilsPure'; +import { showErrorToast } from '../utils/ToastUtils'; + +export const ENTITY_FEED_COUNTS_QUERY_KEY = ['entityFeedCounts']; + +const NO_TASKS = { openTaskCount: 0, closedTaskCount: 0, totalTasksCount: 0 }; +const NO_ACTIVITY = { conversationCount: 0, activityCount: 0 }; + +interface UseEntityFeedCountsOptions { + /** False until the page may read the entity. */ + enabled?: boolean; + /** False when the page shows only the task counts. */ + includeActivity?: boolean; +} + +/** + * The feed and task counts of an entity page. Tasks and activity are separate + * queries, so one failing request leaves the other count in place. + * `getEntityFeedCount` reloads them and `handleFeedCount` replaces them. + */ +export const useEntityFeedCounts = ( + entityType: EntityType, + fqn: string | undefined, + { enabled = true, includeActivity = true }: UseEntityFeedCountsOptions = {} +) => { + const { t } = useTranslation(); + const queryClient = useQueryClient(); + const isEnabled = enabled && Boolean(fqn); + const isActivityEnabled = isEnabled && includeActivity; + const tasksKey = useMemo( + () => [...ENTITY_FEED_COUNTS_QUERY_KEY, 'tasks', fqn], + [fqn] + ); + const activityKey = useMemo( + () => [...ENTITY_FEED_COUNTS_QUERY_KEY, 'activity', entityType, fqn], + [entityType, fqn] + ); + + const tasks = useQuery({ + queryKey: tasksKey, + queryFn: () => fetchEntityTaskCounts(fqn ?? ''), + enabled: isEnabled, + }); + const activity = useQuery({ + queryKey: activityKey, + queryFn: () => fetchEntityActivityCounts(entityType, fqn ?? ''), + enabled: isActivityEnabled, + }); + + const error = tasks.error ?? activity.error; + + useEffect(() => { + if (error) { + showErrorToast(error as AxiosError, t('server.entity-feed-fetch-error')); + } + }, [error, t]); + + const feedCount = useMemo( + () => buildFeedCounts(tasks.data ?? NO_TASKS, activity.data ?? NO_ACTIVITY), + [tasks.data, activity.data] + ); + + const { refetch: refetchTasks } = tasks; + const { refetch: refetchActivity } = activity; + + const getEntityFeedCount = useCallback(async () => { + await Promise.all([ + isEnabled && refetchTasks(), + isActivityEnabled && refetchActivity(), + ]); + }, [isEnabled, isActivityEnabled, refetchTasks, refetchActivity]); + + const handleFeedCount = useCallback( + ({ + openTaskCount, + closedTaskCount, + totalTasksCount, + conversationCount, + activityCount, + }: FeedCounts) => { + queryClient.setQueryData(tasksKey, { + openTaskCount, + closedTaskCount, + totalTasksCount, + }); + queryClient.setQueryData(activityKey, { + conversationCount, + activityCount, + }); + }, + [queryClient, tasksKey, activityKey] + ); + + return { feedCount, getEntityFeedCount, handleFeedCount }; +}; diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.test.tsx index eb4c6a361ff6..c290a7653e76 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.test.tsx @@ -15,14 +15,14 @@ import { waitFor } from '@testing-library/react'; import { useParams } from 'react-router-dom'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { OperationPermission } from '../../context/PermissionProvider/PermissionProvider.interface'; -import { TabSpecificField } from '../../enums/entity.enum'; +import { EntityType, TabSpecificField } from '../../enums/entity.enum'; import { ResourceEntity } from '../../enums/permissions.enum'; import { Include } from '../../generated/type/include'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useFqn } from '../../hooks/useFqn'; import { getApiCollectionByFQN } from '../../rest/apiCollectionsAPI'; import { getApiEndPoints } from '../../rest/apiEndpointsAPI'; import { renderWithQueryClient } from '../../test/unit/test-utils'; -import { fetchEntityTaskCountsInto } from '../../utils/FeedUtilsPure'; import { getDerivedPermissionFlags } from '../../utils/PermissionDerivation'; import { showErrorToast } from '../../utils/ToastUtils'; import APICollectionPage from './APICollectionPage'; @@ -79,10 +79,13 @@ jest.mock('../../utils/EntityDisplayPureUtils', () => ({ jest.mock('../../utils/EntityNameUtils', () => ({ getEntityName: jest.fn().mockReturnValue('test-api-collection'), })); -jest.mock('../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../hooks/useFqn', () => ({ @@ -256,9 +259,10 @@ describe('APICollectionPage', () => { paging: { limit: 0 }, include: Include.NonDeleted, }); - expect(fetchEntityTaskCountsInto).toHaveBeenCalledWith( + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.API_COLLECTION, 'api.collection.v1', - expect.any(Function) + { enabled: true } ); }); @@ -287,16 +291,16 @@ describe('APICollectionPage', () => { paging: { limit: 0 }, include: Include.NonDeleted, }); - expect(fetchEntityTaskCountsInto).toHaveBeenCalledWith( + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.API_COLLECTION, 'api.collection.v2', - expect.any(Function) + { enabled: true } ); }); // Verify each API was called exactly once with new FQN expect(getApiCollectionByFQN).toHaveBeenCalledTimes(1); expect(getApiEndPoints).toHaveBeenCalledTimes(1); - expect(fetchEntityTaskCountsInto).toHaveBeenCalledTimes(1); }); it('should pass entity name as pageTitle to PageLayoutV1', async () => { diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.tsx index 58092f5b8dfa..9cd9786610b2 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/APICollectionPage/APICollectionPage.tsx @@ -42,7 +42,6 @@ import { useEntityExportModalProvider } from '../../components/Entity/EntityExpo import { EntityName } from '../../components/Modals/EntityNameModal/EntityNameModal.interface'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { ROUTES } from '../../constants/constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { ClientErrors } from '../../enums/Axios.enum'; import { EntityTabs, EntityType, FqnPart } from '../../enums/entity.enum'; import { ResourceEntity } from '../../enums/permissions.enum'; @@ -52,11 +51,11 @@ import { APICollection } from '../../generated/entity/data/apiCollection'; import { PageType } from '../../generated/system/ui/page'; import { Include } from '../../generated/type/include'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; import { useTableFilters } from '../../hooks/useTableFilters'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { patchApiCollection, restoreApiCollection, @@ -80,11 +79,6 @@ import { import { getEntityMissingError } from '../../utils/EntityDisplayPureUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; import entityUtilClassBase from '../../utils/EntityUtilClassBase'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { getEntityDetailsPath, getVersionPath } from '../../utils/RouterUtils'; import { @@ -102,9 +96,6 @@ const APICollectionPage: FunctionComponent = () => { const { showModal } = useEntityExportModalProvider(); const queryClient = useQueryClient(); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const [apiEndpointCount, setApiEndpointCount] = useState(0); const [isTabExpanded, setIsTabExpanded] = useState(false); const { filters, setFilters } = useTableFilters({ @@ -273,33 +264,10 @@ const APICollectionPage: FunctionComponent = () => { [apiCollection] ); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = useCallback(() => { - getFeedCounts( - EntityType.API_COLLECTION, - decodedAPICollectionFQN, - handleFeedCount - ); - }, [handleFeedCount, decodedAPICollectionFQN]); - - const fetchTaskCounts = useCallback(() => { - if (decodedAPICollectionFQN) { - fetchEntityTaskCountsInto(decodedAPICollectionFQN, setFeedCount); - } - }, [decodedAPICollectionFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedAPICollectionFQN) { - fetchEntityActivityCountInto( - EntityType.API_COLLECTION, - decodedAPICollectionFQN, - setFeedCount - ); - } - }, [decodedAPICollectionFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.API_COLLECTION, decodedAPICollectionFQN, { + enabled: viewAPICollectionPermission, + }); const getApiEndpointCount = useCallback(async () => { const res = await getApiEndPoints({ @@ -492,13 +460,6 @@ const APICollectionPage: FunctionComponent = () => { [setAPICollection] ); - useEffect(() => { - if (viewAPICollectionPermission) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [viewAPICollectionPermission, fetchTaskCounts, fetchActivityCount]); - useEffect(() => { if (viewAPICollectionPermission && decodedAPICollectionFQN) { getApiEndpointCount(); diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.test.tsx index 732246a3921d..6f86dba8962f 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.test.tsx @@ -215,10 +215,13 @@ jest.mock('../../utils/EntityDisplayPureUtils', () => ({ jest.mock('../../utils/RecentActivityUtils', () => ({ addToRecentViewed: jest.fn(), })); -jest.mock('../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn().mockReturnValue(0), +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../utils/TagsUtils', () => ({ sortTagsCaseInsensitive: jest.fn().mockImplementation((tags) => tags), diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.tsx index 2a789779b180..a612f0aa8dca 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/ContainerPage/ContainerPage.tsx @@ -32,7 +32,6 @@ import { EntityName } from '../../components/Modals/EntityNameModal/EntityNameMo import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { ROUTES } from '../../constants/constants'; import { CustomizeEntityType } from '../../constants/Customize.constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { ClientErrors } from '../../enums/Axios.enum'; import { EntityTabs, @@ -49,10 +48,10 @@ import { PageType } from '../../generated/system/ui/page'; import LimitWrapper from '../../hoc/LimitWrapper'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { containerQueryFn, containerQueryKey, @@ -77,11 +76,6 @@ import { } from '../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityMissingError } from '../../utils/EntityDisplayPureUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import Fqn from '../../utils/Fqn'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { addToRecentViewed } from '../../utils/RecentActivityUtils'; @@ -118,9 +112,8 @@ const ContainerPage = () => { const [isTabExpanded, setIsTabExpanded] = useState(false); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.CONTAINER, resolvedEntityFqn); const [childrenCount, setChildrenCount] = useState(0); // Two useEntityPermissions calls in this component, partitioned by deleted-sensitivity — @@ -279,30 +272,6 @@ const ContainerPage = () => { [refetchContainerData] ); - const handleFeedCount = useCallback( - (data: FeedCounts) => setFeedCount(data), - [] - ); - - const getEntityFeedCount = () => - getFeedCounts(EntityType.CONTAINER, resolvedEntityFqn, handleFeedCount); - - const fetchTaskCounts = useCallback(() => { - if (resolvedEntityFqn) { - fetchEntityTaskCountsInto(resolvedEntityFqn, setFeedCount); - } - }, [resolvedEntityFqn]); - - const fetchActivityCount = useCallback(() => { - if (resolvedEntityFqn) { - fetchEntityActivityCountInto( - EntityType.CONTAINER, - resolvedEntityFqn, - setFeedCount - ); - } - }, [resolvedEntityFqn]); - const { deleted, version, isUserFollowing } = useMemo(() => { return { deleted: containerData?.deleted, @@ -755,8 +724,6 @@ const ContainerPage = () => { } // Reset so a stale value from the previous container isn't shown. setChildrenCount(0); - fetchTaskCounts(); - fetchActivityCount(); // Eager-fetch the children total so the tab badge is correct even before // the user opens the Children tab. ContainerChildren is lazily mounted, so diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.test.tsx index ba76e2cef1cc..0024328b8033 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.test.tsx @@ -169,6 +169,15 @@ const mockGetServiceDataAssetsTabPath = jest .fn() .mockReturnValue('/service/databaseServices/bigquery/databases'); +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), +})); + jest.mock('../../utils/ConnectionsRouterClassBase', () => ({ __esModule: true, default: { diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.tsx index 7f8a6eeee961..6b1329aa475d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseDetailsPage/DatabaseDetailsPage.tsx @@ -41,7 +41,6 @@ import { useEntityExportModalProvider } from '../../components/Entity/EntityExpo import { EntityName } from '../../components/Modals/EntityNameModal/EntityNameModal.interface'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { ROUTES } from '../../constants/constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { GlobalSettingOptions } from '../../constants/GlobalSettings.constants'; import { ClientErrors } from '../../enums/Axios.enum'; import { EntityTabs, EntityType, FqnPart } from '../../enums/entity.enum'; @@ -53,10 +52,10 @@ import { PageType } from '../../generated/system/ui/uiCustomization'; import { useLocationSearch } from '../../hooks/LocationSearch/useLocationSearch'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { addFollowers, getDatabaseSchemas, @@ -82,11 +81,6 @@ import databaseClassBase from '../../utils/Database/DatabaseClassBase'; import { getEntityMissingError } from '../../utils/EntityDisplayPureUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; import entityUtilClassBase from '../../utils/EntityUtilClassBase'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { getEntityDetailsPath, @@ -212,9 +206,8 @@ const DatabaseDetails: FunctionComponent = () => { PageType.Database ); const [schemaInstanceCount, setSchemaInstanceCount] = useState(0); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.DATABASE, decodedDatabaseFQN); const [updateProfilerSetting, setUpdateProfilerSetting] = useState(false); @@ -329,30 +322,6 @@ const DatabaseDetails: FunctionComponent = () => { [decodedDatabaseFQN, databasePermission, database, showModal] ); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = useCallback(() => { - getFeedCounts(EntityType.DATABASE, decodedDatabaseFQN, handleFeedCount); - }, [decodedDatabaseFQN, handleFeedCount]); - - const fetchTaskCounts = useCallback(() => { - if (decodedDatabaseFQN) { - fetchEntityTaskCountsInto(decodedDatabaseFQN, setFeedCount); - } - }, [decodedDatabaseFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedDatabaseFQN) { - fetchEntityActivityCountInto( - EntityType.DATABASE, - decodedDatabaseFQN, - setFeedCount - ); - } - }, [decodedDatabaseFQN]); - const fetchDatabaseSchemaCount = useCallback(async () => { if (isEmpty(decodedDatabaseFQN)) { return; @@ -438,11 +407,6 @@ const DatabaseDetails: FunctionComponent = () => { [database, settingsUpdateHandler] ); - useEffect(() => { - fetchTaskCounts(); - fetchActivityCount(); - }, [decodedDatabaseFQN]); - useEffect(() => { if (withinPageSearch && serviceType && database) { navigate( diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.component.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.component.tsx index 24f860494406..d5513a9c6de4 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.component.tsx @@ -48,7 +48,6 @@ import { INITIAL_TABLE_FILTERS, ROUTES, } from '../../constants/constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { GlobalSettingOptions } from '../../constants/GlobalSettings.constants'; import { ClientErrors } from '../../enums/Axios.enum'; import { @@ -64,11 +63,11 @@ import { PageType } from '../../generated/system/ui/page'; import { Include } from '../../generated/type/include'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; import { useTableFilters } from '../../hooks/useTableFilters'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { addFollowers, patchDatabaseSchemaDetails, @@ -94,11 +93,6 @@ import databaseSchemaClassBase from '../../utils/DatabaseSchemaClassBase'; import { getEntityMissingError } from '../../utils/EntityDisplayPureUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; import entityUtilClassBase from '../../utils/EntityUtilClassBase'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { getEntityDetailsPath, getVersionPath } from '../../utils/RouterUtils'; import { @@ -123,9 +117,6 @@ const DatabaseSchemaPage: FunctionComponent = () => { const navigate = useNavigate(); const { showModal } = useEntityExportModalProvider(); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const [isTabExpanded, setIsTabExpanded] = useState(false); const { customizedPage } = useCustomPages(PageType.DatabaseSchema); const [storedProcedureCount, setStoredProcedureCount] = useState(0); @@ -300,33 +291,10 @@ const DatabaseSchemaPage: FunctionComponent = () => { [databaseSchema] ); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = useCallback(() => { - getFeedCounts( - EntityType.DATABASE_SCHEMA, - decodedDatabaseSchemaFQN, - handleFeedCount - ); - }, [decodedDatabaseSchemaFQN, handleFeedCount]); - - const fetchTaskCounts = useCallback(() => { - if (decodedDatabaseSchemaFQN) { - fetchEntityTaskCountsInto(decodedDatabaseSchemaFQN, setFeedCount); - } - }, [decodedDatabaseSchemaFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedDatabaseSchemaFQN) { - fetchEntityActivityCountInto( - EntityType.DATABASE_SCHEMA, - decodedDatabaseSchemaFQN, - setFeedCount - ); - } - }, [decodedDatabaseSchemaFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.DATABASE_SCHEMA, decodedDatabaseSchemaFQN, { + enabled: viewDatabaseSchemaPermission, + }); const saveUpdatedDatabaseSchemaData = useCallback( (updatedData: DatabaseSchema) => { @@ -543,15 +511,8 @@ const DatabaseSchemaPage: FunctionComponent = () => { useEffect(() => { if (viewDatabaseSchemaPermission) { fetchStoreProcedureCount(); - fetchTaskCounts(); - fetchActivityCount(); } - }, [ - viewDatabaseSchemaPermission, - fetchStoreProcedureCount, - fetchTaskCounts, - fetchActivityCount, - ]); + }, [viewDatabaseSchemaPermission, fetchStoreProcedureCount]); useEffect(() => { fetchTableCount(); diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.test.tsx index e5e84c54a0a9..b3d97753cb6a 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/DatabaseSchemaPage/DatabaseSchemaPage.test.tsx @@ -13,9 +13,10 @@ import { act, fireEvent, screen, waitFor } from '@testing-library/react'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { OperationPermission } from '../../context/PermissionProvider/PermissionProvider.interface'; +import { EntityType } from '../../enums/entity.enum'; import { ResourceEntity } from '../../enums/permissions.enum'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { getDatabaseSchemaDetailsByFQN, updateDatabaseSchemaVotes, @@ -25,7 +26,6 @@ import { renderWithQueryClient, runQueryNotificationsSynchronously, } from '../../test/unit/test-utils'; -import { fetchEntityTaskCountsInto } from '../../utils/FeedUtilsPure'; import { getDerivedPermissionFlags } from '../../utils/PermissionDerivation'; import { DEFAULT_ENTITY_PERMISSION } from '../../utils/PermissionsUtils'; import DatabaseSchemaPageComponent from './DatabaseSchemaPage.component'; @@ -251,10 +251,13 @@ jest.mock('../../utils/EntityDisplayPureUtils', () => ({ getEntityMissingError: jest.fn().mockImplementation((error) => error), })); -jest.mock('../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn().mockImplementation(() => FEED_COUNT_INITIAL_DATA), +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../utils/TagsUtils', () => ({ @@ -537,9 +540,10 @@ describe('Tests for DatabaseSchemaPage', () => { databaseSchema: 'sample_data.ecommerce_db.shopify', limit: 0, }); - expect(fetchEntityTaskCountsInto).toHaveBeenCalledWith( + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.DATABASE_SCHEMA, 'sample_data.ecommerce_db.shopify', - expect.any(Function) + { enabled: true } ); }); @@ -563,9 +567,10 @@ describe('Tests for DatabaseSchemaPage', () => { databaseSchema: 'Glue.default.information_schema', limit: 0, }); - expect(fetchEntityTaskCountsInto).toHaveBeenCalledWith( + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.DATABASE_SCHEMA, 'Glue.default.information_schema', - expect.any(Function) + { enabled: true } ); }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.test.tsx index 792e96de4b78..9a83d3110877 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.test.tsx @@ -15,8 +15,10 @@ import { renderHook, waitFor } from '@testing-library/react'; import React, { act } from 'react'; import { MemoryRouter } from 'react-router-dom'; import { OperationPermission } from '../../../context/PermissionProvider/PermissionProvider.interface'; +import { EntityType } from '../../../enums/entity.enum'; import { ResourceEntity } from '../../../enums/permissions.enum'; import { Include } from '../../../generated/type/include'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { MOCK_PERMISSIONS } from '../../../mocks/Glossary.mock'; import { MOCK_TEST_CASE_DATA } from '../../../mocks/TestCase.mock'; import { @@ -26,10 +28,6 @@ import { restoreTestCase, updateTestCaseById, } from '../../../rest/testAPI'; -import { - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation'; import { showErrorToast, showSuccessToast } from '../../../utils/ToastUtils'; import { TestCasePageTabs } from '../IncidentManager.interface'; @@ -139,9 +137,13 @@ const mockNavigationState = { }, ], }; -jest.mock('../../../utils/FeedUtilsPure', () => ({ - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../../utils/ToastUtils', () => ({ @@ -245,9 +247,10 @@ describe('useTestCaseDetailPage', () => { ) ); - expect(fetchEntityTaskCountsInto).toHaveBeenCalledWith( + expect(useEntityFeedCounts).toHaveBeenCalledWith( + EntityType.TEST_CASE, mockTestCaseFqn, - expect.any(Function) + { enabled: true, includeActivity: false } ); }); @@ -598,7 +601,7 @@ describe('useTestCaseDetailPage', () => { expect(isRestored).toBe(false); }); - it('getEntityFeedCount should fetch feed counts', async () => { + it('getEntityFeedCount should reload the feed counts', async () => { const { result } = renderDetailPageHook(); await waitFor(() => expect(result.current.isLoading).toBe(false)); @@ -607,11 +610,10 @@ describe('useTestCaseDetailPage', () => { result.current.getEntityFeedCount(); }); - expect(getFeedCounts).toHaveBeenCalledWith( - 'testCase', - mockTestCaseFqn, - expect.any(Function) - ); + expect( + (useEntityFeedCounts as jest.Mock).mock.results.at(-1)?.value + .getEntityFeedCount + ).toHaveBeenCalled(); }); describe('version responses that resolve after the version page unmounts', () => { diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx index 00b69ea5a25e..22f51e455710 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx @@ -20,7 +20,6 @@ import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import { ManageButtonItemLabel } from '../../../components/common/ManageButtonContentItem/ManageButtonContentItem.component'; import { EntityName } from '../../../components/Modals/EntityNameModal/EntityNameModal.interface'; -import { FEED_COUNT_INITIAL_DATA } from '../../../constants/entity.constants'; import { EntityField } from '../../../constants/Feeds.constants'; import { OperationPermission } from '../../../context/PermissionProvider/PermissionProvider.interface'; import { EntityTabs, EntityType } from '../../../enums/entity.enum'; @@ -32,6 +31,7 @@ import { } from '../../../generated/tests/testCase'; import { EntityHistory } from '../../../generated/type/entityHistory'; import useCustomLocation from '../../../hooks/useCustomLocation/useCustomLocation'; +import { useEntityFeedCounts } from '../../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../../hooks/useFqn'; import { FeedCounts } from '../../../interface/feed.interface'; @@ -47,10 +47,6 @@ import { } from '../../../rest/testAPI'; import { getRenderedActiveTab } from '../../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityVersionByField } from '../../../utils/EntityVersionUtilsPure'; -import { - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../../utils/FeedUtilsPure'; import observabilityRouterClassBase from '../../../utils/ObservabilityRouterClassBase'; import { showErrorToast, showSuccessToast } from '../../../utils/ToastUtils'; import { useRequiredParams } from '../../../utils/useRequiredParams'; @@ -139,9 +135,6 @@ export const useTestCaseDetailPage = ({ isTabExpanded, setIsTabExpanded, } = useTestCaseStore(); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const [versionList, setVersionList] = useState({ entityType: EntityType.TEST_CASE, versions: [], @@ -175,6 +168,11 @@ export const useTestCaseDetailPage = ({ } = useEntityPermissions(ResourceEntity.TEST_CASE, testCaseFQN, { enabled: Boolean(testCaseFQN), }); + const { feedCount, getEntityFeedCount } = useEntityFeedCounts( + EntityType.TEST_CASE, + testCaseFQN, + { enabled: Boolean(hasViewPermission), includeActivity: false } + ); const hasEditPermission = !isDeleted && canEditAll; const editDisplayNamePermission = !isDeleted && canEditDisplayName; @@ -395,22 +393,6 @@ export const useTestCaseDetailPage = ({ } }; - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = useCallback(() => { - getFeedCounts(EntityType.TEST_CASE, testCaseFQN, handleFeedCount); - }, [testCaseFQN]); - - // Only the open-task count is used here (tab badge); skip the - // activity-events fetch that getFeedCounts would bundle in. - const fetchTaskCounts = useCallback(() => { - if (testCaseFQN) { - fetchEntityTaskCountsInto(testCaseFQN, setFeedCount); - } - }, [testCaseFQN]); - const handleCancelDimension = useCallback( () => setIsDimensionEdit(false), [] @@ -471,10 +453,6 @@ export const useTestCaseDetailPage = ({ }, [testCase?.changeDescription, testCase?.displayName, isVersionPage]); useEffect(() => { - if (hasViewPermission && testCaseFQN) { - fetchTaskCounts(); - } - return () => { reset(); testCaseClassBase.setShowSqlQueryTab(false); diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.test.tsx index 60f1b699f22d..45a7b55600b1 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.test.tsx @@ -53,6 +53,15 @@ const setMockPermissions = ( }); }; +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), +})); + jest.mock('../../hooks/useEntityPermissions/useEntityPermissions', () => ({ useEntityPermissions: (...args: unknown[]) => mockUseEntityPermissions(...args), diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.tsx index 2e539cc1c246..f6b384d72f86 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/SearchIndexDetailsPage/SearchIndexDetailsPage.tsx @@ -31,7 +31,6 @@ import { DataAssetWithDomains } from '../../components/DataAssets/DataAssetsHead import EntityDetailsPageSkeleton from '../../components/Entity/EntityDetailsPageSkeleton/EntityDetailsPageSkeleton'; import { EntityName } from '../../components/Modals/EntityNameModal/EntityNameModal.interface'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { EntityTabs, EntityType, FqnPart } from '../../enums/entity.enum'; import { ResourceEntity } from '../../enums/permissions.enum'; import { ServiceCategory } from '../../enums/service.enum'; @@ -41,10 +40,10 @@ import { PageType } from '../../generated/system/ui/page'; import LimitWrapper from '../../hoc/LimitWrapper'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { searchIndexQueryFn, searchIndexQueryKey, @@ -64,11 +63,6 @@ import { getTabLabelMapFromTabs, } from '../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { addToRecentViewed } from '../../utils/RecentActivityUtils'; import { getEntityDetailsPath, getVersionPath } from '../../utils/RouterUtils'; @@ -95,9 +89,6 @@ function SearchIndexDetailsPage() { const queryClient = useQueryClient(); const { currentUser } = useApplicationStore(); const USERId = currentUser?.id ?? ''; - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const { customizedPage, isLoading } = useCustomPages(PageType.SearchIndex); const [isTabExpanded, setIsTabExpanded] = useState(false); @@ -213,32 +204,10 @@ function SearchIndexDetailsPage() { deleted: Boolean(deleted), }); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => - getFeedCounts( - EntityType.SEARCH_INDEX, - decodedSearchIndexFQN, - handleFeedCount - ); - - const fetchTaskCounts = useCallback(() => { - if (decodedSearchIndexFQN) { - fetchEntityTaskCountsInto(decodedSearchIndexFQN, setFeedCount); - } - }, [decodedSearchIndexFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedSearchIndexFQN) { - fetchEntityActivityCountInto( - EntityType.SEARCH_INDEX, - decodedSearchIndexFQN, - setFeedCount - ); - } - }, [decodedSearchIndexFQN]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.SEARCH_INDEX, decodedSearchIndexFQN, { + enabled: viewPermission, + }); const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { @@ -561,13 +530,6 @@ function SearchIndexDetailsPage() { [setSearchIndexDetails] ); - useEffect(() => { - if (viewPermission) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [decodedSearchIndexFQN, viewPermission]); - const toggleTabExpanded = () => { setIsTabExpanded(!isTabExpanded); }; diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.test.tsx index a3d36426444c..b9fa4310afef 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.test.tsx @@ -73,10 +73,13 @@ jest.mock('../../utils/RecentActivityUtils', () => ({ ...jest.requireActual('../../utils/RecentActivityUtils'), addToRecentViewed: jest.fn(), })); -jest.mock('../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../utils/TagsUtils', () => ({ sortTagsCaseInsensitive: jest.fn(), diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.tsx index 3e7381174a49..4c027a447bec 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/StoredProcedure/StoredProcedurePage.tsx @@ -30,7 +30,6 @@ import { EntityName } from '../../components/Modals/EntityNameModal/EntityNameMo import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { FQN_SEPARATOR_CHAR } from '../../constants/char.constants'; import { ROUTES } from '../../constants/constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { ClientErrors } from '../../enums/Axios.enum'; import { EntityTabs, EntityType, FqnPart } from '../../enums/entity.enum'; import { ResourceEntity } from '../../enums/permissions.enum'; @@ -43,10 +42,10 @@ import { PageType } from '../../generated/system/ui/page'; import LimitWrapper from '../../hoc/LimitWrapper'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { storedProcedureQueryFn, storedProcedureQueryKey, @@ -65,11 +64,6 @@ import { getTabLabelMapFromTabs, } from '../../utils/CustomizePage/CustomizePageEntityTabUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { addToRecentViewed } from '../../utils/RecentActivityUtils'; import { getEntityDetailsPath, getVersionPath } from '../../utils/RouterUtils'; @@ -134,9 +128,14 @@ const StoredProcedurePage = () => { const { customizedPage, isLoading: loading } = useCustomPages( PageType.StoredProcedure ); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts( + EntityType.STORED_PROCEDURE, + decodedStoredProcedureFQN, + { + enabled: viewBasicPermission, + } + ); const storedProcedureCacheKey = useMemo( () => @@ -242,34 +241,6 @@ const StoredProcedurePage = () => { }; }, [followers, USER_ID]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts( - EntityType.STORED_PROCEDURE, - decodedStoredProcedureFQN, - handleFeedCount - ); - }; - - const fetchTaskCounts = useCallback(() => { - if (decodedStoredProcedureFQN) { - fetchEntityTaskCountsInto(decodedStoredProcedureFQN, setFeedCount); - } - }, [decodedStoredProcedureFQN]); - - const fetchActivityCount = useCallback(() => { - if (decodedStoredProcedureFQN) { - fetchEntityActivityCountInto( - EntityType.STORED_PROCEDURE, - decodedStoredProcedureFQN, - setFeedCount - ); - } - }, [decodedStoredProcedureFQN]); - const versionHandler = useCallback(() => { version && navigate( @@ -617,13 +588,6 @@ const StoredProcedurePage = () => { [storedProcedure, handleStoreProcedureUpdate] ); - useEffect(() => { - if (viewBasicPermission) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [decodedStoredProcedureFQN, viewBasicPermission]); - const isPageLoading = useMemo( () => permissionsLoading || loading || storedProcedureLoading, [permissionsLoading, loading, storedProcedureLoading] diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.test.tsx index 7ea445102d24..6312445e3cf4 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.test.tsx @@ -152,10 +152,13 @@ jest.mock('../../utils/RecentActivityUtils', () => ({ ...jest.requireActual('../../utils/RecentActivityUtils'), addToRecentViewed: jest.fn(), })); -jest.mock('../../utils/FeedUtilsPure', () => ({ - fetchEntityActivityCountInto: jest.fn(), - fetchEntityTaskCountsInto: jest.fn(), - getFeedCounts: jest.fn(), +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), })); jest.mock('../../utils/FqnUtils', () => ({ getPartialNameFromTableFQN: jest.fn().mockImplementation(() => 'fqn'), diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.tsx index 3230a264ab00..62ca5fda1c2a 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/TableDetailsPageV1/TableDetailsPageV1.tsx @@ -43,7 +43,6 @@ import { useEntityExportModalProvider } from '../../components/Entity/EntityExpo import { EntityName } from '../../components/Modals/EntityNameModal/EntityNameModal.interface'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { FQN_SEPARATOR_CHAR } from '../../constants/char.constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { ClientErrors } from '../../enums/Axios.enum'; import { EntityTabs, @@ -60,6 +59,7 @@ import { TagLabel } from '../../generated/type/tagLabel'; import LimitWrapper from '../../hoc/LimitWrapper'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { permissionQueryKeys, PERMISSION_STALE_TIME, @@ -68,7 +68,6 @@ import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntity import { useFqn } from '../../hooks/useFqn'; import { useSub } from '../../hooks/usePubSub'; import { QueryVote } from '../../interface/entity/vote.interface'; -import { FeedCounts } from '../../interface/feed.interface'; import { getListTestCaseIncidentStatus } from '../../rest/incidentManagerAPI'; import { getDataQualityLineage } from '../../rest/lineageAPI'; import { getResourcePermission } from '../../rest/permissionAPI'; @@ -97,11 +96,6 @@ import { defaultFieldsWithColumns } from '../../utils/DatasetDetailsUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; import { mergeEntityStateUpdate } from '../../utils/EntityUpdateUtils'; import entityUtilClassBase from '../../utils/EntityUtilClassBase'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { getPartialNameFromTableFQN } from '../../utils/FqnUtils'; import { getDerivedPermissionFlags } from '../../utils/PermissionDerivation'; import { PERMISSION_POLICY } from '../../utils/permissionPolicy'; @@ -176,9 +170,6 @@ const TableDetailsPageV1: React.FC = () => { } | null )?.breadcrumbData; const USERId = currentUser?.id ?? ''; - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); // Tagged with the table they were fetched for: the page is not remounted between tables, // so the header of the next table renders before its own counts arrive. @@ -486,28 +477,10 @@ const TableDetailsPageV1: React.FC = () => { }; }, [tableFqn]); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); - - const getEntityFeedCount = () => { - getFeedCounts(EntityType.TABLE, tableFqn, handleFeedCount); - }; - - // P2-A: task counts drive the always-visible "Open Tasks" button in the page header chrome, - // so they must stay eager on mount. The heavier activity-events fetch (up to 100 events just - // to compute a count) only feeds the Activity Feed tab badge and is deferred below. - const fetchTaskCounts = useCallback(() => { - if (tableFqn) { - fetchEntityTaskCountsInto(tableFqn, setFeedCount); - } - }, [tableFqn]); - - const fetchActivityCount = useCallback(() => { - if (tableFqn) { - fetchEntityActivityCountInto(EntityType.TABLE, tableFqn, setFeedCount); - } - }, [tableFqn]); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.TABLE, tableFqn, { + enabled: viewBasicPermission, + }); const handleTabChange = (activeKey: string) => { if (activeKey !== activeTab) { @@ -924,17 +897,6 @@ const TableDetailsPageV1: React.FC = () => { [setTableDetails] ); - useEffect(() => { - if (viewBasicPermission) { - // Don't manually clear the cache to {@code undefined} here — that would flash a Loader - // on every navigation between tables even when the destination is already cached. - // {@link useQuery}'s own refetch-on-key-change handles this: a stale entry serves - // immediately while a background refresh runs. - fetchTaskCounts(); - fetchActivityCount(); - } - }, [tableFqn, viewBasicPermission]); - const loadedTableFqn = tableDetails?.fullyQualifiedName; // P1.2: fetchDqIndicatorCounts drives the global DQ indicator in the page chrome, diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.test.tsx index 446e6a0993bc..19ae46596eb5 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.test.tsx @@ -11,11 +11,11 @@ * limitations under the License. */ -import { screen, waitFor } from '@testing-library/react'; +import { act, screen, waitFor } from '@testing-library/react'; import { EntityTabs } from '../../enums/entity.enum'; import { useFqn } from '../../hooks/useFqn'; import { searchQuery } from '../../rest/searchAPI'; -import { getTagByFqn } from '../../rest/tagAPI'; +import { getTagByFqn, patchTag } from '../../rest/tagAPI'; import { renderWithQueryClient } from '../../test/unit/test-utils'; import { getDerivedPermissionFlags } from '../../utils/PermissionDerivation'; import tagClassBase from '../../utils/TagClassBase'; @@ -50,6 +50,15 @@ const setMockTagPermissions = ( }); }; +jest.mock('../../hooks/useEntityFeedCounts', () => ({ + useEntityFeedCounts: jest.fn().mockReturnValue({ + feedCount: jest.requireActual('../../constants/entity.constants') + .FEED_COUNT_INITIAL_DATA, + getEntityFeedCount: jest.fn(), + handleFeedCount: jest.fn(), + }), +})); + jest.mock('../../hooks/useEntityPermissions/useEntityPermissions', () => ({ useEntityPermissions: (...args: unknown[]) => mockUseEntityPermissions(...args), @@ -178,6 +187,11 @@ jest.mock('../../rest/tagAPI', () => ({ name: 'NonSensitive', fullyQualifiedName: 'PII.NonSensitive', }), + patchTag: jest.fn().mockResolvedValue({ + name: 'NonSensitive', + fullyQualifiedName: 'PII.NonSensitive', + description: 'Updated', + }), })); jest.mock('../../rest/searchAPI', () => ({ @@ -312,6 +326,7 @@ jest.mock( ); const mockGenericProvider = jest.fn(); +const mockGenericProviderUpdate = jest.fn(); jest.mock( '../../components/Customization/GenericProvider/GenericProvider', @@ -322,8 +337,12 @@ jest.mock( return { ...actual, - GenericProvider: (props: { permissions: unknown }) => { + GenericProvider: (props: { + permissions: unknown; + onUpdate: (tag: unknown) => Promise; + }) => { mockGenericProvider(props.permissions); + mockGenericProviderUpdate.mockImplementation(props.onUpdate); return actual.GenericProvider(props); }, @@ -367,6 +386,27 @@ describe('TagPage', () => { expect(breadcrumb).toHaveTextContent('NonSensitive'); }); + it('reloads the feed counts after the tag is updated', async () => { + const { getEntityFeedCount } = jest + .requireMock('../../hooks/useEntityFeedCounts') + .useEntityFeedCounts(); + (useFqn as jest.Mock).mockReturnValue({ fqn: 'PII.NonSensitive' }); + + render(); + + await waitFor(() => expect(mockGenericProvider).toHaveBeenCalled()); + await act(() => + mockGenericProviderUpdate({ + name: 'NonSensitive', + fullyQualifiedName: 'PII.NonSensitive', + description: 'Updated', + }) + ); + + expect(patchTag).toHaveBeenCalled(); + expect(getEntityFeedCount).toHaveBeenCalled(); + }); + it('should call getTagData and fetchClassificationTagAssets when tagFqn changes', async () => { (useFqn as jest.Mock).mockReturnValue({ fqn: 'PII.NonSensitive' }); diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.tsx index df88879b6c4f..61eb61defe6d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/TagPage/TagPage.tsx @@ -77,7 +77,6 @@ import { TIER_CATEGORY, } from '../../constants/constants'; import { CustomizeEntityType } from '../../constants/Customize.constants'; -import { FEED_COUNT_INITIAL_DATA } from '../../constants/entity.constants'; import { LEARNING_PAGE_IDS } from '../../constants/Learning.constants'; import { COMMON_RESIZABLE_PANEL_CONFIG } from '../../constants/ResizablePanel.constants'; import { usePermissionProvider } from '../../context/PermissionProvider/PermissionProvider'; @@ -92,9 +91,9 @@ import { PageType } from '../../generated/system/ui/page'; import { Style } from '../../generated/type/tagLabel'; import { useIsAiMode } from '../../hooks/useAppMode'; import { useCustomPages } from '../../hooks/useCustomPages'; +import { useEntityFeedCounts } from '../../hooks/useEntityFeedCounts'; import { useEntityPermissions } from '../../hooks/useEntityPermissions/useEntityPermissions'; import { useFqn } from '../../hooks/useFqn'; -import { FeedCounts } from '../../interface/feed.interface'; import { tagQueryFn, tagQueryKey, @@ -107,11 +106,6 @@ import { LazyDataQualityDashboard } from '../../utils/Domain/LazyDomainComponent import { getEntityMissingError } from '../../utils/EntityDisplayPureUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; import entityUtilClassBase from '../../utils/EntityUtilClassBase'; -import { - fetchEntityActivityCountInto, - fetchEntityTaskCountsInto, - getFeedCounts, -} from '../../utils/FeedUtilsPure'; import { revokeEditPermissions } from '../../utils/PermissionsUtils'; import { getClassificationDetailsPath, @@ -180,9 +174,6 @@ const TagPage = () => { const assetTabRef = useRef(null); const [previewAsset, setPreviewAsset] = useState(); - const [feedCount, setFeedCount] = useState( - FEED_COUNT_INITIAL_DATA - ); const tagCacheKey = useMemo( () => tagQueryKey(tagFqn, TAG_DEFAULT_FIELDS), @@ -291,9 +282,8 @@ const TagPage = () => { [] ); - const handleFeedCount = useCallback((data: FeedCounts) => { - setFeedCount(data); - }, []); + const { feedCount, getEntityFeedCount, handleFeedCount } = + useEntityFeedCounts(EntityType.TAG, tagItem?.fullyQualifiedName); const { editTagsPermission, disabledAwarePermissions } = useMemo(() => { if (tagItem) { @@ -382,12 +372,13 @@ const TagPage = () => { const response = await patchTag(tagItem.id ?? '', jsonPatch); setTagItem(response); + void getEntityFeedCount(); } catch (error) { showErrorToast(error as AxiosError); } } }, - [tagItem, setTagItem] + [tagItem, setTagItem, getEntityFeedCount] ); const onNameSave = async (obj: Tag) => { @@ -491,32 +482,6 @@ const TagPage = () => { } }, [tagFqn, t]); - const fetchFeedCount = async () => { - if (tagItem?.fullyQualifiedName) { - await getFeedCounts( - EntityType.TAG, - tagItem.fullyQualifiedName, - handleFeedCount - ); - } - }; - - const fetchTaskCounts = useCallback(() => { - if (tagItem?.fullyQualifiedName) { - fetchEntityTaskCountsInto(tagItem.fullyQualifiedName, setFeedCount); - } - }, [tagItem?.fullyQualifiedName]); - - const fetchActivityCount = useCallback(() => { - if (tagItem?.fullyQualifiedName) { - fetchEntityActivityCountInto( - EntityType.TAG, - tagItem.fullyQualifiedName, - setFeedCount - ); - } - }, [tagItem?.fullyQualifiedName]); - const handleAssetSave = useCallback(() => { fetchClassificationTagAssets(); assetTabRef.current?.refreshAssets(); @@ -712,7 +677,7 @@ const TagPage = () => { layoutType={ActivityFeedLayoutType.THREE_PANEL} owners={tagItem.owners} subTab={ActivityFeedTabs.ALL} - onFeedUpdate={fetchFeedCount} + onFeedUpdate={getEntityFeedCount} onUpdateEntityDetails={refetchTagItem} onUpdateFeedCount={handleFeedCount} /> @@ -762,6 +727,7 @@ const TagPage = () => { haveAssetEditPermission, handleAssetSave, handleAssetClick, + getEntityFeedCount, handleFeedCount, refetchTagItem, assetTabRef, @@ -849,13 +815,6 @@ const TagPage = () => { fetchClassificationTagAssets(); }, [fetchClassificationTagAssets]); - useEffect(() => { - if (tagItem) { - fetchTaskCounts(); - fetchActivityCount(); - } - }, [tagItem, fetchTaskCounts, fetchActivityCount]); - if (tagLoading || isCustomPageLoading) { return ; } diff --git a/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.getFeedCounts.test.ts b/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.getFeedCounts.test.ts index 8b8541d8c4e5..901f350c0939 100644 --- a/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.getFeedCounts.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.getFeedCounts.test.ts @@ -15,7 +15,7 @@ import { getEntityActivityByFqn } from '../rest/activityAPI'; import { listConversations } from '../rest/conversationsAPI'; import { getTaskCounts } from '../rest/tasksAPI'; import { - fetchEntityActivityCountInto, + fetchEntityActivityCounts, getFeedCounts, getFeedTotalCount, } from './FeedUtilsPure'; @@ -144,7 +144,7 @@ describe('getFeedTotalCount', () => { }); }); -describe('fetchEntityActivityCountInto', () => { +describe('fetchEntityActivityCounts', () => { it('counts the conversations on the entity fields too', async () => { (listConversations as jest.Mock).mockResolvedValue({ data: [], @@ -155,8 +155,9 @@ describe('fetchEntityActivityCountInto', () => { paging: { total: 0 }, }); - await fetchEntityActivityCountInto('pipeline', 'svc.p', jest.fn()); - + await expect( + fetchEntityActivityCounts('pipeline', 'svc.p') + ).resolves.toEqual({ activityCount: 0, conversationCount: 1 }); expect(listConversations).toHaveBeenCalledWith({ entityLink: '<#E::pipeline::svc.p>', includeFields: true, diff --git a/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.ts b/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.ts index a89c803f514e..3d5c4d511eee 100644 --- a/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.ts +++ b/openmetadata-ui/src/main/resources/ui/src/utils/FeedUtilsPure.ts @@ -14,7 +14,6 @@ import type { AxiosError } from 'axios'; import { isUndefined } from 'lodash'; import { Marked } from 'marked'; -import type { Dispatch, SetStateAction } from 'react'; import TurndownService from 'turndown'; import { FQN_SEPARATOR_CHAR } from '../constants/char.constants'; import { ROUTES } from '../constants/constants'; @@ -413,130 +412,79 @@ export const getFeedTotalCount = ({ }: Pick) => conversationCount + activityCount + openTaskCount; -export const getFeedCounts = async ( - entityType: string, - entityFQN: string, - domainOrCallback: string | undefined | ((countValue: FeedCounts) => void), - callback?: (countValue: FeedCounts) => void -) => { - try { - const domain = - typeof domainOrCallback === 'string' || domainOrCallback === undefined - ? domainOrCallback - : undefined; - const feedCountCallback = - typeof domainOrCallback === 'function' ? domainOrCallback : callback; - - if (!feedCountCallback) { - return; - } - - const [conversations, activityRes, taskCounts] = await Promise.all([ - listConversations({ - entityLink: getEntityFeedLink(entityType, entityFQN), - includeFields: true, - limit: 1, - }), - getEntityActivityByFqn(entityType, entityFQN, { - days: 30, - limit: 0, - domain, - }), - getTaskCounts({ aboutEntity: entityFQN, domain }), - ]); - - const conversationCount = conversations.paging.total ?? 0; - const mentionCount = 0; - const activityCount = activityRes?.paging?.total ?? 0; - - const openTaskCount = taskCounts.open ?? 0; - const closedTaskCount = taskCounts.completed ?? 0; - const totalTasksCount = taskCounts.total ?? 0; - - feedCountCallback({ - conversationCount, - activityCount, - totalTasksCount, - openTaskCount, - closedTaskCount, - totalCount: getFeedTotalCount({ - conversationCount, - activityCount, - openTaskCount, - }), - mentionCount, - }); - } catch (err) { - showErrorToast(err as AxiosError, t('server.entity-feed-fetch-error')); - } +type EntityTaskCounts = Pick< + FeedCounts, + 'openTaskCount' | 'closedTaskCount' | 'totalTasksCount' +>; + +type EntityActivityCounts = Pick< + FeedCounts, + 'conversationCount' | 'activityCount' +>; + +export const fetchEntityTaskCounts = async ( + entityFqn: string +): Promise => { + const taskCounts = await getTaskCounts({ aboutEntity: entityFqn }); + + return { + openTaskCount: taskCounts.open ?? 0, + closedTaskCount: taskCounts.completed ?? 0, + totalTasksCount: taskCounts.total ?? 0, + }; }; -export const fetchEntityTaskCountsInto = async ( - entityFqn: string, - setFeedCount: Dispatch>, - domain?: string -) => { - try { - const taskCounts = await getTaskCounts({ aboutEntity: entityFqn, domain }); - setFeedCount((prev) => { - const openTaskCount = taskCounts.open ?? 0; - const closedTaskCount = taskCounts.completed ?? 0; - const totalTasksCount = taskCounts.total ?? 0; - - return { - ...prev, - openTaskCount, - closedTaskCount, - totalTasksCount, - totalCount: getFeedTotalCount({ - conversationCount: prev.conversationCount ?? 0, - activityCount: prev.activityCount ?? 0, - openTaskCount, - }), - }; - }); - } catch (err) { - showErrorToast(err as AxiosError, t('server.entity-feed-fetch-error')); - } +/** + * Conversations and activity change-events live in separate stores; the + * entity feed shows both, so the count must include both. + */ +export const fetchEntityActivityCounts = async ( + entityType: string, + entityFqn: string +): Promise => { + const [activityRes, conversations] = await Promise.all([ + getEntityActivityByFqn(entityType, entityFqn, { days: 30, limit: 0 }), + listConversations({ + entityLink: getEntityFeedLink(entityType, entityFqn), + includeFields: true, + limit: 1, + }), + ]); + + return { + activityCount: activityRes?.paging?.total ?? 0, + conversationCount: conversations.paging.total ?? 0, + }; }; -export const fetchEntityActivityCountInto = async ( +export const buildFeedCounts = ( + tasks: EntityTaskCounts, + activity: EntityActivityCounts +): FeedCounts => ({ + ...tasks, + ...activity, + mentionCount: 0, + totalCount: getFeedTotalCount({ + ...activity, + openTaskCount: tasks.openTaskCount, + }), +}); + +/** + * Kept for openmetadata-collate; new code uses useEntityFeedCounts. + * ADR:2026-12-04-getfeedcounts-is-kept-for-collate + */ +export const getFeedCounts = async ( entityType: string, - entityFqn: string, - setFeedCount: Dispatch>, - domain?: string + entityFQN: string, + callback: (countValue: FeedCounts) => void ) => { try { - // Conversations and activity change-events live in separate stores; the - // entity feed shows both, so the count must include both. - const [activityRes, conversations] = await Promise.all([ - getEntityActivityByFqn(entityType, entityFqn, { - days: 30, - limit: 0, - domain, - }), - listConversations({ - entityLink: getEntityFeedLink(entityType, entityFqn), - includeFields: true, - limit: 1, - }), + const [tasks, activity] = await Promise.all([ + fetchEntityTaskCounts(entityFQN), + fetchEntityActivityCounts(entityType, entityFQN), ]); - setFeedCount((prev) => { - const activityCount = activityRes?.paging?.total ?? 0; - const conversationCount = conversations.paging.total ?? 0; - - return { - ...prev, - activityCount, - conversationCount, - mentionCount: 0, - totalCount: getFeedTotalCount({ - conversationCount, - activityCount, - openTaskCount: prev.openTaskCount ?? 0, - }), - }; - }); + callback(buildFeedCounts(tasks, activity)); } catch (err) { showErrorToast(err as AxiosError, t('server.entity-feed-fetch-error')); }