-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
ContactMethodDetailsPage.tsx
273 lines (246 loc) · 13.2 KB
/
ContactMethodDetailsPage.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type {StackScreenProps} from '@react-navigation/stack';
import {Str} from 'expensify-common';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {InteractionManager, Keyboard, View} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import ConfirmModal from '@components/ConfirmModal';
import DotIndicatorMessage from '@components/DotIndicatorMessage';
import FullscreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import * as Expensicons from '@components/Icon/Expensicons';
import MenuItem from '@components/MenuItem';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import Text from '@components/Text';
import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import {canUseTouchScreen} from '@libs/DeviceCapabilities';
import * as ErrorUtils from '@libs/ErrorUtils';
import Navigation from '@libs/Navigation/Navigation';
import type {SettingsNavigatorParamList} from '@libs/Navigation/types';
import * as User from '@userActions/User';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type SCREENS from '@src/SCREENS';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';
import ValidateCodeForm from './ValidateCodeForm';
import type {ValidateCodeFormHandle} from './ValidateCodeForm/BaseValidateCodeForm';
type ContactMethodDetailsPageProps = StackScreenProps<SettingsNavigatorParamList, typeof SCREENS.SETTINGS.PROFILE.CONTACT_METHOD_DETAILS>;
function ContactMethodDetailsPage({route}: ContactMethodDetailsPageProps) {
const [loginList, loginListResult] = useOnyx(ONYXKEYS.LOGIN_LIST);
const [session, sessionResult] = useOnyx(ONYXKEYS.SESSION);
const [myDomainSecurityGroups, myDomainSecurityGroupsResult] = useOnyx(ONYXKEYS.MY_DOMAIN_SECURITY_GROUPS);
const [securityGroups, securityGroupsResult] = useOnyx(ONYXKEYS.COLLECTION.SECURITY_GROUP);
const [isLoadingReportData, isLoadingReportDataResult] = useOnyx(ONYXKEYS.IS_LOADING_REPORT_DATA, {initialValue: true});
const isLoadingOnyxValues = isLoadingOnyxValue(loginListResult, sessionResult, myDomainSecurityGroupsResult, securityGroupsResult, isLoadingReportDataResult);
const {formatPhoneNumber, translate} = useLocalize();
const theme = useTheme();
const themeStyles = useThemeStyles();
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const validateCodeFormRef = useRef<ValidateCodeFormHandle>(null);
const backTo = route.params.backTo;
/**
* Gets the current contact method from the route params
*/
const contactMethod: string = useMemo(() => {
const contactMethodParam = route.params.contactMethod;
// We find the number of times the url is encoded based on the last % sign and remove them.
const lastPercentIndex = contactMethodParam.lastIndexOf('%');
const encodePercents = contactMethodParam.substring(lastPercentIndex).match(new RegExp('25', 'g'));
let numberEncodePercents = encodePercents?.length ?? 0;
const beforeAtSign = contactMethodParam.substring(0, lastPercentIndex).replace(CONST.REGEX.ENCODE_PERCENT_CHARACTER, (match) => {
if (numberEncodePercents > 0) {
numberEncodePercents--;
return '%';
}
return match;
});
const afterAtSign = contactMethodParam.substring(lastPercentIndex).replace(CONST.REGEX.ENCODE_PERCENT_CHARACTER, '%');
return decodeURIComponent(beforeAtSign + afterAtSign);
}, [route.params.contactMethod]);
const loginData = useMemo(() => loginList?.[contactMethod], [loginList, contactMethod]);
const isDefaultContactMethod = useMemo(() => session?.email === loginData?.partnerUserID, [session?.email, loginData?.partnerUserID]);
/**
* Attempt to set this contact method as user's "Default contact method"
*/
const setAsDefault = useCallback(() => {
User.setContactMethodAsDefault(contactMethod, backTo);
}, [contactMethod, backTo]);
/**
* Checks if the user is allowed to change their default contact method. This should only be allowed if:
* 1. The viewed contact method is not already their default contact method
* 2. The viewed contact method is validated
* 3. If the user is on a private domain, their security group must allow primary login switching
*/
const canChangeDefaultContactMethod = useMemo(() => {
// Cannot set this contact method as default if:
// 1. This contact method is already their default
// 2. This contact method is not validated
if (isDefaultContactMethod || !loginData?.validatedDate) {
return false;
}
const domainName = Str.extractEmailDomain(session?.email ?? '');
const primaryDomainSecurityGroupID = myDomainSecurityGroups?.[domainName];
// If there's no security group associated with the user for the primary domain,
// default to allowing the user to change their default contact method.
if (!primaryDomainSecurityGroupID) {
return true;
}
// Allow user to change their default contact method if they don't have a security group OR if their security group
// does NOT restrict primary login switching.
return !securityGroups?.[`${ONYXKEYS.COLLECTION.SECURITY_GROUP}${primaryDomainSecurityGroupID}`]?.hasRestrictedPrimaryLogin;
}, [isDefaultContactMethod, loginData?.validatedDate, session?.email, myDomainSecurityGroups, securityGroups]);
/**
* Toggle delete confirm modal visibility
*/
const toggleDeleteModal = useCallback((isOpen: boolean) => {
if (canUseTouchScreen() && isOpen) {
InteractionManager.runAfterInteractions(() => {
setIsDeleteModalOpen(isOpen);
});
Keyboard.dismiss();
} else {
setIsDeleteModalOpen(isOpen);
}
}, []);
/**
* Delete the contact method and hide the modal
*/
const confirmDeleteAndHideModal = useCallback(() => {
toggleDeleteModal(false);
User.deleteContactMethod(contactMethod, loginList ?? {}, backTo);
}, [contactMethod, loginList, toggleDeleteModal, backTo]);
useEffect(() => {
if (isEmptyObject(loginData)) {
return;
}
User.resetContactMethodValidateCodeSentState(contactMethod);
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, []);
const prevValidatedDate = usePrevious(loginData?.validatedDate);
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
if (prevValidatedDate || !loginData?.validatedDate) {
return;
}
// Navigate to methods page on successful magic code verification
// validatedDate property is responsible to decide the status of the magic code verification
Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo));
}, [prevValidatedDate, loginData?.validatedDate, isDefaultContactMethod, backTo]);
if (isLoadingOnyxValues || (isLoadingReportData && isEmptyObject(loginList))) {
return <FullscreenLoadingIndicator />;
}
if (!contactMethod || !loginData) {
return (
<ScreenWrapper testID={ContactMethodDetailsPage.displayName}>
<FullPageNotFoundView
shouldShow
linkKey="contacts.goBackContactMethods"
onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo))}
onLinkPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo))}
/>
</ScreenWrapper>
);
}
// Replacing spaces with "hard spaces" to prevent breaking the number
const formattedContactMethod = Str.isSMSLogin(contactMethod) ? formatPhoneNumber(contactMethod) : contactMethod;
const hasMagicCodeBeenSent = !!loginData.validateCodeSent;
const isFailedAddContactMethod = !!loginData.errorFields?.addedLogin;
const isFailedRemovedContactMethod = !!loginData.errorFields?.deletedLogin;
return (
<ScreenWrapper
onEntryTransitionEnd={() => validateCodeFormRef.current?.focus?.()}
testID={ContactMethodDetailsPage.displayName}
>
<HeaderWithBackButton
title={formattedContactMethod}
onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo))}
/>
<ScrollView keyboardShouldPersistTaps="handled">
<ConfirmModal
title={translate('contacts.removeContactMethod')}
onConfirm={confirmDeleteAndHideModal}
onCancel={() => toggleDeleteModal(false)}
onModalHide={() => {
InteractionManager.runAfterInteractions(() => {
validateCodeFormRef.current?.focusLastSelected?.();
});
}}
prompt={translate('contacts.removeAreYouSure')}
confirmText={translate('common.yesContinue')}
cancelText={translate('common.cancel')}
isVisible={isDeleteModalOpen && !isDefaultContactMethod}
danger
/>
{isFailedAddContactMethod && (
<DotIndicatorMessage
style={[themeStyles.mh5, themeStyles.mv3]}
messages={ErrorUtils.getLatestErrorField(loginData, 'addedLogin')}
type="error"
/>
)}
{!loginData.validatedDate && !isFailedAddContactMethod && (
<View style={[themeStyles.ph5, themeStyles.mt3, themeStyles.mb7]}>
<DotIndicatorMessage
type="success"
style={[themeStyles.mb3]}
// eslint-disable-next-line @typescript-eslint/naming-convention
messages={{0: translate('contacts.enterMagicCode', {contactMethod: formattedContactMethod})}}
/>
<ValidateCodeForm
contactMethod={contactMethod}
hasMagicCodeBeenSent={hasMagicCodeBeenSent}
loginList={loginList ?? {}}
ref={validateCodeFormRef}
/>
</View>
)}
{canChangeDefaultContactMethod ? (
<OfflineWithFeedback
errors={ErrorUtils.getLatestErrorField(loginData, 'defaultLogin')}
errorRowStyles={[themeStyles.ml8, themeStyles.mr5]}
onClose={() => User.clearContactMethodErrors(contactMethod, 'defaultLogin')}
>
<MenuItem
title={translate('contacts.setAsDefault')}
icon={Expensicons.Profile}
onPress={setAsDefault}
/>
</OfflineWithFeedback>
) : null}
{isDefaultContactMethod ? (
<OfflineWithFeedback
pendingAction={loginData.pendingFields?.defaultLogin}
errors={ErrorUtils.getLatestErrorField(loginData, isFailedRemovedContactMethod ? 'deletedLogin' : 'defaultLogin')}
errorRowStyles={[themeStyles.ml8, themeStyles.mr5]}
onClose={() => User.clearContactMethodErrors(contactMethod, isFailedRemovedContactMethod ? 'deletedLogin' : 'defaultLogin')}
>
<Text style={[themeStyles.ph5, themeStyles.mv3]}>{translate('contacts.yourDefaultContactMethod')}</Text>
</OfflineWithFeedback>
) : (
<OfflineWithFeedback
pendingAction={loginData.pendingFields?.deletedLogin}
errors={ErrorUtils.getLatestErrorField(loginData, 'deletedLogin')}
errorRowStyles={[themeStyles.mt6, themeStyles.ph5]}
onClose={() => User.clearContactMethodErrors(contactMethod, 'deletedLogin')}
>
<MenuItem
title={translate('common.remove')}
icon={Expensicons.Trashcan}
iconFill={theme.danger}
onPress={() => toggleDeleteModal(true)}
/>
</OfflineWithFeedback>
)}
</ScrollView>
</ScreenWrapper>
);
}
ContactMethodDetailsPage.displayName = 'ContactMethodDetailsPage';
export default ContactMethodDetailsPage;