-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
WorkspaceInvitePage.js
271 lines (236 loc) · 11.5 KB
/
WorkspaceInvitePage.js
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
import React, {useEffect, useMemo, useState} from 'react';
import PropTypes from 'prop-types';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import lodashGet from 'lodash/get';
import ScreenWrapper from '../../components/ScreenWrapper';
import HeaderWithBackButton from '../../components/HeaderWithBackButton';
import Navigation from '../../libs/Navigation/Navigation';
import styles from '../../styles/styles';
import compose from '../../libs/compose';
import ONYXKEYS from '../../ONYXKEYS';
import * as Policy from '../../libs/actions/Policy';
import FormAlertWithSubmitButton from '../../components/FormAlertWithSubmitButton';
import * as OptionsListUtils from '../../libs/OptionsListUtils';
import CONST from '../../CONST';
import withPolicy, {policyDefaultProps, policyPropTypes} from './withPolicy';
import FullPageNotFoundView from '../../components/BlockingViews/FullPageNotFoundView';
import ROUTES from '../../ROUTES';
import * as PolicyUtils from '../../libs/PolicyUtils';
import useNetwork from '../../hooks/useNetwork';
import useLocalize from '../../hooks/useLocalize';
import SelectionList from '../../components/SelectionList';
const personalDetailsPropTypes = PropTypes.shape({
/** The login of the person (either email or phone number) */
login: PropTypes.string,
/** The URL of the person's avatar (there should already be a default avatar if
the person doesn't have their own avatar uploaded yet, except for anon users) */
avatar: PropTypes.string,
/** This is either the user's full name, or their login if full name is an empty string */
displayName: PropTypes.string,
});
const propTypes = {
/** Beta features list */
betas: PropTypes.arrayOf(PropTypes.string),
/** All of the personal details for everyone */
personalDetails: PropTypes.objectOf(personalDetailsPropTypes),
/** URL Route params */
route: PropTypes.shape({
/** Params from the URL path */
params: PropTypes.shape({
/** policyID passed via route: /workspace/:policyID/invite */
policyID: PropTypes.string,
}),
}).isRequired,
isLoadingReportData: PropTypes.bool,
...policyPropTypes,
};
const defaultProps = {
personalDetails: {},
betas: [],
isLoadingReportData: true,
...policyDefaultProps,
};
function WorkspaceInvitePage(props) {
const {translate} = useLocalize();
const [searchTerm, setSearchTerm] = useState('');
const [selectedOptions, setSelectedOptions] = useState([]);
const [personalDetails, setPersonalDetails] = useState([]);
const [userToInvite, setUserToInvite] = useState(null);
const openWorkspaceInvitePage = () => {
const policyMemberEmailsToAccountIDs = PolicyUtils.getMemberAccountIDsForWorkspace(props.policyMembers, props.personalDetails);
Policy.openWorkspaceInvitePage(props.route.params.policyID, _.keys(policyMemberEmailsToAccountIDs));
};
useEffect(() => {
Policy.clearErrors(props.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(props.policyMembers, props.personalDetails), [props.policyMembers, props.personalDetails]);
useEffect(() => {
const inviteOptions = OptionsListUtils.getMemberInviteOptions(props.personalDetails, props.betas, searchTerm, excludedUsers);
// Update selectedOptions with the latest personalDetails and policyMembers information
const detailsMap = {};
_.forEach(inviteOptions.personalDetails, (detail) => (detailsMap[detail.login] = OptionsListUtils.formatMemberForList(detail, false)));
const newSelectedOptions = [];
_.forEach(selectedOptions, (option) => {
newSelectedOptions.push(_.has(detailsMap, option.login) ? {...detailsMap[option.login], isSelected: true} : option);
});
setUserToInvite(inviteOptions.userToInvite);
setPersonalDetails(inviteOptions.personalDetails);
setSelectedOptions(newSelectedOptions);
// eslint-disable-next-line react-hooks/exhaustive-deps -- we don't want to recalculate when selectedOptions change
}, [props.personalDetails, props.policyMembers, props.betas, searchTerm, excludedUsers]);
const getSections = () => {
const sections = [];
let indexOffset = 0;
sections.push({
title: undefined,
data: selectedOptions,
shouldShow: true,
indexOffset,
});
indexOffset += selectedOptions.length;
// Filtering out selected users from the search results
const selectedLogins = _.map(selectedOptions, ({login}) => login);
const personalDetailsWithoutSelected = _.filter(personalDetails, ({login}) => !_.contains(selectedLogins, login));
const personalDetailsFormatted = _.map(personalDetailsWithoutSelected, (personalDetail) => OptionsListUtils.formatMemberForList(personalDetail, false));
const hasUnselectedUserToInvite = userToInvite && !_.contains(selectedLogins, userToInvite.login);
sections.push({
title: translate('common.contacts'),
data: personalDetailsFormatted,
shouldShow: !_.isEmpty(personalDetailsFormatted),
indexOffset,
});
indexOffset += personalDetailsFormatted.length;
if (hasUnselectedUserToInvite) {
sections.push({
title: undefined,
data: [OptionsListUtils.formatMemberForList(userToInvite, false)],
shouldShow: true,
indexOffset,
});
}
return sections;
};
const toggleOption = (option) => {
Policy.clearErrors(props.route.params.policyID);
const isOptionInList = _.some(selectedOptions, (selectedOption) => selectedOption.login === option.login);
let newSelectedOptions;
if (isOptionInList) {
newSelectedOptions = _.reject(selectedOptions, (selectedOption) => selectedOption.login === option.login);
} else {
newSelectedOptions = [...selectedOptions, {...option, isSelected: true}];
}
setSelectedOptions(newSelectedOptions);
};
const validate = () => {
const errors = {};
if (selectedOptions.length <= 0) {
errors.noUserSelected = true;
}
Policy.setWorkspaceErrors(props.route.params.policyID, errors);
return _.size(errors) <= 0;
};
const inviteUser = () => {
if (!validate()) {
return;
}
const invitedEmailsToAccountIDs = {};
_.each(selectedOptions, (option) => {
const login = option.login || '';
const accountID = lodashGet(option, 'accountID', '');
if (!login.toLowerCase().trim() || !accountID) {
return;
}
invitedEmailsToAccountIDs[login] = Number(accountID);
});
Policy.setWorkspaceInviteMembersDraft(props.route.params.policyID, invitedEmailsToAccountIDs);
Navigation.navigate(ROUTES.WORKSPACE_INVITE_MESSAGE.getRoute(props.route.params.policyID));
};
const [policyName, shouldShowAlertPrompt] = useMemo(
() => [lodashGet(props.policy, 'name'), _.size(lodashGet(props.policy, 'errors', {})) > 0 || lodashGet(props.policy, 'alertMessage', '').length > 0],
[props.policy],
);
const headerMessage = useMemo(() => {
const searchValue = searchTerm.trim().toLowerCase();
if (!userToInvite && CONST.EXPENSIFY_EMAILS.includes(searchValue)) {
return translate('messages.errorMessageInvalidEmail');
}
if (!userToInvite && excludedUsers.includes(searchValue)) {
return translate('messages.userIsAlreadyMemberOfWorkspace', {login: searchValue, workspace: policyName});
}
return OptionsListUtils.getHeaderMessage(personalDetails.length !== 0, Boolean(userToInvite), searchValue);
}, [excludedUsers, translate, searchTerm, policyName, userToInvite, personalDetails]);
return (
<ScreenWrapper
shouldEnableMaxHeight
testID={WorkspaceInvitePage.displayName}
>
{({didScreenTransitionEnd}) => {
const sections = didScreenTransitionEnd ? getSections() : [];
return (
<FullPageNotFoundView
shouldShow={((_.isEmpty(props.policy) || !PolicyUtils.isPolicyAdmin(props.policy)) && !props.isLoadingReportData) || PolicyUtils.isPendingDeletePolicy(props.policy)}
subtitleKey={_.isEmpty(props.policy) ? undefined : 'workspace.common.notAuthorized'}
onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_WORKSPACES)}
>
<HeaderWithBackButton
title={translate('workspace.invite.invitePeople')}
subtitle={policyName}
shouldShowGetAssistanceButton
guidesCallTaskID={CONST.GUIDES_CALL_TASK_IDS.WORKSPACE_MEMBERS}
onBackButtonPress={() => {
Policy.clearErrors(props.route.params.policyID);
Navigation.goBack(ROUTES.WORKSPACE_MEMBERS.getRoute(props.route.params.policyID));
}}
/>
<SelectionList
canSelectMultiple
sections={sections}
textInputLabel={translate('optionsSelector.nameEmailOrPhoneNumber')}
textInputValue={searchTerm}
onChangeText={setSearchTerm}
headerMessage={headerMessage}
onSelectRow={toggleOption}
onConfirm={inviteUser}
showScrollIndicator
showLoadingPlaceholder={!didScreenTransitionEnd || !OptionsListUtils.isPersonalDetailsReady(props.personalDetails)}
/>
<View style={[styles.flexShrink0]}>
<FormAlertWithSubmitButton
isDisabled={!selectedOptions.length}
isAlertVisible={shouldShowAlertPrompt}
buttonText={translate('common.next')}
onSubmit={inviteUser}
message={props.policy.alertMessage}
containerStyles={[styles.flexReset, styles.flexGrow0, styles.flexShrink0, styles.flexBasisAuto, styles.mb5]}
enabledWhenOffline
disablePressOnEnter
/>
</View>
</FullPageNotFoundView>
);
}}
</ScreenWrapper>
);
}
WorkspaceInvitePage.propTypes = propTypes;
WorkspaceInvitePage.defaultProps = defaultProps;
WorkspaceInvitePage.displayName = 'WorkspaceInvitePage';
export default compose(
withPolicy,
withOnyx({
personalDetails: {
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
},
betas: {
key: ONYXKEYS.BETAS,
},
isLoadingReportData: {
key: ONYXKEYS.IS_LOADING_REPORT_DATA,
},
}),
)(WorkspaceInvitePage);