From a63bbdfd0b045356966e0d4fd4be7bc4bdec4080 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Fri, 27 Nov 2026 17:56:02 +0100 Subject: [PATCH 1/3] Read Pay button reports and actions at press time --- src/components/KYCWall/BaseKYCWall.tsx | 11 +- .../ListItem/ActionCell/PayActionCell.tsx | 19 +-- tests/ui/components/KYCWallTest.tsx | 122 ++++++++++++++++++ tests/ui/components/PayActionCellTest.tsx | 74 ++++++++++- 4 files changed, 210 insertions(+), 16 deletions(-) create mode 100644 tests/ui/components/KYCWallTest.tsx diff --git a/src/components/KYCWall/BaseKYCWall.tsx b/src/components/KYCWall/BaseKYCWall.tsx index 3254a29effac..bb6e02e1866b 100644 --- a/src/components/KYCWall/BaseKYCWall.tsx +++ b/src/components/KYCWall/BaseKYCWall.tsx @@ -42,6 +42,7 @@ import type {EmitterSubscription, View} from 'react-native'; import {hasSeenTourSelector} from '@selectors/Onboarding'; import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react'; import {Dimensions} from 'react-native'; +import Onyx from 'react-native-onyx'; import type {AnchorPosition, ContinueActionParams, DomRect, KYCWallProps, PaymentMethod} from './types'; @@ -95,8 +96,6 @@ function KYCWall({ const localCurrency = currentUserDetails.localCurrencyCode ?? CONST.CURRENCY.USD; const reportPreviewAction = useParentReportAction(iouReport); const reportTransactions = useReportTransactions(iouReport?.reportID); - const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS); const anchorRef = useRef>(null); const transferBalanceButtonRef = useRef(null); @@ -150,7 +149,7 @@ function KYCWall({ }, [getAnchorPosition]); const selectPaymentMethod = useCallback( - (paymentMethod?: PaymentMethod, policy?: Policy, personalBankAccountOnSuccessFallbackRoute?: Route) => { + async (paymentMethod?: PaymentMethod, policy?: Policy, personalBankAccountOnSuccessFallbackRoute?: Route) => { const canLinkExistingBusinessBankAccount = getEligibleExistingBusinessBankAccounts(bankAccountList, policy?.outputCurrency, true).length > 0; if (paymentMethod) { @@ -167,8 +166,10 @@ function KYCWall({ } else if (paymentMethod === CONST.PAYMENT_METHODS.DEBIT_CARD) { Navigation.navigate(addDebitCardRoute ?? ROUTES.INBOX); } else if (paymentMethod === CONST.PAYMENT_METHODS.BUSINESS_BANK_ACCOUNT || policy) { - const filteredReportActions = getAllPolicyExpenseChatReportActions(allReports, allReportActions); if (iouReport && isIOUReport(iouReport)) { + // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read on Search chat previews: moving the IOU report writes optimistic data to live keys, so reports and report actions must be live to find the workspace chat + const [allReports, allReportActions] = await Onyx.multiGet([ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_ACTIONS]); + const filteredReportActions = getAllPolicyExpenseChatReportActions(allReports, allReportActions); const adminPolicy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policy?.id}`]; if (adminPolicy) { const inviteResult = moveIOUReportToPolicyAndInviteSubmitter( @@ -323,8 +324,6 @@ function KYCWall({ introSelected, translate, reportTransactions, - allReports, - allReportActions, lastPaymentMethod, isSelfTourViewed, conciergeChat, diff --git a/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx b/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx index 15ce1ccd1e14..250e8a27e610 100644 --- a/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx +++ b/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx @@ -11,6 +11,7 @@ import {useReportPaymentContext} from '@hooks/usePaymentContext'; import usePayViaABA from '@hooks/usePayViaABA'; import usePayWithWiseQuote from '@hooks/usePayWithWiseQuote'; import usePolicy from '@hooks/usePolicy'; +import useReportIsArchived from '@hooks/useReportIsArchived'; import useReportWithTransactionsAndViolations from '@hooks/useReportWithTransactionsAndViolations'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -18,7 +19,7 @@ import {payInvoice} from '@libs/actions/IOU/PayMoneyRequest'; import {getChatReportWithFallback, getSearchPayOnyxData} from '@libs/actions/Search'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import Log from '@libs/Log'; -import {canIOUBePaid, getReimbursableTotal, isArchivedReport, isIndividualInvoiceRoom, isInvoiceReport} from '@libs/ReportUtils'; +import {canIOUBePaid, getReimbursableTotal, isIndividualInvoiceRoom, isInvoiceReport} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -52,9 +53,6 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab const policy = usePolicy(policyID); const {payReportsViaABA, isDownloadingABAFile} = usePayViaABA(); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); - const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS); - const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const invoiceReceiverPolicyID = chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : undefined; const invoiceReceiverPolicy = usePolicy(invoiceReceiverPolicyID); @@ -74,7 +72,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab chatReportPolicyID: chatReport?.policyID, }); - const isChatReportArchived = isArchivedReport(reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${chatReport?.reportID}`]); + const isChatReportArchived = useReportIsArchived(chatReport?.reportID); const canBePaid = canIOUBePaid( iouReport, chatReport, @@ -140,6 +138,8 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab Log.info('[SearchPay] Dropping invoice row pay: chat report is not loaded', false, {reportID}); return; } + // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: payInvoice builds optimistic data against live keys, so reports and name-value pairs must be live to find the existing invoice room + const [allReports, reportNameValuePairs] = await Onyx.multiGet([ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS]); const existingB2BInvoiceReport = getParticipantsInvoiceReport( allReports, reportNameValuePairs, @@ -152,8 +152,9 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab // when paying an individual invoice room as a business. `payAsBusiness` is only known at click time, so pick // the right report's actions here in the function scope. const shouldUseB2BInvoiceReport = !!payAsBusiness && !!existingB2BInvoiceReport && isIndividualInvoiceRoom(chatReport); - const chatReportActions = - allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(shouldUseB2BInvoiceReport ? existingB2BInvoiceReport?.reportID : chatReport?.reportID)}`]; + const chatReportActionsID = getNonEmptyStringOnyxID(shouldUseB2BInvoiceReport ? existingB2BInvoiceReport?.reportID : chatReport?.reportID); + // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: the payment updates the report preview in live report actions, so it must find it there + const chatReportActions = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportActionsID}`); const {conciergeChat, rules, introSelected, isTrackIntentUser, isSelfTourViewed} = await readPaymentInputs(); payInvoice({ @@ -201,6 +202,8 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab } const {conciergeChat, rules, introSelected, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd, isTrackIntentUser, isSelfTourViewed} = await readPaymentInputs(); + // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: the payment updates the report preview in live report actions, so it must find it there + const chatReportActions = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(chatReport?.reportID)}`); payWithWiseQuote({ bankAccountList, isASAPSubmitBetaEnabled, @@ -223,7 +226,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab methodID: type === CONST.IOU.PAYMENT_TYPE.VBBA ? methodID : undefined, isWiseReimbursementsBetaEnabled, additionalOnyxData, - chatReportActions: allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(chatReport?.reportID)}`], + chatReportActions, delegateAccountID, isTrackIntentUser, conciergeChat, diff --git a/tests/ui/components/KYCWallTest.tsx b/tests/ui/components/KYCWallTest.tsx new file mode 100644 index 000000000000..a3e6a9e28cd7 --- /dev/null +++ b/tests/ui/components/KYCWallTest.tsx @@ -0,0 +1,122 @@ +import {act, render} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; +import KYCWall from '@components/KYCWall'; +import type {ContinueActionParams, KYCWallRef} from '@components/KYCWall/types'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; + +import {moveIOUReportToPolicyAndInviteSubmitter} from '@libs/actions/Report'; + +import CONST from '@src/CONST'; +import IntlStore from '@src/languages/IntlStore'; +import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; +import type {Policy, Report, ReportActions} from '@src/types/onyx'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import createRandomPolicy from '../../utils/collections/policies'; +import createRandomReportAction from '../../utils/collections/reportActions'; +import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; + +jest.mock('@libs/Navigation/Navigation', () => ({ + __esModule: true, + default: { + navigate: jest.fn(), + goBack: jest.fn(), + getActiveRoute: jest.fn(() => ''), + }, +})); + +jest.mock('@libs/actions/Report', () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const actual = jest.requireActual('@libs/actions/Report'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return { + ...actual, + __esModule: true, + moveIOUReportToPolicy: jest.fn(() => undefined), + moveIOUReportToPolicyAndInviteSubmitter: jest.fn(() => undefined), + }; +}); + +const mockedMoveIOUReportToPolicyAndInviteSubmitter = jest.mocked(moveIOUReportToPolicyAndInviteSubmitter); + +const POLICY_ID = 'kyc-wall-policy'; +const WORKSPACE_CHAT_ID = '300'; + +const iouReport = { + reportID: '100', + chatReportID: '200', + type: CONST.REPORT.TYPE.IOU, + ownerAccountID: 2, + managerID: 1, + currency: CONST.CURRENCY.USD, +} as Report; + +const adminPolicy: Policy = { + ...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM, 'Admin workspace'), + id: POLICY_ID, + role: CONST.POLICY.ROLE.ADMIN, + outputCurrency: CONST.CURRENCY.USD, +}; + +const workspaceChat = { + reportID: WORKSPACE_CHAT_ID, + type: CONST.REPORT.TYPE.CHAT, + chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, + policyID: POLICY_ID, +} as Report; + +const workspaceChatAction = createRandomReportAction(1); +const workspaceChatActions: ReportActions = {[workspaceChatAction.reportActionID]: workspaceChatAction}; + +describe('KYCWall', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + IntlStore.load(CONST.LOCALES.EN); + }); + + afterEach(async () => { + jest.clearAllMocks(); + await Onyx.clear(); + }); + + it('should pass the workspace chat actions stored at press time when moving an IOU report to a workspace', async () => { + // Given an IOU report payer without a payment method who administers a workspace + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, adminPolicy); + let continueAction: ((params?: ContinueActionParams) => void) | undefined; + render( + + ()} + iouReport={iouReport} + chatReportID={iouReport.chatReportID} + enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS} + onSuccessfulKYC={jest.fn()} + > + {(triggerKYCFlow) => { + continueAction = triggerKYCFlow; + }} + + , + ); + await waitForBatchedUpdatesWithAct(); + + // And the workspace chat and its actions land in Onyx after the wall rendered + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, workspaceChat); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`, workspaceChatActions); + + // When the payer picks the workspace to pay through + act(() => { + continueAction?.({policy: adminPolicy}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the move should get those actions, because the wall reads workspace chats only when paying, so the report joins the live workspace chat + expect(mockedMoveIOUReportToPolicyAndInviteSubmitter.mock.calls.at(0)?.at(2)).toEqual({[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`]: workspaceChatActions}); + }); +}); diff --git a/tests/ui/components/PayActionCellTest.tsx b/tests/ui/components/PayActionCellTest.tsx index 2fe43a9265ce..932e0ca8c336 100644 --- a/tests/ui/components/PayActionCellTest.tsx +++ b/tests/ui/components/PayActionCellTest.tsx @@ -1,4 +1,4 @@ -import {act, render} from '@testing-library/react-native'; +import {act, render, waitFor} from '@testing-library/react-native'; import PayActionCell from '@components/Search/SearchList/ListItem/ActionCell/PayActionCell'; import type {PaymentActionParams} from '@components/SettlementButton/types'; @@ -12,12 +12,15 @@ import {isInvoiceReport} from '@libs/ReportUtils'; import {payInvoice, payMoneyRequest} from '@userActions/IOU/PayMoneyRequest'; import CONST from '@src/CONST'; -import type {Report} from '@src/types/onyx'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report, ReportActions} from '@src/types/onyx'; import type {UseOnyxResult} from 'react-native-onyx'; import React from 'react'; +import Onyx from 'react-native-onyx'; +import createRandomReportAction from '../../utils/collections/reportActions'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; const TEST_INVOICE_REPORT_ID = '1001'; @@ -137,10 +140,22 @@ const expenseReport = { total: -5000, } as Report; +const reportPreviewAction = {...createRandomReportAction(1), actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW}; +const chatReportActions: ReportActions = {[reportPreviewAction.reportActionID]: reportPreviewAction}; + describe('PayActionCell', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + await Onyx.clear(); + }); + beforeEach(() => { jest.clearAllMocks(); mockOnPressHolder.current = undefined; + mockedIsInvoiceReport.mockReturnValue(true); mockedUseReportWithTransactionsAndViolations.mockReturnValue([invoiceReport, [], undefined]); mockedUseOnyx.mockImplementation(() => createOnyxResult(undefined)); }); @@ -329,4 +344,59 @@ describe('PayActionCell', () => { expect(mockedPayMoneyRequest).not.toHaveBeenCalled(); expect(mockLogInfo).toHaveBeenCalledWith('[SearchPay] Dropping row pay: chat report is not loaded and no chatReportID is available', false, {reportID: TEST_EXPENSE_REPORT_ID}); }); + + it('should pass the chat report actions stored at press time to payInvoice', async () => { + // Given an invoice report row whose chat report actions land in Onyx after the row rendered + render( + , + ); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${TEST_CHAT_REPORT_ID}`, chatReportActions); + + // When the user confirms the payment from the cell's settlement button + act(() => { + mockOnPressHolder.current?.({ + paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE, + payAsBusiness: false, + }); + }); + + // Then the payment should get those actions, because the row reads them only when paying so it can update the live report preview + await waitFor(() => expect(mockedPayInvoice).toHaveBeenCalledWith(expect.objectContaining({chatReportActions}))); + }); + + it('should pass the chat report actions stored at press time to a money request payment', async () => { + // Given an expense report row whose chat report actions land in Onyx after the row rendered + mockedIsInvoiceReport.mockReturnValue(false); + mockedUseReportWithTransactionsAndViolations.mockReturnValue([expenseReport, [], undefined]); + + render( + , + ); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${TEST_CHAT_REPORT_ID}`, chatReportActions); + + // When the user confirms the payment from the cell's settlement button + act(() => { + mockOnPressHolder.current?.({ + paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE, + payAsBusiness: false, + }); + }); + + // Then the payment should get those actions, because the row reads them only when paying so it can update the live report preview + await waitFor(() => expect(mockedPayMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({chatReportActions}))); + }); }); From f4b4281b8ac08d614147a3e60aad0e5600f6be45 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Tue, 1 Dec 2026 18:38:46 +0100 Subject: [PATCH 2/3] Type requireActual in KYCWall test mock --- tests/ui/components/KYCWallTest.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/ui/components/KYCWallTest.tsx b/tests/ui/components/KYCWallTest.tsx index a3e6a9e28cd7..df29b6c82739 100644 --- a/tests/ui/components/KYCWallTest.tsx +++ b/tests/ui/components/KYCWallTest.tsx @@ -7,6 +7,7 @@ import type {ContinueActionParams, KYCWallRef} from '@components/KYCWall/types'; import {LocaleContextProvider} from '@components/LocaleContextProvider'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import type * as ReportActionsModule from '@libs/actions/Report'; import {moveIOUReportToPolicyAndInviteSubmitter} from '@libs/actions/Report'; import CONST from '@src/CONST'; @@ -32,9 +33,7 @@ jest.mock('@libs/Navigation/Navigation', () => ({ })); jest.mock('@libs/actions/Report', () => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const actual = jest.requireActual('@libs/actions/Report'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const actual = jest.requireActual('@libs/actions/Report'); return { ...actual, __esModule: true, From 65ea87b173cf40ac1b703651d69d0c3e1b456e3e Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Tue, 1 Dec 2026 19:57:24 +0100 Subject: [PATCH 3/3] Keep snapshot invoice room lookup and scope KYCWall chat subscriptions --- src/components/KYCWall/BaseKYCWall.tsx | 15 +++---- .../ListItem/ActionCell/PayActionCell.tsx | 27 +++++++----- src/hooks/useOnyx.ts | 1 + src/hooks/useSubmitterWorkspaceChatActions.ts | 43 +++++++++++++++++++ tests/ui/components/KYCWallTest.tsx | 39 ++++++++++++++++- tests/ui/components/PayActionCellTest.tsx | 40 ++++++++++++++++- 6 files changed, 143 insertions(+), 22 deletions(-) create mode 100644 src/hooks/useSubmitterWorkspaceChatActions.ts diff --git a/src/components/KYCWall/BaseKYCWall.tsx b/src/components/KYCWall/BaseKYCWall.tsx index bb6e02e1866b..2d42e653cab8 100644 --- a/src/components/KYCWall/BaseKYCWall.tsx +++ b/src/components/KYCWall/BaseKYCWall.tsx @@ -8,6 +8,7 @@ import useOnyx from '@hooks/useOnyx'; import useParentReportAction from '@hooks/useParentReportAction'; import {usePersonalDetail} from '@hooks/usePersonalDetails'; import useReportTransactions from '@hooks/useReportTransactions'; +import useSubmitterWorkspaceChatActions from '@hooks/useSubmitterWorkspaceChatActions'; import {openPersonalBankAccountSetupView, setPersonalBankAccountContinueKYCOnSuccess} from '@libs/actions/BankAccounts'; import {completePaymentOnboarding, savePreferredPaymentMethod} from '@libs/actions/IOU/PayMoneyRequest'; @@ -20,7 +21,7 @@ import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNav import Navigation from '@libs/Navigation/Navigation'; import {hasExpensifyPaymentMethod} from '@libs/PaymentUtils'; import {getAccessiblePolicyBankAccount} from '@libs/PolicyPaymentUtils'; -import {getAllPolicyExpenseChatReportActions, getBankAccountRoute, getInvoiceReceiverPolicyID, isExpenseReport as isExpenseReportReportUtils, isIOUReport} from '@libs/ReportUtils'; +import {getBankAccountRoute, getInvoiceReceiverPolicyID, isExpenseReport as isExpenseReportReportUtils, isIOUReport} from '@libs/ReportUtils'; import {getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts} from '@libs/WorkflowUtils'; import {createWorkspaceFromIOUPayment} from '@userActions/Policy/Policy'; @@ -42,7 +43,6 @@ import type {EmitterSubscription, View} from 'react-native'; import {hasSeenTourSelector} from '@selectors/Onboarding'; import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react'; import {Dimensions} from 'react-native'; -import Onyx from 'react-native-onyx'; import type {AnchorPosition, ContinueActionParams, DomRect, KYCWallProps, PaymentMethod} from './types'; @@ -96,6 +96,7 @@ function KYCWall({ const localCurrency = currentUserDetails.localCurrencyCode ?? CONST.CURRENCY.USD; const reportPreviewAction = useParentReportAction(iouReport); const reportTransactions = useReportTransactions(iouReport?.reportID); + const submitterWorkspaceChatActions = useSubmitterWorkspaceChatActions(isIOUReport(iouReport) ? ownerAccountID : undefined); const anchorRef = useRef>(null); const transferBalanceButtonRef = useRef(null); @@ -149,7 +150,7 @@ function KYCWall({ }, [getAnchorPosition]); const selectPaymentMethod = useCallback( - async (paymentMethod?: PaymentMethod, policy?: Policy, personalBankAccountOnSuccessFallbackRoute?: Route) => { + (paymentMethod?: PaymentMethod, policy?: Policy, personalBankAccountOnSuccessFallbackRoute?: Route) => { const canLinkExistingBusinessBankAccount = getEligibleExistingBusinessBankAccounts(bankAccountList, policy?.outputCurrency, true).length > 0; if (paymentMethod) { @@ -167,15 +168,12 @@ function KYCWall({ Navigation.navigate(addDebitCardRoute ?? ROUTES.INBOX); } else if (paymentMethod === CONST.PAYMENT_METHODS.BUSINESS_BANK_ACCOUNT || policy) { if (iouReport && isIOUReport(iouReport)) { - // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read on Search chat previews: moving the IOU report writes optimistic data to live keys, so reports and report actions must be live to find the workspace chat - const [allReports, allReportActions] = await Onyx.multiGet([ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_ACTIONS]); - const filteredReportActions = getAllPolicyExpenseChatReportActions(allReports, allReportActions); const adminPolicy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policy?.id}`]; if (adminPolicy) { const inviteResult = moveIOUReportToPolicyAndInviteSubmitter( iouReport, adminPolicy, - filteredReportActions, + submitterWorkspaceChatActions, reportPreviewAction, currentUserAccountID, employeeLogin, @@ -221,7 +219,7 @@ function KYCWall({ currentUserLocalCurrency: localCurrency, lastWorkspaceNumber, localeTranslate: translate, - reportActionsList: filteredReportActions, + reportActionsList: submitterWorkspaceChatActions, doesEmployeePersonalDetailExist: doesSubmitterPersonalDetailExist ?? false, getCurrencyDecimals, reportTransactions, @@ -324,6 +322,7 @@ function KYCWall({ introSelected, translate, reportTransactions, + submitterWorkspaceChatActions, lastPaymentMethod, isSelfTourViewed, conciergeChat, diff --git a/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx b/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx index 250e8a27e610..f4142db10333 100644 --- a/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx +++ b/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx @@ -5,7 +5,7 @@ import type {PaymentActionParams} from '@components/SettlementButton/types'; import {useCurrencyListActions} from '@hooks/useCurrencyList'; import useNetwork from '@hooks/useNetwork'; -import useOnyx from '@hooks/useOnyx'; +import useOnyx, {getSnapshotKeyData} from '@hooks/useOnyx'; import {getParticipantsInvoiceReport} from '@hooks/useParticipantsInvoiceReport'; import {useReportPaymentContext} from '@hooks/usePaymentContext'; import usePayViaABA from '@hooks/usePayViaABA'; @@ -24,9 +24,9 @@ import {canIOUBePaid, getReimbursableTotal, isIndividualInvoiceRoom, isInvoiceRe import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type {Report} from '@src/types/onyx'; +import type {Report, ReportNameValuePairs} from '@src/types/onyx'; -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import {hasSeenTourSelector, isTrackIntentUserSelector} from '@selectors/Onboarding'; import React from 'react'; @@ -138,15 +138,20 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab Log.info('[SearchPay] Dropping invoice row pay: chat report is not loaded', false, {reportID}); return; } - // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: payInvoice builds optimistic data against live keys, so reports and name-value pairs must be live to find the existing invoice room + // eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: payInvoice builds optimistic data against live keys, so the invoice room lookup tries live reports and name-value pairs first and the snapshot only when live has no match const [allReports, reportNameValuePairs] = await Onyx.multiGet([ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS]); - const existingB2BInvoiceReport = getParticipantsInvoiceReport( - allReports, - reportNameValuePairs, - activePolicyID, - CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, - invoiceReceiverPolicyID ?? chatReport?.policyID, - ); + const receiverPolicyID = invoiceReceiverPolicyID ?? chatReport?.policyID; + let existingB2BInvoiceReport = getParticipantsInvoiceReport(allReports, reportNameValuePairs, activePolicyID, CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, receiverPolicyID); + const snapshot = !existingB2BInvoiceReport && hash !== undefined ? await Onyx.get(`${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`) : undefined; + if (snapshot) { + existingB2BInvoiceReport = getParticipantsInvoiceReport( + getSnapshotKeyData>(snapshot, ONYXKEYS.COLLECTION.REPORT), + getSnapshotKeyData>(snapshot, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS), + activePolicyID, + CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, + receiverPolicyID, + ); + } // getPayMoneyRequestParams resolves the chat report from `chatReport` but swaps to `existingB2BInvoiceReport` // when paying an individual invoice room as a business. `payAsBusiness` is only known at click time, so pick diff --git a/src/hooks/useOnyx.ts b/src/hooks/useOnyx.ts index f0faf4346dba..ec7484d6e738 100644 --- a/src/hooks/useOnyx.ts +++ b/src/hooks/useOnyx.ts @@ -93,3 +93,4 @@ const useOnyx: UseOnyxWithoutSnapshots = { + const [submitterWorkspaceChatIDs] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { + selector: (reports) => { + if (submitterAccountID === undefined) { + return undefined; + } + const reportIDs: string[] = []; + for (const report of Object.values(reports ?? {})) { + if (report?.reportID && report.ownerAccountID === submitterAccountID && isPolicyExpenseChat(report) && !isThread(report)) { + reportIDs.push(report.reportID); + } + } + return reportIDs; + }, + }); + const [submitterWorkspaceChatActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS, { + selector: (allReportActions) => { + const reportActions: OnyxCollection = {}; + for (const reportID of submitterWorkspaceChatIDs ?? []) { + const key = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}` as const; + const actions = allReportActions?.[key]; + if (actions) { + reportActions[key] = actions; + } + } + return reportActions; + }, + }); + + return submitterWorkspaceChatActions; +} + +export default useSubmitterWorkspaceChatActions; diff --git a/tests/ui/components/KYCWallTest.tsx b/tests/ui/components/KYCWallTest.tsx index df29b6c82739..9d26d06c1d3c 100644 --- a/tests/ui/components/KYCWallTest.tsx +++ b/tests/ui/components/KYCWallTest.tsx @@ -68,6 +68,7 @@ const workspaceChat = { type: CONST.REPORT.TYPE.CHAT, chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, policyID: POLICY_ID, + ownerAccountID: iouReport.ownerAccountID, } as Report; const workspaceChatAction = createRandomReportAction(1); @@ -84,7 +85,7 @@ describe('KYCWall', () => { await Onyx.clear(); }); - it('should pass the workspace chat actions stored at press time when moving an IOU report to a workspace', async () => { + it('should pass the submitter workspace chat actions when moving an IOU report to a workspace', async () => { // Given an IOU report payer without a payment method who administers a workspace await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, adminPolicy); let continueAction: ((params?: ContinueActionParams) => void) | undefined; @@ -108,6 +109,7 @@ describe('KYCWall', () => { // And the workspace chat and its actions land in Onyx after the wall rendered await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, workspaceChat); await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`, workspaceChatActions); + await waitForBatchedUpdatesWithAct(); // When the payer picks the workspace to pay through act(() => { @@ -115,7 +117,40 @@ describe('KYCWall', () => { }); await waitForBatchedUpdatesWithAct(); - // Then the move should get those actions, because the wall reads workspace chats only when paying, so the report joins the live workspace chat + // Then the move should get those actions, because the wall subscribes to the submitter's workspace chats so the report joins the existing chat expect(mockedMoveIOUReportToPolicyAndInviteSubmitter.mock.calls.at(0)?.at(2)).toEqual({[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`]: workspaceChatActions}); }); + + it('should not pass workspace chats of other members when moving an IOU report to a workspace', async () => { + // Given an IOU report payer who administers a workspace where only another member has a workspace chat + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, adminPolicy); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, {...workspaceChat, ownerAccountID: 3}); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`, workspaceChatActions); + let continueAction: ((params?: ContinueActionParams) => void) | undefined; + render( + + ()} + iouReport={iouReport} + chatReportID={iouReport.chatReportID} + enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS} + onSuccessfulKYC={jest.fn()} + > + {(triggerKYCFlow) => { + continueAction = triggerKYCFlow; + }} + + , + ); + await waitForBatchedUpdatesWithAct(); + + // When the payer picks the workspace to pay through + act(() => { + continueAction?.({policy: adminPolicy}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the move should get no workspace chat actions, because only the submitter's own workspace chat can receive the report + expect(mockedMoveIOUReportToPolicyAndInviteSubmitter.mock.calls.at(0)?.at(2)).toEqual({}); + }); }); diff --git a/tests/ui/components/PayActionCellTest.tsx b/tests/ui/components/PayActionCellTest.tsx index 932e0ca8c336..1712e5224c94 100644 --- a/tests/ui/components/PayActionCellTest.tsx +++ b/tests/ui/components/PayActionCellTest.tsx @@ -4,6 +4,8 @@ import PayActionCell from '@components/Search/SearchList/ListItem/ActionCell/Pay import type {PaymentActionParams} from '@components/SettlementButton/types'; import useOnyx from '@hooks/useOnyx'; +import type * as UseOnyxModule from '@hooks/useOnyx'; +import {getParticipantsInvoiceReport} from '@hooks/useParticipantsInvoiceReport'; import useReportWithTransactionsAndViolations from '@hooks/useReportWithTransactionsAndViolations'; import type * as SearchActions from '@libs/actions/Search'; @@ -14,6 +16,7 @@ import {payInvoice, payMoneyRequest} from '@userActions/IOU/PayMoneyRequest'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Report, ReportActions} from '@src/types/onyx'; +import type {SearchReport} from '@src/types/onyx/SearchResults'; import type {UseOnyxResult} from 'react-native-onyx'; @@ -115,7 +118,11 @@ jest.mock('@hooks/usePaymentContext', () => ({ chatReportPolicy: undefined, })), })); -jest.mock('@hooks/useOnyx', () => jest.fn()); +jest.mock('@hooks/useOnyx', () => ({ + __esModule: true, + default: jest.fn(), + getSnapshotKeyData: jest.requireActual('@hooks/useOnyx').getSnapshotKeyData, +})); jest.mock('@components/DelegateNoAccessModalProvider', () => ({ __esModule: true, @@ -128,6 +135,7 @@ const mockedUseReportWithTransactionsAndViolations = jest.mocked(useReportWithTr const mockedPayInvoice = jest.mocked(payInvoice); const mockedPayMoneyRequest = jest.mocked(payMoneyRequest); const mockedIsInvoiceReport = jest.mocked(isInvoiceReport); +const mockedGetParticipantsInvoiceReport = jest.mocked(getParticipantsInvoiceReport); const TEST_EXPENSE_REPORT_ID = '3003'; @@ -399,4 +407,34 @@ describe('PayActionCell', () => { // Then the payment should get those actions, because the row reads them only when paying so it can update the live report preview await waitFor(() => expect(mockedPayMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({chatReportActions}))); }); + + it('should find the business invoice room in the Search snapshot when live Onyx does not have it', async () => { + // Given a business invoice room that only the Search snapshot holds + const businessInvoiceRoom = {reportID: '4004', type: CONST.REPORT.TYPE.CHAT, chatType: CONST.REPORT.CHAT_TYPE.INVOICE} as SearchReport; + const businessInvoiceRoomKey = `${ONYXKEYS.COLLECTION.REPORT}4004` as const; + mockedGetParticipantsInvoiceReport.mockImplementation((reports) => reports?.[businessInvoiceRoomKey] ?? undefined); + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${TEST_HASH}`, {data: {[businessInvoiceRoomKey]: businessInvoiceRoom}}); + + render( + , + ); + + // When the user pays the invoice as a business + act(() => { + mockOnPressHolder.current?.({ + paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE, + payAsBusiness: true, + }); + }); + + // Then the payment should get the snapshot room, so paying as a business does not turn the individual room into a business room locally + await waitFor(() => expect(mockedPayInvoice).toHaveBeenCalledWith(expect.objectContaining({existingB2BInvoiceReport: businessInvoiceRoom}))); + }); });