From 7ee52ac43b08e8cd01252b0b44c51ec372cb2db3 Mon Sep 17 00:00:00 2001 From: Mukher Date: Tue, 21 Apr 2026 08:18:58 +0500 Subject: [PATCH 01/13] auto-select workspace after confirmation on creating report --- src/ROUTES.ts | 12 +- src/hooks/useCreateReportAction.tsx | 134 ++++++ src/libs/Navigation/types.ts | 2 + src/pages/NewReportWorkspaceSelectionPage.tsx | 34 +- src/pages/Search/EmptySearchView.tsx | 52 +-- .../menuItems/CreateReportMenuItem.tsx | 59 +-- .../request/step/IOURequestStepUpgrade.tsx | 6 +- tests/unit/useCreateReportActionTest.tsx | 411 ++++++++++++++++++ 8 files changed, 600 insertions(+), 110 deletions(-) create mode 100644 src/hooks/useCreateReportAction.tsx create mode 100644 tests/unit/useCreateReportActionTest.tsx diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 412d0f86092d..28cf093fbd0b 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -897,8 +897,16 @@ const ROUTES = { NEW_REPORT_WORKSPACE_SELECTION: { route: 'new-report-workspace-selection', - getRoute: (isMovingExpenses?: boolean, backTo?: string) => { - const baseRoute = `new-report-workspace-selection${isMovingExpenses ? '?isMovingExpenses=true' : ''}` as const; + getRoute: (isMovingExpenses?: boolean, backTo?: string, selectedPolicyID?: string) => { + const params = new URLSearchParams(); + if (isMovingExpenses) { + params.set('isMovingExpenses', 'true'); + } + if (selectedPolicyID) { + params.set('selectedPolicyID', selectedPolicyID); + } + const query = params.toString(); + const baseRoute = `new-report-workspace-selection${query ? `?${query}` : ''}` as const; // eslint-disable-next-line no-restricted-syntax -- Legacy route generation return getUrlWithBackToParam(baseRoute, backTo); diff --git a/src/hooks/useCreateReportAction.tsx b/src/hooks/useCreateReportAction.tsx new file mode 100644 index 000000000000..9e4000aae89e --- /dev/null +++ b/src/hooks/useCreateReportAction.tsx @@ -0,0 +1,134 @@ +import {useCallback} from 'react'; +import type {OnyxEntry} from 'react-native-onyx'; +import interceptAnonymousUser from '@libs/interceptAnonymousUser'; +import Navigation from '@libs/Navigation/Navigation'; +import {getDefaultChatEnabledPolicy} from '@libs/PolicyUtils'; +import {generateReportID} from '@libs/ReportUtils'; +import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; +import useRedirectToExpensifyClassic from '@pages/inbox/sidebar/FABPopoverContent/useRedirectToExpensifyClassic'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; +import type * as OnyxTypes from '@src/types/onyx'; +import useCreateEmptyReportConfirmation from './useCreateEmptyReportConfirmation'; +import useHasEmptyReportsForPolicy from './useHasEmptyReportsForPolicy'; +import useOnyx from './useOnyx'; + +type UseCreateReportActionParams = { + /** Callback that creates the report and navigates after creation */ + onCreateReport: (shouldDismissEmptyReportsConfirmation?: boolean) => void; + /** Group paid policies with expense chat enabled */ + groupPoliciesWithChatEnabled: readonly never[] | Array>; + /** Whether the empty-report confirmation modal should push a history entry so browser-back dismisses it (default: true) */ + shouldHandleNavigationBack?: boolean; +}; + +type UseCreateReportActionResult = { + /** The action to trigger when the user clicks "Create report" */ + createReportAction: () => void; + /** Whether the menu item/button should be visible — false only when redirecting to Classic is required but not currently possible */ + isVisible: boolean; +}; + +/** + * Hook that encapsulates the shared "create report" branching logic used across + * the FAB, the search Create dropdown, and the empty reports state. + * + * Decision flow: + * 1. Redirect to Expensify Classic if all group policies have expense chat disabled + * 2. Navigate to upgrade path if user has no valid group policies at all + * 3. Navigate to workspace selector if no default workspace or restricted with multiple options + * 4. Show empty report confirmation or create directly if workspace is valid + * 5. Navigate to restricted action if billing restricts the workspace + */ +export default function useCreateReportAction({onCreateReport, groupPoliciesWithChatEnabled, shouldHandleNavigationBack = true}: UseCreateReportActionParams): UseCreateReportActionResult { + const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); + const [activePolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`); + const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); + const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); + const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); + const [hasDismissedEmptyReportsConfirmation] = useOnyx(ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED); + + const {shouldRedirectToExpensifyClassic, canUseAction, showRedirectToExpensifyClassicModal} = useRedirectToExpensifyClassic(); + + // Visible whenever clicking the button would do something meaningful (upgrade flow, workspace selection, direct create, or classic redirect). + // Hidden only when classic redirect is required but currently suppressed (e.g. TryNewDot loading / hybrid app state). + const isVisible = canUseAction; + const shouldNavigateToUpgradePath = !shouldRedirectToExpensifyClassic && groupPoliciesWithChatEnabled.length === 0; + + const defaultChatEnabledPolicy = getDefaultChatEnabledPolicy(groupPoliciesWithChatEnabled as Array>, activePolicy); + const defaultChatEnabledPolicyID = defaultChatEnabledPolicy?.id; + + const hasEmptyReport = useHasEmptyReportsForPolicy(defaultChatEnabledPolicyID); + const shouldShowEmptyReportConfirmation = hasEmptyReport && hasDismissedEmptyReportsConfirmation !== true; + + const {openCreateReportConfirmation} = useCreateEmptyReportConfirmation({ + policyID: defaultChatEnabledPolicyID, + policyName: defaultChatEnabledPolicy?.name ?? '', + onConfirm: onCreateReport, + shouldHandleNavigationBack, + }); + + const createReportAction = useCallback(() => { + interceptAnonymousUser(() => { + if (shouldRedirectToExpensifyClassic) { + showRedirectToExpensifyClassicModal(); + return; + } + + // No valid policy at all → upgrade + create workspace flow + if (shouldNavigateToUpgradePath) { + const freshReportID = generateReportID(); + const freshTransactionID = generateReportID(); + Navigation.navigate( + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.CREATE, + iouType: CONST.IOU.TYPE.CREATE, + transactionID: freshTransactionID, + reportID: freshReportID, + upgradePath: CONST.UPGRADE_PATHS.REPORTS, + }), + ); + return; + } + + const workspaceIDForReportCreation = defaultChatEnabledPolicyID; + + // No default or restricted with multiple workspaces → workspace selector + if ( + !workspaceIDForReportCreation || + (shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed) && + groupPoliciesWithChatEnabled.length > 1) + ) { + Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + return; + } + + // Default workspace is not restricted → create report directly (or show empty-report confirmation) + if (!shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed)) { + if (shouldShowEmptyReportConfirmation) { + openCreateReportConfirmation(); + } else { + onCreateReport(false); + } + return; + } + + Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(workspaceIDForReportCreation)); + }); + }, [ + shouldRedirectToExpensifyClassic, + showRedirectToExpensifyClassicModal, + shouldNavigateToUpgradePath, + defaultChatEnabledPolicyID, + ownerBillingGracePeriodEnd, + userBillingGracePeriodEnds, + amountOwed, + groupPoliciesWithChatEnabled.length, + shouldShowEmptyReportConfirmation, + openCreateReportConfirmation, + onCreateReport, + ]); + + return {createReportAction, isVisible}; +} diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index 79c3e91bf687..ff8c71a1ab27 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -1679,6 +1679,8 @@ type ProfileNavigatorParamList = { type NewReportWorkspaceSelectionNavigatorParamList = { [SCREENS.NEW_REPORT_WORKSPACE_SELECTION.ROOT]: { isMovingExpenses?: boolean; + /** When provided, the page auto-selects this policy on mount and creates the report without waiting for user input */ + selectedPolicyID?: string; // eslint-disable-next-line no-restricted-syntax -- `backTo` usages in this file are legacy. Do not add new `backTo` params to screens. See contributingGuides/NAVIGATION.md backTo?: Routes; }; diff --git a/src/pages/NewReportWorkspaceSelectionPage.tsx b/src/pages/NewReportWorkspaceSelectionPage.tsx index 8813717e577c..92c7edaf063d 100644 --- a/src/pages/NewReportWorkspaceSelectionPage.tsx +++ b/src/pages/NewReportWorkspaceSelectionPage.tsx @@ -1,5 +1,5 @@ import {accountIDSelector, emailSelector} from '@selectors/Session'; -import React, {useEffect, useState} from 'react'; +import React, {useCallback, useEffect, useRef, useState} from 'react'; import {View} from 'react-native'; import type {OnyxCollection} from 'react-native-onyx'; import ActivityIndicator from '@components/ActivityIndicator'; @@ -51,7 +51,7 @@ type WorkspaceListItem = { type NewReportWorkspaceSelectionPageProps = PlatformStackScreenProps; function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPageProps) { - const {isMovingExpenses, backTo} = route.params ?? {}; + const {isMovingExpenses, backTo, selectedPolicyID} = route.params ?? {}; const {isOffline} = useNetwork(); const icons = useMemoizedLazyExpensifyIcons(['FallbackWorkspaceAvatar']); const {selectedTransactions, selectedTransactionIDs} = useSearchStateContext(); @@ -82,15 +82,16 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag const shouldShowLoadingIndicator = isLoadingApp && !isOffline; const [pendingPolicySelection, setPendingPolicySelection] = useState<{policy: WorkspaceListItem; shouldShowEmptyReportConfirmation: boolean} | null>(null); - const [policiesWithEmptyReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { - selector: (reports: OnyxCollection) => { + const policiesWithEmptyReportsSelector = useCallback( + (reports: OnyxCollection) => { if (!accountID) { return {}; } - return getPolicyIDsWithEmptyReportsForAccount(reports, accountID); }, - }); + [accountID], + ); + const [policiesWithEmptyReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: policiesWithEmptyReportsSelector}); const navigateToNewReport = (optimisticReportID: string) => { if (isRHPOnReportInSearch) { @@ -243,6 +244,27 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag usersWorkspaces = result.sort((a, b) => localeCompare(a.text, b.text)); } + // Auto-select path: when callers pass selectedPolicyID (e.g. IOURequestStepUpgrade after creating a + // workspace), create the report directly without making the user pick from a list or dismiss an + // empty-report confirmation — they already confirmed intent on the previous screen. + const didAutoSelectRef = useRef(false); + useEffect(() => { + if (didAutoSelectRef.current || !selectedPolicyID || shouldShowLoadingIndicator) { + return; + } + const targetPolicy = usersWorkspaces.find((policy) => policy.policyID === selectedPolicyID); + if (!targetPolicy?.policyID) { + return; + } + didAutoSelectRef.current = true; + + if (shouldRestrictUserBillableActions(targetPolicy.policyID, ownerBillingGracePeriodEnd, userBillingGracePeriods, amountOwed)) { + Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(targetPolicy.policyID)); + return; + } + createReport(targetPolicy.policyID, false); + }, [selectedPolicyID, usersWorkspaces, shouldShowLoadingIndicator, ownerBillingGracePeriodEnd, userBillingGracePeriods, amountOwed, createReport]); + const filteredAndSortedUserWorkspaces: WorkspaceListItem[] = usersWorkspaces.filter((policy) => policy.text?.toLowerCase().includes(debouncedSearchTerm?.toLowerCase() ?? '')); const areResultsFound = filteredAndSortedUserWorkspaces.length > 0; diff --git a/src/pages/Search/EmptySearchView.tsx b/src/pages/Search/EmptySearchView.tsx index cc96498f1592..ea0fe00cecb9 100644 --- a/src/pages/Search/EmptySearchView.tsx +++ b/src/pages/Search/EmptySearchView.tsx @@ -16,9 +16,8 @@ import type {SearchQueryJSON} from '@components/Search/types'; import Text from '@components/Text'; import TextLink from '@components/TextLink'; import useConfirmModal from '@hooks/useConfirmModal'; -import useCreateEmptyReportConfirmation from '@hooks/useCreateEmptyReportConfirmation'; +import useCreateReportAction from '@hooks/useCreateReportAction'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; -import useHasEmptyReportsForPolicy from '@hooks/useHasEmptyReportsForPolicy'; import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; import {useMemoizedLazyIllustrations} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; @@ -37,7 +36,6 @@ import {generateReportID, hasViolations as hasViolationsReportUtils} from '@libs import {isDefaultExpenseReportsQuery, isDefaultExpensesQuery} from '@libs/SearchQueryUtils'; import type {SearchTypeMenuSection} from '@libs/SearchUIUtils'; import {TODO_SEARCH_KEYS} from '@libs/SearchUIUtils'; -import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -144,9 +142,6 @@ function EmptySearchViewContent({ }); const hasViolations = hasViolationsReportUtils(undefined, transactionViolations, accountID ?? CONST.DEFAULT_NUMBER_ID, ''); const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {selector: validTransactionDraftIDsSelector}); - const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); - const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); - const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); const [hasTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, { selector: hasTransactionsSelector, }); @@ -158,12 +153,6 @@ function EmptySearchViewContent({ const defaultChatEnabledPolicy = getDefaultChatEnabledPolicy(groupPoliciesWithChatEnabled as Array>, activePolicy); - const defaultChatEnabledPolicyID = defaultChatEnabledPolicy?.id; - - const hasEmptyReport = useHasEmptyReportsForPolicy(defaultChatEnabledPolicyID); - const [hasDismissedEmptyReportsConfirmation] = useOnyx(ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED); - const shouldShowEmptyReportConfirmation = hasEmptyReport && hasDismissedEmptyReportsConfirmation !== true; - const filteredPolicyID = queryJSON?.policyID; let isFilteredWorkspaceAccessible = true; if (filteredPolicyID) { @@ -196,20 +185,11 @@ function EmptySearchViewContent({ }); }; - const {openCreateReportConfirmation: openCreateReportFromSearch} = useCreateEmptyReportConfirmation({ - policyID: defaultChatEnabledPolicyID, - policyName: defaultChatEnabledPolicy?.name ?? '', - onConfirm: handleCreateWorkspaceReport, + const {createReportAction, isVisible: isCreateReportVisible} = useCreateReportAction({ + onCreateReport: handleCreateWorkspaceReport, + groupPoliciesWithChatEnabled, }); - const handleCreateReportClick = () => { - if (shouldShowEmptyReportConfirmation) { - openCreateReportFromSearch(); - } else { - handleCreateWorkspaceReport(false); - } - }; - const handleRedirectToExpensifyClassic = () => { showConfirmModal({ prompt: translate('sidebarScreen.redirectToExpensifyClassicModal.description'), @@ -323,31 +303,11 @@ function EmptySearchViewContent({ }, ] : []), - ...(groupPoliciesWithChatEnabled.length > 0 + ...(isCreateReportVisible ? [ { buttonText: translate('quickAction.createReport'), - buttonAction: () => { - interceptAnonymousUser(() => { - const workspaceIDForReportCreation = defaultChatEnabledPolicyID; - - if ( - !workspaceIDForReportCreation || - (shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed) && - groupPoliciesWithChatEnabled.length > 1) - ) { - // If we couldn't guess the workspace to create the report, or a guessed workspace is past it's grace period and we have other workspaces to choose from - Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); - return; - } - - if (!shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed)) { - handleCreateReportClick(); - } else { - Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(workspaceIDForReportCreation)); - } - }); - }, + buttonAction: createReportAction, success: true, }, ] diff --git a/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx b/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx index 64dc67d0a143..808a7725351e 100644 --- a/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx +++ b/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx @@ -1,23 +1,19 @@ import React from 'react'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; -import useCreateEmptyReportConfirmation from '@hooks/useCreateEmptyReportConfirmation'; +import useCreateReportAction from '@hooks/useCreateReportAction'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; -import useHasEmptyReportsForPolicy from '@hooks/useHasEmptyReportsForPolicy'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePermissions from '@hooks/usePermissions'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import {createNewReport} from '@libs/actions/Report'; -import interceptAnonymousUser from '@libs/interceptAnonymousUser'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import Navigation from '@libs/Navigation/Navigation'; import {getDefaultChatEnabledPolicy, isPaidGroupPolicy, shouldShowPolicy} from '@libs/PolicyUtils'; import {hasViolations as hasViolationsReportUtils} from '@libs/ReportUtils'; -import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import isOnSearchMoneyRequestReportPage from '@navigation/helpers/isOnSearchMoneyRequestReportPage'; import FABFocusableMenuItem from '@pages/inbox/sidebar/FABPopoverContent/FABFocusableMenuItem'; -import useRedirectToExpensifyClassic from '@pages/inbox/sidebar/FABPopoverContent/useRedirectToExpensifyClassic'; import {clearLastSearchParams} from '@userActions/ReportNavigation'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -54,12 +50,10 @@ function CreateReportMenuItem() { const {translate} = useLocalize(); const {shouldUseNarrowLayout} = useResponsiveLayout(); const icons = useMemoizedLazyExpensifyIcons(['Document']); - const {shouldRedirectToExpensifyClassic, canRedirectToExpensifyClassic, showRedirectToExpensifyClassicModal} = useRedirectToExpensifyClassic(); const [activePolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`); const [session] = useOnyx(ONYXKEYS.SESSION, {selector: sessionEmailAndAccountIDSelector}); const [allBetas] = useOnyx(ONYXKEYS.BETAS); const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); - const [hasDismissedEmptyReportsConfirmation] = useOnyx(ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const {isBetaEnabled} = usePermissions(); const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); @@ -67,18 +61,9 @@ function CreateReportMenuItem() { const chatEnabledPaidGroupPolicies = (policies: Parameters[0]) => chatEnabledPaidGroupPoliciesSelector(policies, session?.email); const [groupPoliciesWithChatEnabled = CONST.EMPTY_ARRAY] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: chatEnabledPaidGroupPolicies}, [session?.email]); - const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); - const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); - const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); - - const isVisible = canRedirectToExpensifyClassic || groupPoliciesWithChatEnabled.length > 0; const defaultChatEnabledPolicy = getDefaultChatEnabledPolicy(groupPoliciesWithChatEnabled as Array>, activePolicy); - const defaultChatEnabledPolicyID = defaultChatEnabledPolicy?.id; - const hasEmptyReport = useHasEmptyReportsForPolicy(defaultChatEnabledPolicyID); - const shouldShowEmptyReportConfirmation = hasEmptyReport && hasDismissedEmptyReportsConfirmation !== true; - const isReportInSearch = isOnSearchMoneyRequestReportPage(); const handleCreateWorkspaceReport = (shouldDismissEmptyReportsConfirmation?: boolean) => { @@ -109,10 +94,9 @@ function CreateReportMenuItem() { }); }; - const {openCreateReportConfirmation} = useCreateEmptyReportConfirmation({ - policyID: defaultChatEnabledPolicyID, - policyName: defaultChatEnabledPolicy?.name ?? '', - onConfirm: handleCreateWorkspaceReport, + const {createReportAction, isVisible} = useCreateReportAction({ + onCreateReport: handleCreateWorkspaceReport, + groupPoliciesWithChatEnabled, shouldHandleNavigationBack: false, }); @@ -123,40 +107,7 @@ function CreateReportMenuItem() { pressableTestID={CONST.SENTRY_LABEL.FAB_MENU.CREATE_REPORT} icon={icons.Document} title={translate('report.newReport.createReport')} - onPress={() => { - interceptAnonymousUser(() => { - if (shouldRedirectToExpensifyClassic) { - if (canRedirectToExpensifyClassic) { - showRedirectToExpensifyClassicModal(); - } - return; - } - - const workspaceIDForReportCreation = defaultChatEnabledPolicyID; - - // If we couldn't guess the workspace to create the report, or a guessed workspace is past its grace period and we have other workspaces to choose from - if ( - !workspaceIDForReportCreation || - (shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed) && - groupPoliciesWithChatEnabled.length > 1) - ) { - Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); - return; - } - - if (!shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed)) { - // Check if empty report confirmation should be shown - if (shouldShowEmptyReportConfirmation) { - openCreateReportConfirmation(); - } else { - handleCreateWorkspaceReport(false); - } - return; - } - - Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(workspaceIDForReportCreation)); - }); - }} + onPress={createReportAction} shouldCallAfterModalHide={shouldUseNarrowLayout} /> ); diff --git a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx index 4393299348ec..db8454991c15 100644 --- a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx +++ b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx @@ -123,8 +123,10 @@ function IOURequestStepUpgrade({ case CONST.UPGRADE_PATHS.REPORTS: Navigation.goBack(); if (action === CONST.IOU.ACTION.CREATE) { - // Coming from "Create report" button (no workspace) → go to workspace selection which creates the report - navigateWithMicrotask(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + // Coming from "Create report" button (no workspace) → workspace selection. + // Pass the just-created policyID so the page auto-selects it and creates the report + // without making the user pick the single workspace they just created. + navigateWithMicrotask(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute(undefined, undefined, policyID)); } else { navigateWithMicrotask(ROUTES.MONEY_REQUEST_STEP_REPORT.getRoute(action, CONST.IOU.TYPE.SUBMIT, transactionID, reportID)); } diff --git a/tests/unit/useCreateReportActionTest.tsx b/tests/unit/useCreateReportActionTest.tsx new file mode 100644 index 000000000000..7b04e72a6093 --- /dev/null +++ b/tests/unit/useCreateReportActionTest.tsx @@ -0,0 +1,411 @@ +import {act, renderHook} from '@testing-library/react-native'; +import type {OnyxEntry} from 'react-native-onyx'; +import useCreateReportAction from '@hooks/useCreateReportAction'; +import useOnyx from '@hooks/useOnyx'; +import Navigation from '@libs/Navigation/Navigation'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; +import type {Policy} from '@src/types/onyx'; + +// ── Mocks ────────────────────────────────────────────────────────────────────── + +jest.mock('@hooks/useLocalize', () => () => ({translate: jest.fn((key: string) => key)})); + +jest.mock('@hooks/useOnyx', () => jest.fn()); +const mockUseOnyx = useOnyx as jest.MockedFunction; + +jest.mock('@hooks/useHasEmptyReportsForPolicy', () => jest.fn(() => false)); +// eslint-disable-next-line @typescript-eslint/no-require-imports +const mockUseHasEmptyReportsForPolicy = require('@hooks/useHasEmptyReportsForPolicy') as jest.Mock; + +const mockOpenCreateReportConfirmation = jest.fn(); +jest.mock('@hooks/useCreateEmptyReportConfirmation', () => + jest.fn(() => ({ + openCreateReportConfirmation: mockOpenCreateReportConfirmation, + CreateReportConfirmationModal: null, + })), +); + +const mockShowRedirectToExpensifyClassicModal = jest.fn(); +const mockUseRedirectToExpensifyClassic = jest.fn(() => ({ + shouldRedirectToExpensifyClassic: false, + canRedirectToExpensifyClassic: false, + canUseAction: true, + showRedirectToExpensifyClassicModal: mockShowRedirectToExpensifyClassicModal, +})); +jest.mock('@pages/inbox/sidebar/FABPopoverContent/useRedirectToExpensifyClassic', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + default: () => mockUseRedirectToExpensifyClassic(), +})); + +jest.mock('@libs/PolicyUtils', () => ({ + getDefaultChatEnabledPolicy: jest.fn((policies: Array>) => policies.at(0) ?? undefined), +})); + +jest.mock('@libs/interceptAnonymousUser', () => jest.fn((cb: () => void) => cb())); + +jest.mock('@libs/Navigation/Navigation', () => ({ + navigate: jest.fn(), +})); + +const reportIDCounter = {value: 100}; +jest.mock('@libs/ReportUtils', () => ({ + generateReportID: jest.fn(() => String(++reportIDCounter.value)), +})); + +const mockShouldRestrictUserBillableActions = jest.fn(() => false); +jest.mock('@libs/SubscriptionUtils', () => ({ + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + shouldRestrictUserBillableActions: (...args: Parameters) => mockShouldRestrictUserBillableActions(...args), +})); + +// ── Helpers ──────────────────────────────────────────────────────────────────── + +const POLICY_ID = 'policy-123'; + +function makePaidPolicy(id = POLICY_ID): OnyxEntry { + return { + id, + name: 'Test Workspace', + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + isPolicyExpenseChatEnabled: true, + owner: 'test@test.com', + ownerAccountID: 1, + outputCurrency: 'USD', + employeeList: {}, + } as OnyxEntry; +} + +function setupUseOnyx(overrides: Record = {}) { + const impl = ((key: string, options?: {selector?: (value: unknown) => unknown}) => { + const rawValue = key in overrides ? overrides[key] : undefined; + const value = options?.selector ? options.selector(rawValue) : rawValue; + return [value, {status: 'loaded'}]; + }) as typeof useOnyx; + mockUseOnyx.mockImplementation(impl); +} + +function setupRedirectToExpensifyClassic({shouldRedirect = false, canRedirect = false}: {shouldRedirect?: boolean; canRedirect?: boolean} = {}) { + mockUseRedirectToExpensifyClassic.mockReturnValue({ + shouldRedirectToExpensifyClassic: shouldRedirect, + canRedirectToExpensifyClassic: canRedirect, + canUseAction: !shouldRedirect || canRedirect, + showRedirectToExpensifyClassicModal: mockShowRedirectToExpensifyClassicModal, + }); +} + +// ── Tests ────────────────────────────────────────────────────────────────────── + +describe('useCreateReportAction', () => { + beforeEach(() => { + jest.clearAllMocks(); + reportIDCounter.value = 100; + mockShouldRestrictUserBillableActions.mockReturnValue(false); + mockUseHasEmptyReportsForPolicy.mockReturnValue(false); + setupUseOnyx(); + setupRedirectToExpensifyClassic(); + }); + + describe('upgrade path (no policies)', () => { + it('navigates to upgrade path when user has no group policies', () => { + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).toHaveBeenCalledTimes(1); + const navigateArg = jest.mocked(Navigation.navigate).mock.calls.at(0)?.at(0) as string; + expect(navigateArg).toContain('upgrade'); + expect(navigateArg).toContain(CONST.UPGRADE_PATHS.REPORTS); + expect(onCreateReport).not.toHaveBeenCalled(); + }); + }); + + describe('redirect to Expensify Classic', () => { + it('shows classic redirect modal when shouldRedirectToExpensifyClassic is true', () => { + setupRedirectToExpensifyClassic({shouldRedirect: true, canRedirect: true}); + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(mockShowRedirectToExpensifyClassicModal).toHaveBeenCalledTimes(1); + expect(onCreateReport).not.toHaveBeenCalled(); + expect(Navigation.navigate).not.toHaveBeenCalled(); + }); + }); + + describe('workspace selection', () => { + it('navigates to workspace selector when default policy ID is not available', () => { + const onCreateReport = jest.fn(); + // Pass array with undefined so getDefaultChatEnabledPolicy returns undefined + const policies = [undefined] as Array>; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + expect(onCreateReport).not.toHaveBeenCalled(); + }); + + it('navigates to workspace selector when restricted with multiple workspaces', () => { + mockShouldRestrictUserBillableActions.mockReturnValue(true); + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy('p1'), makePaidPolicy('p2')]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + }); + }); + + describe('direct report creation', () => { + it('calls onCreateReport directly when workspace is valid and no confirmation needed', () => { + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy()]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(onCreateReport).toHaveBeenCalledWith(false); + expect(Navigation.navigate).not.toHaveBeenCalled(); + }); + + it('opens empty report confirmation when policy has empty reports', () => { + mockUseHasEmptyReportsForPolicy.mockReturnValue(true); + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy()]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(mockOpenCreateReportConfirmation).toHaveBeenCalledTimes(1); + expect(onCreateReport).not.toHaveBeenCalled(); + }); + }); + + describe('restricted action', () => { + it('navigates to restricted action when single workspace is billing-restricted', () => { + mockShouldRestrictUserBillableActions.mockReturnValue(true); + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy()]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.RESTRICTED_ACTION.getRoute(POLICY_ID)); + expect(onCreateReport).not.toHaveBeenCalled(); + }); + }); + + describe('decision flow priority', () => { + it('classic redirect takes priority over upgrade path', () => { + setupRedirectToExpensifyClassic({shouldRedirect: true, canRedirect: true}); + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(mockShowRedirectToExpensifyClassicModal).toHaveBeenCalledTimes(1); + // Should NOT navigate to upgrade + expect(Navigation.navigate).not.toHaveBeenCalled(); + }); + + it('upgrade path takes priority over workspace selection when no policies exist', () => { + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + const navigateArg = jest.mocked(Navigation.navigate).mock.calls.at(0)?.at(0) as string; + expect(navigateArg).toContain('upgrade'); + }); + }); + + describe('policies loaded with valid workspace', () => { + it('does not navigate to upgrade path when user has a workspace', () => { + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy()]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + // Should call onCreateReport directly, not navigate to upgrade + expect(onCreateReport).toHaveBeenCalledWith(false); + const calls = jest.mocked(Navigation.navigate).mock.calls; + const navigatedToUpgrade = calls.some((call) => { + const firstArg = call.at(0); + return typeof firstArg === 'string' && firstArg.includes('upgrade'); + }); + expect(navigatedToUpgrade).toBe(false); + }); + }); + + describe('empty report confirmation dismissed', () => { + it('calls onCreateReport directly when confirmation was previously dismissed', () => { + mockUseHasEmptyReportsForPolicy.mockReturnValue(true); + setupUseOnyx({ + [ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED]: true, + }); + + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy()]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(onCreateReport).toHaveBeenCalledWith(false); + expect(mockOpenCreateReportConfirmation).not.toHaveBeenCalled(); + }); + }); + + describe('returns', () => { + it('returns createReportAction function and isVisible flag', () => { + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + expect(typeof result.current.createReportAction).toBe('function'); + expect(typeof result.current.isVisible).toBe('boolean'); + }); + + it('isVisible is true when policies exist', () => { + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [makePaidPolicy()], + }), + ); + + expect(result.current.isVisible).toBe(true); + }); + + it('isVisible is true when classic redirect is available', () => { + setupRedirectToExpensifyClassic({shouldRedirect: true, canRedirect: true}); + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + expect(result.current.isVisible).toBe(true); + }); + + it('isVisible is false when classic redirect is required but not usable', () => { + setupRedirectToExpensifyClassic({shouldRedirect: true, canRedirect: false}); + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + expect(result.current.isVisible).toBe(false); + }); + }); +}); From 650a5db22879a604726059e73614697cef82505b Mon Sep 17 00:00:00 2001 From: Mukher Date: Tue, 21 Apr 2026 08:41:33 +0500 Subject: [PATCH 02/13] fix: hide Create Report CTA until policy collection hydrates --- src/hooks/useCreateReportAction.tsx | 15 ++++++-- tests/unit/useCreateReportActionTest.tsx | 47 ++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/hooks/useCreateReportAction.tsx b/src/hooks/useCreateReportAction.tsx index 9e4000aae89e..18615a558000 100644 --- a/src/hooks/useCreateReportAction.tsx +++ b/src/hooks/useCreateReportAction.tsx @@ -10,6 +10,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; +import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import useCreateEmptyReportConfirmation from './useCreateEmptyReportConfirmation'; import useHasEmptyReportsForPolicy from './useHasEmptyReportsForPolicy'; import useOnyx from './useOnyx'; @@ -44,6 +45,7 @@ type UseCreateReportActionResult = { export default function useCreateReportAction({onCreateReport, groupPoliciesWithChatEnabled, shouldHandleNavigationBack = true}: UseCreateReportActionParams): UseCreateReportActionResult { const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); const [activePolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`); + const [, policiesMeta] = useOnyx(ONYXKEYS.COLLECTION.POLICY); const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); @@ -51,9 +53,11 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith const {shouldRedirectToExpensifyClassic, canUseAction, showRedirectToExpensifyClassicModal} = useRedirectToExpensifyClassic(); - // Visible whenever clicking the button would do something meaningful (upgrade flow, workspace selection, direct create, or classic redirect). - // Hidden only when classic redirect is required but currently suppressed (e.g. TryNewDot loading / hybrid app state). - const isVisible = canUseAction; + // Gate visibility and routing on policy hydration. Without this, during Onyx cold-start + // groupPoliciesWithChatEnabled.length === 0 would be true even for users who actually have + // workspaces, sending them to MONEY_REQUEST_UPGRADE as if they had none. + const arePoliciesLoaded = !isLoadingOnyxValue(policiesMeta); + const isVisible = arePoliciesLoaded && canUseAction; const shouldNavigateToUpgradePath = !shouldRedirectToExpensifyClassic && groupPoliciesWithChatEnabled.length === 0; const defaultChatEnabledPolicy = getDefaultChatEnabledPolicy(groupPoliciesWithChatEnabled as Array>, activePolicy); @@ -71,6 +75,10 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith const createReportAction = useCallback(() => { interceptAnonymousUser(() => { + if (!arePoliciesLoaded) { + return; + } + if (shouldRedirectToExpensifyClassic) { showRedirectToExpensifyClassicModal(); return; @@ -117,6 +125,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(workspaceIDForReportCreation)); }); }, [ + arePoliciesLoaded, shouldRedirectToExpensifyClassic, showRedirectToExpensifyClassicModal, shouldNavigateToUpgradePath, diff --git a/tests/unit/useCreateReportActionTest.tsx b/tests/unit/useCreateReportActionTest.tsx index 7b04e72a6093..489f7304dcb7 100644 --- a/tests/unit/useCreateReportActionTest.tsx +++ b/tests/unit/useCreateReportActionTest.tsx @@ -408,4 +408,51 @@ describe('useCreateReportAction', () => { expect(result.current.isVisible).toBe(false); }); }); + + describe('policy hydration gate', () => { + it('isVisible is false while the policy collection is still loading', () => { + const impl = ((_key: string, options?: {selector?: (value: unknown) => unknown}) => { + const value = options?.selector ? options.selector(undefined) : undefined; + return [value, {status: 'loading'}]; + }) as typeof useOnyx; + mockUseOnyx.mockImplementation(impl); + + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + expect(result.current.isVisible).toBe(false); + }); + + it('does not navigate to upgrade path when the user actually has policies but Onyx is still loading', () => { + // Simulates cold start: consumer defaulted groupPoliciesWithChatEnabled to [] because Onyx + // hasn't hydrated yet. The hook should NOT treat this as "no policies" and misroute to upgrade. + const impl = ((_key: string, options?: {selector?: (value: unknown) => unknown}) => { + const value = options?.selector ? options.selector(undefined) : undefined; + return [value, {status: 'loading'}]; + }) as typeof useOnyx; + mockUseOnyx.mockImplementation(impl); + + const onCreateReport = jest.fn(); + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: [], + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).not.toHaveBeenCalled(); + expect(onCreateReport).not.toHaveBeenCalled(); + }); + }); }); From 9f431279a87bf474dd6fa20038f9b88f05880eab Mon Sep 17 00:00:00 2001 From: Mukher Date: Tue, 21 Apr 2026 08:55:21 +0500 Subject: [PATCH 03/13] fix spell error --- tests/unit/useCreateReportActionTest.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/useCreateReportActionTest.tsx b/tests/unit/useCreateReportActionTest.tsx index 489f7304dcb7..1a0dcb3b6dbe 100644 --- a/tests/unit/useCreateReportActionTest.tsx +++ b/tests/unit/useCreateReportActionTest.tsx @@ -431,7 +431,7 @@ describe('useCreateReportAction', () => { it('does not navigate to upgrade path when the user actually has policies but Onyx is still loading', () => { // Simulates cold start: consumer defaulted groupPoliciesWithChatEnabled to [] because Onyx - // hasn't hydrated yet. The hook should NOT treat this as "no policies" and misroute to upgrade. + // hasn't hydrated yet. The hook should NOT treat this as "no policies" and navigate to upgrade. const impl = ((_key: string, options?: {selector?: (value: unknown) => unknown}) => { const value = options?.selector ? options.selector(undefined) : undefined; return [value, {status: 'loading'}]; From 48563cb78627b5a14ee2681293de8405fc480e1d Mon Sep 17 00:00:00 2001 From: Mukher Date: Thu, 23 Apr 2026 20:36:16 +0500 Subject: [PATCH 04/13] moved policy ids into separate selector --- src/pages/NewReportWorkspaceSelectionPage.tsx | 19 +++++-------------- src/selectors/Report.ts | 12 ++++++++++-- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/pages/NewReportWorkspaceSelectionPage.tsx b/src/pages/NewReportWorkspaceSelectionPage.tsx index 92c7edaf063d..4052ec7647be 100644 --- a/src/pages/NewReportWorkspaceSelectionPage.tsx +++ b/src/pages/NewReportWorkspaceSelectionPage.tsx @@ -1,7 +1,7 @@ +import {policyIDsWithEmptyReportsSelector} from '@selectors/Report'; import {accountIDSelector, emailSelector} from '@selectors/Session'; -import React, {useCallback, useEffect, useRef, useState} from 'react'; +import React, {useEffect, useMemo, useRef, useState} from 'react'; import {View} from 'react-native'; -import type {OnyxCollection} from 'react-native-onyx'; import ActivityIndicator from '@components/ActivityIndicator'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; import ScreenWrapper from '@components/ScreenWrapper'; @@ -27,7 +27,7 @@ import Navigation from '@libs/Navigation/Navigation'; import type {NewReportWorkspaceSelectionNavigatorParamList} from '@libs/Navigation/types'; import {getHeaderMessageForNonUserList} from '@libs/OptionsListUtils'; import {canSubmitPerDiemExpenseFromWorkspace, isPolicyAdmin, shouldShowPolicy} from '@libs/PolicyUtils'; -import {getDefaultWorkspaceAvatar, getPolicyIDsWithEmptyReportsForAccount, hasViolations as hasViolationsReportUtils} from '@libs/ReportUtils'; +import {getDefaultWorkspaceAvatar, hasViolations as hasViolationsReportUtils} from '@libs/ReportUtils'; import {buildCannedSearchQuery} from '@libs/SearchQueryUtils'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import {isPerDiemRequest} from '@libs/TransactionUtils'; @@ -39,7 +39,6 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; -import type * as OnyxTypes from '@src/types/onyx'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; type WorkspaceListItem = { @@ -82,16 +81,8 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag const shouldShowLoadingIndicator = isLoadingApp && !isOffline; const [pendingPolicySelection, setPendingPolicySelection] = useState<{policy: WorkspaceListItem; shouldShowEmptyReportConfirmation: boolean} | null>(null); - const policiesWithEmptyReportsSelector = useCallback( - (reports: OnyxCollection) => { - if (!accountID) { - return {}; - } - return getPolicyIDsWithEmptyReportsForAccount(reports, accountID); - }, - [accountID], - ); - const [policiesWithEmptyReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: policiesWithEmptyReportsSelector}); + const policiesWithEmptyReportsForAccountSelector = useMemo(() => policyIDsWithEmptyReportsSelector(accountID), [accountID]); + const [policiesWithEmptyReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: policiesWithEmptyReportsForAccountSelector}); const navigateToNewReport = (optimisticReportID: string) => { if (isRHPOnReportInSearch) { diff --git a/src/selectors/Report.ts b/src/selectors/Report.ts index 829c234e74ac..71248c6eae3c 100644 --- a/src/selectors/Report.ts +++ b/src/selectors/Report.ts @@ -1,6 +1,7 @@ -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import {getOriginalMessage, isClosedAction} from '@libs/ReportActionsUtils'; +import {getPolicyIDsWithEmptyReportsForAccount} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import type {Report, ReportActions} from '@src/types/onyx'; import {getLastClosedReportAction} from './ReportAction'; @@ -27,4 +28,11 @@ function getReportOwnerAccountID(report: OnyxEntry) { return report?.ownerAccountID; } -export {getArchiveReason, getReportChatType, getReportOwnerAccountID, getReportPolicyID}; +const policyIDsWithEmptyReportsSelector = (accountID: number | undefined) => (reports: OnyxCollection) => { + if (!accountID) { + return {}; + } + return getPolicyIDsWithEmptyReportsForAccount(reports, accountID); +}; + +export {getArchiveReason, getReportChatType, getReportOwnerAccountID, getReportPolicyID, policyIDsWithEmptyReportsSelector}; From 0c33f5ac488b0d666bacdc956f5b4cd2cbee9897 Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 27 Apr 2026 16:47:49 +0500 Subject: [PATCH 05/13] fixed intermediate page showing after got it thanks --- src/ROUTES.ts | 5 +-- src/components/ConfirmationPage.tsx | 5 +++ src/hooks/useCreateNewReport.tsx | 43 +++++++++++++++++++ src/libs/Navigation/types.ts | 2 - src/pages/NewReportWorkspaceSelectionPage.tsx | 25 +---------- .../request/step/IOURequestStepUpgrade.tsx | 17 +++++--- .../workspace/upgrade/UpgradeConfirmation.tsx | 5 ++- 7 files changed, 66 insertions(+), 36 deletions(-) create mode 100644 src/hooks/useCreateNewReport.tsx diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 0fe5f17f3b8e..f41be00a4ad2 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -917,14 +917,11 @@ const ROUTES = { NEW_REPORT_WORKSPACE_SELECTION: { route: 'new-report-workspace-selection', - getRoute: (isMovingExpenses?: boolean, backTo?: string, selectedPolicyID?: string) => { + getRoute: (isMovingExpenses?: boolean, backTo?: string) => { const params = new URLSearchParams(); if (isMovingExpenses) { params.set('isMovingExpenses', 'true'); } - if (selectedPolicyID) { - params.set('selectedPolicyID', selectedPolicyID); - } const query = params.toString(); const baseRoute = `new-report-workspace-selection${query ? `?${query}` : ''}` as const; diff --git a/src/components/ConfirmationPage.tsx b/src/components/ConfirmationPage.tsx index 91973f9d64a0..d115a39c01be 100644 --- a/src/components/ConfirmationPage.tsx +++ b/src/components/ConfirmationPage.tsx @@ -42,6 +42,9 @@ type ConfirmationPageProps = { /** Whether we should show a primary confirmation button */ shouldShowButton?: boolean; + /** Whether the primary button should show a loading indicator */ + isButtonLoading?: boolean; + /** The text for the secondary button label */ secondaryButtonText?: string; @@ -83,6 +86,7 @@ function ConfirmationPage({ buttonText = '', onButtonPress = () => {}, shouldShowButton = false, + isButtonLoading = false, secondaryButtonText = '', onSecondaryButtonPress = () => {}, shouldShowSecondaryButton = false, @@ -162,6 +166,7 @@ function ConfirmationPage({ testID="confirmation-primary-button" style={styles.mt3} pressOnEnter + isLoading={isButtonLoading} onPress={onButtonPress} /> )} diff --git a/src/hooks/useCreateNewReport.tsx b/src/hooks/useCreateNewReport.tsx new file mode 100644 index 000000000000..b4804c5ed510 --- /dev/null +++ b/src/hooks/useCreateNewReport.tsx @@ -0,0 +1,43 @@ +import {accountIDSelector, emailSelector} from '@selectors/Session'; +import {useCallback} from 'react'; +import {createNewReport} from '@libs/actions/Report'; +import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNavigationActionToMicrotaskQueue'; +import Navigation from '@libs/Navigation/Navigation'; +import {hasViolations as hasViolationsUtil} from '@libs/ReportUtils'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; +import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; +import useOnyx from './useOnyx'; +import usePermissions from './usePermissions'; + +/** + * Returns a stable callback that creates a new expense report for the given + * policyID and navigates to it. Useful for callers that already know which + * workspace to use and don't need the workspace-selection page. + */ +function useCreateNewReport() { + const currentUserPersonalDetails = useCurrentUserPersonalDetails(); + const {isBetaEnabled} = usePermissions(); + const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); + const [accountID] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector}); + const [email] = useOnyx(ONYXKEYS.SESSION, {selector: emailSelector}); + const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); + const [betas] = useOnyx(ONYXKEYS.BETAS); + const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); + + const hasViolations = hasViolationsUtil(undefined, transactionViolations, accountID ?? CONST.DEFAULT_NUMBER_ID, email ?? ''); + + return useCallback( + (policyID: string, forceReplace = false) => { + const policy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]; + const result = createNewReport(currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policy, betas, false); + setNavigationActionToMicrotaskQueue(() => { + Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(result.reportID), {forceReplace}); + }); + }, + [betas, currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policies], + ); +} + +export default useCreateNewReport; diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index 6697fd7ec140..cf0ccac31cd8 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -1684,8 +1684,6 @@ type ProfileNavigatorParamList = { type NewReportWorkspaceSelectionNavigatorParamList = { [SCREENS.NEW_REPORT_WORKSPACE_SELECTION.ROOT]: { isMovingExpenses?: boolean; - /** When provided, the page auto-selects this policy on mount and creates the report without waiting for user input */ - selectedPolicyID?: string; // eslint-disable-next-line no-restricted-syntax -- `backTo` usages in this file are legacy. Do not add new `backTo` params to screens. See contributingGuides/NAVIGATION.md backTo?: Routes; }; diff --git a/src/pages/NewReportWorkspaceSelectionPage.tsx b/src/pages/NewReportWorkspaceSelectionPage.tsx index a4e2e6061275..84f76d68564d 100644 --- a/src/pages/NewReportWorkspaceSelectionPage.tsx +++ b/src/pages/NewReportWorkspaceSelectionPage.tsx @@ -1,6 +1,6 @@ import {policyIDsWithEmptyReportsSelector} from '@selectors/Report'; import {accountIDSelector, emailSelector} from '@selectors/Session'; -import React, {useEffect, useMemo, useRef, useState} from 'react'; +import React, {useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import ActivityIndicator from '@components/ActivityIndicator'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; @@ -50,7 +50,7 @@ type WorkspaceListItem = { type NewReportWorkspaceSelectionPageProps = PlatformStackScreenProps; function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPageProps) { - const {isMovingExpenses, backTo, selectedPolicyID} = route.params ?? {}; + const {isMovingExpenses, backTo} = route.params ?? {}; const {isOffline} = useNetwork(); const icons = useMemoizedLazyExpensifyIcons(['FallbackWorkspaceAvatar']); const {selectedTransactions, selectedTransactionIDs} = useSearchStateContext(); @@ -239,27 +239,6 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag usersWorkspaces = result.sort((a, b) => localeCompare(a.text, b.text)); } - // Auto-select path: when callers pass selectedPolicyID (e.g. IOURequestStepUpgrade after creating a - // workspace), create the report directly without making the user pick from a list or dismiss an - // empty-report confirmation — they already confirmed intent on the previous screen. - const didAutoSelectRef = useRef(false); - useEffect(() => { - if (didAutoSelectRef.current || !selectedPolicyID || shouldShowLoadingIndicator) { - return; - } - const targetPolicy = usersWorkspaces.find((policy) => policy.policyID === selectedPolicyID); - if (!targetPolicy?.policyID) { - return; - } - didAutoSelectRef.current = true; - - if (shouldRestrictUserBillableActions(targetPolicy.policyID, ownerBillingGracePeriodEnd, userBillingGracePeriods, amountOwed)) { - Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(targetPolicy.policyID)); - return; - } - createReport(targetPolicy.policyID, false); - }, [selectedPolicyID, usersWorkspaces, shouldShowLoadingIndicator, ownerBillingGracePeriodEnd, userBillingGracePeriods, amountOwed, createReport]); - const filteredAndSortedUserWorkspaces: WorkspaceListItem[] = usersWorkspaces.filter((policy) => policy.text?.toLowerCase().includes(debouncedSearchTerm?.toLowerCase() ?? '')); const areResultsFound = filteredAndSortedUserWorkspaces.length > 0; diff --git a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx index db8454991c15..93e39e855a38 100644 --- a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx +++ b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx @@ -7,6 +7,7 @@ import ScreenWrapper from '@components/ScreenWrapper'; import ScrollView from '@components/ScrollView'; import WorkspaceConfirmationForm from '@components/WorkspaceConfirmationForm'; import type {WorkspaceConfirmationSubmitFunctionParams} from '@components/WorkspaceConfirmationForm'; +import useCreateNewReport from '@hooks/useCreateNewReport'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useHasActiveAdminPolicies from '@hooks/useHasActiveAdminPolicies'; import useLastWorkspaceNumber from '@hooks/useLastWorkspaceNumber'; @@ -56,6 +57,7 @@ function IOURequestStepUpgrade({ const [showConfirmationForm, setShowConfirmationForm] = useState(false); const [createdPolicyName, setCreatedPolicyName] = useState(''); const [isUpgradeWarningModalOpen, setIsUpgradeWarningModalOpen] = useState(false); + const [isCreatingReport, setIsCreatingReport] = useState(false); const policyDataRef = useRef(null); const isDistanceRateUpgrade = upgradePath === CONST.UPGRADE_PATHS.DISTANCE_RATES; const isCategorizing = upgradePath === CONST.UPGRADE_PATHS.CATEGORIES; @@ -67,6 +69,7 @@ function IOURequestStepUpgrade({ const [betas] = useOnyx(ONYXKEYS.BETAS); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); + const createNewReport = useCreateNewReport(); const feature = Object.values(CONST.UPGRADE_FEATURE_INTRO_MAPPING) .filter((value) => value.id !== CONST.UPGRADE_FEATURE_INTRO_MAPPING.policyPreventMemberChangingTitle.id) @@ -121,13 +124,14 @@ function IOURequestStepUpgrade({ break; } case CONST.UPGRADE_PATHS.REPORTS: - Navigation.goBack(); - if (action === CONST.IOU.ACTION.CREATE) { - // Coming from "Create report" button (no workspace) → workspace selection. - // Pass the just-created policyID so the page auto-selects it and creates the report - // without making the user pick the single workspace they just created. - navigateWithMicrotask(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute(undefined, undefined, policyID)); + if (action === CONST.IOU.ACTION.CREATE && policyID) { + // Coming from "Create report" (no workspace) — create directly with the just-created + // workspace. forceReplace removes the upgrade screen from history so back returns to + // the originating screen, not the upgrade step. + setIsCreatingReport(true); + createNewReport(policyID, true); } else { + Navigation.goBack(); navigateWithMicrotask(ROUTES.MONEY_REQUEST_STEP_REPORT.getRoute(action, CONST.IOU.TYPE.SUBMIT, transactionID, reportID)); } @@ -236,6 +240,7 @@ function IOURequestStepUpgrade({ isCategorizing={isCategorizing} isReporting={isReporting} isDistanceRateUpgrade={isDistanceRateUpgrade} + isButtonLoading={isCreatingReport} /> )} {!isUpgraded && ( diff --git a/src/pages/workspace/upgrade/UpgradeConfirmation.tsx b/src/pages/workspace/upgrade/UpgradeConfirmation.tsx index 931f8d81a99c..011d70e216c0 100644 --- a/src/pages/workspace/upgrade/UpgradeConfirmation.tsx +++ b/src/pages/workspace/upgrade/UpgradeConfirmation.tsx @@ -18,9 +18,11 @@ type Props = { isReporting?: boolean; isTravelUpgrade?: boolean; isDistanceRateUpgrade?: boolean; + /** Whether the "Got it, thanks" button should show a loading indicator */ + isButtonLoading?: boolean; }; -function UpgradeConfirmation({policyName, afterUpgradeAcknowledged, isReporting, isCategorizing, isTravelUpgrade, isDistanceRateUpgrade}: Props) { +function UpgradeConfirmation({policyName, afterUpgradeAcknowledged, isReporting, isCategorizing, isTravelUpgrade, isDistanceRateUpgrade, isButtonLoading}: Props) { const {translate} = useLocalize(); const styles = useThemeStyles(); const {environmentURL} = useEnvironment(); @@ -69,6 +71,7 @@ function UpgradeConfirmation({policyName, afterUpgradeAcknowledged, isReporting, shouldShowButton onButtonPress={afterUpgradeAcknowledged} buttonText={translate('workspace.upgrade.completed.gotIt')} + isButtonLoading={isButtonLoading} containerStyle={styles.h100} /> ); From f1090bba6fa13405bebd3b55e4cd2b14a1f7bebd Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 27 Apr 2026 16:58:06 +0500 Subject: [PATCH 06/13] DRY ed report creation flow --- src/hooks/useCreateNewReport.tsx | 15 ++++--------- src/pages/NewReportWorkspaceSelectionPage.tsx | 21 +++++-------------- .../request/step/IOURequestStepUpgrade.tsx | 5 ++++- 3 files changed, 13 insertions(+), 28 deletions(-) diff --git a/src/hooks/useCreateNewReport.tsx b/src/hooks/useCreateNewReport.tsx index b4804c5ed510..ea0a41c18875 100644 --- a/src/hooks/useCreateNewReport.tsx +++ b/src/hooks/useCreateNewReport.tsx @@ -1,20 +1,16 @@ import {accountIDSelector, emailSelector} from '@selectors/Session'; import {useCallback} from 'react'; import {createNewReport} from '@libs/actions/Report'; -import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNavigationActionToMicrotaskQueue'; -import Navigation from '@libs/Navigation/Navigation'; import {hasViolations as hasViolationsUtil} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import ROUTES from '@src/ROUTES'; import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useOnyx from './useOnyx'; import usePermissions from './usePermissions'; /** - * Returns a stable callback that creates a new expense report for the given - * policyID and navigates to it. Useful for callers that already know which - * workspace to use and don't need the workspace-selection page. + * Returns a stable callback that creates a new expense report for a given policyID. + * Returns the full optimistic report data so callers can navigate or use the result as needed. */ function useCreateNewReport() { const currentUserPersonalDetails = useCurrentUserPersonalDetails(); @@ -29,12 +25,9 @@ function useCreateNewReport() { const hasViolations = hasViolationsUtil(undefined, transactionViolations, accountID ?? CONST.DEFAULT_NUMBER_ID, email ?? ''); return useCallback( - (policyID: string, forceReplace = false) => { + (policyID: string, shouldDismissEmptyReportsConfirmation = false) => { const policy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]; - const result = createNewReport(currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policy, betas, false); - setNavigationActionToMicrotaskQueue(() => { - Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(result.reportID), {forceReplace}); - }); + return createNewReport(currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policy, betas, false, shouldDismissEmptyReportsConfirmation); }, [betas, currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policies], ); diff --git a/src/pages/NewReportWorkspaceSelectionPage.tsx b/src/pages/NewReportWorkspaceSelectionPage.tsx index 84f76d68564d..984c2aee9983 100644 --- a/src/pages/NewReportWorkspaceSelectionPage.tsx +++ b/src/pages/NewReportWorkspaceSelectionPage.tsx @@ -1,5 +1,5 @@ import {policyIDsWithEmptyReportsSelector} from '@selectors/Report'; -import {accountIDSelector, emailSelector} from '@selectors/Session'; +import {accountIDSelector} from '@selectors/Session'; import React, {useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import ActivityIndicator from '@components/ActivityIndicator'; @@ -11,6 +11,7 @@ import UserListItem from '@components/SelectionList/ListItem/UserListItem'; import type {ListItem} from '@components/SelectionList/types'; import Text from '@components/Text'; import useCreateEmptyReportConfirmation from '@hooks/useCreateEmptyReportConfirmation'; +import useCreateNewReport from '@hooks/useCreateNewReport'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useDebouncedState from '@hooks/useDebouncedState'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; @@ -20,14 +21,13 @@ import useOnyx from '@hooks/useOnyx'; import usePermissions from '@hooks/usePermissions'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; -import {createNewReport} from '@libs/actions/Report'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNavigationActionToMicrotaskQueue'; import Navigation from '@libs/Navigation/Navigation'; import type {NewReportWorkspaceSelectionNavigatorParamList} from '@libs/Navigation/types'; import {getHeaderMessageForNonUserList} from '@libs/OptionsListUtils'; import {canSubmitPerDiemExpenseFromWorkspace, isPolicyAdmin, shouldShowPolicy} from '@libs/PolicyUtils'; -import {getDefaultWorkspaceAvatar, hasViolations as hasViolationsReportUtils} from '@libs/ReportUtils'; +import {getDefaultWorkspaceAvatar} from '@libs/ReportUtils'; import {buildCannedSearchQuery} from '@libs/SearchQueryUtils'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import {isPerDiemRequest} from '@libs/TransactionUtils'; @@ -61,15 +61,12 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag const {shouldUseNarrowLayout} = useResponsiveLayout(); const [allReportNextSteps] = useOnyx(ONYXKEYS.COLLECTION.NEXT_STEP); const isRHPOnReportInSearch = isRHPOnSearchMoneyRequestReportPage(); - const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); const {isBetaEnabled} = usePermissions(); const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); const [accountID] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector}); - const [email] = useOnyx(ONYXKEYS.SESSION, {selector: emailSelector}); - const hasViolations = hasViolationsReportUtils(undefined, transactionViolations, accountID ?? CONST.DEFAULT_NUMBER_ID, email ?? ''); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); const [hasDismissedEmptyReportsConfirmation] = useOnyx(ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED); - const [betas] = useOnyx(ONYXKEYS.BETAS); + const createNewReport = useCreateNewReport(); const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const [userBillingGracePeriods] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); @@ -102,15 +99,7 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag }; const createReport = (policyID: string, shouldDismissEmptyReportsConfirmation?: boolean) => { - const optimisticReport = createNewReport( - currentUserPersonalDetails, - isASAPSubmitBetaEnabled, - hasViolations, - policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`], - betas, - false, - shouldDismissEmptyReportsConfirmation, - ); + const optimisticReport = createNewReport(policyID, shouldDismissEmptyReportsConfirmation); const selectedTransactionsKeys = Object.keys(selectedTransactions); if (isMovingExpenses && (!!selectedTransactionsKeys.length || !!selectedTransactionIDs.length)) { diff --git a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx index 93e39e855a38..6b7d7e85c849 100644 --- a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx +++ b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx @@ -129,7 +129,10 @@ function IOURequestStepUpgrade({ // workspace. forceReplace removes the upgrade screen from history so back returns to // the originating screen, not the upgrade step. setIsCreatingReport(true); - createNewReport(policyID, true); + const {reportID: newReportID} = createNewReport(policyID); + Navigation.setNavigationActionToMicrotaskQueue(() => { + Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(newReportID), {forceReplace: true}); + }); } else { Navigation.goBack(); navigateWithMicrotask(ROUTES.MONEY_REQUEST_STEP_REPORT.getRoute(action, CONST.IOU.TYPE.SUBMIT, transactionID, reportID)); From f4ab0c35c047b56236fd4604e745792794ca3f54 Mon Sep 17 00:00:00 2001 From: Mukher Date: Wed, 29 Apr 2026 07:04:30 +0500 Subject: [PATCH 07/13] fix: unshadow createNewReport hook variable; remove unused loading state Renames useCreateNewReport's destructured value to avoid shadowing the imported action used by the bulk-move branch. Also drops the dead isCreatingReport plumbing through ConfirmationPage / UpgradeConfirmation since report creation is fully optimistic. --- src/components/ConfirmationPage.tsx | 5 ----- src/pages/iou/request/step/IOURequestStepUpgrade.tsx | 8 +++----- src/pages/workspace/upgrade/UpgradeConfirmation.tsx | 5 +---- 3 files changed, 4 insertions(+), 14 deletions(-) diff --git a/src/components/ConfirmationPage.tsx b/src/components/ConfirmationPage.tsx index d115a39c01be..91973f9d64a0 100644 --- a/src/components/ConfirmationPage.tsx +++ b/src/components/ConfirmationPage.tsx @@ -42,9 +42,6 @@ type ConfirmationPageProps = { /** Whether we should show a primary confirmation button */ shouldShowButton?: boolean; - /** Whether the primary button should show a loading indicator */ - isButtonLoading?: boolean; - /** The text for the secondary button label */ secondaryButtonText?: string; @@ -86,7 +83,6 @@ function ConfirmationPage({ buttonText = '', onButtonPress = () => {}, shouldShowButton = false, - isButtonLoading = false, secondaryButtonText = '', onSecondaryButtonPress = () => {}, shouldShowSecondaryButton = false, @@ -166,7 +162,6 @@ function ConfirmationPage({ testID="confirmation-primary-button" style={styles.mt3} pressOnEnter - isLoading={isButtonLoading} onPress={onButtonPress} /> )} diff --git a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx index a842abe62f81..b78d49c9625f 100644 --- a/src/pages/iou/request/step/IOURequestStepUpgrade.tsx +++ b/src/pages/iou/request/step/IOURequestStepUpgrade.tsx @@ -64,7 +64,6 @@ function IOURequestStepUpgrade({ const [showConfirmationForm, setShowConfirmationForm] = useState(false); const [createdPolicyName, setCreatedPolicyName] = useState(''); const [isUpgradeWarningModalOpen, setIsUpgradeWarningModalOpen] = useState(false); - const [isCreatingReport, setIsCreatingReport] = useState(false); const policyDataRef = useRef(null); const isDistanceRateUpgrade = upgradePath === CONST.UPGRADE_PATHS.DISTANCE_RATES; const isCategorizing = upgradePath === CONST.UPGRADE_PATHS.CATEGORIES; @@ -76,7 +75,7 @@ function IOURequestStepUpgrade({ const [betas] = useOnyx(ONYXKEYS.BETAS); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); - const createNewReport = useCreateNewReport(); + const createReportForCurrentUser = useCreateNewReport(); // Hooks for bulk move functionality const {selectedTransactions} = useSearchStateContext(); @@ -200,8 +199,7 @@ function IOURequestStepUpgrade({ // Coming from "Create report" (no workspace) — create directly with the just-created // workspace. forceReplace removes the upgrade screen from history so back returns to // the originating screen, not the upgrade step. - setIsCreatingReport(true); - const {reportID: newReportID} = createNewReport(policyID); + const {reportID: newReportID} = createReportForCurrentUser(policyID); Navigation.setNavigationActionToMicrotaskQueue(() => { Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(newReportID), {forceReplace: true}); }); @@ -242,6 +240,7 @@ function IOURequestStepUpgrade({ iouType, isTrack, allPolicyTags, + createReportForCurrentUser, ]); const participant = transaction?.participants?.[0]; @@ -336,7 +335,6 @@ function IOURequestStepUpgrade({ isCategorizing={isCategorizing} isReporting={isReporting} isDistanceRateUpgrade={isDistanceRateUpgrade} - isButtonLoading={isCreatingReport} /> )} {!isUpgraded && ( diff --git a/src/pages/workspace/upgrade/UpgradeConfirmation.tsx b/src/pages/workspace/upgrade/UpgradeConfirmation.tsx index 197b843b2f37..639f056d2411 100644 --- a/src/pages/workspace/upgrade/UpgradeConfirmation.tsx +++ b/src/pages/workspace/upgrade/UpgradeConfirmation.tsx @@ -18,11 +18,9 @@ type Props = { isReporting?: boolean; isTravelUpgrade?: boolean; isDistanceRateUpgrade?: boolean; - /** Whether the "Got it, thanks" button should show a loading indicator */ - isButtonLoading?: boolean; }; -function UpgradeConfirmation({policyName, afterUpgradeAcknowledged, isReporting, isCategorizing, isTravelUpgrade, isDistanceRateUpgrade, isButtonLoading}: Props) { +function UpgradeConfirmation({policyName, afterUpgradeAcknowledged, isReporting, isCategorizing, isTravelUpgrade, isDistanceRateUpgrade}: Props) { const {translate} = useLocalize(); const styles = useThemeStyles(); const {environmentURL} = useEnvironment(); @@ -71,7 +69,6 @@ function UpgradeConfirmation({policyName, afterUpgradeAcknowledged, isReporting, shouldShowButton onButtonPress={afterUpgradeAcknowledged} buttonText={translate('workspace.upgrade.completed.gotIt')} - isButtonLoading={isButtonLoading} containerStyle={styles.h100} /> ); From 5a82e140308cc9e954c4b158c7cca7672e4c4fb2 Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 4 May 2026 09:41:38 +0500 Subject: [PATCH 08/13] fixed ts errors --- src/selectors/Report.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/selectors/Report.ts b/src/selectors/Report.ts index db75d4a52552..ce0341760891 100644 --- a/src/selectors/Report.ts +++ b/src/selectors/Report.ts @@ -37,7 +37,6 @@ const policyIDsWithEmptyReportsSelector = (accountID: number | undefined) => (re return getPolicyIDsWithEmptyReportsForAccount(reports, accountID); }; -export {getArchiveReason, getReportChatType, getReportOwnerAccountID, getReportPolicyID, policyIDsWithEmptyReportsSelector}; function openExpenseReportIDsSelector(reports: OnyxCollection): OpenExpenseReportIDMap { if (!reports) { return {}; @@ -55,4 +54,4 @@ function openExpenseReportIDsSelector(reports: OnyxCollection): OpenExpe return openExpenseReportIDMap; } -export {getArchiveReason, getReportChatType, getReportOwnerAccountID, getReportPolicyID, openExpenseReportIDsSelector}; +export {getArchiveReason, getReportChatType, getReportOwnerAccountID, getReportPolicyID, policyIDsWithEmptyReportsSelector, openExpenseReportIDsSelector}; From e84d4d93ba84af6b431a6fe86cdec303b925fd33 Mon Sep 17 00:00:00 2001 From: Mukher Date: Tue, 5 May 2026 15:59:55 +0500 Subject: [PATCH 09/13] fixed conflict issues --- src/hooks/useCreateReportAction.tsx | 6 +++-- src/pages/NewReportWorkspaceSelectionPage.tsx | 22 +++++-------------- src/selectors/Report.ts | 6 ++--- 3 files changed, 12 insertions(+), 22 deletions(-) diff --git a/src/hooks/useCreateReportAction.tsx b/src/hooks/useCreateReportAction.tsx index 18615a558000..5881d28b5d8f 100644 --- a/src/hooks/useCreateReportAction.tsx +++ b/src/hooks/useCreateReportAction.tsx @@ -50,6 +50,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); const [hasDismissedEmptyReportsConfirmation] = useOnyx(ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED); + const [accountID] = useOnyx(ONYXKEYS.SESSION, {selector: (session) => session?.accountID}); const {shouldRedirectToExpensifyClassic, canUseAction, showRedirectToExpensifyClassicModal} = useRedirectToExpensifyClassic(); @@ -105,7 +106,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith // No default or restricted with multiple workspaces → workspace selector if ( !workspaceIDForReportCreation || - (shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed) && + (shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID) && groupPoliciesWithChatEnabled.length > 1) ) { Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -113,7 +114,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith } // Default workspace is not restricted → create report directly (or show empty-report confirmation) - if (!shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed)) { + if (!shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID)) { if (shouldShowEmptyReportConfirmation) { openCreateReportConfirmation(); } else { @@ -133,6 +134,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, + accountID, groupPoliciesWithChatEnabled.length, shouldShowEmptyReportConfirmation, openCreateReportConfirmation, diff --git a/src/pages/NewReportWorkspaceSelectionPage.tsx b/src/pages/NewReportWorkspaceSelectionPage.tsx index d7349235bc63..b7f38d869f4b 100644 --- a/src/pages/NewReportWorkspaceSelectionPage.tsx +++ b/src/pages/NewReportWorkspaceSelectionPage.tsx @@ -1,7 +1,7 @@ +import {policyIDsWithEmptyReportsSelector} from '@selectors/Report'; import {accountIDSelector} from '@selectors/Session'; -import React, {useEffect, useState} from 'react'; +import React, {useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; -import type {OnyxCollection} from 'react-native-onyx'; import ActivityIndicator from '@components/ActivityIndicator'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; import ScreenWrapper from '@components/ScreenWrapper'; @@ -27,7 +27,7 @@ import Navigation from '@libs/Navigation/Navigation'; import type {NewReportWorkspaceSelectionNavigatorParamList} from '@libs/Navigation/types'; import {getHeaderMessageForNonUserList} from '@libs/OptionsListUtils'; import {canSubmitPerDiemExpenseFromWorkspace, isPolicyAdmin, shouldShowPolicy} from '@libs/PolicyUtils'; -import {getDefaultWorkspaceAvatar, getPolicyIDsWithEmptyReportsForAccount} from '@libs/ReportUtils'; +import {getDefaultWorkspaceAvatar} from '@libs/ReportUtils'; import {buildCannedSearchQuery} from '@libs/SearchQueryUtils'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import {isPerDiemRequest} from '@libs/TransactionUtils'; @@ -39,7 +39,6 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; -import type * as OnyxTypes from '@src/types/onyx'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; type WorkspaceListItem = { @@ -84,19 +83,8 @@ function NewReportWorkspaceSelectionPage({route}: NewReportWorkspaceSelectionPag const [todos] = useOnyx(ONYXKEYS.DERIVED.TODOS); const transactionsByReportID = todos?.transactionsByReportID; - const [policiesWithEmptyReports] = useOnyx( - ONYXKEYS.COLLECTION.REPORT, - { - selector: (reports: OnyxCollection) => { - if (!accountID) { - return {}; - } - - return getPolicyIDsWithEmptyReportsForAccount(reports, accountID, transactionsByReportID ?? {}); - }, - }, - [accountID, transactionsByReportID], - ); + const policiesWithEmptyReportsForAccountSelector = useMemo(() => policyIDsWithEmptyReportsSelector(accountID, transactionsByReportID ?? {}), [accountID, transactionsByReportID]); + const [policiesWithEmptyReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: policiesWithEmptyReportsForAccountSelector}); const navigateToNewReport = (optimisticReportID: string) => { if (isRHPOnReportInSearch) { diff --git a/src/selectors/Report.ts b/src/selectors/Report.ts index ce0341760891..4edd2534c0b8 100644 --- a/src/selectors/Report.ts +++ b/src/selectors/Report.ts @@ -3,7 +3,7 @@ import type {ValueOf} from 'type-fest'; import {getOriginalMessage, isClosedAction} from '@libs/ReportActionsUtils'; import {getPolicyIDsWithEmptyReportsForAccount, isOpenExpenseReport} from '@libs/ReportUtils'; import CONST from '@src/CONST'; -import type {Report, ReportActions} from '@src/types/onyx'; +import type {Report, ReportActions, Transaction} from '@src/types/onyx'; import {getLastClosedReportAction} from './ReportAction'; type OpenExpenseReportIDMap = Record; @@ -30,11 +30,11 @@ function getReportOwnerAccountID(report: OnyxEntry) { return report?.ownerAccountID; } -const policyIDsWithEmptyReportsSelector = (accountID: number | undefined) => (reports: OnyxCollection) => { +const policyIDsWithEmptyReportsSelector = (accountID: number | undefined, transactionsByReportID: Record) => (reports: OnyxCollection) => { if (!accountID) { return {}; } - return getPolicyIDsWithEmptyReportsForAccount(reports, accountID); + return getPolicyIDsWithEmptyReportsForAccount(reports, accountID, transactionsByReportID); }; function openExpenseReportIDsSelector(reports: OnyxCollection): OpenExpenseReportIDMap { From bdb366edfada9db0b187dc9dee0aaecbfb3e2251 Mon Sep 17 00:00:00 2001 From: Mukher Date: Fri, 8 May 2026 11:28:36 +0500 Subject: [PATCH 10/13] added tests --- src/hooks/useCreateReportAction.tsx | 20 +++-- tests/unit/useCreateReportActionTest.tsx | 104 +++++++++++++++++++++-- 2 files changed, 112 insertions(+), 12 deletions(-) diff --git a/src/hooks/useCreateReportAction.tsx b/src/hooks/useCreateReportAction.tsx index 5881d28b5d8f..5418c2d03be4 100644 --- a/src/hooks/useCreateReportAction.tsx +++ b/src/hooks/useCreateReportAction.tsx @@ -2,7 +2,7 @@ import {useCallback} from 'react'; import type {OnyxEntry} from 'react-native-onyx'; import interceptAnonymousUser from '@libs/interceptAnonymousUser'; import Navigation from '@libs/Navigation/Navigation'; -import {getDefaultChatEnabledPolicy} from '@libs/PolicyUtils'; +import {getDefaultChatEnabledPolicy, isPaidGroupPolicy} from '@libs/PolicyUtils'; import {generateReportID} from '@libs/ReportUtils'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import useRedirectToExpensifyClassic from '@pages/inbox/sidebar/FABPopoverContent/useRedirectToExpensifyClassic'; @@ -103,12 +103,17 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith const workspaceIDForReportCreation = defaultChatEnabledPolicyID; - // No default or restricted with multiple workspaces → workspace selector - if ( - !workspaceIDForReportCreation || - (shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID) && - groupPoliciesWithChatEnabled.length > 1) - ) { + // Per spec: show the workspace selector only when the default (active) workspace is personal + // AND the user has 2+ non-personal workspaces to choose between. We also fall back to the + // selector if the chosen default is billing-restricted and alternatives exist, so the user + // isn't dead-ended on the restricted-action page. + const isDefaultPersonal = !activePolicy || activePolicy.type === CONST.POLICY.TYPE.PERSONAL || !isPaidGroupPolicy(activePolicy); + const hasMultipleNonPersonalWorkspaces = groupPoliciesWithChatEnabled.length > 1; + const isDefaultBillingRestricted = + !!workspaceIDForReportCreation && + shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID); + + if (!workspaceIDForReportCreation || (isDefaultPersonal && hasMultipleNonPersonalWorkspaces) || (isDefaultBillingRestricted && hasMultipleNonPersonalWorkspaces)) { Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); return; } @@ -130,6 +135,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith shouldRedirectToExpensifyClassic, showRedirectToExpensifyClassicModal, shouldNavigateToUpgradePath, + activePolicy, defaultChatEnabledPolicyID, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, diff --git a/tests/unit/useCreateReportActionTest.tsx b/tests/unit/useCreateReportActionTest.tsx index 1a0dcb3b6dbe..c706bbd5893b 100644 --- a/tests/unit/useCreateReportActionTest.tsx +++ b/tests/unit/useCreateReportActionTest.tsx @@ -16,7 +16,7 @@ jest.mock('@hooks/useOnyx', () => jest.fn()); const mockUseOnyx = useOnyx as jest.MockedFunction; jest.mock('@hooks/useHasEmptyReportsForPolicy', () => jest.fn(() => false)); -// eslint-disable-next-line @typescript-eslint/no-require-imports + const mockUseHasEmptyReportsForPolicy = require('@hooks/useHasEmptyReportsForPolicy') as jest.Mock; const mockOpenCreateReportConfirmation = jest.fn(); @@ -35,14 +35,23 @@ const mockUseRedirectToExpensifyClassic = jest.fn(() => ({ showRedirectToExpensifyClassicModal: mockShowRedirectToExpensifyClassicModal, })); jest.mock('@pages/inbox/sidebar/FABPopoverContent/useRedirectToExpensifyClassic', () => ({ - // eslint-disable-next-line @typescript-eslint/naming-convention __esModule: true, - // eslint-disable-next-line @typescript-eslint/no-unsafe-return + default: () => mockUseRedirectToExpensifyClassic(), })); jest.mock('@libs/PolicyUtils', () => ({ - getDefaultChatEnabledPolicy: jest.fn((policies: Array>) => policies.at(0) ?? undefined), + getDefaultChatEnabledPolicy: jest.fn((policies: Array>, activePolicy: OnyxEntry) => { + // Mirror the real helper: prefer activePolicy if it's a paid group with chat enabled, otherwise the single non-personal candidate. + if (activePolicy && activePolicy.isPolicyExpenseChatEnabled && (activePolicy.type === 'team' || activePolicy.type === 'corporate')) { + return activePolicy; + } + if (policies.length === 1) { + return policies.at(0); + } + return undefined; + }), + isPaidGroupPolicy: jest.fn((policy: OnyxEntry) => policy?.type === 'team' || policy?.type === 'corporate'), })); jest.mock('@libs/interceptAnonymousUser', () => jest.fn((cb: () => void) => cb())); @@ -58,7 +67,6 @@ jest.mock('@libs/ReportUtils', () => ({ const mockShouldRestrictUserBillableActions = jest.fn(() => false); jest.mock('@libs/SubscriptionUtils', () => ({ - // eslint-disable-next-line @typescript-eslint/no-unsafe-return shouldRestrictUserBillableActions: (...args: Parameters) => mockShouldRestrictUserBillableActions(...args), })); @@ -177,6 +185,12 @@ describe('useCreateReportAction', () => { }); it('navigates to workspace selector when restricted with multiple workspaces', () => { + // Set activePolicy to a non-personal paid policy so isDefaultPersonal is false; the selector + // should fire purely on the billing-restricted safety net branch. + setupUseOnyx({ + [ONYXKEYS.NVP_ACTIVE_POLICY_ID]: 'p1', + [`${ONYXKEYS.COLLECTION.POLICY}p1`]: makePaidPolicy('p1'), + }); mockShouldRestrictUserBillableActions.mockReturnValue(true); const onCreateReport = jest.fn(); const policies = [makePaidPolicy('p1'), makePaidPolicy('p2')]; @@ -194,6 +208,86 @@ describe('useCreateReportAction', () => { expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); }); + + it('navigates to workspace selector when default is personal and there are 2+ non-personal workspaces', () => { + // Per spec: selector shows iff default workspace is personal AND user has 2+ non-personal options. + const personalPolicy = { + ...makePaidPolicy('personal-1'), + type: CONST.POLICY.TYPE.PERSONAL, + } as OnyxEntry; + setupUseOnyx({ + [ONYXKEYS.NVP_ACTIVE_POLICY_ID]: 'personal-1', + [`${ONYXKEYS.COLLECTION.POLICY}personal-1`]: personalPolicy, + }); + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy('p1'), makePaidPolicy('p2')]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + expect(onCreateReport).not.toHaveBeenCalled(); + }); + + it('does NOT show selector when default is non-personal, even with multiple non-personal workspaces', () => { + // Per spec: if default is already non-personal, just create in default — no selector. + setupUseOnyx({ + [ONYXKEYS.NVP_ACTIVE_POLICY_ID]: 'p1', + [`${ONYXKEYS.COLLECTION.POLICY}p1`]: makePaidPolicy('p1'), + }); + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy('p1'), makePaidPolicy('p2'), makePaidPolicy('p3')]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + expect(onCreateReport).toHaveBeenCalledWith(false); + }); + + it('does NOT show selector when default is personal but only 1 non-personal workspace exists', () => { + // Per spec: with a single non-personal candidate, just create there — no selector. + const personalPolicy = { + ...makePaidPolicy('personal-1'), + type: CONST.POLICY.TYPE.PERSONAL, + } as OnyxEntry; + setupUseOnyx({ + [ONYXKEYS.NVP_ACTIVE_POLICY_ID]: 'personal-1', + [`${ONYXKEYS.COLLECTION.POLICY}personal-1`]: personalPolicy, + }); + const onCreateReport = jest.fn(); + const policies = [makePaidPolicy('p1')]; + + const {result} = renderHook(() => + useCreateReportAction({ + onCreateReport, + groupPoliciesWithChatEnabled: policies, + }), + ); + + act(() => { + result.current.createReportAction(); + }); + + expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); + expect(onCreateReport).toHaveBeenCalledWith(false); + }); }); describe('direct report creation', () => { From a6cb389606a16262ac61ef058d0981aaf36e39db Mon Sep 17 00:00:00 2001 From: Mukher Date: Tue, 12 May 2026 21:43:18 +0500 Subject: [PATCH 11/13] Pass `defaultChatEnabledPolicy` instead of the policy ID string in useCreateReportAction. --- src/hooks/useCreateReportAction.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/hooks/useCreateReportAction.tsx b/src/hooks/useCreateReportAction.tsx index 67ca94ce7ed2..3396c3eda56c 100644 --- a/src/hooks/useCreateReportAction.tsx +++ b/src/hooks/useCreateReportAction.tsx @@ -101,8 +101,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith const isDefaultPersonal = !activePolicy || activePolicy.type === CONST.POLICY.TYPE.PERSONAL || !isPaidGroupPolicy(activePolicy); const hasMultipleNonPersonalWorkspaces = groupPoliciesWithChatEnabled.length > 1; const isDefaultBillingRestricted = - !!workspaceIDForReportCreation && - shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID); + !!workspaceIDForReportCreation && shouldRestrictUserBillableActions(defaultChatEnabledPolicy, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID); if (!workspaceIDForReportCreation || (isDefaultPersonal && hasMultipleNonPersonalWorkspaces) || (isDefaultBillingRestricted && hasMultipleNonPersonalWorkspaces)) { Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -110,7 +109,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith } // Default workspace is not restricted → create report directly (or show empty-report confirmation) - if (!shouldRestrictUserBillableActions(workspaceIDForReportCreation, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID)) { + if (!shouldRestrictUserBillableActions(defaultChatEnabledPolicy, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID)) { if (shouldShowEmptyReportConfirmation) { openCreateReportConfirmation(); } else { @@ -125,6 +124,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith arePoliciesLoaded, shouldNavigateToUpgradePath, activePolicy, + defaultChatEnabledPolicy, defaultChatEnabledPolicyID, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, From 869fce595dc576f9fb897c63645059b74a8968dc Mon Sep 17 00:00:00 2001 From: Mukher Date: Thu, 14 May 2026 18:15:47 +0500 Subject: [PATCH 12/13] fixed comments and namings --- src/hooks/{useCreateReportAction.tsx => useCreateReport.tsx} | 0 .../{useCreateReportActionTest.tsx => useCreateReportTest.tsx} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename src/hooks/{useCreateReportAction.tsx => useCreateReport.tsx} (100%) rename tests/unit/{useCreateReportActionTest.tsx => useCreateReportTest.tsx} (100%) diff --git a/src/hooks/useCreateReportAction.tsx b/src/hooks/useCreateReport.tsx similarity index 100% rename from src/hooks/useCreateReportAction.tsx rename to src/hooks/useCreateReport.tsx diff --git a/tests/unit/useCreateReportActionTest.tsx b/tests/unit/useCreateReportTest.tsx similarity index 100% rename from tests/unit/useCreateReportActionTest.tsx rename to tests/unit/useCreateReportTest.tsx From aede2dd4295c90d3c6a61ab7ecb00c6291f8936a Mon Sep 17 00:00:00 2001 From: Mukher Date: Thu, 14 May 2026 18:16:04 +0500 Subject: [PATCH 13/13] fixed comments and namings --- src/hooks/useCreateReport.tsx | 28 ++++---- src/pages/Search/EmptySearchView.tsx | 6 +- .../menuItems/CreateReportMenuItem.tsx | 6 +- tests/unit/useCreateReportTest.tsx | 66 +++++++++---------- 4 files changed, 53 insertions(+), 53 deletions(-) diff --git a/src/hooks/useCreateReport.tsx b/src/hooks/useCreateReport.tsx index 3396c3eda56c..9f06a7c51f10 100644 --- a/src/hooks/useCreateReport.tsx +++ b/src/hooks/useCreateReport.tsx @@ -14,7 +14,7 @@ import useCreateEmptyReportConfirmation from './useCreateEmptyReportConfirmation import useHasEmptyReportsForPolicy from './useHasEmptyReportsForPolicy'; import useOnyx from './useOnyx'; -type UseCreateReportActionParams = { +type UseCreateReportParams = { /** Callback that creates the report and navigates after creation */ onCreateReport: (shouldDismissEmptyReportsConfirmation?: boolean) => void; /** Group paid policies with expense chat enabled */ @@ -23,9 +23,9 @@ type UseCreateReportActionParams = { shouldHandleNavigationBack?: boolean; }; -type UseCreateReportActionResult = { - /** The action to trigger when the user clicks "Create report" */ - createReportAction: () => void; +type UseCreateReportResult = { + /** The callback to trigger when the user clicks "Create report" */ + createReport: () => void; /** Whether the menu item/button should be visible */ isVisible: boolean; }; @@ -36,14 +36,14 @@ type UseCreateReportActionResult = { * * Decision flow: * 1. Navigate to upgrade path if user has no valid group policies at all - * 2. Navigate to workspace selector if default is personal AND there are 2+ non-personal workspaces, or if the chosen default is billing-restricted and alternatives exist + * 2. Navigate to workspace selector if default is personal AND there are at least 2 non-personal workspaces, or if the chosen default is billing-restricted and alternatives exist * 3. Show empty report confirmation or create directly if workspace is valid * 4. Navigate to restricted action if billing restricts the workspace */ -export default function useCreateReportAction({onCreateReport, groupPoliciesWithChatEnabled, shouldHandleNavigationBack = true}: UseCreateReportActionParams): UseCreateReportActionResult { +export default function useCreateReport({onCreateReport, groupPoliciesWithChatEnabled, shouldHandleNavigationBack = true}: UseCreateReportParams): UseCreateReportResult { const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); const [activePolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`); - const [, policiesMeta] = useOnyx(ONYXKEYS.COLLECTION.POLICY); + const [, policiesLoadStatus] = useOnyx(ONYXKEYS.COLLECTION.POLICY); const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); @@ -53,7 +53,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith // Gate visibility and routing on policy hydration. Without this, during Onyx cold-start // groupPoliciesWithChatEnabled.length === 0 would be true even for users who actually have // workspaces, sending them to MONEY_REQUEST_UPGRADE as if they had none. - const arePoliciesLoaded = !isLoadingOnyxValue(policiesMeta); + const arePoliciesLoaded = !isLoadingOnyxValue(policiesLoadStatus); const isVisible = arePoliciesLoaded; const shouldNavigateToUpgradePath = groupPoliciesWithChatEnabled.length === 0; @@ -70,7 +70,7 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith shouldHandleNavigationBack, }); - const createReportAction = useCallback(() => { + const createReport = useCallback(() => { interceptAnonymousUser(() => { if (!arePoliciesLoaded) { return; @@ -94,10 +94,10 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith const workspaceIDForReportCreation = defaultChatEnabledPolicyID; - // Per spec: show the workspace selector only when the default (active) workspace is personal - // AND the user has 2+ non-personal workspaces to choose between. We also fall back to the - // selector if the chosen default is billing-restricted and alternatives exist, so the user - // isn't dead-ended on the restricted-action page. + // Show the workspace selector only when the default workspace is personal and there are + // at least 2 non-personal workspaces to choose between. Also fall back to the selector if + // the default is billing-restricted and alternatives exist, so the user isn't dead-ended + // on the restricted-action page. const isDefaultPersonal = !activePolicy || activePolicy.type === CONST.POLICY.TYPE.PERSONAL || !isPaidGroupPolicy(activePolicy); const hasMultipleNonPersonalWorkspaces = groupPoliciesWithChatEnabled.length > 1; const isDefaultBillingRestricted = @@ -136,5 +136,5 @@ export default function useCreateReportAction({onCreateReport, groupPoliciesWith onCreateReport, ]); - return {createReportAction, isVisible}; + return {createReport, isVisible}; } diff --git a/src/pages/Search/EmptySearchView.tsx b/src/pages/Search/EmptySearchView.tsx index 7727a557cf6b..3639cb1dbb7c 100644 --- a/src/pages/Search/EmptySearchView.tsx +++ b/src/pages/Search/EmptySearchView.tsx @@ -13,7 +13,7 @@ import {SearchScopeProvider} from '@components/Search/SearchScopeProvider'; import type {SearchQueryJSON} from '@components/Search/types'; import Text from '@components/Text'; import TextLink from '@components/TextLink'; -import useCreateReportAction from '@hooks/useCreateReportAction'; +import useCreateReport from '@hooks/useCreateReport'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; import {useMemoizedLazyIllustrations} from '@hooks/useLazyAsset'; @@ -178,7 +178,7 @@ function EmptySearchViewContent({ }); }; - const {createReportAction, isVisible: isCreateReportVisible} = useCreateReportAction({ + const {createReport, isVisible: isCreateReportVisible} = useCreateReport({ onCreateReport: handleCreateWorkspaceReport, groupPoliciesWithChatEnabled, }); @@ -282,7 +282,7 @@ function EmptySearchViewContent({ ? [ { buttonText: translate('quickAction.createReport'), - buttonAction: createReportAction, + buttonAction: createReport, success: true, }, ] diff --git a/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx b/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx index 808a7725351e..8e6c0962b3ed 100644 --- a/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx +++ b/src/pages/inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem.tsx @@ -1,6 +1,6 @@ import React from 'react'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; -import useCreateReportAction from '@hooks/useCreateReportAction'; +import useCreateReport from '@hooks/useCreateReport'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; @@ -94,7 +94,7 @@ function CreateReportMenuItem() { }); }; - const {createReportAction, isVisible} = useCreateReportAction({ + const {createReport, isVisible} = useCreateReport({ onCreateReport: handleCreateWorkspaceReport, groupPoliciesWithChatEnabled, shouldHandleNavigationBack: false, @@ -107,7 +107,7 @@ function CreateReportMenuItem() { pressableTestID={CONST.SENTRY_LABEL.FAB_MENU.CREATE_REPORT} icon={icons.Document} title={translate('report.newReport.createReport')} - onPress={createReportAction} + onPress={createReport} shouldCallAfterModalHide={shouldUseNarrowLayout} /> ); diff --git a/tests/unit/useCreateReportTest.tsx b/tests/unit/useCreateReportTest.tsx index 0262c1002822..a39e2dff81de 100644 --- a/tests/unit/useCreateReportTest.tsx +++ b/tests/unit/useCreateReportTest.tsx @@ -1,6 +1,6 @@ import {act, renderHook} from '@testing-library/react-native'; import type {OnyxEntry} from 'react-native-onyx'; -import useCreateReportAction from '@hooks/useCreateReportAction'; +import useCreateReport from '@hooks/useCreateReport'; import useOnyx from '@hooks/useOnyx'; import Navigation from '@libs/Navigation/Navigation'; import CONST from '@src/CONST'; @@ -86,7 +86,7 @@ function setupUseOnyx(overrides: Record = {}) { // ── Tests ────────────────────────────────────────────────────────────────────── -describe('useCreateReportAction', () => { +describe('useCreateReport', () => { beforeEach(() => { jest.clearAllMocks(); reportIDCounter.value = 100; @@ -100,14 +100,14 @@ describe('useCreateReportAction', () => { const onCreateReport = jest.fn(); const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: [], }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).toHaveBeenCalledTimes(1); @@ -125,14 +125,14 @@ describe('useCreateReportAction', () => { const policies = [undefined] as Array>; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -151,14 +151,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy('p1'), makePaidPolicy('p2')]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -178,14 +178,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy('p1'), makePaidPolicy('p2')]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -202,14 +202,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy('p1'), makePaidPolicy('p2'), makePaidPolicy('p3')]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -230,14 +230,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy('p1')]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute()); @@ -251,14 +251,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy()]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(onCreateReport).toHaveBeenCalledWith(false); @@ -271,14 +271,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy()]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(mockOpenCreateReportConfirmation).toHaveBeenCalledTimes(1); @@ -293,14 +293,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy()]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.RESTRICTED_ACTION.getRoute(POLICY_ID)); @@ -313,14 +313,14 @@ describe('useCreateReportAction', () => { const onCreateReport = jest.fn(); const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: [], }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); const navigateArg = jest.mocked(Navigation.navigate).mock.calls.at(0)?.at(0) as string; @@ -334,14 +334,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy()]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); // Should call onCreateReport directly, not navigate to upgrade @@ -366,14 +366,14 @@ describe('useCreateReportAction', () => { const policies = [makePaidPolicy()]; const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: policies, }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(onCreateReport).toHaveBeenCalledWith(false); @@ -382,17 +382,17 @@ describe('useCreateReportAction', () => { }); describe('returns', () => { - it('returns createReportAction function and isVisible flag', () => { + it('returns createReport function and isVisible flag', () => { const onCreateReport = jest.fn(); const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: [], }), ); - expect(typeof result.current.createReportAction).toBe('function'); + expect(typeof result.current.createReport).toBe('function'); expect(typeof result.current.isVisible).toBe('boolean'); }); @@ -400,7 +400,7 @@ describe('useCreateReportAction', () => { const onCreateReport = jest.fn(); const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: [makePaidPolicy()], }), @@ -421,7 +421,7 @@ describe('useCreateReportAction', () => { const onCreateReport = jest.fn(); const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: [], }), @@ -442,14 +442,14 @@ describe('useCreateReportAction', () => { const onCreateReport = jest.fn(); const {result} = renderHook(() => - useCreateReportAction({ + useCreateReport({ onCreateReport, groupPoliciesWithChatEnabled: [], }), ); act(() => { - result.current.createReportAction(); + result.current.createReport(); }); expect(Navigation.navigate).not.toHaveBeenCalled();