-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathInviteReportParticipantsPage.tsx
242 lines (215 loc) · 11.7 KB
/
InviteReportParticipantsPage.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
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import type {SectionListData} from 'react-native';
import {View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import {withOnyx} 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 useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import * as LoginUtils from '@libs/LoginUtils';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as PhoneNumber from '@libs/PhoneNumber';
import * as ReportUtils from '@libs/ReportUtils';
import * as Report from '@userActions/Report';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {InvitedEmailsToAccountIDs, PersonalDetailsList} from '@src/types/onyx';
import type {WithReportOrNotFoundProps} from './home/report/withReportOrNotFound';
import withReportOrNotFound from './home/report/withReportOrNotFound';
type InviteReportParticipantsPageOnyxProps = {
/** All of the personal details for everyone */
personalDetails: OnyxEntry<PersonalDetailsList>;
};
type InviteReportParticipantsPageProps = InviteReportParticipantsPageOnyxProps & WithReportOrNotFoundProps & WithNavigationTransitionEndProps;
type Sections = Array<SectionListData<OptionsListUtils.MemberForList, Section<OptionsListUtils.MemberForList>>>;
function InviteReportParticipantsPage({betas, personalDetails, report, didScreenTransitionEnd}: InviteReportParticipantsPageProps) {
const {options, areOptionsInitialized} = useOptionsList({
shouldInitialize: didScreenTransitionEnd,
});
const styles = useThemeStyles();
const {translate} = useLocalize();
const [searchTerm, setSearchTerm] = useState('');
const [selectedOptions, setSelectedOptions] = useState<ReportUtils.OptionData[]>([]);
const [invitePersonalDetails, setInvitePersonalDetails] = useState<ReportUtils.OptionData[]>([]);
const [recentReports, setRecentReports] = useState<ReportUtils.OptionData[]>([]);
const [userToInvite, setUserToInvite] = useState<ReportUtils.OptionData | null>(null);
// Any existing participants and Expensify emails should not be eligible for invitation
const excludedUsers = useMemo(() => [...PersonalDetailsUtils.getLoginsByAccountIDs(ReportUtils.getParticipantAccountIDs(report?.reportID ?? '')), ...CONST.EXPENSIFY_EMAILS], [report]);
useEffect(() => {
const inviteOptions = OptionsListUtils.getMemberInviteOptions(options.personalDetails, betas ?? [], searchTerm, excludedUsers, false, options.reports, true);
// Update selectedOptions with the latest personalDetails information
const detailsMap: Record<string, OptionsListUtils.MemberForList> = {};
inviteOptions.personalDetails.forEach((detail) => {
if (!detail.login) {
return;
}
detailsMap[detail.login] = OptionsListUtils.formatMemberForList(detail);
});
const newSelectedOptions: ReportUtils.OptionData[] = [];
selectedOptions.forEach((option) => {
newSelectedOptions.push(option.login && option.login in detailsMap ? {...detailsMap[option.login], isSelected: true} : option);
});
setUserToInvite(inviteOptions.userToInvite);
setInvitePersonalDetails(inviteOptions.personalDetails);
setRecentReports(inviteOptions.recentReports);
setSelectedOptions(newSelectedOptions);
// eslint-disable-next-line react-hooks/exhaustive-deps -- we don't want to recalculate when selectedOptions change
}, [personalDetails, betas, searchTerm, excludedUsers, options]);
const sections = useMemo(() => {
const sectionsArr: Sections = [];
if (!areOptionsInitialized) {
return [];
}
// Filter all options that is a part of the search term or in the personal details
let filterSelectedOptions = selectedOptions;
if (searchTerm !== '') {
filterSelectedOptions = selectedOptions.filter((option) => {
const accountID = option?.accountID;
const isOptionInPersonalDetails = invitePersonalDetails.some((personalDetail) => accountID && personalDetail?.accountID === accountID);
const searchValue = OptionsListUtils.getSearchValueForPhoneOrEmail(searchTerm);
const isPartOfSearchTerm = !!option.text?.toLowerCase().includes(searchValue) || !!option.login?.toLowerCase().includes(searchValue);
return isPartOfSearchTerm || isOptionInPersonalDetails;
});
}
const filterSelectedOptionsFormatted = filterSelectedOptions.map((selectedOption) => OptionsListUtils.formatMemberForList(selectedOption));
sectionsArr.push({
title: undefined,
data: filterSelectedOptionsFormatted,
});
// Filtering out selected users from the search results
const selectedLogins = selectedOptions.map(({login}) => login);
const recentReportsWithoutSelected = recentReports.filter(({login}) => !selectedLogins.includes(login));
const recentReportsFormatted = recentReportsWithoutSelected.map((reportOption) => OptionsListUtils.formatMemberForList(reportOption));
const personalDetailsWithoutSelected = invitePersonalDetails.filter(({login}) => !selectedLogins.includes(login));
const personalDetailsFormatted = personalDetailsWithoutSelected.map((personalDetail) => OptionsListUtils.formatMemberForList(personalDetail));
const hasUnselectedUserToInvite = userToInvite && !selectedLogins.includes(userToInvite.login);
sectionsArr.push({
title: translate('common.recents'),
data: recentReportsFormatted,
});
sectionsArr.push({
title: translate('common.contacts'),
data: personalDetailsFormatted,
});
if (hasUnselectedUserToInvite) {
sectionsArr.push({
title: undefined,
data: [OptionsListUtils.formatMemberForList(userToInvite)],
});
}
return sectionsArr;
}, [invitePersonalDetails, searchTerm, selectedOptions, translate, userToInvite, areOptionsInitialized, recentReports]);
const toggleOption = useCallback(
(option: OptionsListUtils.MemberForList) => {
const isOptionInList = selectedOptions.some((selectedOption) => selectedOption.login === option.login);
let newSelectedOptions: ReportUtils.OptionData[];
if (isOptionInList) {
newSelectedOptions = selectedOptions.filter((selectedOption) => selectedOption.login !== option.login);
} else {
newSelectedOptions = [...selectedOptions, {...option, isSelected: true}];
}
setSelectedOptions(newSelectedOptions);
},
[selectedOptions],
);
const validate = useCallback(() => selectedOptions.length > 0, [selectedOptions]);
const reportID = report.reportID;
const backRoute = useMemo(() => ROUTES.REPORT_PARTICIPANTS.getRoute(reportID), [reportID]);
const reportName = useMemo(() => ReportUtils.getGroupChatName(undefined, true, report?.reportID ?? ''), [report]);
const inviteUsers = useCallback(() => {
if (!validate()) {
return;
}
const invitedEmailsToAccountIDs: InvitedEmailsToAccountIDs = {};
selectedOptions.forEach((option) => {
const login = option.login ?? '';
const accountID = option.accountID;
if (!login.toLowerCase().trim() || !accountID) {
return;
}
invitedEmailsToAccountIDs[login] = accountID;
});
Report.inviteToGroupChat(reportID, invitedEmailsToAccountIDs);
Navigation.navigate(backRoute);
}, [selectedOptions, backRoute, reportID, validate]);
const headerMessage = useMemo(() => {
const searchValue = searchTerm.trim().toLowerCase();
const expensifyEmails = CONST.EXPENSIFY_EMAILS as string[];
if (!userToInvite && expensifyEmails.includes(searchValue)) {
return translate('messages.errorMessageInvalidEmail');
}
if (
!userToInvite &&
excludedUsers.includes(
PhoneNumber.parsePhoneNumber(LoginUtils.appendCountryCode(searchValue)).possible
? PhoneNumber.addSMSDomainIfPhoneNumber(LoginUtils.appendCountryCode(searchValue))
: searchValue,
)
) {
return translate('messages.userIsAlreadyMember', {login: searchValue, name: reportName ?? ''});
}
return OptionsListUtils.getHeaderMessage(invitePersonalDetails.length !== 0, Boolean(userToInvite), searchValue);
}, [searchTerm, userToInvite, excludedUsers, invitePersonalDetails, translate, reportName]);
return (
<ScreenWrapper
shouldEnableMaxHeight
testID={InviteReportParticipantsPage.displayName}
>
<HeaderWithBackButton
title={translate('workspace.invite.members')}
subtitle={reportName}
onBackButtonPress={() => {
Navigation.goBack(backRoute);
}}
/>
<View style={[styles.flex1, styles.p1]}>
<SelectionList
canSelectMultiple
sections={sections}
ListItem={InviteMemberListItem}
textInputLabel={translate('selectionList.nameEmailOrPhoneNumber')}
textInputValue={searchTerm}
onChangeText={setSearchTerm}
headerMessage={headerMessage}
onSelectRow={toggleOption}
onConfirm={inviteUsers}
showScrollIndicator
shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
showLoadingPlaceholder={!didScreenTransitionEnd || !OptionsListUtils.isPersonalDetailsReady(personalDetails)}
/>
</View>
<View style={[styles.flexShrink0, styles.p5]}>
<FormAlertWithSubmitButton
isDisabled={!selectedOptions.length}
buttonText={translate('common.invite')}
onSubmit={inviteUsers}
containerStyles={[styles.flexReset, styles.flexGrow0, styles.flexShrink0, styles.flexBasisAuto, styles.mb5]}
enabledWhenOffline
disablePressOnEnter
/>
</View>
</ScreenWrapper>
);
}
InviteReportParticipantsPage.displayName = 'InviteReportParticipantsPage';
export default withNavigationTransitionEnd(
withReportOrNotFound()(
withOnyx<InviteReportParticipantsPageProps, InviteReportParticipantsPageOnyxProps>({
personalDetails: {
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
},
})(InviteReportParticipantsPage),
),
);