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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/ROUTES.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1069,7 +1069,12 @@ 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;
const params = new URLSearchParams();
if (isMovingExpenses) {
params.set('isMovingExpenses', 'true');
}
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);
Expand Down
36 changes: 36 additions & 0 deletions src/hooks/useCreateNewReport.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {accountIDSelector, emailSelector} from '@selectors/Session';
import {useCallback} from 'react';
import {createNewReport} from '@libs/actions/Report';
import {hasViolations as hasViolationsUtil} from '@libs/ReportUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails';
import useOnyx from './useOnyx';
import usePermissions from './usePermissions';

/**
* 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();
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, shouldDismissEmptyReportsConfirmation = false) => {
const policy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
return createNewReport(currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policy, betas, false, shouldDismissEmptyReportsConfirmation);
},
[betas, currentUserPersonalDetails, hasViolations, isASAPSubmitBetaEnabled, policies],
);
}

export default useCreateNewReport;
140 changes: 140 additions & 0 deletions src/hooks/useCreateReport.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import {useCallback} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import interceptAnonymousUser from '@libs/interceptAnonymousUser';
import Navigation from '@libs/Navigation/Navigation';
import {getDefaultChatEnabledPolicy, isPaidGroupPolicy} from '@libs/PolicyUtils';
import {generateReportID} from '@libs/ReportUtils';
import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils';
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';

type UseCreateReportParams = {
/** Callback that creates the report and navigates after creation */
onCreateReport: (shouldDismissEmptyReportsConfirmation?: boolean) => void;
/** Group paid policies with expense chat enabled */
groupPoliciesWithChatEnabled: readonly never[] | Array<OnyxEntry<OnyxTypes.Policy>>;
/** Whether the empty-report confirmation modal should push a history entry so browser-back dismisses it (default: true) */
shouldHandleNavigationBack?: boolean;
};

type UseCreateReportResult = {
/** The callback to trigger when the user clicks "Create report" */
createReport: () => void;
/** Whether the menu item/button should be visible */
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. 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 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 useCreateReport({onCreateReport, groupPoliciesWithChatEnabled, shouldHandleNavigationBack = true}: UseCreateReportParams): UseCreateReportResult {
const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID);
const [activePolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`);
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);
const [hasDismissedEmptyReportsConfirmation] = useOnyx(ONYXKEYS.NVP_EMPTY_REPORTS_CONFIRMATION_DISMISSED);
const [accountID] = useOnyx(ONYXKEYS.SESSION, {selector: (session) => session?.accountID});

// 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(policiesLoadStatus);
const isVisible = arePoliciesLoaded;
const shouldNavigateToUpgradePath = groupPoliciesWithChatEnabled.length === 0;

const defaultChatEnabledPolicy = getDefaultChatEnabledPolicy(groupPoliciesWithChatEnabled as Array<OnyxEntry<OnyxTypes.Policy>>, 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 createReport = useCallback(() => {
interceptAnonymousUser(() => {
if (!arePoliciesLoaded) {
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;

// 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 =
!!workspaceIDForReportCreation && shouldRestrictUserBillableActions(defaultChatEnabledPolicy, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID);

if (!workspaceIDForReportCreation || (isDefaultPersonal && hasMultipleNonPersonalWorkspaces) || (isDefaultBillingRestricted && hasMultipleNonPersonalWorkspaces)) {
Navigation.navigate(ROUTES.NEW_REPORT_WORKSPACE_SELECTION.getRoute());
return;
}

// Default workspace is not restricted → create report directly (or show empty-report confirmation)
if (!shouldRestrictUserBillableActions(defaultChatEnabledPolicy, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, accountID)) {
if (shouldShowEmptyReportConfirmation) {
openCreateReportConfirmation();
} else {
onCreateReport(false);
}
return;
}

Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(workspaceIDForReportCreation));
});
}, [
arePoliciesLoaded,
shouldNavigateToUpgradePath,
activePolicy,
defaultChatEnabledPolicy,
defaultChatEnabledPolicyID,
ownerBillingGracePeriodEnd,
userBillingGracePeriodEnds,
amountOwed,
accountID,
groupPoliciesWithChatEnabled.length,
shouldShowEmptyReportConfirmation,
openCreateReportConfirmation,
onCreateReport,
]);

return {createReport, isVisible};
}
41 changes: 9 additions & 32 deletions src/pages/NewReportWorkspaceSelectionPage.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {accountIDSelector, emailSelector} from '@selectors/Session';
import React, {useEffect, useState} from 'react';
import {policyIDsWithEmptyReportsSelector} from '@selectors/Report';
import {accountIDSelector} from '@selectors/Session';
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';
Expand All @@ -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';
Expand All @@ -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, getPolicyIDsWithEmptyReportsForAccount, 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';
Expand All @@ -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 = {
Expand All @@ -62,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);
Expand All @@ -87,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<OnyxTypes.Report>) => {
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) {
Expand All @@ -117,15 +102,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)) {
Expand Down
Loading
Loading