Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions src/components/Search/SearchQueryProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import useCardFeedsForDisplay from '@hooks/useCardFeedsForDisplay';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useLoadSearchCategoryData from '@hooks/useLoadSearchCategoryData';
import useOnyx from '@hooks/useOnyx';
import usePreviousDefined from '@hooks/usePreviousDefined';
import useRootNavigationState from '@hooks/useRootNavigationState';

import {getDeepestFocusedScreen} from '@libs/Navigation/Navigation';
import {buildSearchQueryJSON, buildSearchQueryString} from '@libs/SearchQueryUtils';
import {getSuggestedSearches, getSuggestedSearchesVisibility} from '@libs/SearchUIUtils';
import {getSuggestedSearches} from '@libs/SearchUIUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';

import type {NavigationState} from '@react-navigation/routers';

import {useNavigation} from '@react-navigation/native';
import React, {useMemo, useState} from 'react';
import React, {useState} from 'react';

import type {SearchQueryActionsValue, SearchQueryContextValue} from './types';

Expand Down Expand Up @@ -48,12 +46,9 @@ function SearchQueryProvider({children}: SearchQueryProviderProps) {
useLoadSearchCategoryData({shouldLoad: shouldLoadCategoryData});

const {defaultCardFeed, activeExpensifyCardFeedID} = useCardFeedsForDisplay();
const {accountID, email} = useCurrentUserPersonalDetails();
const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const {accountID} = useCurrentUserPersonalDetails();
const defaultCardFeedID = defaultCardFeed?.id;
// Only policy IDs are needed so Top Spenders matches the type menu hash; card feeds aren't used for that eligibility.
const topSpendersPolicyIDs = useMemo(() => getSuggestedSearchesVisibility(email, {}, policies, undefined).topSpendersPolicyIDs, [email, policies]);
const suggestedSearches = getSuggestedSearches(accountID, defaultCardFeedID, undefined, topSpendersPolicyIDs, activeExpensifyCardFeedID);
const suggestedSearches = getSuggestedSearches(accountID, defaultCardFeedID, undefined, activeExpensifyCardFeedID);

const currentSearchHash = currentSearchQueryJSON?.hash ?? -1;
const currentSimilarSearchHash = currentSearchQueryJSON?.similarSearchHash ?? -1;
Expand Down
13 changes: 2 additions & 11 deletions src/libs/SearchUIUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,6 @@ function getSuggestedSearches(
accountID: number = CONST.DEFAULT_NUMBER_ID,
defaultFeedID?: string,
shouldShowExpensifyCard?: boolean,
topSpendersPolicyIDs: string[] = [],
activeExpensifyCardFeedID?: string,
): Record<ValueOf<typeof CONST.SEARCH.SEARCH_KEYS>, SearchTypeMenuItem> {
// Card accruals (UNAPPROVED_CARD) defaults to the active workspace's Expensify Card when it has one,
Expand Down Expand Up @@ -1016,8 +1015,6 @@ function getSuggestedSearches(
type: CONST.SEARCH.DATA_TYPES.EXPENSE,
groupBy: CONST.SEARCH.GROUP_BY.FROM,
dateOn: CONST.SEARCH.DATE_PRESETS.LAST_MONTH,
// Scope Top Spenders to the eligible workspaces so individual-chat/personal expenses don't leak in.
...(topSpendersPolicyIDs.length > 0 ? {policyID: topSpendersPolicyIDs} : {}),
status: [
CONST.SEARCH.STATUS.EXPENSE.DRAFTS,
CONST.SEARCH.STATUS.EXPENSE.OUTSTANDING,
Expand Down Expand Up @@ -1156,7 +1153,7 @@ function getSuggestedSearchesVisibility(
hasReportAwaitingApproval = false,
isTrackIntentUser = false,
policyCategories?: OnyxCollection<OnyxTypes.PolicyCategories>,
): {visibility: Record<ValueOf<typeof CONST.SEARCH.SEARCH_KEYS>, boolean>; hasEligibleGroupPolicies: boolean; shouldShowExpensifyCard: boolean; topSpendersPolicyIDs: string[]} {
): {visibility: Record<ValueOf<typeof CONST.SEARCH.SEARCH_KEYS>, boolean>; hasEligibleGroupPolicies: boolean; shouldShowExpensifyCard: boolean} {
let shouldShowSubmitSuggestion = false;
let shouldShowPaySuggestion = false;
let shouldShowApproveSuggestion = hasReportAwaitingApproval;
Expand All @@ -1172,7 +1169,6 @@ function getSuggestedSearchesVisibility(
let shouldShowViolationsBySubmitterSuggestion = false;
let hasEligibleGroupPolicies = false;
let shouldShowSpendOverTimeSuggestion = false;
const topSpendersPolicyIDs: string[] = [];

const hasCardFeed = Object.values(cardFeedsByPolicy ?? {}).some((feeds) => feeds.length > 0);
const hasAnyPolicyWithWorkflowsEnabled = Object.values(policies ?? {}).some((policy) => policy?.areWorkflowsEnabled);
Expand Down Expand Up @@ -1233,9 +1229,6 @@ function getSuggestedSearchesVisibility(
shouldShowExpensifyCardSuggestion ||= isEligibleForExpensifyCardSuggestion;
shouldShowReimbursementsSuggestion ||= isEligibleForReimbursementsSuggestion;
shouldShowTopSpendersSuggestion ||= isEligibleForTopSpendersSuggestion;
if (policy.id && isEligibleForTopSpendersSuggestion) {
topSpendersPolicyIDs.push(policy.id);
}
shouldShowTopCategoriesSuggestion ||= isEligibleForTopCategoriesSuggestion;
shouldShowTopMerchantsSuggestion ||= isEligibleForTopMerchantsSuggestion;
shouldShowViolationsBySubmitterSuggestion ||= isEligibleForViolationsBySubmitterSuggestion;
Expand Down Expand Up @@ -1267,7 +1260,6 @@ function getSuggestedSearchesVisibility(
},
hasEligibleGroupPolicies,
shouldShowExpensifyCard: shouldShowExpensifyCardSuggestion,
topSpendersPolicyIDs,
};
}

Expand Down Expand Up @@ -5028,9 +5020,8 @@ function createTypeMenuSections(params: TypeMenuSectionsParams): SearchTypeMenuS
visibility: suggestedSearchesVisibility,
hasEligibleGroupPolicies,
shouldShowExpensifyCard,
topSpendersPolicyIDs,
} = getSuggestedSearchesVisibility(currentUserEmail, cardFeedsByPolicy, policies, defaultExpensifyCard, hasReportAwaitingApproval, isTrackIntentUser, policyCategories);
const suggestedSearches = getSuggestedSearches(currentUserAccountID, defaultCardFeed?.id, shouldShowExpensifyCard, topSpendersPolicyIDs, activeExpensifyCardFeedID);
const suggestedSearches = getSuggestedSearches(currentUserAccountID, defaultCardFeed?.id, shouldShowExpensifyCard, activeExpensifyCardFeedID);
const hasAnyPolicyWithWorkflowsEnabled = Object.values(policies ?? {}).some((policy) => policy?.areWorkflowsEnabled);
const isTrackIntentWithWorkflowsDisabled = isTrackIntentUser && !hasAnyPolicyWithWorkflowsEnabled;

Expand Down
11 changes: 2 additions & 9 deletions src/pages/home/InsightsSection/useHomeInsightConfigs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,8 @@ function useHomeInsightConfigs(): SearchTypeMenuItem[] {
const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector});
const {defaultCardFeed, cardFeedsByPolicy} = useCardFeedsForDisplay();

const {visibility, shouldShowExpensifyCard, topSpendersPolicyIDs} = getSuggestedSearchesVisibility(
session?.email,
cardFeedsByPolicy,
policies,
defaultExpensifyCard,
false,
!!isTrackIntentUser,
);
const suggestedSearches = getSuggestedSearches(session?.accountID, (defaultCardFeed ?? defaultExpensifyCard)?.id, shouldShowExpensifyCard, topSpendersPolicyIDs);
const {visibility, shouldShowExpensifyCard} = getSuggestedSearchesVisibility(session?.email, cardFeedsByPolicy, policies, defaultExpensifyCard, false, !!isTrackIntentUser);
const suggestedSearches = getSuggestedSearches(session?.accountID, (defaultCardFeed ?? defaultExpensifyCard)?.id, shouldShowExpensifyCard);

return HOME_INSIGHT_KEYS.filter((key) => visibility[key]).map((key) => suggestedSearches[key]);
}
Expand Down
48 changes: 3 additions & 45 deletions tests/unit/Search/SearchUIUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10342,48 +10342,6 @@ describe('SearchUIUtils', () => {
expect(response.visibility.topSpenders).toBe(true);
});

test('Should collect Top Spenders-eligible policy IDs and scope the suggested search query to them', () => {
const eligiblePolicyID = 'GROUP_POLICY_01';
const ineligiblePolicyID = 'PERSONAL_POLICY_02';

const policies: OnyxCollection<OnyxTypes.Policy> = {
[`policy_${eligiblePolicyID}`]: {
...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM),
id: eligiblePolicyID,
role: CONST.POLICY.ROLE.ADMIN,
employeeList: {
'employee1@policy.com': {submitsTo: '', forwardsTo: ''},
'employee2@policy.com': {submitsTo: '', forwardsTo: ''},
},
},
// Personal (non-group) policy is not eligible for Top Spenders and must not be scoped in.
[`policy_${ineligiblePolicyID}`]: {
...createRandomPolicy(2, CONST.POLICY.TYPE.PERSONAL),
id: ineligiblePolicyID,
role: CONST.POLICY.ROLE.ADMIN,
employeeList: {
'employee1@policy.com': {submitsTo: '', forwardsTo: ''},
'employee2@policy.com': {submitsTo: '', forwardsTo: ''},
},
},
};

const response = SearchUIUtils.getSuggestedSearchesVisibility(adminEmail, {}, policies, undefined);
expect(response.visibility.topSpenders).toBe(true);
expect(response.topSpendersPolicyIDs).toEqual([eligiblePolicyID]);

const suggestedSearches = SearchUIUtils.getSuggestedSearches(adminAccountID, undefined, undefined, response.topSpendersPolicyIDs);
const topSpendersQuery = suggestedSearches[CONST.SEARCH.SEARCH_KEYS.TOP_SPENDERS].searchQuery;
expect(topSpendersQuery).toContain(`${CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID}:${eligiblePolicyID}`);
expect(topSpendersQuery).not.toContain(ineligiblePolicyID);
});

test('Should not add a policyID filter to the Top Spenders query when there are no eligible workspaces', () => {
const suggestedSearches = SearchUIUtils.getSuggestedSearches(adminAccountID, undefined, undefined, []);
const topSpendersQuery = suggestedSearches[CONST.SEARCH.SEARCH_KEYS.TOP_SPENDERS].searchQuery;
expect(topSpendersQuery).not.toContain(`${CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID}:`);
});

test('Should show Spend Over Time for workflow approver (forwardsTo) in paid policy', () => {
const workflowApproverEmail = 'workflow-approver@policy.com';
const policyKey = `policy_${policyID}`;
Expand Down Expand Up @@ -10609,7 +10567,7 @@ describe('SearchUIUtils', () => {
const activeExpensifyCardFeedID = 'fund1_Expensify Card';

const getCardAccrualsFeedValues = (activeCardFeedID?: string, defaultFeedID?: string): unknown[] => {
const suggestedSearches = SearchUIUtils.getSuggestedSearches(adminAccountID, defaultFeedID, undefined, [], activeCardFeedID);
const suggestedSearches = SearchUIUtils.getSuggestedSearches(adminAccountID, defaultFeedID, undefined, activeCardFeedID);
const cardAccruals = suggestedSearches[CONST.SEARCH.SEARCH_KEYS.UNAPPROVED_CARD];
const feedFilter = cardAccruals.searchQueryJSON?.flatFilters?.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.FEED);
return (feedFilter?.filters ?? []).map((f) => f.value).filter(Boolean);
Expand Down Expand Up @@ -10637,8 +10595,8 @@ describe('SearchUIUtils', () => {
// real call sites differ in the `defaultFeedID` and `shouldShowExpensifyCard` args, so mirror that here to
// prove Card accruals is driven purely by `activeExpensifyCardFeedID` and doesn't split on those inputs.
const otherCompanyFeedID = 'fund2_oauth.chase.com';
const fromProvider = SearchUIUtils.getSuggestedSearches(adminAccountID, companyFeedID, undefined, [], activeExpensifyCardFeedID);
const fromMenu = SearchUIUtils.getSuggestedSearches(adminAccountID, otherCompanyFeedID, true, [], activeExpensifyCardFeedID);
const fromProvider = SearchUIUtils.getSuggestedSearches(adminAccountID, companyFeedID, undefined, activeExpensifyCardFeedID);
const fromMenu = SearchUIUtils.getSuggestedSearches(adminAccountID, otherCompanyFeedID, true, activeExpensifyCardFeedID);
expect(fromMenu[CONST.SEARCH.SEARCH_KEYS.UNAPPROVED_CARD].similarSearchHash).toBe(fromProvider[CONST.SEARCH.SEARCH_KEYS.UNAPPROVED_CARD].similarSearchHash);
});
});
Expand Down
1 change: 0 additions & 1 deletion tests/unit/TransactionGroupListItemTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ jest.mock('@libs/SearchUIUtils', () => ({
isCorrectSearchUserName: jest.fn(() => true),
getTableMinWidth: jest.fn(() => 0),
getSuggestedSearches: jest.fn(() => ({})),
getSuggestedSearchesVisibility: jest.fn(() => ({topSpendersPolicyIDs: []})),
getSubmittedViolationsForTransaction: jest.fn(() => ''),
}));

Expand Down
Loading