Debian Codegraph @

install/freeipa-webui/src/pages/SudoCmds/SudoCmds.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 { SudoCmd } 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 SudoCmdsTable from "./SudoCmdsTable";
28 // Components
29 import PaginationLayout from "../../components/layouts/PaginationLayout";
30 import BulkSelectorPrep from "src/components/BulkSelectorPrep";
31 // Modals
32 import AddSudoCmd from "src/components/modals/SudoModals/AddSudoCmd";
33 import DeleteSudoCmd from "src/components/modals/SudoModals/DeleteSudoCmd";
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, isSudoCmdSelectable } from "src/utils/utils";
40 // RPC client
41 import { GenericPayload, useSearchEntriesMutation } from "src/services/rpc";
42 import { useGettingSudoCmdsQuery } from "src/services/rpcSudoCmds";
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-commands" });
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, setCmdsList] = useState<SudoCmd[]>([]);
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, setCmdsTotalCount] = 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 cmdsDataResponse = useGettingSudoCmdsQuery({
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 } = cmdsDataResponse;
96
97 // Handle data when the API call is finished
98 useEffect(() => {
99 if (cmdsDataResponse.isFetching) {
100 setShowTableRows(false);
101 // Reset selected entries on refresh
102 setCmdsTotalCount(0);
103 globalErrors.clear();
104 return;
105 }
106
107 // API response: Success
108 if (
109 cmdsDataResponse.isSuccess &&
110 cmdsDataResponse.data &&
111 batchResponse !== undefined
112 ) {
113 const cmdsListResult = batchResponse.result.results;
114 const totalCount = batchResponse.result.totalCount;
115 const cmdsListSize = batchResponse.result.count;
116 const cmdsList: SudoCmd[] = [];
117
118 for (let i = 0; i < cmdsListSize; i++) {
119 cmdsList.push(cmdsListResult[i].result);
120 }
121
122 setCmdsTotalCount(totalCount);
123 // Update the list
124 setCmdsList(cmdsList);
125 // Show table elements
126 setShowTableRows(true);
127 }
128
129 // API response: Error
130 if (
131 !cmdsDataResponse.isLoading &&
132 cmdsDataResponse.isError &&
133 cmdsDataResponse.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 }, [cmdsDataResponse]);
140
141 // Refresh button handling
142 const refreshData = () => {
143 // Hide table
144 setShowTableRows(false);
145 setCmdsTotalCount(0);
146 clearSelectedCmds();
147
148 cmdsDataResponse.refetch();
149 };
150
151 // Always refetch data when the component is loaded.
152 // This ensures the data is always up-to-date.
153 React.useEffect(() => {
154 cmdsDataResponse.refetch();
155 }, [page, perPage]);
156
157 // 'Delete' button state
158 const [isDeleteButtonDisabled, setIsDeleteButtonDisabled] =
159 useState<boolean>(true);
160
161 const updateIsDeleteButtonDisabled = (value: boolean) => {
162 setIsDeleteButtonDisabled(value);
163 };
164
165 // If some entries have been deleted, restore the selected list
166 const [isDeletion, setIsDeletion] = useState(false);
167
168 const updateIsDeletion = (value: boolean) => {
169 setIsDeletion(value);
170 };
171
172 // Elements selected (per page)
173 // - This will help to calculate the remaining elements on a specific page (bulk selector)
174 const [selectedPerPage, setSelectedPerPage] = useState<number>(0);
175
176 const updateSelectedPerPage = (selected: number) => {
177 setSelectedPerPage(selected);
178 };
179
180 // Pagination
181 const updatePage = (newPage: number) => {
182 setPage(newPage);
183 };
184
185 const updatePerPage = (newSetPerPage: number) => {
186 setPerPage(newSetPerPage);
187 };
188
189 // Commands displayed on the first page
190 const updateShownCmdsList = (newShownCmdsList: SudoCmd[]) => {
191 setCmdsList(newShownCmdsList);
192 };
193
194 // Update search input valie
195 const updateSearchValue = (value: string) => {
196 setSearchValue(value);
197 };
198
199 const [selectedCmds, setSelectedCmds] = useState<SudoCmd[]>([]);
200
201 const clearSelectedCmds = () => {
202 const emptyList: SudoCmd[] = [];
203 setSelectedCmds(emptyList);
204 };
205
206 const [retrieveCmds] = useSearchEntriesMutation({});
207
208 // Issue a search using a specific search value
209 const submitSearchValue = () => {
210 setShowTableRows(false);
211 setSearchIsDisabled(true);
212 setCmdsTotalCount(0);
213 retrieveCmds({
214 searchValue: searchValue,
215 sizeLimit: 0,
216 apiVersion: apiVersion || API_VERSION_BACKUP,
217 startIdx: firstIdx,
218 stopIdx: lastIdx,
219 entryType: "sudocmd",
220 } as GenericPayload).then((result) => {
221 // Manage new response here
222 if ("data" in result) {
223 const searchError = result.data?.error as
224 | FetchBaseQueryError
225 | SerializedError;
226
227 if (searchError) {
228 // Error
229 let error: string | undefined = "";
230 if ("error" in searchError) {
231 error = searchError.error;
232 } else if ("message" in searchError) {
233 error = searchError.message;
234 }
235 dispatch(
236 addAlert({
237 name: "submit-search-value-error",
238 title: error || "Error when searching for sudo commands",
239 variant: "danger",
240 })
241 );
242 } else {
243 // Success
244 const cmdsListResult = result.data?.result.results || [];
245 const cmdsListSize = result.data?.result.count || 0;
246 const totalCount = result.data?.result.totalCount || 0;
247 const cmdsList: SudoCmd[] = [];
248
249 for (let i = 0; i < cmdsListSize; i++) {
250 cmdsList.push(cmdsListResult[i].result);
251 }
252
253 setCmdsTotalCount(totalCount);
254 setCmdsList(cmdsList);
255 // Show table elements
256 setShowTableRows(true);
257 }
258 setSearchIsDisabled(false);
259 }
260 });
261 };
262
263 // Show table rows
264 const [showTableRows, setShowTableRows] = useState(!isBatchLoading);
265
266 // Show table rows only when data is fully retrieved
267 useEffect(() => {
268 if (showTableRows !== !isBatchLoading) {
269 setShowTableRows(!isBatchLoading);
270 }
271 }, [isBatchLoading]);
272
273 // Modals functionality
274 const [showAddModal, setShowAddModal] = useState(false);
275 const [showDeleteModal, setShowDeleteModal] = useState(false);
276
277 const onAddClickHandler = () => {
278 setShowAddModal(true);
279 };
280
281 const onCloseAddModal = () => {
282 setShowAddModal(false);
283 };
284
285 const onAddModalToggle = () => {
286 setShowAddModal(!showAddModal);
287 };
288
289 const onDeleteHandler = () => {
290 setShowDeleteModal(true);
291 };
292
293 const onDeleteModalToggle = () => {
294 setShowDeleteModal(!showDeleteModal);
295 };
296
297 // Table-related shared functionality
298 // - Selectable checkboxes on table
299 const selectableCmdsTable = cmdList.filter(isSudoCmdSelectable); // elements per Table
300
301 const updateSelectedCmds = (cmds: SudoCmd[], isSelected: boolean) => {
302 let newSelectedCmds: SudoCmd[] = [];
303 if (isSelected) {
304 newSelectedCmds = JSON.parse(JSON.stringify(selectedCmds));
305 for (let i = 0; i < cmds.length; i++) {
306 if (
307 selectedCmds.find(
308 (selectedCmds) => selectedCmds.sudocmd[0] === cmds[i].sudocmd[0]
309 )
310 ) {
311 // Already in the list
312 continue;
313 }
314 // Add command to list
315 newSelectedCmds.push(cmds[i]);
316 }
317 } else {
318 // Remove entry
319 for (let i = 0; i < selectedCmds.length; i++) {
320 let found = false;
321 for (let ii = 0; ii < cmds.length; ii++) {
322 if (selectedCmds[i].sudocmd[0] === cmds[ii].sudocmd[0]) {
323 found = true;
324 break;
325 }
326 }
327 if (!found) {
328 // Keep this valid selected entry
329 newSelectedCmds.push(selectedCmds[i]);
330 }
331 }
332 }
333 setSelectedCmds(newSelectedCmds);
334 setIsDeleteButtonDisabled(newSelectedCmds.length === 0);
335 };
336
337 // - Helper method to set the selected entries from the table
338 const setCmdsSelected = (cmd: SudoCmd, isSelecting = true) => {
339 if (isSudoCmdSelectable(cmd)) {
340 updateSelectedCmds([cmd], isSelecting);
341 }
342 };
343
344 // Data wrappers
345 // - 'PaginationLayout'
346 const paginationData = {
347 page,
348 perPage,
349 updatePage,
350 updatePerPage,
351 updateSelectedPerPage,
352 updateShownElementsList: updateShownCmdsList,
353 totalCount,
354 };
355
356 // - 'BulkSelector'
357 const cmdsBulkSelectorData = {
358 selected: selectedCmds,
359 updateSelected: updateSelectedCmds,
360 selectableTable: selectableCmdsTable,
361 nameAttr: "sudocmd",
362 };
363
364 const buttonsData = {
365 updateIsDeleteButtonDisabled,
366 };
367
368 const selectedPerPageData = {
369 selectedPerPage,
370 updateSelectedPerPage,
371 };
372
373 // 'DeleteSudoCmds'
374 const deleteCmdsButtonsData = {
375 updateIsDeleteButtonDisabled,
376 updateIsDeletion,
377 };
378
379 const selectedCmdsData = {
380 selectedCmds,
381 clearSelectedCmds,
382 };
383
384 // 'SudoCmdsTable'
385 const cmdsTableData = {
386 isSudoCmdSelectable,
387 selectedCmds,
388 selectableCmdsTable,
389 setCmdsSelected,
390 clearSelectedCmds,
391 };
392
393 const cmdsTableButtonsData = {
394 updateIsDeleteButtonDisabled,
395 isDeletion,
396 updateIsDeletion,
397 };
398
399 // SearchInputLayout
400 const searchValueData = {
401 searchValue,
402 updateSearchValue,
403 submitSearchValue,
404 };
405
406 // List of Toolbar items
407 const toolbarItems: ToolbarItem[] = [
408 {
409 key: 0,
410 element: (
411 <BulkSelectorPrep
412 list={cmdList}
413 shownElementsList={cmdList}
414 elementData={cmdsBulkSelectorData}
415 buttonsData={buttonsData}
416 selectedPerPageData={selectedPerPageData}
417 />
418 ),
419 },
420 {
421 key: 1,
422 element: (
423 <SearchInputLayout
424 dataCy="search"
425 name="search"
426 ariaLabel="Search commands"
427 placeholder="Search"
428 searchValueData={searchValueData}
429 isDisabled={searchDisabled}
430 />
431 ),
432 toolbarItemVariant: ToolbarItemVariant.label,
433 toolbarItemGap: { default: "gapMd" },
434 },
435 {
436 key: 2,
437 toolbarItemVariant: ToolbarItemVariant.separator,
438 },
439 {
440 key: 3,
441 element: (
442 <SecondaryButton
443 onClickHandler={refreshData}
444 isDisabled={!showTableRows}
445 dataCy="sudo-commands-button-refresh"
446 >
447 Refresh
448 </SecondaryButton>
449 ),
450 },
451 {
452 key: 4,
453 element: (
454 <SecondaryButton
455 isDisabled={isDeleteButtonDisabled || !showTableRows}
456 onClickHandler={onDeleteHandler}
457 dataCy="sudo-commands-button-delete"
458 >
459 Delete
460 </SecondaryButton>
461 ),
462 },
463 {
464 key: 5,
465 element: (
466 <SecondaryButton
467 onClickHandler={onAddClickHandler}
468 isDisabled={!showTableRows}
469 dataCy="sudo-commands-button-add"
470 >
471 Add
472 </SecondaryButton>
473 ),
474 },
475 {
476 key: 6,
477 toolbarItemVariant: ToolbarItemVariant.separator,
478 },
479 {
480 key: 7,
481 element: <HelpTextWithIconLayout textContent="Help" />,
482 },
483 {
484 key: 8,
485 element: (
486 <PaginationLayout
487 list={cmdList}
488 paginationData={paginationData}
489 widgetId="pagination-options-menu-top"
490 isCompact={true}
491 />
492 ),
493 toolbarItemAlignment: { default: "alignEnd" },
494 },
495 ];
496
497 return (
498 <div>
499 <PageSection hasBodyWrapper={false}>
500 <TitleLayout
501 id="sudocmd title"
502 headingLevel="h1"
503 text="Sudo commands"
504 />
505 </PageSection>
506 <PageSection hasBodyWrapper={false} isFilled={false}>
507 <Flex direction={{ default: "column" }}>
508 <FlexItem>
509 <ToolbarLayout toolbarItems={toolbarItems} />
510 </FlexItem>
511 <FlexItem style={{ flex: "0 0 auto" }}>
512 <OuterScrollContainer>
513 <InnerScrollContainer
514 style={{ height: "60vh", overflow: "auto" }}
515 >
516 {batchError !== undefined && batchError ? (
517 <GlobalErrors errors={globalErrors.getAll()} />
518 ) : (
519 <SudoCmdsTable
520 shownElementsList={cmdList}
521 showTableRows={showTableRows}
522 cmdsData={cmdsTableData}
523 buttonsData={cmdsTableButtonsData}
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={cmdList}
534 paginationData={paginationData}
535 variant={PaginationVariant.bottom}
536 widgetId="pagination-options-menu-bottom"
537 />
538 </FlexItem>
539 </Flex>
540 </PageSection>
541 <AddSudoCmd
542 show={showAddModal}
543 handleModalToggle={onAddModalToggle}
544 onOpenAddModal={onAddClickHandler}
545 onCloseAddModal={onCloseAddModal}
546 onRefresh={refreshData}
547 />
548 <DeleteSudoCmd
549 show={showDeleteModal}
550 handleModalToggle={onDeleteModalToggle}
551 selectedCmdsData={selectedCmdsData}
552 buttonsData={deleteCmdsButtonsData}
553 onRefresh={refreshData}
554 />
555 <ModalErrors
556 errors={modalErrors.getAll()}
557 dataCy="sudo-cmds-modal-error"
558 />
559 </div>
560 );
561 };
562
563 export default SudoCmds;