diff --git a/src/ROUTES.ts b/src/ROUTES.ts index bef92550a407..2cdbd88feb00 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -239,7 +239,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'], }, WISE_BUSINESS_ONBOARDING: { path: 'business-onboarding/:subPage?/:action?', diff --git a/src/components/EnableGlobalReimbursementsPayModal.tsx b/src/components/EnableGlobalReimbursementsPayModal.tsx index ca4b43a45d88..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. @@ -37,7 +63,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/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/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 1a3b394b2d75..203ea1faea85 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -13,6 +13,7 @@ import type {ASTNode, BulkPaySelectionData, PaymentData, SearchColumnType, Searc import {getAccountingIntegrationDisplayName, getExportLabelForConnection, isIntuitEnterpriseSuiteConnection} from '@libs/AccountingUtils'; 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'; @@ -51,11 +52,13 @@ import { import initSplitExpense from '@libs/actions/SplitExpenses'; import {setNameValuePair} from '@libs/actions/User'; import {getWiseQuote} from '@libs/actions/Wise'; +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 getSearchTimeGroupingDateKey from '@libs/getSearchTimeGroupingDateKey'; import getSelectedTransactionOwnerAccountID from '@libs/getSelectedTransactionOwnerAccountID'; import Log from '@libs/Log'; @@ -66,6 +69,7 @@ import Parser from '@libs/Parser'; import {getLoginByAccountID} from '@libs/PersonalDetailsUtils'; import {canAccessPolicyBankAccount} from '@libs/PolicyPaymentUtils'; import {canPayViaABA, getConnectedIntegration, isAdminOfCardEnabledPolicy, isSubmitPolicy} from '@libs/PolicyUtils'; +import {getReportName} from '@libs/ReportNameUtils'; import {getReportAccountingExportActions, isMergeActionForSelectedTransactions} from '@libs/ReportSecondaryActionUtils'; import { canEditMultipleTransactions, @@ -1905,6 +1909,10 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { let paidReportCount = 0; 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, 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'); @@ -2010,8 +2018,26 @@ 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({ + paymentType: paymentItem.paymentType, + iouReport, + policy: reportPolicy, + methodID, + bankAccountList, + isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), + }); + + if (methodID && bankAccountToSetUp) { + reportNamesNeedingGlobalReimbursements.set(item.reportID, getReportName(iouReport) || translate('common.report')); + continue; + } + const payMoneyRequestParams: PayMoneyRequestFunctionParams = { bankAccountList, isASAPSubmitBetaEnabled: isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), @@ -2046,32 +2072,45 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { expensePayments.push(payMoneyRequestParams); } + const hasPaidInvoices = paidReportCount > 0; const payExpenseReports = (wiseQuoteIDsByReportID: Record = {}) => { - let count = 0; + 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}); - - // payMoneyRequest opens the global reimbursements onboarding instead of paying, so this report stays unpaid - if ( - getBankAccountToSetUpBeforePaying({ - paymentType: params.paymentType, - methodID: params.methodID, - bankAccountList, - isWiseReimbursementsBetaEnabled: params.isWiseReimbursementsBetaEnabled, - }) - ) { - continue; - } - count += 1; } - return count; }; // One report with an expense in another currency than the bank account is enough to show every report with its quote before paying const shouldConfirmWiseQuotes = expensePayments.some((params) => shouldConfirmWiseQuoteBeforePaying(params)); if (!shouldConfirmWiseQuotes) { - paidReportCount += payExpenseReports(); + payExpenseReports(); + paidReportCount += expensePayments.length; } if (paidReportCount + (shouldConfirmWiseQuotes ? expensePayments.length : 0) < itemsToPay.length) { @@ -2083,29 +2122,29 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { clearSelectedTransactions(); } - if (shouldConfirmWiseQuotes) { - const reports = expensePayments.flatMap((params) => (params.iouReport?.reportID ? [params.iouReport] : [])); - const quotedReports = expensePayments.flatMap((params) => (params.iouReport?.reportID && shouldGetWiseQuote(params) ? [params.iouReport] : [])); - for (const report of quotedReports) { - // Search results don't hold the quote, which the server merges into the report in Onyx - getWiseQuote({...report, ...allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`]}, true); - } - const quotedReportIDs = quotedReports.map((report) => report.reportID); - // 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) => { - if (payExpenseReports(wiseQuoteIDsByReportID) === 0) { - return; - } - playSound(SOUNDS.SUCCESS); - clearSelectedTransactions(); - }, - }); - }); + if (!shouldConfirmWiseQuotes) { + return; + } + + const reports = expensePayments.flatMap((params) => (params.iouReport?.reportID ? [params.iouReport] : [])); + const quotedReports = expensePayments.flatMap((params) => (params.iouReport?.reportID && shouldGetWiseQuote(params) ? [params.iouReport] : [])); + for (const report of quotedReports) { + // Search results don't hold the quote, which the server merges into the report in Onyx + getWiseQuote({...report, ...allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`]}, true); } + const quotedReportIDs = quotedReports.map((report) => report.reportID); + // 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) => { + payExpenseReports(wiseQuoteIDsByReportID); + playSound(SOUNDS.SUCCESS); + clearSelectedTransactions(); + }, + }); + }); }, [ hash, @@ -2151,6 +2190,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { isTrackIntentUser, getCurrencyDecimals, rules, + translate, payReportsViaABA, ], ); @@ -2534,7 +2574,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, @@ -2567,7 +2607,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, @@ -3030,7 +3070,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, diff --git a/src/languages/de.ts b/src/languages/de.ts index 691da6428fe7..176d3057aceb 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -3317,6 +3317,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 cbda1a1ac53e..54cfbae8096c 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -3378,6 +3378,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/en.ts b/src/languages/en.ts index bb298e4a44e8..12143b6c9d64 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -3385,8 +3385,13 @@ 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: { + 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/languages/es.ts b/src/languages/es.ts index 99b46cc549ec..c5bd43c85f5d 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -3295,6 +3295,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.'}, wiseMoreInfoNeeded: 'Se necesita más información para habilitar los reembolsos globales', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index dea4fe39d6c0..ef76c8c9780e 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -3323,6 +3323,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 7dce95424399..d3041339ee67 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -3305,6 +3305,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 b4a6e3e2fc79..9cbfd064a956 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -3278,6 +3278,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 884d6c15d07a..f4fde758929b 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -3305,6 +3305,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 b7fa5d55ee95..74e30a14639f 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -3347,6 +3347,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 f900d3271e44..131e0022e6a2 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -3309,6 +3309,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 d9ace769ee40..0e691ee57b3c 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -3191,6 +3191,11 @@ const translations: TranslationDeepObject = { getStarted: '开始使用', headerTitle: '全球报销', payingReportSubtitle: '公司账户和员工账户使用的货币不同。', + payingMultipleReportsSubtitle: '由于公司账户和员工账户使用的货币不同,这些报告均无法支付。', + }, + wiseGlobalReimbursementsBulkPayModal: { + title: (lastFour: string) => (lastFour ? `使用 x${lastFour} 支付` : '使用银行账户支付'), + description: '这些报告需要全球报销,因此未使用该银行账户支付。请在下方开始设置流程。', }, wiseGlobalReimbursementsBanner: {title: '向全球付款', subtitle: '在您的美元账户中启用全球报销。'}, wiseMoreInfoNeeded: '启用全球报销所需的更多信息', diff --git a/src/libs/BankAccountUtils.ts b/src/libs/BankAccountUtils.ts index 1e28eb5993ec..65d2e8594ebe 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); } /** @@ -256,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; } @@ -564,6 +573,7 @@ function showUnlockAlreadyRequestedModal(showConfirmModal: ReturnType([ 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_HAS_RULES_FETCH_FAILED, @@ -560,6 +559,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 c8f0108b6e87..0b0852e90668 100644 --- a/src/libs/Middleware/register.ts +++ b/src/libs/Middleware/register.ts @@ -56,7 +56,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/Navigation/helpers/enableGlobalReimbursementsNavigationUtils.ts b/src/libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils.ts index a3d20d645052..c3e794c23835 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 d1f9e5b7ff09..717fc8c50c07 100644 --- a/src/libs/Navigation/paramLists/AccountSettingsParamList.ts +++ b/src/libs/Navigation/paramLists/AccountSettingsParamList.ts @@ -182,6 +182,7 @@ type AccountSettingsParamList = { }; [SCREENS.SETTINGS.WALLET.DYNAMIC_WISE_GLOBAL_REIMBURSEMENTS_INTRO]: { bankAccountID: string; + isPayingMultipleReports?: string; }; [SCREENS.SETTINGS.WALLET.DYNAMIC_WISE_BUSINESS_ONBOARDING]: { bankAccountID: string; 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/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/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index 69fa9700a1f8..59a237ab458f 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -7,13 +7,14 @@ import * as API from '@libs/API'; import type {MarkReportPaymentReceivedParams, PayInvoiceParams, PayMoneyRequestParams} from '@libs/API/parameters'; import {WRITE_COMMANDS} from '@libs/API/types'; import {getCommandURL} from '@libs/ApiUtils'; -import {shouldSetUpGlobalReimbursementsBeforePaying} from '@libs/BankAccountUtils'; +import {getBusinessBankAccountForPayment, shouldSetUpGlobalReimbursementsBeforePaying} from '@libs/BankAccountUtils'; import DateUtils from '@libs/DateUtils'; import type HttpsError from '@libs/Errors/HttpsError'; import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import fileDownload from '@libs/fileDownload'; import Navigation from '@libs/Navigation/Navigation'; import enhanceParameters from '@libs/Network/enhanceParameters'; +import {getIsOffline} from '@libs/NetworkState'; import {buildOptimisticNextStep} from '@libs/NextStepUtils'; import {getPersonalDetailsForAccountIDs} from '@libs/PersonalDetailsUtils'; import {isPaidGroupPolicy, isPolicyAdmin} from '@libs/PolicyUtils'; @@ -35,6 +36,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'; @@ -50,7 +52,7 @@ import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; import type {OnyxData} from '@src/types/onyx/Request'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; -import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry, OnyxKey, OnyxUpdate} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import {format} from 'date-fns'; @@ -909,20 +911,64 @@ 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 { - 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; + } + if (methodID !== policy?.achAccount?.bankAccountID) { return undefined; } const bankAccount = bankAccountList?.[methodID]; return shouldSetUpGlobalReimbursementsBeforePaying(bankAccount) ? bankAccount : undefined; } +/** + * 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, +): boolean { + if (params.iouReport?.nextStep && !!params.methodID && params.methodID === params.policy?.achAccount?.bankAccountID) { + return false; + } + 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, @@ -968,13 +1014,9 @@ 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, policy, 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; } @@ -1022,11 +1064,22 @@ 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, 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 + 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/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/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx b/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx index 1f5a88acbf86..9016abaa9563 100644 --- a/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx +++ b/src/pages/settings/Wallet/WiseGlobalReimbursementsIntroPage.tsx @@ -40,6 +40,7 @@ function WiseGlobalReimbursementsIntroPage({route}: WiseGlobalReimbursementsIntr 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]; @@ -93,7 +94,9 @@ function WiseGlobalReimbursementsIntroPage({route}: WiseGlobalReimbursementsIntr /> {translate('walletPage.wiseGlobalReimbursementsIntro.title')} - {translate(isPayingReport ? 'walletPage.wiseGlobalReimbursementsIntro.payingReportSubtitle' : 'walletPage.wiseGlobalReimbursementsIntro.subtitle')} + {isPayingMultipleReports + ? translate('walletPage.wiseGlobalReimbursementsIntro.payingMultipleReportsSubtitle') + : translate(isPayingReport ? 'walletPage.wiseGlobalReimbursementsIntro.payingReportSubtitle' : 'walletPage.wiseGlobalReimbursementsIntro.subtitle')} diff --git a/src/types/onyx/EnableGlobalReimbursementsModal.ts b/src/types/onyx/EnableGlobalReimbursementsModal.ts index c83cea15904b..0fb0f7eae3dd 100644 --- a/src/types/onyx/EnableGlobalReimbursementsModal.ts +++ b/src/types/onyx/EnableGlobalReimbursementsModal.ts @@ -6,6 +6,12 @@ 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; + /** 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/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index 3d671e36f766..1f61d45b8f45 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -2997,6 +2997,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 { @@ -3013,7 +3014,12 @@ describe('actions/IOU/PayMoneyRequest', () => { }; } - function payWithBusinessBankAccount(bankAccountList: BankAccountList, isWiseReimbursementsBetaEnabled: boolean) { + function payWithBusinessBankAccount( + bankAccountList: BankAccountList, + isWiseReimbursementsBetaEnabled: boolean, + requiresGlobalReimbursement = true, + workspaceBankAccountID = BANK_ACCOUNT_ID, + ) { const chatReport = { ...createRandomReport(0, undefined), type: CONST.REPORT.TYPE.CHAT, @@ -3025,6 +3031,9 @@ 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}, }; payMoneyRequest({ @@ -3042,6 +3051,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, @@ -3050,10 +3060,11 @@ 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 () => { - // 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 @@ -3070,20 +3081,102 @@ 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 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(); + }); + + 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 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, 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 + 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 other than the workspace one that has not enabled global reimbursements + mockFetch?.pause?.(); + const expenseReport = payWithBusinessBankAccount(buildBankAccountList(false), true, false, OTHER_WORKSPACE_BANK_ACCOUNT_ID); + 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 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?.(); + + // 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', () => { diff --git a/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts b/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts index 3d7cde17eca8..37b249ff3b8b 100644 --- a/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts +++ b/tests/navigation/enableGlobalReimbursementsDynamicRouteTest.ts @@ -115,6 +115,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/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/BankAccountUtilsTest.ts b/tests/unit/BankAccountUtilsTest.ts index b78ad531d0a7..f32cd6e358d2 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/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 ef6f73c27693..a2bbdb0b1159 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -1,6 +1,7 @@ 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'; @@ -8,26 +9,33 @@ import useBulkPayOptions from '@hooks/useBulkPayOptions'; 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 {openPaymentMethods} from '@libs/actions/PaymentMethods'; 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'; +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}]; -let mockEnabledBetas: string[] = []; +// 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), @@ -38,7 +46,8 @@ jest.mock('@libs/deferModalPresentationAfterPopoverDismiss', () => ({ default: (presentModal: () => void) => mockDeferModalPresentation(presentModal), })); -const mockShowWiseQuoteCarouselModal = jest.fn(); +type WiseQuoteCarouselModalOptions = {onConfirm: (wiseQuoteIDsByReportID: Record) => void}; +const mockShowWiseQuoteCarouselModal = jest.fn}>, [WiseQuoteCarouselModalOptions]>(() => Promise.resolve({action: ModalActions.CLOSE})); jest.mock('@hooks/useWiseQuoteConfirmModal', () => ({ __esModule: true, default: () => ({showWiseQuoteConfirmModal: jest.fn(), showWiseQuoteCarouselModal: mockShowWiseQuoteCarouselModal}), @@ -49,6 +58,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'), @@ -164,14 +185,16 @@ 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}), })); +let mockEnabledBetas = new Set(); jest.mock('@hooks/usePermissions', () => ({ __esModule: true, - default: () => ({isBetaEnabled: (beta: string) => mockEnabledBetas.includes(beta), isBetaEnabledOrUnknown: () => false}), + default: () => ({isBetaEnabled: (beta: string) => mockEnabledBetas.has(beta), isBetaEnabledOrUnknown: (beta: string) => mockEnabledBetas.has(beta)}), })); jest.mock('@hooks/useSelfDMReport', () => ({ @@ -729,6 +752,339 @@ describe('useSearchBulkActions - bulk pay chat report fallback', () => { }); }); +describe('useSearchBulkActions - bulk pay with reports that need global reimbursements', () => { + const BANK_ACCOUNT_ID = 99; + const ENABLED_BANK_ACCOUNT_ID = 88; + const OTHER_BANK_ACCOUNT_ID = 77; + + 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, 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(() => { + 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; + mockEnabledBetas = new Set([CONST.BETAS.WISE_REIMBURSEMENTS]); + mockSelectedTransactions = {tx1: makeSelectedTransaction()}; + 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]: 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); + // 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 () => { + mockEnabledBetas = new Set(); + mockShouldConfirmWiseQuote = false; + mockIsClientTheLeader = true; + 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?.(); + }); + } + + 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 + await selectBulkPay(); + + // 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'}), 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); + + // 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 () => { + // 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 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 () => { + // 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(); + + // 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 () => { + // 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 only the flagged report is handed over as skipped + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['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 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(getFollowedBulkPay()?.skippedReportNames).toEqual([]); + 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(getFollowedBulkPay()?.skippedReportNames).toEqual(['Report needing GR']); + }); + + 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 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 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 () => { + // 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', policyID: 'policy2'}), + }; + + // When the user selects bulk Pay + await selectBulkPay(); + + // 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 () => { + // Given a skipped report without a name, next to a payable one + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {reportName: ''}); + + // When the user selects bulk Pay + await selectBulkPay(); + + // Then the report is still handed over, so the modal list is never empty + expect(getFollowedBulkPay()?.skippedReportNames).toEqual(['common.report']); + }); + + 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'})]; + + // 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 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('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 both reports are handed over, so the onboarding explains that all the selected reports need it + expect(payMoneyRequest).not.toHaveBeenCalled(); + expect(getFollowedBulkPay()).toEqual(expect.objectContaining({skippedReportNames: ['Report needing GR', 'Second report needing GR'], hasPaidReports: false})); + }); + + 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'; + let resolveCarouselClose: ((payload: {action: ValueOf}) => void) | undefined; + mockShowWiseQuoteCarouselModal.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveCarouselClose = resolve; + }), + ); + + // When the user selects bulk Pay + await selectBulkPay(); + + // 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(followGlobalReimbursementsBulkPay).not.toHaveBeenCalled(); + + // When the user confirms the quotes and the carousel closes + await act(async () => { + mockShowWiseQuoteCarouselModal.mock.calls + .at(0) + ?.at(0) + ?.onConfirm({[PAYABLE_REPORT_ID]: 'quote3'}); + resolveCarouselClose?.({action: ModalActions.CONFIRM}); + }); + + // 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(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 () => { + // 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 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([]); + }); +}); + describe('useSearchBulkActions - bulk pay Wise quote', () => { beforeAll(() => { Onyx.init({keys: ONYXKEYS}); @@ -800,7 +1156,7 @@ describe('useSearchBulkActions - pay via ABA', () => { mockShouldEnableBulkPayOption = true; mockBulkPayButtonOptions = [{text: 'Mark as paid', key: CONST.IOU.PAYMENT_TYPE.ELSEWHERE}]; mockAreAllMatchingItemsSelected = false; - mockEnabledBetas = [CONST.BETAS.PAY_VIA_ABA]; + mockEnabledBetas = new Set([CONST.BETAS.PAY_VIA_ABA]); mockSelectedTransactions = {tx1: makeSelectedTransaction()}; mockSelectedReports = [makeSelectedReport({reportID: '1', chatReportID: 'chat1'}), makeSelectedReport({reportID: '3', chatReportID: 'chat3'})]; jest.mocked(getLastPolicyPaymentMethod).mockReturnValue(CONST.IOU.PAYMENT_TYPE.ELSEWHERE); @@ -812,7 +1168,7 @@ describe('useSearchBulkActions - pay via ABA', () => { }); afterEach(async () => { - mockEnabledBetas = []; + mockEnabledBetas = new Set(); await Onyx.clear(); });