diff --git a/src/hooks/useActivePolicy.ts b/src/hooks/useActivePolicy.ts new file mode 100644 index 000000000000..97bd67abbd72 --- /dev/null +++ b/src/hooks/useActivePolicy.ts @@ -0,0 +1,8 @@ +import ONYXKEYS from '@src/ONYXKEYS'; +import useOnyx from './useOnyx'; +import usePolicy from './usePolicy'; + +export default function useActivePolicy() { + const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID, {canBeMissing: false}); + return usePolicy(activePolicyID); +} diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index f15613ff14ef..c150168a4499 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -1203,12 +1203,6 @@ Onyx.connectWithoutView({ }, }); -let activePolicyID: OnyxEntry; -Onyx.connectWithoutView({ - key: ONYXKEYS.NVP_ACTIVE_POLICY_ID, - callback: (value) => (activePolicyID = value), -}); - let reportAttributesDerivedValue: ReportAttributesDerivedValue['reports']; Onyx.connectWithoutView({ key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, @@ -11172,6 +11166,7 @@ function createDraftTransactionAndNavigateToParticipantSelector( actionName: IOUAction, reportActionID: string | undefined, introSelected: OnyxEntry, + activePolicy: OnyxEntry, isRestrictedToPreferredPolicy = false, preferredPolicyID?: string, ): void { @@ -11215,23 +11210,20 @@ function createDraftTransactionAndNavigateToParticipantSelector( const filteredPolicies = Object.values(allPolicies ?? {}).filter((policy) => shouldShowPolicy(policy, false, currentUserEmail)); if (actionName === CONST.IOU.ACTION.CATEGORIZE) { - // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850 - // eslint-disable-next-line @typescript-eslint/no-deprecated - const activePolicy = getPolicy(activePolicyID); if (activePolicy && shouldRestrictUserBillableActions(activePolicy.id)) { Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(activePolicy.id)); return; } - if (shouldShowPolicy(activePolicy, false, currentUserEmail)) { - const policyExpenseReportID = getPolicyExpenseChat(currentUserAccountID, activePolicyID)?.reportID; + if (activePolicy && shouldShowPolicy(activePolicy, false, currentUserEmail)) { + const policyExpenseReportID = getPolicyExpenseChat(currentUserAccountID, activePolicy.id)?.reportID; setMoneyRequestParticipants(transactionID, [ { selected: true, accountID: 0, isPolicyExpenseChat: true, reportID: policyExpenseReportID, - policyID: activePolicyID, + policyID: activePolicy.id, searchText: activePolicy?.name, }, ]); diff --git a/src/pages/ReportDetailsPage.tsx b/src/pages/ReportDetailsPage.tsx index ce3ab6b0db79..f75fefa38197 100644 --- a/src/pages/ReportDetailsPage.tsx +++ b/src/pages/ReportDetailsPage.tsx @@ -22,6 +22,7 @@ import RoomHeaderAvatars from '@components/RoomHeaderAvatars'; import ScreenWrapper from '@components/ScreenWrapper'; import ScrollView from '@components/ScrollView'; import {useSearchContext} from '@components/Search/SearchContext'; +import useActivePolicy from '@hooks/useActivePolicy'; import useAncestors from '@hooks/useAncestors'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useDeleteTransactions from '@hooks/useDeleteTransactions'; @@ -155,6 +156,7 @@ function ReportDetailsPage({policy, report, route, reportMetadata}: ReportDetail const {translate, localeCompare, formatPhoneNumber} = useLocalize(); const {isOffline} = useNetwork(); const {isRestrictedToPreferredPolicy, preferredPolicyID} = usePreferredPolicy(); + const activePolicy = useActivePolicy(); const styles = useThemeStyles(); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Users', 'Gear', 'Send', 'Folder', 'UserPlus', 'Pencil', 'Checkmark', 'Building', 'Exit', 'Bug', 'Camera', 'Trashcan']); const backTo = route.params.backTo; @@ -440,6 +442,7 @@ function ReportDetailsPage({policy, report, route, reportMetadata}: ReportDetail CONST.IOU.ACTION.SUBMIT, actionableWhisperReportActionID, introSelected, + activePolicy, isRestrictedToPreferredPolicy, preferredPolicyID, ); @@ -453,7 +456,14 @@ function ReportDetailsPage({policy, report, route, reportMetadata}: ReportDetail isAnonymousAction: false, shouldShowRightIcon: true, action: () => { - createDraftTransactionAndNavigateToParticipantSelector(iouTransactionID, actionReportID, CONST.IOU.ACTION.CATEGORIZE, actionableWhisperReportActionID, introSelected); + createDraftTransactionAndNavigateToParticipantSelector( + iouTransactionID, + actionReportID, + CONST.IOU.ACTION.CATEGORIZE, + actionableWhisperReportActionID, + introSelected, + activePolicy, + ); }, }); items.push({ @@ -463,7 +473,14 @@ function ReportDetailsPage({policy, report, route, reportMetadata}: ReportDetail isAnonymousAction: false, shouldShowRightIcon: true, action: () => { - createDraftTransactionAndNavigateToParticipantSelector(iouTransactionID, actionReportID, CONST.IOU.ACTION.SHARE, actionableWhisperReportActionID, introSelected); + createDraftTransactionAndNavigateToParticipantSelector( + iouTransactionID, + actionReportID, + CONST.IOU.ACTION.SHARE, + actionableWhisperReportActionID, + introSelected, + activePolicy, + ); }, }); } @@ -584,6 +601,7 @@ function ReportDetailsPage({policy, report, route, reportMetadata}: ReportDetail isRestrictedToPreferredPolicy, preferredPolicyID, introSelected, + activePolicy, parentReport, ]); diff --git a/src/pages/home/report/PureReportActionItem.tsx b/src/pages/home/report/PureReportActionItem.tsx index 41178c62cc31..94e34614ca81 100644 --- a/src/pages/home/report/PureReportActionItem.tsx +++ b/src/pages/home/report/PureReportActionItem.tsx @@ -39,6 +39,7 @@ import {ShowContextMenuContext} from '@components/ShowContextMenuContext'; import Text from '@components/Text'; import TextLink from '@components/TextLink'; import UnreadActionIndicator from '@components/UnreadActionIndicator'; +import useActivePolicy from '@hooks/useActivePolicy'; import useConfirmModal from '@hooks/useConfirmModal'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; @@ -358,6 +359,7 @@ type PureReportActionItemProps = { actionName: IOUAction, reportActionID: string, introSelected: OnyxEntry, + activePolicy: OnyxEntry, isRestrictedToPreferredPolicy?: boolean, preferredPolicyID?: string, ) => void; @@ -517,6 +519,7 @@ function PureReportActionItem({ const [isEmojiPickerActive, setIsEmojiPickerActive] = useState(); const [isPaymentMethodPopoverActive, setIsPaymentMethodPopoverActive] = useState(); const {isRestrictedToPreferredPolicy, preferredPolicyID} = usePreferredPolicy(); + const activePolicy = useActivePolicy(); const shouldRenderViewBasedOnAction = useTableReportViewActionRenderConditionals(action); const [isHidden, setIsHidden] = useState(false); const [moderationDecision, setModerationDecision] = useState(CONST.MODERATION.MODERATOR_DECISION_APPROVED); @@ -877,6 +880,7 @@ function PureReportActionItem({ CONST.IOU.ACTION.SUBMIT, action.reportActionID, introSelected, + activePolicy, isRestrictedToPreferredPolicy, preferredPolicyID, ); @@ -890,14 +894,28 @@ function PureReportActionItem({ text: 'actionableMentionTrackExpense.categorize', key: `${action.reportActionID}-actionableMentionTrackExpense-categorize`, onPress: () => { - createDraftTransactionAndNavigateToParticipantSelector(transactionID, reportActionReportID, CONST.IOU.ACTION.CATEGORIZE, action.reportActionID, introSelected); + createDraftTransactionAndNavigateToParticipantSelector( + transactionID, + reportActionReportID, + CONST.IOU.ACTION.CATEGORIZE, + action.reportActionID, + introSelected, + activePolicy, + ); }, }, { text: 'actionableMentionTrackExpense.share', key: `${action.reportActionID}-actionableMentionTrackExpense-share`, onPress: () => { - createDraftTransactionAndNavigateToParticipantSelector(transactionID, reportActionReportID, CONST.IOU.ACTION.SHARE, action.reportActionID, introSelected); + createDraftTransactionAndNavigateToParticipantSelector( + transactionID, + reportActionReportID, + CONST.IOU.ACTION.SHARE, + action.reportActionID, + introSelected, + activePolicy, + ); }, }, ); @@ -1037,6 +1055,7 @@ function PureReportActionItem({ isOriginalReportArchived, resolveActionableMentionWhisper, introSelected, + activePolicy, report, originalReport, ]); diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 1d829ca82b25..3a10f3adeaff 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -578,6 +578,7 @@ describe('actions/IOU', () => { CONST.IOU.ACTION.CATEGORIZE, reportActionableTrackExpense?.reportActionID, {choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM}, + undefined, ); await waitForBatchedUpdates(); diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 7f478374558e..92b06534c34f 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -18,6 +18,7 @@ import {compute} from '@libs/Formula'; import type {FormulaContext} from '@libs/Formula'; import getBase62ReportID from '@libs/getBase62ReportID'; import {translate} from '@libs/Localize'; +import Log from '@libs/Log'; import getReportURLForCurrentContext from '@libs/Navigation/helpers/getReportURLForCurrentContext'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import Navigation from '@libs/Navigation/Navigation'; @@ -52,6 +53,7 @@ import { canRejectReportAction, canSeeDefaultRoom, canUserPerformWriteAction, + createDraftTransactionAndNavigateToParticipantSelector, excludeParticipantsForDisplay, findLastAccessedReport, getAllReportActionsErrorsAndReportActionThatRequiresAttention, @@ -180,6 +182,18 @@ jest.mock('@libs/Permissions'); jest.mock('@libs/Navigation/helpers/isSearchTopmostFullScreenRoute', () => jest.fn()); +jest.mock('@libs/Log', () => ({ + __esModule: true, + default: { + warn: jest.fn(), + info: jest.fn(), + alert: jest.fn(), + hmmm: jest.fn(), + clientLoggingCallback: jest.fn(), + serverLoggingCallback: jest.fn(), + }, +})); + jest.mock('@libs/Navigation/Navigation', () => ({ setNavigationActionToMicrotaskQueue: jest.fn(), navigate: jest.fn(), @@ -11046,4 +11060,183 @@ describe('ReportUtils', () => { expect(reportAction).not.toEqual(dewSubmitFailedAction); }); }); + + describe('createDraftTransactionAndNavigateToParticipantSelector', () => { + describe('when action is CATEGORIZE', () => { + beforeEach(async () => { + jest.clearAllMocks(); + await Onyx.clear(); + await Onyx.set(ONYXKEYS.SESSION, {email: currentUserEmail, accountID: currentUserAccountID}); + }); + + it("should navigate to the restricted action page if the active policy's billable actions are restricted", async () => { + // Given a transaction and an active policy where billable actions are restricted + const transaction = createRandomTransaction(1); + const activePolicy: Policy = { + ...createRandomPolicy(100), + ownerAccountID: currentUserAccountID, + }; + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${1}`, {}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${activePolicy.id}`, activePolicy); + await Onyx.merge(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED, 1); + // Grace period end is in the past (Unix timestamp in seconds) + await Onyx.merge(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END, Math.floor(Date.now() / 1000) - 3600); + + // When we call createDraftTransactionAndNavigateToParticipantSelector with the restricted policy + createDraftTransactionAndNavigateToParticipantSelector(transaction.transactionID, '1', CONST.IOU.ACTION.CATEGORIZE, '1', undefined, activePolicy); + + // Then it should navigate to the restricted action page + expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.RESTRICTED_ACTION.getRoute(activePolicy.id)); + }); + + it('should navigate to the category step if the active policy is valid and not restricted', async () => { + // Given a transaction and a valid, non-restricted active policy + const transaction = createRandomTransaction(2); + const activePolicy: Policy = { + ...createRandomPolicy(101), + ownerAccountID: currentUserAccountID, + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + pendingAction: null, + }; + const policyExpenseReport = { + ...createPolicyExpenseChat(1), + policyID: activePolicy.id, + ownerAccountID: currentUserAccountID, + }; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${1}`, {}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${activePolicy.id}`, activePolicy); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseReport.reportID}`, policyExpenseReport); + + // When we call createDraftTransactionAndNavigateToParticipantSelector + createDraftTransactionAndNavigateToParticipantSelector(transaction.transactionID, '1', CONST.IOU.ACTION.CATEGORIZE, '1', undefined, activePolicy); + + // Then it should navigate to the category step + expect(Navigation.navigate).toHaveBeenCalledWith( + ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(CONST.IOU.ACTION.CATEGORIZE, CONST.IOU.TYPE.SUBMIT, transaction.transactionID, policyExpenseReport.reportID), + ); + }); + + it('should navigate to the category step via filteredPolicies when activePolicy is null', async () => { + // Given a transaction and no active policy, but one valid policy is available in Onyx + const transaction = createRandomTransaction(3); + const ownPolicy = { + ...createRandomPolicy(102), + ownerAccountID: currentUserAccountID, + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + pendingAction: null, + }; + const policyExpenseReport = { + ...createPolicyExpenseChat(2), + policyID: ownPolicy.id, + ownerAccountID: currentUserAccountID, + }; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${2}`, {}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${ownPolicy.id}`, ownPolicy); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseReport.reportID}`, policyExpenseReport); + + // When we call createDraftTransactionAndNavigateToParticipantSelector with undefined activePolicy + createDraftTransactionAndNavigateToParticipantSelector(transaction.transactionID, '2', CONST.IOU.ACTION.CATEGORIZE, '2', undefined, undefined); + + // Then it should automatically pick the available policy and navigate to the category step + expect(Navigation.navigate).toHaveBeenCalledWith( + ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(CONST.IOU.ACTION.CATEGORIZE, CONST.IOU.TYPE.SUBMIT, transaction.transactionID, policyExpenseReport.reportID), + ); + }); + + it('should navigate to the upgrade page when activePolicy is null and no policies are found', async () => { + // Given a transaction and no policies in Onyx + const transaction = createRandomTransaction(0); + + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${1}`, {}); + await Onyx.setCollection(ONYXKEYS.COLLECTION.POLICY, {}); + + // When we call createDraftTransactionAndNavigateToParticipantSelector with undefined activePolicy + createDraftTransactionAndNavigateToParticipantSelector(transaction.transactionID, '1', CONST.IOU.ACTION.CATEGORIZE, '1', undefined, undefined); + + // Then it should navigate to the upgrade page because no policies were found to categorize with + expect(Navigation.navigate).toHaveBeenCalledWith( + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.CATEGORIZE, + iouType: CONST.IOU.TYPE.SUBMIT, + transactionID: transaction.transactionID, + reportID: '1', + backTo: '', + upgradePath: CONST.UPGRADE_PATHS.CATEGORIES, + shouldSubmitExpense: true, + }), + ); + }); + + it('should navigate to the upgrade page when activePolicy is null and multiple policies are found', async () => { + // Given a transaction and multiple policies in Onyx + const transaction = createRandomTransaction(0); + const policy1 = { + ...createRandomPolicy(103), + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + pendingAction: null, + }; + const policy2 = { + ...createRandomPolicy(104), + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + pendingAction: null, + }; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${1}`, {}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy1.id}`, policy1); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy2.id}`, policy2); + + // When we call createDraftTransactionAndNavigateToParticipantSelector with undefined activePolicy + createDraftTransactionAndNavigateToParticipantSelector(transaction.transactionID, '1', CONST.IOU.ACTION.CATEGORIZE, '1', undefined, undefined); + + // Then it should navigate to the upgrade page because it's ambiguous which policy to use + expect(Navigation.navigate).toHaveBeenCalledWith( + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.CATEGORIZE, + iouType: CONST.IOU.TYPE.SUBMIT, + transactionID: transaction.transactionID, + reportID: '1', + backTo: '', + upgradePath: CONST.UPGRADE_PATHS.CATEGORIES, + shouldSubmitExpense: true, + }), + ); + }); + + it('should log a warning when policyExpenseReportID is missing during categorization', async () => { + // Given a transaction and an active policy, but no corresponding policy expense report in Onyx + const logWarnSpy = jest.spyOn(Log, 'warn'); + const transaction = createRandomTransaction(4); + const activePolicy: Policy = { + ...createRandomPolicy(105), + ownerAccountID: currentUserAccountID, + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + pendingAction: null, + }; + + // We don't merge any policy expense report for this policy + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${1}`, {}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${activePolicy.id}`, activePolicy); + + // When we call createDraftTransactionAndNavigateToParticipantSelector + createDraftTransactionAndNavigateToParticipantSelector(transaction.transactionID, '1', CONST.IOU.ACTION.CATEGORIZE, '1', undefined, activePolicy); + + // Then it should log a warning and not navigate + expect(logWarnSpy).toHaveBeenCalledWith('policyExpenseReportID is not valid during expense categorizing'); + expect(Navigation.navigate).not.toHaveBeenCalled(); + }); + }); + }); });