From fed64919fabd99c114e12c2b7c3cf6bf301212f6 Mon Sep 17 00:00:00 2001
From: Johanna Szepanski <johanna.szepanski@softhouse.se>
Date: Wed, 4 Dec 2024 10:27:05 +0100
Subject: [PATCH] removed all two way and unneccessary dependencies between
 details view and management view

---
 src/components/IOC/IOCManage/IOCManage.jsx    | 85 ++++-------------
 .../{IOCService => IOCManage}/IOCService.jsx  | 73 +++------------
 src/components/IOC/IOCService/index.js        |  4 -
 .../IOCUndeployDialog/IOCUndeployDialog.jsx   | 18 ++--
 .../IOC/UndeployIOC/UndeployIOC.jsx           | 48 ++++------
 src/views/IOC/IOCDetailsView.jsx              | 91 ++-----------------
 6 files changed, 62 insertions(+), 257 deletions(-)
 rename src/components/IOC/{IOCService => IOCManage}/IOCService.jsx (75%)
 delete mode 100644 src/components/IOC/IOCService/index.js

diff --git a/src/components/IOC/IOCManage/IOCManage.jsx b/src/components/IOC/IOCManage/IOCManage.jsx
index 5a4a8bfc..c0557e3e 100644
--- a/src/components/IOC/IOCManage/IOCManage.jsx
+++ b/src/components/IOC/IOCManage/IOCManage.jsx
@@ -1,59 +1,27 @@
 import { Button, Stack, Tooltip } from "@mui/material";
-import { useState, useEffect, useContext, useCallback, useMemo } from "react";
-import {
-  userContext,
-  useAPIMethod,
-  ExternalLink,
-  InternalLink
-} from "@ess-ics/ce-ui-common";
+import { useState, useEffect, useContext, useCallback } from "react";
+import { userContext, ExternalLink, InternalLink } from "@ess-ics/ce-ui-common";
 import { JobSection } from "./JobSection";
+import { IOCService } from "./IOCService";
 import { IOCDetails } from "../IOCDetails";
 import { DeployIOC } from "../DeployIOC";
 import { UndeployIOC } from "../UndeployIOC";
 import { AccessControl } from "../../auth/AccessControl";
 import { DeploymentStatus } from "../../../api/DataTypes";
-import { IOCService } from "../IOCService";
-import { apiContext } from "../../../api/DeployApi";
+import { useLazyFetchJobStatusQuery } from "../../../store/deployApi";
 import env from "../../../config/env";
 
-export function IOCManage({
-  ioc,
-  buttonDisabled,
-  currentCommand,
-  getJobs,
-  setButtonDisabled,
-  pagination
-}) {
+export const IOCManage = ({ ioc }) => {
   const { user } = useContext(userContext);
-  const client = useContext(apiContext);
-
   const [deployDialogOpen, setDeployDialogOpen] = useState(false);
   const [undeployDialogOpen, setUndeployDialogOpen] = useState(false);
-
-  const jobStatusParams = useMemo(
-    () => ({ awx_job_id: ioc.activeDeployment?.jobId }),
-    [ioc]
-  );
-
-  const { value: deploymentJob, wrapper: callGetJobDetails } = useAPIMethod({
-    fcn: client.apis.Jobs.fetchJobStatus,
-    call: false,
-    params: jobStatusParams
-  });
+  const [getjobStatus, { data: jobStatus }] = useLazyFetchJobStatusQuery();
 
   useEffect(() => {
     if (ioc.activeDeployment?.jobId) {
-      callGetJobDetails(ioc.activeDeployment?.jobId);
+      getjobStatus({ awxJobId: ioc.activeDeployment?.jobId });
     }
-  }, [callGetJobDetails, ioc.activeDeployment?.jobId]);
-
-  const closeDeployModal = () => {
-    setDeployDialogOpen(false);
-  };
-
-  const closeUndeployModal = () => {
-    setUndeployDialogOpen(false);
-  };
+  }, [getjobStatus, ioc.activeDeployment?.jobId]);
 
   const getSubset = useCallback(
     (ioc) => {
@@ -63,7 +31,7 @@ export function IOCManage({
       // Show START/STOP components only when IOC was deployed SUCCESSFULLY
       const deploymentStatus = new DeploymentStatus(
         ioc.activeDeployment,
-        deploymentJob
+        jobStatus
       );
       const showControls = deploymentStatus.wasSuccessful();
 
@@ -96,16 +64,7 @@ export function IOCManage({
 
       if (user) {
         subset["IOC Service Controls"] = showControls ? (
-          <IOCService
-            {...{
-              ioc,
-              currentCommand,
-              getJobs,
-              buttonDisabled,
-              setButtonDisabled,
-              jobLazyParams: pagination
-            }}
-          />
+          <IOCService {...{ ioc }} />
         ) : (
           "IOC is not currently deployed"
         );
@@ -113,15 +72,7 @@ export function IOCManage({
 
       return subset;
     },
-    [
-      buttonDisabled,
-      pagination,
-      currentCommand,
-      deploymentJob,
-      getJobs,
-      setButtonDisabled,
-      user
-    ]
+    [jobStatus, user]
   );
 
   if (ioc) {
@@ -145,13 +96,13 @@ export function IOCManage({
     }
 
     let disabledDebployButtonTitle = "";
-    if (buttonDisabled || ioc.operationInProgress) {
+    if (ioc.operationInProgress) {
       disabledDebployButtonTitle =
         "There is an ongoing operation, you can not deploy the IOC right now";
     }
 
     let disabledUndeployButtonTitle = "";
-    if (buttonDisabled || ioc.operationInProgress) {
+    if (ioc.operationInProgress) {
       disabledUndeployButtonTitle =
         "There is an ongoing operation, you can not undeploy the IOC right now";
     }
@@ -207,19 +158,15 @@ export function IOCManage({
           <DeployIOC
             open={deployDialogOpen}
             setOpen={setDeployDialogOpen}
-            submitCallback={closeDeployModal}
+            submitCallback={() => setDeployDialogOpen(false)}
             deployIocFormDefaults={deployIocFormDefaults}
             ioc={ioc}
             hasActiveDeployment={Boolean(ioc.activeDeployment)}
-            buttonDisabled={buttonDisabled}
-            setButtonDisabled={setButtonDisabled}
           />
           <UndeployIOC
             open={undeployDialogOpen}
             setOpen={setUndeployDialogOpen}
-            submitCallback={closeUndeployModal}
-            buttonDisabled={buttonDisabled}
-            setButtonDisabled={setButtonDisabled}
+            submitCallback={() => setUndeployDialogOpen(false)}
             ioc={ioc}
           />
         </AccessControl>
@@ -227,4 +174,4 @@ export function IOCManage({
     );
   }
   return null;
-}
+};
diff --git a/src/components/IOC/IOCService/IOCService.jsx b/src/components/IOC/IOCManage/IOCService.jsx
similarity index 75%
rename from src/components/IOC/IOCService/IOCService.jsx
rename to src/components/IOC/IOCManage/IOCService.jsx
index c2d9d1b6..f80c5911 100644
--- a/src/components/IOC/IOCService/IOCService.jsx
+++ b/src/components/IOC/IOCManage/IOCService.jsx
@@ -3,40 +3,30 @@ import {
   LinearProgress,
   Grid,
   Typography,
-  Tooltip,
-  Alert
+  Tooltip
 } from "@mui/material";
 import { useState, useEffect, useCallback } from "react";
 import { useNavigate } from "react-router-dom";
 import { ConfirmationDialog } from "@ess-ics/ce-ui-common";
-import { initRequestParams } from "../../common/Helper";
 import { AccessControl } from "../../auth/AccessControl";
 import { useStartJobMutation } from "../../../store/deployApi";
-import { getErrorMessage } from "../../common/Alerts/AlertsData";
+import { ApiAlertError } from "../../common/Alerts/ApiAlertError";
 
-export function IOCService({
-  ioc,
-  currentCommand,
-  getJobs,
-  buttonDisabled,
-  setButtonDisabled,
-  jobLazyParams
-}) {
+export function IOCService({ ioc, currentCommand }) {
   const navigate = useNavigate();
   const [error, setError] = useState();
-  const [inProgress, setInProgress] = useState(false);
   const [startModalOpen, setStartModalOpen] = useState(false);
   const [stopModalOpen, setStopModalOpen] = useState(false);
   const [command, setCommand] = useState(null);
 
-  const [startJob, { error: jobError, data: jobData }] = useStartJobMutation();
+  const [startJob, { error: jobError, data: jobData, isLoading }] =
+    useStartJobMutation();
 
   useEffect(() => {
     if (jobError) {
       setError(jobError);
-      setButtonDisabled(false);
     }
-  }, [jobError, setButtonDisabled]);
+  }, [jobError]);
 
   useEffect(() => {
     if (jobData && (!command || command.id !== jobData.id)) {
@@ -54,55 +44,23 @@ export function IOCService({
 
   const start = useCallback(() => {
     resetUI();
-    setInProgress(true);
-    setButtonDisabled(true);
-
     startJob({
       iocId: ioc.id,
       createJobRequest: {
         type: "START"
       }
     });
-
-    let requestParams = initRequestParams(jobLazyParams);
-
-    requestParams.deployment_id = ioc.activeDeployment?.id;
-    getJobs(requestParams);
-  }, [
-    getJobs,
-    ioc.activeDeployment?.id,
-    jobLazyParams,
-    resetUI,
-    setButtonDisabled,
-    startJob,
-    ioc.id
-  ]);
+  }, [resetUI, startJob, ioc.id]);
 
   const stop = useCallback(() => {
     resetUI();
-    setInProgress(true);
-    setButtonDisabled(true);
-
     startJob({
       iocId: ioc.id,
       createJobRequest: {
         type: "STOP"
       }
     });
-
-    let requestParams = initRequestParams(jobLazyParams);
-
-    requestParams.deployment_id = ioc.activeDeployment?.id;
-    getJobs(requestParams);
-  }, [
-    getJobs,
-    ioc.activeDeployment?.id,
-    jobLazyParams,
-    resetUI,
-    setButtonDisabled,
-    startJob,
-    ioc.id
-  ]);
+  }, [resetUI, startJob, ioc.id]);
 
   const onStartModalClose = useCallback(() => {
     setStartModalOpen(false);
@@ -121,13 +79,13 @@ export function IOCService({
   }, [stop]);
 
   let disabledStartButtonTitle = "";
-  if (buttonDisabled || ioc.operationInProgress) {
+  if (isLoading || ioc.operationInProgress) {
     disabledStartButtonTitle =
       "There is an ongoing operation, you can not Start the IOC right now";
   }
 
   let disabledStopButtonTitle = "";
-  if (buttonDisabled || ioc.operationInProgress) {
+  if (isLoading || ioc.operationInProgress) {
     disabledStopButtonTitle =
       "There is an ongoing operation, you can not Stop the IOC right now";
   }
@@ -203,7 +161,7 @@ export function IOCService({
           <Tooltip title={disabledStopButtonTitle}>
             <Button
               color="secondary"
-              disabled={buttonDisabled}
+              disabled={ioc.operationInProgress || isLoading}
               variant="contained"
               sx={{
                 ":hover": {
@@ -221,7 +179,7 @@ export function IOCService({
             <Button
               color="essGrass"
               variant="contained"
-              disabled={buttonDisabled}
+              disabled={ioc.operationInProgress || isLoading}
               sx={{
                 color: "essWhite.main" // theme.palette.primary.main
               }}
@@ -236,11 +194,8 @@ export function IOCService({
           xs={12}
           md={12}
         >
-          {error ? (
-            <Alert severity="error">{getErrorMessage(error)}</Alert>
-          ) : (
-            inProgress && <LinearProgress color="primary" />
-          )}
+          {error && <ApiAlertError error={error} />}
+          {isLoading && <LinearProgress color="primary" />}
         </Grid>
       </Grid>
     </AccessControl>
diff --git a/src/components/IOC/IOCService/index.js b/src/components/IOC/IOCService/index.js
deleted file mode 100644
index 809b8cc5..00000000
--- a/src/components/IOC/IOCService/index.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import { IOCService } from "./IOCService";
-
-export { IOCService };
-export default IOCService;
diff --git a/src/components/IOC/IOCUndeployDialog/IOCUndeployDialog.jsx b/src/components/IOC/IOCUndeployDialog/IOCUndeployDialog.jsx
index 134f3bd7..890e6649 100644
--- a/src/components/IOC/IOCUndeployDialog/IOCUndeployDialog.jsx
+++ b/src/components/IOC/IOCUndeployDialog/IOCUndeployDialog.jsx
@@ -9,8 +9,7 @@ export function IOCUndeployDialog({
   ioc,
   error,
   resetError,
-  buttonDisabled,
-  setButtonDisabled
+  buttonDisabled
 }) {
   const handleClose = () => {
     setOpen(false);
@@ -19,18 +18,13 @@ export function IOCUndeployDialog({
 
   const onSubmit = (event) => {
     event.preventDefault();
-    setButtonDisabled(true);
 
-    submitCallback(
-      {
-        ioc_id: ioc.id
-      },
-      {
-        requestBody: {
-          type: "UNDEPLOY"
-        }
+    submitCallback({
+      iocId: ioc.id,
+      createJobRequest: {
+        type: "UNDEPLOY"
       }
-    );
+    });
   };
 
   return (
diff --git a/src/components/IOC/UndeployIOC/UndeployIOC.jsx b/src/components/IOC/UndeployIOC/UndeployIOC.jsx
index f4b8f35c..d6832919 100644
--- a/src/components/IOC/UndeployIOC/UndeployIOC.jsx
+++ b/src/components/IOC/UndeployIOC/UndeployIOC.jsx
@@ -1,57 +1,41 @@
-import { useContext, useState, useEffect } from "react";
+import { useState, useEffect } from "react";
 import { Navigate } from "react-router-dom";
-import { useAPIMethod } from "@ess-ics/ce-ui-common";
 import { IOCUndeployDialog } from "../IOCUndeployDialog";
-import { apiContext } from "../../../api/DeployApi";
-import { getErrorMessage } from "../../common/Helper";
+import { useStartJobMutation } from "../../../store/deployApi";
 
-// Process component
-export function UndeployIOC({
-  open,
-  setOpen,
-  submitCallback,
-  ioc,
-  buttonDisabled,
-  setButtonDisabled
-}) {
+export const UndeployIOC = ({ open, setOpen, submitCallback, ioc }) => {
   const [error, setError] = useState();
-  const client = useContext(apiContext);
-  const {
-    value: deployment,
-    wrapper: action,
-    error: deploymentError
-  } = useAPIMethod({
-    fcn: client.apis.Jobs.startJob,
-    call: false
-  });
+
+  const [
+    undeploy,
+    { data: undeployment, error: unDeploymentError, isLoading }
+  ] = useStartJobMutation();
 
   useEffect(() => {
-    if (deploymentError) {
-      setButtonDisabled(false);
-      setError(getErrorMessage(deploymentError));
+    if (unDeploymentError) {
+      setError(unDeploymentError);
     }
-  }, [deploymentError, setButtonDisabled]);
+  }, [unDeploymentError]);
 
-  if (!deployment) {
+  if (!undeployment) {
     return (
       <IOCUndeployDialog
         open={open}
         setOpen={setOpen}
-        submitCallback={action}
+        submitCallback={undeploy}
         ioc={ioc}
         error={error}
         resetError={() => setError(null)}
-        buttonDisabled={buttonDisabled}
-        setButtonDisabled={setButtonDisabled}
+        buttonDisabled={ioc.operationInProgress || isLoading}
       />
     );
   } else {
     submitCallback(); // This works but throws a warning because I am changing state in the parent while the child is rerendering. Not sure yet how to fix.
     return (
       <Navigate
-        to={`/jobs/${deployment.id}`}
+        to={`/jobs/${undeployment.id}`}
         push
       />
     );
   }
-}
+};
diff --git a/src/views/IOC/IOCDetailsView.jsx b/src/views/IOC/IOCDetailsView.jsx
index 695b8472..7ca29cba 100644
--- a/src/views/IOC/IOCDetailsView.jsx
+++ b/src/views/IOC/IOCDetailsView.jsx
@@ -1,97 +1,38 @@
 import { Grid, IconButton, Stack } from "@mui/material";
 import ArrowBackIcon from "@mui/icons-material/ArrowBack";
-import { useCallback, useContext, useEffect, useMemo, useState } from "react";
+import { useContext, useEffect, useState } from "react";
 import { useNavigate } from "react-router-dom";
 import {
   GlobalAppBarContext,
-  useAPIMethod,
   useIsCurrentUserPermitted,
-  TabPanel,
-  usePagination,
-  usePolling
+  TabPanel
 } from "@ess-ics/ce-ui-common";
 import { IOCLiveStatus } from "../../components/IOC/IOCLiveStatus";
 import { IOCManage } from "../../components/IOC/IOCManage";
 import { IOCAdmin } from "../../components/IOC/IOCAdmin";
 import { applicationTitle } from "../../components/common/Helper";
-import { apiContext } from "../../api/DeployApi";
-import { ROWS_PER_PAGE } from "../../constants";
 
-const IOC_POLL_INTERVAL = 10000;
-export function IOCDetailsView({ ioc, getIOC, abortGetIOC, loading }) {
+export function IOCDetailsView({ ioc }) {
   const { setTitle } = useContext(GlobalAppBarContext);
-  useEffect(() => {
-    if (ioc) {
-      setTitle(applicationTitle(`IOC Details: ${ioc.namingName}`));
-    }
-  }, [ioc, setTitle]);
-
   const [buttonDisabled, setButtonDisabled] = useState(false);
   const navigate = useNavigate();
 
-  const client = useContext(apiContext);
-
-  const ongoingCommandParams = useMemo(
-    () => ({
-      ioc_id: ioc.id,
-      type: "COMMAND",
-      status: "ONGOING"
-    }),
-    [ioc]
-  );
-
-  const {
-    value: ongoingCommand,
-    wrapper: getOngoingCommand,
-    loading: ongoingCommandLoading,
-    dataReady: ongoingCommandDataReady,
-    abort: abortGetOngoingCommand
-  } = useAPIMethod({
-    fcn: client.apis.Jobs.listJobs,
-    params: ongoingCommandParams,
-    call: false
-  });
-
-  const { pagination: jobPagination, setPagination: setJobPagination } =
-    usePagination({
-      rowsPerPageOptions: ROWS_PER_PAGE,
-      initLimit: ROWS_PER_PAGE[0],
-      initPage: 0
-    });
   const [tabIndex, setTabIndex] = useState(0);
 
-  // Invoked by Table on change to pagination
-  const onPage = useCallback(
-    (params) => {
-      setJobPagination(params);
-    },
-    [setJobPagination]
-  );
-
-  usePolling(getIOC, loading, IOC_POLL_INTERVAL, abortGetIOC);
-  usePolling(
-    getOngoingCommand,
-    ongoingCommandLoading || !ongoingCommandDataReady,
-    IOC_POLL_INTERVAL,
-    abortGetOngoingCommand
-  );
-
   useEffect(() => {
     setButtonDisabled(Boolean(ioc?.operationInProgress));
   }, [ioc?.operationInProgress]);
 
+  useEffect(() => {
+    if (ioc) {
+      setTitle(applicationTitle(`IOC Details: ${ioc.namingName}`));
+    }
+  }, [ioc, setTitle]);
+
   const handleClick = () => {
     navigate(-1);
   };
 
-  const setButtonDisabledAndUpdate = useCallback(
-    (isDisabled) => {
-      setButtonDisabled(isDisabled);
-      getIOC();
-    },
-    [getIOC]
-  );
-
   const tabs = [
     {
       label: "Status",
@@ -110,18 +51,7 @@ export function IOCDetailsView({ ioc, getIOC, abortGetIOC, loading }) {
   if (isPermittedManagement) {
     tabs.push({
       label: "Management",
-      content: (
-        <IOCManage
-          ioc={ioc}
-          buttonDisabled={buttonDisabled}
-          currentCommand={
-            ongoingCommand?.jobs?.length > 0 ? ongoingCommand.jobs[0] : null
-          }
-          setButtonDisabled={setButtonDisabledAndUpdate}
-          pagination={jobPagination}
-          onPage={onPage}
-        />
-      )
+      content: <IOCManage ioc={ioc} />
     });
   }
   if (isPermittedAdmin) {
@@ -130,7 +60,6 @@ export function IOCDetailsView({ ioc, getIOC, abortGetIOC, loading }) {
       content: (
         <IOCAdmin
           ioc={ioc}
-          getIOC={getIOC}
           resetTab={() => setTabIndex(0)}
           buttonDisabled={buttonDisabled}
           setButtonDisabled={setButtonDisabled}
-- 
GitLab