Debian Codegraph @

install/freeipa-webui/src/pages/IDViews/IDViewsAppliedTo.tsx

raw
1 import React, { useEffect, useState } from "react";
2 // PatternFly
3 import {
4 Button,
5 Dropdown,
6 DropdownItem,
7 DropdownList,
8 MenuToggle,
9 MenuToggleElement,
10 PageSection,
11 PaginationVariant,
12 SearchInput,
13 ToolbarItemVariant,
14 } from "@patternfly/react-core";
15 import {
16 InnerScrollContainer,
17 OuterScrollContainer,
18 } from "@patternfly/react-table";
19 // Layouts
20 import DualListLayout from "src/components/layouts/DualListLayout";
21 import ToolbarLayout, {
22 ToolbarItem,
23 } from "src/components/layouts/ToolbarLayout";
24 import HelpTextWithIconLayout from "src/components/layouts/HelpTextWithIconLayout";
25 // Components
26 import PaginationLayout from "src/components/layouts/PaginationLayout";
27 import MemberOfDeleteModal from "src/components/MemberOf/MemberOfDeleteModal";
28 // Tables
29 import IDViewsAppliedToTable from "src/pages/IDViews/IDViewsAppliedToTable";
30 import DeletedElementsTable from "src/components/tables/DeletedElementsTable";
31 // Utils
32 import { partialViewToView } from "src/utils/idViewUtils";
33 // Data types
34 import { IDView } from "src/utils/datatypes/globalDataTypes";
35 // Redux
36 import { useAppDispatch } from "src/store/hooks";
37 // Hooks
38 import { addAlert } from "src/store/Global/alerts-slice";
39 import useUpdateRoute from "src/hooks/useUpdateRoute";
40 import useListPageSearchParams from "src/hooks/useListPageSearchParams";
41 // Errors
42 import useApiError from "src/hooks/useApiError";
43 import ModalErrors from "src/components/errors/ModalErrors";
44 // RPC client
45 import { ErrorResult } from "../../services/rpc";
46 import {
47 ViewApplyPayload,
48 useGetIDViewsFullDataQuery,
49 useApplyHostsMutation,
50 useApplyHostGroupsMutation,
51 useUnapplyHostsMutation,
52 useUnapplyHostgroupsMutation,
53 } from "../../services/rpcIDViews";
54 import TabLayout from "src/components/layouts/TabLayout";
55
56 interface AppliesToProps {
57 idView: IDView;
58 onRefresh: () => void;
59 }
60
61 const IDViewsAppliedTo = (props: AppliesToProps) => {
62 const dispatch = useAppDispatch();
63
64 // Update current route data to Redux and highlight the current page in the Nav bar
65 const { browserTitle } = useUpdateRoute({
66 pathname: "id-views",
67 noBreadcrumb: true,
68 });
69
70 // API
71 const [executeApplyHosts] = useApplyHostsMutation();
72 const [executeApplyHostgroups] = useApplyHostGroupsMutation();
73 const [executeUnapplyHosts] = useUnapplyHostsMutation();
74 const [executeUnapplyHostgroups] = useUnapplyHostgroupsMutation();
75
76 // Set the page title to be shown in the browser tab
77 React.useEffect(() => {
78 document.title = browserTitle;
79 }, [browserTitle]);
80
81 // Initialize views (Redux)
82 const [hostsList, setHostsList] = useState<string[]>([]);
83 const [shownHostsList, setShownHostsList] = useState<string[]>([]);
84
85 // URL parameters: page number, page size, search value
86 const { page, setPage, perPage, setPerPage, searchValue, setSearchValue } =
87 useListPageSearchParams();
88
89 // Handle API calls errors
90 const modalErrors = useApiError([]);
91
92 // Table comps
93 const [selectedPerPage, setSelectedPerPage] = useState<number>(0);
94 const [totalCount, setTotalCount] = useState<number>(0);
95
96 const updateSelectedPerPage = (selected: number) => {
97 setSelectedPerPage(selected);
98 };
99 const updatePage = (newPage: number) => {
100 setPage(newPage);
101 };
102 const updatePerPage = (newSetPerPage: number) => {
103 setPerPage(newSetPerPage);
104 };
105
106 // 'Delete' button state
107 const [isDeleteButtonDisabled, setIsDeleteButtonDisabled] =
108 useState<boolean>(true);
109
110 const updateIsUnapplyButtonDisabled = (value: boolean) => {
111 setIsDeleteButtonDisabled(value);
112 };
113
114 const [isUnapply, setIsUnapply] = useState(false);
115 const updateIsUnapply = (value: boolean) => {
116 setIsUnapply(value);
117 };
118
119 const updateShownHosts = (newShownHostsList: string[]) => {
120 setShownHostsList(newShownHostsList);
121 };
122
123 // Page indexes
124 const firstIdx = (page - 1) * perPage;
125 const lastIdx = page * perPage;
126
127 const idViewFullDataQuery = useGetIDViewsFullDataQuery(props.idView.cn);
128 const idViewFullData = idViewFullDataQuery.data;
129
130 useEffect(() => {
131 if (
132 idViewFullData &&
133 idViewFullData.idView &&
134 !idViewFullDataQuery.isFetching
135 ) {
136 const idView = partialViewToView(idViewFullData.idView);
137 const length = idView["appliedtohosts"].length;
138 const shownHosts: string[] = [];
139 for (let i = firstIdx; i < length && i < lastIdx; i++) {
140 shownHosts.push(idView["appliedtohosts"][i]);
141 }
142 setHostsList(idView["appliedtohosts"]);
143 setShownHostsList(shownHosts);
144 }
145 }, [idViewFullData, idViewFullDataQuery.isFetching]);
146
147 // Always refetch data when the component is loaded.
148 // This ensures the data is always up-to-date.
149 useEffect(() => {
150 idViewFullDataQuery.refetch();
151 }, [page, perPage]);
152
153 // Refresh button handling
154 const refreshViewsData = () => {
155 setTotalCount(0);
156 clearSelectedHosts();
157 setPage(1);
158 props.onRefresh();
159 };
160
161 const updateSearchValue = (value: string) => {
162 setSearchValue(value);
163 };
164
165 useEffect(() => {
166 const searchResults: string[] = [];
167 for (let i = 0; i < hostsList.length; i++) {
168 if (hostsList[i].toLowerCase().includes(searchValue.toLowerCase())) {
169 searchResults.push(hostsList[i]);
170 }
171 }
172 setShownHostsList(searchResults);
173 }, [searchValue]);
174
175 const [selectedHosts, setSelectedHosts] = useState<string[]>([]);
176 const clearSelectedHosts = () => {
177 const emptyList: string[] = [];
178 setSelectedHosts(emptyList);
179 };
180
181 // Unapply functions
182 const [showUnapplyHostsModal, setShowUnapplyHostsModal] = useState(false);
183 const [showUnapplyHostGroupModal, setShowUnapplyHostGroupModal] =
184 useState(false);
185 const [applySpinning, setApplySpinning] = useState(false);
186
187 const onUnapplyHosts = () => {
188 setApplySpinning(true);
189
190 // unapply views from hosts
191 executeUnapplyHosts(selectedHosts).then((response) => {
192 if ("data" in response) {
193 if (response.data?.result) {
194 const failed_response = response.data.result["failed"];
195 if (failed_response.memberhost.host.length > 0) {
196 const failed_hosts = failed_response.memberhost.host;
197 const failed_msgs: string[] = [];
198 for (let i = 0; i < failed_hosts.length; i++) {
199 failed_msgs.push(failed_hosts[i][0]);
200 }
201 const alert_msg = (
202 <>
203 ID View cannot be unapplied to IPA master
204 {failed_msgs.length > 1 ? "s" : ""}:
205 <ul>
206 {failed_msgs.map((item) => (
207 <li className="pf-v6-u-ml-sm" key={item}>
208 &#8226; {item}
209 </li>
210 ))}
211 </ul>
212 {response.data.result["completed"] > 0
213 ? "However " +
214 response.data.result["completed"] +
215 " hosts were unapplied"
216 : ""}
217 </>
218 );
219 dispatch(
220 addAlert({
221 name: "unapply-id-view-hosts-error",
222 title: alert_msg,
223 variant: "danger",
224 })
225 );
226 } else {
227 dispatch(
228 addAlert({
229 name: "unapply-id-view-hosts-success",
230 title:
231 "ID view unapplied from " +
232 response.data.result["completed"] +
233 " hosts",
234 variant: "success",
235 })
236 );
237 }
238 // Refresh data
239 refreshViewsData();
240 } else if (response.data?.error) {
241 // Show toast notification: error
242 const errorMessage = response.data.error as ErrorResult;
243 dispatch(
244 addAlert({
245 name: "unapply-id-view-hosts-error",
246 title:
247 "ID view unapplied from hosts failed: " + errorMessage.message,
248 variant: "danger",
249 })
250 );
251 }
252 }
253 setApplySpinning(false);
254 // Close Unapply modal
255 setShowUnapplyHostsModal(false);
256 });
257 };
258
259 const onUnapplyHostgroups = (hostGroups: string[]) => {
260 setApplySpinning(true);
261
262 // unapply views from host groups
263 executeUnapplyHostgroups(hostGroups).then((response) => {
264 if ("data" in response) {
265 if (response.data?.result) {
266 const failed_response = response.data.result["failed"];
267 if (failed_response.memberhost.host.length > 0) {
268 const failed_hosts = failed_response.memberhost.host;
269 const failed_msgs: string[] = [];
270 for (let i = 0; i < failed_hosts.length; i++) {
271 failed_msgs.push(failed_hosts[i][0]);
272 }
273 const alert_msg = (
274 <>
275 ID View cannot be unapplied to IPA master
276 {failed_msgs.length > 1 ? "s" : ""}:
277 <ul>
278 {failed_msgs.map((item) => (
279 <li className="pf-v6-u-ml-sm" key={item}>
280 &#8226; {item}
281 </li>
282 ))}
283 </ul>
284 {response.data.result["completed"] > 0
285 ? "However " +
286 response.data.result["completed"] +
287 " hosts were unapplied"
288 : ""}
289 </>
290 );
291 dispatch(
292 addAlert({
293 name: "unapply-id-view-host-groups-error",
294 title: alert_msg,
295 variant: "danger",
296 })
297 );
298 } else {
299 dispatch(
300 addAlert({
301 name: "unapply-id-view-hosts-success",
302 title:
303 "ID view unapplied from " +
304 response.data.result["completed"] +
305 " hosts",
306 variant: "success",
307 })
308 );
309 }
310 // Refresh data
311 refreshViewsData();
312 } else if (response.data?.error) {
313 // Show toast notification: error
314 const errorMessage = response.data.error as ErrorResult;
315 dispatch(
316 addAlert({
317 name: "unapply-id-view-hosts-error",
318 title:
319 "ID view unapplied from host groups failed: " +
320 errorMessage.message,
321 variant: "danger",
322 })
323 );
324 }
325 }
326 setApplySpinning(false);
327 // Close Unapply modal
328 setShowUnapplyHostGroupModal(false);
329 });
330 };
331
332 // Apply functions
333 const [showApplyHostModal, setShowApplyHostModal] = useState(false);
334 const [showApplyHostGroupModal, setShowApplyHostGroupModal] = useState(false);
335
336 const onApplyHosts = (hosts: string[]) => {
337 setApplySpinning(true);
338
339 const payload = {
340 viewName: props.idView.cn,
341 items: hosts,
342 } as ViewApplyPayload;
343
344 // Apply views to hosts
345 executeApplyHosts(payload).then((response) => {
346 if ("data" in response) {
347 if (response.data?.result) {
348 const failed_response = response.data.result["failed"];
349 if (failed_response.memberhost.host.length > 0) {
350 const failed_hosts = failed_response.memberhost.host;
351 const failed_msgs: string[] = [];
352 for (let i = 0; i < failed_hosts.length; i++) {
353 failed_msgs.push(failed_hosts[i][0]);
354 }
355 const alert_msg = (
356 <>
357 ID View cannot be applied to IPA master
358 {failed_msgs.length > 1 ? "s" : ""}:
359 <ul>
360 {failed_msgs.map((item) => (
361 <li className="pf-v6-u-ml-sm" key={item}>
362 &#8226; {item}
363 </li>
364 ))}
365 </ul>
366 {response.data?.result["completed"] > 0
367 ? "However " +
368 response.data?.result["completed"] +
369 " hosts were applied"
370 : ""}
371 </>
372 );
373 dispatch(
374 addAlert({
375 name: "apply-id-view-hosts-error",
376 title: alert_msg,
377 variant: "danger",
378 })
379 );
380 } else {
381 dispatch(
382 addAlert({
383 name: "apply-id-view-hosts-success",
384 title:
385 "ID view applied to " +
386 response.data?.result["completed"] +
387 " hosts",
388 variant: "success",
389 })
390 );
391 }
392 // Refresh data
393 refreshViewsData();
394 } else if (response.data?.error) {
395 // Show toast notification: error
396 const errorMessage = response.data.error as ErrorResult;
397 dispatch(
398 addAlert({
399 name: "apply-id-view-hosts-error",
400 title: "ID view applied to hosts failed: " + errorMessage.message,
401 variant: "danger",
402 })
403 );
404 }
405 }
406 setApplySpinning(false);
407 // Close Apply modal
408 setShowApplyHostModal(false);
409 });
410 };
411
412 const onApplyHostGroups = (hostGroups: string[]) => {
413 setApplySpinning(true);
414
415 const payload = {
416 viewName: props.idView.cn,
417 items: hostGroups,
418 } as ViewApplyPayload;
419
420 // Apply views to host groups
421 executeApplyHostgroups(payload).then((response) => {
422 if ("data" in response) {
423 if (response.data?.result) {
424 const failed_response = response.data.result["failed"];
425 if (failed_response.memberhost.host.length > 0) {
426 const failed_hosts = failed_response.memberhost.host;
427 const failed_msgs: string[] = [];
428 for (let i = 0; i < failed_hosts.length; i++) {
429 failed_msgs.push(failed_hosts[i][0]);
430 }
431 const alert_msg = (
432 <>
433 ID View cannot be applied to IPA master
434 {failed_msgs.length > 1 ? "s" : ""}:
435 <ul>
436 {failed_msgs.map((item) => (
437 <li className="pf-v6-u-ml-sm" key={item}>
438 &#8226; {item}
439 </li>
440 ))}
441 </ul>
442 {response.data.result["completed"] > 0
443 ? "However " +
444 response.data.result["completed"] +
445 " hosts were applied"
446 : ""}
447 </>
448 );
449 dispatch(
450 addAlert({
451 name: "apply-id-view-hosts-error",
452 title: alert_msg,
453 variant: "danger",
454 })
455 );
456 } else {
457 dispatch(
458 addAlert({
459 name: "apply-id-view-host-groups-success",
460 title:
461 "ID view applied to " +
462 response.data.result["completed"] +
463 " hosts",
464 variant: "success",
465 })
466 );
467 }
468 // Refresh data
469 refreshViewsData();
470 } else if (response.data?.error) {
471 // Show toast notification: error
472 const errorMessage = response.data.error as ErrorResult;
473 dispatch(
474 addAlert({
475 name: "apply-id-view-host-groups-error",
476 title:
477 "ID view applied to host groups failed: " +
478 errorMessage.message,
479 variant: "danger",
480 })
481 );
482 }
483 }
484 setApplySpinning(false);
485 // Close Apply modal
486 setShowApplyHostGroupModal(false);
487 });
488 };
489
490 // Data wrappers
491 // - 'PaginationLayout'
492 const paginationData = {
493 page,
494 perPage,
495 updatePage,
496 updatePerPage,
497 updateSelectedPerPage,
498 updateShownElementsList: updateShownHosts,
499 totalCount,
500 };
501
502 const selectedPerPageData = {
503 selectedPerPage,
504 updateSelectedPerPage,
505 };
506
507 const hostsTableData = {
508 selectedHosts,
509 hostsList,
510 setSelectedHosts,
511 clearSelectedHosts,
512 };
513
514 const viewsTableButtonsData = {
515 updateIsUnapplyButtonDisabled,
516 isUnapply,
517 updateIsUnapply,
518 };
519
520 // Dropdown select feature
521 const [isApplyOpen, setIsApplyOpen] = React.useState(false);
522 const onToggleClickApply = () => {
523 setIsApplyOpen(!isApplyOpen);
524 };
525 const onSelectApply = () => {
526 setIsApplyOpen(false);
527 };
528
529 const [isUnapplyOpen, setIsUnapplyOpen] = React.useState(false);
530 const onToggleClickUnapply = () => {
531 setIsUnapplyOpen(!isUnapplyOpen);
532 };
533 const onSelectUnapply = () => {
534 setIsUnapplyOpen(false);
535 };
536
537 // List of toolbar items
538 const toolbarItems: ToolbarItem[] = [
539 {
540 key: 1,
541 element: (
542 <SearchInput
543 data-cy="search"
544 name="search"
545 placeholder="Search hosts"
546 value={searchValue}
547 onChange={(_event, value) => updateSearchValue(value)}
548 onClear={() => setSearchValue("")}
549 />
550 ),
551 toolbarItemVariant: ToolbarItemVariant.label,
552 toolbarItemGap: { default: "gapMd" },
553 },
554 {
555 key: 2,
556 toolbarItemVariant: ToolbarItemVariant.separator,
557 },
558 {
559 key: 3,
560 element: (
561 <Button
562 data-cy="id-views-tab-applied-to-refresh"
563 variant="secondary"
564 onClick={refreshViewsData}
565 >
566 Refresh
567 </Button>
568 ),
569 },
570 {
571 key: 4,
572 element: (
573 <Dropdown
574 data-cy="id-views-tab-applied-to-kebab"
575 isOpen={isApplyOpen}
576 onSelect={onSelectApply}
577 onOpenChange={(isApplyOpen: boolean) => setIsApplyOpen(isApplyOpen)}
578 toggle={(toggleRef: React.Ref<MenuToggleElement>) => (
579 <MenuToggle
580 data-cy="id-views-tab-applied-to-kebab-apply-toggle"
581 ref={toggleRef}
582 onClick={onToggleClickApply}
583 isExpanded={isApplyOpen}
584 variant="secondary"
585 >
586 Apply
587 </MenuToggle>
588 )}
589 ouiaId="ApplyDropdown"
590 shouldFocusToggleOnSelect
591 >
592 <DropdownList>
593 <DropdownItem
594 data-cy="id-views-tab-applied-to-kebab-apply-hosts"
595 value={1}
596 key="apply-hosts"
597 onClick={() => setShowApplyHostModal(true)}
598 >
599 Apply hosts
600 </DropdownItem>
601 <DropdownItem
602 data-cy="id-views-tab-applied-to-kebab-apply-host-groups"
603 value={2}
604 key="apply-host-groups"
605 onClick={() => setShowApplyHostGroupModal(true)}
606 >
607 Apply host groups
608 </DropdownItem>
609 </DropdownList>
610 </Dropdown>
611 ),
612 },
613 {
614 key: 5,
615 element: (
616 <Dropdown
617 data-cy="id-views-tab-applied-to-kebab-unapply"
618 isOpen={isUnapplyOpen}
619 onSelect={onSelectUnapply}
620 onOpenChange={(isUnapplyOpen: boolean) =>
621 setIsUnapplyOpen(isUnapplyOpen)
622 }
623 toggle={(toggleRef: React.Ref<MenuToggleElement>) => (
624 <MenuToggle
625 data-cy="id-views-tab-applied-to-kebab-unapply-toggle"
626 ref={toggleRef}
627 onClick={onToggleClickUnapply}
628 isExpanded={isUnapplyOpen}
629 variant="secondary"
630 >
631 Unapply
632 </MenuToggle>
633 )}
634 ouiaId="UnapplyDropdown"
635 shouldFocusToggleOnSelect
636 >
637 <DropdownList>
638 <DropdownItem
639 data-cy="id-views-tab-applied-to-kebab-unapply-hosts"
640 value={1}
641 key="unapply-hosts"
642 onClick={() => setShowUnapplyHostsModal(true)}
643 isDisabled={isDeleteButtonDisabled}
644 >
645 Unapply hosts
646 </DropdownItem>
647 <DropdownItem
648 data-cy="id-views-tab-applied-to-kebab-unapply-host-groups"
649 value={2}
650 key="unapply-host-groups"
651 onClick={() => setShowUnapplyHostGroupModal(true)}
652 >
653 Unapply host groups
654 </DropdownItem>
655 </DropdownList>
656 </Dropdown>
657 ),
658 },
659 {
660 key: 6,
661 toolbarItemVariant: ToolbarItemVariant.separator,
662 },
663 {
664 key: 7,
665 element: <HelpTextWithIconLayout textContent="Help" />,
666 },
667 {
668 key: 8,
669 element: (
670 <PaginationLayout
671 list={hostsList}
672 paginationData={paginationData}
673 widgetId="pagination-options-menu-top"
674 isCompact={true}
675 />
676 ),
677 toolbarItemAlignment: { default: "alignEnd" },
678 },
679 ];
680
681 return (
682 <div
683 style={{
684 height: `var(--subsettings-calc)`,
685 }}
686 >
687 <TabLayout id="override sections">
688 <PageSection hasBodyWrapper={false} isFilled={false}>
689 <ToolbarLayout toolbarItems={toolbarItems} />
690 <OuterScrollContainer>
691 <InnerScrollContainer>
692 <IDViewsAppliedToTable
693 hosts={hostsList}
694 shownHosts={shownHostsList}
695 hostsData={hostsTableData}
696 buttonsData={viewsTableButtonsData}
697 paginationData={selectedPerPageData}
698 />
699 </InnerScrollContainer>
700 </OuterScrollContainer>
701 <PaginationLayout
702 list={hostsList}
703 paginationData={paginationData}
704 variant={PaginationVariant.bottom}
705 widgetId="pagination-options-menu-bottom"
706 />
707 </PageSection>
708 <ModalErrors
709 errors={modalErrors.getAll()}
710 dataCy="id-views-tab-applied-to-modal-error"
711 />
712 <DualListLayout
713 entry={""}
714 target={"hostgroup"}
715 showModal={showUnapplyHostGroupModal}
716 onCloseModal={() => setShowUnapplyHostGroupModal(false)}
717 onOpenModal={() => setShowUnapplyHostGroupModal(true)}
718 tableElementsList={[]}
719 action={onUnapplyHostgroups}
720 title={"Un-apply ID Views from hosts of hostgroups"}
721 spinning={applySpinning}
722 addBtnName="Unapply"
723 addSpinningBtnName="Unapplying"
724 />
725 <DualListLayout
726 entry={""}
727 target={"host"}
728 showModal={showApplyHostModal}
729 onCloseModal={() => setShowApplyHostModal(false)}
730 onOpenModal={() => setShowApplyHostModal(true)}
731 tableElementsList={hostsList}
732 action={onApplyHosts}
733 title={"Apply ID view '" + props.idView.cn + "' on hosts"}
734 spinning={applySpinning}
735 addBtnName="Apply"
736 addSpinningBtnName="Applying"
737 />
738 <DualListLayout
739 entry={""}
740 target={"hostgroup"}
741 showModal={showApplyHostGroupModal}
742 onCloseModal={() => setShowApplyHostGroupModal(false)}
743 onOpenModal={() => setShowApplyHostGroupModal(true)}
744 tableElementsList={[]}
745 action={onApplyHostGroups}
746 title={
747 "Apply ID view '" + props.idView.cn + "' on hosts of host groups"
748 }
749 spinning={applySpinning}
750 addBtnName="Apply"
751 addSpinningBtnName="Applying"
752 />
753 {/* Delete confirmation modal - Unapply Hosts*/}
754 <MemberOfDeleteModal
755 showModal={showUnapplyHostsModal}
756 onCloseModal={() => setShowUnapplyHostsModal(false)}
757 title={"Un-apply ID view '" + props.idView.cn + "' from hosts"}
758 onDelete={onUnapplyHosts}
759 spinning={applySpinning}
760 >
761 <DeletedElementsTable
762 mode="passing_id"
763 elementsToDelete={selectedHosts}
764 columnNames={["Hosts"]}
765 elementType="Host"
766 idAttr="fqdn"
767 />
768 </MemberOfDeleteModal>
769 </TabLayout>
770 </div>
771 );
772 };
773
774 export default IDViewsAppliedTo;