diff --git a/src/libs/ReportSecondaryActionUtils.ts b/src/libs/ReportSecondaryActionUtils.ts index 3347a1a72688..a73e6083b49d 100644 --- a/src/libs/ReportSecondaryActionUtils.ts +++ b/src/libs/ReportSecondaryActionUtils.ts @@ -398,6 +398,23 @@ function isUnapproveAction(currentUserLogin: string, currentUserAccountID: numbe return isReportApprover; } +// Pay actions are at the report level, not per transaction. +function getReportPayActions(reportID: string): ReportAction[] { + return Object.values(getAllReportActions(reportID)).filter((action): action is ReportAction => !!action && isPayAction(action)); +} + +// Whether every pay action on the report has a payment type the predicate accepts. Returns false when there are +// no pay actions, since the payment type cannot be determined. +function everyPayActionHasPaymentType(payActions: ReportAction[], matchesPaymentType: (paymentType: string | undefined) => boolean): boolean { + return ( + payActions.length > 0 && + payActions.every((action) => { + const originalMessage = getOriginalMessage(action); + return !!originalMessage && 'paymentType' in originalMessage && matchesPaymentType(originalMessage.paymentType); + }) + ); +} + function isCancelPaymentAction( currentAccountID: number, currentUserEmail: string, @@ -407,32 +424,36 @@ function isCancelPaymentAction( policy?: Policy, ): boolean { const isExpenseReport = isExpenseReportUtils(report); + const isIOUReport = isIOUReportUtils(report); - if (!isExpenseReport) { + if (!isExpenseReport && !isIOUReport) { return false; } - const isAdmin = policy?.role === CONST.POLICY.ROLE.ADMIN; const isPayer = isPayerUtils(currentAccountID, currentUserEmail, report, bankAccountList, policy, false); + // A P2P "send money" payment made with the Expensify wallet that is waiting for the receiver to set up their + // wallet is held until they onboard. The sender (payer) can cancel it while it is waiting, which returns the + // held funds. + if (isIOUReport) { + if (!isPayer || !report.isWaitingOnBankAccount) { + return false; + } + + const payActions = getReportPayActions(report.reportID); + return everyPayActionHasPaymentType(payActions, (paymentType) => paymentType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY); + } + + const isAdmin = policy?.role === CONST.POLICY.ROLE.ADMIN; + if (!isAdmin || !isPayer) { return false; } - // Get all report actions for this report and filter for pay actions - // Pay actions are at the report level, not per transaction - const allReportActions = getAllReportActions(report.reportID); - const allActionsArray = Object.values(allReportActions); - const payActions = allActionsArray.filter((action): action is ReportAction => !!action && isPayAction(action)); + const payActions = getReportPayActions(report.reportID); // Check if payment was made via bank account (not elsewhere) - // If no pay actions exist, we can't determine the payment type, so we assume it was NOT a bank payment - const isPaidViaBankAccount = - payActions.length > 0 && - payActions.every((action) => { - const originalMessage = getOriginalMessage(action); - return originalMessage && 'paymentType' in originalMessage && originalMessage.paymentType !== CONST.IOU.PAYMENT_TYPE.ELSEWHERE; - }); + const isPaidViaBankAccount = everyPayActionHasPaymentType(payActions, (paymentType) => paymentType !== CONST.IOU.PAYMENT_TYPE.ELSEWHERE); // For reports marked as paid elsewhere or when we can't determine payment type, show cancel button if (report.stateNum === CONST.REPORT.STATE_NUM.APPROVED && report.statusNum === CONST.REPORT.STATUS_NUM.REIMBURSED && !isPaidViaBankAccount) { diff --git a/src/libs/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index c77d047e71bd..b923300f9e3a 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -24,6 +24,7 @@ import { isExpenseReport, isIndividualInvoiceRoom, isInvoiceReport as isInvoiceReportReportUtils, + isIOUReport, updateReportPreview, } from '@libs/ReportUtils'; import playSound, {SOUNDS} from '@libs/Sound'; @@ -521,6 +522,87 @@ function getPayMoneyRequestParams({ }; } +/** + * Cancels a P2P "send money" wallet payment that is waiting for the receiver to set up their wallet. The + * sender (payer) can do this while the payment is held; it returns the held funds. These reports have no + * policy, approval flow, or next step, so we only reverse the optimistic IOU report state. + */ +function cancelSendMoneyPayment(iouReport: OnyxTypes.Report, chatReport: OnyxTypes.Report, currentUserAccountIDParam: number) { + const optimisticIOUCancelAction = buildOptimisticCancelPaymentReportAction(iouReport.reportID, -(iouReport.total ?? 0), iouReport.currency ?? '', currentUserAccountIDParam); + + const optimisticData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`, + value: { + [optimisticIOUCancelAction.reportActionID]: optimisticIOUCancelAction as OnyxTypes.ReportAction, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`, + value: { + isWaitingOnBankAccount: false, + isCancelledIOU: true, + // These reports belong to the sender's personal policy, which approves optionally, so cancelling + // returns the report to submitted and closed rather than approved. + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.CLOSED, + lastVisibleActionCreated: optimisticIOUCancelAction.created, + lastMessageText: getReportActionText(optimisticIOUCancelAction), + lastMessageHtml: getReportActionHtml(optimisticIOUCancelAction), + }, + }, + ]; + + const successData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`, + value: { + [optimisticIOUCancelAction.reportActionID]: { + pendingAction: null, + }, + }, + }, + ]; + + const failureData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`, + value: { + [optimisticIOUCancelAction.reportActionID]: { + errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.other'), + }, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`, + value: { + isWaitingOnBankAccount: iouReport.isWaitingOnBankAccount, + isCancelledIOU: false, + stateNum: iouReport.stateNum, + statusNum: iouReport.statusNum, + }, + }, + ]; + + API.write( + WRITE_COMMANDS.CANCEL_PAYMENT, + { + iouReportID: iouReport.reportID, + chatReportID: chatReport.reportID, + managerAccountID: iouReport.managerID ?? CONST.DEFAULT_NUMBER_ID, + reportActionID: optimisticIOUCancelAction.reportActionID, + }, + {optimisticData, successData, failureData}, + ); + + notifyNewAction(iouReport.reportID, undefined, true); +} + function cancelPayment( expenseReport: OnyxEntry, chatReport: OnyxTypes.Report, @@ -535,6 +617,15 @@ function cancelPayment( return; } + // A P2P "send money" payment waiting for the receiver to set up their wallet has no policy, approval + // flow, or next step, so it is cancelled through a simplified path that just reverses the optimistic IOU + // report state and lets the backend return the held funds. Other IOU reports (e.g. a money request paid + // elsewhere) keep using the standard path below. + if (isIOUReport(expenseReport) && expenseReport.isWaitingOnBankAccount) { + cancelSendMoneyPayment(expenseReport, chatReport, currentUserAccountIDParam); + return; + } + // Prefer the freshly computed reimbursableTotal over deriving from the (sometimes stale) stored total. const optimisticReportAction = buildOptimisticCancelPaymentReportAction( expenseReport.reportID, diff --git a/tests/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index 839200e19ec9..1ee41471d74c 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -1682,6 +1682,45 @@ describe('actions/IOU/PayMoneyRequest', () => { }); }); + it('cancels a pending P2P wallet payment and optimistically marks the IOU report cancelled', async () => { + // Given a P2P "send money" IOU report that is waiting for the receiver to set up their wallet + const chatReportID = '7777'; + const iouReportID = '8888'; + const chatReport: Report = {...createRandomReport(7777, undefined), reportID: chatReportID}; + const iouReport: Report = { + ...createRandomReport(8888, undefined), + reportID: iouReportID, + chatReportID, + type: CONST.REPORT.TYPE.IOU, + managerID: CARLOS_ACCOUNT_ID, + ownerAccountID: RORY_ACCOUNT_ID, + total: -amount, + currency: CONST.CURRENCY.USD, + isWaitingOnBankAccount: true, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, + }; + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`, iouReport); + await waitForBatchedUpdates(); + + // When the payer cancels the pending payment + cancelPayment(iouReport, chatReport, undefined, true, CARLOS_ACCOUNT_ID, CARLOS_EMAIL, true, false); + await waitForBatchedUpdates(); + + // Then the IOU report is optimistically marked cancelled and no longer waiting on the bank account + const updatedReport = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`); + expect(updatedReport?.isCancelledIOU).toBe(true); + expect(updatedReport?.isWaitingOnBankAccount).toBe(false); + expect(updatedReport?.stateNum).toBe(CONST.REPORT.STATE_NUM.SUBMITTED); + expect(updatedReport?.statusNum).toBe(CONST.REPORT.STATUS_NUM.CLOSED); + + // And a reimbursement-dequeued cancel action is added to the IOU report + const reportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`); + const cancelAction = Object.values(reportActions ?? {}).find((action) => action?.actionName === CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DEQUEUED); + expect(cancelAction).toBeTruthy(); + }); + it('optimistic nextStep shows waiting to pay when approvals are disabled and bank account is connected', async () => { const adminEmail = 'admin@expensifail.com'; const adminAccountID = 10; diff --git a/tests/unit/ReportSecondaryActionUtilsTest.ts b/tests/unit/ReportSecondaryActionUtilsTest.ts index a99fad4fb345..864477d9f7ad 100644 --- a/tests/unit/ReportSecondaryActionUtilsTest.ts +++ b/tests/unit/ReportSecondaryActionUtilsTest.ts @@ -33,6 +33,12 @@ const APPROVER_EMAIL = 'approver@mail.com'; const ADMIN_ACCOUNT_ID = 4; const ADMIN_EMAIL = 'admin@mail.com'; +// For the P2P wallet "send money" cases below, the sender is the payer (managerID) and the receiver is the owner. +const SENDER_ACCOUNT_ID = EMPLOYEE_ACCOUNT_ID; +const SENDER_EMAIL = EMPLOYEE_EMAIL; +const RECEIVER_ACCOUNT_ID = MANAGER_ACCOUNT_ID; +const RECEIVER_EMAIL = MANAGER_EMAIL; + const SESSION = { email: EMPLOYEE_EMAIL, accountID: EMPLOYEE_ACCOUNT_ID, @@ -2009,6 +2015,162 @@ describe('getSecondaryAction', () => { expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(true); }); + it('includes CANCEL_PAYMENT option for the sender of a P2P wallet payment waiting on the receiver wallet', async () => { + const report = createMock({ + reportID: REPORT_ID, + type: CONST.REPORT.TYPE.IOU, + ownerAccountID: RECEIVER_ACCOUNT_ID, + managerID: SENDER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, + isWaitingOnBankAccount: true, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); + + const ACTION_ID = 'action_id'; + const reportAction = createMock({ + reportActionID: ACTION_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + message: { + type: CONST.IOU.REPORT_ACTION_TYPE.PAY, + paymentType: CONST.IOU.PAYMENT_TYPE.EXPENSIFY, + }, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {[ACTION_ID]: reportAction}); + + const result = getSecondaryReportActions({ + currentUserLogin: SENDER_EMAIL, + currentUserAccountID: SENDER_ACCOUNT_ID, + submitterLogin: '', + report, + chatReport, + reportTransactions: [], + originalTransaction: createMock({}), + violations: {}, + bankAccountList: {}, + policy: undefined, + isProduction: false, + }); + expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(true); + }); + + it('excludes CANCEL_PAYMENT option for the receiver of a P2P wallet payment waiting on the receiver wallet', async () => { + const report = createMock({ + reportID: REPORT_ID, + type: CONST.REPORT.TYPE.IOU, + ownerAccountID: RECEIVER_ACCOUNT_ID, + managerID: SENDER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, + isWaitingOnBankAccount: true, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); + + const ACTION_ID = 'action_id'; + const reportAction = createMock({ + reportActionID: ACTION_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + message: { + type: CONST.IOU.REPORT_ACTION_TYPE.PAY, + paymentType: CONST.IOU.PAYMENT_TYPE.EXPENSIFY, + }, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {[ACTION_ID]: reportAction}); + + const result = getSecondaryReportActions({ + currentUserLogin: RECEIVER_EMAIL, + currentUserAccountID: RECEIVER_ACCOUNT_ID, + submitterLogin: '', + report, + chatReport, + reportTransactions: [], + originalTransaction: createMock({}), + violations: {}, + bankAccountList: {}, + policy: undefined, + isProduction: false, + }); + expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(false); + }); + + it('excludes CANCEL_PAYMENT option for a P2P payment sent elsewhere (not via wallet)', async () => { + const report = createMock({ + reportID: REPORT_ID, + type: CONST.REPORT.TYPE.IOU, + ownerAccountID: RECEIVER_ACCOUNT_ID, + managerID: SENDER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, + isWaitingOnBankAccount: true, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); + + const ACTION_ID = 'action_id'; + const reportAction = createMock({ + reportActionID: ACTION_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + message: { + type: CONST.IOU.REPORT_ACTION_TYPE.PAY, + paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE, + }, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {[ACTION_ID]: reportAction}); + + const result = getSecondaryReportActions({ + currentUserLogin: SENDER_EMAIL, + currentUserAccountID: SENDER_ACCOUNT_ID, + submitterLogin: '', + report, + chatReport, + reportTransactions: [], + originalTransaction: createMock({}), + violations: {}, + bankAccountList: {}, + policy: undefined, + isProduction: false, + }); + expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(false); + }); + + it('excludes CANCEL_PAYMENT option for a P2P wallet payment no longer waiting on the receiver wallet', async () => { + const report = createMock({ + reportID: REPORT_ID, + type: CONST.REPORT.TYPE.IOU, + ownerAccountID: RECEIVER_ACCOUNT_ID, + managerID: SENDER_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, + isWaitingOnBankAccount: false, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); + + const ACTION_ID = 'action_id'; + const reportAction = createMock({ + reportActionID: ACTION_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + message: { + type: CONST.IOU.REPORT_ACTION_TYPE.PAY, + paymentType: CONST.IOU.PAYMENT_TYPE.EXPENSIFY, + }, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {[ACTION_ID]: reportAction}); + + const result = getSecondaryReportActions({ + currentUserLogin: SENDER_EMAIL, + currentUserAccountID: SENDER_ACCOUNT_ID, + submitterLogin: '', + report, + chatReport, + reportTransactions: [], + originalTransaction: createMock({}), + violations: {}, + bankAccountList: {}, + policy: undefined, + isProduction: false, + }); + expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(false); + }); + it('includes RECEIVED_PAYMENT option for approved expense report submitter with reimbursable spend', () => { const report = createMock({ reportID: REPORT_ID,