-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
WorkspaceInvitePage.tsx
354 lines (308 loc) · 16 KB
/
WorkspaceInvitePage.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import type {StackScreenProps} from '@react-navigation/stack';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import type {SectionListData} from 'react-native';
import {useOnyx, withOnyx} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import FormAlertWithSubmitButton from '@components/FormAlertWithSubmitButton';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import {useOptionsList} from '@components/OptionListContextProvider';
import ScreenWrapper from '@components/ScreenWrapper';
import SelectionList from '@components/SelectionList';
import InviteMemberListItem from '@components/SelectionList/InviteMemberListItem';
import type {Section} from '@components/SelectionList/types';
import withNavigationTransitionEnd from '@components/withNavigationTransitionEnd';
import type {WithNavigationTransitionEndProps} from '@components/withNavigationTransitionEnd';
import useDebouncedState from '@hooks/useDebouncedState';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useThemeStyles from '@hooks/useThemeStyles';
import * as ReportActions from '@libs/actions/Report';
import {READ_COMMANDS} from '@libs/API/types';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import HttpUtils from '@libs/HttpUtils';
import * as LoginUtils from '@libs/LoginUtils';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import type {MemberForList} from '@libs/OptionsListUtils';
import * as PhoneNumber from '@libs/PhoneNumber';
import * as PolicyUtils from '@libs/PolicyUtils';
import type {OptionData} from '@libs/ReportUtils';
import type {SettingsNavigatorParamList} from '@navigation/types';
import * as Member from '@userActions/Policy/Member';
import * as Policy from '@userActions/Policy/Policy';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type SCREENS from '@src/SCREENS';
import type {Beta, InvitedEmailsToAccountIDs} from '@src/types/onyx';
import type {Errors} from '@src/types/onyx/OnyxCommon';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import AccessOrNotFoundWrapper from './AccessOrNotFoundWrapper';
import SearchInputManager from './SearchInputManager';
import withPolicyAndFullscreenLoading from './withPolicyAndFullscreenLoading';
import type {WithPolicyAndFullscreenLoadingProps} from './withPolicyAndFullscreenLoading';
type MembersSection = SectionListData<MemberForList, Section<MemberForList>>;
type WorkspaceInvitePageOnyxProps = {
/** Beta features list */
betas: OnyxEntry<Beta[]>;
/** An object containing the accountID for every invited user email */
invitedEmailsToAccountIDsDraft: OnyxEntry<InvitedEmailsToAccountIDs>;
};
type WorkspaceInvitePageProps = WithPolicyAndFullscreenLoadingProps &
WithNavigationTransitionEndProps &
WorkspaceInvitePageOnyxProps &
StackScreenProps<SettingsNavigatorParamList, typeof SCREENS.WORKSPACE.INVITE>;
function WorkspaceInvitePage({route, betas, invitedEmailsToAccountIDsDraft, policy}: WorkspaceInvitePageProps) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const [searchTerm, debouncedSearchTerm, setSearchTerm] = useDebouncedState('');
const [selectedOptions, setSelectedOptions] = useState<MemberForList[]>([]);
const [personalDetails, setPersonalDetails] = useState<OptionData[]>([]);
const [usersToInvite, setUsersToInvite] = useState<OptionData[]>([]);
const [didScreenTransitionEnd, setDidScreenTransitionEnd] = useState(false);
const [isSearchingForReports] = useOnyx(ONYXKEYS.IS_SEARCHING_FOR_REPORTS, {initWithStoredValues: false});
const firstRenderRef = useRef(true);
const openWorkspaceInvitePage = () => {
const policyMemberEmailsToAccountIDs = PolicyUtils.getMemberAccountIDsForWorkspace(policy?.employeeList);
Policy.openWorkspaceInvitePage(route.params.policyID, Object.keys(policyMemberEmailsToAccountIDs));
};
const {options, areOptionsInitialized} = useOptionsList({
shouldInitialize: didScreenTransitionEnd,
});
useEffect(() => {
setSearchTerm(SearchInputManager.searchInput);
return () => {
Member.setWorkspaceInviteMembersDraft(route.params.policyID, {});
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [route.params.policyID]);
useEffect(() => {
Policy.clearErrors(route.params.policyID);
openWorkspaceInvitePage();
// eslint-disable-next-line react-hooks/exhaustive-deps -- policyID changes remount the component
}, []);
useNetwork({onReconnect: openWorkspaceInvitePage});
const excludedUsers = useMemo(() => PolicyUtils.getIneligibleInvitees(policy?.employeeList), [policy?.employeeList]);
useEffect(() => {
const newUsersToInviteDict: Record<number, OptionData> = {};
const newPersonalDetailsDict: Record<number, OptionData> = {};
const newSelectedOptionsDict: Record<number, MemberForList> = {};
const inviteOptions = OptionsListUtils.getMemberInviteOptions(options.personalDetails, betas ?? [], debouncedSearchTerm, excludedUsers, true);
// Update selectedOptions with the latest personalDetails and policyEmployeeList information
const detailsMap: Record<string, MemberForList> = {};
inviteOptions.personalDetails.forEach((detail) => {
if (!detail.login) {
return;
}
detailsMap[detail.login] = OptionsListUtils.formatMemberForList(detail);
});
const newSelectedOptions: MemberForList[] = [];
if (firstRenderRef.current) {
// We only want to add the saved selected user on first render
firstRenderRef.current = false;
Object.keys(invitedEmailsToAccountIDsDraft ?? {}).forEach((login) => {
if (!(login in detailsMap)) {
return;
}
newSelectedOptions.push({...detailsMap[login], isSelected: true});
});
}
selectedOptions.forEach((option) => {
newSelectedOptions.push(option.login && option.login in detailsMap ? {...detailsMap[option.login], isSelected: true} : option);
});
const userToInvite = inviteOptions.userToInvite;
// Only add the user to the invites list if it is valid
if (typeof userToInvite?.accountID === 'number') {
newUsersToInviteDict[userToInvite.accountID] = userToInvite;
}
// Add all personal details to the new dict
inviteOptions.personalDetails.forEach((details) => {
if (typeof details.accountID !== 'number') {
return;
}
newPersonalDetailsDict[details.accountID] = details;
});
// Add all selected options to the new dict
newSelectedOptions.forEach((option) => {
if (typeof option.accountID !== 'number') {
return;
}
newSelectedOptionsDict[option.accountID] = option;
});
// Strip out dictionary keys and update arrays
setUsersToInvite(Object.values(newUsersToInviteDict));
setPersonalDetails(Object.values(newPersonalDetailsDict));
setSelectedOptions(Object.values(newSelectedOptionsDict));
// eslint-disable-next-line react-hooks/exhaustive-deps -- we don't want to recalculate when selectedOptions change
}, [options.personalDetails, policy?.employeeList, betas, debouncedSearchTerm, excludedUsers]);
const sections: MembersSection[] = useMemo(() => {
const sectionsArr: MembersSection[] = [];
if (!areOptionsInitialized) {
return [];
}
// Filter all options that is a part of the search term or in the personal details
let filterSelectedOptions = selectedOptions;
if (debouncedSearchTerm !== '') {
filterSelectedOptions = selectedOptions.filter((option) => {
const accountID = option.accountID;
const isOptionInPersonalDetails = Object.values(personalDetails).some((personalDetail) => personalDetail.accountID === accountID);
const searchValue = OptionsListUtils.getSearchValueForPhoneOrEmail(debouncedSearchTerm);
const isPartOfSearchTerm = !!option.text?.toLowerCase().includes(searchValue) || !!option.login?.toLowerCase().includes(searchValue);
return isPartOfSearchTerm || isOptionInPersonalDetails;
});
}
sectionsArr.push({
title: undefined,
data: filterSelectedOptions,
shouldShow: true,
});
// Filtering out selected users from the search results
const selectedLogins = selectedOptions.map(({login}) => login);
const personalDetailsWithoutSelected = Object.values(personalDetails).filter(({login}) => !selectedLogins.some((selectedLogin) => selectedLogin === login));
const personalDetailsFormatted = personalDetailsWithoutSelected.map((item) => OptionsListUtils.formatMemberForList(item));
sectionsArr.push({
title: translate('common.contacts'),
data: personalDetailsFormatted,
shouldShow: !isEmptyObject(personalDetailsFormatted),
});
Object.values(usersToInvite).forEach((userToInvite) => {
const hasUnselectedUserToInvite = !selectedLogins.some((selectedLogin) => selectedLogin === userToInvite.login);
if (hasUnselectedUserToInvite) {
sectionsArr.push({
title: undefined,
data: [OptionsListUtils.formatMemberForList(userToInvite)],
shouldShow: true,
});
}
});
return sectionsArr;
}, [areOptionsInitialized, selectedOptions, debouncedSearchTerm, personalDetails, translate, usersToInvite]);
const toggleOption = (option: MemberForList) => {
Policy.clearErrors(route.params.policyID);
const isOptionInList = selectedOptions.some((selectedOption) => selectedOption.login === option.login);
let newSelectedOptions: MemberForList[];
if (isOptionInList) {
newSelectedOptions = selectedOptions.filter((selectedOption) => selectedOption.login !== option.login);
} else {
newSelectedOptions = [...selectedOptions, {...option, isSelected: true}];
}
setSelectedOptions(newSelectedOptions);
};
const inviteUser = useCallback(() => {
const errors: Errors = {};
if (selectedOptions.length <= 0) {
errors.noUserSelected = 'true';
}
Policy.setWorkspaceErrors(route.params.policyID, errors);
const isValid = isEmptyObject(errors);
if (!isValid) {
return;
}
HttpUtils.cancelPendingRequests(READ_COMMANDS.SEARCH_FOR_REPORTS);
const invitedEmailsToAccountIDs: InvitedEmailsToAccountIDs = {};
selectedOptions.forEach((option) => {
const login = option.login ?? '';
const accountID = option.accountID ?? '-1';
if (!login.toLowerCase().trim() || !accountID) {
return;
}
invitedEmailsToAccountIDs[login] = Number(accountID);
});
Member.setWorkspaceInviteMembersDraft(route.params.policyID, invitedEmailsToAccountIDs);
Navigation.navigate(ROUTES.WORKSPACE_INVITE_MESSAGE.getRoute(route.params.policyID));
}, [route.params.policyID, selectedOptions]);
const [policyName, shouldShowAlertPrompt] = useMemo(() => [policy?.name ?? '', !isEmptyObject(policy?.errors) || !!policy?.alertMessage], [policy]);
const headerMessage = useMemo(() => {
const searchValue = debouncedSearchTerm.trim().toLowerCase();
if (usersToInvite.length === 0 && CONST.EXPENSIFY_EMAILS.some((email) => email === searchValue)) {
return translate('messages.errorMessageInvalidEmail');
}
if (
usersToInvite.length === 0 &&
excludedUsers.includes(
PhoneNumber.parsePhoneNumber(LoginUtils.appendCountryCode(searchValue)).possible
? PhoneNumber.addSMSDomainIfPhoneNumber(LoginUtils.appendCountryCode(searchValue))
: searchValue,
)
) {
return translate('messages.userIsAlreadyMember', {login: searchValue, name: policyName});
}
return OptionsListUtils.getHeaderMessage(personalDetails.length !== 0, usersToInvite.length > 0, searchValue);
}, [excludedUsers, translate, debouncedSearchTerm, policyName, usersToInvite, personalDetails.length]);
const footerContent = useMemo(
() => (
<FormAlertWithSubmitButton
isDisabled={!selectedOptions.length}
isAlertVisible={shouldShowAlertPrompt}
buttonText={translate('common.next')}
onSubmit={inviteUser}
message={[policy?.alertMessage ?? '', {isTranslated: true}]}
containerStyles={[styles.flexReset, styles.flexGrow0, styles.flexShrink0, styles.flexBasisAuto]}
enabledWhenOffline
disablePressOnEnter
/>
),
[inviteUser, policy?.alertMessage, selectedOptions.length, shouldShowAlertPrompt, styles, translate],
);
useEffect(() => {
ReportActions.searchInServer(debouncedSearchTerm);
}, [debouncedSearchTerm]);
return (
<AccessOrNotFoundWrapper
policyID={route.params.policyID}
accessVariants={[CONST.POLICY.ACCESS_VARIANTS.ADMIN]}
fullPageNotFoundViewProps={{subtitleKey: isEmptyObject(policy) ? undefined : 'workspace.common.notAuthorized', onLinkPress: PolicyUtils.goBackFromInvalidPolicy}}
>
<ScreenWrapper
shouldEnableMaxHeight
shouldUseCachedViewportHeight
testID={WorkspaceInvitePage.displayName}
includeSafeAreaPaddingBottom={false}
onEntryTransitionEnd={() => setDidScreenTransitionEnd(true)}
>
<HeaderWithBackButton
title={translate('workspace.invite.invitePeople')}
subtitle={policyName}
shouldShowGetAssistanceButton
guidesCallTaskID={CONST.GUIDES_CALL_TASK_IDS.WORKSPACE_MEMBERS}
onBackButtonPress={() => {
Policy.clearErrors(route.params.policyID);
Navigation.goBack();
}}
/>
<SelectionList
canSelectMultiple
sections={sections}
ListItem={InviteMemberListItem}
textInputLabel={translate('selectionList.nameEmailOrPhoneNumber')}
textInputValue={searchTerm}
onChangeText={(value) => {
SearchInputManager.searchInput = value;
setSearchTerm(value);
}}
headerMessage={headerMessage}
onSelectRow={toggleOption}
onConfirm={inviteUser}
showScrollIndicator
showLoadingPlaceholder={!areOptionsInitialized || !didScreenTransitionEnd}
shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
footerContent={footerContent}
isLoadingNewOptions={!!isSearchingForReports}
/>
</ScreenWrapper>
</AccessOrNotFoundWrapper>
);
}
WorkspaceInvitePage.displayName = 'WorkspaceInvitePage';
export default withNavigationTransitionEnd(
withPolicyAndFullscreenLoading(
withOnyx<WorkspaceInvitePageProps, WorkspaceInvitePageOnyxProps>({
betas: {
key: ONYXKEYS.BETAS,
},
invitedEmailsToAccountIDsDraft: {
key: ({route}) => `${ONYXKEYS.COLLECTION.WORKSPACE_INVITE_MEMBERS_DRAFT}${route.params.policyID.toString()}`,
},
})(WorkspaceInvitePage),
),
);