From 2ed5c78189b78a57dfa84f47e62b32c174b26d2b Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Wed, 28 Oct 2026 09:07:10 +0100 Subject: [PATCH 01/20] Show global reimbursements modal for reports skipped in bulk pay --- src/hooks/useSearchBulkActions.ts | 82 +++++-- src/languages/en.ts | 4 + src/libs/actions/App.ts | 8 + .../unit/hooks/useSearchBulkActionsPayTest.ts | 201 +++++++++++++++++- 4 files changed, 280 insertions(+), 15 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 785aca96d34f..037ccd36f90e 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -10,6 +10,7 @@ import {getSearchGroupCountByKey} from '@components/Search/selectionBuilders'; import type {BulkPaySelectionData, PaymentData, QueryFilterKey, SearchColumnType, SearchGroupBy, SearchQueryJSON, SelectedReports, SelectedTransactions} from '@components/Search/types'; import {getAccountingIntegrationDisplayName, getExportLabelForConnection, isIntuitEnterpriseSuiteConnection} from '@libs/AccountingUtils'; +import {showEnableGlobalReimbursementsModal} from '@libs/actions/App'; import {getExpensifyCardStatementPDF} from '@libs/actions/CompanyCards'; import {exportReceiptsToZip, exportReportsToPDF} from '@libs/actions/Export'; import {unholdRequest} from '@libs/actions/IOU/Hold'; @@ -44,6 +45,7 @@ import { } from '@libs/actions/Search'; import initSplitExpense from '@libs/actions/SplitExpenses'; import {setNameValuePair} from '@libs/actions/User'; +import {getLastFourDigits} from '@libs/BankAccountUtils'; import {canResolveTransactionCard} from '@libs/CardUtils'; import {getConnectionCompanyID} from '@libs/CopyPolicySettingsUtils'; import deferModalPresentationAfterPopoverDismiss from '@libs/deferModalPresentationAfterPopoverDismiss'; @@ -57,6 +59,7 @@ import Parser from '@libs/Parser'; import {getLoginByAccountID} from '@libs/PersonalDetailsUtils'; import {canAccessPolicyBankAccount} from '@libs/PolicyPaymentUtils'; import {getConnectedIntegration, isAdminOfCardEnabledPolicy, isSubmitPolicy} from '@libs/PolicyUtils'; +import {getReportName} from '@libs/ReportNameUtils'; import {getReportAccountingExportActions, isMergeActionForSelectedTransactions} from '@libs/ReportSecondaryActionUtils'; import { canEditMultipleTransactions, @@ -129,7 +132,18 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import {columnsSelector} from '@src/selectors/AdvancedSearchFiltersForm'; import {doesPersonalDetailExistSelector} from '@src/selectors/PersonalDetails'; -import type {BillingGraceEndPeriod, ExportTemplate, Policy, Report, ReportAction, ReportNameValuePairs, SearchResults, Transaction, TransactionViolations} from '@src/types/onyx'; +import type { + BankAccount, + BillingGraceEndPeriod, + ExportTemplate, + Policy, + Report, + ReportAction, + ReportNameValuePairs, + SearchResults, + Transaction, + TransactionViolations, +} from '@src/types/onyx'; import type {SearchResultDataType} from '@src/types/onyx/SearchResults'; import type DeepValueOf from '@src/types/utils/DeepValueOf'; import {getEmptyObject, isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -169,6 +183,7 @@ import {useGetPersonalDetailsByLogin} from './usePersonalDetailByLogin'; import {useAllPersonalDetails} from './usePersonalDetails'; import usePersonalPolicy from './usePersonalPolicy'; import usePolicyForMovingExpenses from './usePolicyForMovingExpenses'; +import {useDerivedReportNamesByReportIDs} from './useReportAttributes'; import useReportPDFDownloadModal from './useReportPDFDownloadModal'; import useRestrictedActionPolicyID from './useRestrictedActionPolicyID'; import useSearchShouldCalculateTotals from './useSearchShouldCalculateTotals'; @@ -807,6 +822,9 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const payableSelectedReports = useMemo(() => selectedReports.filter((report) => report.canPay), [selectedReports]); const payableSelectedReportIDs = useMemo(() => payableSelectedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payableSelectedReports]); const payScopedReports = useMemo(() => (payableSelectedReports.length > 0 ? payableSelectedReports : selectedReports), [payableSelectedReports, selectedReports]); + // Names of the selected reports, so bulk pay can list the reports it skipped the same way Search shows them + const selectedReportNames = useDerivedReportNamesByReportIDs(selectedReports.length > 0 ? payableSelectedReports.map((report) => report.reportID) : selectedTransactionReportIDs); + const payScopedReportIDs = useMemo(() => payScopedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payScopedReports]); const isCurrencySupportedBulkWallet = isCurrencySupportWalletBulkPay(selectedReports, selectedTransactions); @@ -1791,6 +1809,8 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { }); let paidReportCount = 0; + // Reports skipped because their bank account needs global reimbursements, grouped by that bank account + const reportsNeedingGlobalReimbursementsByBankAccount = new Map}>(); for (const item of itemsToPay) { if (!item.reportID) { Log.info('[BulkPay] Skipping report: item has no reportID'); @@ -1898,6 +1918,22 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const methodID = paymentItem.paymentType === CONST.IOU.PAYMENT_TYPE.VBBA ? (paymentItem.bankAccountID ?? workspaceMethodID ?? reportPolicy?.achAccount?.bankAccountID) : undefined; + + // The backend rejects this payment until the account is set up for global reimbursements, so keep the report unpaid and list it in the modal after the loop + const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({ + paymentType: paymentItem.paymentType as PaymentMethodType, + methodID, + bankAccountList, + isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), + }); + if (methodID && bankAccountToSetUp) { + const skippedReports = reportsNeedingGlobalReimbursementsByBankAccount.get(methodID) ?? {bankAccount: bankAccountToSetUp, reportNames: new Map()}; + // Keyed by reportID because selecting several expenses of one report yields one item per expense + skippedReports.reportNames.set(item.reportID, getReportName(iouReport, selectedReportNames?.[item.reportID]) || translate('common.report')); + reportsNeedingGlobalReimbursementsByBankAccount.set(methodID, skippedReports); + continue; + } + payMoneyRequest({ bankAccountList, isASAPSubmitBetaEnabled: isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), @@ -1929,17 +1965,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { rules, }); - // payMoneyRequest opens the global reimbursements onboarding instead of paying, so this report stays unpaid - if ( - getBankAccountToSetUpBeforePaying({ - paymentType: paymentItem.paymentType as PaymentMethodType, - methodID, - bankAccountList, - isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), - }) - ) { - continue; - } paidReportCount += 1; } @@ -1951,6 +1976,36 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { playSound(SOUNDS.SUCCESS); clearSelectedTransactions(); } + + // The modal sets up one bank account, so it lists only the reports paid from that account + const [firstSkippedBankAccount, ...otherSkippedBankAccounts] = reportsNeedingGlobalReimbursementsByBankAccount.entries(); + if (otherSkippedBankAccounts.length > 0) { + Log.info('[BulkPay] Reports from more than one bank account need global reimbursements, prompting for the first one only', false, { + bankAccountIDs: [...reportsNeedingGlobalReimbursementsByBankAccount.keys()], + }); + } + if (firstSkippedBankAccount) { + const [bankAccountID, {bankAccount, reportNames}] = firstSkippedBankAccount; + deferModalPresentationAfterPopoverDismiss(() => { + showConfirmModal({ + title: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.title', getLastFourDigits(bankAccount.accountData?.accountNumber ?? '')), + subtitle: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.description'), + prompt: [...reportNames.values()].map((reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'), + confirmText: translate('walletPage.wiseGlobalReimbursementsIntro.getStarted'), + cancelText: translate('common.notNow'), + shouldEnablePromptScroll: true, + }).then((result) => { + if (result.action !== ModalActions.CONFIRM) { + return; + } + showEnableGlobalReimbursementsModal({ + bankAccountID, + bankCountry: bankAccount.bankCountry, + bankCurrency: bankAccount.bankCurrency, + }); + }); + }); + } }, [ hash, @@ -1997,6 +2052,9 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { conciergeChat, getCurrencyDecimals, rules, + showConfirmModal, + translate, + selectedReportNames, ], ); diff --git a/src/languages/en.ts b/src/languages/en.ts index b05b999ac768..bc1953875330 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -2940,6 +2940,10 @@ const translations = { payingReportSubtitle: 'The company and employee bank accounts use different currencies.', getStarted: 'Get started', }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Pay with x${lastFour}` : 'Pay with bank account'), + description: 'These reports weren’t paid with the bank account because they require global reimbursements. Get started with the process below.', + }, wiseGlobalReimbursementsBanner: { title: 'Pay people worldwide', subtitle: 'Enable global reimbursements on your USD account.', diff --git a/src/libs/actions/App.ts b/src/libs/actions/App.ts index 3b3ca7375fa7..b840c4ab22e4 100644 --- a/src/libs/actions/App.ts +++ b/src/libs/actions/App.ts @@ -698,6 +698,13 @@ function showSupportalPermissionDenied(payload: OnyxTypes.SupportalPermissionDen Onyx.set(ONYXKEYS.SUPPORTAL_PERMISSION_DENIED, payload); } +/** + * Opens the global reimbursements onboarding for the given bank account, the same way a rejected pay attempt does. + */ +function showEnableGlobalReimbursementsModal(modalData: OnyxTypes.EnableGlobalReimbursementsModal) { + Onyx.set(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, modalData); +} + /** * Clears the enable global reimbursements modal signal for the current session. */ @@ -723,6 +730,7 @@ export { clearOnyxAndResetApp, clearSupportalPermissionDenied, showSupportalPermissionDenied, + showEnableGlobalReimbursementsModal, clearEnableGlobalReimbursementsModal, setPreservedUserSession, getNonOptimisticPolicyIDs, diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 1754f20ba513..8c727c62b8b3 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -1,18 +1,23 @@ import {act, renderHook, waitFor} from '@testing-library/react-native'; import type {DropdownOption} from '@components/ButtonWithDropdownMenu/types'; +import {ModalActions} from '@components/Modal/Global/ModalContext'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; import type {SearchQueryJSON, SelectedReports, SelectedTransactions} from '@components/Search/types'; import useSearchBulkActions from '@hooks/useSearchBulkActions'; import type {SearchHeaderOptionValue} from '@hooks/useSearchBulkActions'; -import {payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest'; +import {showEnableGlobalReimbursementsModal} from '@libs/actions/App'; +import {getBankAccountToSetUpBeforePaying, payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest'; import {getLastPolicyPaymentMethod, queueBulkPayReports} from '@libs/actions/Search'; import type * as SearchActions from '@libs/actions/Search'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {BankAccount} from '@src/types/onyx'; + +import type {ValueOf} from 'type-fest'; import Onyx from 'react-native-onyx'; @@ -21,6 +26,10 @@ import Onyx from 'react-native-onyx'; let mockShouldEnableBulkPayOption = true; let mockBulkPayButtonOptions: Array> = [{text: 'Pay with bank account', key: CONST.IOU.PAYMENT_TYPE.VBBA}]; +jest.mock('@libs/actions/App', () => ({ + showEnableGlobalReimbursementsModal: jest.fn(), +})); + jest.mock('@libs/actions/IOU/PayMoneyRequest', () => ({ payMoneyRequest: jest.fn(), payInvoice: jest.fn(), @@ -103,7 +112,7 @@ jest.mock('@libs/Navigation/Navigation', () => ({ jest.mock('@hooks/useLocalize', () => ({ __esModule: true, default: () => ({ - translate: (key: string) => key, + translate: (key: string, ...params: unknown[]) => (key === 'walletPage.wiseGlobalReimbursementsBulkPayModal.title' ? `${key}(${params.join(',')})` : key), localeCompare: (first: string, second: string) => first && second, formatPhoneNumber: (phone: string) => phone, }), @@ -141,9 +150,10 @@ jest.mock('@components/DelegateNoAccessModalProvider', () => ({ useDelegateNoAccessActions: () => ({showDelegateNoAccessModal: jest.fn()}), })); +const mockShowConfirmModal = jest.fn((): Promise<{action: ValueOf}> => Promise.resolve({action: ModalActions.CLOSE})); jest.mock('@hooks/useConfirmModal', () => ({ __esModule: true, - default: () => ({showConfirmModal: jest.fn()}), + default: () => ({showConfirmModal: mockShowConfirmModal}), })); jest.mock('@hooks/usePermissions', () => ({ @@ -661,3 +671,188 @@ describe('useSearchBulkActions - bulk pay chat report fallback', () => { expect(mockLogInfo).toHaveBeenCalledWith('[BulkPay] Bulk pay finished with skipped reports', false, {paidReportCount: 0, selectedCount: 1}); }); }); + +describe('useSearchBulkActions - bulk pay with reports that need global reimbursements', () => { + const BANK_ACCOUNT_ID = 99; + const bankAccount: BankAccount = { + accountData: {bankAccountID: BANK_ACCOUNT_ID, accountNumber: 'XXXXXX1234'}, + bankCountry: 'US', + bankCurrency: CONST.CURRENCY.USD, + }; + + const OTHER_BANK_ACCOUNT_ID = 77; + const otherBankAccount: BankAccount = { + accountData: {bankAccountID: OTHER_BANK_ACCOUNT_ID, accountNumber: 'XXXXXX5678'}, + bankCountry: 'US', + bankCurrency: CONST.CURRENCY.USD, + }; + + function makePayableReport(reportID: string, chatReportID: string, policyID = 'policy1'): SelectedReports { + return makeSelectedReport({reportID, chatReportID, policyID}); + } + + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + mockIsOffline = false; + mockShouldEnableBulkPayOption = true; + mockBulkPayButtonOptions = [{text: 'Pay with bank account', key: CONST.IOU.PAYMENT_TYPE.VBBA}]; + mockAreAllMatchingItemsSelected = false; + mockSelectedTransactions = {tx1: makeSelectedTransaction()}; + mockSelectedReports = [makePayableReport('1', '2'), makePayableReport('3', '4')]; + jest.mocked(getLastPolicyPaymentMethod).mockReturnValue(CONST.IOU.PAYMENT_TYPE.VBBA); + + await Onyx.merge(ONYXKEYS.SESSION, {accountID: CURRENT_USER_ACCOUNT_ID, email: 'test@example.com'}); + await Onyx.merge(ONYXKEYS.BANK_ACCOUNT_LIST, {[BANK_ACCOUNT_ID]: bankAccount}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}policy1`, {id: 'policy1', role: CONST.POLICY.ROLE.ADMIN, achAccount: {bankAccountID: BANK_ACCOUNT_ID}}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {reportID: '1', type: CONST.REPORT.TYPE.EXPENSE, chatReportID: '2', policyID: 'policy1', reportName: 'Report needing GR'}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}3`, {reportID: '3', type: CONST.REPORT.TYPE.EXPENSE, chatReportID: '4', policyID: 'policy1', reportName: 'Payable report'}); + }); + + afterEach(async () => { + await Onyx.clear(); + }); + + async function selectBulkPay() { + const {result} = renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider}); + await waitFor(() => { + expect(getPayOptionFromResult(result.current.headerButtonsOptions)).toBeDefined(); + }); + const payOption = getPayOptionFromResult(result.current.headerButtonsOptions); + await act(async () => { + await payOption?.onSelected?.(); + }); + } + + it('pays the other reports and lists the ones that need global reimbursements in a modal', async () => { + // Given two selected reports where only the first one would be rejected until the bank account is set up for global reimbursements + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then the check runs with the workspace bank account the payment would have used + expect(getBankAccountToSetUpBeforePaying).toHaveBeenCalledWith( + expect.objectContaining({paymentType: CONST.IOU.PAYMENT_TYPE.VBBA, methodID: BANK_ACCOUNT_ID, isWiseReimbursementsBetaEnabled: false}), + ); + + // And only the second report is paid, because paying the first one would fail on the backend + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); + + // And a single modal lists the skipped report, so the user knows which reports still need global reimbursements + expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'walletPage.wiseGlobalReimbursementsBulkPayModal.title(1234)', + prompt: `${CONST.DOT_SEPARATOR} Report needing GR`, + confirmText: 'walletPage.wiseGlobalReimbursementsIntro.getStarted', + }), + ); + }); + + it('opens the global reimbursements onboarding when the user picks Get started', async () => { + // Given a selected report whose payment needs global reimbursements and a user who confirms the modal + mockSelectedReports = [makePayableReport('1', '2')]; + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then nothing is paid and the selection stays, so the user can still act on these reports + expect(payMoneyRequest).not.toHaveBeenCalled(); + expect(mockClearSelectedTransactions).not.toHaveBeenCalled(); + + // And the onboarding signal is set for the paying bank account, so the existing intro flow takes over + await waitFor(() => { + expect(showEnableGlobalReimbursementsModal).toHaveBeenCalledWith({ + bankAccountID: BANK_ACCOUNT_ID, + bankCountry: 'US', + bankCurrency: CONST.CURRENCY.USD, + }); + }); + }); + + it('does not open the onboarding when the user picks Not now', async () => { + // Given a selected report whose payment needs global reimbursements and a user who dismisses the modal + mockSelectedReports = [makePayableReport('1', '2')]; + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then the onboarding stays closed, because the user chose to set it up later + await waitFor(() => { + expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); + }); + expect(showEnableGlobalReimbursementsModal).not.toHaveBeenCalled(); + }); + + it('lists only the reports of the bank account the modal sets up when several accounts need global reimbursements', async () => { + // Given two selected reports paid from two different workspace bank accounts that both need global reimbursements + mockSelectedReports = [makePayableReport('1', '2'), makePayableReport('3', '4', 'policy2')]; + await Onyx.merge(ONYXKEYS.BANK_ACCOUNT_LIST, {[OTHER_BANK_ACCOUNT_ID]: otherBankAccount}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}policy2`, {id: 'policy2', role: CONST.POLICY.ROLE.ADMIN, achAccount: {bankAccountID: OTHER_BANK_ACCOUNT_ID}}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}3`, {policyID: 'policy2'}); + jest.mocked(getBankAccountToSetUpBeforePaying).mockImplementation(({methodID}) => (methodID === OTHER_BANK_ACCOUNT_ID ? otherBankAccount : bankAccount)); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then both reports are checked against their own bank account + expect(getBankAccountToSetUpBeforePaying).toHaveBeenCalledWith(expect.objectContaining({methodID: BANK_ACCOUNT_ID})); + expect(getBankAccountToSetUpBeforePaying).toHaveBeenCalledWith(expect.objectContaining({methodID: OTHER_BANK_ACCOUNT_ID})); + + // And the modal names the first account and lists only its report, because Get started sets up that account alone + expect(payMoneyRequest).not.toHaveBeenCalled(); + expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'walletPage.wiseGlobalReimbursementsBulkPayModal.title(1234)', + prompt: `${CONST.DOT_SEPARATOR} Report needing GR`, + }), + ); + }); + + it('lists a report once when several of its expenses are selected', async () => { + // Given two selected expenses from the same report whose payment needs global reimbursements + mockSelectedReports = []; + mockSelectedTransactions = {tx1: makeSelectedTransaction({reportID: '1'}), tx2: makeSelectedTransaction({reportID: '1'})}; + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then the report appears once in the modal, because it is one report the user has to set up global reimbursements for + expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + }); + + it('falls back to a generic name for a skipped report without a name', async () => { + // Given a selected report without a name whose payment needs global reimbursements + mockSelectedReports = [makePayableReport('1', '2')]; + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {reportName: ''}); + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then the modal still lists the report, so the list is never empty + expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} common.report`})); + }); + + it('does not show the modal when no report needs global reimbursements', async () => { + // Given selected reports that can all be paid with the bank account + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(undefined); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then every report is paid and no modal interrupts the user + expect(payMoneyRequest).toHaveBeenCalledTimes(2); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + }); +}); From 973c14c76c01663d6111941ca0d99abd0c85f1da Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Wed, 28 Oct 2026 15:35:06 +0100 Subject: [PATCH 02/20] Open global reimbursements intro directly when bulk pay pays nothing --- src/ROUTES.ts | 7 +- .../EnableGlobalReimbursementsPayModal.tsx | 4 +- src/hooks/useSearchBulkActions.ts | 14 ++-- src/languages/en.ts | 1 + ...ableGlobalReimbursementsNavigationUtils.ts | 4 +- .../paramLists/AccountSettingsParamList.ts | 1 + .../WiseGlobalReimbursementsIntroPage.tsx | 10 ++- .../onyx/EnableGlobalReimbursementsModal.ts | 2 + ...bleGlobalReimbursementsDynamicRouteTest.ts | 11 ++++ .../unit/hooks/useSearchBulkActionsPayTest.ts | 64 ++++++++++++++----- 10 files changed, 93 insertions(+), 25 deletions(-) diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 7eb28788940b..62f50824b89c 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -231,7 +231,12 @@ const DYNAMIC_ROUTES = { WISE_GLOBAL_REIMBURSEMENTS_INTRO: { path: 'global-reimbursements/:bankAccountID', entryScreens: ENABLE_GLOBAL_REIMBURSEMENTS_ENTRY_SCREENS, - getRoute: (bankAccountID: number | undefined) => `global-reimbursements/${bankAccountID}` as const, + getRoute: (bankAccountID: number | undefined, isPayingMultipleReports?: boolean) => + getUrlWithParams(`global-reimbursements/${bankAccountID}`, { + // Shows the copy for several reports when bulk pay could not pay any of them + isPayingMultipleReports: isPayingMultipleReports ? 'true' : undefined, + }), + queryParams: ['isPayingMultipleReports'], }, BANK_ACCOUNT_VERIFY_ACCOUNT: { path: 'verify-bank-account', diff --git a/src/components/EnableGlobalReimbursementsPayModal.tsx b/src/components/EnableGlobalReimbursementsPayModal.tsx index ca4b43a45d88..cf149034979f 100644 --- a/src/components/EnableGlobalReimbursementsPayModal.tsx +++ b/src/components/EnableGlobalReimbursementsPayModal.tsx @@ -37,7 +37,9 @@ function EnableGlobalReimbursementsPayModal() { if (isAccountLocked) { showLockedAccountModal(); } else { - Navigation.navigate(getWiseGlobalReimbursementsIntroNavigationRoute(modalData.bankAccountID, navigationPathAtSignal), {skipMatchingFullScreenRoute: true}); + Navigation.navigate(getWiseGlobalReimbursementsIntroNavigationRoute(modalData.bankAccountID, navigationPathAtSignal, modalData.isPayingMultipleReports), { + skipMatchingFullScreenRoute: true, + }); } clearEnableGlobalReimbursementsModal(); return; diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 037ccd36f90e..079bd26046b3 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1986,6 +1986,14 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { } if (firstSkippedBankAccount) { const [bankAccountID, {bankAccount, reportNames}] = firstSkippedBankAccount; + const globalReimbursementsModalData = {bankAccountID, bankCountry: bankAccount.bankCountry, bankCurrency: bankAccount.bankCurrency}; + + // Nothing was paid, so there is nothing to list next to the skipped reports. Open the intro directly, the same way paying a single report does + if (paidReportCount === 0 && otherSkippedBankAccounts.length === 0) { + showEnableGlobalReimbursementsModal({...globalReimbursementsModalData, isPayingMultipleReports: reportNames.size > 1}); + return; + } + deferModalPresentationAfterPopoverDismiss(() => { showConfirmModal({ title: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.title', getLastFourDigits(bankAccount.accountData?.accountNumber ?? '')), @@ -1998,11 +2006,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { if (result.action !== ModalActions.CONFIRM) { return; } - showEnableGlobalReimbursementsModal({ - bankAccountID, - bankCountry: bankAccount.bankCountry, - bankCurrency: bankAccount.bankCurrency, - }); + showEnableGlobalReimbursementsModal(globalReimbursementsModalData); }); }); } diff --git a/src/languages/en.ts b/src/languages/en.ts index cb4ca39e0683..2f845b47b7b8 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -2940,6 +2940,7 @@ const translations = { title: 'Set up global reimbursements?', subtitle: 'Pay members worldwide in their local currency.', payingReportSubtitle: 'The company and employee bank accounts use different currencies.', + payingMultipleReportsSubtitle: 'None of these reports could be paid because the company and employee bank accounts use different currencies.', getStarted: 'Get started', }, wiseGlobalReimbursementsBulkPayModal: { diff --git a/src/libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils.ts b/src/libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils.ts index b772ce560076..2cd1ba6fe0f0 100644 --- a/src/libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils.ts +++ b/src/libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils.ts @@ -97,9 +97,9 @@ function getEnableGlobalReimbursementsBusinessNavigationRoute( return ROUTES.SETTINGS_WALLET_ENABLE_GLOBAL_REIMBURSEMENTS_BUSINESS.getRoute(bankAccountID, subPage, undefined, params); } -function getWiseGlobalReimbursementsIntroNavigationRoute(bankAccountID: number, navigationPathAtSignal?: string): Route { +function getWiseGlobalReimbursementsIntroNavigationRoute(bankAccountID: number, navigationPathAtSignal?: string, isPayingMultipleReports?: boolean): Route { const basePath = navigationPathAtSignal ? getDynamicBasePathFromNavigationPath(navigationPathAtSignal) : undefined; - const introRoute = DYNAMIC_ROUTES.WISE_GLOBAL_REIMBURSEMENTS_INTRO.getRoute(bankAccountID); + const introRoute = DYNAMIC_ROUTES.WISE_GLOBAL_REIMBURSEMENTS_INTRO.getRoute(bankAccountID, isPayingMultipleReports); if (basePath && shouldUseDynamicEnableGlobalReimbursementsBase(basePath, WISE_GLOBAL_REIMBURSEMENTS_INTRO_ENTRY_SCREENS)) { return createDynamicRoute(introRoute, basePath); diff --git a/src/libs/Navigation/paramLists/AccountSettingsParamList.ts b/src/libs/Navigation/paramLists/AccountSettingsParamList.ts index cec98c13ad20..e276fab8cfc7 100644 --- a/src/libs/Navigation/paramLists/AccountSettingsParamList.ts +++ b/src/libs/Navigation/paramLists/AccountSettingsParamList.ts @@ -183,6 +183,7 @@ type AccountSettingsParamList = { }; [SCREENS.SETTINGS.WALLET.DYNAMIC_WISE_GLOBAL_REIMBURSEMENTS_INTRO]: { bankAccountID: string; + isPayingMultipleReports?: string; }; [SCREENS.SETTINGS.WALLET.EDIT_BANK_ACCOUNT_NICKNAME]: { bankAccountID: string; diff --git a/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx b/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx index f054840677bc..2a0664b5fe5f 100644 --- a/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx +++ b/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx @@ -31,12 +31,20 @@ import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import React, {useEffect} from 'react'; +function getSubtitleTranslationKey(isPayingReport: boolean, isPayingMultipleReports: boolean) { + if (isPayingMultipleReports) { + return 'walletPage.wiseGlobalReimbursementsIntro.payingMultipleReportsSubtitle'; + } + return isPayingReport ? 'walletPage.wiseGlobalReimbursementsIntro.payingReportSubtitle' : 'walletPage.wiseGlobalReimbursementsIntro.subtitle'; +} + type WiseGlobalReimbursementsIntroPageProps = PlatformStackScreenProps; function WiseGlobalReimbursementsIntroPage({route}: WiseGlobalReimbursementsIntroPageProps) { const bankAccountID = Number(route.params.bankAccountID); const backPath = useDynamicBackPath(DYNAMIC_ROUTES.WISE_GLOBAL_REIMBURSEMENTS_INTRO.path); const isPayingReport = isWiseGlobalReimbursementsIntroOverPayReportScreen(backPath); + const isPayingMultipleReports = route.params.isPayingMultipleReports === 'true'; const [bankAccountList, bankAccountListMetadata] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const [isLoadingPaymentMethods = true] = useOnyx(ONYXKEYS.IS_LOADING_PAYMENT_METHODS); const bankAccount = bankAccountList?.[bankAccountID]; @@ -83,7 +91,7 @@ function WiseGlobalReimbursementsIntroPage({route}: WiseGlobalReimbursementsIntr /> {translate('walletPage.wiseGlobalReimbursementsIntro.title')} - {translate(isPayingReport ? 'walletPage.wiseGlobalReimbursementsIntro.payingReportSubtitle' : 'walletPage.wiseGlobalReimbursementsIntro.subtitle')} + {translate(getSubtitleTranslationKey(isPayingReport, isPayingMultipleReports))} diff --git a/src/types/onyx/EnableGlobalReimbursementsModal.ts b/src/types/onyx/EnableGlobalReimbursementsModal.ts index c83cea15904b..cde236c98368 100644 --- a/src/types/onyx/EnableGlobalReimbursementsModal.ts +++ b/src/types/onyx/EnableGlobalReimbursementsModal.ts @@ -6,6 +6,8 @@ type EnableGlobalReimbursementsModal = { bankCountry: string; /** The currency of the VBBA, sent so the client can render the business form without an extra BANK_ACCOUNT_LIST lookup */ bankCurrency: string; + /** Whether bulk pay could not pay any of several selected reports, set only by the client so the intro explains it for all of them */ + isPayingMultipleReports?: boolean; }; export default EnableGlobalReimbursementsModal; diff --git a/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts b/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts index 92ca83b8a191..ef2c7b2737f8 100644 --- a/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts +++ b/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts @@ -114,6 +114,17 @@ describe('Enable global reimbursements dynamic routes', () => { expect(route).toBe('r/123/global-reimbursements/456'); }); + it('keeps the multiple reports flag on the intro opened by bulk pay', () => { + // Given bulk pay could not pay any of the selected reports on the search root + const signalPath = 'search'; + + // When the intro route is built for several reports + const route = getWiseGlobalReimbursementsIntroNavigationRoute(456, signalPath, true); + + // Then the intro is nested over search and carries the flag, so it shows the copy for several reports + expect(route).toBe('search/global-reimbursements/456?isPayingMultipleReports=true'); + }); + it('falls back to the wallet when the signal arrives on an unsupported screen', () => { // Given the admin navigated to a screen that is not an intro entry screen const signalPath = 'settings/preferences'; diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 8c727c62b8b3..ca04ab1af79d 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -755,17 +755,16 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('opens the global reimbursements onboarding when the user picks Get started', async () => { - // Given a selected report whose payment needs global reimbursements and a user who confirms the modal - mockSelectedReports = [makePayableReport('1', '2')]; - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + // Given one selected report whose payment needs global reimbursements next to a payable one, and a user who confirms the modal + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); // When the user selects bulk Pay await selectBulkPay(); - // Then nothing is paid and the selection stays, so the user can still act on these reports - expect(payMoneyRequest).not.toHaveBeenCalled(); - expect(mockClearSelectedTransactions).not.toHaveBeenCalled(); + // Then only the payable report is paid + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); // And the onboarding signal is set for the paying bank account, so the existing intro flow takes over await waitFor(() => { @@ -778,9 +777,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('does not open the onboarding when the user picks Not now', async () => { - // Given a selected report whose payment needs global reimbursements and a user who dismisses the modal - mockSelectedReports = [makePayableReport('1', '2')]; - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + // Given one selected report whose payment needs global reimbursements next to a payable one, and a user who dismisses the modal + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); // When the user selects bulk Pay await selectBulkPay(); @@ -819,10 +817,10 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('lists a report once when several of its expenses are selected', async () => { - // Given two selected expenses from the same report whose payment needs global reimbursements + // Given two selected expenses from a report whose payment needs global reimbursements, and one expense from a payable report mockSelectedReports = []; - mockSelectedTransactions = {tx1: makeSelectedTransaction({reportID: '1'}), tx2: makeSelectedTransaction({reportID: '1'})}; - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + mockSelectedTransactions = {tx1: makeSelectedTransaction({reportID: '1'}), tx2: makeSelectedTransaction({reportID: '1'}), tx3: makeSelectedTransaction({reportID: '3'})}; + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); // When the user selects bulk Pay await selectBulkPay(); @@ -832,10 +830,9 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('falls back to a generic name for a skipped report without a name', async () => { - // Given a selected report without a name whose payment needs global reimbursements - mockSelectedReports = [makePayableReport('1', '2')]; + // Given a selected report without a name whose payment needs global reimbursements, next to a payable one await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {reportName: ''}); - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); // When the user selects bulk Pay await selectBulkPay(); @@ -844,6 +841,43 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} common.report`})); }); + it('opens the onboarding directly when the only selected report needs global reimbursements', async () => { + // Given a single selected report whose payment needs global reimbursements + mockSelectedReports = [makePayableReport('1', '2')]; + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then nothing is paid and the selection stays, so the user can pay the report after the setup + expect(payMoneyRequest).not.toHaveBeenCalled(); + expect(mockClearSelectedTransactions).not.toHaveBeenCalled(); + + // And the onboarding opens without the modal, the same way paying a single report does, with the copy for one report + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(showEnableGlobalReimbursementsModal).toHaveBeenCalledWith({ + bankAccountID: BANK_ACCOUNT_ID, + bankCountry: 'US', + bankCurrency: CONST.CURRENCY.USD, + isPayingMultipleReports: false, + }); + }); + + it('opens the onboarding directly with the copy for several reports when none of them can be paid', async () => { + // Given two selected reports paid from the same bank account that needs global reimbursements + jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then nothing is paid and the onboarding opens without the modal, because there are no paid reports to report on + expect(payMoneyRequest).not.toHaveBeenCalled(); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + + // And the onboarding explains that all the selected reports need it + expect(showEnableGlobalReimbursementsModal).toHaveBeenCalledWith(expect.objectContaining({bankAccountID: BANK_ACCOUNT_ID, isPayingMultipleReports: true})); + }); + it('does not show the modal when no report needs global reimbursements', async () => { // Given selected reports that can all be paid with the bank account jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(undefined); From 05419036c2da6c10fccd7f4b6e2dcb7cf9d4526a Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 29 Oct 2026 16:28:07 +0100 Subject: [PATCH 03/20] Test bulk pay global reimbursements with real bank account data --- .../unit/hooks/useSearchBulkActionsPayTest.ts | 157 ++++++++++-------- 1 file changed, 85 insertions(+), 72 deletions(-) diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index ca04ab1af79d..8c95fb7f3d42 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -8,8 +8,8 @@ import type {SearchQueryJSON, SelectedReports, SelectedTransactions} from '@comp import useSearchBulkActions from '@hooks/useSearchBulkActions'; import type {SearchHeaderOptionValue} from '@hooks/useSearchBulkActions'; -import {showEnableGlobalReimbursementsModal} from '@libs/actions/App'; -import {getBankAccountToSetUpBeforePaying, payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest'; +import {payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest'; +import type * as PayMoneyRequestActions from '@libs/actions/IOU/PayMoneyRequest'; import {getLastPolicyPaymentMethod, queueBulkPayReports} from '@libs/actions/Search'; import type * as SearchActions from '@libs/actions/Search'; @@ -21,19 +21,18 @@ import type {ValueOf} from 'type-fest'; import Onyx from 'react-native-onyx'; +import getOnyxValue from '../../utils/getOnyxValue'; + // The Pay option is shown only when getPayOption enables it and useBulkPayOptions returns at least one payment option. // Both are driven from these module-level flags so each test can toggle them independently. let mockShouldEnableBulkPayOption = true; let mockBulkPayButtonOptions: Array> = [{text: 'Pay with bank account', key: CONST.IOU.PAYMENT_TYPE.VBBA}]; -jest.mock('@libs/actions/App', () => ({ - showEnableGlobalReimbursementsModal: jest.fn(), -})); - +// The real check runs so the tests cover the beta gate and the bank account rules, not just the modal jest.mock('@libs/actions/IOU/PayMoneyRequest', () => ({ payMoneyRequest: jest.fn(), payInvoice: jest.fn(), - getBankAccountToSetUpBeforePaying: jest.fn(), + getBankAccountToSetUpBeforePaying: jest.requireActual('@libs/actions/IOU/PayMoneyRequest').getBankAccountToSetUpBeforePaying, })); // On iOS the offline modal is deferred until the payment popover finishes dismissing (via TransitionTracker), @@ -156,9 +155,10 @@ jest.mock('@hooks/useConfirmModal', () => ({ default: () => ({showConfirmModal: mockShowConfirmModal}), })); +let mockEnabledBetas = new Set(); jest.mock('@hooks/usePermissions', () => ({ __esModule: true, - default: () => ({isBetaEnabled: () => false, isBetaEnabledOrUnknown: () => false}), + default: () => ({isBetaEnabled: (beta: string) => mockEnabledBetas.has(beta), isBetaEnabledOrUnknown: (beta: string) => mockEnabledBetas.has(beta)}), })); jest.mock('@hooks/useSelfDMReport', () => ({ @@ -674,21 +674,29 @@ describe('useSearchBulkActions - bulk pay chat report fallback', () => { describe('useSearchBulkActions - bulk pay with reports that need global reimbursements', () => { const BANK_ACCOUNT_ID = 99; - const bankAccount: BankAccount = { - accountData: {bankAccountID: BANK_ACCOUNT_ID, accountNumber: 'XXXXXX1234'}, - bankCountry: 'US', - bankCurrency: CONST.CURRENCY.USD, - }; - + const ENABLED_BANK_ACCOUNT_ID = 88; const OTHER_BANK_ACCOUNT_ID = 77; - const otherBankAccount: BankAccount = { - accountData: {bankAccountID: OTHER_BANK_ACCOUNT_ID, accountNumber: 'XXXXXX5678'}, - bankCountry: 'US', - bankCurrency: CONST.CURRENCY.USD, - }; - function makePayableReport(reportID: string, chatReportID: string, policyID = 'policy1'): SelectedReports { - return makeSelectedReport({reportID, chatReportID, policyID}); + function makeBankAccount(bankAccountID: number, accountNumber: string, isGlobalReimbursementEnabled: boolean): BankAccount { + return { + accountData: { + bankAccountID, + accountNumber, + type: CONST.BANK_ACCOUNT.TYPE.BUSINESS, + state: CONST.BANK_ACCOUNT.STATE.OPEN, + additionalData: {currency: CONST.CURRENCY.USD, isGlobalReimbursementEnabled}, + }, + bankCountry: 'US', + bankCurrency: CONST.CURRENCY.USD, + }; + } + + async function seedPolicy(policyID: string, bankAccountID: number) { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {id: policyID, role: CONST.POLICY.ROLE.ADMIN, achAccount: {bankAccountID}}); + } + + async function seedReport(reportID: string, chatReportID: string, policyID: string, reportName: string) { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {reportID, type: CONST.REPORT.TYPE.EXPENSE, chatReportID, policyID, reportName}); } beforeAll(() => { @@ -701,18 +709,29 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs mockShouldEnableBulkPayOption = true; mockBulkPayButtonOptions = [{text: 'Pay with bank account', key: CONST.IOU.PAYMENT_TYPE.VBBA}]; mockAreAllMatchingItemsSelected = false; + mockEnabledBetas = new Set([CONST.BETAS.WISE_REIMBURSEMENTS]); mockSelectedTransactions = {tx1: makeSelectedTransaction()}; - mockSelectedReports = [makePayableReport('1', '2'), makePayableReport('3', '4')]; + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '3', chatReportID: '4', policyID: 'policy2'})]; jest.mocked(getLastPolicyPaymentMethod).mockReturnValue(CONST.IOU.PAYMENT_TYPE.VBBA); + // policy1 and policy3 pay from USD business accounts without global reimbursements, policy2 from one that already has them await Onyx.merge(ONYXKEYS.SESSION, {accountID: CURRENT_USER_ACCOUNT_ID, email: 'test@example.com'}); - await Onyx.merge(ONYXKEYS.BANK_ACCOUNT_LIST, {[BANK_ACCOUNT_ID]: bankAccount}); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}policy1`, {id: 'policy1', role: CONST.POLICY.ROLE.ADMIN, achAccount: {bankAccountID: BANK_ACCOUNT_ID}}); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {reportID: '1', type: CONST.REPORT.TYPE.EXPENSE, chatReportID: '2', policyID: 'policy1', reportName: 'Report needing GR'}); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}3`, {reportID: '3', type: CONST.REPORT.TYPE.EXPENSE, chatReportID: '4', policyID: 'policy1', reportName: 'Payable report'}); + await Onyx.merge(ONYXKEYS.BANK_ACCOUNT_LIST, { + [BANK_ACCOUNT_ID]: makeBankAccount(BANK_ACCOUNT_ID, 'XXXXXX1234', false), + [ENABLED_BANK_ACCOUNT_ID]: makeBankAccount(ENABLED_BANK_ACCOUNT_ID, 'XXXXXX9999', true), + [OTHER_BANK_ACCOUNT_ID]: makeBankAccount(OTHER_BANK_ACCOUNT_ID, 'XXXXXX5678', false), + }); + await seedPolicy('policy1', BANK_ACCOUNT_ID); + await seedPolicy('policy2', ENABLED_BANK_ACCOUNT_ID); + await seedPolicy('policy3', OTHER_BANK_ACCOUNT_ID); + await seedReport('1', '2', 'policy1', 'Report needing GR'); + await seedReport('3', '4', 'policy2', 'Payable report'); + await seedReport('5', '6', 'policy3', 'Other report needing GR'); + await seedReport('7', '8', 'policy1', 'Second report needing GR'); }); afterEach(async () => { + mockEnabledBetas = new Set(); await Onyx.clear(); }); @@ -728,18 +747,12 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs } it('pays the other reports and lists the ones that need global reimbursements in a modal', async () => { - // Given two selected reports where only the first one would be rejected until the bank account is set up for global reimbursements - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); + // Given one selected report paid from an account without global reimbursements and one paid from an account that has them // When the user selects bulk Pay await selectBulkPay(); - // Then the check runs with the workspace bank account the payment would have used - expect(getBankAccountToSetUpBeforePaying).toHaveBeenCalledWith( - expect.objectContaining({paymentType: CONST.IOU.PAYMENT_TYPE.VBBA, methodID: BANK_ACCOUNT_ID, isWiseReimbursementsBetaEnabled: false}), - ); - - // And only the second report is paid, because paying the first one would fail on the backend + // Then only the second report is paid, because the backend would reject paying the first one expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); @@ -754,21 +767,29 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs ); }); + it('pays every report and shows no modal when the global reimbursements beta is off', async () => { + // Given the same selection, but an admin without the global reimbursements beta + mockEnabledBetas = new Set(); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then bulk pay behaves as before the beta, leaving the final call to the backend + expect(payMoneyRequest).toHaveBeenCalledTimes(2); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); + }); + it('opens the global reimbursements onboarding when the user picks Get started', async () => { - // Given one selected report whose payment needs global reimbursements next to a payable one, and a user who confirms the modal - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); + // Given a mixed selection and a user who confirms the modal mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); // When the user selects bulk Pay await selectBulkPay(); - // Then only the payable report is paid - expect(payMoneyRequest).toHaveBeenCalledTimes(1); - expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); - - // And the onboarding signal is set for the paying bank account, so the existing intro flow takes over - await waitFor(() => { - expect(showEnableGlobalReimbursementsModal).toHaveBeenCalledWith({ + // Then the onboarding signal is set for the paying bank account, so the existing intro flow takes over + await waitFor(async () => { + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual({ bankAccountID: BANK_ACCOUNT_ID, bankCountry: 'US', bankCurrency: CONST.CURRENCY.USD, @@ -777,8 +798,7 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('does not open the onboarding when the user picks Not now', async () => { - // Given one selected report whose payment needs global reimbursements next to a payable one, and a user who dismisses the modal - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); + // Given a mixed selection and a user who dismisses the modal // When the user selects bulk Pay await selectBulkPay(); @@ -787,25 +807,17 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs await waitFor(() => { expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); }); - expect(showEnableGlobalReimbursementsModal).not.toHaveBeenCalled(); + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); }); it('lists only the reports of the bank account the modal sets up when several accounts need global reimbursements', async () => { - // Given two selected reports paid from two different workspace bank accounts that both need global reimbursements - mockSelectedReports = [makePayableReport('1', '2'), makePayableReport('3', '4', 'policy2')]; - await Onyx.merge(ONYXKEYS.BANK_ACCOUNT_LIST, {[OTHER_BANK_ACCOUNT_ID]: otherBankAccount}); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}policy2`, {id: 'policy2', role: CONST.POLICY.ROLE.ADMIN, achAccount: {bankAccountID: OTHER_BANK_ACCOUNT_ID}}); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}3`, {policyID: 'policy2'}); - jest.mocked(getBankAccountToSetUpBeforePaying).mockImplementation(({methodID}) => (methodID === OTHER_BANK_ACCOUNT_ID ? otherBankAccount : bankAccount)); + // Given two selected reports paid from two different bank accounts that both need global reimbursements + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '5', chatReportID: '6', policyID: 'policy3'})]; // When the user selects bulk Pay await selectBulkPay(); - // Then both reports are checked against their own bank account - expect(getBankAccountToSetUpBeforePaying).toHaveBeenCalledWith(expect.objectContaining({methodID: BANK_ACCOUNT_ID})); - expect(getBankAccountToSetUpBeforePaying).toHaveBeenCalledWith(expect.objectContaining({methodID: OTHER_BANK_ACCOUNT_ID})); - - // And the modal names the first account and lists only its report, because Get started sets up that account alone + // Then nothing is paid, and the modal names the first account and lists only its report, because Get started sets up that account alone expect(payMoneyRequest).not.toHaveBeenCalled(); expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); expect(mockShowConfirmModal).toHaveBeenCalledWith( @@ -817,10 +829,13 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('lists a report once when several of its expenses are selected', async () => { - // Given two selected expenses from a report whose payment needs global reimbursements, and one expense from a payable report + // Given two selected expenses from a report that needs global reimbursements, and one expense from a payable report mockSelectedReports = []; - mockSelectedTransactions = {tx1: makeSelectedTransaction({reportID: '1'}), tx2: makeSelectedTransaction({reportID: '1'}), tx3: makeSelectedTransaction({reportID: '3'})}; - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); + mockSelectedTransactions = { + tx1: makeSelectedTransaction({reportID: '1'}), + tx2: makeSelectedTransaction({reportID: '1'}), + tx3: makeSelectedTransaction({reportID: '3', policyID: 'policy2'}), + }; // When the user selects bulk Pay await selectBulkPay(); @@ -830,9 +845,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('falls back to a generic name for a skipped report without a name', async () => { - // Given a selected report without a name whose payment needs global reimbursements, next to a payable one + // Given a skipped report without a name, next to a payable one await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {reportName: ''}); - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValueOnce(bankAccount).mockReturnValue(undefined); // When the user selects bulk Pay await selectBulkPay(); @@ -842,9 +856,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); it('opens the onboarding directly when the only selected report needs global reimbursements', async () => { - // Given a single selected report whose payment needs global reimbursements - mockSelectedReports = [makePayableReport('1', '2')]; - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + // Given a single selected report that needs global reimbursements + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'})]; // When the user selects bulk Pay await selectBulkPay(); @@ -855,7 +868,7 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // And the onboarding opens without the modal, the same way paying a single report does, with the copy for one report expect(mockShowConfirmModal).not.toHaveBeenCalled(); - expect(showEnableGlobalReimbursementsModal).toHaveBeenCalledWith({ + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual({ bankAccountID: BANK_ACCOUNT_ID, bankCountry: 'US', bankCurrency: CONST.CURRENCY.USD, @@ -865,7 +878,7 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs it('opens the onboarding directly with the copy for several reports when none of them can be paid', async () => { // Given two selected reports paid from the same bank account that needs global reimbursements - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(bankAccount); + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '7', chatReportID: '8'})]; // When the user selects bulk Pay await selectBulkPay(); @@ -875,18 +888,18 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(mockShowConfirmModal).not.toHaveBeenCalled(); // And the onboarding explains that all the selected reports need it - expect(showEnableGlobalReimbursementsModal).toHaveBeenCalledWith(expect.objectContaining({bankAccountID: BANK_ACCOUNT_ID, isPayingMultipleReports: true})); + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual(expect.objectContaining({bankAccountID: BANK_ACCOUNT_ID, isPayingMultipleReports: true})); }); it('does not show the modal when no report needs global reimbursements', async () => { - // Given selected reports that can all be paid with the bank account - jest.mocked(getBankAccountToSetUpBeforePaying).mockReturnValue(undefined); + // Given a selected report paid from an account that already has global reimbursements + mockSelectedReports = [makeSelectedReport({reportID: '3', chatReportID: '4', policyID: 'policy2'})]; // When the user selects bulk Pay await selectBulkPay(); - // Then every report is paid and no modal interrupts the user - expect(payMoneyRequest).toHaveBeenCalledTimes(2); + // Then the report is paid and no modal interrupts the user + expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(mockShowConfirmModal).not.toHaveBeenCalled(); }); }); From 7965b10d61d067b0327bf27e5b18ed0008b813b3 Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 29 Oct 2026 16:30:03 +0100 Subject: [PATCH 04/20] Add empty line before global reimbursements skip check --- src/hooks/useSearchBulkActions.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 079bd26046b3..c29586af1b03 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1926,6 +1926,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { bankAccountList, isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), }); + if (methodID && bankAccountToSetUp) { const skippedReports = reportsNeedingGlobalReimbursementsByBankAccount.get(methodID) ?? {bankAccount: bankAccountToSetUp, reportNames: new Map()}; // Keyed by reportID because selecting several expenses of one report yields one item per expense From ea52bc6a5a3396c99e17c1c5e7d6a1e838c476db Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 29 Oct 2026 16:35:24 +0100 Subject: [PATCH 05/20] Reuse payable report IDs for bulk pay report names --- src/hooks/useSearchBulkActions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index c29586af1b03..9eb6e1c0248a 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -822,8 +822,8 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const payableSelectedReports = useMemo(() => selectedReports.filter((report) => report.canPay), [selectedReports]); const payableSelectedReportIDs = useMemo(() => payableSelectedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payableSelectedReports]); const payScopedReports = useMemo(() => (payableSelectedReports.length > 0 ? payableSelectedReports : selectedReports), [payableSelectedReports, selectedReports]); - // Names of the selected reports, so bulk pay can list the reports it skipped the same way Search shows them - const selectedReportNames = useDerivedReportNamesByReportIDs(selectedReports.length > 0 ? payableSelectedReports.map((report) => report.reportID) : selectedTransactionReportIDs); + // Names of the reports bulk pay goes through, picked the same way as its items, so it can list the reports it skipped the same way Search shows them + const selectedReportNames = useDerivedReportNamesByReportIDs(selectedReports.length > 0 ? payableSelectedReportIDs : selectedTransactionReportIDs); const payScopedReportIDs = useMemo(() => payScopedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payScopedReports]); From f58015f01901b40a74124433b894fa0075ad9d45 Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 19:36:28 +0100 Subject: [PATCH 06/20] Skip only reports the backend flags for global reimbursements in bulk pay Read nextStep.requiresGlobalReimbursement from the report row instead of judging by the paying bank account alone, so reports paid to domestic accounts go through. --- src/hooks/useSearchBulkActions.ts | 1 + src/libs/DebugUtils.ts | 2 ++ src/libs/actions/IOU/PayMoneyRequest.ts | 8 +++-- src/types/onyx/Report.ts | 6 ++++ tests/actions/IOUTest/PayMoneyRequestTest.ts | 14 ++++---- .../unit/hooks/useSearchBulkActionsPayTest.ts | 36 +++++++++++++++---- 6 files changed, 52 insertions(+), 15 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 9eb6e1c0248a..0dd53480879e 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1922,6 +1922,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { // The backend rejects this payment until the account is set up for global reimbursements, so keep the report unpaid and list it in the modal after the loop const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({ paymentType: paymentItem.paymentType as PaymentMethodType, + iouReport, methodID, bankAccountList, isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), diff --git a/src/libs/DebugUtils.ts b/src/libs/DebugUtils.ts index 1d54b0e5a9f5..bce497e2ba6c 100644 --- a/src/libs/DebugUtils.ts +++ b/src/libs/DebugUtils.ts @@ -595,6 +595,8 @@ function validateReportDraftProperty(key: keyof Report | keyof ReportNameValuePa eta: 'object', iconFill: 'string', requiredDepositCurrency: 'string', + requiresGlobalReimbursement: 'boolean', + depositCurrency: 'string', }); case 'tripData': return validateObject>(value, { diff --git a/src/libs/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index e4987ed0b9e7..3d0c1e3065d9 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -880,14 +880,16 @@ function completePaymentOnboarding( /** * Returns the paying bank account when the payment must wait for global reimbursements onboarding, so payMoneyRequest opens the onboarding instead of paying. + * The backend flags the reports that go through global reimbursements on their waiting-to-pay next step, because only it knows the submitter's deposit account. */ function getBankAccountToSetUpBeforePaying({ paymentType, + iouReport, methodID, bankAccountList, isWiseReimbursementsBetaEnabled, -}: Pick): OnyxTypes.BankAccount | undefined { - if (!isWiseReimbursementsBetaEnabled || paymentType !== CONST.IOU.PAYMENT_TYPE.VBBA || !methodID) { +}: Pick): OnyxTypes.BankAccount | undefined { + if (!isWiseReimbursementsBetaEnabled || paymentType !== CONST.IOU.PAYMENT_TYPE.VBBA || !methodID || !iouReport?.nextStep?.requiresGlobalReimbursement) { return undefined; } const bankAccount = bankAccountList?.[methodID]; @@ -938,7 +940,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { } // The backend rejects this payment until the account is set up for global reimbursements, so open the onboarding right away instead of showing an optimistic payment - const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({paymentType, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); + const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({paymentType, iouReport, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); if (methodID && bankAccountToSetUp) { Onyx.set(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, { bankAccountID: methodID, diff --git a/src/types/onyx/Report.ts b/src/types/onyx/Report.ts index 2b8060efbab8..67be5870668b 100644 --- a/src/types/onyx/Report.ts +++ b/src/types/onyx/Report.ts @@ -72,6 +72,12 @@ type ReportNextStep = { /** Currency the submitter's deposit account must use for direct reimbursement, named in the waitingForSubmitterAccount copy */ requiredDepositCurrency?: string; + + /** Whether paying this report goes through global reimbursements, sent only on a waiting-to-pay step */ + requiresGlobalReimbursement?: boolean; + + /** Currency of the submitter's deposit account, sent only on a waiting-to-pay step */ + depositCurrency?: string; }; /** Model of report data */ diff --git a/tests/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index 608421b8431b..778bf7b1dc88 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -3006,7 +3006,7 @@ describe('actions/IOU/PayMoneyRequest', () => { }; } - function payWithBusinessBankAccount(bankAccountList: BankAccountList, isWiseReimbursementsBetaEnabled: boolean) { + function payWithBusinessBankAccount(bankAccountList: BankAccountList, isWiseReimbursementsBetaEnabled: boolean, requiresGlobalReimbursement = true) { const chatReport = { ...createRandomReport(0, undefined), type: CONST.REPORT.TYPE.CHAT, @@ -3018,6 +3018,7 @@ describe('actions/IOU/PayMoneyRequest', () => { chatReportID: chatReport.reportID, total: -100, currency: CONST.CURRENCY.USD, + nextStep: {messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_PAY, icon: CONST.NEXT_STEP.ICONS.HOURGLASS, requiresGlobalReimbursement}, }; payMoneyRequest({ @@ -3046,7 +3047,7 @@ describe('actions/IOU/PayMoneyRequest', () => { } it('opens the onboarding instead of paying when the business bank account is not set up for global reimbursements', async () => { - // Given an admin in the Wise beta paying from a USD business account that has not enabled global reimbursements + // Given an admin in the Wise beta paying a report the backend flags for global reimbursements from a USD business account that has not enabled them const writeSpy = jest.spyOn(APIActions, 'write'); // When they pay a report with it @@ -3063,14 +3064,15 @@ describe('actions/IOU/PayMoneyRequest', () => { }); it.each([ - ['the admin is not in the Wise beta', false, false], - ['the account already has global reimbursements enabled', true, true], - ])('pays as usual when %s', async (_label, isWiseReimbursementsBetaEnabled, isGlobalReimbursementEnabled) => { + ['the admin is not in the Wise beta', false, false, true], + ['the account already has global reimbursements enabled', true, true, true], + ['the backend does not flag the report for global reimbursements', true, false, false], + ])('pays as usual when %s', async (_label, isWiseReimbursementsBetaEnabled, isGlobalReimbursementEnabled, requiresGlobalReimbursement) => { // Given an admin whose payment the backend accepts from this account const writeSpy = jest.spyOn(APIActions, 'write'); // When they pay a report with it - payWithBusinessBankAccount(buildBankAccountList(isGlobalReimbursementEnabled), isWiseReimbursementsBetaEnabled); + payWithBusinessBankAccount(buildBankAccountList(isGlobalReimbursementEnabled), isWiseReimbursementsBetaEnabled, requiresGlobalReimbursement); await waitForBatchedUpdates(); // Then the payment is sent and no onboarding opens diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 8c95fb7f3d42..76ac3ba1bc09 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -695,8 +695,15 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {id: policyID, role: CONST.POLICY.ROLE.ADMIN, achAccount: {bankAccountID}}); } - async function seedReport(reportID: string, chatReportID: string, policyID: string, reportName: string) { - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {reportID, type: CONST.REPORT.TYPE.EXPENSE, chatReportID, policyID, reportName}); + async function seedReport(reportID: string, chatReportID: string, policyID: string, reportName: string, requiresGlobalReimbursement: boolean) { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, { + reportID, + type: CONST.REPORT.TYPE.EXPENSE, + chatReportID, + policyID, + reportName, + nextStep: {messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_PAY, icon: CONST.NEXT_STEP.ICONS.HOURGLASS, requiresGlobalReimbursement}, + }); } beforeAll(() => { @@ -724,10 +731,12 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs await seedPolicy('policy1', BANK_ACCOUNT_ID); await seedPolicy('policy2', ENABLED_BANK_ACCOUNT_ID); await seedPolicy('policy3', OTHER_BANK_ACCOUNT_ID); - await seedReport('1', '2', 'policy1', 'Report needing GR'); - await seedReport('3', '4', 'policy2', 'Payable report'); - await seedReport('5', '6', 'policy3', 'Other report needing GR'); - await seedReport('7', '8', 'policy1', 'Second report needing GR'); + // The backend flags the reports whose submitters are paid through global reimbursements, report 9 goes to a domestic account + await seedReport('1', '2', 'policy1', 'Report needing GR', true); + await seedReport('3', '4', 'policy2', 'Payable report', true); + await seedReport('5', '6', 'policy3', 'Other report needing GR', true); + await seedReport('7', '8', 'policy1', 'Second report needing GR', true); + await seedReport('9', '10', 'policy1', 'Domestic report', false); }); afterEach(async () => { @@ -780,6 +789,21 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); }); + it('pays a report the backend does not flag for global reimbursements, even from an account without them', async () => { + // Given two reports paid from the same account without global reimbursements, where only the first one goes to a submitter abroad + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '9', chatReportID: '10'})]; + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then the domestic report is paid, because only the flagged report would be rejected by the backend + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '9'})})); + + // And the modal lists only the flagged report + expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + }); + it('opens the global reimbursements onboarding when the user picks Get started', async () => { // Given a mixed selection and a user who confirms the modal mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); From e8b4628d5d79375436e3d48b3c7f3b8e0522ae06 Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 20:06:57 +0100 Subject: [PATCH 07/20] Add Spanish copy for the bulk pay global reimbursements modal --- src/languages/es.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/languages/es.ts b/src/languages/es.ts index ac2b51f02a8f..0a430511c961 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -2769,6 +2769,11 @@ const translations: TranslationDeepObject = { getStarted: 'Empieza', headerTitle: 'Reembolsos globales', payingReportSubtitle: 'Las cuentas bancarias de la empresa y del empleado usan monedas diferentes.', + payingMultipleReportsSubtitle: 'No se pudo pagar ninguno de estos informes porque las cuentas bancarias de la empresa y del empleado usan monedas diferentes.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Pagar con x${lastFour}` : 'Pagar con cuenta bancaria'), + description: 'Estos informes no se pagaron con la cuenta bancaria porque requieren reembolsos globales. Comienza el proceso a continuación.', }, wiseGlobalReimbursementsBanner: {title: 'Paga a personas de todo el mundo', subtitle: 'Habilita los reembolsos globales en tu cuenta en USD.'}, }, From 72041d8a58a2843d32cf8a88eba34083f47cb45b Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 20:07:23 +0100 Subject: [PATCH 08/20] Open the global reimbursements onboarding through its action in payMoneyRequest --- src/libs/actions/IOU/PayMoneyRequest.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/libs/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index 3d0c1e3065d9..628174febbab 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -31,6 +31,7 @@ import playSound, {SOUNDS} from '@libs/Sound'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import {shouldSplitScanFailedTransactions} from '@libs/TransactionUtils'; +import {showEnableGlobalReimbursementsModal} from '@userActions/App'; import {buildPolicyData, generatePolicyID} from '@userActions/Policy/Policy'; import type {BuildPolicyDataKeys} from '@userActions/Policy/Policy'; import {completeOnboarding} from '@userActions/Report'; @@ -942,11 +943,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { // The backend rejects this payment until the account is set up for global reimbursements, so open the onboarding right away instead of showing an optimistic payment const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({paymentType, iouReport, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); if (methodID && bankAccountToSetUp) { - Onyx.set(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, { - bankAccountID: methodID, - bankCountry: bankAccountToSetUp.bankCountry, - bankCurrency: bankAccountToSetUp.bankCurrency, - }); + showEnableGlobalReimbursementsModal({bankAccountID: methodID, bankCountry: bankAccountToSetUp.bankCountry, bankCurrency: bankAccountToSetUp.bankCurrency}); return; } From e8496e3f29ce566b7bda1bacf0a377070f7b0b2a Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 20:07:46 +0100 Subject: [PATCH 09/20] Name skipped bulk pay reports from the report row instead of subscribing to report attributes --- src/hooks/useSearchBulkActions.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 0dd53480879e..a3977621581b 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -183,7 +183,6 @@ import {useGetPersonalDetailsByLogin} from './usePersonalDetailByLogin'; import {useAllPersonalDetails} from './usePersonalDetails'; import usePersonalPolicy from './usePersonalPolicy'; import usePolicyForMovingExpenses from './usePolicyForMovingExpenses'; -import {useDerivedReportNamesByReportIDs} from './useReportAttributes'; import useReportPDFDownloadModal from './useReportPDFDownloadModal'; import useRestrictedActionPolicyID from './useRestrictedActionPolicyID'; import useSearchShouldCalculateTotals from './useSearchShouldCalculateTotals'; @@ -822,9 +821,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const payableSelectedReports = useMemo(() => selectedReports.filter((report) => report.canPay), [selectedReports]); const payableSelectedReportIDs = useMemo(() => payableSelectedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payableSelectedReports]); const payScopedReports = useMemo(() => (payableSelectedReports.length > 0 ? payableSelectedReports : selectedReports), [payableSelectedReports, selectedReports]); - // Names of the reports bulk pay goes through, picked the same way as its items, so it can list the reports it skipped the same way Search shows them - const selectedReportNames = useDerivedReportNamesByReportIDs(selectedReports.length > 0 ? payableSelectedReportIDs : selectedTransactionReportIDs); - const payScopedReportIDs = useMemo(() => payScopedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payScopedReports]); const isCurrencySupportedBulkWallet = isCurrencySupportWalletBulkPay(selectedReports, selectedTransactions); @@ -1931,7 +1927,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { if (methodID && bankAccountToSetUp) { const skippedReports = reportsNeedingGlobalReimbursementsByBankAccount.get(methodID) ?? {bankAccount: bankAccountToSetUp, reportNames: new Map()}; // Keyed by reportID because selecting several expenses of one report yields one item per expense - skippedReports.reportNames.set(item.reportID, getReportName(iouReport, selectedReportNames?.[item.reportID]) || translate('common.report')); + skippedReports.reportNames.set(item.reportID, getReportName(iouReport) || translate('common.report')); reportsNeedingGlobalReimbursementsByBankAccount.set(methodID, skippedReports); continue; } @@ -2060,7 +2056,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { rules, showConfirmModal, translate, - selectedReportNames, ], ); From 506f61104d557b2525df08dc9686e60400425a5b Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 20:08:06 +0100 Subject: [PATCH 10/20] Share the report name bullet list across bulk action modals --- src/hooks/useSearchBulkActions.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index a3977621581b..740b0321a4d0 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -630,6 +630,10 @@ function getChatReportForBulkPay( return getReportFromSearchSnapshot(resolvedChatReportID, searchData, allReports) ?? getReportOrDraftReport(resolvedChatReportID); } +function formatReportNamesAsBulletList(reportNames: Iterable): string { + return Array.from(reportNames, (reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'); +} + /** * A single export option. It is typed as a dropdown option rather than a plain menu item because it is rendered at * either level of the bulk-action dropdown: nested inside the Export submenu, or directly at the top level when @@ -1996,7 +2000,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { showConfirmModal({ title: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.title', getLastFourDigits(bankAccount.accountData?.accountNumber ?? '')), subtitle: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.description'), - prompt: [...reportNames.values()].map((reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'), + prompt: formatReportNamesAsBulletList(reportNames.values()), confirmText: translate('walletPage.wiseGlobalReimbursementsIntro.getStarted'), cancelText: translate('common.notNow'), shouldEnablePromptScroll: true, @@ -2436,7 +2440,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { connectionNameFriendly, reportName: '', }).trim(), - prompt: exportedReportNames.map((reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'), + prompt: formatReportNamesAsBulletList(exportedReportNames), confirmText: translate('workspace.exportAgainModal.confirmText'), cancelText: translate('workspace.exportAgainModal.cancelText'), shouldEnablePromptScroll: true, @@ -2469,7 +2473,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { integrationReportIDs.length < integrationGroupSize, connectionNameFriendly, ), - prompt: exportableReportNames.map((reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'), + prompt: formatReportNamesAsBulletList(exportableReportNames), confirmText: translate('workspace.exportPartialModal.confirmText', {count: integrationReportIDs.length}), cancelText: translate('workspace.exportPartialModal.cancelText'), shouldEnablePromptScroll: true, @@ -3120,7 +3124,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { showConfirmModalAfterMoreMenuDismiss(showConfirmModal, { title: translate(allReportsShouldMarkAsDone ? 'iou.error.reportsNotMarkedAsDoneTitle' : 'iou.error.reportsNotSubmittedTitle'), subtitle: translate(allReportsShouldMarkAsDone ? 'iou.error.reportsNotMarkedAsDoneDescription' : 'iou.error.reportsNotSubmittedDescription'), - prompt: blockedReportNames.map((reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'), + prompt: formatReportNamesAsBulletList(blockedReportNames), confirmText: translate('common.buttonConfirm'), shouldShowCancelButton: false, shouldEnablePromptScroll: true, From 0a4726d17ea6a31b3d4da7cc95292bfbb2974d17 Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 20:08:19 +0100 Subject: [PATCH 11/20] Assert bulk pay clears the selection after paying some reports --- tests/unit/hooks/useSearchBulkActionsPayTest.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 76ac3ba1bc09..12eac6652bd2 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -765,6 +765,9 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); + // And the selection is cleared, the same as after any bulk pay that paid at least one report + expect(mockClearSelectedTransactions).toHaveBeenCalledTimes(1); + // And a single modal lists the skipped report, so the user knows which reports still need global reimbursements expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); expect(mockShowConfirmModal).toHaveBeenCalledWith( From fabc5354b07f683244736801b95a1e2e482ca1a8 Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Fri, 6 Nov 2026 22:27:21 +0100 Subject: [PATCH 12/20] Use the global reimbursements flag only when paying from the workspace bank account The backend computes requiresGlobalReimbursement for a payment from the workspace reimbursement account, so a payment from any other account is left to the backend. --- src/hooks/useSearchBulkActions.ts | 1 + src/libs/actions/IOU/PayMoneyRequest.ts | 9 ++++- tests/actions/IOUTest/PayMoneyRequestTest.ts | 22 ++++++++++- .../unit/hooks/useSearchBulkActionsPayTest.ts | 37 +++++++++++++++++++ 4 files changed, 66 insertions(+), 3 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 740b0321a4d0..ae3bdb3659e5 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1923,6 +1923,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({ paymentType: paymentItem.paymentType as PaymentMethodType, iouReport, + policy: reportPolicy, methodID, bankAccountList, isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), diff --git a/src/libs/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index 628174febbab..e5f4286b84be 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -882,17 +882,22 @@ function completePaymentOnboarding( /** * Returns the paying bank account when the payment must wait for global reimbursements onboarding, so payMoneyRequest opens the onboarding instead of paying. * The backend flags the reports that go through global reimbursements on their waiting-to-pay next step, because only it knows the submitter's deposit account. + * The flag describes a payment from the workspace reimbursement account only, so a payment from any other account is left to the backend. */ function getBankAccountToSetUpBeforePaying({ paymentType, iouReport, + policy, methodID, bankAccountList, isWiseReimbursementsBetaEnabled, -}: Pick): OnyxTypes.BankAccount | undefined { +}: Pick): OnyxTypes.BankAccount | undefined { if (!isWiseReimbursementsBetaEnabled || paymentType !== CONST.IOU.PAYMENT_TYPE.VBBA || !methodID || !iouReport?.nextStep?.requiresGlobalReimbursement) { return undefined; } + if (methodID !== policy?.achAccount?.bankAccountID) { + return undefined; + } const bankAccount = bankAccountList?.[methodID]; return shouldSetUpGlobalReimbursementsBeforePaying(bankAccount) ? bankAccount : undefined; } @@ -941,7 +946,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { } // The backend rejects this payment until the account is set up for global reimbursements, so open the onboarding right away instead of showing an optimistic payment - const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({paymentType, iouReport, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); + const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({paymentType, iouReport, policy, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); if (methodID && bankAccountToSetUp) { showEnableGlobalReimbursementsModal({bankAccountID: methodID, bankCountry: bankAccountToSetUp.bankCountry, bankCurrency: bankAccountToSetUp.bankCurrency}); return; diff --git a/tests/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index 778bf7b1dc88..a203a792a076 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -2990,6 +2990,7 @@ describe('actions/IOU/PayMoneyRequest', () => { describe('global reimbursements onboarding before paying', () => { const BANK_ACCOUNT_ID = 9053192; + const OTHER_WORKSPACE_BANK_ACCOUNT_ID = 9053193; function buildBankAccountList(isGlobalReimbursementEnabled: boolean): BankAccountList { return { @@ -3006,7 +3007,12 @@ describe('actions/IOU/PayMoneyRequest', () => { }; } - function payWithBusinessBankAccount(bankAccountList: BankAccountList, isWiseReimbursementsBetaEnabled: boolean, requiresGlobalReimbursement = true) { + function payWithBusinessBankAccount( + bankAccountList: BankAccountList, + isWiseReimbursementsBetaEnabled: boolean, + requiresGlobalReimbursement = true, + workspaceBankAccountID = BANK_ACCOUNT_ID, + ) { const chatReport = { ...createRandomReport(0, undefined), type: CONST.REPORT.TYPE.CHAT, @@ -3036,6 +3042,7 @@ describe('actions/IOU/PayMoneyRequest', () => { isSelfTourViewed: false, userBillingGracePeriodEnds: undefined, amountOwed: 0, + policy: {...createRandomPolicy(2), achAccount: {bankAccountID: workspaceBankAccountID, accountNumber: '', routingNumber: '', addressName: '', bankName: '', reimburser: ''}}, chatReportPolicy: undefined, methodID: BANK_ACCOUNT_ID, chatReportActions: undefined, @@ -3079,5 +3086,18 @@ describe('actions/IOU/PayMoneyRequest', () => { expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.PAY_MONEY_REQUEST, expect.anything(), expect.anything()); expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); }); + + it('sends the payment when the report is flagged but the admin pays from an account other than the workspace one', async () => { + // Given a report the backend flags for global reimbursements, which describes a payment from the workspace account only + const writeSpy = jest.spyOn(APIActions, 'write'); + + // When the admin pays it from another account that has not enabled global reimbursements + payWithBusinessBankAccount(buildBankAccountList(false), true, true, OTHER_WORKSPACE_BANK_ACCOUNT_ID); + await waitForBatchedUpdates(); + + // Then the payment is sent and the backend decides, because the flag says nothing about this account + expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.PAY_MONEY_REQUEST, expect.anything(), expect.anything()); + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); + }); }); }); diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 12eac6652bd2..0b893cb6dca4 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -807,6 +807,43 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); }); + async function payWithBankAccount(bankAccountID: number) { + const {result} = renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider}); + await waitFor(() => { + expect(getPayOptionFromResult(result.current.headerButtonsOptions)).toBeDefined(); + }); + await act(async () => { + result.current.confirmPayment?.(CONST.IOU.PAYMENT_TYPE.VBBA, {bankAccountID, paymentMethod: CONST.PAYMENT_METHODS.BUSINESS_BANK_ACCOUNT}); + }); + } + + it('pays a flagged report from a bank account other than the workspace one and leaves the decision to the backend', async () => { + // Given a flagged report of policy1, whose flag describes a payment from the policy1 account only + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'})]; + + // When the user picks another account without global reimbursements in the bulk Pay menu + await payWithBankAccount(OTHER_BANK_ACCOUNT_ID); + + // Then the report is paid from that account and no modal opens, because the flag says nothing about it + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '1'}), methodID: OTHER_BANK_ACCOUNT_ID})); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); + }); + + it('skips a flagged report when the user picks the workspace bank account in the bulk Pay menu', async () => { + // Given a flagged report of policy1 and a domestic one + mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '9', chatReportID: '10'})]; + + // When the user picks the policy1 account, which has not enabled global reimbursements + await payWithBankAccount(BANK_ACCOUNT_ID); + + // Then only the domestic report is paid, because the flag describes exactly this account + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '9'})})); + expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + }); + it('opens the global reimbursements onboarding when the user picks Get started', async () => { // Given a mixed selection and a user who confirms the modal mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); From e94c8bdf8a1dc6343c6a48c454bf9dba10cae8fe Mon Sep 17 00:00:00 2001 From: Dariusz Biela Date: Sat, 7 Nov 2026 00:36:16 +0100 Subject: [PATCH 13/20] Translate the bulk pay global reimbursements copy and drop an unneeded payment type assertion --- src/hooks/useSearchBulkActions.ts | 2 +- src/languages/de.ts | 5 +++++ src/languages/el.ts | 6 ++++++ src/languages/fr.ts | 5 +++++ src/languages/it.ts | 5 +++++ src/languages/ja.ts | 5 +++++ src/languages/nl.ts | 5 +++++ src/languages/pl.ts | 5 +++++ src/languages/pt-BR.ts | 5 +++++ src/languages/zh-hans.ts | 5 +++++ 10 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index f879980b66da..329f726a4aca 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1960,7 +1960,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { // The backend rejects this payment until the account is set up for global reimbursements, so keep the report unpaid and list it in the modal after the loop const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({ - paymentType: paymentItem.paymentType as PaymentMethodType, + paymentType: paymentItem.paymentType, iouReport, policy: reportPolicy, methodID, diff --git a/src/languages/de.ts b/src/languages/de.ts index 5806be5b59ad..cc16a8b86602 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -3190,6 +3190,11 @@ const translations: TranslationDeepObject = { getStarted: "Los geht's", headerTitle: 'Globale Erstattungen', payingReportSubtitle: 'Die Bankkonten des Unternehmens und der Mitarbeitenden verwenden unterschiedliche Währungen.', + payingMultipleReportsSubtitle: 'Keiner dieser Berichte konnte bezahlt werden, weil die Bankkonten des Unternehmens und der Mitarbeitenden unterschiedliche Währungen verwenden.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Mit x${lastFour} bezahlen` : 'Mit Bankkonto bezahlen'), + description: 'Diese Berichte wurden nicht mit dem Bankkonto bezahlt, weil sie globale Rückerstattungen erfordern. Starten Sie den Vorgang unten.', }, wiseGlobalReimbursementsBanner: {title: 'Weltweit bezahlen', subtitle: 'Aktivieren Sie globale Erstattungen auf Ihrem USD-Konto.'}, wiseMoreInfoNeeded: 'Weitere Informationen erforderlich, um globale Rückerstattungen zu aktivieren', diff --git a/src/languages/el.ts b/src/languages/el.ts index 6b209fa6600e..b2fedcecbc11 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -3247,6 +3247,12 @@ const translations: TranslationDeepObject = { getStarted: 'Ξεκινήστε', headerTitle: 'Παγκόσμιες αποζημιώσεις', payingReportSubtitle: 'Οι τραπεζικοί λογαριασμοί της εταιρείας και των εργαζομένων χρησιμοποιούν διαφορετικά νομίσματα.', + payingMultipleReportsSubtitle: + 'Καμία από αυτές τις αναφορές δεν ήταν δυνατό να πληρωθεί, επειδή οι τραπεζικοί λογαριασμοί της εταιρείας και των εργαζομένων χρησιμοποιούν διαφορετικά νομίσματα.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Πληρωμή με x${lastFour}` : 'Πληρωμή με τραπεζικό λογαριασμό'), + description: 'Αυτές οι αναφορές δεν πληρώθηκαν με τον τραπεζικό λογαριασμό, επειδή απαιτούν παγκόσμιες αποζημιώσεις. Ξεκινήστε τη διαδικασία παρακάτω.', }, wiseGlobalReimbursementsBanner: {title: 'Πληρώστε ανθρώπους παγκοσμίως', subtitle: 'Ενεργοποιήστε τις παγκόσμιες αποζημιώσεις στον λογαριασμό USD σας.'}, wiseMoreInfoNeeded: 'Απαιτούνται περισσότερες πληροφορίες για την ενεργοποίηση των παγκόσμιων επιστροφών χρημάτων', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index 6d658d4b6412..4aabc9df33ed 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -3196,6 +3196,11 @@ const translations: TranslationDeepObject = { getStarted: 'Commencer', headerTitle: 'Remboursements globaux', payingReportSubtitle: 'Les comptes bancaires de l’entreprise et de l’employé utilisent des devises différentes.', + payingMultipleReportsSubtitle: 'Aucune de ces notes de frais n’a pu être payée, car les comptes bancaires de l’entreprise et de l’employé utilisent des devises différentes.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Payer avec x${lastFour}` : 'Payer avec un compte bancaire'), + description: 'Ces notes de frais n’ont pas été payées avec le compte bancaire, car elles nécessitent des remboursements globaux. Commencez la procédure ci-dessous.', }, wiseGlobalReimbursementsBanner: {title: 'Payer des personnes dans le monde entier', subtitle: 'Activez les remboursements globaux sur votre compte en USD.'}, wiseMoreInfoNeeded: 'Informations supplémentaires requises pour activer les remboursements globaux', diff --git a/src/languages/it.ts b/src/languages/it.ts index 5d8b966b6df3..7485b232ddf8 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -3177,6 +3177,11 @@ const translations: TranslationDeepObject = { getStarted: 'Inizia', headerTitle: 'Rimborsi globali', payingReportSubtitle: 'I conti bancari dell’azienda e del dipendente utilizzano valute diverse.', + payingMultipleReportsSubtitle: 'Nessuno di questi resoconti è stato pagato perché i conti bancari dell’azienda e del dipendente utilizzano valute diverse.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Paga con x${lastFour}` : 'Paga con conto bancario'), + description: 'Questi resoconti non sono stati pagati con il conto bancario perché richiedono i rimborsi globali. Avvia la procedura qui sotto.', }, wiseGlobalReimbursementsBanner: {title: 'Paga persone in tutto il mondo', subtitle: 'Abilita i rimborsi globali sul tuo conto in USD.'}, wiseMoreInfoNeeded: 'Servono più informazioni per abilitare i rimborsi globali', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index cb1b10be8505..2e5467827cc3 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -3149,6 +3149,11 @@ const translations: TranslationDeepObject = { getStarted: '使い始める', headerTitle: 'グローバル払い戻し', payingReportSubtitle: '会社と従業員の銀行口座は異なる通貨を使用しています。', + payingMultipleReportsSubtitle: '会社と従業員の銀行口座が異なる通貨を使用しているため、これらのレポートはいずれも支払えませんでした。', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `x${lastFour}で支払う` : '銀行口座で支払う'), + description: 'これらのレポートはグローバル払い戻しが必要なため、銀行口座で支払われませんでした。以下から手続きを開始してください。', }, wiseGlobalReimbursementsBanner: {title: '世界中の人に支払いましょう', subtitle: 'USD アカウントでグローバル払い戻しを有効にします。'}, wiseMoreInfoNeeded: 'グローバル払い戻しを有効にするには、さらに情報が必要です', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 61ea5bc4fc23..f6709dc8f129 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -3177,6 +3177,11 @@ const translations: TranslationDeepObject = { getStarted: 'Aan de slag', headerTitle: 'Wereldwijde terugbetalingen', payingReportSubtitle: 'De bankrekeningen van het bedrijf en de medewerker gebruiken verschillende valuta.', + payingMultipleReportsSubtitle: 'Geen van deze rapporten kon worden betaald, omdat de bankrekeningen van het bedrijf en de medewerker verschillende valuta gebruiken.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Betalen met x${lastFour}` : 'Betalen met bankrekening'), + description: 'Deze rapporten zijn niet met de bankrekening betaald, omdat ze wereldwijde terugbetalingen vereisen. Start het proces hieronder.', }, wiseGlobalReimbursementsBanner: {title: 'Betaal mensen wereldwijd', subtitle: 'Schakel wereldwijde terugbetalingen in op je USD-rekening.'}, wiseMoreInfoNeeded: 'Meer informatie nodig om wereldwijde terugbetalingen in te schakelen', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index 3834762a3543..2f630e9948c2 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -3219,6 +3219,11 @@ const translations: TranslationDeepObject = { getStarted: 'Zacznij', headerTitle: 'Globalne zwroty kosztów', payingReportSubtitle: 'Konta bankowe firmy i pracownika są w różnych walutach.', + payingMultipleReportsSubtitle: 'Nie udało się opłacić żadnego z tych raportów, ponieważ konta bankowe firmy i pracownika są w różnych walutach.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Zapłać z konta x${lastFour}` : 'Zapłać z konta bankowego'), + description: 'Te raporty nie zostały opłacone z konta bankowego, ponieważ wymagają globalnych zwrotów kosztów. Rozpocznij proces poniżej.', }, wiseGlobalReimbursementsBanner: {title: 'Płać ludziom na całym świecie', subtitle: 'Włącz globalne zwroty wydatków na swoim koncie w USD.'}, wiseMoreInfoNeeded: 'Potrzeba więcej informacji, aby włączyć globalne zwroty kosztów', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index b73e9845ab8b..5a711227d5bd 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -3180,6 +3180,11 @@ const translations: TranslationDeepObject = { getStarted: 'Começar', headerTitle: 'Reembolsos globais', payingReportSubtitle: 'As contas bancárias da empresa e do funcionário usam moedas diferentes.', + payingMultipleReportsSubtitle: 'Nenhum desses relatórios pôde ser pago porque as contas bancárias da empresa e do funcionário usam moedas diferentes.', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `Pagar com x${lastFour}` : 'Pagar com conta bancária'), + description: 'Esses relatórios não foram pagos com a conta bancária porque exigem reembolsos globais. Comece o processo abaixo.', }, wiseGlobalReimbursementsBanner: {title: 'Pague pessoas no mundo todo', subtitle: 'Ative reembolsos globais na sua conta em USD.'}, wiseMoreInfoNeeded: 'Mais informações necessárias para ativar reembolsos globais', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 8365b62afa9d..06547811d99b 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -3073,6 +3073,11 @@ const translations: TranslationDeepObject = { getStarted: '开始使用', headerTitle: '全球报销', payingReportSubtitle: '公司账户和员工账户使用的货币不同。', + payingMultipleReportsSubtitle: '由于公司账户和员工账户使用的货币不同,这些报告均无法支付。', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `使用 x${lastFour} 支付` : '使用银行账户支付'), + description: '这些报告需要全球报销,因此未使用该银行账户支付。请在下方开始设置流程。', }, wiseGlobalReimbursementsBanner: {title: '向全球付款', subtitle: '在您的美元账户中启用全球报销。'}, wiseMoreInfoNeeded: '启用全球报销所需的更多信息', From 777e489d9c74b1ade36dd75ebcf365310118384e Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 12 Nov 2026 13:16:08 +0100 Subject: [PATCH 14/20] Skip the global reimbursements prompt when the Wise quote carousel is cancelled --- src/hooks/useSearchBulkActions.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 329f726a4aca..d88063cc2942 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -2096,7 +2096,13 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { }, }) // The skipped reports wait for the carousel to close, so the two modals never stack - .then(() => promptToSetUpGlobalReimbursements(paidReportCount > 0 || hasConfirmedWiseQuotes)); + .then(() => { + // Cancelling the carousel backs out of bulk pay, so don't follow it with the global reimbursements setup + if (!hasConfirmedWiseQuotes) { + return; + } + promptToSetUpGlobalReimbursements(true); + }); }); }, [ From 575c57ebc15fed6eb56cc28cb91a33e23d5bc69c Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 12 Nov 2026 13:32:52 +0100 Subject: [PATCH 15/20] Pay every bulk pay report from one bank account instead of skipping other accounts' reports --- src/hooks/useSearchBulkActions.ts | 30 ++++++++----------- .../unit/hooks/useSearchBulkActionsPayTest.ts | 17 ++++++----- 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index d88063cc2942..81b8459cbe7c 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1848,8 +1848,10 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { let paidReportCount = 0; const expensePayments: PayMoneyRequestFunctionParams[] = []; - // Reports skipped because their bank account needs global reimbursements, grouped by that bank account - const reportsNeedingGlobalReimbursementsByBankAccount = new Map}>(); + // Bulk pay pays every expense report from one bank account: the one the user picked, or else the first one a report resolves to + let bulkPayBankAccountID = expenseReportBankAccountID; + // Reports skipped because the bank account needs global reimbursements + let reportsNeedingGlobalReimbursements: {bankAccountID: number; bankAccount: BankAccount; reportNames: Map} | undefined; for (const item of itemsToPay) { if (!item.reportID) { Log.info('[BulkPay] Skipping report: item has no reportID'); @@ -1955,8 +1957,10 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { continue; } - const methodID = - paymentItem.paymentType === CONST.IOU.PAYMENT_TYPE.VBBA ? (paymentItem.bankAccountID ?? workspaceMethodID ?? reportPolicy?.achAccount?.bankAccountID) : undefined; + if (paymentItem.paymentType === CONST.IOU.PAYMENT_TYPE.VBBA) { + bulkPayBankAccountID ??= workspaceMethodID ?? reportPolicy?.achAccount?.bankAccountID; + } + const methodID = paymentItem.paymentType === CONST.IOU.PAYMENT_TYPE.VBBA ? bulkPayBankAccountID : undefined; // The backend rejects this payment until the account is set up for global reimbursements, so keep the report unpaid and list it in the modal after the loop const bankAccountToSetUp = getBankAccountToSetUpBeforePaying({ @@ -1969,10 +1973,9 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { }); if (methodID && bankAccountToSetUp) { - const skippedReports = reportsNeedingGlobalReimbursementsByBankAccount.get(methodID) ?? {bankAccount: bankAccountToSetUp, reportNames: new Map()}; + reportsNeedingGlobalReimbursements ??= {bankAccountID: methodID, bankAccount: bankAccountToSetUp, reportNames: new Map()}; // Keyed by reportID because selecting several expenses of one report yields one item per expense - skippedReports.reportNames.set(item.reportID, getReportName(iouReport) || translate('common.report')); - reportsNeedingGlobalReimbursementsByBankAccount.set(methodID, skippedReports); + reportsNeedingGlobalReimbursements.reportNames.set(item.reportID, getReportName(iouReport) || translate('common.report')); continue; } @@ -2033,22 +2036,15 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { clearSelectedTransactions(); } - // The modal sets up one bank account, so it lists only the reports paid from that account const promptToSetUpGlobalReimbursements = (hasPaidReports: boolean) => { - const [firstSkippedBankAccount, ...otherSkippedBankAccounts] = reportsNeedingGlobalReimbursementsByBankAccount.entries(); - if (otherSkippedBankAccounts.length > 0) { - Log.info('[BulkPay] Reports from more than one bank account need global reimbursements, prompting for the first one only', false, { - bankAccountIDs: [...reportsNeedingGlobalReimbursementsByBankAccount.keys()], - }); - } - if (!firstSkippedBankAccount) { + if (!reportsNeedingGlobalReimbursements) { return; } - const [bankAccountID, {bankAccount, reportNames}] = firstSkippedBankAccount; + const {bankAccountID, bankAccount, reportNames} = reportsNeedingGlobalReimbursements; const globalReimbursementsModalData = {bankAccountID, bankCountry: bankAccount.bankCountry, bankCurrency: bankAccount.bankCurrency}; // Nothing was paid, so there is nothing to list next to the skipped reports. Open the intro directly, the same way paying a single report does - if (!hasPaidReports && otherSkippedBankAccounts.length === 0) { + if (!hasPaidReports) { showEnableGlobalReimbursementsModal({...globalReimbursementsModalData, isPayingMultipleReports: reportNames.size > 1}); return; } diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 7655acf192d1..bcd718f44e03 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -813,14 +813,14 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs } it('pays the other reports and lists the ones that need global reimbursements in a modal', async () => { - // Given one selected report paid from an account without global reimbursements and one paid from an account that has them + // Given one flagged report of a workspace whose account has no global reimbursements, and one flagged report of a workspace whose account has them // When the user selects bulk Pay await selectBulkPay(); - // Then only the second report is paid, because the backend would reject paying the first one + // Then only the second report is paid, from the first report's account, because bulk pay pays every report from one account and the backend would reject paying the first one expect(payMoneyRequest).toHaveBeenCalledTimes(1); - expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'}), methodID: BANK_ACCOUNT_ID})); // And the selection is cleared, the same as after any bulk pay that paid at least one report expect(mockClearSelectedTransactions).toHaveBeenCalledTimes(1); @@ -931,15 +931,18 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); }); - it('lists only the reports of the bank account the modal sets up when several accounts need global reimbursements', async () => { - // Given two selected reports paid from two different bank accounts that both need global reimbursements + it('pays a report of another workspace from the same bank account instead of skipping it', async () => { + // Given two flagged reports from workspaces linked to two different bank accounts without global reimbursements mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '5', chatReportID: '6', policyID: 'policy3'})]; // When the user selects bulk Pay await selectBulkPay(); - // Then nothing is paid, and the modal names the first account and lists only its report, because Get started sets up that account alone - expect(payMoneyRequest).not.toHaveBeenCalled(); + // Then the second report is paid from the first report's account, because bulk pay pays every report from one account and the flag describes the policy3 account only + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '5'}), methodID: BANK_ACCOUNT_ID})); + + // And the modal lists the first report, which that account can't pay until it sets up global reimbursements expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); expect(mockShowConfirmModal).toHaveBeenCalledWith( expect.objectContaining({ From eee9ff62ef2d70412e2dc3d5539b044f4456ced8 Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 12 Nov 2026 13:40:01 +0100 Subject: [PATCH 16/20] Inline the global reimbursements intro subtitle so React Compiler keeps caching translate --- .../Wallet/WiseGlobalReimbursementsIntroPage.tsx | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx b/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx index 0d6200540ea4..c0a5db42ae8e 100644 --- a/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx +++ b/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx @@ -32,13 +32,6 @@ import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import React, {useEffect} from 'react'; -function getSubtitleTranslationKey(isPayingReport: boolean, isPayingMultipleReports: boolean) { - if (isPayingMultipleReports) { - return 'walletPage.wiseGlobalReimbursementsIntro.payingMultipleReportsSubtitle'; - } - return isPayingReport ? 'walletPage.wiseGlobalReimbursementsIntro.payingReportSubtitle' : 'walletPage.wiseGlobalReimbursementsIntro.subtitle'; -} - type WiseGlobalReimbursementsIntroPageProps = PlatformStackScreenProps; function WiseGlobalReimbursementsIntroPage({route}: WiseGlobalReimbursementsIntroPageProps) { @@ -93,7 +86,9 @@ function WiseGlobalReimbursementsIntroPage({route}: WiseGlobalReimbursementsIntr /> {translate('walletPage.wiseGlobalReimbursementsIntro.title')} - {translate(getSubtitleTranslationKey(isPayingReport, isPayingMultipleReports))} + {isPayingMultipleReports + ? translate('walletPage.wiseGlobalReimbursementsIntro.payingMultipleReportsSubtitle') + : translate(isPayingReport ? 'walletPage.wiseGlobalReimbursementsIntro.payingReportSubtitle' : 'walletPage.wiseGlobalReimbursementsIntro.subtitle')} From eab51721efb2a56a3e2eb755f33907ff981139dd Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Fri, 13 Nov 2026 11:32:46 +0100 Subject: [PATCH 17/20] Treat a bank account without the global reimbursements flag as not set up before paying --- src/libs/BankAccountUtils.ts | 6 ++---- tests/unit/BankAccountUtilsTest.ts | 12 ++++++----- .../unit/hooks/useSearchBulkActionsPayTest.ts | 20 +++++++++++++++++++ 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/libs/BankAccountUtils.ts b/src/libs/BankAccountUtils.ts index c5490af73a76..bac0337f7ba6 100644 --- a/src/libs/BankAccountUtils.ts +++ b/src/libs/BankAccountUtils.ts @@ -231,12 +231,10 @@ function isBankAccountEligibleForGlobalReimbursements(accountData: AccountData | /** * Whether a payment from this account would be rejected until global reimbursements are set up, so the onboarding should open instead of paying. - * Only an explicit `false` counts, so an account without the flag still goes to the backend, which makes the final call. + * An account without the flag counts too, because the backend only pays through global reimbursements once the flag is `true`. */ function shouldSetUpGlobalReimbursementsBeforePaying(bankAccount: OnyxEntry): boolean { - return ( - bankAccount?.accountData?.additionalData?.isGlobalReimbursementEnabled === false && isBankAccountEligibleForGlobalReimbursements(bankAccount.accountData, bankAccount.bankCurrency) - ); + return isBankAccountEligibleForGlobalReimbursements(bankAccount?.accountData, bankAccount?.bankCurrency); } /** diff --git a/tests/unit/BankAccountUtilsTest.ts b/tests/unit/BankAccountUtilsTest.ts index 5385bc7d08d6..b45bf8f1fc8a 100644 --- a/tests/unit/BankAccountUtilsTest.ts +++ b/tests/unit/BankAccountUtilsTest.ts @@ -326,16 +326,18 @@ describe('BankAccountUtils', () => { accountData: {type, state: CONST.BANK_ACCOUNT.STATE.OPEN, additionalData: {currency: CONST.CURRENCY.USD, ...additionalData}}, }); - it('returns true when a USD business account has global reimbursements disabled', () => { - // Given a USD business account the backend marks as not set up for global reimbursements + it.each([ + ['has global reimbursements disabled', buildBankAccount({isGlobalReimbursementEnabled: false})], + ['comes without the global reimbursements flag', buildBankAccount({})], + ])('returns true when a USD business account %s', (_label, bankAccount) => { + // Given a USD business account that has not enabled global reimbursements // When checking it before paying - // Then onboarding should open, because the backend rejects every payment from this account - expect(shouldSetUpGlobalReimbursementsBeforePaying(buildBankAccount({isGlobalReimbursementEnabled: false}))).toBe(true); + // Then onboarding should open, because the backend only pays through global reimbursements once the flag is true + expect(shouldSetUpGlobalReimbursementsBeforePaying(bankAccount)).toBe(true); }); it.each([ ['global reimbursements are already enabled', buildBankAccount({isGlobalReimbursementEnabled: true})], - ['the backend did not send the flag', buildBankAccount({})], ['the account is personal', buildBankAccount({isGlobalReimbursementEnabled: false}, CONST.BANK_ACCOUNT.TYPE.PERSONAL)], ['the account is unknown', undefined], ])('returns false when %s', (_label, bankAccount) => { diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index bcd718f44e03..9c088f390014 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -836,6 +836,26 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs ); }); + it('skips a flagged report when the bank account comes without the global reimbursements flag', async () => { + // Given the mixed selection from the first test, paid from an account the backend sent without the flag, which it treats as not enabled + const bankAccountWithoutFlag = makeBankAccount(BANK_ACCOUNT_ID, 'XXXXXX1234', false); + delete bankAccountWithoutFlag.accountData?.additionalData?.isGlobalReimbursementEnabled; + await Onyx.set(ONYXKEYS.BANK_ACCOUNT_LIST, { + [BANK_ACCOUNT_ID]: bankAccountWithoutFlag, + [ENABLED_BANK_ACCOUNT_ID]: makeBankAccount(ENABLED_BANK_ACCOUNT_ID, 'XXXXXX9999', true), + }); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then only the second report is paid, because the backend would reject paying the first one + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); + + // And the modal lists the skipped report instead of the backend opening the onboarding after a failed payment + expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + }); + it('pays every report and shows no modal when the global reimbursements beta is off', async () => { // Given the same selection, but an admin without the global reimbursements beta mockEnabledBetas = new Set(); From 3095ecef99d4e18307a2b48dcfb7aa0a109d19c9 Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Tue, 17 Nov 2026 17:11:28 +0100 Subject: [PATCH 18/20] List bulk pay reports the backend rejects for global reimbursements in the same modal and drop their generic error --- .../EnableGlobalReimbursementsPayModal.tsx | 28 +++- src/hooks/useSearchBulkActions.ts | 102 +++++------- src/libs/ExportOnyxState/masking.ts | 3 +- .../Middleware/GlobalReimbursementPayError.ts | 55 +++++-- src/libs/Middleware/register.ts | 2 +- .../actions/GlobalReimbursementsBulkPay.ts | 91 +++++++++++ src/libs/formatReportNamesAsBulletList.ts | 8 + .../onyx/EnableGlobalReimbursementsModal.ts | 4 + ...EnableGlobalReimbursementsPayModalTest.tsx | 52 +++++- tests/unit/GlobalReimbursementPayErrorTest.ts | 102 ++++++++++++ tests/unit/GlobalReimbursementsBulkPayTest.ts | 150 +++++++++++++++++ .../unit/hooks/useSearchBulkActionsPayTest.ts | 153 +++++++++--------- 12 files changed, 580 insertions(+), 170 deletions(-) create mode 100644 src/libs/actions/GlobalReimbursementsBulkPay.ts create mode 100644 src/libs/formatReportNamesAsBulletList.ts create mode 100644 tests/unit/GlobalReimbursementsBulkPayTest.ts diff --git a/src/components/EnableGlobalReimbursementsPayModal.tsx b/src/components/EnableGlobalReimbursementsPayModal.tsx index cf149034979f..e6e110b8122b 100644 --- a/src/components/EnableGlobalReimbursementsPayModal.tsx +++ b/src/components/EnableGlobalReimbursementsPayModal.tsx @@ -3,10 +3,13 @@ import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePermissions from '@hooks/usePermissions'; +import {getLastFourDigits} from '@libs/BankAccountUtils'; +import deferModalPresentationAfterPopoverDismiss from '@libs/deferModalPresentationAfterPopoverDismiss'; +import formatReportNamesAsBulletList from '@libs/formatReportNamesAsBulletList'; import {getEnableGlobalReimbursementsBusinessNavigationRoute, getWiseGlobalReimbursementsIntroNavigationRoute} from '@libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils'; import Navigation from '@libs/Navigation/Navigation'; -import {clearEnableGlobalReimbursementsModal} from '@userActions/App'; +import {clearEnableGlobalReimbursementsModal, showEnableGlobalReimbursementsModal as showEnableGlobalReimbursementsModalAction} from '@userActions/App'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -30,6 +33,29 @@ function EnableGlobalReimbursementsPayModal() { if (isModalOpenRef.current) { return; } + + // Search bulk pay paid some reports and left these unpaid. It lists them here rather than in Search, because the responses can arrive after the admin left the Search page + const {unpaidReportNames, accountNumber, ...bankAccount} = modalData; + if (unpaidReportNames?.length) { + clearEnableGlobalReimbursementsModal(); + deferModalPresentationAfterPopoverDismiss(() => { + showConfirmModal({ + title: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.title', getLastFourDigits(accountNumber ?? '')), + subtitle: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.description'), + prompt: formatReportNamesAsBulletList(unpaidReportNames), + confirmText: translate('walletPage.wiseGlobalReimbursementsIntro.getStarted'), + cancelText: translate('common.notNow'), + shouldEnablePromptScroll: true, + }).then((result) => { + if (result.action !== ModalActions.CONFIRM) { + return; + } + showEnableGlobalReimbursementsModalAction(bankAccount); + }); + }); + return; + } + const navigationPathAtSignal = Navigation.getActiveRoute(); // The signal arrives after a pay attempt, so betas are loaded. An unknown beta state should take the Corpay path. diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 81b8459cbe7c..fe36ea256bb5 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -10,9 +10,9 @@ import {getClaimedGroupKey, getSearchGroupCountByKey, mergeRowsIntoPartlyLoadedG import type {BulkPaySelectionData, PaymentData, QueryFilterKey, SearchColumnType, SearchGroupBy, SearchQueryJSON, SelectedReports, SelectedTransactions} from '@components/Search/types'; import {getAccountingIntegrationDisplayName, getExportLabelForConnection, isIntuitEnterpriseSuiteConnection} from '@libs/AccountingUtils'; -import {showEnableGlobalReimbursementsModal} from '@libs/actions/App'; import {getExpensifyCardStatementPDF} from '@libs/actions/CompanyCards'; import {exportReceiptsToZip, exportReportsToPDF} from '@libs/actions/Export'; +import {followGlobalReimbursementsBulkPay} from '@libs/actions/GlobalReimbursementsBulkPay'; import {unholdRequest} from '@libs/actions/IOU/Hold'; import {getBankAccountToSetUpBeforePaying, payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest'; import type {PayMoneyRequestFunctionParams} from '@libs/actions/IOU/PayMoneyRequest'; @@ -49,11 +49,13 @@ import { import initSplitExpense from '@libs/actions/SplitExpenses'; import {setNameValuePair} from '@libs/actions/User'; import {getWiseQuote} from '@libs/actions/Wise'; -import {getLastFourDigits, shouldConfirmWiseQuoteBeforePaying, shouldGetWiseQuote} from '@libs/BankAccountUtils'; +import {isClientTheLeader} from '@libs/ActiveClientManager'; +import {shouldConfirmWiseQuoteBeforePaying, shouldGetWiseQuote} from '@libs/BankAccountUtils'; import {canResolveTransactionCard} from '@libs/CardUtils'; import {getConnectionCompanyID} from '@libs/CopyPolicySettingsUtils'; import deferModalPresentationAfterPopoverDismiss from '@libs/deferModalPresentationAfterPopoverDismiss'; import {getExpensifyCardStatementParamsFromFeed, getExpensifyCardStatementSelection} from '@libs/ExpensifyCardStatementUtils'; +import formatReportNamesAsBulletList from '@libs/formatReportNamesAsBulletList'; import getSelectedTransactionOwnerAccountID from '@libs/getSelectedTransactionOwnerAccountID'; import Log from '@libs/Log'; import {getTransactionsAndReportsFromSearch} from '@libs/MergeTransactionUtils'; @@ -135,18 +137,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import {columnsSelector} from '@src/selectors/AdvancedSearchFiltersForm'; import {doesPersonalDetailExistSelector} from '@src/selectors/PersonalDetails'; -import type { - BankAccount, - BillingGraceEndPeriod, - ExportTemplate, - Policy, - Report, - ReportAction, - ReportNameValuePairs, - SearchResults, - Transaction, - TransactionViolations, -} from '@src/types/onyx'; +import type {BillingGraceEndPeriod, ExportTemplate, Policy, Report, ReportAction, ReportNameValuePairs, SearchResults, Transaction, TransactionViolations} from '@src/types/onyx'; import type {SearchResultDataType} from '@src/types/onyx/SearchResults'; import type DeepValueOf from '@src/types/utils/DeepValueOf'; import {getEmptyObject, isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -645,10 +636,6 @@ function getChatReportForBulkPay( return getReportFromSearchSnapshot(resolvedChatReportID, searchData, allReports) ?? getReportOrDraftReport({reportID: resolvedChatReportID}); } -function formatReportNamesAsBulletList(reportNames: Iterable): string { - return Array.from(reportNames, (reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'); -} - /** * A single export option. It is typed as a dropdown option rather than a plain menu item because it is rendered at * either level of the bulk-action dropdown: nested inside the Export submenu, or directly at the top level when @@ -1850,8 +1837,8 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const expensePayments: PayMoneyRequestFunctionParams[] = []; // Bulk pay pays every expense report from one bank account: the one the user picked, or else the first one a report resolves to let bulkPayBankAccountID = expenseReportBankAccountID; - // Reports skipped because the bank account needs global reimbursements - let reportsNeedingGlobalReimbursements: {bankAccountID: number; bankAccount: BankAccount; reportNames: Map} | undefined; + // Reports skipped because the bank account needs global reimbursements, keyed by reportID because selecting several expenses of one report yields one item per expense + const reportNamesNeedingGlobalReimbursements = new Map(); for (const item of itemsToPay) { if (!item.reportID) { Log.info('[BulkPay] Skipping report: item has no reportID'); @@ -1973,9 +1960,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { }); if (methodID && bankAccountToSetUp) { - reportsNeedingGlobalReimbursements ??= {bankAccountID: methodID, bankAccount: bankAccountToSetUp, reportNames: new Map()}; - // Keyed by reportID because selecting several expenses of one report yields one item per expense - reportsNeedingGlobalReimbursements.reportNames.set(item.reportID, getReportName(iouReport) || translate('common.report')); + reportNamesNeedingGlobalReimbursements.set(item.reportID, getReportName(iouReport) || translate('common.report')); continue; } @@ -2013,7 +1998,34 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { expensePayments.push(payMoneyRequestParams); } + const hasPaidInvoices = paidReportCount > 0; const payExpenseReports = (wiseQuoteIDsByReportID: Record = {}) => { + const bankAccount = bulkPayBankAccountID ? bankAccountList?.[bulkPayBankAccountID] : undefined; + if (bulkPayBankAccountID && bankAccount && isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS)) { + // The pre-check can't catch every report the backend rejects for global reimbursements, so the rejected reports are listed with the skipped ones + // once every payment has a response. Only the leader tab gets the responses, so another tab lists the skipped reports right away. + const shouldWaitForResponses = isClientTheLeader(); + const pendingReportNames = new Map(); + if (shouldWaitForResponses) { + for (const {iouReport} of expensePayments) { + if (iouReport?.reportID) { + pendingReportNames.set(iouReport.reportID, getReportName(iouReport) || translate('common.report')); + } + } + } + followGlobalReimbursementsBulkPay({ + bankAccount: { + bankAccountID: bulkPayBankAccountID, + bankCountry: bankAccount.bankCountry, + bankCurrency: bankAccount.bankCurrency, + accountNumber: bankAccount.accountData?.accountNumber, + }, + pendingReportNames, + skippedReportNames: [...reportNamesNeedingGlobalReimbursements.values()], + hasPaidReports: hasPaidInvoices || (!shouldWaitForResponses && expensePayments.length > 0), + }); + } + for (const params of expensePayments) { const reportID = params.iouReport?.reportID; payMoneyRequest({...params, wiseQuoteID: reportID ? wiseQuoteIDsByReportID[reportID] : undefined}); @@ -2036,38 +2048,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { clearSelectedTransactions(); } - const promptToSetUpGlobalReimbursements = (hasPaidReports: boolean) => { - if (!reportsNeedingGlobalReimbursements) { - return; - } - const {bankAccountID, bankAccount, reportNames} = reportsNeedingGlobalReimbursements; - const globalReimbursementsModalData = {bankAccountID, bankCountry: bankAccount.bankCountry, bankCurrency: bankAccount.bankCurrency}; - - // Nothing was paid, so there is nothing to list next to the skipped reports. Open the intro directly, the same way paying a single report does - if (!hasPaidReports) { - showEnableGlobalReimbursementsModal({...globalReimbursementsModalData, isPayingMultipleReports: reportNames.size > 1}); - return; - } - - deferModalPresentationAfterPopoverDismiss(() => { - showConfirmModal({ - title: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.title', getLastFourDigits(bankAccount.accountData?.accountNumber ?? '')), - subtitle: translate('walletPage.wiseGlobalReimbursementsBulkPayModal.description'), - prompt: formatReportNamesAsBulletList(reportNames.values()), - confirmText: translate('walletPage.wiseGlobalReimbursementsIntro.getStarted'), - cancelText: translate('common.notNow'), - shouldEnablePromptScroll: true, - }).then((result) => { - if (result.action !== ModalActions.CONFIRM) { - return; - } - showEnableGlobalReimbursementsModal(globalReimbursementsModalData); - }); - }); - }; - if (!shouldConfirmWiseQuotes) { - promptToSetUpGlobalReimbursements(paidReportCount > 0); return; } @@ -2078,27 +2059,17 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { getWiseQuote({...report, ...allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`]}, true); } const quotedReportIDs = quotedReports.map((report) => report.reportID); - let hasConfirmedWiseQuotes = false; // Bulk pay runs while the pay popover is still dismissing, and iOS can't present a modal until it's gone deferModalPresentationAfterPopoverDismiss(() => { showWiseQuoteCarouselModal({ reports, quotedReportIDs, onConfirm: (wiseQuoteIDsByReportID) => { - hasConfirmedWiseQuotes = true; payExpenseReports(wiseQuoteIDsByReportID); playSound(SOUNDS.SUCCESS); clearSelectedTransactions(); }, - }) - // The skipped reports wait for the carousel to close, so the two modals never stack - .then(() => { - // Cancelling the carousel backs out of bulk pay, so don't follow it with the global reimbursements setup - if (!hasConfirmedWiseQuotes) { - return; - } - promptToSetUpGlobalReimbursements(true); - }); + }); }); }, [ @@ -2144,7 +2115,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { isTrackIntentUser, getCurrencyDecimals, rules, - showConfirmModal, translate, ], ); diff --git a/src/libs/ExportOnyxState/masking.ts b/src/libs/ExportOnyxState/masking.ts index fa5e13274d48..814a4539a501 100644 --- a/src/libs/ExportOnyxState/masking.ts +++ b/src/libs/ExportOnyxState/masking.ts @@ -359,7 +359,6 @@ const safeOnyxKeys = new Set([ ONYXKEYS.PREFERRED_EMOJI_SKIN_TONE, ONYXKEYS.PREFERRED_THEME, ONYXKEYS.RAM_ONLY_ARE_TRANSLATIONS_LOADING, - ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, ONYXKEYS.RAM_ONLY_EXPENSE_ADDED_GROWL_TRANSACTION_IDS, ONYXKEYS.RAM_ONLY_HAS_RULES_DATA_BEEN_FETCHED, ONYXKEYS.RAM_ONLY_IS_AUTHENTICATING_WITH_SHORT_LIVED_TOKEN, @@ -545,6 +544,8 @@ const onyxKeysToMaskFragileData = new Set([ ONYXKEYS.PURCHASE_LIST, ONYXKEYS.QUEUE_FLUSHED_DATA, ONYXKEYS.RAM_ONLY_DOMAIN_MEMBERS_SELECTED_FOR_MOVE, + // Holds report names, which often include the submitter's name + ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, ONYXKEYS.RAM_ONLY_HAS_DISMISSED_CONCIERGE_NOTIFICATION_BANNER, ONYXKEYS.RAM_ONLY_HAS_FRESH_WALLET_DATA, ONYXKEYS.RAM_ONLY_IS_LOADING_SEARCH_FILTERS_CATEGORY_DATA, diff --git a/src/libs/Middleware/GlobalReimbursementPayError.ts b/src/libs/Middleware/GlobalReimbursementPayError.ts index 08f2d763ee7b..99f7a3b738eb 100644 --- a/src/libs/Middleware/GlobalReimbursementPayError.ts +++ b/src/libs/Middleware/GlobalReimbursementPayError.ts @@ -1,3 +1,4 @@ +import {settleGlobalReimbursementsBulkPayReport} from '@libs/actions/GlobalReimbursementsBulkPay'; import {PAYMENT_COMMANDS} from '@libs/API/types'; import Log from '@libs/Log'; import {isRecord} from '@libs/ObjectUtils'; @@ -13,48 +14,68 @@ import type {OnyxKey} from 'react-native-onyx'; import type Middleware from './types'; /** - * Middleware that detects the Corpay pay modal signal sent by the backend when a pay attempt fails because the - * workspace USD VBBA is not set up on Corpay. The backend sends an Onyx SET on enableGlobalReimbursementsModal instead of writing - * an inline error onto the report action. + * Middleware that detects the global reimbursements signal sent by the backend when a pay attempt fails because the + * bank account isn't set up for global reimbursements (Corpay or Wise). The backend sends an Onyx SET on + * enableGlobalReimbursementsModal instead of writing an inline error onto the report action. The setup explains the + * rejection, so the middleware drops the failed PAY action and the report error. + * + * It also tells Search bulk pay how each of its payments ended, and holds the signal back for them, so one modal lists + * the unpaid reports of a click instead of the setup opening once per rejected report. */ const GlobalReimbursementPayError: Middleware = (responsePromise: Promise | void>, request: Request | PaginatedRequest) => responsePromise.then((response) => { - if (!request?.command || !PAYMENT_COMMANDS.has(request.command) || !response || response.jsonCode === CONST.JSON_CODE.SUCCESS) { + if (!request?.command || !PAYMENT_COMMANDS.has(request.command) || !response) { return response; } - const onyxData = response.onyxData ?? []; - const hasEnableGlobalReimbursementsModal = onyxData.some((update) => update.key === ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL); + const iouReportID = request?.data?.iouReportID; + const reportActionID = request?.data?.reportActionID; + const isPaid = response.jsonCode === CONST.JSON_CODE.SUCCESS; + const enableGlobalReimbursementsModalUpdate = isPaid ? undefined : response.onyxData?.find((update) => update.key === ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL); + const isBulkPayRequest = + typeof iouReportID === 'string' && settleGlobalReimbursementsBulkPayReport(iouReportID, {isPaid, needsGlobalReimbursements: !!enableGlobalReimbursementsModalUpdate}); - if (!hasEnableGlobalReimbursementsModal) { + if (!enableGlobalReimbursementsModalUpdate) { return response; } - const iouReportID = request?.data?.iouReportID; - const reportActionID = request?.data?.reportActionID; + if (isBulkPayRequest) { + response.onyxData = response.onyxData?.filter((update) => update !== enableGlobalReimbursementsModalUpdate); + } if (typeof iouReportID !== 'string' || typeof reportActionID !== 'string' || !request?.failureData) { return response; } const actionsKey = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`; + const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`; for (const update of request.failureData as AnyOnyxUpdate[]) { - if (update.key !== actionsKey || !update.value) { + if (!isRecord(update.value)) { continue; } - if (!isRecord(update.value)) { + if (update.key === actionsKey) { + // Drop the optimistic PAY action instead of merging an error onto it. + update.value = { + ...update.value, + [reportActionID]: null, + }; continue; } - // Drop the optimistic PAY action instead of merging an error onto it. - update.value = { - ...update.value, - [reportActionID]: null, - }; + // Search pay adds a generic error to the report when the payment fails. The global reimbursements setup explains this + // rejection instead, and the Search row has no way to dismiss the error. + if (update.key === reportKey && 'errors' in update.value) { + const {errors, ...reportValue} = update.value; + update.value = reportValue; + } } - Log.info('GlobalReimbursementPayError: replaced optimistic PAY action-error with action-null for enableGlobalReimbursementsModal', false, {iouReportID, reportActionID}); + Log.info('GlobalReimbursementPayError: dropped the optimistic PAY action and the report error for enableGlobalReimbursementsModal', false, { + iouReportID, + reportActionID, + isBulkPayRequest, + }); return response; }); diff --git a/src/libs/Middleware/register.ts b/src/libs/Middleware/register.ts index f0432162dac1..e0915480e1dd 100644 --- a/src/libs/Middleware/register.ts +++ b/src/libs/Middleware/register.ts @@ -55,7 +55,7 @@ function registerMiddlewares() { // Handle supportal permission denial centrally addMiddleware(SupportalPermission); - // Handle the Corpay pay modal signal: when the backend signals that the workspace USD VBBA is not set up on Corpay, replace the optimistic PAY action-error with an action-null so no inline error shows. + // Handle the global reimbursements pay signal (Corpay or Wise): drop the failed PAY action and the report error, and hold the signal back for Search bulk pay, which lists its unpaid reports itself. addMiddleware(GlobalReimbursementPayError); // Show the "Cannot disable category" modal when the backend rejects disabling categories some members can't do without. diff --git a/src/libs/actions/GlobalReimbursementsBulkPay.ts b/src/libs/actions/GlobalReimbursementsBulkPay.ts new file mode 100644 index 000000000000..6d5c81ea7340 --- /dev/null +++ b/src/libs/actions/GlobalReimbursementsBulkPay.ts @@ -0,0 +1,91 @@ +/** + * Follows the payments of a Search bulk pay click, so the reports left unpaid because the bank account needs global + * reimbursements are listed in one modal once every payment has a response. Those are the reports the client skipped + * before paying and the ones the backend rejected. Writes go through the SequentialQueue, so Search can't wait for the + * responses itself. GlobalReimbursementPayError reports each one here instead. + * + * The clicks are kept in memory, because only the tab that sends the requests gets their responses. + */ +import type {EnableGlobalReimbursementsModal} from '@src/types/onyx'; + +import {showEnableGlobalReimbursementsModal} from './App'; + +type BulkPay = { + /** The bank account every expense report of the click is paid from */ + bankAccount: EnableGlobalReimbursementsModal; + + /** The names of the reports whose payment has no response yet, keyed by reportID */ + pendingReportNames: Map; + unpaidReportNames: string[]; + hasPaidReports: boolean; +}; + +type BulkPayParams = Pick & { + /** The names of the reports the client didn't pay because the bank account needs global reimbursements */ + skippedReportNames: string[]; +}; + +type PaymentOutcome = { + isPaid: boolean; + + /** Whether the backend rejected the payment because the bank account needs global reimbursements */ + needsGlobalReimbursements: boolean; +}; + +// Each click is followed on its own, so one whose payment never gets a response doesn't hold back the clicks after it +const bulkPays = new Set(); + +function showUnpaidReportsIfSettled(bulkPay: BulkPay) { + if (bulkPay.pendingReportNames.size > 0) { + return; + } + bulkPays.delete(bulkPay); + + const {bankAccount, unpaidReportNames, hasPaidReports} = bulkPay; + if (unpaidReportNames.length === 0) { + return; + } + + // Nothing was paid, so there is nothing to list next to the unpaid reports. Open the intro directly, the same way paying a single report does + const {accountNumber, ...introData} = bankAccount; + showEnableGlobalReimbursementsModal(hasPaidReports ? {...bankAccount, unpaidReportNames} : {...introData, isPayingMultipleReports: unpaidReportNames.length > 1}); +} + +/** Starts following a bulk pay click. Call it before sending the payments, so no response is missed. */ +function followGlobalReimbursementsBulkPay({bankAccount, pendingReportNames, skippedReportNames, hasPaidReports}: BulkPayParams) { + // A report can't be paid again while its payment is in flight, so an earlier click that still waits for one of these reports never got its response. + // Forget it, or the response of this click would settle that one instead. + for (const earlierBulkPay of bulkPays) { + if ([...pendingReportNames.keys()].some((reportID) => earlierBulkPay.pendingReportNames.has(reportID))) { + bulkPays.delete(earlierBulkPay); + } + } + + const bulkPay = {bankAccount, pendingReportNames: new Map(pendingReportNames), unpaidReportNames: [...skippedReportNames], hasPaidReports}; + bulkPays.add(bulkPay); + showUnpaidReportsIfSettled(bulkPay); +} + +/** + * Records the response of a payment. + * + * @returns whether the payment belongs to a bulk pay click, which then lists the report itself if it was rejected + */ +function settleGlobalReimbursementsBulkPayReport(reportID: string, {isPaid, needsGlobalReimbursements}: PaymentOutcome): boolean { + for (const bulkPay of bulkPays) { + const reportName = bulkPay.pendingReportNames.get(reportID); + if (reportName === undefined) { + continue; + } + bulkPay.pendingReportNames.delete(reportID); + bulkPay.hasPaidReports ||= isPaid; + if (needsGlobalReimbursements) { + bulkPay.unpaidReportNames.push(reportName); + } + showUnpaidReportsIfSettled(bulkPay); + return true; + } + return false; +} + +export {followGlobalReimbursementsBulkPay, settleGlobalReimbursementsBulkPayReport}; diff --git a/src/libs/formatReportNamesAsBulletList.ts b/src/libs/formatReportNamesAsBulletList.ts new file mode 100644 index 000000000000..c20633ab5157 --- /dev/null +++ b/src/libs/formatReportNamesAsBulletList.ts @@ -0,0 +1,8 @@ +import CONST from '@src/CONST'; + +/** Lists report names one per line, each after a bullet, for the prompt of a confirm modal */ +function formatReportNamesAsBulletList(reportNames: Iterable): string { + return Array.from(reportNames, (reportName) => `${CONST.DOT_SEPARATOR} ${reportName}`).join('\n'); +} + +export default formatReportNamesAsBulletList; diff --git a/src/types/onyx/EnableGlobalReimbursementsModal.ts b/src/types/onyx/EnableGlobalReimbursementsModal.ts index cde236c98368..0fb0f7eae3dd 100644 --- a/src/types/onyx/EnableGlobalReimbursementsModal.ts +++ b/src/types/onyx/EnableGlobalReimbursementsModal.ts @@ -8,6 +8,10 @@ type EnableGlobalReimbursementsModal = { bankCurrency: string; /** Whether bulk pay could not pay any of several selected reports, set only by the client so the intro explains it for all of them */ isPayingMultipleReports?: boolean; + /** The names of the reports bulk pay left unpaid while paying others, set only by the client so they are listed before the intro opens */ + unpaidReportNames?: string[]; + /** The masked number of the bank account, set with unpaidReportNames so the list can name the account */ + accountNumber?: string; }; export default EnableGlobalReimbursementsModal; diff --git a/tests/ui/components/EnableGlobalReimbursementsPayModalTest.tsx b/tests/ui/components/EnableGlobalReimbursementsPayModalTest.tsx index 4f099cb67f32..bc2925d56804 100644 --- a/tests/ui/components/EnableGlobalReimbursementsPayModalTest.tsx +++ b/tests/ui/components/EnableGlobalReimbursementsPayModalTest.tsx @@ -4,6 +4,7 @@ import ComposeProviders from '@components/ComposeProviders'; import EnableGlobalReimbursementsPayModal from '@components/EnableGlobalReimbursementsPayModal'; import {LocaleContextProvider} from '@components/LocaleContextProvider'; import LockedAccountModalProvider from '@components/LockedAccountModalProvider'; +import {ModalActions} from '@components/Modal/Global/ModalContext'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; import Navigation from '@libs/Navigation/Navigation'; @@ -26,10 +27,17 @@ jest.mock('@libs/Navigation/Navigation', () => ({ })); // The confirm modal is UI the global modal host renders, so the test only checks what it was asked to show -const mockShowConfirmModal = jest.fn(() => Promise.resolve({action: 'CLOSE'})); +const mockShowConfirmModal = jest.fn, [{id?: string; title?: string; prompt?: string}]>(() => Promise.resolve({action: 'CLOSE'})); jest.mock('@hooks/useConfirmModal', () => jest.fn(() => ({showConfirmModal: mockShowConfirmModal}))); +// The bulk pay modal waits for the pay popover to dismiss, which never happens under Jest +jest.mock('@libs/deferModalPresentationAfterPopoverDismiss', () => ({ + __esModule: true, + default: (presentModal: () => void) => presentModal(), +})); + const BANK_ACCOUNT_ID = 9053192; +const ACCOUNT_NUMBER = 'XXXXXX1234'; const INTRO_ROUTE = `r/123/global-reimbursements/${BANK_ACCOUNT_ID}`; function createBusinessBankAccount(globalReimbursementProvider: ValueOf | undefined, wise: BankAccountAdditionalData['wise']): BankAccount { @@ -46,7 +54,12 @@ function createBusinessBankAccount(globalReimbursementProvider: ValueOf { await Onyx.set(ONYXKEYS.BETAS, betas); await Onyx.set(ONYXKEYS.NVP_PRIVATE_LOCK_ACCOUNT_DETAILS, {isLocked: isAccountLocked}); @@ -60,7 +73,12 @@ async function blockPay({betas = [CONST.BETAS.WISE_REIMBURSEMENTS], isAccountLoc await waitForBatchedUpdatesWithAct(); await act(async () => { - await Onyx.set(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, {bankAccountID: BANK_ACCOUNT_ID, bankCountry: CONST.COUNTRY.US, bankCurrency: CONST.CURRENCY.USD}); + await Onyx.set(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL, { + bankAccountID: BANK_ACCOUNT_ID, + bankCountry: CONST.COUNTRY.US, + bankCurrency: CONST.CURRENCY.USD, + ...(unpaidReportNames ? {unpaidReportNames, accountNumber: ACCOUNT_NUMBER} : {}), + }); }); await waitForBatchedUpdatesWithAct(); } @@ -112,4 +130,32 @@ describe('EnableGlobalReimbursementsPayModal', () => { expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.not.objectContaining({id: 'corpayPayModal'})); expect(Navigation.navigate).not.toHaveBeenCalled(); }); + + describe('Search bulk pay', () => { + it('lists the reports bulk pay left unpaid instead of opening the intro', async () => { + // Given an admin on the Wise beta + // When bulk pay paid some reports and left two unpaid because the account needs global reimbursements + await blockPay({unpaidReportNames: ['Report B', 'Report C']}); + + // Then one modal lists them under the last four digits of the paying account, and the intro waits for the admin to ask for it + expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); + const modalOptions = mockShowConfirmModal.mock.calls.at(0)?.at(0); + expect(modalOptions?.title).toContain('1234'); + expect(modalOptions?.prompt).toBe(`${CONST.DOT_SEPARATOR} Report B\n${CONST.DOT_SEPARATOR} Report C`); + expect(Navigation.navigate).not.toHaveBeenCalled(); + }); + + it('opens the intro when the admin picks Get started', async () => { + // Given an admin who confirms the list of unpaid reports + mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); + + // When bulk pay left a report unpaid + await blockPay({unpaidReportNames: ['Report B']}); + + // Then the intro opens once for the paying account, without listing the reports again + expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); + expect(Navigation.navigate).toHaveBeenCalledTimes(1); + expect(Navigation.navigate).toHaveBeenCalledWith(INTRO_ROUTE, {skipMatchingFullScreenRoute: true}); + }); + }); }); diff --git a/tests/unit/GlobalReimbursementPayErrorTest.ts b/tests/unit/GlobalReimbursementPayErrorTest.ts index 2338cb7d27c6..481f9751e3bf 100644 --- a/tests/unit/GlobalReimbursementPayErrorTest.ts +++ b/tests/unit/GlobalReimbursementPayErrorTest.ts @@ -1,3 +1,4 @@ +import {followGlobalReimbursementsBulkPay} from '@libs/actions/GlobalReimbursementsBulkPay'; import {WRITE_COMMANDS} from '@libs/API/types'; import globalReimbursementPayError from '@libs/Middleware/GlobalReimbursementPayError'; @@ -9,6 +10,11 @@ import type Response from '@src/types/onyx/Response'; import type {OnyxKey} from 'react-native-onyx'; +import Onyx from 'react-native-onyx'; + +import getOnyxValue from '../utils/getOnyxValue'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + const IOU_REPORT_ID = '12345'; const REPORT_ACTION_ID = '67890'; const OTHER_REPORT_ACTION_ID = '11111'; @@ -85,6 +91,102 @@ describe('GlobalReimbursementPayError middleware', () => { }); }); + describe('Search bulk pay', () => { + const BANK_ACCOUNT = {bankAccountID: 100, bankCountry: CONST.COUNTRY.US, bankCurrency: CONST.CURRENCY.USD}; + const OTHER_IOU_REPORT_ID = '54321'; + + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + await Onyx.clear(); + }); + + it('holds back the backend signal and lists the rejected report once every payment of the click has a response', async () => { + // Given a bulk pay click that pays two reports + followGlobalReimbursementsBulkPay({ + bankAccount: BANK_ACCOUNT, + pendingReportNames: new Map([ + [IOU_REPORT_ID, 'Rejected report'], + [OTHER_IOU_REPORT_ID, 'Paid report'], + ]), + skippedReportNames: [], + hasPaidReports: false, + }); + const request = buildPayRequest(); + const response = buildEnableGlobalReimbursementsModalResponse(); + + // When the backend rejects the first payment because the account needs global reimbursements + const result = await globalReimbursementPayError(Promise.resolve(response), request, false); + await waitForBatchedUpdates(); + + // Then the signal doesn't open the global reimbursements intro for this single rejection, and nothing shows while the other payment is in flight + expect(result).toBe(response); + expect(response.onyxData?.some((update) => update.key === ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBe(false); + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); + // And the failed PAY action is still dropped, the same as for a single payment + expect(findFailureUpdate(request, `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${IOU_REPORT_ID}`)?.value).toEqual({ + [REPORT_ACTION_ID]: null, + [OTHER_REPORT_ACTION_ID]: {errors: {error: 'Other error'}}, + }); + + // When the other payment goes through + const otherRequest = buildPayRequest({data: {iouReportID: OTHER_IOU_REPORT_ID, reportActionID: REPORT_ACTION_ID}}); + await globalReimbursementPayError(Promise.resolve({jsonCode: CONST.JSON_CODE.SUCCESS, onyxData: []}), otherRequest, false); + await waitForBatchedUpdates(); + + // Then the rejected report is listed next to the paid one + expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual({...BANK_ACCOUNT, unpaidReportNames: ['Rejected report']}); + }); + }); + + it('keeps the backend signal for a payment outside of bulk pay', async () => { + // Given a pay request that isn't part of a bulk pay run + const request = buildPayRequest(); + const response = buildEnableGlobalReimbursementsModalResponse(); + + // When the backend rejects the payment because the account needs global reimbursements + await globalReimbursementPayError(Promise.resolve(response), request, false); + + // Then the signal stays, so the global reimbursements intro opens right away as before + expect(response.onyxData?.some((update) => update.key === ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBe(true); + }); + + it('drops the generic report error that Search pay adds to failureData when payment fails with enableGlobalReimbursementsModal', async () => { + // Given a pay request from Search, whose failureData puts a generic error on the report + const request = buildPayRequest(); + const reportUpdate = findFailureUpdate(request, `${ONYXKEYS.COLLECTION.REPORT}${IOU_REPORT_ID}`); + expect(reportUpdate).toBeDefined(); + if (reportUpdate) { + reportUpdate.value = {statusNum: CONST.REPORT.STATUS_NUM.OPEN, errors: {error: 'Generic error'}}; + } + const response = buildEnableGlobalReimbursementsModalResponse(); + + // When the backend rejects the payment because the account needs global reimbursements + await globalReimbursementPayError(Promise.resolve(response), request, false); + + // Then the report keeps its other failure updates but not the error, because the global reimbursements setup explains the rejection + expect(findFailureUpdate(request, `${ONYXKEYS.COLLECTION.REPORT}${IOU_REPORT_ID}`)?.value).toEqual({statusNum: CONST.REPORT.STATUS_NUM.OPEN}); + }); + + it('keeps the generic report error when the payment fails for another reason', async () => { + // Given a pay request from Search, whose failureData puts a generic error on the report + const request = buildPayRequest(); + const reportUpdate = findFailureUpdate(request, `${ONYXKEYS.COLLECTION.REPORT}${IOU_REPORT_ID}`); + expect(reportUpdate).toBeDefined(); + if (reportUpdate) { + reportUpdate.value = {statusNum: CONST.REPORT.STATUS_NUM.OPEN, errors: {error: 'Generic error'}}; + } + const response: Response = {jsonCode: CONST.JSON_CODE.EXP_ERROR, onyxData: []}; + + // When the payment fails without the global reimbursements signal + await globalReimbursementPayError(Promise.resolve(response), request, false); + + // Then the error stays, because nothing else tells the admin the payment failed + expect(findFailureUpdate(request, `${ONYXKEYS.COLLECTION.REPORT}${IOU_REPORT_ID}`)?.value).toEqual({statusNum: CONST.REPORT.STATUS_NUM.OPEN, errors: {error: 'Generic error'}}); + }); + it('works identically for PAY_MONEY_REQUEST_WITH_WALLET command', async () => { const request = buildPayRequest({command: WRITE_COMMANDS.PAY_MONEY_REQUEST_WITH_WALLET}); const response = buildEnableGlobalReimbursementsModalResponse(); diff --git a/tests/unit/GlobalReimbursementsBulkPayTest.ts b/tests/unit/GlobalReimbursementsBulkPayTest.ts new file mode 100644 index 000000000000..0f9ea87d240a --- /dev/null +++ b/tests/unit/GlobalReimbursementsBulkPayTest.ts @@ -0,0 +1,150 @@ +import {followGlobalReimbursementsBulkPay, settleGlobalReimbursementsBulkPayReport} from '@libs/actions/GlobalReimbursementsBulkPay'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import Onyx from 'react-native-onyx'; + +import getOnyxValue from '../utils/getOnyxValue'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +const INTRO_DATA = {bankAccountID: 99, bankCountry: CONST.COUNTRY.US, bankCurrency: CONST.CURRENCY.USD}; +const BANK_ACCOUNT = {...INTRO_DATA, accountNumber: 'XXXXXX1234'}; +const PAID = {isPaid: true, needsGlobalReimbursements: false}; +const REJECTED = {isPaid: false, needsGlobalReimbursements: true}; +const FAILED = {isPaid: false, needsGlobalReimbursements: false}; + +async function getModalData() { + await waitForBatchedUpdates(); + return getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL); +} + +describe('GlobalReimbursementsBulkPay', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + await Onyx.clear(); + }); + + it('lists the skipped and the rejected reports in one modal after the last response', async () => { + // Given a click that pays reports A and C and skips report B + followGlobalReimbursementsBulkPay({ + bankAccount: BANK_ACCOUNT, + pendingReportNames: new Map([ + ['A', 'Report A'], + ['C', 'Report C'], + ]), + skippedReportNames: ['Report B'], + hasPaidReports: false, + }); + + // When report A is paid + expect(settleGlobalReimbursementsBulkPayReport('A', PAID)).toBe(true); + + // Then nothing shows yet, because report C could still be rejected and belongs in the same modal + expect(await getModalData()).toBeUndefined(); + + // When the backend rejects report C + expect(settleGlobalReimbursementsBulkPayReport('C', REJECTED)).toBe(true); + + // Then one modal lists both unpaid reports for the paying account + expect(await getModalData()).toEqual({...BANK_ACCOUNT, unpaidReportNames: ['Report B', 'Report C']}); + }); + + it('opens the intro for several reports when the only payment is rejected next to a skipped report', async () => { + // Given a click that pays one report and skips another + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: ['Report B'], hasPaidReports: false}); + + // When the backend rejects the payment + settleGlobalReimbursementsBulkPayReport('A', REJECTED); + + // Then the intro opens without a list, because no report was paid to list them next to + expect(await getModalData()).toEqual({...INTRO_DATA, isPayingMultipleReports: true}); + }); + + it('opens the intro for one report right away when the click only skipped that report', async () => { + // Given a click with nothing to pay + // When it skips its only report + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map(), skippedReportNames: ['Report B'], hasPaidReports: false}); + + // Then the intro opens with the copy for one report, without waiting for any response + expect(await getModalData()).toEqual({...INTRO_DATA, isPayingMultipleReports: false}); + }); + + it('lists a rejected report next to payments it does not wait for, like invoices', async () => { + // Given a click that already paid invoices and pays one expense report + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: [], hasPaidReports: true}); + + // When the backend rejects the expense report + settleGlobalReimbursementsBulkPayReport('A', REJECTED); + + // Then the list shows, because the invoices count as paid + expect(await getModalData()).toEqual({...BANK_ACCOUNT, unpaidReportNames: ['Report A']}); + }); + + it('does not count a payment that failed for another reason as paid, and does not list it', async () => { + // Given a click that pays one report and skips another + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: ['Report B'], hasPaidReports: false}); + + // When the payment fails without the global reimbursements signal + settleGlobalReimbursementsBulkPayReport('A', FAILED); + + // Then the intro opens for the skipped report alone, because the failed one shows its own error + expect(await getModalData()).toEqual({...INTRO_DATA, isPayingMultipleReports: false}); + }); + + it('shows nothing when every report was paid', async () => { + // Given a click that pays one report and skips none + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: [], hasPaidReports: false}); + + // When the payment goes through + settleGlobalReimbursementsBulkPayReport('A', PAID); + + // Then no modal interrupts the admin + expect(await getModalData()).toBeUndefined(); + }); + + it('gives each click its own modal, even when an earlier click never gets a response', async () => { + // Given a first click whose payment never gets a response, and a second click + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: ['Report B'], hasPaidReports: false}); + followGlobalReimbursementsBulkPay({ + bankAccount: BANK_ACCOUNT, + pendingReportNames: new Map([ + ['C', 'Report C'], + ['D', 'Report D'], + ]), + skippedReportNames: [], + hasPaidReports: false, + }); + + // When the payments of the second click have their responses + settleGlobalReimbursementsBulkPayReport('C', PAID); + settleGlobalReimbursementsBulkPayReport('D', REJECTED); + + // Then the second click lists only its own report + expect(await getModalData()).toEqual({...BANK_ACCOUNT, unpaidReportNames: ['Report D']}); + }); + + it('forgets an earlier click that still waits for a report the admin pays again', async () => { + // Given a click whose payment of report A never gets a response, and a later click that pays report A again + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: ['Stale report'], hasPaidReports: true}); + followGlobalReimbursementsBulkPay({bankAccount: BANK_ACCOUNT, pendingReportNames: new Map([['A', 'Report A']]), skippedReportNames: [], hasPaidReports: true}); + + // When the backend rejects report A + settleGlobalReimbursementsBulkPayReport('A', REJECTED); + + // Then the later click lists it, without the report the earlier click skipped + expect(await getModalData()).toEqual({...BANK_ACCOUNT, unpaidReportNames: ['Report A']}); + }); + + it('leaves a payment outside of bulk pay to the caller', () => { + // Given no bulk pay click that pays the report + // When its payment is rejected + const isBulkPayReport = settleGlobalReimbursementsBulkPayReport('unknown', REJECTED); + + // Then the caller keeps the backend signal, so the intro opens as it does for a single report + expect(isBulkPayReport).toBe(false); + }); +}); diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 9c088f390014..16f7a41ee677 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -8,6 +8,7 @@ import type {SearchQueryJSON, SelectedReports, SelectedTransactions} from '@comp import useSearchBulkActions from '@hooks/useSearchBulkActions'; import type {SearchHeaderOptionValue} from '@hooks/useSearchBulkActions'; +import {followGlobalReimbursementsBulkPay} from '@libs/actions/GlobalReimbursementsBulkPay'; import {payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest'; import type * as PayMoneyRequestActions from '@libs/actions/IOU/PayMoneyRequest'; import {getLastPolicyPaymentMethod, queueBulkPayReports} from '@libs/actions/Search'; @@ -55,6 +56,18 @@ jest.mock('@libs/actions/Wise', () => ({ getWiseQuote: jest.fn(), })); +// The modal that lists the unpaid reports shows once the payments have a response, so these tests check what bulk pay hands over to it +jest.mock('@libs/actions/GlobalReimbursementsBulkPay', () => ({ + followGlobalReimbursementsBulkPay: jest.fn(), +})); + +// Only the leader tab sends the queued requests, so the tests choose which tab pays +let mockIsClientTheLeader = true; +jest.mock('@libs/ActiveClientManager', () => ({ + ...jest.requireActual>('@libs/ActiveClientManager'), + isClientTheLeader: () => mockIsClientTheLeader, +})); + let mockShouldConfirmWiseQuote = false; jest.mock('@libs/BankAccountUtils', () => ({ ...jest.requireActual>('@libs/BankAccountUtils'), @@ -131,7 +144,7 @@ jest.mock('@libs/Navigation/Navigation', () => ({ jest.mock('@hooks/useLocalize', () => ({ __esModule: true, default: () => ({ - translate: (key: string, ...params: unknown[]) => (key === 'walletPage.wiseGlobalReimbursementsBulkPayModal.title' ? `${key}(${params.join(',')})` : key), + translate: (key: string) => key, localeCompare: (first: string, second: string) => first && second, formatPhoneNumber: (phone: string) => phone, }), @@ -798,6 +811,7 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs afterEach(async () => { mockEnabledBetas = new Set(); mockShouldConfirmWiseQuote = false; + mockIsClientTheLeader = true; await Onyx.clear(); }); @@ -812,7 +826,13 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs }); } - it('pays the other reports and lists the ones that need global reimbursements in a modal', async () => { + function getFollowedBulkPay() { + return jest.mocked(followGlobalReimbursementsBulkPay).mock.calls.at(0)?.at(0); + } + + const PAID_REPORT_ID = '3'; + + it('pays the other reports and hands over the ones that need global reimbursements', async () => { // Given one flagged report of a workspace whose account has no global reimbursements, and one flagged report of a workspace whose account has them // When the user selects bulk Pay @@ -825,15 +845,27 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // And the selection is cleared, the same as after any bulk pay that paid at least one report expect(mockClearSelectedTransactions).toHaveBeenCalledTimes(1); - // And a single modal lists the skipped report, so the user knows which reports still need global reimbursements - expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); - expect(mockShowConfirmModal).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'walletPage.wiseGlobalReimbursementsBulkPayModal.title(1234)', - prompt: `${CONST.DOT_SEPARATOR} Report needing GR`, - confirmText: 'walletPage.wiseGlobalReimbursementsIntro.getStarted', - }), - ); + // And the skipped report is handed over with the paying account and the payment to wait for, so a backend rejection ends up in the same modal + expect(followGlobalReimbursementsBulkPay).toHaveBeenCalledTimes(1); + expect(getFollowedBulkPay()).toEqual({ + bankAccount: {bankAccountID: BANK_ACCOUNT_ID, bankCountry: 'US', bankCurrency: CONST.CURRENCY.USD, accountNumber: 'XXXXXX1234'}, + pendingReportNames: new Map([[PAID_REPORT_ID, 'Payable report']]), + skippedReportNames: ['Report needing GR'], + hasPaidReports: false, + }); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + }); + + it('lists the skipped reports right away from a tab that does not send the requests', async () => { + // Given the mixed selection from the first test, paid from a tab that isn't the leader, which only queues the requests + mockIsClientTheLeader = false; + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then no payment is waited for, because its response arrives in the leader tab, and the paid report is counted right away + expect(payMoneyRequest).toHaveBeenCalledTimes(1); + expect(getFollowedBulkPay()).toEqual(expect.objectContaining({pendingReportNames: new Map(), skippedReportNames: ['Report needing GR'], hasPaidReports: true})); }); it('skips a flagged report when the bank account comes without the global reimbursements flag', async () => { @@ -852,8 +884,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '3'})})); - // And the modal lists the skipped report instead of the backend opening the onboarding after a failed payment - expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + // And the skipped report is handed over instead of the backend opening the onboarding after a failed payment + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['Report needing GR']); }); it('pays every report and shows no modal when the global reimbursements beta is off', async () => { @@ -867,6 +899,9 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(payMoneyRequest).toHaveBeenCalledTimes(2); expect(mockShowConfirmModal).not.toHaveBeenCalled(); expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); + + // And the payments aren't followed, so each backend rejection opens the setup as it does for a single report + expect(followGlobalReimbursementsBulkPay).not.toHaveBeenCalled(); }); it('pays a report the backend does not flag for global reimbursements, even from an account without them', async () => { @@ -880,8 +915,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '9'})})); - // And the modal lists only the flagged report - expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + // And only the flagged report is handed over as skipped + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['Report needing GR']); }); async function payWithBankAccount(bankAccountID: number) { @@ -901,10 +936,10 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // When the user picks another account without global reimbursements in the bulk Pay menu await payWithBankAccount(OTHER_BANK_ACCOUNT_ID); - // Then the report is paid from that account and no modal opens, because the flag says nothing about it + // Then the report is paid from that account and nothing is skipped, because the flag says nothing about it expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '1'}), methodID: OTHER_BANK_ACCOUNT_ID})); - expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(getFollowedBulkPay()?.skippedReportNames).toEqual([]); expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); }); @@ -918,37 +953,7 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // Then only the domestic report is paid, because the flag describes exactly this account expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '9'})})); - expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); - }); - - it('opens the global reimbursements onboarding when the user picks Get started', async () => { - // Given a mixed selection and a user who confirms the modal - mockShowConfirmModal.mockReturnValueOnce(Promise.resolve({action: ModalActions.CONFIRM})); - - // When the user selects bulk Pay - await selectBulkPay(); - - // Then the onboarding signal is set for the paying bank account, so the existing intro flow takes over - await waitFor(async () => { - expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual({ - bankAccountID: BANK_ACCOUNT_ID, - bankCountry: 'US', - bankCurrency: CONST.CURRENCY.USD, - }); - }); - }); - - it('does not open the onboarding when the user picks Not now', async () => { - // Given a mixed selection and a user who dismisses the modal - - // When the user selects bulk Pay - await selectBulkPay(); - - // Then the onboarding stays closed, because the user chose to set it up later - await waitFor(() => { - expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); - }); - expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['Report needing GR']); }); it('pays a report of another workspace from the same bank account instead of skipping it', async () => { @@ -962,14 +967,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '5'}), methodID: BANK_ACCOUNT_ID})); - // And the modal lists the first report, which that account can't pay until it sets up global reimbursements - expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); - expect(mockShowConfirmModal).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'walletPage.wiseGlobalReimbursementsBulkPayModal.title(1234)', - prompt: `${CONST.DOT_SEPARATOR} Report needing GR`, - }), - ); + // And the first report is handed over under that account, which can't pay it until it sets up global reimbursements + expect(getFollowedBulkPay()).toEqual(expect.objectContaining({bankAccount: expect.objectContaining({bankAccountID: BANK_ACCOUNT_ID}), skippedReportNames: ['Report needing GR']})); }); it('lists a report once when several of its expenses are selected', async () => { @@ -984,8 +983,8 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // When the user selects bulk Pay await selectBulkPay(); - // Then the report appears once in the modal, because it is one report the user has to set up global reimbursements for - expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + // Then the report is handed over once, because it is one report the user has to set up global reimbursements for + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['Report needing GR']); }); it('falls back to a generic name for a skipped report without a name', async () => { @@ -995,11 +994,11 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // When the user selects bulk Pay await selectBulkPay(); - // Then the modal still lists the report, so the list is never empty - expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} common.report`})); + // Then the report is still handed over, so the modal list is never empty + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['common.report']); }); - it('opens the onboarding directly when the only selected report needs global reimbursements', async () => { + it('hands over the only selected report with nothing paid next to it', async () => { // Given a single selected report that needs global reimbursements mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'})]; @@ -1010,32 +1009,23 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs expect(payMoneyRequest).not.toHaveBeenCalled(); expect(mockClearSelectedTransactions).not.toHaveBeenCalled(); - // And the onboarding opens without the modal, the same way paying a single report does, with the copy for one report - expect(mockShowConfirmModal).not.toHaveBeenCalled(); - expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual({ - bankAccountID: BANK_ACCOUNT_ID, - bankCountry: 'US', - bankCurrency: CONST.CURRENCY.USD, - isPayingMultipleReports: false, - }); + // And the report is handed over with nothing paid or pending, so the onboarding opens directly, the same way paying a single report does + expect(getFollowedBulkPay()).toEqual(expect.objectContaining({pendingReportNames: new Map(), skippedReportNames: ['Report needing GR'], hasPaidReports: false})); }); - it('opens the onboarding directly with the copy for several reports when none of them can be paid', async () => { + it('hands over every selected report when none of them can be paid', async () => { // Given two selected reports paid from the same bank account that needs global reimbursements mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: '2'}), makeSelectedReport({reportID: '7', chatReportID: '8'})]; // When the user selects bulk Pay await selectBulkPay(); - // Then nothing is paid and the onboarding opens without the modal, because there are no paid reports to report on + // Then nothing is paid and both reports are handed over, so the onboarding explains that all the selected reports need it expect(payMoneyRequest).not.toHaveBeenCalled(); - expect(mockShowConfirmModal).not.toHaveBeenCalled(); - - // And the onboarding explains that all the selected reports need it - expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toEqual(expect.objectContaining({bankAccountID: BANK_ACCOUNT_ID, isPayingMultipleReports: true})); + expect(getFollowedBulkPay()).toEqual(expect.objectContaining({skippedReportNames: ['Report needing GR', 'Second report needing GR'], hasPaidReports: false})); }); - it('lists the skipped reports only after the Wise quote carousel closes', async () => { + it('hands over the skipped reports only once the Wise quotes are confirmed', async () => { // Given a report that needs global reimbursements and a payable report whose expenses need a Wise quote mockShouldConfirmWiseQuote = true; const PAYABLE_REPORT_ID = '3'; @@ -1050,10 +1040,10 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // When the user selects bulk Pay await selectBulkPay(); - // Then the carousel opens and nothing is paid yet, while the skipped report waits so the two modals don't stack + // Then the carousel opens and nothing is paid or handed over yet, because cancelling the carousel backs out of bulk pay expect(mockShowWiseQuoteCarouselModal).toHaveBeenCalledTimes(1); expect(payMoneyRequest).not.toHaveBeenCalled(); - expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(followGlobalReimbursementsBulkPay).not.toHaveBeenCalled(); // When the user confirms the quotes and the carousel closes await act(async () => { @@ -1064,10 +1054,10 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs resolveCarouselClose?.({action: ModalActions.CONFIRM}); }); - // Then the payable report is paid with its quote, and the modal lists the skipped report + // Then the payable report is paid with its quote, and the skipped report is handed over with that payment to wait for expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: PAYABLE_REPORT_ID}), wiseQuoteID: 'quote3'})); - expect(mockShowConfirmModal).toHaveBeenCalledWith(expect.objectContaining({prompt: `${CONST.DOT_SEPARATOR} Report needing GR`})); + expect(getFollowedBulkPay()).toEqual(expect.objectContaining({pendingReportNames: new Map([[PAYABLE_REPORT_ID, 'Payable report']]), skippedReportNames: ['Report needing GR']})); }); it('does not show the modal when no report needs global reimbursements', async () => { @@ -1077,9 +1067,10 @@ describe('useSearchBulkActions - bulk pay with reports that need global reimburs // When the user selects bulk Pay await selectBulkPay(); - // Then the report is paid and no modal interrupts the user + // Then the report is paid and nothing is skipped, so no modal interrupts the user unless the backend rejects it expect(payMoneyRequest).toHaveBeenCalledTimes(1); expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(getFollowedBulkPay()?.skippedReportNames).toEqual([]); }); }); From 7736683669d396b39fd1f1cdbef2e9f673edb6c3 Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 19 Nov 2026 14:09:59 +0100 Subject: [PATCH 19/20] Keep reports in place until the backend answers a payment it may reject for global reimbursements --- .../PayPrimaryAction.tsx | 5 +- .../PayActionButton.tsx | 6 +- src/libs/BankAccountUtils.ts | 18 +++++- src/libs/actions/IOU/PayMoneyRequest.ts | 54 ++++++++++++++++-- tests/actions/IOUTest/PayMoneyRequestTest.ts | 55 +++++++++++++++++++ 5 files changed, 127 insertions(+), 11 deletions(-) diff --git a/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx b/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx index aa6a1deaa3c7..ccef3cc4b8b8 100644 --- a/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx +++ b/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx @@ -40,6 +40,7 @@ import ROUTES from '@src/ROUTES'; import type {Transaction} from '@src/types/onyx'; import {hasSeenTourSelector} from '@selectors/Onboarding'; +import {isActionLoadingSelector} from '@selectors/ReportMetaData'; import React from 'react'; import Onyx from 'react-native-onyx'; @@ -69,6 +70,8 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(moneyRequestReport?.policyID)}`); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); + // The button keeps loading while an action on the report is in flight, such as a payment held until the backend answers, so it can't be paid twice + const [isPaymentInFlight] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${getNonEmptyStringOnyxID(moneyRequestReport?.reportID)}`, {selector: isActionLoadingSelector}); const activePolicy = usePolicy(activePolicyID); const chatReportPolicy = usePolicy(chatReport?.policyID); @@ -257,7 +260,7 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS} shouldHidePaymentOptions={!shouldShowPayButton} isDisabled={(isOffline && !canAllowSettlement) || isDisabled} - isLoading={(!isOffline && !canAllowSettlement) || isDownloadingABAFile} + isLoading={(!isOffline && !canAllowSettlement) || isDownloadingABAFile || !!isPaymentInFlight} /> ); } diff --git a/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx b/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx index f12353fe9608..71cb6e22b4e3 100644 --- a/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx +++ b/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx @@ -19,6 +19,7 @@ import usePermissions from '@hooks/usePermissions'; import usePolicy from '@hooks/usePolicy'; import {generateDefaultWorkspaceName} from '@libs/actions/Policy/Policy'; +import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import getHoldMenuAmounts from '@libs/HoldMenuUtils'; import {getTotalAmountForIOUReportPreviewButton} from '@libs/MoneyRequestReportUtils'; import {isTrackOnboardingChoice} from '@libs/OnboardingUtils'; @@ -33,6 +34,7 @@ import ROUTES from '@src/ROUTES'; import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; import {hasSeenTourSelector} from '@selectors/Onboarding'; +import {isActionLoadingSelector} from '@selectors/ReportMetaData'; import React from 'react'; import Onyx from 'react-native-onyx'; @@ -61,6 +63,8 @@ function PayActionButton() { const {reportPreviewAction, canIOUBePaid, onlyShowPayElsewhere, shouldShowPayButton} = useReportPreviewActionState(); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); + // The button keeps loading while an action on the report is in flight, such as a payment held until the backend answers, so it can't be paid twice + const [isPaymentInFlight] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${getNonEmptyStringOnyxID(iouReportID)}`, {selector: isActionLoadingSelector}); const activePolicy = usePolicy(activePolicyID); const actionButtonData = useReportPreviewActionButtonData(iouReportID); const {iouReport, policy, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd} = actionButtonData; @@ -205,7 +209,7 @@ function PayActionButton() { vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM, }} isDisabled={isOffline && !canAllowSettlement} - isLoading={(!isOffline && !canAllowSettlement) || isDownloadingABAFile} + isLoading={(!isOffline && !canAllowSettlement) || isDownloadingABAFile || !!isPaymentInFlight} sentryLabel={CONST.SENTRY_LABEL.REPORT_PREVIEW.PAY_BUTTON} /> ); diff --git a/src/libs/BankAccountUtils.ts b/src/libs/BankAccountUtils.ts index 7980bb74e6c5..65d2e8594ebe 100644 --- a/src/libs/BankAccountUtils.ts +++ b/src/libs/BankAccountUtils.ts @@ -254,13 +254,24 @@ type WiseQuotePaymentParams = { wiseQuoteID?: string; }; -/** The Wise account a business bank account payment debits. Without a chosen account the backend pays from the workspace account */ -function getWiseBankAccountForPayment({paymentType, methodID, bankAccountList, isWiseReimbursementsBetaEnabled, policy}: WiseQuotePaymentParams): OnyxTypes.BankAccount | undefined { +/** The business bank account a payment debits, for admins in the Wise beta. Without a chosen account the backend pays from the workspace account */ +function getBusinessBankAccountForPayment({ + paymentType, + methodID, + bankAccountList, + isWiseReimbursementsBetaEnabled, + policy, +}: Pick): OnyxTypes.BankAccount | undefined { const bankAccountID = methodID ?? policy?.achAccount?.bankAccountID; if (!isWiseReimbursementsBetaEnabled || paymentType !== CONST.IOU.PAYMENT_TYPE.VBBA || !bankAccountID) { return undefined; } - const bankAccount = bankAccountList?.[bankAccountID]; + return bankAccountList?.[bankAccountID]; +} + +/** The Wise account a business bank account payment debits */ +function getWiseBankAccountForPayment(params: WiseQuotePaymentParams): OnyxTypes.BankAccount | undefined { + const bankAccount = getBusinessBankAccountForPayment(params); const isWiseAccount = isGlobalReimbursementsEnabled(bankAccount) && bankAccount?.accountData?.additionalData?.globalReimbursementProvider === CONST.GLOBAL_REIMBURSEMENT_PROVIDER.WISE; return isWiseAccount ? bankAccount : undefined; } @@ -562,6 +573,7 @@ function showUnlockAlreadyRequestedModal(showConfirmModal: ReturnType, +): boolean { + return shouldSetUpGlobalReimbursementsBeforePaying(getBusinessBankAccountForPayment(params)); +} + +/** + * Holds the optimistic payment back until the backend answers. Showing the report as paid and then rolling it back on a global reimbursements + * rejection makes it drop out of the lists and come back, so the report only shows a loading state while the payment is in flight. + * On success the response carries the paid report, and only the last used payment method, which the backend doesn't send back, is saved. + * On failure the optimistic data is applied before the failure data, so a failure ends in the same state it would after an optimistic + * payment, and the failure data never merges errors into report actions that don't exist. + */ +function holdOptimisticPayOnyxDataUntilResponse(onyxData: OnyxData, iouReportID: string): OnyxData { + const loadingStateKey = `${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${iouReportID}` as const; + const loadingStateOnyxData: AdditionalPayOnyxData = { + optimisticData: [{onyxMethod: Onyx.METHOD.MERGE, key: loadingStateKey, value: {isActionLoading: true}}], + successData: [{onyxMethod: Onyx.METHOD.MERGE, key: loadingStateKey, value: {isActionLoading: false}}], + failureData: [{onyxMethod: Onyx.METHOD.MERGE, key: loadingStateKey, value: {isActionLoading: false}}], + }; + const heldOnyxData: OnyxData = { + ...onyxData, + optimisticData: [], + successData: [...(onyxData.successData ?? []), ...(onyxData.optimisticData ?? []).filter((update) => update.key === ONYXKEYS.NVP_LAST_PAYMENT_METHOD)], + failureData: [...(onyxData.optimisticData ?? []), ...(onyxData.failureData ?? [])], + }; + return mergeAdditionalPayOnyxData(heldOnyxData, loadingStateOnyxData); +} + function payMoneyRequest(params: PayMoneyRequestFunctionParams) { const { paymentType, @@ -1026,11 +1060,19 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { // Expensify Wallets. const apiCommand = paymentType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY ? WRITE_COMMANDS.PAY_MONEY_REQUEST_WITH_WALLET : WRITE_COMMANDS.PAY_MONEY_REQUEST; - onPaid?.(); - if (shouldPlaySuccessSound) { - playSound(SOUNDS.SUCCESS); + // Offline the payment is queued and has to show as paid right away, and a partial payment creates the report for the held expenses optimistically + const shouldHoldOptimisticPayment = + full && !getIsOffline() && !!iouReport?.reportID && canGlobalReimbursementsRejectPayment({paymentType, policy, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); + const requestOnyxData = shouldHoldOptimisticPayment && iouReport?.reportID ? holdOptimisticPayOnyxDataUntilResponse(onyxData, iouReport.reportID) : onyxData; + + // A held payment may still be rejected, so it doesn't celebrate before the backend answers + if (!shouldHoldOptimisticPayment) { + onPaid?.(); + if (shouldPlaySuccessSound) { + playSound(SOUNDS.SUCCESS); + } } - API.write(apiCommand, {...payMoneyRequestParams, wiseQuoteID}, mergeAdditionalPayOnyxData(onyxData, additionalOnyxData)); + API.write(apiCommand, {...payMoneyRequestParams, wiseQuoteID}, mergeAdditionalPayOnyxData(requestOnyxData, additionalOnyxData)); notifyNewAction(!full ? (Navigation.getTopmostReportId() ?? iouReport?.reportID) : iouReport?.reportID, undefined, true); return payMoneyRequestParams.optimisticHoldReportID; } diff --git a/tests/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index 96d5451e3d59..bbc6ee068d2e 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -3031,6 +3031,8 @@ describe('actions/IOU/PayMoneyRequest', () => { chatReportID: chatReport.reportID, total: -100, currency: CONST.CURRENCY.USD, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.APPROVED, nextStep: {messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_PAY, icon: CONST.NEXT_STEP.ICONS.HOURGLASS, requiresGlobalReimbursement}, }; @@ -3058,6 +3060,7 @@ describe('actions/IOU/PayMoneyRequest', () => { getCurrencyDecimals: getCurrencyDecimalsLocal, rules: undefined, }); + return expenseReport; } it('opens the onboarding instead of paying when the business bank account is not set up for global reimbursements', async () => { @@ -3106,6 +3109,58 @@ describe('actions/IOU/PayMoneyRequest', () => { expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.PAY_MONEY_REQUEST, expect.anything(), expect.anything()); expect(await getOnyxValue(ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL)).toBeUndefined(); }); + + it('keeps the report unpaid with a loading state until the backend answers a payment it may still reject', async () => { + // Given a payment the pre-check can't stop, from a USD business account that has not enabled global reimbursements, so the backend may reject it + mockFetch?.pause?.(); + + // When the admin pays the report + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false); + await waitForBatchedUpdates(); + + // Then the report isn't shown as paid yet, because rolling a rejected payment back makes it drop out of the lists and come back, and it shows a loading state instead + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`))?.statusNum).not.toBe(CONST.REPORT.STATUS_NUM.REIMBURSED); + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${expenseReport.reportID}`))?.isActionLoading).toBe(true); + + // When the backend rejects the payment + mockFetch?.fail?.(); + await mockFetch?.resume?.(); + await waitForBatchedUpdates(); + + // Then the loading state ends and the payment shows the same error it would have after an optimistic payment + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${expenseReport.reportID}`))?.isActionLoading).toBe(false); + const reportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`); + const payAction = Object.values(reportActions ?? {}).find((action) => action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU); + expect(payAction?.errors).toBeTruthy(); + }); + + it('ends the loading state when the backend accepts a held payment', async () => { + // Given a held payment from an account that has not enabled global reimbursements + mockFetch?.pause?.(); + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false); + await waitForBatchedUpdates(); + + // When the backend accepts it + await mockFetch?.resume?.(); + await waitForBatchedUpdates(); + + // Then the loading state ends, and the last used payment method is saved since the backend doesn't send it back + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${expenseReport.reportID}`))?.isActionLoading).toBe(false); + expect(await getOnyxValue(ONYXKEYS.NVP_LAST_PAYMENT_METHOD)).toBeTruthy(); + }); + + it('shows the report as paid right away when the account has global reimbursements enabled', async () => { + // Given an account the backend won't reject for global reimbursements + mockFetch?.pause?.(); + + // When the admin pays the report with it + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(true), true, false); + await waitForBatchedUpdates(); + + // Then the report is shown as paid before the backend answers, as for any other payment + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`))?.statusNum).toBe(CONST.REPORT.STATUS_NUM.REIMBURSED); + await mockFetch?.resume?.(); + }); }); describe('payViaABA', () => { From c37be90ad76b9dc457b32737f8fa985f1094768e Mon Sep 17 00:00:00 2001 From: Wojciech Boman Date: Thu, 19 Nov 2026 18:57:54 +0100 Subject: [PATCH 20/20] Show payments from the workspace account as paid right away when the backend does not flag them for global reimbursements --- src/libs/actions/IOU/PayMoneyRequest.ts | 11 +++++++-- tests/actions/IOUTest/PayMoneyRequestTest.ts | 24 ++++++++++++++++---- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/libs/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index 1a74f52d0f75..59a237ab458f 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -935,10 +935,14 @@ function getBankAccountToSetUpBeforePaying({ /** * Whether the backend may still reject this payment until the paying account is set up for global reimbursements. * The pre-check above can't catch every such payment, because only the backend knows the submitter's deposit account. + * For a payment from the workspace reimbursement account the next step flag already answers, and the pre-check stops every payment it flags. */ function canGlobalReimbursementsRejectPayment( - params: Pick, + params: Pick, ): boolean { + if (params.iouReport?.nextStep && !!params.methodID && params.methodID === params.policy?.achAccount?.bankAccountID) { + return false; + } return shouldSetUpGlobalReimbursementsBeforePaying(getBusinessBankAccountForPayment(params)); } @@ -1062,7 +1066,10 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { // Offline the payment is queued and has to show as paid right away, and a partial payment creates the report for the held expenses optimistically const shouldHoldOptimisticPayment = - full && !getIsOffline() && !!iouReport?.reportID && canGlobalReimbursementsRejectPayment({paymentType, policy, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); + full && + !getIsOffline() && + !!iouReport?.reportID && + canGlobalReimbursementsRejectPayment({paymentType, iouReport, policy, methodID, bankAccountList, isWiseReimbursementsBetaEnabled}); const requestOnyxData = shouldHoldOptimisticPayment && iouReport?.reportID ? holdOptimisticPayOnyxDataUntilResponse(onyxData, iouReport.reportID) : onyxData; // A held payment may still be rejected, so it doesn't celebrate before the backend answers diff --git a/tests/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index bbc6ee068d2e..1f61d45b8f45 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -3111,11 +3111,11 @@ describe('actions/IOU/PayMoneyRequest', () => { }); it('keeps the report unpaid with a loading state until the backend answers a payment it may still reject', async () => { - // Given a payment the pre-check can't stop, from a USD business account that has not enabled global reimbursements, so the backend may reject it + // Given a payment the pre-check can't stop, from a USD business account other than the workspace one that has not enabled global reimbursements, so the backend may reject it mockFetch?.pause?.(); // When the admin pays the report - const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false); + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false, OTHER_WORKSPACE_BANK_ACCOUNT_ID); await waitForBatchedUpdates(); // Then the report isn't shown as paid yet, because rolling a rejected payment back makes it drop out of the lists and come back, and it shows a loading state instead @@ -3135,9 +3135,9 @@ describe('actions/IOU/PayMoneyRequest', () => { }); it('ends the loading state when the backend accepts a held payment', async () => { - // Given a held payment from an account that has not enabled global reimbursements + // Given a held payment from an account other than the workspace one that has not enabled global reimbursements mockFetch?.pause?.(); - const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false); + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false, OTHER_WORKSPACE_BANK_ACCOUNT_ID); await waitForBatchedUpdates(); // When the backend accepts it @@ -3149,6 +3149,22 @@ describe('actions/IOU/PayMoneyRequest', () => { expect(await getOnyxValue(ONYXKEYS.NVP_LAST_PAYMENT_METHOD)).toBeTruthy(); }); + it('shows the report as paid right away when the backend does not flag a report paid from the workspace account', async () => { + // Given a report the backend does not flag for global reimbursements, like one for a US employee, and a workspace USD account that has not enabled them + mockFetch?.pause?.(); + const writeSpy = jest.spyOn(APIActions, 'write'); + + // When the admin pays the report from the workspace account + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false); + await waitForBatchedUpdates(); + + // Then the report is shown as paid before the backend answers, because the flag already says the backend won't reject it, and there is no loading state + expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.PAY_MONEY_REQUEST, expect.anything(), expect.anything()); + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`))?.statusNum).toBe(CONST.REPORT.STATUS_NUM.REIMBURSED); + expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${expenseReport.reportID}`))?.isActionLoading).toBeUndefined(); + await mockFetch?.resume?.(); + }); + it('shows the report as paid right away when the account has global reimbursements enabled', async () => { // Given an account the backend won't reject for global reimbursements mockFetch?.pause?.();