diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 36eaa08da9c6..67c9ccf1bf43 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -4,9 +4,11 @@ import {SELECTION_LIST_POPOVER_HEADER_HEIGHT} from '@components/SelectionListPop import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useOutstandingReports from '@hooks/useOutstandingReports'; +import usePermissions from '@hooks/usePermissions'; import {usePersonalDetail} from '@hooks/usePersonalDetails'; import {useDerivedReportNameByReportID} from '@hooks/useReportAttributes'; +import {isMovingTransactionFromTrackExpense} from '@libs/IOUUtils'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import Parser from '@libs/Parser'; @@ -14,10 +16,13 @@ import {getReportName} from '@libs/ReportNameUtils'; import { canAddTransaction, generateReportID, - getNewestOutstandingReportForUser, + getDefaultMoneyRequestReport, + getMoneyRequestReportCandidate, getOutstandingReportsForUser, isMoneyRequestReport, + isOpenExpenseReport, isReportOutstanding, + isSavedThroughMoneyRequestBuilder, sortOutstandingReportsBySelected, } from '@libs/ReportUtils'; @@ -56,6 +61,7 @@ type ReportFieldProps = { function ReportField({selectedParticipants, iouType, reportID, reportActionID, action, transactionID, isPerDiemRequest, isPolicyExpenseChat}: ReportFieldProps) { const {shouldUseDropdownRows} = useExpenseFormLayout(); const {translate, localeCompare} = useLocalize(); + const {isBetaEnabled} = usePermissions(); const ownerAccountID = selectedParticipants?.at(0)?.ownerAccountID; const [ownerPersonalDetail] = usePersonalDetail(ownerAccountID); @@ -69,6 +75,7 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a const transactionReportID = transactionState?.reportID; const participantReportID = transactionState?.participantReportID; const isFromGlobalCreate = transactionState?.isFromGlobalCreate ?? false; + const isScanRequest = transactionState?.isScanRequest ?? false; // Per-key report subscriptions instead of full COLLECTION.REPORT const [transactionReportEntry] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${transactionReportID}`); @@ -78,6 +85,7 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a const isUnreported = transactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID; const isCreatingExpense = action === CONST.IOU.ACTION.CREATE; + const isMovingTrackedExpense = isMovingTransactionFromTrackExpense(action); /** * We need to check if the transaction report exists first in order to prevent the outstanding reports from being used. @@ -90,14 +98,15 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a (report1, report2) => sortOutstandingReportsBySelected(report1, report2, undefined, localeCompare), ); - // Match the builder's automatic destination before checking eligibility, rather than falling back to a report it would not use. - const defaultOutstandingReport = isCreatingExpense - ? getNewestOutstandingReportForUser(policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {}) - : availableOutstandingReports.at(0); - const outstandingReportID = isPolicyExpenseChat ? (iouReportIDFromMain ?? defaultOutstandingReport?.reportID) : reportID; + // Match the save path's automatic destination before checking eligibility, rather than falling back to a report it would not use. + const candidateReport = getMoneyRequestReportCandidate(iouReport, action, policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy); + const defaultReport = candidateReport ?? (isSavedThroughMoneyRequestBuilder(action) ? undefined : availableOutstandingReports.at(0)); + const defaultReportID = getDefaultMoneyRequestReport(defaultReport, mainReport, isScanRequest, isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), rules, action)?.reportID; + + const outstandingReportID = isPolicyExpenseChat ? defaultReportID : reportID; + const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID; const [selectedReportID, selectedReport] = (() => { - const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID; if (!reportIDToUse) { // Even if we have no report to use we still need a report id for proper navigation return [generateReportID(), undefined] as const; @@ -110,6 +119,8 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a reportToUse = mainReport; } else if (reportIDToUse === iouReportIDFromMain) { reportToUse = iouReport; + } else if (reportIDToUse === defaultReport?.reportID) { + reportToUse = defaultReport; } else { reportToUse = availableOutstandingReports.find((r) => r?.reportID === reportIDToUse); } @@ -129,11 +140,14 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a return name; })(); - const outstandingReports = useOutstandingReports(undefined, isFromGlobalCreate && !isPerDiemRequest ? undefined : policyID, ownerAccountID, false, ownerPersonalDetail?.login); + const allOutstandingReports = useOutstandingReports(undefined, isFromGlobalCreate && !isPerDiemRequest ? undefined : policyID, ownerAccountID, false, ownerPersonalDetail?.login); + // A tracked expense moved to a workspace can only join an open report, so the picker lists only those. Count the same reports here. + const outstandingReports = isMovingTrackedExpense ? allOutstandingReports.filter(isOpenExpenseReport) : allOutstandingReports; const eligibleOutstandingReports = isCreatingExpense ? outstandingReports.filter((report) => canAddTransaction(report, rules)) : outstandingReports; // When creating an expense in an individual report, the report field becomes read-only // since the destination is already determined and there's no need to show a selectable list. - const shouldReportBeEditable = shouldReportFieldBeEditable(eligibleOutstandingReports, selectedReportID, isUnreported) && !isMoneyRequestReport(reportID); + // Use the default rather than the picked report, so picking the only outstanding report keeps the field editable to switch back. + const shouldReportBeEditable = shouldReportFieldBeEditable(eligibleOutstandingReports, selectedReportID, isUnreported || !outstandingReportID) && !isMoneyRequestReport(reportID); // Editing a saved expense's report and moving a per diem expense both navigate on from the list (to the report, or to // the destination step when the workspace changes), so those keep the full page. const shouldOpenInDropdown = !!transactionID && shouldReportBeEditable && action !== CONST.IOU.ACTION.EDIT && !isPerDiemRequest; diff --git a/src/components/MoneyRequestConfirmationList/sections/selectors.ts b/src/components/MoneyRequestConfirmationList/sections/selectors.ts index e8233b470a58..049b0e471c06 100644 --- a/src/components/MoneyRequestConfirmationList/sections/selectors.ts +++ b/src/components/MoneyRequestConfirmationList/sections/selectors.ts @@ -10,6 +10,7 @@ import { isCreatedMissing, isFailedScanAmountPlaceholder, isMerchantMissing, + isScanRequest, isScanning, willFieldBeAutomaticallyFilled, } from '@libs/TransactionUtils'; @@ -355,6 +356,7 @@ type ReportFieldTransactionState = { reportID: Transaction['reportID']; isFromGlobalCreate: boolean; participantReportID: string | undefined; + isScanRequest: boolean; }; const reportFieldTransactionStateSelector = (t: OnyxEntry): ReportFieldTransactionState | undefined => { @@ -365,6 +367,7 @@ const reportFieldTransactionStateSelector = (t: OnyxEntry): ReportF reportID: t.reportID, isFromGlobalCreate: !!t.isFromGlobalCreate, participantReportID: t.participants?.at(0)?.reportID, + isScanRequest: isScanRequest(t), }; }; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index e4366b06de44..806e09fa9e60 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -13674,6 +13674,62 @@ function getNewestOutstandingReportForUser( return openReports.reduce>((newest, report) => ((report?.created ?? '') > (newest?.created ?? '') ? (report ?? null) : newest), openReports.at(0) ?? null); } +/** + * Whether saving the expense for this action goes through the money request builder and its report checks: new expenses and tracked + * expenses moved to a workspace. Other actions, like editing, move the expense to a report without them. + */ +function isSavedThroughMoneyRequestBuilder(action: IOUAction): boolean { + return action === CONST.IOU.ACTION.CREATE || action === CONST.IOU.ACTION.SUBMIT || action === CONST.IOU.ACTION.CATEGORIZE || action === CONST.IOU.ACTION.SHARE; +} + +/** + * Returns the report the expense would join before the save path's checks run. The Report field and the report picker both start from + * it, so they show and mark the same report. For actions saved through the money request builder it matches the builder: the report the + * workspace chat points at, or the member's newest open report when the chat's iouReportID was cleared, e.g. after a submit. + * + * @param chatIOUReport - The report the workspace chat's iouReportID points at + * @param policyID - The workspace the expense is created in + * @param reportOwnerAccountID - The member the expense is created for + * @param outstandingReportsForPolicy - The policy's outstanding reports, from the OUTSTANDING_REPORTS_BY_POLICY_ID derived value + */ +function getMoneyRequestReportCandidate( + chatIOUReport: OnyxInputOrEntry, + action: IOUAction, + policyID: string | undefined, + reportOwnerAccountID: number | undefined, + rules: OnyxCollection, + reportNameValuePairs: OnyxCollection, + outstandingReportsForPolicy: OnyxCollection, +): OnyxInputOrEntry { + if (chatIOUReport || !isSavedThroughMoneyRequestBuilder(action)) { + return chatIOUReport; + } + return getNewestOutstandingReportForUser(policyID, reportOwnerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {}); +} + +/** + * Returns the report a new expense is added to when the user doesn't pick one, or undefined when saving it starts a new report. + * The Report field and the report picker both read it, so the picker marks the same report the field shows, and picking any + * other report, including the candidate when saving would skip it, writes the choice to the expense. + * + * @param candidateReport - The report the expense would join, from getMoneyRequestReportCandidate + * @param chatReport - The workspace chat the expense is created in + */ +function getDefaultMoneyRequestReport( + candidateReport: OnyxInputOrEntry, + chatReport: OnyxInputOrEntry, + isScanRequest: boolean, + isASAPSubmitBetaEnabled: boolean, + rules: OnyxCollection, + action: IOUAction, +): OnyxInputOrEntry { + // Actions that skip the save path's checks keep the report they were given. + if (!isSavedThroughMoneyRequestBuilder(action)) { + return candidateReport; + } + return shouldCreateNewMoneyRequestReport(candidateReport, chatReport, isScanRequest, isASAPSubmitBetaEnabled, rules, action) ? undefined : candidateReport; +} + /** * Whether the member is the approver of any of the policy's reports that are waiting for their approval. * An approver assigned through "Change approver" is only stored in the report's `managerID`, so they are not covered by `isPolicyApprover`. @@ -16368,6 +16424,9 @@ export { buildOptimisticMovedTransactionAction, getOutstandingReportsForUser, getNewestOutstandingReportForUser, + getDefaultMoneyRequestReport, + getMoneyRequestReportCandidate, + isSavedThroughMoneyRequestBuilder, isApproverOfOutstandingPolicyReports, isReportOutstanding, isReportTotalPending, diff --git a/src/pages/iou/request/step/IOURequestEditReportCommon.tsx b/src/pages/iou/request/step/IOURequestEditReportCommon.tsx index 3be3886c398c..bf7b19ba68b9 100644 --- a/src/pages/iou/request/step/IOURequestEditReportCommon.tsx +++ b/src/pages/iou/request/step/IOURequestEditReportCommon.tsx @@ -23,7 +23,7 @@ import {fetchOutstandingReports} from '@libs/actions/OutstandingReports'; import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus'; import Navigation from '@libs/Navigation/Navigation'; import {canSubmitPerDiemExpenseFromWorkspace, isPerDiemEnabled, isPolicyAdmin, isTimeTrackingEnabled} from '@libs/PolicyUtils'; -import {canAddTransaction, getIconsForExpenseReport, isIOUReport, isOpenReport, isReportOwner, isSelfDM, sortOutstandingReportsBySelected} from '@libs/ReportUtils'; +import {canAddTransaction, getIconsForExpenseReport, isIOUReport, isOpenExpenseReport, isOpenReport, isReportOwner, isSelfDM, sortOutstandingReportsBySelected} from '@libs/ReportUtils'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import {isPerDiemRequest as isPerDiemRequestUtil} from '@libs/TransactionUtils'; @@ -81,6 +81,8 @@ type IOURequestEditReportCommonProps = { isPerDiemRequest: boolean; isTimeRequest?: boolean; isUnreportedManagedCardTransaction?: boolean; + /** Whether only open reports can take the expense, e.g. a tracked expense moved to a workspace, which the server only adds to an open report */ + shouldOnlyListOpenReports?: boolean; /** Whether the expenses being moved belong to more than one submitter */ hasMultipleSubmitters?: boolean; /** Whether every expense being moved sits on a card this user can resolve, which "Auto report" requires */ @@ -129,6 +131,7 @@ function IOURequestEditReportCommon({ isPerDiemRequest, isTimeRequest = false, isUnreportedManagedCardTransaction = false, + shouldOnlyListOpenReports = false, hasMultipleSubmitters = false, areAllManagedCardsResolvable = false, autoReport, @@ -233,6 +236,9 @@ function IOURequestEditReportCommon({ .sort((report1, report2) => sortOutstandingReportsBySelected(report1, report2, selectedReportID, localeCompare)) .filter((report): report is NonNullable => report !== undefined) .filter((report) => { + if (shouldOnlyListOpenReports && !isOpenExpenseReport(report)) { + return false; + } const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`]; if (isTimeRequest && !isTimeTrackingEnabled(policy)) { return false; diff --git a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts index 0c1565b295e9..8b3da2323e43 100644 --- a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts +++ b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts @@ -13,14 +13,23 @@ import useReportOrReportDraft from '@hooks/useReportOrReportDraft'; import {createNewReport} from '@libs/actions/Report'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; +import {isMovingTransactionFromTrackExpense} from '@libs/IOUUtils'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import {getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils'; -import {getPersonalDetailsForAccountID, getReportOrDraftReport, isPolicyExpenseChat, isReportOutstanding} from '@libs/ReportUtils'; +import { + getDefaultMoneyRequestReport, + getMoneyRequestReportCandidate, + getPersonalDetailsForAccountID, + getReportOrDraftReport, + isPolicyExpenseChat, + isReportOutstanding, +} from '@libs/ReportUtils'; import { isDistanceRequest as isDistanceRequestUtil, isManualDistanceRequest as isManualDistanceRequestUtil, isOdometerDistanceRequest as isOdometerDistanceRequestUtil, isPerDiemRequest, + isScanRequest, isTimeRequest as isTimeRequestUtil, isUnreportedManagedCardTransaction as isUnreportedManagedCardTransactionUtil, } from '@libs/TransactionUtils'; @@ -38,6 +47,7 @@ import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails'; import type {OnyxEntry} from 'react-native-onyx'; import {isTrackIntentUserSelector} from '@selectors/Onboarding'; +import {createOutstandingReportsForPolicySelector} from '@selectors/Report'; import useCreateReportRestrictionCheck from './useCreateReportRestrictionCheck'; import usePerDiemPolicyData from './usePerDiemPolicyData'; @@ -90,6 +100,7 @@ type ReportPickerListProps = Pick< | 'isPerDiemRequest' | 'isTimeRequest' | 'isUnreportedManagedCardTransaction' + | 'shouldOnlyListOpenReports' | 'createReport' | 'targetOwnerAccountID' >; @@ -106,6 +117,12 @@ const getIOUActionsSelector = (actions: OnyxEntry): Array getOriginalMessage(iouAction)?.IOUTransactionID === transaction.transactionID)?.actorAccountID : selectedReport?.ownerAccountID; - const ownerPersonalDetails: CurrentUserPersonalDetails = {...getPersonalDetailsForAccountID(ownerAccountID, personalDetails), accountID: ownerAccountID ?? CONST.DEFAULT_NUMBER_ID}; + // A new report needs an owner even when the expense has no report to read one from yet, e.g. after the chat's report was submitted + // and its iouReportID cleared. Fall back to the workspace chat's owner, then the current user, so the report is linked to the chat. + // ownerAccountID itself stays unchanged, because targetExpensePolicyID relies on it. + const newReportOwnerAccountID = ownerAccountID ?? (isPolicyExpenseChat(participantReport) ? participantReport?.ownerAccountID : undefined) ?? session?.accountID; + const ownerPersonalDetails: CurrentUserPersonalDetails = { + ...getPersonalDetailsForAccountID(newReportOwnerAccountID, personalDetails), + accountID: newReportOwnerAccountID ?? CONST.DEFAULT_NUMBER_ID, + }; const isPerDiemTransaction = isPerDiemRequest(transaction); const isUnreportedManagedCardTransaction = isUnreportedManagedCardTransactionUtil(transaction); @@ -271,7 +311,9 @@ function useReportPickerActions({ if (isPerDiemTransaction) { selectedPolicyID = isFromGlobalCreate ? undefined : perDiemOriginalPolicy?.id; } else { - selectedPolicyID = !isEditing && !isFromGlobalCreate ? reportOrDraftReport?.policyID : undefined; + // The route can hold a generated ID for a report that doesn't exist yet (the field shows "New report"), so fall back to the + // workspace chat the expense is created in. Otherwise the list would offer reports from every workspace. + selectedPolicyID = !isEditing && !isFromGlobalCreate ? (reportOrDraftReport?.policyID ?? transactionPolicyID) : undefined; } return { @@ -292,8 +334,9 @@ function useReportPickerActions({ isPerDiemRequest: transaction ? isPerDiemTransaction : false, isTimeRequest: transaction ? isTimeRequestUtil(transaction) : false, isUnreportedManagedCardTransaction: transaction ? isUnreportedManagedCardTransaction : false, + shouldOnlyListOpenReports: isMovingTransactionFromTrackExpense(action), createReport: policyForMovingExpensesID || shouldSelectPolicy || isPerDiemTransaction || isUnreportedManagedCardTransaction ? createReport : undefined, - targetOwnerAccountID: ownerAccountID, + targetOwnerAccountID: newReportOwnerAccountID, }, }; } diff --git a/tests/ui/MoneyRequestReportFooter.tsx b/tests/ui/MoneyRequestReportFooter.tsx index d790a08e4f49..74e67e61cddf 100644 --- a/tests/ui/MoneyRequestReportFooter.tsx +++ b/tests/ui/MoneyRequestReportFooter.tsx @@ -207,7 +207,8 @@ describe('MoneyRequestConfirmationListFooter', () => { expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: false})); }); - it('should disable report field when there is only 1 outstanding report and creating from policy chat', async () => { + it('should disable report field when the only eligible report is already selected and creating from policy chat', async () => { + // Given the submitter's only eligible report is already selected, so there is no alternative destination const mockTransactionReport: Transaction = { ...mockTransaction, isFromGlobalCreate: false, @@ -230,10 +231,12 @@ describe('MoneyRequestConfirmationListFooter', () => { }); initOnyxDerivedValues(); + // When the confirmation footer renders the report field await renderMoneyRequestConfirmationListFooter(mockTransactionReport); await waitForBatchedUpdatesWithAct(); + // Then the field is read-only because the selected report is the only eligible destination const reportItem = screen.getByTestId('menu-item-Report'); expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: true})); }); @@ -260,7 +263,8 @@ describe('MoneyRequestConfirmationListFooter', () => { expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: true})); }); - it('should disable report field when transaction has reportID and creating from FAB with only 1 outstanding report', async () => { + it('should disable report field when the only eligible report is already selected and creating from FAB', async () => { + // Given the submitter's only eligible report is already selected, so there is no alternative destination const mockTransactionReport: Transaction = { ...mockTransaction, isFromGlobalCreate: true, @@ -283,10 +287,12 @@ describe('MoneyRequestConfirmationListFooter', () => { }); initOnyxDerivedValues(); + // When the confirmation footer renders the report field await renderMoneyRequestConfirmationListFooter(mockTransactionReport); await waitForBatchedUpdatesWithAct(); + // Then the field is read-only because the selected report is the only eligible destination const reportItem = screen.getByTestId('menu-item-Report'); expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: true})); }); diff --git a/tests/ui/components/IOURequestStepReportNewReportTest.tsx b/tests/ui/components/IOURequestStepReportNewReportTest.tsx new file mode 100644 index 000000000000..333aea41fd1d --- /dev/null +++ b/tests/ui/components/IOURequestStepReportNewReportTest.tsx @@ -0,0 +1,240 @@ +import {render, screen} from '@testing-library/react-native'; + +import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; +import HTMLEngineProvider from '@components/HTMLEngineProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; + +import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; +import {fetchOutstandingReports} from '@libs/actions/OutstandingReports'; + +import DynamicIOURequestStepReportWithWritableReportOrNotFound from '@pages/iou/request/step/DynamicIOURequestStepReport'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import createRandomPolicy from '../../utils/collections/policies'; +import {createPolicyExpenseChat, createRandomReport} from '../../utils/collections/reports'; +import {signInWithTestUser} from '../../utils/TestHelper'; +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + +jest.mock('@components/ProductTrainingContext', () => ({ + useProductTrainingContext: () => [false], +})); +jest.mock('@src/hooks/useResponsiveLayout'); + +jest.mock('@libs/Navigation/navigationRef', () => ({ + getCurrentRoute: jest.fn(() => ({ + name: 'Dynamic_Money_Request_Report', + params: {}, + })), + getState: jest.fn(() => ({})), + isReady: jest.fn(() => false), + addListener: jest.fn(() => jest.fn()), +})); + +jest.mock('@libs/Navigation/Navigation', () => { + const mockRef = { + getCurrentRoute: jest.fn(() => ({ + name: 'Dynamic_Money_Request_Report', + params: {}, + })), + getState: jest.fn(() => ({})), + }; + return { + navigate: jest.fn(), + goBack: jest.fn(), + navigationRef: mockRef, + getActiveRoute: () => '', + getActiveRouteWithoutParams: jest.fn(() => ''), + isNavigationReady: jest.fn(() => Promise.resolve()), + }; +}); + +jest.mock('@react-navigation/native', () => { + const mockRef = { + getCurrentRoute: jest.fn(() => ({ + name: 'Dynamic_Money_Request_Report', + params: {}, + })), + getState: jest.fn(() => ({})), + }; + return { + ...jest.requireActual>('@react-navigation/native'), + createNavigationContainerRef: jest.fn(() => mockRef), + useIsFocused: () => true, + useNavigation: () => ({navigate: jest.fn(), addListener: jest.fn()}), + useFocusEffect: jest.fn(), + usePreventRemove: jest.fn(), + }; +}); + +jest.mock('@libs/actions/Transaction', () => { + return { + setTransactionReport: jest.fn(), + }; +}); + +jest.mock('@libs/actions/OutstandingReports', () => ({ + fetchOutstandingReports: jest.fn(), +})); + +const ACCOUNT_ID = 1; +const ACCOUNT_LOGIN = 'test@user.com'; +const REPORT_ID_1 = '1'; +const REPORT_ID_2 = '2'; +const MEMBER_OPEN_REPORT_ID = '3'; +const TRANSACTION_ID = '1'; +const POLICY_ID_1 = '1'; +const POLICY_ID_2 = '2'; + +function HTMLProviderWrapper({children}: {children: React.ReactNode}) { + return {children}; +} + +const GENERATED_REPORT_ID = 'generated-report-not-in-onyx'; +const WORKSPACE_CHAT_ID = '20'; +const APPROVER_ACCOUNT_ID = 3; +const APPROVER_LOGIN = 'approver@user.com'; + +/** Opens the report list from the confirmation page's Report field while it shows "New report", which passes a generated report ID */ +async function renderReportPickerForNewReport() { + render( + + + + + + + + + , + ); + await waitForBatchedUpdates(); +} + +function buildExpenseReport(reportID: string, policyID: string, chatReportID: string) { + return { + ...createRandomReport(Number(reportID), undefined), + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + type: CONST.REPORT.TYPE.EXPENSE, + policyID, + chatReportID, + ownerAccountID: ACCOUNT_ID, + managerID: ACCOUNT_ID, + }; +} + +/** An expense being created in the workspace chat of POLICY_ID_2, whose report was just submitted, which clears the chat's iouReportID */ +async function givenExpenseInWorkspaceChatWithSubmittedReport() { + await signInWithTestUser(ACCOUNT_ID, ACCOUNT_LOGIN); + await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[APPROVER_ACCOUNT_ID]: {accountID: APPROVER_ACCOUNT_ID, login: APPROVER_LOGIN}}); + const buildPolicy = (policyID: string) => ({ + ...createRandomPolicy(Number(policyID)), + id: policyID, + role: CONST.POLICY.ROLE.USER, + type: CONST.POLICY.TYPE.TEAM, + approver: APPROVER_LOGIN, + owner: APPROVER_LOGIN, + approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC, + pendingAction: null, + // A fixed membership, because the random policy may leave the user out, which hides the workspace from the list + employeeList: { + [ACCOUNT_LOGIN]: {email: ACCOUNT_LOGIN, role: CONST.POLICY.ROLE.USER, submitsTo: APPROVER_LOGIN}, + [APPROVER_LOGIN]: {email: APPROVER_LOGIN, role: CONST.POLICY.ROLE.ADMIN}, + }, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID_1}`, buildPolicy(POLICY_ID_1)); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID_2}`, buildPolicy(POLICY_ID_2)); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, { + ...createPolicyExpenseChat(Number(WORKSPACE_CHAT_ID), true), + reportID: WORKSPACE_CHAT_ID, + policyID: POLICY_ID_2, + ownerAccountID: ACCOUNT_ID, + iouReportID: undefined, + }); + // The report awaiting approval, which a submitter can still add expenses to when they pick it + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID_2}`, { + ...buildExpenseReport(REPORT_ID_2, POLICY_ID_2, WORKSPACE_CHAT_ID), + managerID: APPROVER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${TRANSACTION_ID}`, { + amount: 0, + currency: 'USD', + created: '2025-08-29', + merchant: '(none)', + transactionID: TRANSACTION_ID, + isFromGlobalCreate: false, + participants: [{accountID: 0, reportID: WORKSPACE_CHAT_ID, policyID: POLICY_ID_2, isPolicyExpenseChat: true, selected: true}], + }); + await waitForBatchedUpdates(); +} + +describe('IOURequestStepReport with a generated New report ID', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + initOnyxDerivedValues(); + return waitForBatchedUpdates(); + }); + + beforeEach(() => Onyx.clear().then(waitForBatchedUpdates)); + + it('should only list reports of the workspace the expense is created in when the Report field shows New report', async () => { + // Given an expense in workspace B's chat, and an open report of the same user in workspace A + await givenExpenseInWorkspaceChatWithSubmittedReport(); + const otherWorkspaceChatID = '21'; + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID_1}`, buildExpenseReport(REPORT_ID_1, POLICY_ID_1, otherWorkspaceChatID)); + await waitForBatchedUpdates(); + + // When the list opens with the generated report ID of "New report", which doesn't exist in Onyx + await renderReportPickerForNewReport(); + + // Then only workspace B's report is listed, because the expense is created in workspace B's chat + expect(await screen.findByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}${REPORT_ID_2}`)).toBeTruthy(); + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}${REPORT_ID_1}`)).toBeNull(); + }); + + it('should fetch member reports without offering creation-ineligible reports to an admin in the member workspace chat', async () => { + // Given an admin creating an expense for a member whose chat no longer points to a report + await givenExpenseInWorkspaceChatWithSubmittedReport(); + await Onyx.merge(ONYXKEYS.SESSION, {accountID: APPROVER_ACCOUNT_ID, email: APPROVER_LOGIN}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID_2}`, {role: CONST.POLICY.ROLE.ADMIN}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, {isOwnPolicyExpenseChat: false}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${MEMBER_OPEN_REPORT_ID}`, buildExpenseReport(MEMBER_OPEN_REPORT_ID, POLICY_ID_2, WORKSPACE_CHAT_ID)); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID_1}`, { + ...buildExpenseReport(REPORT_ID_1, POLICY_ID_2, WORKSPACE_CHAT_ID), + ownerAccountID: APPROVER_ACCOUNT_ID, + managerID: APPROVER_ACCOUNT_ID, + }); + await waitForBatchedUpdates(); + jest.mocked(fetchOutstandingReports).mockClear(); + + // When the picker opens from New report without an existing report to supply the owner + await renderReportPickerForNewReport(); + + // Then fetching remains scoped to the member, while creation eligibility excludes reports the admin does not own. + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}${MEMBER_OPEN_REPORT_ID}`)).toBeNull(); + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}${REPORT_ID_1}`)).toBeNull(); + expect(fetchOutstandingReports).toHaveBeenCalledWith(ACCOUNT_ID, POLICY_ID_2, 0); + expect(fetchOutstandingReports).not.toHaveBeenCalledWith(APPROVER_ACCOUNT_ID, POLICY_ID_2, 0); + }); +}); diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 94476327ce64..af080f4fab25 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -109,6 +109,7 @@ import { getChatRoomSubtitle, getChildReportNotificationPreference, getDefaultGroupAvatar, + getDefaultMoneyRequestReport, getDefaultWorkspaceAvatar, getDeletedTransactionMessage, getDisplayedReportID, @@ -124,6 +125,7 @@ import { getIOUReportActionDisplayMessage, getLinkedIOUTransaction, getMissingPaymentMethodForQueuedPayment, + getMoneyRequestReportCandidate, getMoneyRequestSpendBreakdown, getMostRecentlyVisitedReport, getMovedActionMessage, @@ -21631,6 +21633,70 @@ describe('ReportUtils', () => { }); }); + describe('money request report defaults', () => { + const olderReport: Report = { + reportID: 'candidate-older', + policyID: 'candidate-policy', + ownerAccountID: currentUserAccountID, + type: CONST.REPORT.TYPE.EXPENSE, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + created: '2026-11-18 10:00:00', + }; + const newerReport: Report = {...olderReport, reportID: 'candidate-newer', created: '2026-11-19 10:00:00'}; + const reports = { + [`${ONYXKEYS.COLLECTION.REPORT}${olderReport.reportID}`]: olderReport, + [`${ONYXKEYS.COLLECTION.REPORT}${newerReport.reportID}`]: newerReport, + [`${ONYXKEYS.COLLECTION.REPORT}other-owner`]: {...newerReport, reportID: 'other-owner', ownerAccountID: currentUserAccountID + 1, created: '2026-11-20 10:00:00'}, + [`${ONYXKEYS.COLLECTION.REPORT}submitted`]: {...newerReport, reportID: 'submitted', stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED}, + }; + + it.each([CONST.IOU.ACTION.CREATE, CONST.IOU.ACTION.SUBMIT, CONST.IOU.ACTION.CATEGORIZE, CONST.IOU.ACTION.SHARE])( + 'uses the newest open report for %s when the chat link is cleared', + (action) => { + // Given a cleared chat link and reports from different owners and workflow states + // When the action uses the builder's automatic fallback + const candidate = getMoneyRequestReportCandidate(undefined, action, olderReport.policyID, currentUserAccountID, undefined, undefined, reports); + + // Then only the current member's newest open report is selected + expect(candidate).toBe(newerReport); + }, + ); + + it.each([CONST.IOU.ACTION.CREATE, CONST.IOU.ACTION.SUBMIT, CONST.IOU.ACTION.CATEGORIZE, CONST.IOU.ACTION.SHARE])('rejects a pending-delete default for %s', (action) => { + // Given a linked report that the builder cannot reuse + const candidate = {...olderReport, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}; + + // When resolving a default for an action saved through the builder + const defaultReport = getDefaultMoneyRequestReport(candidate, undefined, false, false, undefined, action); + + // Then confirmation and picker both fall back to creating a new report + expect(defaultReport).toBeUndefined(); + }); + + it('preserves a linked candidate rather than replacing it with the newest report', () => { + // Given a chat linked to an older report despite a newer report being available + // When resolving the automatic candidate + const candidate = getMoneyRequestReportCandidate(olderReport, CONST.IOU.ACTION.CREATE, olderReport.policyID, currentUserAccountID, undefined, undefined, reports); + + // Then the linked report takes precedence, matching the builder + expect(candidate).toBe(olderReport); + }); + + it('does not apply builder defaults or checks when editing an expense', () => { + // Given an editing action and an explicitly chosen report pending deletion + const candidate = {...olderReport, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}; + + // When resolving an absent chat candidate and the explicitly chosen default + const absentCandidate = getMoneyRequestReportCandidate(undefined, CONST.IOU.ACTION.EDIT, olderReport.policyID, currentUserAccountID, undefined, undefined, reports); + const defaultReport = getDefaultMoneyRequestReport(candidate, undefined, false, false, undefined, CONST.IOU.ACTION.EDIT); + + // Then editing neither automatically selects a fallback nor runs the builder's checks + expect(absentCandidate).toBeUndefined(); + expect(defaultReport).toBe(candidate); + }); + }); + describe('canDuplicateExpenseIntoSourceReport', () => { const sourcePolicy: Policy = { ...createRandomPolicy(30001), diff --git a/tests/unit/components/MoneyRequestConfirmationList/ReportField.test.tsx b/tests/unit/components/MoneyRequestConfirmationList/ReportField.test.tsx new file mode 100644 index 000000000000..449216165c7f --- /dev/null +++ b/tests/unit/components/MoneyRequestConfirmationList/ReportField.test.tsx @@ -0,0 +1,245 @@ +import {render, screen, waitFor} from '@testing-library/react-native'; + +import ConfirmationFieldsProvider from '@components/MoneyRequestConfirmationFields/Provider'; +import ReportField from '@components/MoneyRequestConfirmationList/sections/ReportField'; + +import initOnyxDerivedValues from '@userActions/OnyxDerived'; + +import CONST from '@src/CONST'; +import type {IOUAction} from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report} from '@src/types/onyx'; + +import type {ValueOf} from 'type-fest'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../../../utils/waitForBatchedUpdates'; + +jest.mock('@components/MenuItem/presets/MenuItemFieldHTML', () => { + const {Text} = jest.requireActual>>('react-native'); + // The row is only pressable when the report is editable, so a missing onPress reads as a disabled row. + return ({value, onPress}: {value?: string; onPress?: () => void}) => {value}; +}); + +jest.mock('@hooks/useLocalize', () => () => ({translate: (key: string) => key, localeCompare: (a: string, b: string) => a.localeCompare(b)})); +jest.mock('@hooks/useReportAttributes', () => ({ + ...jest.requireActual>('@hooks/useReportAttributes'), + useDerivedReportNameByReportID: () => undefined, +})); + +const mockIsBetaEnabled = jest.fn(() => false); +jest.mock('@hooks/usePermissions', () => () => ({isBetaEnabled: (beta: string) => mockIsBetaEnabled(beta)})); + +const TRANSACTION_ID = '1'; +const POLICY_ID = 'policy-test-1'; +const CHAT_REPORT_ID = 'report-chat-1'; +const SUBMITTED_REPORT_ID = 'expense-report-awaiting-approval'; +const OPEN_REPORT_ID = 'expense-report-open'; +const SUBMITTER_ACCOUNT_ID = 100; +const SUBMITTER_EMAIL = 'submitter@example.com'; +const APPROVER_ACCOUNT_ID = 300; +const APPROVER_EMAIL = 'approver@example.com'; + +const chatReport: Report = { + reportID: CHAT_REPORT_ID, + chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, + policyID: POLICY_ID, + isOwnPolicyExpenseChat: true, + type: CONST.REPORT.TYPE.CHAT, +}; + +function buildExpenseReport(reportID: string, reportName: string, created: string): Report { + return { + reportID, + reportName, + type: CONST.REPORT.TYPE.EXPENSE, + policyID: POLICY_ID, + chatReportID: CHAT_REPORT_ID, + ownerAccountID: SUBMITTER_ACCOUNT_ID, + managerID: SUBMITTER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + currency: 'USD', + total: 0, + created, + }; +} + +const submittedReport: Report = { + ...buildExpenseReport(SUBMITTED_REPORT_ID, 'Submitted report', '2024-03-04'), + // Awaiting first-level approval, which is what lets `canAddTransaction` accept this report when it is picked by hand. + managerID: APPROVER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, +}; + +const renderReportField = (action: IOUAction = CONST.IOU.ACTION.CREATE) => + render( + + + , + ); + +describe('ReportField', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + initOnyxDerivedValues(); + }); + + beforeEach(async () => { + mockIsBetaEnabled.mockReturnValue(false); + await Onyx.clear(); + // `canAddTransaction` requires the submitter to own the report and the policy to be a group policy with an approver. + await Onyx.merge(ONYXKEYS.SESSION, {accountID: SUBMITTER_ACCOUNT_ID, email: SUBMITTER_EMAIL}); + await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, { + [SUBMITTER_ACCOUNT_ID]: {accountID: SUBMITTER_ACCOUNT_ID, login: SUBMITTER_EMAIL}, + [APPROVER_ACCOUNT_ID]: {accountID: APPROVER_ACCOUNT_ID, login: APPROVER_EMAIL}, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, { + id: POLICY_ID, + type: CONST.POLICY.TYPE.TEAM, + role: CONST.POLICY.ROLE.USER, + approver: APPROVER_EMAIL, + owner: APPROVER_EMAIL, + approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC, + }); + await waitForBatchedUpdates(); + }); + + async function givenExpense(iouRequestType: ValueOf = CONST.IOU.REQUEST_TYPE.MANUAL) { + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${TRANSACTION_ID}`, { + transactionID: TRANSACTION_ID, + amount: 1000, + currency: 'USD', + iouRequestType, + participants: [{accountID: 0, reportID: CHAT_REPORT_ID, policyID: POLICY_ID, isPolicyExpenseChat: true, selected: true}], + }); + await waitForBatchedUpdates(); + } + + it('shows New report when the submitter only has a report that is awaiting approval', async () => { + // Given the submitter just sent their only report for approval, which clears the chat's iouReportID + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, chatReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${SUBMITTED_REPORT_ID}`, submittedReport); + await givenExpense(); + + // When the confirmation form renders the report row + renderReportField(); + + // Then the row says New report, because saving never adds the expense to a report awaiting approval + await waitFor(() => { + expect(screen.getByText('iou.newReport')).toBeOnTheScreen(); + }); + expect(screen.queryByText('Submitted report')).toBeNull(); + + // And the row stays editable, so the user can still pick the submitted report by hand + expect(screen.getByText('iou.newReport')).toBeEnabled(); + }); + + it('keeps the row editable after the user picks the only report, which is awaiting approval', async () => { + // Given the submitter only has a report awaiting approval, and the user picked it on the confirmation form + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, chatReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${SUBMITTED_REPORT_ID}`, submittedReport); + await givenExpense(); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${TRANSACTION_ID}`, {reportID: SUBMITTED_REPORT_ID}); + await waitForBatchedUpdates(); + + // When the confirmation form renders the report row + renderReportField(); + + // Then the row shows the picked report + await waitFor(() => { + expect(screen.getByText('Submitted report')).toBeOnTheScreen(); + }); + + // And the row stays editable, so the user can switch back to a new report + expect(screen.getByText('Submitted report')).toBeEnabled(); + }); + + it('keeps the row read-only when a tracked expense is moved and the only report is awaiting approval', async () => { + // Given the submitter only has a report awaiting approval, and they move a tracked expense from their self DM to the workspace + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, chatReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${SUBMITTED_REPORT_ID}`, submittedReport); + await givenExpense(); + + // When the confirmation form renders the report row for the move + renderReportField(CONST.IOU.ACTION.SUBMIT); + + // Then the row says New report and is not editable, because the server only adds a tracked expense to an open report + await waitFor(() => { + expect(screen.getByText('iou.newReport')).toBeOnTheScreen(); + }); + expect(screen.getByText('iou.newReport')).toBeDisabled(); + }); + + it('shows the newest open report rather than a newer report awaiting approval', async () => { + // Given the submitter has an open report and a more recent report awaiting approval + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, chatReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${OPEN_REPORT_ID}`, buildExpenseReport(OPEN_REPORT_ID, 'Open report', '2024-01-02')); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${SUBMITTED_REPORT_ID}`, submittedReport); + await givenExpense(); + + // When the confirmation form renders the report row + renderReportField(); + + // Then the row shows the open report, which is where saving adds the expense + await waitFor(() => { + expect(screen.getByText('Open report')).toBeOnTheScreen(); + }); + expect(screen.queryByText('Submitted report')).toBeNull(); + }); + + it('shows New report for a scan in the ASAP submit beta even when the chat points at an open report', async () => { + // Given the chat points at an open report and the user is in the ASAP submit beta + mockIsBetaEnabled.mockImplementation((beta: string) => beta === CONST.BETAS.ASAP_SUBMIT); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, {...chatReport, iouReportID: OPEN_REPORT_ID}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${OPEN_REPORT_ID}`, buildExpenseReport(OPEN_REPORT_ID, 'Open report', '2024-01-02')); + await givenExpense(CONST.IOU.REQUEST_TYPE.SCAN); + + // When the confirmation form renders the report row for the scan + renderReportField(); + + // Then the row says New report, because saving a scan in this beta always starts a new report + await waitFor(() => { + expect(screen.getByText('iou.newReport')).toBeOnTheScreen(); + }); + expect(screen.queryByText('Open report')).toBeNull(); + + // And the row stays editable, so the user can still pick the open report instead + expect(screen.getByText('iou.newReport')).toBeEnabled(); + }); + + it('shows the open report the chat points at for a manual expense', async () => { + // Given the chat points at an open report + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, {...chatReport, iouReportID: OPEN_REPORT_ID}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${OPEN_REPORT_ID}`, buildExpenseReport(OPEN_REPORT_ID, 'Open report', '2024-01-02')); + await givenExpense(); + + // When the confirmation form renders the report row + renderReportField(); + + // Then the row shows that report, which is where saving adds the expense + await waitFor(() => { + expect(screen.getByText('Open report')).toBeOnTheScreen(); + }); + + // And the row is not editable, because that report is the only one the user could pick + expect(screen.getByText('Open report')).toBeDisabled(); + }); +}); diff --git a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx index 615a20cb2050..dd28ac644807 100644 --- a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx +++ b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx @@ -30,6 +30,12 @@ jest.mock('@libs/actions/Transaction', () => ({ jest.mock('@hooks/useCurrencyList', () => ({useCurrencyListActions: jest.fn(() => ({getCurrencyDecimals: jest.fn(() => 2), getCurrencySymbol: jest.fn(() => '$')}))})); jest.mock('@hooks/useConfirmModal', () => () => ({showConfirmModal: jest.fn()})); +const mockIsBetaEnabled = jest.fn(() => false); +jest.mock('@hooks/usePermissions', () => { + const actualUsePermissions = jest.requireActual<{default: () => Record}>('@hooks/usePermissions').default; + return () => ({...actualUsePermissions(), isBetaEnabled: mockIsBetaEnabled}); +}); + // Where a new report may go, and whether the workspace is behind on billing. Each test sets the case it needs rather than // building the policies and billing state the real hooks read. let mockPolicyForMovingExpenses: Policy | undefined; @@ -58,7 +64,17 @@ const CURRENT_REPORT_ID = 'report1'; const OTHER_REPORT_ID = 'report2'; const chatReport: Report = {reportID: CHAT_REPORT_ID, policyID: POLICY_ID, chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, iouReportID: CURRENT_REPORT_ID}; -const currentReport: Report = {reportID: CURRENT_REPORT_ID, policyID: POLICY_ID, chatReportID: CHAT_REPORT_ID, type: CONST.REPORT.TYPE.EXPENSE}; +// An open report, so a new expense can join it on its own. +const currentReport: Report = { + reportID: CURRENT_REPORT_ID, + policyID: POLICY_ID, + chatReportID: CHAT_REPORT_ID, + type: CONST.REPORT.TYPE.EXPENSE, + ownerAccountID: 1, + managerID: 1, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, +}; const otherReport: Report = {reportID: OTHER_REPORT_ID, policyID: POLICY_ID, chatReportID: CHAT_REPORT_ID, type: CONST.REPORT.TYPE.EXPENSE}; const getDropdown = (onClose: jest.Mock, isVisible = true) => ( @@ -106,6 +122,7 @@ describe('ReportFieldDropdown', () => { mockPolicyForMovingExpenses = undefined; mockShouldSelectPolicy = false; mockIsCreateReportRestricted = false; + mockIsBetaEnabled.mockReturnValue(false); jest.mocked(setTransactionReport).mockClear(); // Each navigate-away test spies on the navigation and transition tracker; nothing keeps those spies between tests. jest.restoreAllMocks(); @@ -186,6 +203,51 @@ describe('ReportFieldDropdown', () => { expect(onClose).toHaveBeenCalledTimes(1); }); + it('moves a scan in the ASAP submit beta to the open report the chat points at when the user picks it', async () => { + // Given the user is in the ASAP submit beta, and a scan is being created in a workspace chat that points at an open report. + // Saving a scan in this beta starts a new report, so the Report field shows New report even though the chat points at `report1`. + mockIsBetaEnabled.mockImplementation((beta: string) => beta === CONST.BETAS.ASAP_SUBMIT); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${TRANSACTION_ID}`, { + transactionID: TRANSACTION_ID, + reportID: CHAT_REPORT_ID, + iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN, + participants: [{policyID: POLICY_ID, reportID: CHAT_REPORT_ID, isPolicyExpenseChat: true, selected: true}], + }); + await waitForBatchedUpdates(); + const onClose = jest.fn(); + + // When the report row's dropdown opens and the user picks `report1` + renderDropdown(onClose); + await waitForBatchedUpdates(); + await act(async () => { + mockModalProps?.selectReport({value: CURRENT_REPORT_ID, keyForList: CURRENT_REPORT_ID, policyID: POLICY_ID}); + }); + + // Then the list doesn't mark `report1`, matching the field, and picking it moves the draft there, so saving adds the scan to it + // instead of starting a new report + expect(mockModalProps?.selectedReportID).not.toBe(CURRENT_REPORT_ID); + expect(setTransactionReport).toHaveBeenCalledWith(TRANSACTION_ID, expect.objectContaining({reportID: CURRENT_REPORT_ID}), true); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('does not reevaluate unchanged beta permissions when only the draft amount changes', async () => { + // Given a mounted picker with a stable permissions function, as provided by usePermissions + await setDraftExpense(); + renderDropdown(jest.fn()); + await waitForBatchedUpdates(); + expect(mockIsBetaEnabled).toHaveBeenCalledWith(CONST.BETAS.ASAP_SUBMIT); + mockIsBetaEnabled.mockClear(); + + // When unrelated draft data makes the picker hook render again + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${TRANSACTION_ID}`, {amount: 100}); + await waitForBatchedUpdates(); + }); + + // Then the compiler reuses the unchanged beta result instead of evaluating permissions again + expect(mockIsBetaEnabled).not.toHaveBeenCalled(); + }); + it('mounts the list only while the container is open or still closing', async () => { // Given a draft expense and the report row's dropdown, which the row keeps mounted once it has been opened await setDraftExpense(); diff --git a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdownRow.test.tsx b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdownRow.test.tsx index 7b419aa07a2d..59f052a8bc18 100644 --- a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdownRow.test.tsx +++ b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdownRow.test.tsx @@ -247,17 +247,17 @@ describe('ReportField', () => { }); }); - it('preserves the report default and interaction when submitting a tracked expense', async () => { - // Given reports which are not valid creation destinations but remain usable by the submit flow + it('shows New report while keeping report selection interactive when submitting a tracked expense', async () => { + // Given open reports that the builder cannot select automatically await addNonReimbursableExpense(outstandingReport); await addNonReimbursableExpense(otherOutstandingReport); - // When submitting rather than creating the expense + // When submitting a tracked expense renderReportRow({action: CONST.IOU.ACTION.SUBMIT}); - // Then creation-only restrictions do not change the existing field + // Then the default matches the builder while explicit report selection remains available await waitFor(() => { - expect(mockReportName).toBe(outstandingReport.reportName); + expect(mockReportName).toBe('iou.newReport'); expect(mockIsInteractive).toBe(true); }); });