Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import useThemeStyles from '@hooks/useThemeStyles';

import {payInvoice, payMoneyRequest} from '@libs/actions/IOU/PayMoneyRequest';
import {canIOUBePaid} from '@libs/actions/IOU/ReportWorkflow';
import {getSearchPayOnyxData} from '@libs/actions/Search';
import {getChatReportWithFallback, getSearchPayOnyxData} from '@libs/actions/Search';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import Log from '@libs/Log';
import {getReimbursableTotal, isIndividualInvoiceRoom, isInvoiceReport} from '@libs/ReportUtils';
Expand Down Expand Up @@ -83,13 +83,12 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
const {currency} = iouReport ?? {};

const confirmPayment = ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => {
if (!type || !reportID || !hash || !amount || !chatReport) {
if (!type || !reportID || !hash || !amount) {
Log.info('[SearchPay] Dropping row pay: missing required data', false, {
hasPaymentType: !!type,
reportID,
hasHash: !!hash,
hasAmount: !!amount,
hasChatReport: !!chatReport,
});
return;
}
Expand All @@ -102,6 +101,11 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
const additionalOnyxData = getSearchPayOnyxData(hash, reportID);

if (isInvoiceReport(iouReport)) {
// Invoice payments rely on the invoice room data, so they can't proceed without the chat report.
if (!chatReport) {
Log.info('[SearchPay] Dropping invoice row pay: chat report is not loaded', false, {reportID});
return;
}
const existingB2BInvoiceReport = getParticipantsInvoiceReport(
allReports,
reportNameValuePairs,
Expand Down Expand Up @@ -143,10 +147,21 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
return;
}

// The chat report is only needed for optimistic chat updates, so when it isn't loaded, pay with a fallback
// built from the known IDs and let the server fill in the chat data.
const fallbackChatReportID = iouReport?.chatReportID ?? iouReport?.parentReportID;
const fallbackPolicyID = iouReport?.policyID ?? policyID;
const {chatReport: chatReportForPayment, isFallbackChatReport} = getChatReportWithFallback(chatReport, fallbackChatReportID, fallbackPolicyID);
if (!chatReportForPayment) {
Log.info('[SearchPay] Dropping row pay: chat report is not loaded and no chatReportID is available', false, {reportID});
return;
}

payMoneyRequest({
getCurrencyDecimals,
paymentType: type,
chatReport,
chatReport: chatReportForPayment,
isFallbackChatReport,
iouReport,
introSelected,
currentUserAccountID,
Expand Down
21 changes: 16 additions & 5 deletions src/hooks/useSearchBulkActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
getPolicyFromSearchSnapshot,
getReportFromSearchSnapshot,
getReportType,
getChatReportWithFallback,
getSearchApproveOnyxData,
getSearchPayOnyxData,
getTotalFormattedAmount,
Expand Down Expand Up @@ -1399,11 +1400,21 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
continue;
}

const chatReport = getChatReportForBulkPay(iouReport, item.chatReportID, searchData, allReports);
if (!chatReport) {
const isItemInvoice = isInvoiceReport(iouReport);
const fallbackChatReportID = item.chatReportID ?? iouReport.chatReportID ?? iouReport.parentReportID;
const fallbackPolicyID = iouReport.policyID ?? item.policyID;
const {chatReport, isFallbackChatReport} = getChatReportWithFallback(
getChatReportForBulkPay(iouReport, item.chatReportID, searchData, allReports),
fallbackChatReportID,
fallbackPolicyID,
);
// The fallback covers money requests only. Invoices genuinely need the invoice room data such as
// receiver type and pay-as-business, so skip them when the chat isn't loaded.
if (!chatReport || (isItemInvoice && isFallbackChatReport)) {
Log.info('[BulkPay] Skipping report: chat report not found in the search snapshot or Onyx', false, {
reportID: item.reportID,
chatReportID: item.chatReportID ?? iouReport.chatReportID ?? iouReport.parentReportID,
chatReportID: fallbackChatReportID,
isItemInvoice,
});
continue;
}
Expand All @@ -1420,7 +1431,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
reportID: item.reportID,
amount: item.amount,
paymentType: resolvedPaymentType,
...(isInvoiceReport(item.reportID)
...(isItemInvoice
? getPayMoneyOnSearchInvoiceParams(
item.policyID,
additionalData?.payAsBusiness ?? isBusinessInvoiceRoom(item.chatReportID),
Expand All @@ -1436,7 +1447,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
const chatReportPolicy = getPolicyFromSearchSnapshot(chatReport.policyID, searchData, policies);
const reportPolicy = workspacePayPolicy ?? getPolicyFromSearchSnapshot(item.policyID, searchData, policies);
const additionalOnyxData = getSearchPayOnyxData(hash, item.reportID, currentSearchKey);
const isItemInvoice = isInvoiceReport(item.reportID);

if (isItemInvoice) {
const invoiceReceiverPolicyID = chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : undefined;
Expand Down Expand Up @@ -1504,6 +1514,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
delegateAccountID,
isTrackIntentUser,
conciergeChat,
isFallbackChatReport,
});
paidReportCount += 1;
}
Expand Down
24 changes: 16 additions & 8 deletions src/libs/actions/IOU/PayMoneyRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ type PayMoneyRequestFunctionParams = {
chatReportActions: OnyxEntry<OnyxTypes.ReportActions>;
isTrackIntentUser: boolean | undefined;
getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals'];
isFallbackChatReport?: boolean;
};

function mergeAdditionalPayOnyxData<
Expand Down Expand Up @@ -172,6 +173,7 @@ function getPayMoneyRequestParams({
chatReportActions,
isTrackIntentUser,
getCurrencyDecimals,
isFallbackChatReport,
}: {
initialChatReport: OnyxTypes.Report;
iouReport: OnyxEntry<OnyxTypes.Report>;
Expand All @@ -197,6 +199,7 @@ function getPayMoneyRequestParams({
chatReportActions: OnyxEntry<OnyxTypes.ReportActions>;
isTrackIntentUser: boolean | undefined;
getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals'];
isFallbackChatReport?: boolean;
}): PayMoneyRequestData {
// TODO: https://github.com/Expensify/App/issues/66512
// eslint-disable-next-line @typescript-eslint/no-deprecated
Expand Down Expand Up @@ -320,12 +323,20 @@ function getPayMoneyRequestParams({
};
}

onyxData.optimisticData?.push(
{
if (!isFallbackChatReport) {
onyxData.optimisticData?.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`,
value: optimisticChatReport,
},
});
onyxData.failureData?.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`,
value: chatReport,
});
}

onyxData.optimisticData?.push(
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`,
Expand Down Expand Up @@ -421,11 +432,6 @@ function getPayMoneyRequestParams({
...iouReport,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`,
value: chatReport,
},
);

// In case the report preview action is loaded locally, let's update it.
Expand Down Expand Up @@ -803,6 +809,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) {
chatReportActions,
isTrackIntentUser,
getCurrencyDecimals,
isFallbackChatReport,
} = params;
const policyForBillingRestriction = chatReportPolicy ?? (policy?.id === chatReport.policyID ? policy : undefined);
if (
Expand Down Expand Up @@ -839,6 +846,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) {
chatReportActions,
isTrackIntentUser,
getCurrencyDecimals,
isFallbackChatReport,
});

// For now, we need to call the PayMoneyRequestWithWallet API since PayMoneyRequest was not updated to work with
Expand Down
19 changes: 19 additions & 0 deletions src/libs/actions/Search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,24 @@ function getChatReportForSearchPay(chatReport: OnyxEntry<Report>, snapshotReport
return chatReport ?? snapshotChatReport ?? (chatReportID ? getReportOrDraftReport(chatReportID) : undefined);
}

/**
* Returns the chat report to pay with. When the chat isn't loaded, builds a fallback from the known IDs so the
* payment isn't blocked; isFallbackChatReport tells payMoneyRequest to skip the optimistic chat updates.
*/
function getChatReportWithFallback(
loadedChatReport: OnyxEntry<Report>,
fallbackChatReportID: string | undefined,
fallbackPolicyID: string | undefined,
): {chatReport: OnyxEntry<Report>; isFallbackChatReport: boolean} {
if (loadedChatReport) {
return {chatReport: loadedChatReport, isFallbackChatReport: false};
}
if (!fallbackChatReportID) {
return {chatReport: undefined, isFallbackChatReport: false};
}
return {chatReport: {reportID: fallbackChatReportID, policyID: fallbackPolicyID}, isFallbackChatReport: true};
}

function getReportFromSearchSnapshot(reportID: string | undefined, searchData: SearchResultDataType | undefined, allReports: OnyxCollection<Report> | undefined): OnyxEntry<Report> {
if (!reportID) {
return undefined;
Expand Down Expand Up @@ -2183,6 +2201,7 @@ export {
setSearchContext,
deleteSavedSearch,
getSearchPayOnyxData,
getChatReportWithFallback,
getSearchApproveOnyxData,
handleActionButtonPress,
submitMoneyRequestOnSearch,
Expand Down
117 changes: 116 additions & 1 deletion tests/ui/components/PayActionCellTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import type {PaymentActionParams} from '@components/SettlementButton/types';
import useOnyx from '@hooks/useOnyx';
import useReportWithTransactionsAndViolations from '@hooks/useReportWithTransactionsAndViolations';

import {payInvoice} from '@userActions/IOU/PayMoneyRequest';
import type * as SearchActions from '@libs/actions/Search';
import {isInvoiceReport} from '@libs/ReportUtils';

import {payInvoice, payMoneyRequest} from '@userActions/IOU/PayMoneyRequest';

import CONST from '@src/CONST';
import type {Report} from '@src/types/onyx';
Expand Down Expand Up @@ -59,9 +62,21 @@ jest.mock('@userActions/IOU/ReportWorkflow', () => ({
canIOUBePaid: jest.fn(() => true),
}));

const mockLogInfo = jest.fn();
jest.mock('@libs/Log', () => ({
__esModule: true,
default: {
info: (...args: unknown[]) => {
mockLogInfo(...args);
},
warn: jest.fn(),
},
}));

jest.mock('@libs/actions/Search', () => ({
__esModule: true,
getSearchPayOnyxData: jest.fn(() => ({optimisticData: [], successData: [], failureData: []})),
getChatReportWithFallback: jest.requireActual<typeof SearchActions>('@libs/actions/Search').getChatReportWithFallback,
}));

jest.mock('@libs/ReportUtils', () => {
Expand Down Expand Up @@ -113,6 +128,19 @@ jest.mock('@components/DelegateNoAccessModalProvider', () => ({
const mockedUseOnyx = jest.mocked(useOnyx);
const mockedUseReportWithTransactionsAndViolations = jest.mocked(useReportWithTransactionsAndViolations);
const mockedPayInvoice = jest.mocked(payInvoice);
const mockedPayMoneyRequest = jest.mocked(payMoneyRequest);
const mockedIsInvoiceReport = jest.mocked(isInvoiceReport);

const TEST_EXPENSE_REPORT_ID = '3003';

const expenseReport = {
reportID: TEST_EXPENSE_REPORT_ID,
chatReportID: TEST_CHAT_REPORT_ID,
type: CONST.REPORT.TYPE.EXPENSE,
currency: CONST.CURRENCY.USD,
policyID: 'policy1',
total: -5000,
} as Report;

describe('PayActionCell', () => {
beforeEach(() => {
Expand Down Expand Up @@ -170,5 +198,92 @@ describe('PayActionCell', () => {
});

expect(mockedPayInvoice).not.toHaveBeenCalled();
expect(mockLogInfo).toHaveBeenCalledWith('[SearchPay] Dropping invoice row pay: chat report is not loaded', false, {reportID: TEST_INVOICE_REPORT_ID});
});

it('pays a money request with a fallback chat report when no chatReport prop is supplied', () => {
mockedIsInvoiceReport.mockReturnValue(false);
mockedUseReportWithTransactionsAndViolations.mockReturnValue([expenseReport, [], undefined]);

render(
<PayActionCell
isLoading={false}
policyID="policy1"
reportID={TEST_EXPENSE_REPORT_ID}
hash={TEST_HASH}
amount={5000}
chatReport={undefined}
/>,
);

act(() => {
mockOnPressHolder.current?.({
paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE,
payAsBusiness: false,
});
});

expect(mockedPayMoneyRequest).toHaveBeenCalledWith(
expect.objectContaining({
chatReport: {reportID: TEST_CHAT_REPORT_ID, policyID: 'policy1'},
isFallbackChatReport: true,
}),
);
});

it('pays a money request with the loaded chat report when it is supplied', () => {
mockedIsInvoiceReport.mockReturnValue(false);
mockedUseReportWithTransactionsAndViolations.mockReturnValue([expenseReport, [], undefined]);

render(
<PayActionCell
isLoading={false}
policyID="policy1"
reportID={TEST_EXPENSE_REPORT_ID}
hash={TEST_HASH}
amount={5000}
chatReport={chatReport}
/>,
);

act(() => {
mockOnPressHolder.current?.({
paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE,
payAsBusiness: false,
});
});

expect(mockedPayMoneyRequest).toHaveBeenCalledWith(
expect.objectContaining({
chatReport,
isFallbackChatReport: false,
}),
);
});

it('does not pay a money request and logs the reason when the chat is not loaded and no chatReportID is available', () => {
mockedIsInvoiceReport.mockReturnValue(false);
mockedUseReportWithTransactionsAndViolations.mockReturnValue([{...expenseReport, chatReportID: undefined, parentReportID: undefined}, [], undefined]);

render(
<PayActionCell
isLoading={false}
policyID="policy1"
reportID={TEST_EXPENSE_REPORT_ID}
hash={TEST_HASH}
amount={5000}
chatReport={undefined}
/>,
);

act(() => {
mockOnPressHolder.current?.({
paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE,
payAsBusiness: false,
});
});

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});
});
});
Loading
Loading