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
70 changes: 56 additions & 14 deletions src/libs/actions/Policy/Policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1503,6 +1503,7 @@ function setWorkspaceReimbursement({
bankAccountList = {},
}: SetWorkspaceReimbursementActionParams) {
const lastUsedPaymentMethod = typeof lastPaymentMethod === 'string' ? lastPaymentMethod : lastPaymentMethod?.expense?.name;
const shouldClearBankAccountID = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO;

const oldBankAccountID = Object.keys(bankAccountList ?? {}).find((accountID) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ CONSISTENCY-18 (docs)

The early-return guard gained two new clauses (!shouldClearBankAccountID and reimbursementChoice === currentReimbursementChoice), but the comment directly above it only explains the original "the bank account selection is only redundant when the workspace's own bank account is selected" reasoning. The new reimbursementChoice === currentReimbursementChoice clause is non-obvious — it is specifically there so a reimbursement-choice change (e.g. switching MANUAL -> YES with the same bank) is not mistakenly skipped as a redundant bank selection, which is exactly what the new does not skip a reimbursement choice change when the bank account stays the same test covers. Without a note, the next reader cannot tell why unchanged-bank-but-changed-choice must still fall through.

Extend the comment to cover the new conditions, e.g.:

// A bank account can list the workspace in its policyIDs while the workspace itself points at another account,
// so the selection is only redundant when the workspace's own bank account is the selected one too.
// Only skip when the reimbursement choice is unchanged as well, otherwise a choice change (e.g. manual -> direct)
// with the same bank account would be dropped. Never skip when we are disabling Payments.
if (
    !shouldClearBankAccountID &&
    reimbursementChoice === currentReimbursementChoice &&
    oldBankAccountID !== undefined &&
    String(bankAccountID) === oldBankAccountID &&
    currentAchAccount?.bankAccountID === bankAccountID
) {
    return;
}

Reviewed at: eb0b7cb | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

const account = bankAccountList?.[accountID];
Expand All @@ -1511,7 +1512,7 @@ function setWorkspaceReimbursement({

// A bank account can list the workspace in its policyIDs while the workspace itself points at another account,
// so the selection is only redundant when the workspace's own bank account is the selected one too.
if (oldBankAccountID !== undefined && String(bankAccountID) === oldBankAccountID && currentAchAccount?.bankAccountID === bankAccountID) {
if (!shouldClearBankAccountID && oldBankAccountID !== undefined && String(bankAccountID) === oldBankAccountID && currentAchAccount?.bankAccountID === bankAccountID) {
return;
}

Expand All @@ -1523,14 +1524,14 @@ function setWorkspaceReimbursement({
reimbursementChoice,
isLoadingWorkspaceReimbursement: true,
reimburser: reimburserEmail,
achAccount: {reimburser: reimburserEmail, bankAccountID, accountNumber, addressName, bankName, state},
achAccount: shouldClearBankAccountID ? null : {reimburser: reimburserEmail, bankAccountID, accountNumber, addressName, bankName, state},
errorFields: {reimbursementChoice: null},
pendingFields: {reimbursementChoice: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE},
},
},
];

if (bankAccountID !== undefined && bankAccountList !== undefined) {
if (!shouldClearBankAccountID && bankAccountID !== undefined && bankAccountList !== undefined) {
const optimisticBankAccountList: NullishDeep<BankAccountList> = {};
if (oldBankAccountID) {
optimisticBankAccountList[oldBankAccountID] = {
Expand Down Expand Up @@ -1596,21 +1597,23 @@ function setWorkspaceReimbursement({
value: {
isLoadingWorkspaceReimbursement: false,
reimbursementChoice: currentReimbursementChoice ?? null,
achAccount: {
reimburser: currentAchAccount?.reimburser ?? null,
bankAccountID: currentAchAccount?.bankAccountID ?? null,
accountNumber: currentAchAccount?.accountNumber ?? null,
addressName: currentAchAccount?.addressName ?? null,
bankName: currentAchAccount?.bankName ?? null,
state: currentAchAccount?.state ?? null,
},
achAccount: shouldClearBankAccountID
? (currentAchAccount ?? null)
Comment on lines 1599 to +1601

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve queued re-enables when disable fails

When a user toggles Payments back on before an offline or slow disable request finishes—a flow explicitly exercised by the added test—the second call applies its optimistic manual/no-bank state immediately, but a failure of the first request unconditionally restores the previous reimbursement choice, ACH account, and bank associations. The later re-enable success only clears pending flags, so it never reapplies its state; the old bank therefore appears connected even though the server processed the later enable without a bank ID. Make this rollback conflict-aware or prevent another toggle while the request is pending.

AGENTS.md reference: AGENTS.md:L97-L102

Useful? React with 👍 / 👎.

: {
reimburser: currentAchAccount?.reimburser ?? null,
bankAccountID: currentAchAccount?.bankAccountID ?? null,
accountNumber: currentAchAccount?.accountNumber ?? null,
addressName: currentAchAccount?.addressName ?? null,
bankName: currentAchAccount?.bankName ?? null,
state: currentAchAccount?.state ?? null,
},
errorFields: {reimbursementChoice: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage')},
pendingFields: {reimbursementChoice: null},
},
},
];

if (bankAccountID !== undefined && bankAccountList !== undefined) {
if (!shouldClearBankAccountID && bankAccountID !== undefined && bankAccountList !== undefined) {
const failureBankAccountList: NullishDeep<BankAccountList> = {};
if (oldBankAccountID) {
failureBankAccountList[oldBankAccountID] = {
Expand All @@ -1636,7 +1639,47 @@ function setWorkspaceReimbursement({
}

// Turning payments off also stops collecting employee bank details and clears the reimbursement countries
if (reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO) {
if (shouldClearBankAccountID) {
const optimisticBankAccountList: NullishDeep<BankAccountList> = {};
const failureBankAccountList: NullishDeep<BankAccountList> = {};

// Incomplete setups can link a workspace without an ACH account or a policyIDs entry.
// Clear both association forms without detaching other workspaces that use the same account.
for (const [accountID, account] of Object.entries(bankAccountList ?? {})) {
const policyIDs = account?.accountData?.policyIDs;
const isLinkedToWorkspace = policyIDs?.includes(policyID);
const isSetupForWorkspace = account?.accountData?.additionalData?.policyID === policyID;
if (!isLinkedToWorkspace && !isSetupForWorkspace) {
continue;
}

optimisticBankAccountList[accountID] = {
accountData: {
...(isLinkedToWorkspace ? {policyIDs: policyIDs?.filter((id) => id !== policyID)} : {}),
...(isSetupForWorkspace ? {additionalData: {policyID: null}} : {}),
},
};
failureBankAccountList[accountID] = {
accountData: {
...(isLinkedToWorkspace ? {policyIDs} : {}),
...(isSetupForWorkspace ? {additionalData: {policyID}} : {}),
},
};
}

if (Object.keys(optimisticBankAccountList).length > 0) {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.BANK_ACCOUNT_LIST,
value: optimisticBankAccountList,
});
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.BANK_ACCOUNT_LIST,
value: failureBankAccountList,
});
}

optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
Expand All @@ -1652,7 +1695,6 @@ function setWorkspaceReimbursement({
});
}

const shouldClearBankAccountID = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO;
const params: SetWorkspaceReimbursementParams = {
policyID,
reimbursementChoice,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ function WorkflowsPaymentsTab({policyID}: WorkflowsPaymentsTabProps) {
addressName: policy?.achAccount?.addressName,
bankName: policy?.achAccount?.bankName,
state: policy?.achAccount?.state,
bankAccountList,
});
};

Expand Down
151 changes: 151 additions & 0 deletions tests/actions/PolicyTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {askToJoinPolicy, joinAccessiblePolicy} from '@src/libs/actions/Policy/Me
import * as Policy from '@src/libs/actions/Policy/Policy';
import ONYXKEYS from '@src/ONYXKEYS';
import type {
BankAccountList,
GovernmentMileageRate,
Onboarding,
PolicyJoinMember,
Expand Down Expand Up @@ -5722,6 +5723,9 @@ describe('actions/Policy', () => {
const FAKE_POLICY_ID = 'FAKE_POLICY';
const FAKE_REIMBURSER_EMAIL = 'admin@example.com';
const FAKE_BANK_ACCOUNT_ID = 12345;
const SHARED_BANK_ACCOUNT_ID = 23456;
const INCOMPLETE_BANK_ACCOUNT_ID = 34567;
const OTHER_BANK_ACCOUNT_ID = 45678;
const FAKE_ACCOUNT_NUMBER = '****1234';
const FAKE_ADDRESS_NAME = 'Test Bank Account';
const FAKE_BANK_NAME = 'Test Bank';
Expand Down Expand Up @@ -6031,6 +6035,153 @@ describe('actions/Policy', () => {
TestHelper.expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.SET_WORKSPACE_REIMBURSEMENT, 0);
});

it.each([true, false])('detaches workspace bank accounts before the disable request completes (has ACH account: %s)', async (hasAchAccount) => {
// Given bank accounts with both association forms, including accounts shared with another workspace
mockFetch.pause();
const otherPolicyID = 'OTHER_POLICY';
const bankAccountList = createMock<BankAccountList>({
[FAKE_BANK_ACCOUNT_ID]: {
methodID: FAKE_BANK_ACCOUNT_ID,
accountData: {
policyIDs: [FAKE_POLICY_ID, otherPolicyID],
additionalData: {policyID: FAKE_POLICY_ID, currency: CONST.CURRENCY.USD},
},
},
[SHARED_BANK_ACCOUNT_ID]: {
accountData: {policyIDs: [FAKE_POLICY_ID, otherPolicyID], additionalData: {policyID: otherPolicyID}},
},
[INCOMPLETE_BANK_ACCOUNT_ID]: {
accountData: {state: CONST.BANK_ACCOUNT.STATE.SETUP, additionalData: {policyID: FAKE_POLICY_ID}},
},
[OTHER_BANK_ACCOUNT_ID]: {
accountData: {policyIDs: [otherPolicyID], additionalData: {policyID: otherPolicyID}},
},
});
const fakePolicy = createRandomPolicy(0);
fakePolicy.id = FAKE_POLICY_ID;
fakePolicy.reimbursementChoice = CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES;
fakePolicy.achAccount = hasAchAccount
? {
bankAccountID: FAKE_BANK_ACCOUNT_ID,
accountNumber: FAKE_ACCOUNT_NUMBER,
routingNumber: '111000025',
addressName: FAKE_ADDRESS_NAME,
bankName: FAKE_BANK_NAME,
reimburser: FAKE_REIMBURSER_EMAIL,
state: FAKE_BANK_STATE,
}
: undefined;
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`, fakePolicy);
await Onyx.set(ONYXKEYS.BANK_ACCOUNT_LIST, bankAccountList);

// When Payments is disabled, the pending request must not leave a bank available for automatic reconnection
Policy.setWorkspaceReimbursement({
policyID: FAKE_POLICY_ID,
currentAchAccount: fakePolicy.achAccount,
currentReimbursementChoice: fakePolicy.reimbursementChoice,
reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO,
bankAccountID: fakePolicy.achAccount?.bankAccountID,
reimburserEmail: FAKE_REIMBURSER_EMAIL,
bankAccountList,
});
await waitForBatchedUpdates();

// Then only this workspace is detached, even when the bank is already selected or there is no ACH account
const disabledPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`);
const detachedBankAccountList = await getOnyxValue(ONYXKEYS.BANK_ACCOUNT_LIST);
expect(disabledPolicy?.reimbursementChoice).toBe(CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO);
expect(disabledPolicy?.achAccount).toBeUndefined();
expect(detachedBankAccountList?.[FAKE_BANK_ACCOUNT_ID]?.accountData).toEqual({
policyIDs: [otherPolicyID],
additionalData: {currency: CONST.CURRENCY.USD},
});
expect(detachedBankAccountList?.[SHARED_BANK_ACCOUNT_ID]?.accountData).toEqual({policyIDs: [otherPolicyID], additionalData: {policyID: otherPolicyID}});
expect(detachedBankAccountList?.[INCOMPLETE_BANK_ACCOUNT_ID]?.accountData).toEqual({state: CONST.BANK_ACCOUNT.STATE.SETUP, additionalData: {}});
expect(detachedBankAccountList?.[OTHER_BANK_ACCOUNT_ID]).toEqual(bankAccountList[OTHER_BANK_ACCOUNT_ID]);
expect(Object.keys(detachedBankAccountList ?? {})).toHaveLength(4);

// When Payments is enabled again while the disable request is still pending
Policy.setWorkspaceReimbursement({
policyID: FAKE_POLICY_ID,
currentAchAccount: disabledPolicy?.achAccount,
currentReimbursementChoice: disabledPolicy?.reimbursementChoice,
reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL,
reimburserEmail: FAKE_REIMBURSER_EMAIL,
bankAccountList: detachedBankAccountList,
});
await waitForBatchedUpdates();

// Then neither the optimistic enable nor successful responses reconnects the previous bank
expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`))?.achAccount?.bankAccountID).toBeUndefined();
expect(await getOnyxValue(ONYXKEYS.BANK_ACCOUNT_LIST)).toEqual(detachedBankAccountList);
await mockFetch.resume();
await waitForBatchedUpdates();
expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`))?.achAccount?.bankAccountID).toBeUndefined();
expect(await getOnyxValue(ONYXKEYS.BANK_ACCOUNT_LIST)).toEqual(detachedBankAccountList);
const calls = TestHelper.getFetchMockCalls(WRITE_COMMANDS.SET_WORKSPACE_REIMBURSEMENT);
expect(calls).toHaveLength(2);
const body = readProperty(requireCallArgument(calls.at(0), 1), 'body');
expect(body instanceof FormData ? body.get('bankAccountID') : undefined).toBe('0');
});

it.each([true, false])('restores bank associations and the complete ACH account after a failed disable (has ACH account: %s)', async (hasAchAccount) => {
// Given a bank with ACH fields that must survive clearing the entire connection, and an incomplete setup on another bank
mockFetch.pause();
const bankAccountList = createMock<BankAccountList>({
[FAKE_BANK_ACCOUNT_ID]: {
accountData: {policyIDs: [FAKE_POLICY_ID, 'OTHER_POLICY'], additionalData: {policyID: FAKE_POLICY_ID, currency: CONST.CURRENCY.USD}},
},
[SHARED_BANK_ACCOUNT_ID]: {accountData: {state: CONST.BANK_ACCOUNT.STATE.SETUP, additionalData: {policyID: FAKE_POLICY_ID}}},
});
const fakePolicy = createRandomPolicy(0);
fakePolicy.id = FAKE_POLICY_ID;
fakePolicy.reimbursementChoice = CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES;
fakePolicy.isCollectDepositAccountsEnabled = true;
fakePolicy.reimbursement = {countries: {US: {}}} as PolicyType['reimbursement'];
fakePolicy.achAccount = hasAchAccount
? {
bankAccountID: FAKE_BANK_ACCOUNT_ID,
accountNumber: FAKE_ACCOUNT_NUMBER,
routingNumber: '111000025',
addressName: FAKE_ADDRESS_NAME,
bankName: FAKE_BANK_NAME,
reimburser: FAKE_REIMBURSER_EMAIL,
state: FAKE_BANK_STATE,
}
: undefined;
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`, fakePolicy);
await Onyx.set(ONYXKEYS.BANK_ACCOUNT_LIST, bankAccountList);

// When the optimistic disconnect is applied and then rejected by the server
Policy.setWorkspaceReimbursement({
policyID: FAKE_POLICY_ID,
currentAchAccount: fakePolicy.achAccount,
currentReimbursementChoice: fakePolicy.reimbursementChoice,
currentIsCollectDepositAccountsEnabled: fakePolicy.isCollectDepositAccountsEnabled,
currentReimbursementCountries: fakePolicy.reimbursement?.countries,
reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO,
bankAccountID: fakePolicy.achAccount?.bankAccountID,
reimburserEmail: FAKE_REIMBURSER_EMAIL,
bankAccountList,
});
await waitForBatchedUpdates();
expect((await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`))?.achAccount).toBeUndefined();
mockFetch.fail();
await mockFetch.resume();
await waitForBatchedUpdates();

// Then rollback restores the original state, including routing details and previously absent fields
const restoredPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${FAKE_POLICY_ID}`);
expect(restoredPolicy?.achAccount).toEqual(fakePolicy.achAccount);
expect(restoredPolicy?.reimbursementChoice).toBe(fakePolicy.reimbursementChoice);
expect(restoredPolicy?.isCollectDepositAccountsEnabled).toBe(true);
expect(restoredPolicy?.reimbursement?.countries).toEqual(fakePolicy.reimbursement?.countries);
expect(restoredPolicy?.pendingFields?.reimbursementChoice).toBeFalsy();
expect(restoredPolicy?.errorFields?.reimbursementChoice).toBeDefined();
expect(await getOnyxValue(ONYXKEYS.BANK_ACCOUNT_LIST)).toEqual(bankAccountList);
mockFetch.succeed();
});

it('turns off deposit account collection and clears countries when switching to None', async () => {
mockFetch?.pause?.();

Expand Down
27 changes: 27 additions & 0 deletions tests/ui/WorkspaceWorkflowsLockedBankAccountTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,33 @@ describe('WorkspaceWorkflowsPageRevamp - bank account row', () => {
expect(mockNavigateToBankAccountRoute).toHaveBeenCalled();
});

it.each([true, false])('does not reconnect an incomplete bank account after toggling Payments off and on (offline: %s)', async (isOffline) => {
// Given an incomplete bank setup without an ACH account, so the row depends on the bank list association
await setUpIncompleteBankAccount();
setForceOffline(isOffline);
renderPage();
await waitForBatchedUpdatesWithAct();
expect(screen.getByText('Test Address')).toBeOnTheScreen();
const toggleName = TestHelper.translateLocal('workflowsPage.makeOrTrackPaymentsDescription');

// When Payments is disabled and enabled again without refreshing or relinking the bank
fireEvent.press(screen.getByRole('switch', {name: toggleName}));
await waitForBatchedUpdatesWithAct();
expect(screen.getByText(TestHelper.translateLocal('workflowsPage.disablePaymentsPrompt'))).toBeOnTheScreen();
fireEvent.press(screen.getByText(TestHelper.translateLocal('common.confirm')));
await waitForBatchedUpdatesWithAct();
expect(screen.queryByText('Test Address')).not.toBeOnTheScreen();
fireEvent.press(screen.getByRole('switch', {name: toggleName}));
await waitForBatchedUpdatesWithAct();

// Then the stale setup cannot reappear, while the account remains available for explicit relinking
expect(screen.queryByText('Test Address')).not.toBeOnTheScreen();
expect(screen.getByText(TestHelper.translateLocal('bankAccount.addBankAccount'))).toBeOnTheScreen();
const bankAccountList = await Onyx.get(ONYXKEYS.BANK_ACCOUNT_LIST);
expect(bankAccountList?.[BANK_ACCOUNT_ID]).toBeDefined();
expect(bankAccountList?.[BANK_ACCOUNT_ID]?.accountData?.additionalData?.policyID).toBeUndefined();
});

it('does not open an incomplete bank account offline, because the bank account flow needs a connection', async () => {
// Given a workspace whose bank account setup was left incomplete, and the user is offline
await setUpIncompleteBankAccount();
Expand Down
Loading