From 2e3b7c2e06be5659724f3ea6bbe7c8935691a4d1 Mon Sep 17 00:00:00 2001
From: Pavlo Tsimura <paultsimura@gmail.com>
Date: Fri, 27 Oct 2023 23:36:36 +0200
Subject: [PATCH] Add goBack parameter for contact-methods route

---
 src/ROUTES.ts                                       | 12 ++++++------
 src/components/ConnectBankAccountButton.js          |  2 +-
 src/components/CountrySelector.js                   |  2 +-
 src/components/MoneyRequestConfirmationList.js      |  2 +-
 src/libs/Navigation/Navigation.js                   | 13 +++++++++++--
 src/libs/Navigation/linkingConfig.js                |  2 +-
 src/libs/actions/User.js                            |  6 +++---
 src/pages/EditRequestPage.js                        |  2 +-
 src/pages/EditSplitBillPage.js                      |  2 +-
 src/pages/TeachersUnite/ImTeacherUpdateEmailPage.js |  5 +++--
 src/pages/iou/steps/NewRequestAmountPage.js         |  2 +-
 .../Profile/Contacts/ContactMethodDetailsPage.js    |  8 ++++----
 .../settings/Profile/Contacts/ContactMethodsPage.js |  3 ++-
 .../Profile/Contacts/NewContactMethodPage.js        |  2 +-
 src/pages/settings/Profile/ProfilePage.js           |  2 +-
 src/pages/workspace/WorkspaceInitialPage.js         |  2 +-
 16 files changed, 39 insertions(+), 28 deletions(-)

diff --git a/src/ROUTES.ts b/src/ROUTES.ts
index bcc4685368cb..864e8934ad88 100644
--- a/src/ROUTES.ts
+++ b/src/ROUTES.ts
@@ -2,14 +2,11 @@ import {ValueOf} from 'type-fest';
 import CONST from './CONST';
 
 /**
- * This is a file containing constants for all of the routes we want to be able to go to
+ * This is a file containing constants for all the routes we want to be able to go to
  */
 
 /**
- * This is a file containing constants for all of the routes we want to be able to go to
- * Returns the URL with an encoded URI component for the backTo param which can be added to the end of URLs
- * @param backTo
- * @returns
+ * Builds a URL with an encoded URI component for the `backTo` param which can be added to the end of URLs
  */
 function getUrlWithBackToParam(url: string, backTo?: string): string {
     const backToParam = backTo ? `${url.includes('?') ? '&' : '?'}backTo=${encodeURIComponent(backTo)}` : '';
@@ -111,7 +108,10 @@ export default {
         route: 'settings/profile/personal-details/address/country',
         getRoute: (country: string, backTo?: string) => getUrlWithBackToParam(`settings/profile/personal-details/address/country?country=${country}`, backTo),
     },
-    SETTINGS_CONTACT_METHODS: 'settings/profile/contact-methods',
+    SETTINGS_CONTACT_METHODS: {
+        route: 'settings/profile/contact-methods',
+        getRoute: (backTo?: string) => getUrlWithBackToParam('settings/profile/contact-methods', backTo),
+    },
     SETTINGS_CONTACT_METHOD_DETAILS: {
         route: 'settings/profile/contact-methods/:contactMethod/details',
         getRoute: (contactMethod: string) => `settings/profile/contact-methods/${encodeURIComponent(contactMethod)}/details`,
diff --git a/src/components/ConnectBankAccountButton.js b/src/components/ConnectBankAccountButton.js
index f5e0afe1d52e..b847cdd14c40 100644
--- a/src/components/ConnectBankAccountButton.js
+++ b/src/components/ConnectBankAccountButton.js
@@ -30,7 +30,7 @@ const defaultProps = {
 };
 
 function ConnectBankAccountButton(props) {
-    const activeRoute = Navigation.getActiveRoute().replace(/\?.*/, '');
+    const activeRoute = Navigation.getActiveRouteWithoutParams();
     return props.network.isOffline ? (
         <View style={props.style}>
             <Text>{`${props.translate('common.youAppearToBeOffline')} ${props.translate('common.thisFeatureRequiresInternet')}`}</Text>
diff --git a/src/components/CountrySelector.js b/src/components/CountrySelector.js
index 3dac127b1963..2b8f16ef8c6f 100644
--- a/src/components/CountrySelector.js
+++ b/src/components/CountrySelector.js
@@ -53,7 +53,7 @@ function CountrySelector({errorText, value: countryCode, onInputChange, forwarde
                 descriptionTextStyle={countryTitleDescStyle}
                 description={translate('common.country')}
                 onPress={() => {
-                    const activeRoute = Navigation.getActiveRoute().replace(/\?.*/, '');
+                    const activeRoute = Navigation.getActiveRouteWithoutParams();
                     Navigation.navigate(ROUTES.SETTINGS_PERSONAL_DETAILS_ADDRESS_COUNTRY.getRoute(countryCode, activeRoute));
                 }}
             />
diff --git a/src/components/MoneyRequestConfirmationList.js b/src/components/MoneyRequestConfirmationList.js
index fd3a89d14c86..06a1c367b1de 100755
--- a/src/components/MoneyRequestConfirmationList.js
+++ b/src/components/MoneyRequestConfirmationList.js
@@ -433,7 +433,7 @@ function MoneyRequestConfirmationList(props) {
      */
     const navigateToReportOrUserDetail = (option) => {
         if (option.accountID) {
-            const activeRoute = Navigation.getActiveRoute().replace(/\?.*/, '');
+            const activeRoute = Navigation.getActiveRouteWithoutParams();
 
             Navigation.navigate(ROUTES.PROFILE.getRoute(option.accountID, activeRoute));
         } else if (option.reportID) {
diff --git a/src/libs/Navigation/Navigation.js b/src/libs/Navigation/Navigation.js
index 6bbf53ffa6ea..fd62ed2b0667 100644
--- a/src/libs/Navigation/Navigation.js
+++ b/src/libs/Navigation/Navigation.js
@@ -96,8 +96,8 @@ function navigate(route = ROUTES.HOME, type) {
 
 /**
  * @param {String} fallbackRoute - Fallback route if pop/goBack action should, but is not possible within RHP
- * @param {Bool} shouldEnforceFallback - Enforces navigation to fallback route
- * @param {Bool} shouldPopToTop - Should we navigate to LHN on back press
+ * @param {Boolean} shouldEnforceFallback - Enforces navigation to fallback route
+ * @param {Boolean} shouldPopToTop - Should we navigate to LHN on back press
  */
 function goBack(fallbackRoute, shouldEnforceFallback = false, shouldPopToTop = false) {
     if (!canNavigate('goBack')) {
@@ -207,6 +207,14 @@ function getActiveRoute() {
     return '';
 }
 
+/**
+ * Returns the current active route without the URL params
+ * @returns {String}
+ */
+function getActiveRouteWithoutParams() {
+    return getActiveRoute().replace(/\?.*/, '');
+}
+
 /** Returns the active route name from a state event from the navigationRef
  * @param {Object} event
  * @returns {String | undefined}
@@ -270,6 +278,7 @@ export default {
     dismissModal,
     isActiveRoute,
     getActiveRoute,
+    getActiveRouteWithoutParams,
     goBack,
     isNavigationReady,
     setIsNavigationReady,
diff --git a/src/libs/Navigation/linkingConfig.js b/src/libs/Navigation/linkingConfig.js
index 79609f551ee4..0a8143125a6a 100644
--- a/src/libs/Navigation/linkingConfig.js
+++ b/src/libs/Navigation/linkingConfig.js
@@ -142,7 +142,7 @@ export default {
                                 exact: true,
                             },
                             Settings_ContactMethods: {
-                                path: ROUTES.SETTINGS_CONTACT_METHODS,
+                                path: ROUTES.SETTINGS_CONTACT_METHODS.route,
                                 exact: true,
                             },
                             Settings_ContactMethodDetails: {
diff --git a/src/libs/actions/User.js b/src/libs/actions/User.js
index f65c20cd7e5b..eb360c9a1777 100644
--- a/src/libs/actions/User.js
+++ b/src/libs/actions/User.js
@@ -238,7 +238,7 @@ function deleteContactMethod(contactMethod, loginList) {
         },
         {optimisticData, successData, failureData},
     );
-    Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS);
+    Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
 }
 
 /**
@@ -328,7 +328,7 @@ function addNewContactMethodAndNavigate(contactMethod) {
     ];
 
     API.write('AddNewContactMethod', {partnerUserID: contactMethod}, {optimisticData, successData, failureData});
-    Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS);
+    Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
 }
 
 /**
@@ -755,7 +755,7 @@ function setContactMethodAsDefault(newDefaultContactMethod) {
         },
     ];
     API.write('SetContactMethodAsDefault', {partnerUserID: newDefaultContactMethod}, {optimisticData, successData, failureData});
-    Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS);
+    Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
 }
 
 /**
diff --git a/src/pages/EditRequestPage.js b/src/pages/EditRequestPage.js
index eedd5bcd10d4..f46fb20ccb2b 100644
--- a/src/pages/EditRequestPage.js
+++ b/src/pages/EditRequestPage.js
@@ -184,7 +184,7 @@ function EditRequestPage({betas, report, route, parentReport, policyCategories,
                     });
                 }}
                 onNavigateToCurrency={() => {
-                    const activeRoute = encodeURIComponent(Navigation.getActiveRoute().replace(/\?.*/, ''));
+                    const activeRoute = encodeURIComponent(Navigation.getActiveRouteWithoutParams());
                     Navigation.navigate(ROUTES.EDIT_CURRENCY_REQUEST.getRoute(report.reportID, defaultCurrency, activeRoute));
                 }}
             />
diff --git a/src/pages/EditSplitBillPage.js b/src/pages/EditSplitBillPage.js
index d10803cd40ea..813be6293a0f 100644
--- a/src/pages/EditSplitBillPage.js
+++ b/src/pages/EditSplitBillPage.js
@@ -112,7 +112,7 @@ function EditSplitBillPage({route, transaction, draftTransaction}) {
                     });
                 }}
                 onNavigateToCurrency={() => {
-                    const activeRoute = encodeURIComponent(Navigation.getActiveRoute().replace(/\?.*/, ''));
+                    const activeRoute = encodeURIComponent(Navigation.getActiveRouteWithoutParams());
                     Navigation.navigate(ROUTES.EDIT_SPLIT_BILL_CURRENCY.getRoute(reportID, reportActionID, defaultCurrency, activeRoute));
                 }}
             />
diff --git a/src/pages/TeachersUnite/ImTeacherUpdateEmailPage.js b/src/pages/TeachersUnite/ImTeacherUpdateEmailPage.js
index de83c71a01c7..9dd117db7a63 100644
--- a/src/pages/TeachersUnite/ImTeacherUpdateEmailPage.js
+++ b/src/pages/TeachersUnite/ImTeacherUpdateEmailPage.js
@@ -17,6 +17,7 @@ const defaultProps = {};
 
 function ImTeacherUpdateEmailPage() {
     const {translate} = useLocalize();
+    const activeRoute = Navigation.getActiveRouteWithoutParams();
 
     return (
         <ScreenWrapper testID={ImTeacherUpdateEmailPage.displayName}>
@@ -31,7 +32,7 @@ function ImTeacherUpdateEmailPage() {
                 title={translate('teachersUnitePage.updateYourEmail')}
                 subtitle={translate('teachersUnitePage.schoolMailAsDefault')}
                 linkKey="teachersUnitePage.contactMethods"
-                onLinkPress={() => Navigation.navigate(ROUTES.SETTINGS_CONTACT_METHODS)}
+                onLinkPress={() => Navigation.navigate(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(activeRoute))}
                 iconWidth={variables.signInLogoWidthLargeScreen}
                 iconHeight={variables.lhnLogoWidth}
             />
@@ -40,7 +41,7 @@ function ImTeacherUpdateEmailPage() {
                     success
                     accessibilityLabel={translate('teachersUnitePage.updateEmail')}
                     text={translate('teachersUnitePage.updateEmail')}
-                    onPress={() => Navigation.navigate(ROUTES.SETTINGS_CONTACT_METHODS)}
+                    onPress={() => Navigation.navigate(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(activeRoute))}
                 />
             </FixedFooter>
         </ScreenWrapper>
diff --git a/src/pages/iou/steps/NewRequestAmountPage.js b/src/pages/iou/steps/NewRequestAmountPage.js
index 15a2c74d8a95..d74ba40775b3 100644
--- a/src/pages/iou/steps/NewRequestAmountPage.js
+++ b/src/pages/iou/steps/NewRequestAmountPage.js
@@ -123,7 +123,7 @@ function NewRequestAmountPage({route, iou, report, selectedTab}) {
         }
 
         // Remove query from the route and encode it.
-        const activeRoute = encodeURIComponent(Navigation.getActiveRoute().replace(/\?.*/, ''));
+        const activeRoute = encodeURIComponent(Navigation.getActiveRouteWithoutParams());
         Navigation.navigate(ROUTES.MONEY_REQUEST_CURRENCY.getRoute(iouType, reportID, currency, activeRoute));
     };
 
diff --git a/src/pages/settings/Profile/Contacts/ContactMethodDetailsPage.js b/src/pages/settings/Profile/Contacts/ContactMethodDetailsPage.js
index 1c9abcf535f6..b108cfdc6754 100644
--- a/src/pages/settings/Profile/Contacts/ContactMethodDetailsPage.js
+++ b/src/pages/settings/Profile/Contacts/ContactMethodDetailsPage.js
@@ -123,7 +123,7 @@ class ContactMethodDetailsPage extends Component {
         // Navigate to methods page on successful magic code verification
         // validatedDate property is responsible to decide the status of the magic code verification
         if (!prevValidatedDate && validatedDate) {
-            Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS);
+            Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
         }
     }
 
@@ -236,8 +236,8 @@ class ContactMethodDetailsPage extends Component {
                     <FullPageNotFoundView
                         shouldShow
                         linkKey="contacts.goBackContactMethods"
-                        onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS)}
-                        onLinkPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS)}
+                        onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route)}
+                        onLinkPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route)}
                     />
                 </ScreenWrapper>
             );
@@ -255,7 +255,7 @@ class ContactMethodDetailsPage extends Component {
             >
                 <HeaderWithBackButton
                     title={formattedContactMethod}
-                    onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS)}
+                    onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route)}
                 />
                 <ScrollView keyboardShouldPersistTaps="handled">
                     <ConfirmModal
diff --git a/src/pages/settings/Profile/Contacts/ContactMethodsPage.js b/src/pages/settings/Profile/Contacts/ContactMethodsPage.js
index c710013f9a68..06372780ba3e 100644
--- a/src/pages/settings/Profile/Contacts/ContactMethodsPage.js
+++ b/src/pages/settings/Profile/Contacts/ContactMethodsPage.js
@@ -59,6 +59,7 @@ const defaultProps = {
 
 function ContactMethodsPage(props) {
     const loginNames = _.keys(props.loginList);
+    const navigateBackTo = lodashGet(props.route, 'params.backTo', ROUTES.SETTINGS_PROFILE);
 
     // Sort the login names by placing the one corresponding to the default contact method as the first item before displaying the contact methods.
     // The default contact method is determined by checking against the session email (the current login).
@@ -116,7 +117,7 @@ function ContactMethodsPage(props) {
         >
             <HeaderWithBackButton
                 title={props.translate('contacts.contactMethods')}
-                onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_PROFILE)}
+                onBackButtonPress={() => Navigation.goBack(navigateBackTo)}
             />
             <ScrollView contentContainerStyle={styles.flexGrow1}>
                 <View style={[styles.ph5, styles.mv3, styles.flexRow, styles.flexWrap]}>
diff --git a/src/pages/settings/Profile/Contacts/NewContactMethodPage.js b/src/pages/settings/Profile/Contacts/NewContactMethodPage.js
index e6f55b7cd6cb..0cd7b1ab47bc 100644
--- a/src/pages/settings/Profile/Contacts/NewContactMethodPage.js
+++ b/src/pages/settings/Profile/Contacts/NewContactMethodPage.js
@@ -103,7 +103,7 @@ function NewContactMethodPage(props) {
         >
             <HeaderWithBackButton
                 title={props.translate('contacts.newContactMethod')}
-                onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS)}
+                onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route)}
             />
             <FormProvider
                 formID={ONYXKEYS.FORMS.NEW_CONTACT_METHOD_FORM}
diff --git a/src/pages/settings/Profile/ProfilePage.js b/src/pages/settings/Profile/ProfilePage.js
index dda3dd4f456a..b3e3affd99c2 100755
--- a/src/pages/settings/Profile/ProfilePage.js
+++ b/src/pages/settings/Profile/ProfilePage.js
@@ -79,7 +79,7 @@ function ProfilePage(props) {
         {
             description: props.translate('contacts.contactMethod'),
             title: props.formatPhoneNumber(lodashGet(currentUserDetails, 'login', '')),
-            pageRoute: ROUTES.SETTINGS_CONTACT_METHODS,
+            pageRoute: ROUTES.SETTINGS_CONTACT_METHODS.route,
             brickRoadIndicator: contactMethodBrickRoadIndicator,
         },
         ...(Permissions.canUseCustomStatus(props.betas)
diff --git a/src/pages/workspace/WorkspaceInitialPage.js b/src/pages/workspace/WorkspaceInitialPage.js
index 5c754a1ef5fb..f98469e098cd 100644
--- a/src/pages/workspace/WorkspaceInitialPage.js
+++ b/src/pages/workspace/WorkspaceInitialPage.js
@@ -173,7 +173,7 @@ function WorkspaceInitialPage(props) {
             icon: Expensicons.Bank,
             action: () =>
                 policy.outputCurrency === CONST.CURRENCY.USD
-                    ? singleExecution(waitForNavigate(() => ReimbursementAccount.navigateToBankAccountRoute(policy.id, Navigation.getActiveRoute().replace(/\?.*/, ''))))()
+                    ? singleExecution(waitForNavigate(() => ReimbursementAccount.navigateToBankAccountRoute(policy.id, Navigation.getActiveRouteWithoutParams())))()
                     : setIsCurrencyModalOpen(true),
             brickRoadIndicator: !_.isEmpty(props.reimbursementAccount.errors) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : '',
         },