Debian Codegraph @

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