From beb83b2eec1e7427a1da8f8bb4b1bd4c50d8ca32 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Tue, 10 Nov 2026 09:41:16 +0000 Subject: [PATCH 1/8] Fix report destination defaults and workspace picker scope Co-authored-by: Yauheni Horbach --- .../sections/ReportField.tsx | 37 ++- .../sections/selectors.ts | 3 + .../step/IOURequestEditReportCommon.tsx | 8 +- .../hooks/useReportPickerActions.ts | 16 +- tests/ui/MoneyRequestReportFooter.tsx | 16 +- .../IOURequestStepReportNewReportTest.tsx | 213 +++++++++++++++ .../ReportField.test.tsx | 245 ++++++++++++++++++ 7 files changed, 526 insertions(+), 12 deletions(-) create mode 100644 tests/ui/components/IOURequestStepReportNewReportTest.tsx create mode 100644 tests/unit/components/MoneyRequestConfirmationList/ReportField.test.tsx diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 1e3a647b5aa4..3fa9a2412dcb 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -8,11 +8,21 @@ 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'; import {getReportName} from '@libs/ReportNameUtils'; -import {generateReportID, getOutstandingReportsForUser, isMoneyRequestReport, isReportOutstanding, sortOutstandingReportsBySelected} from '@libs/ReportUtils'; +import { + generateReportID, + getNewestOutstandingReportForUser, + getOutstandingReportsForUser, + isMoneyRequestReport, + isOpenExpenseReport, + isReportOutstanding, + shouldCreateNewMoneyRequestReport, + sortOutstandingReportsBySelected, +} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; @@ -63,6 +73,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}`); @@ -83,10 +94,22 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a (report1, report2) => sortOutstandingReportsBySelected(report1, report2, undefined, localeCompare), ); - const outstandingReportID = isPolicyExpenseChat ? (iouReportIDFromMain ?? availableOutstandingReports.at(0)?.reportID) : reportID; + // Resolve the default report the same way the save path (MoneyRequestBuilder) does, so the field never shows a report + // the expense won't be added to. For example, a submitted report awaiting approval can still accept expenses when picked, + // but it is never used as the default, so the field shows "New report" instead. + const newestOutstandingReport = iouReport ? undefined : getNewestOutstandingReportForUser(policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {}); + const defaultReport = iouReport ?? newestOutstandingReport; + const shouldCreateNewReport = shouldCreateNewMoneyRequestReport(defaultReport, mainReport, isScanRequest, isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), rules, action); + const defaultReportID = shouldCreateNewReport ? undefined : defaultReport?.reportID; + + const outstandingReportID = isPolicyExpenseChat ? defaultReportID : reportID; + const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID; + + // When saving would create a report by default, any outstanding report is an alternative the user can pick. This is based on + // the default rather than the picked report, so picking the only outstanding report keeps the field editable to switch back. + const isNewReport = !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; @@ -99,6 +122,8 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a reportToUse = mainReport; } else if (reportIDToUse === iouReportIDFromMain) { reportToUse = iouReport; + } else if (reportIDToUse === newestOutstandingReport?.reportID) { + reportToUse = newestOutstandingReport; } else { reportToUse = availableOutstandingReports.find((r) => r?.reportID === reportIDToUse); } @@ -115,10 +140,12 @@ 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 = isMovingTransactionFromTrackExpense(action) ? allOutstandingReports.filter(isOpenExpenseReport) : allOutstandingReports; // 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(outstandingReports, selectedReportID, isUnreported) && !isMoneyRequestReport(reportID); + const shouldReportBeEditable = shouldReportFieldBeEditable(outstandingReports, selectedReportID, isUnreported || isNewReport) && !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 = isBetaEnabled(CONST.BETAS.ANCHORED_FIELD_DROPDOWNS) && !!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 3ae463a796d7..da6afd0c85fd 100644 --- a/src/components/MoneyRequestConfirmationList/sections/selectors.ts +++ b/src/components/MoneyRequestConfirmationList/sections/selectors.ts @@ -11,6 +11,7 @@ import { isCreatedMissing, isFailedScanAmountPlaceholder, isMerchantMissing, + isScanRequest, isScanning, willFieldBeAutomaticallyFilled, } from '@libs/TransactionUtils'; @@ -354,6 +355,7 @@ type ReportFieldTransactionState = { reportID: Transaction['reportID']; isFromGlobalCreate: boolean; participantReportID: string | undefined; + isScanRequest: boolean; }; const reportFieldTransactionStateSelector = (t: OnyxEntry): ReportFieldTransactionState | undefined => { @@ -364,6 +366,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/pages/iou/request/step/IOURequestEditReportCommon.tsx b/src/pages/iou/request/step/IOURequestEditReportCommon.tsx index d2854adff4ff..382db70e1304 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'; @@ -79,6 +79,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 */ @@ -126,6 +128,7 @@ function IOURequestEditReportCommon({ isPerDiemRequest, isTimeRequest = false, isUnreportedManagedCardTransaction = false, + shouldOnlyListOpenReports = false, hasMultipleSubmitters = false, areAllManagedCardsResolvable = false, autoReport, @@ -230,6 +233,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 b6d0b001e433..d3718e25bcb2 100644 --- a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts +++ b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts @@ -13,6 +13,7 @@ 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'; @@ -89,6 +90,7 @@ type ReportPickerListProps = Pick< | 'isPerDiemRequest' | 'isTimeRequest' | 'isUnreportedManagedCardTransaction' + | 'shouldOnlyListOpenReports' | 'createReport' | 'targetOwnerAccountID' >; @@ -148,7 +150,14 @@ function useReportPickerActions({ const ownerAccountID = isUnreported ? iouActions?.find((iouAction) => 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); @@ -270,7 +279,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 { @@ -290,6 +301,7 @@ 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, }, diff --git a/tests/ui/MoneyRequestReportFooter.tsx b/tests/ui/MoneyRequestReportFooter.tsx index 1c7c6cb4ec05..60c95f7b547c 100644 --- a/tests/ui/MoneyRequestReportFooter.tsx +++ b/tests/ui/MoneyRequestReportFooter.tsx @@ -199,7 +199,9 @@ 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 allow editing report field when the only outstanding report is picked and creating from policy chat', async () => { + // Given the expense is on the only outstanding report, while saving would create a new report by default + // because the current user is not that report's submitter const mockTransactionReport: Transaction = { ...mockTransaction, isFromGlobalCreate: false, @@ -222,12 +224,14 @@ describe('MoneyRequestConfirmationListFooter', () => { }); initOnyxDerivedValues(); + // When the confirmation footer renders the report field await renderMoneyRequestConfirmationListFooter(mockTransactionReport); await waitForBatchedUpdatesWithAct(); + // Then the field stays editable, so the user can switch back to a new report const reportItem = screen.getByTestId('menu-item-Report'); - expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: true})); + expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: false})); }); it('should disable report field when there are no reports available', async () => { @@ -252,7 +256,9 @@ 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 allow editing report field when transaction has the only outstanding report and creating from FAB', async () => { + // Given the expense is on the only outstanding report, while saving would create a new report by default + // because the current user is not that report's submitter const mockTransactionReport: Transaction = { ...mockTransaction, isFromGlobalCreate: true, @@ -275,12 +281,14 @@ describe('MoneyRequestConfirmationListFooter', () => { }); initOnyxDerivedValues(); + // When the confirmation footer renders the report field await renderMoneyRequestConfirmationListFooter(mockTransactionReport); await waitForBatchedUpdatesWithAct(); + // Then the field stays editable, so the user can switch back to a new report const reportItem = screen.getByTestId('menu-item-Report'); - expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: true})); + expect(reportItem.props.accessibilityState).toEqual(expect.objectContaining({disabled: false})); }); it('should allow editing report field when transaction is unReported and creating from FAB with only 1 outstanding report', async () => { diff --git a/tests/ui/components/IOURequestStepReportNewReportTest.tsx b/tests/ui/components/IOURequestStepReportNewReportTest.tsx new file mode 100644 index 000000000000..8cad42ddd542 --- /dev/null +++ b/tests/ui/components/IOURequestStepReportNewReportTest.tsx @@ -0,0 +1,213 @@ +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 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 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(); + }); +}); 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(); + }); +}); From b19894e6920a6de91ab476e233e4d3f40bd74018 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Fri, 13 Nov 2026 14:57:42 +0000 Subject: [PATCH 2/8] Keep report picker scoped to the workspace chat owner Co-authored-by: Yauheni Horbach --- .../hooks/useReportPickerActions.ts | 2 +- .../IOURequestStepReportNewReportTest.tsx | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts index d3718e25bcb2..8b4c28541492 100644 --- a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts +++ b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts @@ -303,7 +303,7 @@ function useReportPickerActions({ isUnreportedManagedCardTransaction: transaction ? isUnreportedManagedCardTransaction : false, shouldOnlyListOpenReports: isMovingTransactionFromTrackExpense(action), createReport: policyForMovingExpensesID || shouldSelectPolicy || isPerDiemTransaction || isUnreportedManagedCardTransaction ? createReport : undefined, - targetOwnerAccountID: ownerAccountID, + targetOwnerAccountID: newReportOwnerAccountID, }, }; } diff --git a/tests/ui/components/IOURequestStepReportNewReportTest.tsx b/tests/ui/components/IOURequestStepReportNewReportTest.tsx index 8cad42ddd542..7b74e62e4e0e 100644 --- a/tests/ui/components/IOURequestStepReportNewReportTest.tsx +++ b/tests/ui/components/IOURequestStepReportNewReportTest.tsx @@ -6,6 +6,7 @@ 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'; @@ -85,6 +86,7 @@ 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'; @@ -210,4 +212,29 @@ describe('IOURequestStepReport with a generated New report ID', () => { 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 list the member reports when an admin creates an expense 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 it fetches and lists the member reports, not the signed-in admin reports in the same workspace + expect(await screen.findByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}${MEMBER_OPEN_REPORT_ID}`)).toBeTruthy(); + 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); + }); }); From 68bed71ce02a7fe38c0b8792040184b9d36554a1 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Wed, 18 Nov 2026 10:59:22 +0000 Subject: [PATCH 3/8] Inline report field editability condition Co-authored-by: Yauheni Horbach --- .../MoneyRequestConfirmationList/sections/ReportField.tsx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 096c10a1570b..8206560bfef1 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -112,10 +112,6 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a const outstandingReportID = isPolicyExpenseChat ? defaultReportID : reportID; const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID; - // When saving would create a report by default, any outstanding report is an alternative the user can pick. This is based on - // the default rather than the picked report, so picking the only outstanding report keeps the field editable to switch back. - const isNewReport = !outstandingReportID; - const [selectedReportID, selectedReport] = (() => { if (!reportIDToUse) { // Even if we have no report to use we still need a report id for proper navigation @@ -156,7 +152,8 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a 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 || isNewReport) && !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; From acce1679196fdf5f050ceed5775d3a6a5c7b52a3 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Wed, 18 Nov 2026 12:19:21 +0000 Subject: [PATCH 4/8] Share report defaults between confirmation and picker Co-authored-by: Yauheni Horbach --- .../sections/ReportField.tsx | 5 +-- src/libs/ReportUtils.ts | 24 ++++++++++ .../hooks/useReportPickerActions.ts | 14 ++++-- .../ReportFieldDropdown.test.tsx | 44 ++++++++++++++++++- 4 files changed, 79 insertions(+), 8 deletions(-) diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 8206560bfef1..07bbae21b8d7 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -16,12 +16,12 @@ import {getReportName} from '@libs/ReportNameUtils'; import { canAddTransaction, generateReportID, + getDefaultMoneyRequestReport, getNewestOutstandingReportForUser, getOutstandingReportsForUser, isMoneyRequestReport, isOpenExpenseReport, isReportOutstanding, - shouldCreateNewMoneyRequestReport, sortOutstandingReportsBySelected, } from '@libs/ReportUtils'; @@ -106,8 +106,7 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a ? getNewestOutstandingReportForUser(policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {}) : availableOutstandingReports.at(0); })(); - const shouldCreateNewReport = isCreatingExpense && shouldCreateNewMoneyRequestReport(defaultReport, mainReport, isScanRequest, isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), rules, action); - const defaultReportID = shouldCreateNewReport ? undefined : defaultReport?.reportID; + const defaultReportID = getDefaultMoneyRequestReport(defaultReport, mainReport, isScanRequest, isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), rules, action)?.reportID; const outstandingReportID = isPolicyExpenseChat ? defaultReportID : reportID; const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 1645af16ada3..85412dad4c47 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -13650,6 +13650,29 @@ function getNewestOutstandingReportForUser( return openReports.reduce>((newest, report) => ((report?.created ?? '') > (newest?.created ?? '') ? (report ?? null) : newest), openReports.at(0) ?? null); } +/** + * 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, usually the one the workspace chat points at + * @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 { + // Only a new expense goes through the save path's checks; other actions keep the report they were given. + if (action !== CONST.IOU.ACTION.CREATE) { + 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`. @@ -16329,6 +16352,7 @@ export { buildOptimisticMovedTransactionAction, getOutstandingReportsForUser, getNewestOutstandingReportForUser, + getDefaultMoneyRequestReport, isApproverOfOutstandingPolicyReports, isReportOutstanding, isReportTotalPending, diff --git a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts index 5df5a4570a9a..504a15096d1b 100644 --- a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts +++ b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts @@ -16,12 +16,13 @@ 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, 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'; @@ -130,7 +131,14 @@ function useReportPickerActions({ const [participantReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${participantReportID}`); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); const shouldUseTransactionReport = (!!transactionReport && isReportOutstanding(transactionReport, transactionReport?.policyID, rules, reportNameValuePair)) || isUnreported; - const outstandingReportID = isPolicyExpenseChat(participantReport) ? participantReport?.iouReportID : participantReportID; + const [chatIOUReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(participantReport?.iouReportID)}`); + const {isBetaEnabled} = usePermissions(); + const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); + // Mark the report the Report field shows. When saving would start a new report, e.g. for a scan in the ASAP Submit beta, nothing is + // marked, so picking the chat's open report writes it to the expense instead of only closing the picker. + const outstandingReportID = isPolicyExpenseChat(participantReport) + ? getDefaultMoneyRequestReport(chatIOUReport, participantReport, isScanRequest(transaction), isASAPSubmitBetaEnabled, rules, action)?.reportID + : participantReportID; const selectedReportID = shouldUseTransactionReport ? transactionReport?.reportID : outstandingReportID; const [selectedReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${selectedReportID}`); const {allPolicies, perDiemOriginalPolicy} = usePerDiemPolicyData(transaction); @@ -144,8 +152,6 @@ function useReportPickerActions({ const isEditing = action === CONST.IOU.ACTION.EDIT; const isCreateReport = action === CONST.IOU.ACTION.CREATE; const isFromGlobalCreate = !!transaction?.isFromGlobalCreate; - const {isBetaEnabled} = usePermissions(); - const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); const session = useSession(); const personalDetails = usePersonalDetails(); const ownerAccountID = isUnreported diff --git a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx index 51b2ef7b0bf7..803586a63561 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: (beta: string) => mockIsBetaEnabled(beta)}); +}); + // 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(); @@ -184,6 +201,31 @@ 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(); + act(() => 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('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(); From 78da12feed592d5c35214576b3694caff5a03063 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Wed, 18 Nov 2026 13:38:30 +0000 Subject: [PATCH 5/8] Simplify automatic report fallback selection Co-authored-by: Yauheni Horbach --- .../sections/ReportField.tsx | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 07bbae21b8d7..7c31323e58e9 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -98,14 +98,11 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a ); // Match the save path's automatic destination before checking eligibility, rather than falling back to a report it would not use. - const defaultReport = (() => { - if (iouReport) { - return iouReport; - } - return isCreatingExpense || isMovingTrackedExpense + const defaultReport = + iouReport ?? + (isCreatingExpense || isMovingTrackedExpense ? getNewestOutstandingReportForUser(policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {}) - : availableOutstandingReports.at(0); - })(); + : availableOutstandingReports.at(0)); const defaultReportID = getDefaultMoneyRequestReport(defaultReport, mainReport, isScanRequest, isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), rules, action)?.reportID; const outstandingReportID = isPolicyExpenseChat ? defaultReportID : reportID; From 520ba2e4df050816b0018f817dbf353f20b4e4ce Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Fri, 20 Nov 2026 19:12:13 +0000 Subject: [PATCH 6/8] Align report candidates with money request builder actions Co-authored-by: Yauheni Horbach --- .../sections/ReportField.tsx | 10 ++- src/libs/ReportUtils.ts | 41 +++++++++++- .../hooks/useReportPickerActions.ts | 24 ++++++- tests/unit/ReportUtilsTest.ts | 66 +++++++++++++++++++ .../ReportFieldDropdownRow.test.tsx | 10 +-- 5 files changed, 135 insertions(+), 16 deletions(-) diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 7c31323e58e9..67c9ccf1bf43 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -17,11 +17,12 @@ import { canAddTransaction, generateReportID, getDefaultMoneyRequestReport, - getNewestOutstandingReportForUser, + getMoneyRequestReportCandidate, getOutstandingReportsForUser, isMoneyRequestReport, isOpenExpenseReport, isReportOutstanding, + isSavedThroughMoneyRequestBuilder, sortOutstandingReportsBySelected, } from '@libs/ReportUtils'; @@ -98,11 +99,8 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a ); // Match the save path's automatic destination before checking eligibility, rather than falling back to a report it would not use. - const defaultReport = - iouReport ?? - (isCreatingExpense || isMovingTrackedExpense - ? getNewestOutstandingReportForUser(policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {}) - : availableOutstandingReports.at(0)); + 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; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 85412dad4c47..abc3ce5f22dc 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -13650,12 +13650,45 @@ 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, usually the one the workspace chat points at + * @param candidateReport - The report the expense would join, from getMoneyRequestReportCandidate * @param chatReport - The workspace chat the expense is created in */ function getDefaultMoneyRequestReport( @@ -13666,8 +13699,8 @@ function getDefaultMoneyRequestReport( rules: OnyxCollection, action: IOUAction, ): OnyxInputOrEntry { - // Only a new expense goes through the save path's checks; other actions keep the report they were given. - if (action !== CONST.IOU.ACTION.CREATE) { + // 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; @@ -16353,6 +16386,8 @@ export { getOutstandingReportsForUser, getNewestOutstandingReportForUser, getDefaultMoneyRequestReport, + getMoneyRequestReportCandidate, + isSavedThroughMoneyRequestBuilder, isApproverOfOutstandingPolicyReports, isReportOutstanding, isReportTotalPending, diff --git a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts index 504a15096d1b..04afc80241ef 100644 --- a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts +++ b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts @@ -16,7 +16,14 @@ 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 {getDefaultMoneyRequestReport, getPersonalDetailsForAccountID, getReportOrDraftReport, isPolicyExpenseChat, isReportOutstanding} from '@libs/ReportUtils'; +import { + getDefaultMoneyRequestReport, + getMoneyRequestReportCandidate, + getPersonalDetailsForAccountID, + getReportOrDraftReport, + isPolicyExpenseChat, + isReportOutstanding, +} from '@libs/ReportUtils'; import { isDistanceRequest as isDistanceRequestUtil, isManualDistanceRequest as isManualDistanceRequestUtil, @@ -40,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'; @@ -134,10 +142,22 @@ function useReportPickerActions({ const [chatIOUReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(participantReport?.iouReportID)}`); const {isBetaEnabled} = usePermissions(); const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); + const [outstandingReportsForPolicy] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID, {selector: createOutstandingReportsForPolicySelector(participantReport?.policyID)}); + const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); + // Start from the same report the Report field does, so the picker marks the report it shows. + const candidateReport = getMoneyRequestReportCandidate( + chatIOUReport, + action, + participantReport?.policyID, + participantReport?.ownerAccountID, + rules, + reportNameValuePairs, + outstandingReportsForPolicy, + ); // Mark the report the Report field shows. When saving would start a new report, e.g. for a scan in the ASAP Submit beta, nothing is // marked, so picking the chat's open report writes it to the expense instead of only closing the picker. const outstandingReportID = isPolicyExpenseChat(participantReport) - ? getDefaultMoneyRequestReport(chatIOUReport, participantReport, isScanRequest(transaction), isASAPSubmitBetaEnabled, rules, action)?.reportID + ? getDefaultMoneyRequestReport(candidateReport, participantReport, isScanRequest(transaction), isASAPSubmitBetaEnabled, rules, action)?.reportID : participantReportID; const selectedReportID = shouldUseTransactionReport ? transactionReport?.reportID : outstandingReportID; const [selectedReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${selectedReportID}`); diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 68e9f4fd4cdb..ad7dbca254ea 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -107,6 +107,7 @@ import { getChatRoomSubtitle, getChildReportNotificationPreference, getDefaultGroupAvatar, + getDefaultMoneyRequestReport, getDefaultWorkspaceAvatar, getDeletedTransactionMessage, getDisplayedReportID, @@ -122,6 +123,7 @@ import { getIOUReportActionDisplayMessage, getLinkedIOUTransaction, getMissingPaymentMethodForQueuedPayment, + getMoneyRequestReportCandidate, getMoneyRequestSpendBreakdown, getMostRecentlyVisitedReport, getMovedActionMessage, @@ -21474,6 +21476,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/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); }); }); From 3f8c6b6f7f936cdb1b8c4adfcc9892668de87ef6 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Fri, 20 Nov 2026 19:36:32 +0000 Subject: [PATCH 7/8] Restore cached ASAP Submit beta evaluation in report picker Co-authored-by: Yauheni Horbach --- .../hooks/useReportPickerActions.ts | 9 +++++++-- .../ReportFieldDropdown.test.tsx | 20 ++++++++++++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts index 04afc80241ef..8b3da2323e43 100644 --- a/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts +++ b/src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts @@ -117,6 +117,12 @@ const getIOUActionsSelector = (actions: OnyxEntry): Array () => ({showConfirmModal: jest.fn()})) const mockIsBetaEnabled = jest.fn(() => false); jest.mock('@hooks/usePermissions', () => { const actualUsePermissions = jest.requireActual<{default: () => Record}>('@hooks/usePermissions').default; - return () => ({...actualUsePermissions(), isBetaEnabled: (beta: string) => mockIsBetaEnabled(beta)}); + 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 @@ -226,6 +226,24 @@ describe('ReportFieldDropdown', () => { 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(); From d68fc1c9fbfe79e8eaca08fa3db73c09e2448d07 Mon Sep 17 00:00:00 2001 From: "Yauheni Horbach (via MelvinBot)" Date: Fri, 20 Nov 2026 21:25:56 +0000 Subject: [PATCH 8/8] Await report selection updates in scan regression test Co-authored-by: Yauheni Horbach --- .../MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx index be0481cbfb18..dd28ac644807 100644 --- a/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx +++ b/tests/unit/components/MoneyRequestConfirmationList/ReportFieldDropdown.test.tsx @@ -219,7 +219,9 @@ describe('ReportFieldDropdown', () => { // When the report row's dropdown opens and the user picks `report1` renderDropdown(onClose); await waitForBatchedUpdates(); - act(() => mockModalProps?.selectReport({value: CURRENT_REPORT_ID, keyForList: CURRENT_REPORT_ID, policyID: POLICY_ID})); + 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