Debian Codegraph @

install/freeipa-webui/src/pages/UserGroups/UserGroups.tsx

raw
1 import React, { useEffect, useState } from "react";
2 // PatternFly
3 import {
4 Flex,
5 FlexItem,
6 PageSection,
7 PaginationVariant,
8 ToolbarItemVariant,
9 } from "@patternfly/react-core";
10 import {
11 InnerScrollContainer,
12 OuterScrollContainer,
13 } from "@patternfly/react-table";
14 // Layouts
15 import TitleLayout from "src/components/layouts/TitleLayout";
16 import ToolbarLayout, {
17 ToolbarItem,
18 } from "src/components/layouts/ToolbarLayout";
19 import SearchInputLayout from "src/components/layouts/SearchInputLayout";
20 import SecondaryButton from "src/components/layouts/SecondaryButton";
21 import HelpTextWithIconLayout from "src/components/layouts/HelpTextWithIconLayout";
22 // Components
23 import BulkSelectorPrep from "src/components/BulkSelectorPrep";
24 import PaginationLayout from "src/components/layouts/PaginationLayout";
25 // Tables
26 import UserGroupsTable from "./UserGroupsTable";
27 // Modal
28 import AddUserGroup from "src/components/modals/AddUserGroup";
29 import DeleteUserGroups from "src/components/modals/DeleteUserGroups";
30 // Redux
31 import { useAppSelector } from "src/store/hooks";
32 // Data types
33 import { UserGroup } from "src/utils/datatypes/globalDataTypes";
34 // Utils
35 import { API_VERSION_BACKUP, isUserGroupSelectable } from "src/utils/utils";
36 // Redux
37 import { useAppDispatch } from "src/store/hooks";
38 // Hooks
39 import { addAlert } from "src/store/Global/alerts-slice";
40 import useUpdateRoute from "src/hooks/useUpdateRoute";
41 import useListPageSearchParams from "src/hooks/useListPageSearchParams";
42 // Errors
43 import { FetchBaseQueryError } from "@reduxjs/toolkit/query";
44 import { SerializedError } from "@reduxjs/toolkit";
45 import useApiError from "src/hooks/useApiError";
46 import GlobalErrors from "src/components/errors/GlobalErrors";
47 import ModalErrors from "src/components/errors/ModalErrors";
48 // RPC client
49 import { GenericPayload, useSearchEntriesMutation } from "../../services/rpc";
50 import { useGettingGroupsQuery } from "../../services/rpcUserGroups";
51
52 const UserGroups = () => {
53 // Update current route data to Redux and highlight the current page in the Nav bar
54 const { browserTitle } = useUpdateRoute({ pathname: "user-groups" });
55
56 const dispatch = useAppDispatch();
57
58 // Set the page title to be shown in the browser tab
59 React.useEffect(() => {
60 document.title = browserTitle;
61 }, [browserTitle]);
62
63 // Retrieve API version from environment data
64 const apiVersion = useAppSelector(
65 (state) => state.global.environment.api_version
66 ) as string;
67
68 // Initialize groups list (Redux)
69 const [groupsList, setGroupsList] = useState<UserGroup[]>([]);
70
71 // URL parameters: page number, page size, search value
72 const { page, setPage, perPage, setPerPage, searchValue, setSearchValue } =
73 useListPageSearchParams();
74
75 // Handle API calls errors
76 const globalErrors = useApiError([]);
77 const modalErrors = useApiError([]);
78
79 // Table comps
80 const [selectedPerPage, setSelectedPerPage] = useState<number>(0);
81 const [totalCount, setGroupsTotalCount] = useState<number>(0);
82 const [searchDisabled, setSearchIsDisabled] = useState<boolean>(false);
83
84 const updateSelectedPerPage = (selected: number) => {
85 setSelectedPerPage(selected);
86 };
87 const updatePage = (newPage: number) => {
88 setPage(newPage);
89 };
90 const updatePerPage = (newSetPerPage: number) => {
91 setPerPage(newSetPerPage);
92 };
93
94 // 'Delete' button state
95 const [isDeleteButtonDisabled, setIsDeleteButtonDisabled] =
96 useState<boolean>(true);
97
98 const updateIsDeleteButtonDisabled = (value: boolean) => {
99 setIsDeleteButtonDisabled(value);
100 };
101
102 // If some entries have been deleted, restore the selectedGroups list
103 const [isDeletion, setIsDeletion] = useState(false);
104
105 const updateIsDeletion = (value: boolean) => {
106 setIsDeletion(value);
107 };
108
109 const updateShownGroupsList = (newShownGroupsList: UserGroup[]) => {
110 setGroupsList(newShownGroupsList);
111 };
112
113 // Page indexes
114 const firstIdx = (page - 1) * perPage;
115 const lastIdx = page * perPage;
116
117 // Derived states - what we get from API
118 const groupDataResponse = useGettingGroupsQuery({
119 searchValue: searchValue,
120 sizeLimit: 0,
121 apiVersion: apiVersion || API_VERSION_BACKUP,
122 startIdx: firstIdx,
123 stopIdx: lastIdx,
124 } as GenericPayload);
125
126 const {
127 data: batchResponse,
128 isLoading: isBatchLoading,
129 error: batchError,
130 } = groupDataResponse;
131
132 // Handle data when the API call is finished
133 useEffect(() => {
134 if (groupDataResponse.isFetching) {
135 setShowTableRows(false);
136 // Reset selected user groups on refresh
137 setGroupsTotalCount(0);
138 globalErrors.clear();
139 return;
140 }
141
142 // API response: Success
143 if (
144 groupDataResponse.isSuccess &&
145 groupDataResponse.data &&
146 batchResponse !== undefined
147 ) {
148 const groupsListResult = batchResponse.result.results;
149 const totalCount = batchResponse.result.totalCount;
150 const groupsListSize = batchResponse.result.count;
151 const groupsList: UserGroup[] = [];
152
153 for (let i = 0; i < groupsListSize; i++) {
154 groupsList.push(groupsListResult[i].result);
155 }
156
157 // Update 'Groups' slice data
158 setGroupsList(groupsList);
159 setGroupsTotalCount(totalCount);
160 // Show table elements
161 setShowTableRows(true);
162 }
163
164 // API response: Error
165 if (
166 !groupDataResponse.isLoading &&
167 groupDataResponse.isError &&
168 groupDataResponse.error !== undefined
169 ) {
170 // This normally happens when the user is not authorized to view the data
171 // So instead of adding an error, refresh page
172 window.location.reload();
173 }
174 }, [groupDataResponse]);
175
176 // Always refetch data when the page changes
177 useEffect(() => {
178 groupDataResponse.refetch();
179 }, [page, perPage]);
180
181 // Refresh button handling
182 const refreshGroupsData = () => {
183 // Hide table
184 setShowTableRows(false);
185
186 // Reset selected user groups on refresh
187 setGroupsTotalCount(0);
188 clearSelectedGroups();
189 setPage(1);
190 groupDataResponse.refetch();
191 };
192
193 const updateSearchValue = (value: string) => {
194 setSearchValue(value);
195 };
196
197 const [selectedGroups, setSelectedGroupsList] = useState<UserGroup[]>([]);
198 const clearSelectedGroups = () => {
199 const emptyList: UserGroup[] = [];
200 setSelectedGroupsList(emptyList);
201 };
202
203 const [retrieveGroup] = useSearchEntriesMutation({});
204
205 // Issue a search using a specific search value
206 const submitSearchValue = () => {
207 setShowTableRows(false);
208 setGroupsTotalCount(0);
209 setSearchIsDisabled(true);
210 retrieveGroup({
211 searchValue: searchValue,
212 sizeLimit: 0,
213 apiVersion: apiVersion || API_VERSION_BACKUP,
214 startIdx: firstIdx,
215 stopIdx: lastIdx,
216 entryType: "usergroup",
217 } as GenericPayload).then((result) => {
218 // Manage new response here
219 if ("data" in result) {
220 const searchError = result.data?.error as
221 | FetchBaseQueryError
222 | SerializedError;
223
224 if (searchError) {
225 // Error
226 let error: string | undefined = "";
227 if ("error" in searchError) {
228 error = searchError.error;
229 } else if ("message" in searchError) {
230 error = searchError.message;
231 }
232 dispatch(
233 addAlert({
234 name: "submit-search-value-error",
235 title: error || "Error when searching for user groups",
236 variant: "danger",
237 })
238 );
239 } else {
240 // Success
241 const groupsListResult = result.data?.result.results || [];
242 const groupsListSize = result.data?.result.count || 0;
243 const totalCount = result.data?.result.totalCount || 0;
244 const groupsList: UserGroup[] = [];
245
246 for (let i = 0; i < groupsListSize; i++) {
247 groupsList.push(groupsListResult[i].result);
248 }
249
250 // Update 'user groups' slice data
251 setPage(1);
252 setGroupsList(groupsList);
253 setGroupsTotalCount(totalCount);
254 // Show table elements
255 setShowTableRows(true);
256 }
257 setSearchIsDisabled(false);
258 }
259 });
260 };
261
262 // Show table rows
263 const [showTableRows, setShowTableRows] = useState(!isBatchLoading);
264
265 const updateSelectedGroups = (groups: UserGroup[], isSelected: boolean) => {
266 let newSelectedGroups: UserGroup[] = [];
267 if (isSelected) {
268 newSelectedGroups = JSON.parse(JSON.stringify(selectedGroups));
269 for (let i = 0; i < groups.length; i++) {
270 if (
271 selectedGroups.find(
272 (selectedGroup) => selectedGroup.cn[0] === groups[i].cn[0]
273 )
274 ) {
275 // Already in the list
276 continue;
277 }
278 // Add user to list
279 newSelectedGroups.push(groups[i]);
280 }
281 } else {
282 // Remove user
283 for (let i = 0; i < selectedGroups.length; i++) {
284 let found = false;
285 for (let ii = 0; ii < groups.length; ii++) {
286 if (selectedGroups[i].cn[0] === groups[ii].cn[0]) {
287 found = true;
288 break;
289 }
290 }
291 if (!found) {
292 // Keep this valid selected entry
293 newSelectedGroups.push(selectedGroups[i]);
294 }
295 }
296 }
297 setSelectedGroupsList(newSelectedGroups);
298 setIsDeleteButtonDisabled(newSelectedGroups.length === 0);
299 };
300
301 // - Helper method to set the selected users from the table
302 const setGroupSelected = (group: UserGroup, isSelecting = true) => {
303 if (isUserGroupSelectable(group)) {
304 updateSelectedGroups([group], isSelecting);
305 }
306 };
307
308 // Show table rows only when data is fully retrieved
309 useEffect(() => {
310 if (showTableRows !== !isBatchLoading) {
311 setShowTableRows(!isBatchLoading);
312 }
313 }, [isBatchLoading]);
314
315 // Modals functionality
316 const [showAddModal, setShowAddModal] = useState(false);
317 const [showDeleteModal, setShowDeleteModal] = useState(false);
318
319 const onAddClickHandler = () => {
320 setShowAddModal(true);
321 };
322 const onCloseAddModal = () => {
323 setShowAddModal(false);
324 };
325 const onAddModalToggle = () => {
326 setShowAddModal(!showAddModal);
327 };
328
329 const onDeleteHandler = () => {
330 setShowDeleteModal(true);
331 };
332 const onDeleteModalToggle = () => {
333 setShowDeleteModal(!showDeleteModal);
334 };
335
336 // Table-related shared functionality
337 // - Selectable checkboxes on table
338 const selectableGroupsTable = groupsList.filter(isUserGroupSelectable); // elements per Table
339
340 // Data wrappers
341 // - 'PaginationLayout'
342 const paginationData = {
343 page,
344 perPage,
345 updatePage,
346 updatePerPage,
347 updateSelectedPerPage,
348 updateShownElementsList: updateShownGroupsList,
349 totalCount,
350 };
351
352 // - 'BulkSelectorPrep'
353 const groupsBulkSelectorData = {
354 selected: selectedGroups,
355 updateSelected: updateSelectedGroups,
356 selectableTable: selectableGroupsTable,
357 nameAttr: "cn",
358 };
359
360 const buttonsData = {
361 updateIsDeleteButtonDisabled,
362 };
363
364 const selectedPerPageData = {
365 selectedPerPage,
366 updateSelectedPerPage,
367 };
368
369 // - 'DeleteGroups'
370 const deleteGroupsButtonsData = {
371 updateIsDeleteButtonDisabled,
372 updateIsDeletion,
373 };
374
375 const selectedGroupsData = {
376 selectedGroups,
377 clearSelectedGroups,
378 };
379
380 // - 'UserGroupsTable'
381 const groupsTableData = {
382 isUserGroupSelectable,
383 selectedGroups,
384 selectableGroupsTable,
385 setGroupSelected,
386 clearSelectedGroups,
387 };
388
389 const groupsTableButtonsData = {
390 updateIsDeleteButtonDisabled,
391 isDeletion,
392 updateIsDeletion,
393 };
394
395 // - 'SearchInputLayout'
396 const searchValueData = {
397 searchValue,
398 updateSearchValue,
399 submitSearchValue,
400 };
401
402 // List of toolbar items
403 const toolbarItems: ToolbarItem[] = [
404 {
405 key: 0,
406 element: (
407 <BulkSelectorPrep
408 list={groupsList}
409 shownElementsList={groupsList}
410 elementData={groupsBulkSelectorData}
411 buttonsData={buttonsData}
412 selectedPerPageData={selectedPerPageData}
413 />
414 ),
415 },
416 {
417 key: 1,
418 element: (
419 <SearchInputLayout
420 dataCy="search"
421 name="search"
422 ariaLabel="Search user groups"
423 placeholder="Search"
424 searchValueData={searchValueData}
425 isDisabled={searchDisabled}
426 />
427 ),
428 toolbarItemVariant: ToolbarItemVariant.label,
429 toolbarItemGap: { default: "gapMd" },
430 },
431 {
432 key: 2,
433 toolbarItemVariant: ToolbarItemVariant.separator,
434 },
435 {
436 key: 3,
437 element: (
438 <SecondaryButton
439 onClickHandler={refreshGroupsData}
440 isDisabled={!showTableRows}
441 dataCy="user-groups-button-refresh"
442 >
443 Refresh
444 </SecondaryButton>
445 ),
446 },
447 {
448 key: 4,
449 element: (
450 <SecondaryButton
451 isDisabled={isDeleteButtonDisabled || !showTableRows}
452 onClickHandler={onDeleteHandler}
453 dataCy="user-groups-button-delete"
454 >
455 Delete
456 </SecondaryButton>
457 ),
458 },
459 {
460 key: 5,
461 element: (
462 <SecondaryButton
463 onClickHandler={onAddClickHandler}
464 isDisabled={!showTableRows}
465 dataCy="user-groups-button-add"
466 >
467 Add
468 </SecondaryButton>
469 ),
470 },
471 {
472 key: 6,
473 toolbarItemVariant: ToolbarItemVariant.separator,
474 },
475 {
476 key: 7,
477 element: <HelpTextWithIconLayout textContent="Help" />,
478 },
479 {
480 key: 8,
481 element: (
482 <PaginationLayout
483 list={groupsList}
484 paginationData={paginationData}
485 widgetId="pagination-options-menu-top"
486 isCompact={true}
487 />
488 ),
489 toolbarItemAlignment: { default: "alignEnd" },
490 },
491 ];
492
493 return (
494 <div>
495 <PageSection hasBodyWrapper={false}>
496 <TitleLayout id="Groups title" headingLevel="h1" text="User groups" />
497 </PageSection>
498 <PageSection hasBodyWrapper={false} isFilled={false}>
499 <Flex direction={{ default: "column" }}>
500 <FlexItem>
501 <ToolbarLayout toolbarItems={toolbarItems} />
502 </FlexItem>
503 <FlexItem style={{ flex: "0 0 auto" }}>
504 <OuterScrollContainer>
505 <InnerScrollContainer
506 style={{ height: "60vh", overflow: "auto" }}
507 >
508 {batchError !== undefined && batchError ? (
509 <GlobalErrors errors={globalErrors.getAll()} />
510 ) : (
511 <UserGroupsTable
512 elementsList={groupsList}
513 shownElementsList={groupsList}
514 showTableRows={showTableRows}
515 groupsData={groupsTableData}
516 buttonsData={groupsTableButtonsData}
517 paginationData={selectedPerPageData}
518 searchValue={searchValue}
519 />
520 )}
521 </InnerScrollContainer>
522 </OuterScrollContainer>
523 </FlexItem>
524 <FlexItem style={{ flex: "0 0 auto", position: "sticky", bottom: 0 }}>
525 <PaginationLayout
526 list={groupsList}
527 paginationData={paginationData}
528 variant={PaginationVariant.bottom}
529 widgetId="pagination-options-menu-bottom"
530 />
531 </FlexItem>
532 </Flex>
533 </PageSection>
534 <ModalErrors
535 errors={modalErrors.getAll()}
536 dataCy="user-groups-modal-error"
537 />
538 <AddUserGroup
539 show={showAddModal}
540 handleModalToggle={onAddModalToggle}
541 onOpenAddModal={onAddClickHandler}
542 onCloseAddModal={onCloseAddModal}
543 onRefresh={refreshGroupsData}
544 />
545 <DeleteUserGroups
546 show={showDeleteModal}
547 handleModalToggle={onDeleteModalToggle}
548 selectedGroupsData={selectedGroupsData}
549 buttonsData={deleteGroupsButtonsData}
550 onRefresh={refreshGroupsData}
551 />
552 </div>
553 );
554 };
555
556 export default UserGroups;