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
49 changes: 35 additions & 14 deletions src/libs/ReportSecondaryActionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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) {
Expand Down
91 changes: 91 additions & 0 deletions src/libs/actions/IOU/PayMoneyRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
isExpenseReport,
isIndividualInvoiceRoom,
isInvoiceReport as isInvoiceReportReportUtils,
isIOUReport,
updateReportPreview,
} from '@libs/ReportUtils';
import playSound, {SOUNDS} from '@libs/Sound';
Expand Down Expand Up @@ -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<OnyxUpdate<typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.REPORT>> = [
{
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<OnyxUpdate<typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`,
value: {
[optimisticIOUCancelAction.reportActionID]: {
pendingAction: null,
},
},
},
];

const failureData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.REPORT>> = [
{
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<OnyxTypes.Report>,
chatReport: OnyxTypes.Report,
Expand All @@ -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,
Expand Down
39 changes: 39 additions & 0 deletions tests/actions/IOUTest/PayMoneyRequestTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading