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
7 changes: 6 additions & 1 deletion src/libs/actions/BankAccounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1812,7 +1812,7 @@ function createCorpayBankAccountForWalletFlow(data: InternationalBankAccountForm
inputs: JSON.stringify(inputData),
};

const onyxData: OnyxData<typeof ONYXKEYS.REIMBURSEMENT_ACCOUNT> = {
const onyxData: OnyxData<typeof ONYXKEYS.REIMBURSEMENT_ACCOUNT | typeof ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM_DRAFT> = {
optimisticData: [
{
onyxMethod: Onyx.METHOD.MERGE,
Expand All @@ -1834,6 +1834,11 @@ function createCorpayBankAccountForWalletFlow(data: InternationalBankAccountForm
isSuccess: true,
},
},
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM_DRAFT,
value: null,
},
],
failureData: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import ScreenWrapper from '@components/ScreenWrapper';

import useAndroidBackButtonHandler from '@hooks/useAndroidBackButtonHandler';
import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
import useRootNavigationState from '@hooks/useRootNavigationState';
import useSubPage from '@hooks/useSubPage';

Expand All @@ -29,8 +30,8 @@ import {isEmptyObject} from '@src/types/utils/EmptyObject';

import type {OnyxEntry} from 'react-native-onyx';

import {useRoute} from '@react-navigation/native';
import React from 'react';
import {useIsFocused, useRoute} from '@react-navigation/native';
import React, {useEffect, useEffectEvent, useRef} from 'react';

import type CustomSubPageProps from './types';

Expand Down Expand Up @@ -140,6 +141,11 @@ function InternationalDepositAccountContent({
};

const handleBackButtonPress = () => {
if (pageIndex === CONST.CORPAY_FIELDS.INDEXES.MAPPING.SUCCESS) {
handleFinishStep();
return true;
}

if (isEditing) {
goBackToConfirmStep();
return true;
Expand All @@ -159,14 +165,32 @@ function InternationalDepositAccountContent({

useAndroidBackButtonHandler(handleBackButtonPress);

const hasMovedToSuccess = useRef(false);
Comment thread
Julesssss marked this conversation as resolved.
Resolved
const isFocused = useIsFocused();
const prevIsFocused = usePrevious(isFocused);
const leaveFlow = useEffectEvent(() => handleFinishStep());

const handleNextScreen = () => {
if (isEditing) {
goBackToConfirmStep();
return;
}
if (pageIndex === CONST.CORPAY_FIELDS.INDEXES.MAPPING.CONFIRMATION) {
hasMovedToSuccess.current = true;
}
nextPage();
};

// Each step stays mounted under the next one. Returning to a completed confirmation means
// the user went back from success, so leave the flow instead of allowing another submission.
useEffect(() => {
Comment thread
Julesssss marked this conversation as resolved.
Resolved
if (!hasMovedToSuccess.current || !isFocused || prevIsFocused) {
return;
}
hasMovedToSuccess.current = false;
leaveFlow();
Comment thread
Julesssss marked this conversation as resolved.
Resolved
}, [isFocused, prevIsFocused]);

return (
<ScreenWrapper
shouldEnableMaxHeight
Expand Down
45 changes: 45 additions & 0 deletions tests/unit/BankAccountsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import {
connectBankAccountManually,
connectBankAccountWithPlaid,
createCollectOnlyDepositAccount,
createCorpayBankAccountForWalletFlow,
deletePaymentBankAccount,
getCorpayOnboardingFields,
} from '@userActions/BankAccounts';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {InternationalBankAccountForm} from '@src/types/form';
import type {LastPaymentMethod, PersonalBankAccount} from '@src/types/onyx';
import type PlaidBankAccount from '@src/types/onyx/PlaidBankAccount';

Expand Down Expand Up @@ -186,6 +188,49 @@ describe('BankAccounts', () => {
});
});

describe('createCorpayBankAccountForWalletFlow', () => {
const draft: InternationalBankAccountForm = {bankCountry: CONST.COUNTRY.GB, bankCurrency: CONST.CURRENCY.GBP, acceptTerms: 'true'};

beforeAll(() => Onyx.init({keys: ONYXKEYS}));

beforeEach(async () => {
await Onyx.set(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM_DRAFT, draft);
});

afterEach(() => Onyx.clear());

test('clears the completed draft after successful creation without waiting for the success screen to finish', async () => {
// Given a retained international draft that could otherwise reopen at confirmation
createCorpayBankAccountForWalletFlow(draft, 'individual', CONST.COUNTRY.GB, 'wire');
const [, , onyxData] = mockWrite.mock.calls.at(-1) ?? [];

// When the API applies the successful creation updates, even without a mounted confirmation
await Onyx.update(onyxData?.successData ?? []);
await waitForBatchedUpdates();

// Then the draft is removed and the normal success state is preserved
expect(await getOnyxValue(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM_DRAFT)).toBeUndefined();
expect(await getOnyxValue(ONYXKEYS.REIMBURSEMENT_ACCOUNT)).toEqual(expect.objectContaining({isSuccess: true, isLoading: false}));
});

test('preserves the draft while creation is pending and after failure so it can be retried', async () => {
// Given a filled draft submitted for creation
createCorpayBankAccountForWalletFlow(draft, 'individual', CONST.COUNTRY.GB, 'wire');
const [, , onyxData] = mockWrite.mock.calls.at(-1) ?? [];

// When optimistic updates are applied while the request is pending
await Onyx.update(onyxData?.optimisticData ?? []);
await waitForBatchedUpdates();

// Then the draft remains available, including after failure updates are applied
expect(await getOnyxValue(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM_DRAFT)).toEqual(draft);
await Onyx.update(onyxData?.failureData ?? []);
await waitForBatchedUpdates();
expect(await getOnyxValue(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM_DRAFT)).toEqual(draft);
expect(await getOnyxValue(ONYXKEYS.REIMBURSEMENT_ACCOUNT)).toEqual(expect.objectContaining({isSuccess: false, isLoading: false}));
});
});

describe('deletePaymentBankAccount', () => {
const deletedBankAccountID = 123;
const replacementBankAccountID = 456;
Expand Down
185 changes: 185 additions & 0 deletions tests/unit/pages/InternationalDepositAccountContentTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import {act, render} from '@testing-library/react-native';

import ComposeProviders from '@components/ComposeProviders';
import {LocaleContextProvider} from '@components/LocaleContextProvider';
import OnyxListItemProvider from '@components/OnyxListItemProvider';

import useAndroidBackButtonHandler from '@hooks/useAndroidBackButtonHandler';
import useRootNavigationState from '@hooks/useRootNavigationState';
import useSubPage from '@hooks/useSubPage';
import type {SubPageProps} from '@hooks/useSubPage/types';

import {clearCorpayBankAccountFields} from '@libs/actions/BankAccounts';
import {clearDraftValues} from '@libs/actions/FormActions';
import Navigation from '@libs/Navigation/Navigation';
import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator';
import type {SettingsNavigatorParamList} from '@libs/Navigation/types';

import InternationalDepositAccountContent from '@pages/settings/Wallet/InternationalDepositAccount/InternationalDepositAccountContent';

import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';

import {PortalProvider} from '@gorhom/portal';
import {NavigationContainer, useIsFocused, useRoute} from '@react-navigation/native';
import React from 'react';
import Onyx from 'react-native-onyx';

import createMock from '../../utils/createMock';

jest.mock('@hooks/useAndroidBackButtonHandler', () => jest.fn());
jest.mock('@hooks/useRootNavigationState', () => jest.fn());
jest.mock('@hooks/useSubPage', () => jest.fn());
jest.mock('@react-navigation/native', () => ({
...jest.requireActual<Record<string, unknown>>('@react-navigation/native'),
useIsFocused: jest.fn(),
useRoute: jest.fn(),
}));
jest.mock('@libs/actions/BankAccounts', () => ({clearCorpayBankAccountFields: jest.fn()}));
jest.mock('@libs/actions/FormActions', () => ({
...jest.requireActual<Record<string, unknown>>('@libs/actions/FormActions'),
clearDraftValues: jest.fn(),
}));

const mockStep = jest.fn<null, [SubPageProps]>(() => null);
const nextPage = jest.fn();
const prevPage = jest.fn();
const goBackSpy = jest.spyOn(Navigation, 'goBack').mockImplementation(() => {});
const Stack = createPlatformStackNavigator<SettingsNavigatorParamList>();

function TestFlow() {
return (
<ComposeProviders components={[OnyxListItemProvider, LocaleContextProvider]}>
<PortalProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name={SCREENS.SETTINGS.ADD_BANK_ACCOUNT}>
{() => (
<InternationalDepositAccountContent
privatePersonalDetails={undefined}
corpayFields={undefined}
bankAccountList={undefined}
draftValues={undefined}
country={CONST.COUNTRY.GB}
isAccountLoading={false}
/>
)}
</Stack.Screen>
</Stack.Navigator>
</NavigationContainer>
</PortalProvider>
</ComposeProviders>
);
}

function configureStep(pageIndex: number = CONST.CORPAY_FIELDS.INDEXES.MAPPING.CONFIRMATION, isEditing = false) {
jest.mocked(useSubPage).mockReturnValue(createMock<ReturnType<typeof useSubPage>>({CurrentPage: mockStep, nextPage, prevPage, pageIndex, isEditing, isRedirecting: false}));
}

describe('InternationalDepositAccountContent completion navigation', () => {
beforeAll(() => Onyx.init({keys: ONYXKEYS}));

beforeEach(() => {
jest.clearAllMocks();
jest.mocked(useIsFocused).mockReturnValue(true);
jest.mocked(useRoute).mockReturnValue({key: 'bank-account', name: 'bank-account'});
jest.mocked(useRootNavigationState).mockReturnValue({name: NAVIGATORS.SETTINGS_SPLIT_NAVIGATOR});
configureStep();
});

it('exits when the completed confirmation regains focus without advancing again', () => {
// Given confirmation advanced after a successful creation, not merely after pressing Confirm
const {rerender} = render(<TestFlow />);
act(() => mockStep.mock.lastCall?.[0].onNext());
expect(nextPage).toHaveBeenCalledTimes(1);
expect(goBackSpy).not.toHaveBeenCalled();

// When success covers confirmation and browser Back restores its focus
jest.mocked(useIsFocused).mockReturnValue(false);
rerender(<TestFlow />);
jest.mocked(useIsFocused).mockReturnValue(true);
rerender(<TestFlow />);

// Then the existing finish path clears the draft and exits rather than opening success again
expect(goBackSpy).toHaveBeenCalledTimes(1);
expect(goBackSpy).toHaveBeenCalledWith(ROUTES.SETTINGS_WALLET);
expect(clearDraftValues).toHaveBeenCalledWith(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM);
expect(clearCorpayBankAccountFields).toHaveBeenCalledTimes(1);
expect(nextPage).toHaveBeenCalledTimes(1);
});

it('exits when confirmation loses focus before creation succeeds and then regains focus', () => {
// Given confirmation was covered by an edit while its creation request was still pending
const {rerender} = render(<TestFlow />);
jest.mocked(useIsFocused).mockReturnValue(false);
rerender(<TestFlow />);

// When creation succeeds while confirmation is unfocused, then confirmation regains focus
act(() => mockStep.mock.lastCall?.[0].onNext());
expect(goBackSpy).not.toHaveBeenCalled();
jest.mocked(useIsFocused).mockReturnValue(true);
rerender(<TestFlow />);

// Then the completed flow exits rather than allowing the same account to be submitted again
expect(goBackSpy).toHaveBeenCalledTimes(1);
expect(goBackSpy).toHaveBeenCalledWith(ROUTES.SETTINGS_WALLET);
expect(clearDraftValues).toHaveBeenCalledWith(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM);
expect(nextPage).toHaveBeenCalledTimes(1);
});

it('does not exit an unfinished confirmation when it regains focus', () => {
// Given confirmation has not advanced, including when a creation request fails
const {rerender} = render(<TestFlow />);

// When an edit or another screen covers it and the user comes back
jest.mocked(useIsFocused).mockReturnValue(false);
rerender(<TestFlow />);
jest.mocked(useIsFocused).mockReturnValue(true);
rerender(<TestFlow />);

// Then its draft is retained and the flow is not exited
expect(goBackSpy).not.toHaveBeenCalled();
expect(clearDraftValues).not.toHaveBeenCalled();
expect(clearCorpayBankAccountFields).not.toHaveBeenCalled();
});

it('does not mark an edit return as a successful submission', () => {
// Given an edited bank-details step that returns to confirmation without creating an account
configureStep(CONST.CORPAY_FIELDS.INDEXES.MAPPING.BANK_ACCOUNT_DETAILS, true);
const {rerender} = render(<TestFlow />);

// When the edit is saved and that screen later regains focus
act(() => mockStep.mock.lastCall?.[0].onNext());
jest.mocked(useIsFocused).mockReturnValue(false);
rerender(<TestFlow />);
jest.mocked(useIsFocused).mockReturnValue(true);
rerender(<TestFlow />);

// Then only the normal edit return happens, without completed-account cleanup
expect(goBackSpy).toHaveBeenCalledTimes(1);
expect(goBackSpy).toHaveBeenCalledWith(ROUTES.SETTINGS_ADD_BANK_ACCOUNT.getRoute(undefined, CONST.CORPAY_FIELDS.PAGE_NAME.CONFIRM));
expect(clearDraftValues).not.toHaveBeenCalled();
expect(nextPage).not.toHaveBeenCalled();
});

it('exits on Android Back from success instead of returning to confirmation', () => {
// Given the success screen for an account that has already been created
configureStep(CONST.CORPAY_FIELDS.INDEXES.MAPPING.SUCCESS);
render(<TestFlow />);

// When its registered Android back callback runs
let wasHandled: boolean | undefined;
act(() => {
wasHandled = jest.mocked(useAndroidBackButtonHandler).mock.lastCall?.[0]();
});

// Then the whole flow is finished and no previous wizard step is opened
expect(wasHandled).toBe(true);
expect(goBackSpy).toHaveBeenCalledWith(ROUTES.SETTINGS_WALLET);
expect(clearDraftValues).toHaveBeenCalledWith(ONYXKEYS.FORMS.INTERNATIONAL_BANK_ACCOUNT_FORM);
expect(prevPage).not.toHaveBeenCalled();
});
});
Loading