Debian Codegraph @

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