diff --git a/src/libs/actions/BankAccounts.ts b/src/libs/actions/BankAccounts.ts index 10d712a3b185..ffb4ace5373b 100644 --- a/src/libs/actions/BankAccounts.ts +++ b/src/libs/actions/BankAccounts.ts @@ -1812,7 +1812,7 @@ function createCorpayBankAccountForWalletFlow(data: InternationalBankAccountForm inputs: JSON.stringify(inputData), }; - const onyxData: OnyxData = { + const onyxData: OnyxData = { optimisticData: [ { onyxMethod: Onyx.METHOD.MERGE, @@ -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: [ { diff --git a/src/pages/settings/Wallet/InternationalDepositAccount/InternationalDepositAccountContent.tsx b/src/pages/settings/Wallet/InternationalDepositAccount/InternationalDepositAccountContent.tsx index 2b4485eb2159..230eed4c194c 100644 --- a/src/pages/settings/Wallet/InternationalDepositAccount/InternationalDepositAccountContent.tsx +++ b/src/pages/settings/Wallet/InternationalDepositAccount/InternationalDepositAccountContent.tsx @@ -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'; @@ -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'; @@ -140,6 +141,11 @@ function InternationalDepositAccountContent({ }; const handleBackButtonPress = () => { + if (pageIndex === CONST.CORPAY_FIELDS.INDEXES.MAPPING.SUCCESS) { + handleFinishStep(); + return true; + } + if (isEditing) { goBackToConfirmStep(); return true; @@ -159,14 +165,32 @@ function InternationalDepositAccountContent({ useAndroidBackButtonHandler(handleBackButtonPress); + const hasMovedToSuccess = useRef(false); + 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(() => { + if (!hasMovedToSuccess.current || !isFocused || prevIsFocused) { + return; + } + hasMovedToSuccess.current = false; + leaveFlow(); + }, [isFocused, prevIsFocused]); + return ( { }); }); + 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; diff --git a/tests/unit/pages/InternationalDepositAccountContentTest.tsx b/tests/unit/pages/InternationalDepositAccountContentTest.tsx new file mode 100644 index 000000000000..d172c3ec16ad --- /dev/null +++ b/tests/unit/pages/InternationalDepositAccountContentTest.tsx @@ -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>('@react-navigation/native'), + useIsFocused: jest.fn(), + useRoute: jest.fn(), +})); +jest.mock('@libs/actions/BankAccounts', () => ({clearCorpayBankAccountFields: jest.fn()})); +jest.mock('@libs/actions/FormActions', () => ({ + ...jest.requireActual>('@libs/actions/FormActions'), + clearDraftValues: jest.fn(), +})); + +const mockStep = jest.fn(() => null); +const nextPage = jest.fn(); +const prevPage = jest.fn(); +const goBackSpy = jest.spyOn(Navigation, 'goBack').mockImplementation(() => {}); +const Stack = createPlatformStackNavigator(); + +function TestFlow() { + return ( + + + + + + {() => ( + + )} + + + + + + ); +} + +function configureStep(pageIndex: number = CONST.CORPAY_FIELDS.INDEXES.MAPPING.CONFIRMATION, isEditing = false) { + jest.mocked(useSubPage).mockReturnValue(createMock>({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(); + 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(); + jest.mocked(useIsFocused).mockReturnValue(true); + rerender(); + + // 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(); + jest.mocked(useIsFocused).mockReturnValue(false); + rerender(); + + // 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(); + + // 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(); + + // When an edit or another screen covers it and the user comes back + jest.mocked(useIsFocused).mockReturnValue(false); + rerender(); + jest.mocked(useIsFocused).mockReturnValue(true); + rerender(); + + // 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(); + + // When the edit is saved and that screen later regains focus + act(() => mockStep.mock.lastCall?.[0].onNext()); + jest.mocked(useIsFocused).mockReturnValue(false); + rerender(); + jest.mocked(useIsFocused).mockReturnValue(true); + rerender(); + + // 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(); + + // 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(); + }); +});