-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
WorkspaceMembersPage.tsx
703 lines (635 loc) · 31.6 KB
/
WorkspaceMembersPage.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import {useIsFocused} from '@react-navigation/native';
import type {StackScreenProps} from '@react-navigation/stack';
import lodashIsEqual from 'lodash/isEqual';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import type {TextInput} from 'react-native';
import {InteractionManager, View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import {useOnyx} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import Badge from '@components/Badge';
import Button from '@components/Button';
import ButtonWithDropdownMenu from '@components/ButtonWithDropdownMenu';
import type {DropdownOption, WorkspaceMemberBulkActionType} from '@components/ButtonWithDropdownMenu/types';
import ConfirmModal from '@components/ConfirmModal';
import DecisionModal from '@components/DecisionModal';
import * as Expensicons from '@components/Icon/Expensicons';
import * as Illustrations from '@components/Icon/Illustrations';
import MessagesRow from '@components/MessagesRow';
import TableListItem from '@components/SelectionList/TableListItem';
import type {ListItem, SelectionListHandle} from '@components/SelectionList/types';
import SelectionListWithModal from '@components/SelectionListWithModal';
import Text from '@components/Text';
import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails';
import withCurrentUserPersonalDetails from '@components/withCurrentUserPersonalDetails';
import useLocalize from '@hooks/useLocalize';
import useMobileSelectionMode from '@hooks/useMobileSelectionMode';
import useNetwork from '@hooks/useNetwork';
import usePrevious from '@hooks/usePrevious';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import type {FullScreenNavigatorParamList} from '@libs/Navigation/types';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as PolicyUtils from '@libs/PolicyUtils';
import {getDisplayNameForParticipant} from '@libs/ReportUtils';
import * as Modal from '@userActions/Modal';
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 {PersonalDetailsList, PolicyEmployeeList} from '@src/types/onyx';
import type {Errors, PendingAction} from '@src/types/onyx/OnyxCommon';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {WithPolicyAndFullscreenLoadingProps} from './withPolicyAndFullscreenLoading';
import withPolicyAndFullscreenLoading from './withPolicyAndFullscreenLoading';
import WorkspacePageWithSections from './WorkspacePageWithSections';
type WorkspaceMembersPageProps = WithPolicyAndFullscreenLoadingProps & WithCurrentUserPersonalDetailsProps & StackScreenProps<FullScreenNavigatorParamList, typeof SCREENS.WORKSPACE.MEMBERS>;
/**
* Inverts an object, equivalent of _.invert
*/
function invertObject(object: Record<string, string>): Record<string, string> {
const invertedEntries = Object.entries(object).map(([key, value]) => [value, key] as const);
return Object.fromEntries(invertedEntries);
}
type MemberOption = Omit<ListItem, 'accountID'> & {accountID: number};
function WorkspaceMembersPage({personalDetails, route, policy, currentUserPersonalDetails}: WorkspaceMembersPageProps) {
const policyMemberEmailsToAccountIDs = useMemo(() => PolicyUtils.getMemberAccountIDsForWorkspace(policy?.employeeList, true), [policy?.employeeList]);
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [selectedEmployees, setSelectedEmployees] = useState<number[]>([]);
const [removeMembersConfirmModalVisible, setRemoveMembersConfirmModalVisible] = useState(false);
const [errors, setErrors] = useState({});
const {isOffline} = useNetwork();
const {windowWidth} = useWindowDimensions();
const prevIsOffline = usePrevious(isOffline);
const accountIDs = useMemo(() => Object.values(policyMemberEmailsToAccountIDs ?? {}).map((accountID) => Number(accountID)), [policyMemberEmailsToAccountIDs]);
const prevAccountIDs = usePrevious(accountIDs);
const textInputRef = useRef<TextInput>(null);
const [isOfflineModalVisible, setIsOfflineModalVisible] = useState(false);
const [isDownloadFailureModalVisible, setIsDownloadFailureModalVisible] = useState(false);
const isOfflineAndNoMemberDataAvailable = isEmptyObject(policy?.employeeList) && isOffline;
const prevPersonalDetails = usePrevious(personalDetails);
const {translate, formatPhoneNumber, preferredLocale} = useLocalize();
const {shouldUseNarrowLayout, isSmallScreenWidth} = useResponsiveLayout();
const isPolicyAdmin = PolicyUtils.isPolicyAdmin(policy);
const isLoading = useMemo(
() => !isOfflineAndNoMemberDataAvailable && (!OptionsListUtils.isPersonalDetailsReady(personalDetails) || isEmptyObject(policy?.employeeList)),
[isOfflineAndNoMemberDataAvailable, personalDetails, policy?.employeeList],
);
const [invitedEmailsToAccountIDsDraft] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_INVITE_MEMBERS_DRAFT}${route.params.policyID.toString()}`);
const {selectionMode} = useMobileSelectionMode();
const [session] = useOnyx(ONYXKEYS.SESSION);
const selectionListRef = useRef<SelectionListHandle>(null);
const isFocused = useIsFocused();
const policyID = route.params.policyID;
const canSelectMultiple = isPolicyAdmin && (shouldUseNarrowLayout ? selectionMode?.isEnabled : true);
const confirmModalPrompt = useMemo(() => {
const approverAccountID = selectedEmployees.find((selectedEmployee) => Member.isApprover(policy, selectedEmployee));
if (!approverAccountID) {
return translate('workspace.people.removeMembersPrompt');
}
return translate('workspace.people.removeMembersWarningPrompt', {
memberName: getDisplayNameForParticipant(approverAccountID),
ownerName: getDisplayNameForParticipant(policy?.ownerAccountID),
});
}, [selectedEmployees, policy, translate]);
/**
* Get filtered personalDetails list with current employeeList
*/
const filterPersonalDetails = (members: OnyxEntry<PolicyEmployeeList>, details: OnyxEntry<PersonalDetailsList>): PersonalDetailsList =>
Object.keys(members ?? {}).reduce((acc, key) => {
const memberAccountIdKey = policyMemberEmailsToAccountIDs[key] ?? '';
if (details?.[memberAccountIdKey]) {
acc[memberAccountIdKey] = details[memberAccountIdKey];
}
return acc;
}, {} as PersonalDetailsList);
/**
* Get members for the current workspace
*/
const getWorkspaceMembers = useCallback(() => {
Member.openWorkspaceMembersPage(route.params.policyID, Object.keys(PolicyUtils.getMemberAccountIDsForWorkspace(policy?.employeeList)));
}, [route.params.policyID, policy?.employeeList]);
/**
* Check if the current selection includes members that cannot be removed
*/
const validateSelection = useCallback(() => {
const newErrors: Errors = {};
selectedEmployees.forEach((member) => {
if (member !== policy?.ownerAccountID && member !== session?.accountID) {
return;
}
newErrors[member] = translate('workspace.people.error.cannotRemove');
});
setErrors(newErrors);
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [selectedEmployees, policy?.owner, session?.accountID]);
// useFocus would make getWorkspaceMembers get called twice on fresh login because policyEmployee is a dependency of getWorkspaceMembers.
useEffect(() => {
if (!isFocused) {
setSelectedEmployees([]);
return;
}
getWorkspaceMembers();
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [isFocused]);
useEffect(() => {
validateSelection();
}, [preferredLocale, validateSelection]);
useEffect(() => {
if (removeMembersConfirmModalVisible && !lodashIsEqual(accountIDs, prevAccountIDs)) {
setRemoveMembersConfirmModalVisible(false);
}
setSelectedEmployees((prevSelected) => {
// Filter all personal details in order to use the elements needed for the current workspace
const currentPersonalDetails = filterPersonalDetails(policy?.employeeList ?? {}, personalDetails);
// We need to filter the previous selected employees by the new personal details, since unknown/new user id's change when transitioning from offline to online
const prevSelectedElements = prevSelected.map((id) => {
const prevItem = prevPersonalDetails?.id;
const res = Object.values(currentPersonalDetails).find((item) => prevItem?.login === item?.login);
return res?.accountID ?? id;
});
const currentSelectedElements = Object.entries(PolicyUtils.getMemberAccountIDsForWorkspace(policy?.employeeList))
.filter((employee) => policy?.employeeList?.[employee[0]]?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE)
.map((employee) => employee[1]);
// This is an equivalent of the lodash intersection function. The reduce method below is used to filter the items that exist in both arrays.
return [prevSelectedElements, currentSelectedElements].reduce((prev, members) => prev.filter((item) => members.includes(item)));
});
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [policy?.employeeList, policyMemberEmailsToAccountIDs]);
useEffect(() => {
const isReconnecting = prevIsOffline && !isOffline;
if (!isReconnecting) {
return;
}
getWorkspaceMembers();
}, [isOffline, prevIsOffline, getWorkspaceMembers]);
/**
* Open the modal to invite a user
*/
const inviteUser = () => {
Navigation.navigate(ROUTES.WORKSPACE_INVITE.getRoute(route.params.policyID));
};
/**
* Remove selected users from the workspace
* Please see https://github.com/Expensify/App/blob/main/README.md#Security for more details
*/
const removeUsers = () => {
if (!isEmptyObject(errors)) {
return;
}
// Remove the admin from the list
const accountIDsToRemove = session?.accountID ? selectedEmployees.filter((id) => id !== session.accountID) : selectedEmployees;
Member.removeMembers(accountIDsToRemove, route.params.policyID);
setSelectedEmployees([]);
setRemoveMembersConfirmModalVisible(false);
};
/**
* Show the modal to confirm removal of the selected members
*/
const askForConfirmationToRemove = () => {
if (!isEmptyObject(errors)) {
return;
}
setRemoveMembersConfirmModalVisible(true);
};
/**
* Add or remove all users passed from the selectedEmployees list
*/
const toggleAllUsers = (memberList: MemberOption[]) => {
const enabledAccounts = memberList.filter((member) => !member.isDisabled && !member.isDisabledCheckbox);
const everyoneSelected = enabledAccounts.every((member) => selectedEmployees.includes(member.accountID));
if (everyoneSelected) {
setSelectedEmployees([]);
} else {
const everyAccountId = enabledAccounts.map((member) => member.accountID);
setSelectedEmployees(everyAccountId);
}
validateSelection();
};
/**
* Add user from the selectedEmployees list
*/
const addUser = useCallback(
(accountID: number) => {
setSelectedEmployees((prevSelected) => [...prevSelected, accountID]);
validateSelection();
},
[validateSelection],
);
/**
* Remove user from the selectedEmployees list
*/
const removeUser = useCallback(
(accountID: number) => {
setSelectedEmployees((prevSelected) => prevSelected.filter((id) => id !== accountID));
validateSelection();
},
[validateSelection],
);
/**
* Toggle user from the selectedEmployees list
*/
const toggleUser = useCallback(
(accountID: number, pendingAction?: PendingAction) => {
if (accountID === policy?.ownerAccountID && accountID !== session?.accountID) {
return;
}
if (pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
return;
}
// Add or remove the user if the checkbox is enabled
if (selectedEmployees.includes(accountID)) {
removeUser(accountID);
} else {
addUser(accountID);
}
},
[selectedEmployees, addUser, removeUser, policy?.ownerAccountID, session?.accountID],
);
/** Opens the member details page */
const openMemberDetails = useCallback(
(item: MemberOption) => {
if (!isPolicyAdmin || !PolicyUtils.isPaidGroupPolicy(policy)) {
Navigation.navigate(ROUTES.PROFILE.getRoute(item.accountID));
return;
}
Member.clearWorkspaceOwnerChangeFlow(policyID);
Navigation.navigate(ROUTES.WORKSPACE_MEMBER_DETAILS.getRoute(route.params.policyID, item.accountID));
},
[isPolicyAdmin, policy, policyID, route.params.policyID],
);
/**
* Dismisses the errors on one item
*/
const dismissError = useCallback(
(item: MemberOption) => {
if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
Member.clearDeleteMemberError(route.params.policyID, item.accountID);
} else {
Member.clearAddMemberError(route.params.policyID, item.accountID);
}
},
[route.params.policyID],
);
const policyOwner = policy?.owner;
const currentUserLogin = currentUserPersonalDetails.login;
const invitedPrimaryToSecondaryLogins = invertObject(policy?.primaryLoginsInvited ?? {});
const getUsers = useCallback((): MemberOption[] => {
let result: MemberOption[] = [];
Object.entries(policy?.employeeList ?? {}).forEach(([email, policyEmployee]) => {
const accountID = Number(policyMemberEmailsToAccountIDs[email] ?? '');
if (PolicyUtils.isDeletedPolicyEmployee(policyEmployee, isOffline)) {
return;
}
const details = personalDetails?.[accountID];
if (!details) {
Log.hmmm(`[WorkspaceMembersPage] no personal details found for policy member with accountID: ${accountID}`);
return;
}
// If this policy is owned by Expensify then show all support (expensify.com or team.expensify.com) emails
// We don't want to show guides as policy members unless the user is a guide. Some customers get confused when they
// see random people added to their policy, but guides having access to the policies help set them up.
if (PolicyUtils.isExpensifyTeam(details?.login ?? details?.displayName)) {
if (policyOwner && currentUserLogin && !PolicyUtils.isExpensifyTeam(policyOwner) && !PolicyUtils.isExpensifyTeam(currentUserLogin)) {
return;
}
}
const isSelected = selectedEmployees.includes(accountID) && canSelectMultiple;
const isOwner = policy?.owner === details.login;
const isAdmin = policyEmployee.role === CONST.POLICY.ROLE.ADMIN;
const isAuditor = policyEmployee.role === CONST.POLICY.ROLE.AUDITOR;
let roleBadge = null;
if (isOwner || isAdmin) {
roleBadge = <Badge text={isOwner ? translate('common.owner') : translate('common.admin')} />;
} else if (isAuditor) {
roleBadge = <Badge text={translate('common.auditor')} />;
}
result.push({
keyForList: String(accountID),
accountID,
isSelected,
isDisabledCheckbox: !(isPolicyAdmin && accountID !== policy?.ownerAccountID && accountID !== session?.accountID),
isDisabled:
!!details.isOptimisticPersonalDetail ||
(isPolicyAdmin && (policyEmployee.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || !isEmptyObject(policyEmployee.errors))),
cursorStyle: details.isOptimisticPersonalDetail ? styles.cursorDefault : {},
text: formatPhoneNumber(PersonalDetailsUtils.getDisplayNameOrDefault(details)),
alternateText: formatPhoneNumber(details?.login ?? ''),
rightElement: roleBadge,
icons: [
{
source: details.avatar ?? Expensicons.FallbackAvatar,
name: formatPhoneNumber(details?.login ?? ''),
type: CONST.ICON_TYPE_AVATAR,
id: accountID,
},
],
errors: policyEmployee.errors,
pendingAction: policyEmployee.pendingAction,
// Note which secondary login was used to invite this primary login
invitedSecondaryLogin: details?.login ? invitedPrimaryToSecondaryLogins[details.login] ?? '' : '',
});
});
result = OptionsListUtils.sortAlphabetically(result, 'text');
return result;
}, [
isOffline,
currentUserLogin,
formatPhoneNumber,
invitedPrimaryToSecondaryLogins,
isPolicyAdmin,
personalDetails,
policy?.owner,
policy?.ownerAccountID,
policy?.employeeList,
policyMemberEmailsToAccountIDs,
policyOwner,
selectedEmployees,
session?.accountID,
translate,
styles.cursorDefault,
canSelectMultiple,
]);
const data = useMemo(() => getUsers(), [getUsers]);
useEffect(() => {
if (!isFocused) {
return;
}
if (isEmptyObject(invitedEmailsToAccountIDsDraft) || accountIDs === prevAccountIDs) {
return;
}
const invitedEmails = Object.values(invitedEmailsToAccountIDsDraft).map(String);
selectionListRef.current?.scrollAndHighlightItem?.(invitedEmails, 1500);
Member.setWorkspaceInviteMembersDraft(route.params.policyID, {});
}, [invitedEmailsToAccountIDsDraft, route.params.policyID, isFocused, accountIDs, prevAccountIDs]);
const getHeaderMessage = () => {
if (isOfflineAndNoMemberDataAvailable) {
return translate('workspace.common.mustBeOnlineToViewMembers');
}
return !isLoading && isEmptyObject(policy?.employeeList) ? translate('workspace.common.memberNotFound') : '';
};
const getHeaderContent = () => (
<View style={shouldUseNarrowLayout ? styles.workspaceSectionMobile : styles.workspaceSection}>
<Text style={[styles.pl5, styles.mb4, styles.mt3, styles.textSupporting]}>{translate('workspace.people.membersListTitle')}</Text>
{!isEmptyObject(invitedPrimaryToSecondaryLogins) && (
<MessagesRow
type="success"
// eslint-disable-next-line @typescript-eslint/naming-convention
messages={{0: translate('workspace.people.addedWithPrimary')}}
containerStyles={[styles.pb5, styles.ph5]}
onClose={() => Policy.dismissAddedWithPrimaryLoginMessages(policyID)}
/>
)}
</View>
);
useEffect(() => {
if (selectionMode?.isEnabled) {
return;
}
setSelectedEmployees([]);
}, [setSelectedEmployees, selectionMode?.isEnabled]);
const getCustomListHeader = () => {
const header = (
<View style={[styles.flex1, styles.flexRow, styles.justifyContentBetween]}>
<View>
<Text style={[styles.searchInputStyle, canSelectMultiple ? styles.ml3 : styles.ml0]}>{translate('common.member')}</Text>
</View>
<View style={[StyleUtils.getMinimumWidth(60)]}>
<Text style={[styles.searchInputStyle, styles.textAlignCenter]}>{translate('common.role')}</Text>
</View>
</View>
);
if (canSelectMultiple) {
return header;
}
return <View style={[styles.peopleRow, styles.userSelectNone, styles.ph9, styles.pv3, styles.pb5]}>{header}</View>;
};
const changeUserRole = (role: ValueOf<typeof CONST.POLICY.ROLE>) => {
if (!isEmptyObject(errors)) {
return;
}
const accountIDsToUpdate = selectedEmployees.filter((accountID) => {
const email = personalDetails?.[accountID]?.login ?? '';
return policy?.employeeList?.[email]?.role !== role;
});
Member.updateWorkspaceMembersRole(route.params.policyID, accountIDsToUpdate, role);
setSelectedEmployees([]);
};
const getBulkActionsButtonOptions = () => {
const options: Array<DropdownOption<WorkspaceMemberBulkActionType>> = [
{
text: translate('workspace.people.removeMembersTitle'),
value: CONST.POLICY.MEMBERS_BULK_ACTION_TYPES.REMOVE,
icon: Expensicons.RemoveMembers,
onSelected: askForConfirmationToRemove,
},
];
if (!PolicyUtils.isPaidGroupPolicy(policy)) {
return options;
}
const selectedEmployeesRoles = selectedEmployees.map((accountID) => {
const email = personalDetails?.[accountID]?.login ?? '';
return policy?.employeeList?.[email]?.role;
});
const memberOption = {
text: translate('workspace.people.makeMember'),
value: CONST.POLICY.MEMBERS_BULK_ACTION_TYPES.MAKE_MEMBER,
icon: Expensicons.User,
onSelected: () => changeUserRole(CONST.POLICY.ROLE.USER),
};
const adminOption = {
text: translate('workspace.people.makeAdmin'),
value: CONST.POLICY.MEMBERS_BULK_ACTION_TYPES.MAKE_ADMIN,
icon: Expensicons.MakeAdmin,
onSelected: () => changeUserRole(CONST.POLICY.ROLE.ADMIN),
};
const auditorOption = {
text: translate('workspace.people.makeAuditor'),
value: CONST.POLICY.MEMBERS_BULK_ACTION_TYPES.MAKE_AUDITOR,
icon: Expensicons.UserEye,
onSelected: () => changeUserRole(CONST.POLICY.ROLE.AUDITOR),
};
const hasAtLeastOneNonAuditorRole = selectedEmployeesRoles.some((role) => role !== CONST.POLICY.ROLE.AUDITOR);
const hasAtLeastOneNonMemberRole = selectedEmployeesRoles.some((role) => role !== CONST.POLICY.ROLE.USER);
const hasAtLeastOneNonAdminRole = selectedEmployeesRoles.some((role) => role !== CONST.POLICY.ROLE.ADMIN);
if (hasAtLeastOneNonMemberRole) {
options.push(memberOption);
}
if (hasAtLeastOneNonAdminRole) {
options.push(adminOption);
}
if (hasAtLeastOneNonAuditorRole) {
options.push(auditorOption);
}
return options;
};
const getHeaderButtons = () => {
if (!isPolicyAdmin) {
return null;
}
return (
<View style={[styles.flexRow, styles.gap2, shouldUseNarrowLayout && styles.mb3]}>
{(shouldUseNarrowLayout ? canSelectMultiple : selectedEmployees.length > 0) ? (
<ButtonWithDropdownMenu<WorkspaceMemberBulkActionType>
shouldAlwaysShowDropdownMenu
pressOnEnter
customText={translate('workspace.common.selected', {selectedNumber: selectedEmployees.length})}
buttonSize={CONST.DROPDOWN_BUTTON_SIZE.MEDIUM}
onPress={() => null}
options={getBulkActionsButtonOptions()}
isSplitButton={false}
style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]}
isDisabled={!selectedEmployees.length}
/>
) : (
<Button
success
onPress={inviteUser}
text={translate('workspace.invite.member')}
icon={Expensicons.Plus}
innerStyles={[shouldUseNarrowLayout && styles.alignItemsCenter]}
style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]}
/>
)}
</View>
);
};
const threeDotsMenuItems = useMemo(() => {
if (!isPolicyAdmin) {
return [];
}
const menuItems = [
{
icon: Expensicons.Table,
text: translate('spreadsheet.importSpreadsheet'),
onSelected: () => {
if (isOffline) {
Modal.close(() => setIsOfflineModalVisible(true));
return;
}
Navigation.navigate(ROUTES.WORKSPACE_MEMBERS_IMPORT.getRoute(policyID));
},
},
{
icon: Expensicons.Download,
text: translate('spreadsheet.downloadCSV'),
onSelected: () => {
if (isOffline) {
Modal.close(() => setIsOfflineModalVisible(true));
return;
}
Modal.close(() => {
Member.downloadMembersCSV(policyID, () => {
setIsDownloadFailureModalVisible(true);
});
});
},
},
];
return menuItems;
}, [policyID, translate, isOffline, isPolicyAdmin]);
const selectionModeHeader = selectionMode?.isEnabled && shouldUseNarrowLayout;
return (
<WorkspacePageWithSections
headerText={selectionModeHeader ? translate('common.selectMultiple') : translate('workspace.common.members')}
route={route}
guidesCallTaskID={CONST.GUIDES_CALL_TASK_IDS.WORKSPACE_MEMBERS}
icon={!selectionModeHeader ? Illustrations.ReceiptWrangler : undefined}
headerContent={!shouldUseNarrowLayout && getHeaderButtons()}
testID={WorkspaceMembersPage.displayName}
shouldShowLoading={false}
shouldShowOfflineIndicatorInWideScreen
shouldShowThreeDotsButton={isPolicyAdmin}
threeDotsMenuItems={threeDotsMenuItems}
threeDotsAnchorPosition={styles.threeDotsPopoverOffsetNoCloseButton(windowWidth)}
shouldShowNonAdmin
onBackButtonPress={() => {
if (selectionMode?.isEnabled) {
setSelectedEmployees([]);
turnOffMobileSelectionMode();
return;
}
Navigation.goBack();
}}
>
{() => (
<>
{shouldUseNarrowLayout && <View style={[styles.pl5, styles.pr5]}>{getHeaderButtons()}</View>}
<ConfirmModal
isVisible={isOfflineModalVisible}
onConfirm={() => setIsOfflineModalVisible(false)}
title={translate('common.youAppearToBeOffline')}
prompt={translate('common.thisFeatureRequiresInternet')}
confirmText={translate('common.buttonConfirm')}
shouldShowCancelButton={false}
/>
<ConfirmModal
danger
title={translate('workspace.people.removeMembersTitle')}
isVisible={removeMembersConfirmModalVisible}
onConfirm={removeUsers}
onCancel={() => setRemoveMembersConfirmModalVisible(false)}
prompt={confirmModalPrompt}
confirmText={translate('common.remove')}
cancelText={translate('common.cancel')}
onModalHide={() => {
InteractionManager.runAfterInteractions(() => {
if (!textInputRef.current) {
return;
}
textInputRef.current.focus();
});
}}
/>
<DecisionModal
title={translate('common.downloadFailedTitle')}
prompt={translate('common.downloadFailedDescription')}
isSmallScreenWidth={isSmallScreenWidth}
onSecondOptionSubmit={() => setIsDownloadFailureModalVisible(false)}
secondOptionText={translate('common.buttonConfirm')}
isVisible={isDownloadFailureModalVisible}
onClose={() => setIsDownloadFailureModalVisible(false)}
/>
<View style={[styles.w100, styles.flex1]}>
<SelectionListWithModal
ref={selectionListRef}
canSelectMultiple={canSelectMultiple}
sections={[{data, isDisabled: false}]}
ListItem={TableListItem}
turnOnSelectionModeOnLongPress={isPolicyAdmin}
onTurnOnSelectionMode={(item) => item && toggleUser(item?.accountID)}
shouldUseUserSkeletonView
disableKeyboardShortcuts={removeMembersConfirmModalVisible}
headerMessage={getHeaderMessage()}
headerContent={!shouldUseNarrowLayout && getHeaderContent()}
onSelectRow={openMemberDetails}
shouldSingleExecuteRowSelect={!isPolicyAdmin}
onCheckboxPress={(item) => toggleUser(item.accountID)}
onSelectAll={() => toggleAllUsers(data)}
onDismissError={dismissError}
showLoadingPlaceholder={isLoading}
shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
textInputRef={textInputRef}
customListHeader={getCustomListHeader()}
listHeaderWrapperStyle={[styles.ph9, styles.pv3, styles.pb5]}
listHeaderContent={shouldUseNarrowLayout ? <View style={[styles.pr5]}>{getHeaderContent()}</View> : null}
showScrollIndicator={false}
/>
</View>
</>
)}
</WorkspacePageWithSections>
);
}
WorkspaceMembersPage.displayName = 'WorkspaceMembersPage';
export default withCurrentUserPersonalDetails(withPolicyAndFullscreenLoading(WorkspaceMembersPage));