Skip to content
Open
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
23 changes: 12 additions & 11 deletions src/hooks/useSearchBulkActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
const hasOnlyEmptyReports = selectedReports.length > 0 && emptyReports.length === selectedReports.length;

const payableSelectedReports = useMemo(() => selectedReports.filter((report) => report.canPay), [selectedReports]);
const payableSelectedReportIDs = useMemo(() => payableSelectedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payableSelectedReports]);
const payScopedReports = useMemo(() => (payableSelectedReports.length > 0 ? payableSelectedReports : selectedReports), [payableSelectedReports, selectedReports]);
Comment thread
allgandalf marked this conversation as resolved.
Resolved
const payScopedReportIDs = useMemo(() => payScopedReports.map((report) => report.reportID).filter((reportID) => reportID !== undefined), [payScopedReports]);

Expand Down Expand Up @@ -1771,10 +1770,17 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
return;
}

const selectedOptions = selectedReports.length ? payableSelectedReports : Object.values(selectedTransactions);
const selectedOptions = selectedReports.length ? selectedReports : Object.values(selectedTransactions);
Comment thread
allgandalf marked this conversation as resolved.
Resolved
const expenseReportBankAccountID = additionalData?.bankAccountID;

const restrictedPolicyID = getRestrictedPolicyID(selectedOptions, userBillingGracePeriodEnds, ownerBillingGracePeriodEnd, amountOwed, policies, accountID);
const restrictedPolicyID = getRestrictedPolicyID(
selectedReports.length ? payableSelectedReports : selectedOptions,
userBillingGracePeriodEnds,
ownerBillingGracePeriodEnd,
amountOwed,
policies,
accountID,
);
if (restrictedPolicyID) {
Log.info('[BulkPay] Blocking bulk pay: billable actions are restricted', false, {policyID: restrictedPolicyID});
Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(restrictedPolicyID));
Expand Down Expand Up @@ -1880,7 +1886,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
}
const itemsToPay =
selectedReports.length > 0
? payableSelectedReports.map((report) => ({
? selectedReports.map((report) => ({
reportID: report.reportID,
amount: report.total,
policyID: report.policyID,
Expand Down Expand Up @@ -2157,7 +2163,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
isOffline,
isBetaEnabled,
isDelegateAccessRestricted,
selectedReports.length,
selectedReports,
payableSelectedReports,
selectedTransactions,
userBillingGracePeriodEnds,
Expand Down Expand Up @@ -2378,10 +2384,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {

const options: Array<DropdownOption<SearchHeaderOptionValue>> = [];
const isAnyTransactionOnHold = Object.values(selectedTransactions).some((transaction) => transaction.isHeld);
const isAnyPayableTransactionOnHold =
payableSelectedReports.length > 0
? Object.values(selectedTransactions).some((transaction) => transaction.isHeld && !!transaction.reportID && payableSelectedReportIDs.includes(transaction.reportID))
: isAnyTransactionOnHold;
const allMatchingReportActionQuery = areAllMatchingItemsSelected && queryJSON ? getAllMatchingReportActionQuery(queryJSON, excludedTransactions, isExpenseReportType) : undefined;

const getExportOptions = () => {
Expand Down Expand Up @@ -2871,7 +2873,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
const hasLoadedPayableReport = payableSelectedReports.length > 0 || selectedReports.length === 0;
const shouldShowPayOption = areAllMatchingItemsSelected
? hasLoadedPayableReport && !!bulkPayButtonOptions?.length && !!allMatchingReportActionQuery
: !isAnyPayableTransactionOnHold && shouldEnableBulkPayOption && !!bulkPayButtonOptions?.length;
: !isAnyTransactionOnHold && shouldEnableBulkPayOption && !!bulkPayButtonOptions?.length;
const payButtonOption: DropdownOption<SearchHeaderOptionValue> & Pick<PopoverMenuItem, 'rightIcon'> = {
icon: expensifyIcons.MoneyBag,
text: translate('search.bulkActions.pay'),
Expand Down Expand Up @@ -3778,7 +3780,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) {
isOffline,
selectedReports,
payableSelectedReports.length,
payableSelectedReportIDs,
lastPaymentMethods,
selectedReportIDs,
personalPolicyID,
Expand Down
11 changes: 5 additions & 6 deletions src/libs/actions/Search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2723,20 +2723,19 @@ function getPayOption(
) {
const transactionKeys = Object.keys(selectedTransactions ?? {});
const firstTransaction = selectedTransactions?.[transactionKeys.at(0) ?? ''];
const payableReports = selectedReports.filter((report) => report.canPay);
const firstPayableReport = payableReports.at(0);
const firstReport = selectedReports.at(0);
const getSelectedReportType = (report: SelectedReports | undefined) => report?.type ?? getReportType(report);
const hasLastPaymentMethod =
selectedReports.length > 0
? payableReports.every((report) => !!getLastPolicyPaymentMethod(report.policyID, personalPolicyID, lastPaymentMethods))
? selectedReports.every((report) => !!getLastPolicyPaymentMethod(report.policyID, personalPolicyID, lastPaymentMethods))
: transactionKeys.every((transactionIDKey) => !!getLastPolicyPaymentMethod(selectedTransactions[transactionIDKey].policyID, personalPolicyID, lastPaymentMethods));

const shouldShowBulkPayOption =
selectedReports.length > 0
? payableReports.length > 0 &&
payableReports.every(
? selectedReports.every(
(report) =>
getSelectedReportType(report) === getSelectedReportType(firstPayableReport) &&
report.canPay &&
getSelectedReportType(report) === getSelectedReportType(firstReport) &&
shouldShowBulkOptionForRemainingTransactions(selectedTransactions, selectedReportIDs, transactionKeys),
)
: transactionKeys.every(
Expand Down
16 changes: 7 additions & 9 deletions tests/unit/SearchActionsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -790,24 +790,22 @@ describe('getPayOption', () => {
expect(getShouldEnableBulkPayOption([makeSelectedReport('1', true), makeSelectedReport('2', true)])).toBe(true);
});

it('keeps bulk pay enabled when only some of the selected reports are payable', () => {
// Given a selection mixing two payable reports with one the viewer cannot settle (it only offers View)
it('disables bulk pay when only some of the selected reports are payable', () => {
// Given a selection mixing two payable reports with one the viewer cannot pay (it only offers View)

// When the bulk pay eligibility is computed
const shouldEnableBulkPayOption = getShouldEnableBulkPayOption([makeSelectedReport('1', true), makeSelectedReport('2', true), makeSelectedReport('3', false)]);

// Then bulk pay stays available because it degrades to the payable subset instead of dropping the whole Pay
// group — the ineligible report is skipped at payment time rather than hiding Pay and Mark as paid for all three
expect(shouldEnableBulkPayOption).toBe(true);
// Then bulk pay is disabled, the same way Approve needs every selected report to be approvable
expect(shouldEnableBulkPayOption).toBe(false);
});

it('disables bulk pay when no selected report is payable', () => {
expect(getShouldEnableBulkPayOption([makeSelectedReport('1', false), makeSelectedReport('2', false)])).toBe(false);
});

it('keeps transaction selections all-or-nothing', () => {
// Given a transaction-level selection where one transaction cannot be paid. Individual transactions are not
// paid one by one, so unlike whole reports there is no payable subset to degrade to.
// Given a transaction-level selection where one transaction cannot be paid
function makeSelectedTransaction(reportID: string, action: SelectedTransactions[string]['action']): SelectedTransactions[string] {
return {
isSelected: true,
Expand All @@ -834,7 +832,7 @@ describe('getPayOption', () => {

// When the bulk pay eligibility is computed

// Then bulk pay is unavailable, as it was before whole-report selections learned to degrade
// Then bulk pay is unavailable
expect(getPayOption([], selectedTransactions, undefined, [], undefined).shouldEnableBulkPayOption).toBe(false);
});

Expand All @@ -861,7 +859,7 @@ describe('getPayOption', () => {
});

it('disables bulk pay when the payable reports are of different types', async () => {
// Given a payable subset mixing an expense report with an IOU report. Bulk pay resolves one payment method
// Given payable reports mixing an expense report with an IOU report. Bulk pay resolves one payment method
// for the whole group, so mixed types genuinely cannot be paid together.
Onyx.init({keys: ONYXKEYS});
await Onyx.clear();
Expand Down
81 changes: 39 additions & 42 deletions tests/unit/hooks/useSearchBulkActionsPayTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ 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 Navigation from '@libs/Navigation/Navigation';
import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils';
import type * as SubscriptionUtilsModule from '@libs/SubscriptionUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -139,6 +142,11 @@ jest.mock('@libs/actions/User', () => ({
setNameValuePair: jest.fn(),
}));

jest.mock('@libs/SubscriptionUtils', () => ({
...jest.requireActual<typeof SubscriptionUtilsModule>('@libs/SubscriptionUtils'),
shouldRestrictUserBillableActions: jest.fn(() => false),
}));

jest.mock('@libs/Navigation/Navigation', () => ({
navigate: jest.fn(),
getActiveRoute: jest.fn(() => '/test'),
Expand Down Expand Up @@ -262,6 +270,7 @@ jest.mock('@components/Search/SearchContext', () => ({
}));

const CURRENT_USER_ACCOUNT_ID = 1;
const RESTRICTED_POLICY_OWNER_ACCOUNT_ID = 2;

jest.mock('@hooks/useCurrentUserPersonalDetails', () => ({
__esModule: true,
Expand Down Expand Up @@ -344,6 +353,7 @@ describe('useSearchBulkActions - Pay option', () => {
mockBulkPayButtonOptions = [{text: 'Pay with bank account', key: CONST.IOU.PAYMENT_TYPE.VBBA}];
mockAreAllMatchingItemsSelected = false;
mockExcludedTransactions = {};
jest.mocked(shouldRestrictUserBillableActions).mockImplementation(() => false);
await Onyx.clear();
mockSelectedTransactions = {tx1: makeSelectedTransaction()};
mockSelectedReports = [];
Expand Down Expand Up @@ -521,6 +531,29 @@ describe('useSearchBulkActions - Pay option', () => {
});
});

it('queues the Select all payment when only a report that cannot be paid is in a restricted workspace', async () => {
// Given "Select all" where report 2 cannot be paid and its workspace has billing restrictions
mockAreAllMatchingItemsSelected = true;
mockBulkPayButtonOptions = [{text: 'Mark as paid', key: CONST.IOU.PAYMENT_TYPE.ELSEWHERE}];
mockSelectedReports = [makeSelectedReport({canPay: true}), makeSelectedReport({reportID: '2', policyID: 'policy2', canPay: false, action: CONST.SEARCH.ACTION_TYPES.VIEW})];
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}policy2`, {id: 'policy2', role: CONST.POLICY.ROLE.ADMIN, ownerAccountID: RESTRICTED_POLICY_OWNER_ACCOUNT_ID});
jest.mocked(shouldRestrictUserBillableActions).mockImplementation((policy) => policy?.ownerAccountID === RESTRICTED_POLICY_OWNER_ACCOUNT_ID);

const {result} = renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider});
await waitFor(() => {
expect(getPayOptionFromResult(result.current.headerButtonsOptions)).toBeDefined();
});

// When the user selects the Pay option
await act(async () => {
await getPayOptionFromResult(result.current.headerButtonsOptions)?.onSelected?.();
});

// Then the payment is queued, because report 2 is not one that gets paid
expect(Navigation.navigate).not.toHaveBeenCalled();
expect(queueBulkPayReports).toHaveBeenCalledTimes(1);
});

it('hides the Pay option under Select all when no loaded report is payable', async () => {
// Given "Select all" where every report on the loaded page is view-only. That is the one honest signal
// the loaded page gives us that the query has nothing to pay.
Expand Down Expand Up @@ -554,9 +587,8 @@ describe('useSearchBulkActions - Pay option', () => {
expect(getPayOptionFromResult(result.current.headerButtonsOptions)).toBeUndefined();
});

it('keeps the Pay option when a held expense sits in a report that is not being paid', async () => {
// Given "Select all on this page" over a mixed page: report 1 is payable, report 2 is view-only and holds a
// held expense. Bulk pay only settles report 1, so report 2's hold must not decide the whole selection.
it('hides the Pay option when a held expense sits in any selected report', async () => {
Comment thread
allgandalf marked this conversation as resolved.
Resolved
// Given two selected reports where only the second one contains a held expense and cannot be paid
mockSelectedReports = [makeSelectedReport({reportID: '1', canPay: true}), makeSelectedReport({reportID: '2', canPay: false})];
mockSelectedTransactions = {
tx1: makeSelectedTransaction({reportID: '1'}),
Expand All @@ -566,10 +598,12 @@ describe('useSearchBulkActions - Pay option', () => {
// When the bulk actions hook computes the header dropdown options
const {result} = renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider});

// Then Pay is still offered, because the hold is scoped to the reports that will actually be paid
await waitFor(() => {
expect(getPayOptionFromResult(result.current.headerButtonsOptions)).toBeDefined();
expect(result.current.headerButtonsOptions).toBeDefined();
});

// Then Pay is hidden, the same way a held expense in any selected report hides Approve
expect(getPayOptionFromResult(result.current.headerButtonsOptions)).toBeUndefined();
});

it('hides the Pay option when a held expense sits in a report that is being paid', async () => {
Expand Down Expand Up @@ -684,43 +718,6 @@ describe('useSearchBulkActions - bulk pay chat report fallback', () => {
);
});

it('pays only the payable reports when the selection also contains one the viewer cannot settle', async () => {
// Given a selection of two reports where only the first one can be paid, e.g. the second is still awaiting approval
mockSelectedReports = [
{
reportID: '1',
policyID: 'policy1',
chatReportID: '2',
total: 100,
action: CONST.SEARCH.ACTION_TYPES.PAY,
canPay: true,
canApprove: false,
canSubmit: false,
canChangeApprover: false,
},
{
reportID: '3',
policyID: 'policy1',
chatReportID: '4',
total: 100,
action: CONST.SEARCH.ACTION_TYPES.VIEW,
canPay: false,
canApprove: false,
canSubmit: false,
canChangeApprover: false,
},
];
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}3`, {reportID: '3', type: CONST.REPORT.TYPE.EXPENSE, chatReportID: '4', policyID: 'policy1'});

// When the user selects bulk Pay
await selectBulkPay();

// Then only the payable report is paid: the ineligible one is left out of the run entirely rather than
// being paid alongside it or aborting the whole bulk payment
expect(payMoneyRequest).toHaveBeenCalledTimes(1);
expect(payMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({iouReport: expect.objectContaining({reportID: '1'})}));
});

it('skips a report when the chat is not loaded and no chatReportID is available', async () => {
// Given a payable selected expense report whose chat report is not loaded and which has no chatReportID to build a fallback from
mockSelectedReports = [
Expand Down
Loading