diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 12cb33c2f6ed..bbb582a9ec4c 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -7276,6 +7276,7 @@ const CONST = { SEARCH: { RESULTS_PAGE_SIZE: 50, + TAG_FILTER_PAGE_SIZE: 200, EXITING_ANIMATION_DURATION: 200, ME: 'me', /** How far the cursor may wander from where it last counted as moving over the advanced filter list and still count as resting */ diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 297c19736043..7674a11accc4 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -49,6 +49,12 @@ const ONYXKEYS = { /** Boolean flag set whenever we are searching for reports in the server */ RAM_ONLY_IS_SEARCHING_FOR_REPORTS: 'isSearchingForReports', + /** Pagination state for tag filter search (hasMore, nextCursor). RAM-only so it resets on app restart. */ + RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION: 'searchTagFiltersPagination', + + /** Paginated tag search results. RAM-only so it resets on app restart. */ + RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS: 'searchTagFiltersResults', + /** Boolean flag set whenever we are searching for users in the server */ RAM_ONLY_IS_SEARCHING_FOR_USERS: 'isSearchingForUsers', @@ -1782,6 +1788,8 @@ type OnyxValuesMapping = { [ONYXKEYS.ONBOARDING_ADMINS_CHAT_REPORT_ID]: string; [ONYXKEYS.ONBOARDING_LAST_VISITED_PATH]: string; [ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS]: boolean; + [ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION]: OnyxTypes.SearchTagFiltersPaginationState; + [ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS]: OnyxTypes.SearchTagFilterItem[]; [ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_USERS]: boolean; [ONYXKEYS.RAM_ONLY_IS_AUTHENTICATING_WITH_SHORT_LIVED_TOKEN]: boolean; [ONYXKEYS.LAST_VISITED_PATH]: string | undefined; diff --git a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx index 16e8503daa85..f629cdc74189 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx @@ -1,7 +1,6 @@ import Icon from '@components/Icon'; import {PressableWithFeedback} from '@components/Pressable'; import ScrollView from '@components/ScrollView'; -import type {Filter} from '@components/Search/types'; import SpacerView from '@components/SpacerView'; import Text from '@components/Text'; @@ -34,7 +33,6 @@ type FilterItemCallbacks = { type FilterListProps = FilterItemCallbacks & { type: SearchDataTypes | undefined; - policyID: Filter; selectedFilter?: SearchFilter['key']; style?: StyleProp; contentContainerStyle?: StyleProp; @@ -110,9 +108,9 @@ function FilterItem({filterKey, isSelected, type, onPress, onHoverIn, onFocus}: ); } -function FilterList({type, policyID, selectedFilter, style, contentContainerStyle, onHoverIn, onFocus, onPress, onPointerMove, onPointerLeave}: FilterListProps) { +function FilterList({type, selectedFilter, style, contentContainerStyle, onHoverIn, onFocus, onPress, onPointerMove, onPointerLeave}: FilterListProps) { const styles = useThemeStyles(); - const typeFiltersKeys = useAdvancedSearchFilters(type, policyID); + const typeFiltersKeys = useAdvancedSearchFilters(type); return ( = SearchFilterCommonProps>> & loading?: boolean; shouldShowLoadingPlaceholder?: boolean; + + /** Called when the scroll position gets near the end of the list */ + onEndReached?: () => void; + + /** How far from the end the bottom edge of the list must be to trigger onEndReached */ + onEndReachedThreshold?: number; + + /** Called when the debounced search term changes */ + onSearchChange?: (searchTerm: string) => void; + + /** Whether more items are being loaded (shows spinner at bottom of list) */ + isLoadingMore?: boolean; + + /** Whether a server search is in progress (shows a centered spinner in the list area) */ + isSearching?: boolean; }; function MultiSelect({ @@ -66,6 +81,11 @@ function MultiSelect({ autoFocus, footer, onChange, + onEndReached, + onEndReachedThreshold, + onSearchChange, + isLoadingMore, + isSearching, }: MultiSelectProps) { const theme = useTheme(); const shouldFooterBeInsideList = useShouldFooterBeInsideList(); @@ -75,6 +95,19 @@ function MultiSelect({ const [selectedItems, setSelectedItems] = useState(value); const [searchTerm, debouncedSearchTerm, setSearchTerm] = useDebouncedState(''); + const notifySearchChange = useEffectEvent((term: string) => { + onSearchChange?.(term); + }); + + const isFirstRender = useRef(true); + useEffect(() => { + if (isFirstRender.current) { + isFirstRender.current = false; + return; + } + notifySearchChange(debouncedSearchTerm); + }, [debouncedSearchTerm]); + // Snapshot the values selected when the filter first opened so they can be floated to the top of a long list on // first render without repinning rows that are toggled afterwards. // moveInitialSelectionToTop gates on the *unfiltered* items length so the decision doesn't flip as the user types, @@ -83,9 +116,11 @@ function MultiSelect({ const orderedItems = moveInitialSelectionToTop(items, initialSelectedValues); const searchLower = debouncedSearchTerm.toLowerCase(); - const filteredItems = isSearchable - ? orderedItems.filter((item) => item.text.toLowerCase().includes(searchLower) || item.searchableText?.toLowerCase().includes(searchLower)) - : orderedItems; + // When onSearchChange is provided, the parent handles filtering (server-side search) + const filteredItems = + isSearchable && !onSearchChange + ? orderedItems.filter((item) => item.text.toLowerCase().includes(searchLower) || item.searchableText?.toLowerCase().includes(searchLower)) + : orderedItems; const listData: ListItem[] = filteredItems.map((item) => ({ text: item.text, alternateText: item.alternateText, @@ -95,7 +130,8 @@ function MultiSelect({ leftElement: item.leftElement, })); - const headerMessage = isSearchable && listData.length === 0 ? translate('common.noResultsFound') : undefined; + const shouldShowSearchSpinner = isSearching && listData.length === 0; + const headerMessage = isSearchable && listData.length === 0 && !isSearching ? translate('common.noResultsFound') : undefined; const updateSelectedItems = (item: ListItem) => { if (item.isSelected) { @@ -125,6 +161,29 @@ function MultiSelect({ disableAutoFocus: !autoFocus, }; + const renderCenteredSpinner = () => ( + + + + ); + + const footerContent = ( + <> + {!!isLoadingMore && ( + + + + )} + {footer} + + ); + return ( ({ isNegatable={isNegatable} > {loading ? ( - - - + renderCenteredSpinner() ) : ( ({ onSelectRow={updateSelectedItems} textInputOptions={textInputOptions} style={{contentContainerStyle: [styles.pb0], ...selectionListStyle}} - footerContent={footer} + footerContent={footerContent} shouldFooterBeInsideList={shouldFooterBeInsideList} + onEndReached={onEndReached} + onEndReachedThreshold={onEndReachedThreshold} + listEmptyContent={shouldShowSearchSpinner ? renderCenteredSpinner() : undefined} + shouldShowListEmptyContent={shouldShowSearchSpinner} /> )} diff --git a/src/components/Search/FilterComponents/TagSelector.tsx b/src/components/Search/FilterComponents/TagSelector.tsx index bb1ae7eca189..3b2cc07acef3 100644 --- a/src/components/Search/FilterComponents/TagSelector.tsx +++ b/src/components/Search/FilterComponents/TagSelector.tsx @@ -1,20 +1,24 @@ import type {Filter, SearchFilterCommonProps} from '@components/Search/types'; import useLocalize from '@hooks/useLocalize'; +import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useSearchTagFilters from '@hooks/useSearchTagFilters'; import {getCleanedTagName, getTagNamesFromTagsLists} from '@libs/PolicyUtils'; import {getAllPolicyValues, sortOptionsWithEmptyValue} from '@libs/SearchQueryUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {PolicyTagLists} from '@src/types/onyx'; +import type {Policy, PolicyTagLists} from '@src/types/onyx'; import {getEmptyObject} from '@src/types/utils/EmptyObject'; import type {OnyxCollection} from 'react-native-onyx'; import React from 'react'; +import type {MultiSelectItem} from './MultiSelect'; + import MultiSelect from './MultiSelect'; type TagSelectorProps = SearchFilterCommonProps & { @@ -23,17 +27,57 @@ type TagSelectorProps = SearchFilterCommonProps & { function TagSelector({value = [], policyID, selectionListTextInputStyle, selectionListStyle, autoFocus, footer, onChange}: TagSelectorProps) { const {translate, localeCompare} = useLocalize(); - const [allPolicyTagLists = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS); + const {isOffline} = useNetwork(); + const [policies = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY); + const [allPolicyTags = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS); + const policyIDs = policyID?.value?.length + ? getAllPolicyValues(policyID, ONYXKEYS.COLLECTION.POLICY, policies) + .map((policy) => policy.id) + .join(',') + : ''; + const {searchResults, isSearching, isLoadingMore, hasMore, loadMore, searchTags, isInitialLoading, searchQuery} = useSearchTagFilters(policyIDs); - const tagItems = [{text: translate('search.noTag'), value: CONST.SEARCH.TAG_EMPTY_VALUE as string}]; - const uniqueTagNames = new Set( - getAllPolicyValues(policyID, ONYXKEYS.COLLECTION.POLICY_TAGS, allPolicyTagLists).flatMap((policyTags) => getTagNamesFromTagsLists(policyTags ?? {})), - ); - tagItems.push( - ...Array.from(uniqueTagNames) - .map((tagName) => ({text: getCleanedTagName(tagName), value: tagName})) - .toSorted((a, b) => sortOptionsWithEmptyValue(a.text.toString(), b.text.toString(), localeCompare)), - ); + const hasSearchResults = !!searchResults && searchResults.length > 0; + const shouldUseOfflineFallback = isOffline && !hasSearchResults; + + const tagItems: Array> = []; + const emptyTagItem = {text: translate('search.noTag'), value: CONST.SEARCH.TAG_EMPTY_VALUE as string}; + const seenTagNames = new Set(); + const lowerSearchQuery = searchQuery.toLowerCase(); + + const addTagName = (tagName: string) => { + if (seenTagNames.has(tagName)) { + return; + } + if (lowerSearchQuery && !tagName.toLowerCase().includes(lowerSearchQuery)) { + return; + } + seenTagNames.add(tagName); + tagItems.push({text: getCleanedTagName(tagName), value: tagName}); + }; + + if (shouldUseOfflineFallback) { + // Fall back to synced workspace tag data when the paginated search cache is empty offline. + const policyTagsLists = getAllPolicyValues(policyID?.value?.length ? policyID : undefined, ONYXKEYS.COLLECTION.POLICY_TAGS, allPolicyTags); + for (const policyTagsList of policyTagsLists) { + for (const tagName of getTagNamesFromTagsLists(policyTagsList)) { + addTagName(tagName); + } + } + tagItems.sort((a, b) => sortOptionsWithEmptyValue(a.text.toString(), b.text.toString(), localeCompare)); + } else { + // Preserve backend order - backend pre-sorts tags across policies alphabetically. + // When offline the API is skipped, so cached results are filtered locally by the search query. + for (const tag of searchResults ?? []) { + addTagName(tag.tagName); + } + } + + const shouldShowEmptyTagOption = !isSearching && !isInitialLoading && (!searchQuery || emptyTagItem.text.toLowerCase().includes(lowerSearchQuery)); + + if (shouldShowEmptyTagOption) { + tagItems.unshift(emptyTagItem); + } const selectedTagsItems = value.map((tag) => { if (tag === CONST.SEARCH.TAG_EMPTY_VALUE) { @@ -42,16 +86,40 @@ function TagSelector({value = [], policyID, selectionListTextInputStyle, selecti return {text: getCleanedTagName(tag), value: tag}; }); + // Selected tags that are not in the current result page stay visible once the search is cleared, so the selection doesn't disappear from the list. + // Prepend missing selected items to the top (after "No tag") so they don't land at the bottom of the paginated list. + // Do not gate on !isSearching so they stay mounted during re-fetches without flashing. + if (!searchQuery) { + const itemValues = new Set(tagItems.map((item) => item.value)); + const missingSelectedItems = selectedTagsItems.filter((selectedItem) => !itemValues.has(selectedItem.value)).toSorted((a, b) => localeCompare(a.text.toString(), b.text.toString())); + + if (missingSelectedItems.length > 0) { + const insertIndex = shouldShowEmptyTagOption ? 1 : 0; + tagItems.splice(insertIndex, 0, ...missingSelectedItems); + } + } + + // Keep search mounted while a query is active or in flight. Clearing results for a new search resets hasMore and tag count. + const shouldEnableSearch = shouldUseOfflineFallback + ? seenTagNames.size >= CONST.STANDARD_LIST_ITEM_LIMIT || !!searchQuery + : hasMore || seenTagNames.size >= CONST.STANDARD_LIST_ITEM_LIMIT || isSearching || !!searchQuery; + return ( = CONST.STANDARD_LIST_ITEM_LIMIT} + isSearchable={shouldEnableSearch} autoFocus={autoFocus} selectionListTextInputStyle={selectionListTextInputStyle} selectionListStyle={selectionListStyle} footer={footer} onChange={(tags) => onChange(tags.map((tag) => tag.value))} + onEndReached={hasMore && !shouldUseOfflineFallback ? loadMore : undefined} + onEndReachedThreshold={0.75} + onSearchChange={searchTags} + loading={isInitialLoading} + isSearching={isSearching} + isLoadingMore={isLoadingMore} /> ); } diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 62cce1c24439..bf94de5e7625 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -11,7 +11,7 @@ import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; -import {getFilterNegatableValue, hasFilterContentValuesChanged} from '@libs/SearchUIUtils'; +import {hasFilterContentValuesChanged} from '@libs/SearchUIUtils'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; @@ -196,7 +196,6 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps item.keyForList} + // FlashList can pass a stale index here while its render stack syncs after the dataset shrinks, so item can be undefined. + keyExtractor={(item, index) => item?.keyForList ?? index.toString()} extraData={extraData} ListFooterComponent={ isFooterInsideList ? ( diff --git a/src/hooks/useAdvancedSearchFilters.ts b/src/hooks/useAdvancedSearchFilters.ts index 303a83dce0bc..54ff2aa0531a 100644 --- a/src/hooks/useAdvancedSearchFilters.ts +++ b/src/hooks/useAdvancedSearchFilters.ts @@ -1,12 +1,9 @@ -import type {Filter} from '@components/Search/types'; - import {isFilterableBankAccount} from '@libs/BankAccountUtils'; import {isPolicyFeatureEnabled} from '@libs/PolicyUtils'; -import {getAllPolicyValues} from '@libs/SearchQueryUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {CardList, Policy, PolicyTagLists} from '@src/types/onyx'; +import type {CardList, Policy} from '@src/types/onyx'; import type {SearchDataTypes} from '@src/types/onyx/SearchResults'; import {getEmptyObject} from '@src/types/utils/EmptyObject'; @@ -293,14 +290,6 @@ function advancedSearchPoliciesSelector(policies: OnyxCollection): OnyxC * Checks whether a single policy's tag lists contain at least one tag. * Short-circuits on the first tag found. */ -const policyTagListHasTags = (policyTagList: PolicyTagLists | undefined) => Object.values(policyTagList ?? {}).some((tagList) => Object.keys(tagList.tags ?? {}).length > 0); - -/** - * Selector that checks if any tags exist across all policy tag lists. - * Returns a boolean with early exit on first tag found. - */ -const hasTagsSelector = (allPolicyTagLists: OnyxCollection) => Object.values(allPolicyTagLists ?? {}).some(policyTagListHasTags); - function useAdvancedSearchFiltersWorkspaces(policies: OnyxCollection, searchTerm?: string) { const {localeCompare} = useLocalize(); const [currentUserLogin] = useOnyx(ONYXKEYS.SESSION, {selector: emailSelector}); @@ -322,19 +311,15 @@ function shouldDisplayCardFilterSelector(cardList: OnyxEntry) { return shouldDisplayFilter(Object.keys(filterCardsHiddenFromSearch(cardList)).length, true); } -function useAdvancedSearchFilters(type: SearchDataTypes | undefined, policyID: Filter | undefined) { +function useAdvancedSearchFilters(type: SearchDataTypes | undefined) { const [shouldDisplayCardFilter] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST, {selector: shouldDisplayCardFilterSelector}); const [policies = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: advancedSearchPoliciesSelector}); const [policyDerived] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: policyDerivedSelector}); - const [allPolicyTagLists = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS); - const selectedPolicyTagLists = policyID?.value?.length ? getAllPolicyValues(policyID, ONYXKEYS.COLLECTION.POLICY_TAGS, allPolicyTagLists) : []; - const [hasTags] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS, {selector: hasTagsSelector}); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const {workspaces} = useAdvancedSearchFiltersWorkspaces(policies); - const hasSelectedPolicyTags = selectedPolicyTagLists.some(policyTagListHasTags); - const shouldDisplayTagFilter = shouldDisplayFilter(hasTags ? 1 : 0, policyDerived?.areTagsEnabled ?? false, hasSelectedPolicyTags); + const shouldDisplayTagFilter = !!policyDerived?.areTagsEnabled; // Count business accounts that aren't partially set up, mirroring BankAccountSelector so the row never shows above an empty picker. const hasFilterableBankAccount = Object.values(bankAccountList ?? {}).some(isFilterableBankAccount); const shouldDisplayBankAccountFilter = shouldDisplayFilter(hasFilterableBankAccount ? 1 : 0, true); diff --git a/src/hooks/useFilterFormValues.tsx b/src/hooks/useFilterFormValues.tsx index ffbecb9e2d51..e72d1abf66db 100644 --- a/src/hooks/useFilterFormValues.tsx +++ b/src/hooks/useFilterFormValues.tsx @@ -8,7 +8,7 @@ import {buildFilterFormValuesFromQuery} from '@libs/SearchQueryUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; -import type {Policy, PolicyCategories, PolicyTagLists} from '@src/types/onyx'; +import type {Policy, PolicyCategories} from '@src/types/onyx'; import {getEmptyObject} from '@src/types/utils/EmptyObject'; import type {OnyxCollection} from 'react-native-onyx'; @@ -52,28 +52,6 @@ function policyCategoriesSelector(categories: OnyxCollection): return result; } -function policyTagsSelector(tags: OnyxCollection): OnyxCollection { - if (!tags) { - return tags; - } - const result: OnyxCollection = {}; - for (const [collectionKey, policyTagLists] of Object.entries(tags)) { - if (!policyTagLists) { - continue; - } - const minimalTagLists: PolicyTagLists = {}; - for (const [listKey, tagList] of Object.entries(policyTagLists)) { - const minimalTags: Record = {}; - for (const [tagKey, tag] of Object.entries(tagList.tags ?? {})) { - minimalTags[tagKey] = {name: tag.name}; - } - minimalTagLists[listKey] = {tags: minimalTags} as PolicyTagLists[string]; - } - result[collectionKey] = minimalTagLists; - } - return result; -} - const useFilterFormValues = (queryJSON?: SearchQueryJSON) => { const personalDetails = usePersonalDetails(); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); @@ -84,7 +62,6 @@ const useFilterFormValues = (queryJSON?: SearchQueryJSON) => { // Subscribe to the report collection directly. buildFilterFormValuesFromQuery only does keyed existence // lookups (`in:` filter), so projecting via a selector would just waste an O(n) pass over every report. const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [policyTagsLists] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS, {selector: policyTagsSelector}); const [policyCategories] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES, {selector: policyCategoriesSelector}); const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); @@ -98,7 +75,6 @@ const useFilterFormValues = (queryJSON?: SearchQueryJSON) => { ? buildFilterFormValuesFromQuery( queryJSON, policyCategories, - policyTagsLists, currencyList, personalDetails, allCards, @@ -114,4 +90,4 @@ const useFilterFormValues = (queryJSON?: SearchQueryJSON) => { }; export default useFilterFormValues; -export {policiesSelector, policyCategoriesSelector, policyTagsSelector}; +export {policiesSelector, policyCategoriesSelector}; diff --git a/src/hooks/useSearchTagFilters.ts b/src/hooks/useSearchTagFilters.ts new file mode 100644 index 000000000000..574bd2a6ebe9 --- /dev/null +++ b/src/hooks/useSearchTagFilters.ts @@ -0,0 +1,207 @@ +import {clearSearchTagFiltersState, openSearchTagFiltersPage, setSearchTagFiltersPagination} from '@libs/actions/Search'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type * as OnyxTypes from '@src/types/onyx'; + +import {useEffect, useRef, useState} from 'react'; + +import useNetwork from './useNetwork'; +import useOnyx from './useOnyx'; + +/** + * Hook for managing paginated tag filter search. + */ +type UseSearchTagFiltersResult = { + /** The paginated tag search results from Onyx */ + searchResults: OnyxTypes.SearchTagFilterItem[] | null | undefined; + + /** Whether a new search request is in flight */ + isSearching: boolean; + + /** Whether the next page of results is loading */ + isLoadingMore: boolean; + + /** Whether there are more pages to load */ + hasMore: boolean; + + /** Load the next page of results */ + loadMore: () => void; + + /** Start a new tag search with the given query */ + searchTags: (query: string) => void; + + /** Whether the first fetch is still in flight with no results to show yet */ + isInitialLoading: boolean; + + /** The search query of the currently displayed results */ + searchQuery: string; +}; + +/** + * Hook for managing paginated tag filter search. + * Handles API calls, pagination state, and Onyx data subscription. + * Pagination state is persisted in Onyx (RAM-only) to survive component remounts. + * Accepts a comma-separated list of policy IDs to scope results to specific workspaces. + */ +function useSearchTagFilters(policyIDs: string): UseSearchTagFiltersResult { + const {isOffline} = useNetwork(); + const [searchResults] = useOnyx(ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS); + const [paginationState] = useOnyx(ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION); + const [isSearching, setIsSearching] = useState(false); + const [isLoadingMore, setIsLoadingMore] = useState(false); + + // Derive pagination state from Onyx + const hasMore = paginationState?.hasMore ?? false; + const nextCursor = paginationState?.nextCursor ?? ''; + const searchQuery = paginationState?.searchQuery ?? ''; + + // Track if we have cached data to avoid showing loading state on remount + const hasCachedData = !!searchResults && searchResults.length > 0; + const [prevPolicyIDs, setPrevPolicyIDs] = useState(policyIDs); + const [isFilteringLocally, setIsFilteringLocally] = useState(false); + + if (prevPolicyIDs !== policyIDs) { + setPrevPolicyIDs(policyIDs); + setIsFilteringLocally(false); + } + + // Only treat the cache as complete when the empty-query dataset is fully loaded. + // A finished server search for a non-empty term can still be a partial result set. + const hasCompleteEmptyQueryCache = hasCachedData && !hasMore && (searchQuery === '' || isFilteringLocally); + + // Keep ref updated with latest values for use in stable callbacks + const stateRef = useRef({hasMore, nextCursor, searchQuery, searchResults, hasCachedData, hasCompleteEmptyQueryCache, isSearching, isLoadingMore}); + useEffect(() => { + stateRef.current = {hasMore, nextCursor, searchQuery, searchResults, hasCachedData, hasCompleteEmptyQueryCache, isSearching, isLoadingMore}; + }, [hasMore, nextCursor, searchQuery, searchResults, hasCachedData, hasCompleteEmptyQueryCache, isSearching, isLoadingMore]); + + // Incremented on every new search so a cancelled request doesn't clear the loading state of its successor + const requestSeqRef = useRef(0); + + // Gates the full-list spinner to the initial load. Once any search settles, the list stays mounted + // so the search input keeps focus while the user types, even when the latest results are empty. + const [hasCompletedSearch, setHasCompletedSearch] = useState(hasCachedData); + + const prevWasOfflineRef = useRef(isOffline); + + const loadMore = () => { + const { + hasMore: currentHasMore, + nextCursor: currentCursor, + searchQuery: currentQuery, + searchResults: currentResults, + isSearching: currentIsSearching, + isLoadingMore: currentIsLoadingMore, + } = stateRef.current; + if (currentIsSearching || currentIsLoadingMore || !currentHasMore || isOffline) { + return; + } + const requestSeq = requestSeqRef.current; + setIsLoadingMore(true); + openSearchTagFiltersPage({searchQuery: currentQuery, cursor: currentCursor, limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE, policyIDs}, false, currentResults ?? []) + .then(({hasMore: newHasMore, nextCursor: newCursor}) => { + setSearchTagFiltersPagination(newHasMore, newCursor, currentQuery); + }) + // Failures are already logged by the network Logging middleware. Cancelled requests are expected when a newer search supersedes them. + .catch(() => {}) + .finally(() => { + if (requestSeq !== requestSeqRef.current) { + return; + } + setIsLoadingMore(false); + }); + }; + + const searchTags = (query: string) => { + if (isOffline) { + // When offline, update the search query so TagSelector can filter cached results locally + setSearchTagFiltersPagination(stateRef.current.hasMore, stateRef.current.nextCursor, query); + return; + } + + const {hasCompleteEmptyQueryCache: currentHasCompleteEmptyQueryCache} = stateRef.current; + + // When the full empty-query dataset is already cached, filter locally instead of hitting the server on every keystroke. + if (currentHasCompleteEmptyQueryCache) { + setIsFilteringLocally(true); + setSearchTagFiltersPagination(false, '', query); + setHasCompletedSearch(true); + return; + } + + setIsFilteringLocally(false); + const requestSeq = ++requestSeqRef.current; + + // Reset pagination state immediately so loadMore doesn't fire with stale query/cursor + setSearchTagFiltersPagination(false, '', query); + + // A new search cancels any in-flight request, so it owns the loading state from here on. + // The cancelled loadMore skips its own reset when it sees the bumped sequence, so clear its spinner here. + setIsLoadingMore(false); + // The collection is cleared by openSearchTagFiltersPage, so there is no cached data to show silently. + setIsSearching(true); + + openSearchTagFiltersPage({searchQuery: query, cursor: '', limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE, policyIDs}, true) + .then(({hasMore: newHasMore, nextCursor: newCursor}) => { + setSearchTagFiltersPagination(newHasMore, newCursor, query); + }) + // Failures are already logged by the network Logging middleware. Cancelled requests are expected when a newer search supersedes them. + .catch(() => {}) + .finally(() => { + if (requestSeq !== requestSeqRef.current) { + return; + } + setHasCompletedSearch(true); + setIsSearching(false); + }); + }; + + // Clear persisted pagination and cached pages when the filter closes so a fresh open re-fetches with valid hasMore. + useEffect(() => { + return () => { + clearSearchTagFiltersState(); + }; + }, []); + + // Fetch the first page on mount, when the workspace scope changes, and on reconnect. + // Skips the fetch while offline and re-fetches on reconnect, matching useLoadSearchCategoryData. + // Reconnect uses the active search query so results stay in sync with the search input. + // searchTags is not memoized, so it cannot be in the dependency array. It would fire on every render. + // searchTags reads latest state via refs, so the closure captured here is safe to call. + useEffect(() => { + let isCancelled = false; + + if (isOffline) { + prevWasOfflineRef.current = true; + return; + } + + const wasOffline = prevWasOfflineRef.current; + prevWasOfflineRef.current = false; + + Promise.resolve().then(() => { + if (isCancelled) { + return; + } + + if (wasOffline) { + searchTags(stateRef.current.searchQuery); + return; + } + + searchTags(''); + }); + + return () => { + isCancelled = true; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [policyIDs, isOffline]); + + const isInitialLoading = isSearching && !hasCompletedSearch; + + return {searchResults, isSearching, isLoadingMore, hasMore, loadMore, searchTags, isInitialLoading, searchQuery}; +} + +export default useSearchTagFilters; diff --git a/src/libs/API/parameters/OpenSearchTagFiltersPageParams.ts b/src/libs/API/parameters/OpenSearchTagFiltersPageParams.ts new file mode 100644 index 000000000000..19eefb7d8196 --- /dev/null +++ b/src/libs/API/parameters/OpenSearchTagFiltersPageParams.ts @@ -0,0 +1,18 @@ +type OpenSearchTagFiltersPageParams = { + /** Search query to filter tags */ + searchQuery?: string; + + /** Cursor for pagination */ + cursor?: string; + + /** Maximum number of tags to return per page */ + limit?: number; + + /** Comma-separated list of policy IDs to scope the tag search to specific workspaces */ + policyIDs?: string; + + /** Whether the request can be aborted when superseded by a newer search */ + canCancel?: boolean; +}; + +export default OpenSearchTagFiltersPageParams; diff --git a/src/libs/API/parameters/OpenSearchTagFiltersPageResponse.ts b/src/libs/API/parameters/OpenSearchTagFiltersPageResponse.ts new file mode 100644 index 000000000000..187811aebbae --- /dev/null +++ b/src/libs/API/parameters/OpenSearchTagFiltersPageResponse.ts @@ -0,0 +1,14 @@ +import type {SearchTagFilterItem} from '@src/types/onyx'; + +type OpenSearchTagFiltersPageResponse = { + /** Whether more pages of tag filter results are available */ + hasMore?: boolean; + + /** Pagination cursor to pass for fetching the next page of tag filters */ + nextCursor?: string; + + /** Slice of tag filter results for this page */ + tags?: SearchTagFilterItem[]; +}; + +export default OpenSearchTagFiltersPageResponse; diff --git a/src/libs/API/parameters/index.ts b/src/libs/API/parameters/index.ts index fd90d5a6c1ff..7e7072ea393d 100644 --- a/src/libs/API/parameters/index.ts +++ b/src/libs/API/parameters/index.ts @@ -603,6 +603,8 @@ export type {default as UpdateSamlRequiredParams} from './UpdateSamlRequiredPara export type {default as AddMemberToDomainParams} from './AddMemberToDomainParams'; export type {default as GetInsightsParams} from './GetInsightsParams'; export type {default as OpenSearchPageParams} from './OpenSearchPageParams'; +export type {default as OpenSearchTagFiltersPageParams} from './OpenSearchTagFiltersPageParams'; +export type {default as OpenSearchTagFiltersPageResponse} from './OpenSearchTagFiltersPageResponse'; export type {default as OpenBulkChangeApproverPageParams} from './OpenBulkChangeApproverPageParams'; export type {default as SetPolicyRequireCompanyCardsEnabledParams} from './SetPolicyRequireCompanyCardsEnabled'; export type {default as SetTechnicalContactEmailParams} from './SetTechnicalContactEmailParams'; diff --git a/src/libs/API/types.ts b/src/libs/API/types.ts index e3ef4a8380bf..fc128967c43d 100644 --- a/src/libs/API/types.ts +++ b/src/libs/API/types.ts @@ -1746,6 +1746,7 @@ const SIDE_EFFECT_REQUEST_COMMANDS = { LINK_CARD_FEED_TO_POLICY: 'LinkCardFeedToPolicy', REVEAL_CARD_PIN: 'RevealCardPIN', CHANGE_CARD_PIN: 'ChangeCardPIN', + OPEN_SEARCH_TAG_FILTERS_PAGE: 'OpenSearchTagFiltersPage', } as const; type SideEffectRequestCommand = ValueOf; @@ -1794,6 +1795,7 @@ type SideEffectRequestCommandParameters = { [SIDE_EFFECT_REQUEST_COMMANDS.LINK_CARD_FEED_TO_POLICY]: Parameters.LinkCardToPolicyParams; [SIDE_EFFECT_REQUEST_COMMANDS.REVEAL_CARD_PIN]: Parameters.RevealCardPINParams; [SIDE_EFFECT_REQUEST_COMMANDS.CHANGE_CARD_PIN]: Parameters.ChangeCardPINParams; + [SIDE_EFFECT_REQUEST_COMMANDS.OPEN_SEARCH_TAG_FILTERS_PAGE]: Parameters.OpenSearchTagFiltersPageParams; }; type ApiRequestCommandParameters = WriteCommandParameters & ReadCommandParameters & SideEffectRequestCommandParameters; diff --git a/src/libs/ExportOnyxState/common.ts b/src/libs/ExportOnyxState/common.ts index 5af7ec55c397..46d51664888f 100644 --- a/src/libs/ExportOnyxState/common.ts +++ b/src/libs/ExportOnyxState/common.ts @@ -491,6 +491,8 @@ const onyxKeysToMaskFragileData = new Set([ ONYXKEYS.RAM_ONLY_HAS_DISMISSED_CONCIERGE_NOTIFICATION_BANNER, ONYXKEYS.RAM_ONLY_HAS_FRESH_WALLET_DATA, ONYXKEYS.RAM_ONLY_IS_LOADING_SEARCH_FILTERS_CATEGORY_DATA, + ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION, + ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS, ONYXKEYS.RAM_ONLY_WALLET_ONFIDO, ONYXKEYS.RECENTLY_USED_CURRENCIES, ONYXKEYS.RECENTLY_USED_REPORT_FIELDS, diff --git a/src/libs/HttpUtils.ts b/src/libs/HttpUtils.ts index 9877f4dd861d..d4ad52b448b9 100644 --- a/src/libs/HttpUtils.ts +++ b/src/libs/HttpUtils.ts @@ -32,6 +32,7 @@ const ABORT_COMMANDS = { All: 'All', [READ_COMMANDS.SEARCH_FOR_REPORTS]: READ_COMMANDS.SEARCH_FOR_REPORTS, [READ_COMMANDS.SEARCH_FOR_USERS]: READ_COMMANDS.SEARCH_FOR_USERS, + [SIDE_EFFECT_REQUEST_COMMANDS.OPEN_SEARCH_TAG_FILTERS_PAGE]: SIDE_EFFECT_REQUEST_COMMANDS.OPEN_SEARCH_TAG_FILTERS_PAGE, } as const; type AbortCommand = keyof typeof ABORT_COMMANDS; @@ -53,6 +54,7 @@ const abortControllerMap = new Map(); abortControllerMap.set(ABORT_COMMANDS.All, new AbortController()); abortControllerMap.set(ABORT_COMMANDS.SearchForReports, new AbortController()); abortControllerMap.set(ABORT_COMMANDS.SearchForUsers, new AbortController()); +abortControllerMap.set(ABORT_COMMANDS.OpenSearchTagFiltersPage, new AbortController()); /** * The API commands that require the skew calculation diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index b6cb7381cf2c..021310182ab2 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -1603,11 +1603,9 @@ function getDateRangeForPreset(preset: SearchDatePreset): {start: string; end: s * Reverse operation of buildQueryStringFromFilterFormValues() */ // Adds bankAccountList and currentUserAccountID for the new bank account and from:me filters. Refactoring this to a params object would touch every call site and is out of scope here. -// eslint-disable-next-line @typescript-eslint/max-params function buildFilterFormValuesFromQuery( queryJSON: SearchQueryJSON, policyCategories: OnyxCollection, - policyTags: OnyxCollection, currencyList: OnyxTypes.CurrencyList, personalDetails: OnyxTypes.PersonalDetailsList | undefined, cardList: OnyxTypes.CardList | undefined, @@ -1748,17 +1746,8 @@ function buildFilterFormValuesFromQuery( filtersForm[filterKey] = filterValues.find((currency) => validCurrencies.has(currency)); } if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG) { - const uniqueTags = new Set(); - const tagLists = getAllPolicyValues(policyID, ONYXKEYS.COLLECTION.POLICY_TAGS, policyTags); - for (const tagList of tagLists) { - for (const policyTagList of Object.values(tagList ?? {})) { - for (const tag of Object.values(policyTagList.tags ?? {})) { - uniqueTags.add(tag.name); - } - } - } - uniqueTags.add(CONST.SEARCH.TAG_EMPTY_VALUE); - filtersForm[addNegation(filterKey, isNegated)] = filterValues.filter((name) => uniqueTags.has(name)); + // Tag values are kept as-is: with server-side tag pagination the local tag data is never complete, so validating against it would silently drop valid tags + filtersForm[addNegation(filterKey, isNegated)] = filterValues; } if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY) { const uniqueCategories = new Set(); diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index d48d5a9e9196..38d0600a4de0 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -16,17 +16,20 @@ import type { ExportSearchWithTemplateParams, OpenBulkChangeApproverPageParams, OpenSearchPageParams, + OpenSearchTagFiltersPageParams, + OpenSearchTagFiltersPageResponse, QueueExportSearchItemsToCSVParams, QueueExportSearchWithTemplateParams, ReportExportParams, SubmitReportParams, } from '@libs/API/parameters'; -import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; +import {READ_COMMANDS, SIDE_EFFECT_REQUEST_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; import {getCommandURL} from '@libs/ApiUtils'; import deferModalPresentationAfterPopoverDismiss from '@libs/deferModalPresentationAfterPopoverDismiss'; import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import fileDownload from '@libs/fileDownload'; import {getExportFileName} from '@libs/fileDownload/FileUtils'; +import HttpUtils from '@libs/HttpUtils'; import Log from '@libs/Log'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import Navigation, {navigationRef} from '@libs/Navigation/Navigation'; @@ -88,6 +91,7 @@ import type { ReportActions, Rule, SaveSearch, + SearchTagFilterItem, Transaction, TransactionViolations, } from '@src/types/onyx'; @@ -1082,6 +1086,64 @@ function openSearchCategoryFiltersPage() { read(READ_COMMANDS.OPEN_SEARCH_CATEGORY_FILTERS_PAGE, null, {optimisticData, successData, finallyData}); } +/** + * Fetches a page of tag filter search results from the server. + * Returns pagination metadata (hasMore, nextCursor) for infinite scroll. + * A new search passes `shouldCancelPendingRequests` so a superseded in-flight request cannot overwrite the fresh results. + * `currentResults` is the already-loaded tag list, used to append the next page when a cursor is passed. + */ +function openSearchTagFiltersPage( + params: OpenSearchTagFiltersPageParams, + shouldCancelPendingRequests = false, + currentResults: SearchTagFilterItem[] = [], +): Promise<{hasMore: boolean; nextCursor: string}> { + if (shouldCancelPendingRequests) { + HttpUtils.cancelPendingRequests(SIDE_EFFECT_REQUEST_COMMANDS.OPEN_SEARCH_TAG_FILTERS_PAGE); + } + + const optimisticData: AnyOnyxUpdate[] = shouldCancelPendingRequests + ? [ + { + onyxMethod: Onyx.METHOD.SET, + key: ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS, + value: [], + }, + ] + : []; + + // The response body contains pagination metadata (hasMore, nextCursor) and tag slices needed to drive tag filter infinite scroll. + return makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.OPEN_SEARCH_TAG_FILTERS_PAGE, {...params, canCancel: true}, {optimisticData}).then((response) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- OpenSearchTagFiltersPage response fields are command-specific and not declared on the shared Response type + const tagFiltersResponse = response as OpenSearchTagFiltersPageResponse | undefined; + const newTags = tagFiltersResponse?.tags ?? []; + if (params.cursor && newTags.length > 0) { + Onyx.set(ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS, [...currentResults, ...newTags]); + } + return { + hasMore: !!tagFiltersResponse?.hasMore, + nextCursor: tagFiltersResponse?.nextCursor ?? '', + }; + }); +} + +/** + * Updates the pagination state for tag filter search. + * Stored in RAM-only Onyx key so it survives component remounts but resets on app restart. + */ +function setSearchTagFiltersPagination(hasMore: boolean, nextCursor: string, searchQuery: string) { + Onyx.set(ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION, { + hasMore, + nextCursor, + searchQuery, + }); +} + +/** Resets tag filter pagination and cached results when the filter closes. */ +function clearSearchTagFiltersState() { + setSearchTagFiltersPagination(false, '', ''); + Onyx.set(ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS, []); +} + function openBulkChangeApproverPage(reportIDList: OpenBulkChangeApproverPageParams['reportIDList']) { const optimisticData: Array> = [ { @@ -2509,6 +2571,9 @@ export { handlePreventSearchAPI, openSearchCardFiltersPage, openSearchCategoryFiltersPage, + openSearchTagFiltersPage, + setSearchTagFiltersPagination, + clearSearchTagFiltersState, getPolicyFromSearchSnapshot, getReportFromSearchSnapshot, getReportActionsFromSearchSnapshot, diff --git a/src/pages/Search/SearchAdvancedFiltersPage/SearchAdvancedFiltersBase.tsx b/src/pages/Search/SearchAdvancedFiltersPage/SearchAdvancedFiltersBase.tsx index e774465175be..5a2ea21b9225 100644 --- a/src/pages/Search/SearchAdvancedFiltersPage/SearchAdvancedFiltersBase.tsx +++ b/src/pages/Search/SearchAdvancedFiltersPage/SearchAdvancedFiltersBase.tsx @@ -8,7 +8,6 @@ import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@libs/Navigation/Navigation'; -import {getFilterNegatableValue} from '@libs/SearchUIUtils'; import {SearchAdvancedFiltersActionContext, SearchAdvancedFiltersContext} from '@pages/Search/SearchAdvancedFiltersProvider'; @@ -36,7 +35,6 @@ function SearchAdvancedFiltersBase() { Navigation.navigate(ROUTES.SEARCH_ADVANCED_FILTERS_CONTENT.getRoute(filterKey))} /> diff --git a/src/setup/index.ts b/src/setup/index.ts index 6ec4453f8a68..dd5640a5ada6 100644 --- a/src/setup/index.ts +++ b/src/setup/index.ts @@ -86,6 +86,8 @@ export default function () { ONYXKEYS.RAM_ONLY_WALLET_ONFIDO, ONYXKEYS.RAM_ONLY_HAS_FRESH_WALLET_DATA, ONYXKEYS.RAM_ONLY_IS_LOADING_SEARCH_FILTERS_CATEGORY_DATA, + ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION, + ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS, ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE, ONYXKEYS.COLLECTION.RAM_ONLY_COMPANY_CARDS_LOADING_STATE, ONYXKEYS.RAM_ONLY_MERCHANT_RULE_SUGGESTION, diff --git a/src/types/onyx/PolicyTag.ts b/src/types/onyx/PolicyTag.ts index a8f67a464883..5f5f9945d314 100644 --- a/src/types/onyx/PolicyTag.ts +++ b/src/types/onyx/PolicyTag.ts @@ -62,4 +62,13 @@ type PolicyTagLists = Record; -export type {PolicyTag, PolicyTags, PolicyTagLists, ParticipantsPolicyTags}; +/** Tag filter result item returned in flat searchTagFiltersResults array */ +type SearchTagFilterItem = { + /** Name of the tag */ + tagName: string; + + /** Name of the tag list */ + tagListName: string; +}; + +export type {PolicyTag, PolicyTags, PolicyTagLists, ParticipantsPolicyTags, SearchTagFilterItem}; diff --git a/src/types/onyx/SearchTagFiltersPaginationState.ts b/src/types/onyx/SearchTagFiltersPaginationState.ts new file mode 100644 index 000000000000..9e5c178086ec --- /dev/null +++ b/src/types/onyx/SearchTagFiltersPaginationState.ts @@ -0,0 +1,18 @@ +/** + * Pagination state for tag filter search results. + * + * Stored separately from the tag data so pagination survives component remounts + * without persisting to disk (RAM-only). + */ +type SearchTagFiltersPaginationState = { + /** Whether there are more pages to load */ + hasMore: boolean; + + /** Cursor for fetching the next page */ + nextCursor: string; + + /** The search query that produced this pagination state */ + searchQuery: string; +}; + +export default SearchTagFiltersPaginationState; diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 9d0bdb4bd3d2..59ef93468da9 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -143,7 +143,7 @@ import type PolicyEmployee from './PolicyEmployee'; import type PolicyJoinMember from './PolicyJoinMember'; import type PolicyOwnershipChangeChecks from './PolicyOwnershipChangeChecks'; import type PolicyRoomsMetadata from './PolicyRoomsMetadata'; -import type {ParticipantsPolicyTags, PolicyTag, PolicyTagLists, PolicyTags} from './PolicyTag'; +import type {ParticipantsPolicyTags, PolicyTag, PolicyTagLists, PolicyTags, SearchTagFilterItem} from './PolicyTag'; import type PolicyVendors from './PolicyVendor'; import type PrivatePersonalDetails from './PrivatePersonalDetails'; import type PrivatePromoDiscount from './PrivatePromoDiscount'; @@ -185,6 +185,7 @@ import type SearchFilters from './SearchFilters'; import type SearchFooterConversion from './SearchFooterConversion'; import type SearchResults from './SearchResults'; import type SearchSidebar from './SearchSidebar'; +import type SearchTagFiltersPaginationState from './SearchTagFiltersPaginationState'; import type SecurityGroup from './SecurityGroup'; import type {DomainSecurityGroupMembership} from './SecurityGroup'; import type SelectedTabRequest from './SelectedTabRequest'; @@ -328,6 +329,7 @@ export type { PolicyTags, PolicyTagLists, ParticipantsPolicyTags, + SearchTagFilterItem, PrivatePersonalDetails, QuickAction, ShareBankAccount, @@ -400,6 +402,7 @@ export type { PolicyJoinMember, PolicyRoomsMetadata, SearchResults, + SearchTagFiltersPaginationState, ReviewDuplicates, PrivateSubscription, PrivatePromoDiscount, diff --git a/tests/perf-test/useAdvancedSearchFilters.perf-test.tsx b/tests/perf-test/useAdvancedSearchFilters.perf-test.tsx index 62613cc84ada..f264b8b8ec66 100644 --- a/tests/perf-test/useAdvancedSearchFilters.perf-test.tsx +++ b/tests/perf-test/useAdvancedSearchFilters.perf-test.tsx @@ -76,7 +76,7 @@ jest.mock('@react-navigation/native', () => { function TestComponent() { const currentType = 'expense'; - const filters = useAdvancedSearchFilters(currentType, undefined); + const filters = useAdvancedSearchFilters(currentType); return ; } diff --git a/tests/perf-test/useFilterFormValues.perf-test.tsx b/tests/perf-test/useFilterFormValues.perf-test.tsx index 74e5f572338d..0810e34f6931 100644 --- a/tests/perf-test/useFilterFormValues.perf-test.tsx +++ b/tests/perf-test/useFilterFormValues.perf-test.tsx @@ -2,14 +2,14 @@ import {typeOptionsPoliciesSelector} from '@components/Search/FilterComponents/T import {advancedSearchPoliciesSelector} from '@hooks/useAdvancedSearchFilters'; import {exportedToPoliciesSelector} from '@hooks/useExportedToFilterOptions'; -import {policiesSelector, policyCategoriesSelector, policyTagsSelector} from '@hooks/useFilterFormValues'; +import {policiesSelector, policyCategoriesSelector} from '@hooks/useFilterFormValues'; import {getAllTaxRates} from '@libs/PolicyUtils'; import {buildFilterFormValuesFromQuery, buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import type {SearchQueryJSON} from '@src/components/Search/types'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, PolicyCategories, PolicyTagLists, Report} from '@src/types/onyx'; +import type {Policy, PolicyCategories, Report} from '@src/types/onyx'; import React, {useMemo} from 'react'; import {View} from 'react-native'; @@ -34,7 +34,6 @@ function buildSearchQueryJSONOrThrow(query: string): SearchQueryJSON { const POLICY_COUNT = 500; const REPORT_COUNT = 500; const CATEGORY_COUNT = 500; -const TAG_COUNT = 500; beforeAll(() => Onyx.init({keys: ONYXKEYS})); @@ -84,23 +83,6 @@ describe('useFilterFormValues', () => { await measureFunction(() => policyCategoriesSelector(categories)); }); - test('policyTagsSelector with 500 policy tag collections', async () => { - const tags = createCollection( - (_, index) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${index}`, - () => - createMock({ - Department: { - name: 'Department', - required: true, - tags: Object.fromEntries(Array.from({length: 30}, (_unused, i) => [`Tag${i}`, {name: `Tag${i}`, enabled: true}])), - }, - }), - TAG_COUNT, - ); - - await measureFunction(() => policyTagsSelector(tags)); - }); - test('exportedToPoliciesSelector with 500 policies', async () => { const policies = createCollection( (_, index) => `${ONYXKEYS.COLLECTION.POLICY}${index}`, @@ -171,7 +153,7 @@ describe('useFilterFormValues', () => { }); describe('buildFilterFormValuesFromQuery execution', () => { - test('buildFilterFormValuesFromQuery with 500 policies, reports, categories, tags', async () => { + test('buildFilterFormValuesFromQuery with 500 policies, reports, categories', async () => { const queryJSON = buildSearchQueryJSONOrThrow('type:expense status:all category:Category0 tag:Tag0'); const policies = createCollection( @@ -198,21 +180,9 @@ describe('useFilterFormValues', () => { () => createMock(Object.fromEntries(Array.from({length: 40}, (_unused, i) => [`Category${i}`, {name: `Category${i}`, enabled: true}]))), CATEGORY_COUNT, ); - const tags = createCollection( - (_, index) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${index}`, - () => - createMock({ - Department: { - name: 'Department', - required: true, - tags: Object.fromEntries(Array.from({length: 30}, (_unused, i) => [`Tag${i}`, {name: `Tag${i}`, enabled: true}])), - }, - }), - TAG_COUNT, - ); const taxRates = getAllTaxRates(policies); - await measureFunction(() => buildFilterFormValuesFromQuery(queryJSON, categories, tags, {}, {}, {}, reports, taxRates)); + await measureFunction(() => buildFilterFormValuesFromQuery(queryJSON, categories, {}, {}, {}, reports, taxRates)); }); }); @@ -223,10 +193,9 @@ describe('useFilterFormValues', () => { function TestComponent() { const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: policiesSelector}); const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [policyTagsLists] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS, {selector: policyTagsSelector}); const [policyCategories] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES, {selector: policyCategoriesSelector}); const taxRates = useMemo(() => getAllTaxRates(policies), [policies]); - const formValues = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTagsLists, {}, {}, {}, allReports, taxRates); + const formValues = buildFilterFormValuesFromQuery(queryJSON, policyCategories, {}, {}, {}, allReports, taxRates); return ; } @@ -243,18 +212,6 @@ describe('useFilterFormValues', () => { () => createMock(Object.fromEntries(Array.from({length: 40}, (_unused, i) => [`Category${i}`, {name: `Category${i}`, enabled: true}]))), CATEGORY_COUNT, ); - const tags = createCollection( - (_, index) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${index}`, - () => - createMock({ - Department: { - name: 'Department', - required: true, - tags: Object.fromEntries(Array.from({length: 30}, (_unused, i) => [`Tag${i}`, {name: `Tag${i}`, enabled: true}])), - }, - }), - TAG_COUNT, - ); const reports = createCollection( (_, index) => `${ONYXKEYS.COLLECTION.REPORT}${index}`, (index) => createMock({reportID: `${index}`, reportName: `Report ${index}`}), @@ -262,7 +219,6 @@ describe('useFilterFormValues', () => { ); await Onyx.mergeCollection(ONYXKEYS.COLLECTION.POLICY, policies); await Onyx.mergeCollection(ONYXKEYS.COLLECTION.POLICY_CATEGORIES, categories); - await Onyx.mergeCollection(ONYXKEYS.COLLECTION.POLICY_TAGS, tags); await Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, reports); await waitForBatchedUpdates(); @@ -282,10 +238,9 @@ describe('useFilterFormValues', () => { function TestComponent() { const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [policyTagsLists] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS); const [policyCategories] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES); const taxRates = useMemo(() => getAllTaxRates(policies), [policies]); - const formValues = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTagsLists, {}, {}, {}, allReports, taxRates); + const formValues = buildFilterFormValuesFromQuery(queryJSON, policyCategories, {}, {}, {}, allReports, taxRates); return ; } @@ -302,18 +257,6 @@ describe('useFilterFormValues', () => { () => createMock(Object.fromEntries(Array.from({length: 40}, (_unused, i) => [`Category${i}`, {name: `Category${i}`, enabled: true}]))), CATEGORY_COUNT, ); - const tags = createCollection( - (_, index) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${index}`, - () => - createMock({ - Department: { - name: 'Department', - required: true, - tags: Object.fromEntries(Array.from({length: 30}, (_unused, i) => [`Tag${i}`, {name: `Tag${i}`, enabled: true}])), - }, - }), - TAG_COUNT, - ); const reports = createCollection( (_, index) => `${ONYXKEYS.COLLECTION.REPORT}${index}`, (index) => createMock({reportID: `${index}`, reportName: `Report ${index}`}), @@ -321,7 +264,6 @@ describe('useFilterFormValues', () => { ); await Onyx.mergeCollection(ONYXKEYS.COLLECTION.POLICY, policies); await Onyx.mergeCollection(ONYXKEYS.COLLECTION.POLICY_CATEGORIES, categories); - await Onyx.mergeCollection(ONYXKEYS.COLLECTION.POLICY_TAGS, tags); await Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, reports); await waitForBatchedUpdates(); diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index bac007f8bdea..5872b2600fca 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -1214,7 +1214,6 @@ describe('SearchQueryUtils', () => { }, }, }; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1225,7 +1224,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense', @@ -1235,7 +1234,6 @@ describe('SearchQueryUtils', () => { test('action filter should be set to undefined if the input value is invalid', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1249,7 +1247,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - let result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + let result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense', @@ -1264,7 +1262,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense', @@ -1279,7 +1277,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result).toMatchObject({ type: 'expense-report', @@ -1290,7 +1288,6 @@ describe('SearchQueryUtils', () => { test('withdrawal status filter parses valid values and drops invalid ones', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1304,7 +1301,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - let result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + let result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense', @@ -1319,7 +1316,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense', @@ -1329,7 +1326,6 @@ describe('SearchQueryUtils', () => { test('paid status filter parses valid values and drops invalid ones', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1343,7 +1339,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - let result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + let result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense-report', @@ -1358,7 +1354,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense-report', @@ -1368,7 +1364,6 @@ describe('SearchQueryUtils', () => { test('parses negative backend amounts into filter form values', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1382,7 +1377,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result).toEqual({ type: 'expense', @@ -1394,7 +1389,6 @@ describe('SearchQueryUtils', () => { test('attendee filter preserves name-only attendees without filtering by personalDetails', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = { 12345: {accountID: 12345, login: 'user@example.com'}, @@ -1411,7 +1405,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); // Both values should be preserved - name-only attendees should not be filtered out expect(result).toEqual({ @@ -1422,7 +1416,6 @@ describe('SearchQueryUtils', () => { test('hydrates explicit date range flag from inclusive range boundaries', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1435,7 +1428,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result.dateAfter).toBeUndefined(); expect(result.dateBefore).toBeUndefined(); @@ -1444,7 +1437,6 @@ describe('SearchQueryUtils', () => { test('does not set explicit date range flag when only date boundaries are provided', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1457,7 +1449,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result.dateRange).toBeUndefined(); }); @@ -1480,7 +1472,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.dateOn).toBeUndefined(); expect(result.dateAfter).toBeUndefined(); expect(result.dateBefore).toBeUndefined(); @@ -1495,7 +1487,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.dateOn).toBeUndefined(); expect(result.dateAfter).toBeUndefined(); expect(result.dateBefore).toBeUndefined(); @@ -1510,7 +1502,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.approvedOn).toBeUndefined(); expect(result.approvedAfter).toBeUndefined(); expect(result.approvedBefore).toBeUndefined(); @@ -1525,7 +1517,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.dateOn).toBeUndefined(); expect(result.dateAfter).toBeUndefined(); expect(result.dateBefore).toBeUndefined(); @@ -1540,7 +1532,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.dateOn).toBe('last-12-months'); expect(result.dateRange).toBeUndefined(); }); @@ -1553,14 +1545,13 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.dateRange).toBe('2026-04-01,2026-04-15'); }); }); test('hydrates explicit report field range flag from inclusive range boundaries', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1573,7 +1564,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result['reportFieldAfter-start-date']).toBeUndefined(); expect(result['reportFieldBefore-start-date']).toBeUndefined(); @@ -1582,7 +1573,6 @@ describe('SearchQueryUtils', () => { test('does not set explicit report field range flag when only date boundaries are provided', () => { const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1595,7 +1585,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result['reportFieldRange-start-date']).toBeUndefined(); }); @@ -1603,7 +1593,6 @@ describe('SearchQueryUtils', () => { describe('view parameter', () => { const emptyParams = { policyCategories: {}, - policyTags: {}, currencyList: {}, personalDetails: {}, cardList: {}, @@ -1622,7 +1611,6 @@ describe('SearchQueryUtils', () => { const result = buildFilterFormValuesFromQuery( queryJSON, emptyParams.policyCategories, - emptyParams.policyTags, emptyParams.currencyList, emptyParams.personalDetails, emptyParams.cardList, @@ -1645,7 +1633,6 @@ describe('SearchQueryUtils', () => { const result = buildFilterFormValuesFromQuery( queryJSON, emptyParams.policyCategories, - emptyParams.policyTags, emptyParams.currencyList, emptyParams.personalDetails, emptyParams.cardList, @@ -1659,24 +1646,12 @@ describe('SearchQueryUtils', () => { }); }); - test('tag filter validates against policy tags', () => { + test('tag filter keeps values without validating against local tag data', () => { const policyID = generatePolicyID(); const queryString = `sortBy:date sortOrder:desc type:expense tag:Engineering,Marketing,NonExistent policyID:${policyID}`; const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = createMock>({ - [`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`]: { - Department: { - name: 'Department', - tags: { - Engineering: {name: 'Engineering', enabled: true}, - Marketing: {name: 'Marketing', enabled: true}, - Sales: {name: 'Sales', enabled: true}, - }, - }, - }, - }); const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1687,10 +1662,10 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); - // NonExistent should be filtered out since it's not in any policy's tags - expect(result.tag).toEqual(['Engineering', 'Marketing']); + // Local tag data is never complete with server-side tag pagination, so all values are kept + expect(result.tag).toEqual(['Engineering', 'Marketing', 'NonExistent']); }); test('currency filter validates against currency list', () => { @@ -1698,7 +1673,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = createMock({USD: {}, EUR: {}, GBP: {}}); const personalDetails = {}; const cardList = {}; @@ -1709,7 +1683,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); // INVALID should be filtered out expect(result.currency).toEqual(['USD', 'EUR']); @@ -1720,7 +1694,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1731,7 +1704,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); // nonexistent should be filtered out expect(result.taxRate).toEqual(['id_vat', 'id_gst']); @@ -1742,7 +1715,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1753,7 +1725,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); // invalid should be filtered out, cash and card are valid CONST.SEARCH.TRANSACTION_TYPE values expect(result.expenseType).toEqual(['cash', 'card']); @@ -1764,7 +1736,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1775,7 +1746,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); // invalid should be filtered out, ereceipt and hotel are valid CONST.SEARCH.RECEIPT_TYPE values expect(result.receiptType).toEqual(['ereceipt', 'hotel']); @@ -1786,7 +1757,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1797,7 +1767,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); // Pending and posted are mutually exclusive, so the form holds a single value: the first valid one, with the invalid value discarded expect(result.transactionStatus).toEqual('pending'); @@ -1812,7 +1782,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.transactionStatus).toEqual('posted'); }); @@ -1826,7 +1796,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.transactionStatusNot).toEqual('pending'); expect(result.transactionStatus).toBeUndefined(); @@ -1838,7 +1808,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1849,7 +1818,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result.receiptTypeNot).toEqual(['hotel']); expect(result.receiptType).toBeUndefined(); @@ -1861,7 +1830,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = { '12345': { @@ -1878,18 +1846,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery( - queryJSON, - policyCategories, - policyTags, - currencyList, - personalDetails, - cardList, - reports, - taxRates, - undefined, - currentUserAccountID, - ); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates, undefined, currentUserAccountID); expect(result.from).toEqual(['12345']); }); @@ -1899,7 +1856,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = { '12345': { @@ -1916,7 +1872,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTags, currencyList, personalDetails, cardList, reports, taxRates); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates); expect(result.from).toEqual([]); }); @@ -1927,7 +1883,6 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = {}; const currencyList = {}; const personalDetails = { '99999': { @@ -1944,18 +1899,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery( - queryJSON, - policyCategories, - policyTags, - currencyList, - personalDetails, - cardList, - reports, - taxRates, - undefined, - currentUserAccountID, - ); + const result = buildFilterFormValuesFromQuery(queryJSON, policyCategories, currencyList, personalDetails, cardList, reports, taxRates, undefined, currentUserAccountID); expect(result.to).toEqual(['99999']); }); @@ -1976,7 +1920,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.has).toEqual([CONST.SEARCH.HAS_VALUES.APPROVED_VIOLATION]); expect(result.hasNot).toBeUndefined(); }); @@ -1995,7 +1939,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to parse query string'); } - const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}, {}); + const result = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); expect(result.hasNot).toEqual([CONST.SEARCH.HAS_VALUES.APPROVED_VIOLATION]); expect(result.has).toBeUndefined(); }); diff --git a/tests/unit/hooks/useAdvancedSearchFilters.test.ts b/tests/unit/hooks/useAdvancedSearchFilters.test.ts index 5b301f6ab233..c99c72eb5a2f 100644 --- a/tests/unit/hooks/useAdvancedSearchFilters.test.ts +++ b/tests/unit/hooks/useAdvancedSearchFilters.test.ts @@ -105,7 +105,7 @@ describe('useAdvancedSearchFilters', () => { const policy = buildPolicy(1, {areCategoriesEnabled: false}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -119,7 +119,7 @@ describe('useAdvancedSearchFilters', () => { const policy = buildPolicy(1, {areTagsEnabled: false}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -132,7 +132,7 @@ describe('useAdvancedSearchFilters', () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}1`, buildTagList('Engineering')); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -140,48 +140,27 @@ describe('useAdvancedSearchFilters', () => { }); }); - it('hides tag filter when tags are enabled but no tags exist', async () => { + it('shows tag filter when tags are enabled but no tags exist', async () => { const policy = buildPolicy(1, {areTagsEnabled: true}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const emptyTagList: PolicyTagLists = { - Department: { - name: 'Department', - orderWeight: 0, - required: false, - tags: {}, - }, - }; - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}1`, emptyTagList); - - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); - // Tag filter is hidden because the tag list contains no actual tags await waitFor(() => { const allKeys = result.current.flat(); - expect(allKeys).not.toContain(CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG); + expect(allKeys).toContain(CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG); }); }); - it('hides tag filter when a selected policy has tags enabled but no tags exist', async () => { + it('shows tag filter when a selected policy has tags enabled but no tags exist', async () => { const policy = buildPolicy(1, {areTagsEnabled: true}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const emptyTagList: PolicyTagLists = { - Department: { - name: 'Department', - orderWeight: 0, - required: false, - tags: {}, - }, - }; - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}1`, emptyTagList); - - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, {value: ['1'], isNegated: false}), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); - expect(allKeys).not.toContain(CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG); + expect(allKeys).toContain(CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG); }); }); @@ -190,7 +169,7 @@ describe('useAdvancedSearchFilters', () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}1`, buildTagList('Engineering')); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, {value: ['1'], isNegated: false}), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -204,7 +183,7 @@ describe('useAdvancedSearchFilters', () => { const policy = buildPolicy(1, {tax: {trackingEnabled: false}}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -227,7 +206,7 @@ describe('useAdvancedSearchFilters', () => { }); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -248,7 +227,7 @@ describe('useAdvancedSearchFilters', () => { }); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -262,7 +241,7 @@ describe('useAdvancedSearchFilters', () => { const policy = buildPolicy(1, {type: CONST.POLICY.TYPE.CORPORATE, isAttendeeTrackingEnabled: false}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -276,7 +255,7 @@ describe('useAdvancedSearchFilters', () => { delete (policy as Record).isAttendeeTrackingEnabled; await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -288,7 +267,7 @@ describe('useAdvancedSearchFilters', () => { const policy = buildPolicy(1, {type: CONST.POLICY.TYPE.CORPORATE, isAttendeeTrackingEnabled: true}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -302,7 +281,7 @@ describe('useAdvancedSearchFilters', () => { const policy = buildPolicy(1, {fieldList: {}}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -332,7 +311,7 @@ describe('useAdvancedSearchFilters', () => { }); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -362,7 +341,7 @@ describe('useAdvancedSearchFilters', () => { }); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -373,7 +352,7 @@ describe('useAdvancedSearchFilters', () => { describe('bank account filter visibility', () => { it('hides bank account filter when no bank accounts exist', async () => { - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -395,7 +374,7 @@ describe('useAdvancedSearchFilters', () => { }, }); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -417,7 +396,7 @@ describe('useAdvancedSearchFilters', () => { }, }); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -439,7 +418,7 @@ describe('useAdvancedSearchFilters', () => { }, }); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -461,7 +440,7 @@ describe('useAdvancedSearchFilters', () => { }, }); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -483,7 +462,7 @@ describe('useAdvancedSearchFilters', () => { }, }); - const {result} = renderHook(() => useAdvancedSearchFilters(CONST.SEARCH.DATA_TYPES.CHAT, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(CONST.SEARCH.DATA_TYPES.CHAT), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); @@ -512,7 +491,7 @@ describe('useAdvancedSearchFilters', () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}1`, policy); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}1`, buildTagList('Engineering')); - const {result} = renderHook(() => useAdvancedSearchFilters(undefined, undefined), {wrapper}); + const {result} = renderHook(() => useAdvancedSearchFilters(undefined), {wrapper}); await waitFor(() => { const allKeys = result.current.flat(); diff --git a/tests/unit/hooks/useFilterFormValues.test.ts b/tests/unit/hooks/useFilterFormValues.test.ts index bf11e06d459c..849dd4b865c4 100644 --- a/tests/unit/hooks/useFilterFormValues.test.ts +++ b/tests/unit/hooks/useFilterFormValues.test.ts @@ -2,10 +2,10 @@ import {typeOptionsPoliciesSelector} from '@components/Search/FilterComponents/T import {advancedSearchPoliciesSelector} from '@hooks/useAdvancedSearchFilters'; import {exportedToPoliciesSelector} from '@hooks/useExportedToFilterOptions'; -import {policiesSelector, policyCategoriesSelector, policyTagsSelector} from '@hooks/useFilterFormValues'; +import {policiesSelector, policyCategoriesSelector} from '@hooks/useFilterFormValues'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, PolicyCategories, PolicyReportField, PolicyTagLists} from '@src/types/onyx'; +import type {Policy, PolicyCategories, PolicyReportField} from '@src/types/onyx'; import type {OnyxCollection} from 'react-native-onyx'; @@ -15,8 +15,6 @@ const POLICY_KEY = `${ONYXKEYS.COLLECTION.POLICY}1`; const POLICY_KEY_2 = `${ONYXKEYS.COLLECTION.POLICY}2`; const CATEGORIES_KEY = `${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}1`; const CATEGORIES_KEY_2 = `${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}2`; -const TAGS_KEY = `${ONYXKEYS.COLLECTION.POLICY_TAGS}1`; -const TAGS_KEY_2 = `${ONYXKEYS.COLLECTION.POLICY_TAGS}2`; describe('useFilterFormValues selectors', () => { describe('policiesSelector', () => { @@ -90,77 +88,6 @@ describe('useFilterFormValues selectors', () => { }); }); - describe('policyTagsSelector', () => { - it('returns undefined input as-is', () => { - expect(policyTagsSelector(undefined)).toBeUndefined(); - }); - - it('extracts only tag names', () => { - const tags: OnyxCollection = { - [TAGS_KEY]: createMock({ - Department: { - name: 'Department', - required: true, - tags: { - Engineering: {name: 'Engineering', enabled: true}, - Marketing: {name: 'Marketing', enabled: false}, - }, - }, - }), - }; - - const result = policyTagsSelector(tags); - - expect(result?.[TAGS_KEY]).toEqual({ - Department: { - tags: { - Engineering: {name: 'Engineering'}, - Marketing: {name: 'Marketing'}, - }, - }, - }); - }); - - it('skips undefined collection entries', () => { - const tags: OnyxCollection = { - [TAGS_KEY]: createMock({ - Department: { - tags: { - Engineering: {name: 'Engineering'}, - }, - }, - }), - [TAGS_KEY_2]: undefined, - }; - - const result = policyTagsSelector(tags); - - expect(result).toEqual({ - [TAGS_KEY]: { - Department: {tags: {Engineering: {name: 'Engineering'}}}, - }, - }); - expect(result).not.toHaveProperty(TAGS_KEY_2); - }); - - it('handles tag lists with empty tags object', () => { - const tags: OnyxCollection = { - [TAGS_KEY]: createMock({ - Department: { - name: 'Department', - tags: {}, - }, - }), - }; - - const result = policyTagsSelector(tags); - - expect(result?.[TAGS_KEY]).toEqual({ - Department: {tags: {}}, - }); - }); - }); - describe('exportedToPoliciesSelector', () => { it('returns undefined input as-is', () => { expect(exportedToPoliciesSelector(undefined)).toBeUndefined(); diff --git a/tests/unit/hooks/useSearchTagFiltersTest.ts b/tests/unit/hooks/useSearchTagFiltersTest.ts new file mode 100644 index 000000000000..428793775b3e --- /dev/null +++ b/tests/unit/hooks/useSearchTagFiltersTest.ts @@ -0,0 +1,322 @@ +import {act, renderHook, waitFor} from '@testing-library/react-native'; + +import useSearchTagFilters from '@hooks/useSearchTagFilters'; + +import {clearSearchTagFiltersState, openSearchTagFiltersPage, setSearchTagFiltersPagination} from '@libs/actions/Search'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +const mockOpenSearchTagFiltersPage = jest.mocked(openSearchTagFiltersPage); +const mockSetSearchTagFiltersPagination = jest.mocked(setSearchTagFiltersPagination); +const mockClearSearchTagFiltersState = jest.mocked(clearSearchTagFiltersState); + +const onyxData: Record = {}; + +let mockIsOffline = false; + +const mockUseOnyx = jest.fn((key: string) => [onyxData[key]]); +jest.mock('@hooks/useOnyx', () => ({ + __esModule: true, + default: (key: string) => mockUseOnyx(key), +})); + +jest.mock('@hooks/useNetwork', () => ({ + __esModule: true, + default: () => ({isOffline: mockIsOffline}), +})); + +jest.mock('@libs/actions/Search', () => ({ + openSearchTagFiltersPage: jest.fn(() => Promise.resolve({hasMore: false, nextCursor: ''})), + setSearchTagFiltersPagination: jest.fn(), + clearSearchTagFiltersState: jest.fn(), +})); + +jest.mock('@libs/Log', () => ({ + warn: jest.fn(), +})); + +const POLICY_ID = 'policy-1'; + +function setPartialTagFilterState(searchQuery: string) { + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION] = { + hasMore: true, + nextCursor: 'cursor-1', + searchQuery, + }; + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS] = [{tagName: `${searchQuery}-match`, tagListName: 'TagList'}]; +} + +function setCompleteTagFilterState(searchQuery: string) { + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION] = { + hasMore: false, + nextCursor: '', + searchQuery, + }; + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS] = [ + {tagName: `${searchQuery}-match`, tagListName: 'TagList'}, + {tagName: 'other-tag', tagListName: 'TagList'}, + ]; +} + +describe('useSearchTagFilters', () => { + beforeEach(() => { + for (const key of Object.keys(onyxData)) { + delete onyxData[key]; + } + mockIsOffline = false; + mockUseOnyx.mockClear(); + mockOpenSearchTagFiltersPage.mockClear().mockResolvedValue({hasMore: false, nextCursor: ''}); + mockSetSearchTagFiltersPagination.mockClear().mockImplementation((hasMore, nextCursor, searchQuery) => { + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION] = {hasMore, nextCursor, searchQuery}; + }); + mockClearSearchTagFiltersState.mockClear().mockImplementation(() => { + delete onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS]; + delete onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION]; + }); + }); + + it('fetches with an empty query on mount when pagination still holds a previous search term', async () => { + setPartialTagFilterState('marketing'); + + renderHook(() => useSearchTagFilters(POLICY_ID)); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledWith( + expect.objectContaining({searchQuery: '', policyIDs: POLICY_ID, cursor: '', limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE}), + true, + ); + }); + + expect(mockOpenSearchTagFiltersPage).not.toHaveBeenCalledWith(expect.objectContaining({searchQuery: 'marketing'}), expect.anything()); + }); + + it('clears persisted pagination and cached tags when the filter unmounts', () => { + setPartialTagFilterState('marketing'); + + const {unmount} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + unmount(); + + expect(mockClearSearchTagFiltersState).toHaveBeenCalledTimes(1); + }); + + it('re-fetches on remount after leaving the filter so pagination can continue', async () => { + setPartialTagFilterState(''); + mockOpenSearchTagFiltersPage.mockResolvedValueOnce({hasMore: true, nextCursor: 'cursor-1'}); + + const {unmount} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledTimes(1); + }); + + unmount(); + + mockOpenSearchTagFiltersPage.mockClear().mockResolvedValueOnce({hasMore: true, nextCursor: 'cursor-2'}); + + const {result} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledWith( + expect.objectContaining({searchQuery: '', policyIDs: POLICY_ID, cursor: '', limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE}), + true, + ); + }); + + await waitFor(() => { + expect(onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION]).toEqual(expect.objectContaining({hasMore: true, nextCursor: 'cursor-2', searchQuery: ''})); + }); + + mockOpenSearchTagFiltersPage.mockClear().mockResolvedValueOnce({hasMore: false, nextCursor: ''}); + + act(() => { + result.current.loadMore(); + }); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledWith( + expect.objectContaining({searchQuery: '', policyIDs: POLICY_ID, cursor: 'cursor-2', limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE}), + false, + [], + ); + }); + }); + + it('clears the page-loading state when a new search supersedes an in-flight page load', async () => { + setPartialTagFilterState(''); + mockOpenSearchTagFiltersPage.mockResolvedValueOnce({hasMore: true, nextCursor: 'cursor-2'}); + + const {result} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await waitFor(() => { + expect(onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION]).toEqual(expect.objectContaining({hasMore: true, nextCursor: 'cursor-2'})); + }); + + // Keep the next page request in flight so the search starts while it is still pending + mockOpenSearchTagFiltersPage.mockReturnValueOnce(new Promise(() => {})); + + act(() => { + result.current.loadMore(); + }); + + await waitFor(() => { + expect(result.current.isLoadingMore).toBe(true); + }); + + mockOpenSearchTagFiltersPage.mockResolvedValueOnce({hasMore: false, nextCursor: ''}); + + act(() => { + result.current.searchTags('marketing'); + }); + + await waitFor(() => { + expect(result.current.isLoadingMore).toBe(false); + }); + }); + + it('re-fetches with the active search query on reconnect while the filter stays mounted', async () => { + setPartialTagFilterState('travel'); + mockIsOffline = true; + + const {rerender} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await act(async () => { + await Promise.resolve(); + }); + expect(mockOpenSearchTagFiltersPage).not.toHaveBeenCalled(); + + mockIsOffline = false; + rerender({}); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledWith(expect.objectContaining({searchQuery: 'travel', policyIDs: POLICY_ID}), true); + }); + }); + + it('preserves pagination metadata when searching offline and re-fetches on reconnect after clearing', async () => { + setPartialTagFilterState(''); + mockOpenSearchTagFiltersPage.mockResolvedValueOnce({hasMore: true, nextCursor: 'cursor-1'}); + + const {result, rerender} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledTimes(1); + }); + + mockIsOffline = true; + rerender({}); + + act(() => { + result.current.searchTags('marketing'); + }); + + expect(mockSetSearchTagFiltersPagination).toHaveBeenCalledWith(true, 'cursor-1', 'marketing'); + + act(() => { + result.current.searchTags(''); + }); + + expect(mockSetSearchTagFiltersPagination).toHaveBeenCalledWith(true, 'cursor-1', ''); + + mockIsOffline = false; + mockOpenSearchTagFiltersPage.mockClear(); + rerender({}); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledWith( + expect.objectContaining({searchQuery: '', policyIDs: POLICY_ID, cursor: '', limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE}), + true, + ); + }); + }); + + it('does not call the API when searching with a complete cached dataset', async () => { + setCompleteTagFilterState(''); + + const {result} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await act(async () => { + await Promise.resolve(); + }); + mockOpenSearchTagFiltersPage.mockClear(); + + act(() => { + result.current.searchTags('marketing'); + }); + + expect(mockOpenSearchTagFiltersPage).not.toHaveBeenCalled(); + expect(mockSetSearchTagFiltersPagination).toHaveBeenCalledWith(false, '', 'marketing'); + }); + + it('does not call the API on consecutive keystrokes when searching with a complete cached dataset', async () => { + setCompleteTagFilterState(''); + + const {result} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await act(async () => { + await Promise.resolve(); + }); + mockOpenSearchTagFiltersPage.mockClear(); + + act(() => { + result.current.searchTags('m'); + }); + + expect(mockOpenSearchTagFiltersPage).not.toHaveBeenCalled(); + expect(mockSetSearchTagFiltersPagination).toHaveBeenCalledWith(false, '', 'm'); + + act(() => { + result.current.searchTags('ma'); + }); + + expect(mockOpenSearchTagFiltersPage).not.toHaveBeenCalled(); + expect(mockSetSearchTagFiltersPagination).toHaveBeenCalledWith(false, '', 'ma'); + }); + + it('re-fetches when clearing a server search that only cached partial results', async () => { + setPartialTagFilterState(''); + + const {result, rerender} = renderHook(() => useSearchTagFilters(POLICY_ID)); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledTimes(1); + }); + + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_PAGINATION] = { + hasMore: false, + nextCursor: '', + searchQuery: 'ch', + }; + onyxData[ONYXKEYS.RAM_ONLY_SEARCH_TAG_FILTERS_RESULTS] = [ + {tagName: 'chicago', tagListName: 'TagList'}, + {tagName: 'charlotte', tagListName: 'TagList'}, + ]; + rerender({}); + mockOpenSearchTagFiltersPage.mockClear(); + + act(() => { + result.current.searchTags(''); + }); + + await waitFor(() => { + expect(mockOpenSearchTagFiltersPage).toHaveBeenCalledWith( + expect.objectContaining({searchQuery: '', policyIDs: POLICY_ID, cursor: '', limit: CONST.SEARCH.TAG_FILTER_PAGE_SIZE}), + true, + ); + }); + }); + + it('resets the search query on mount without refetching when the full empty-query dataset is already cached', async () => { + setCompleteTagFilterState(''); + + renderHook(() => useSearchTagFilters(POLICY_ID)); + + await act(async () => { + await Promise.resolve(); + }); + + expect(mockOpenSearchTagFiltersPage).not.toHaveBeenCalled(); + expect(mockSetSearchTagFiltersPagination).toHaveBeenCalledWith(false, '', ''); + }); +});