From 0ae92a9dfe329d5117ca6bb8e95c7cb2a2efa321 Mon Sep 17 00:00:00 2001
From: Christina Jenks <christina.jenks@ess.eu>
Date: Thu, 28 Sep 2023 10:15:42 +0000
Subject: [PATCH] CE-2079: migrate useCSEntrySearch,
 useUpdateActiveDeploymentHost, useTagsAndCommitIds to common

---
 src/api/SwaggerApi.js                         | 73 -----------------
 .../IOC/ChangeHostAdmin/ChangeHostAdmin.js    | 80 +++++++++++++------
 .../IOC/IOCDeployDialog/IOCDeployDialog.js    | 54 ++++++++++---
 src/mocks/fixtures/GitTagsAndCommits.json     | 68 ++++++++++++++++
 src/mocks/mockAPI.js                          | 14 +++-
 src/views/host/HostListView.js                | 27 +++++--
 6 files changed, 197 insertions(+), 119 deletions(-)
 create mode 100644 src/mocks/fixtures/GitTagsAndCommits.json

diff --git a/src/api/SwaggerApi.js b/src/api/SwaggerApi.js
index 5de619f3..ac3393e5 100644
--- a/src/api/SwaggerApi.js
+++ b/src/api/SwaggerApi.js
@@ -241,43 +241,6 @@ export function useJobLogById() {
   return useAsync({ fcn: method, call: false, init: null });
 }
 
-export function unpackHost(host) {
-  return { ...host };
-}
-
-export function unpackCSEntryHost(host) {
-  return { ...host };
-}
-
-const emptyHostListResponse = {
-  totalCount: 0,
-  pageNumber: 0,
-  limit: 0,
-  hostList: []
-};
-
-export function unpackCSEntryHostList(hosts) {
-  let hostArr = hosts.csEntryHosts.map((h) => unpackCSEntryHost(h));
-
-  let unpackedHostList = {
-    totalCount: hosts.totalCount,
-    pageNumber: hosts.pageNumber,
-    limit: hosts.limit,
-    hostList: hostArr
-  };
-
-  return unpackedHostList;
-}
-
-export function useCSEntrySearch() {
-  const api = useContext(apiContext);
-  const method = useCallAndUnpack(
-    (params) => api.apis.Hosts.listHosts(params),
-    unpackCSEntryHostList
-  );
-  return useAsync({ fcn: method, call: false, init: emptyHostListResponse });
-}
-
 export function unpackRecord(record) {
   return { ...record };
 }
@@ -388,29 +351,6 @@ export function useNamingNames() {
   return useAsync({ fcn: method, call: false, init: [] });
 }
 
-export function unpackGitReference(reference) {
-  return { ...reference };
-}
-
-export function unpackTagAndCommitIdList(tagList) {
-  return tagList.map((t) => unpackGitReference(t));
-}
-
-export function useTagsAndCommitIds(onError) {
-  const api = useContext(apiContext);
-  const method = useCallAndUnpack(
-    (gitProjectId, reference, includeAllReference, searchMethod) =>
-      api.apis.Git.listTagsAndCommitIds({
-        project_id: gitProjectId,
-        reference: reference,
-        include_all_reference: includeAllReference,
-        search_method: searchMethod
-      }),
-    unpackTagAndCommitIdList
-  );
-  return useAsync({ fcn: method, call: false, onError: onError, init: [] });
-}
-
 export function unpackCurrentlyActiveIOCS(statistics) {
   return { ...statistics };
 }
@@ -503,16 +443,3 @@ export function unpackUpdateIoc(updateIoc) {
 export function unpackUpdateActiveDeploymentHost(ioc) {
   return { ...ioc };
 }
-
-export function useUpdateActiveDeploymentHost(id, onError) {
-  const api = useContext(apiContext);
-  const method = useCallAndUnpack(
-    (body) =>
-      api.apis.IOCs.updateActiveDeploymentHost(
-        { ioc_id: id },
-        { requestBody: body }
-      ),
-    unpackUpdateActiveDeploymentHost
-  );
-  return useAsync({ fcn: method, call: false, onError: onError });
-}
diff --git a/src/components/IOC/ChangeHostAdmin/ChangeHostAdmin.js b/src/components/IOC/ChangeHostAdmin/ChangeHostAdmin.js
index a3faa68d..9c033943 100644
--- a/src/components/IOC/ChangeHostAdmin/ChangeHostAdmin.js
+++ b/src/components/IOC/ChangeHostAdmin/ChangeHostAdmin.js
@@ -1,6 +1,16 @@
-import React, { useState, useEffect, useCallback, useMemo } from "react";
+import React, {
+  useState,
+  useEffect,
+  useCallback,
+  useMemo,
+  useContext
+} from "react";
 import AccessControl from "../../auth/AccessControl";
-import { SimpleAccordion, ConfirmationDialog } from "@ess-ics/ce-ui-common";
+import {
+  SimpleAccordion,
+  ConfirmationDialog,
+  useAPIMethod
+} from "@ess-ics/ce-ui-common";
 import {
   Button,
   Typography,
@@ -11,12 +21,9 @@ import {
   Alert,
   Autocomplete
 } from "@mui/material";
-import {
-  useUpdateActiveDeploymentHost,
-  useCSEntrySearch
-} from "../../../api/SwaggerApi";
 import { useTypingTimer } from "../../common/SearchBoxFilter/TypingTimer";
 import { transformHostQuery } from "../../common/Helper";
+import { apiContext } from "../../../api/DeployApi";
 
 export default function ChangeHostAdmin({
   ioc,
@@ -33,14 +40,20 @@ export default function ChangeHostAdmin({
     }),
     [ioc?.activeDeployment?.host]
   );
-
-  const [hosts, getHosts, , loadingHosts] = useCSEntrySearch();
   const [host, setHost] = useState(initHost);
-  const [query, onHostKeyUp] = useTypingTimer({ interval: 500 });
 
-  function onError(message) {
-    setError(message);
-  }
+  const client = useContext(apiContext);
+
+  const {
+    value: hosts,
+    wrapper: getHosts,
+    loading: loadingHosts
+  } = useAPIMethod({
+    fcn: client.apis.Hosts.listHosts,
+    call: false
+  });
+
+  const [query, onHostKeyUp] = useTypingTimer({ interval: 500 });
 
   const noModification = useCallback(
     () => !host || host.csEntryHost.id === ioc.activeDeployment.host.csEntryId,
@@ -50,10 +63,21 @@ export default function ChangeHostAdmin({
   // for the dialog
   const [error, setError] = useState();
   const [open, setOpen] = useState();
-  const [updatedIoc, updateHost] = useUpdateActiveDeploymentHost(
-    ioc.id,
-    onError
-  );
+
+  const {
+    value: updatedIoc,
+    wrapper: updateHost,
+    error: updateHostError
+  } = useAPIMethod({
+    fcn: client.apis.IOCs.updateActiveDeploymentHost,
+    call: false
+  });
+
+  useEffect(() => {
+    if (updateHostError) {
+      setError(updateHostError?.message);
+    }
+  }, [updateHostError, setError]);
 
   useEffect(() => {
     if (updatedIoc) {
@@ -62,10 +86,9 @@ export default function ChangeHostAdmin({
     }
   }, [updatedIoc, getIOC, resetTab]);
 
-  useEffect(
-    () => getHosts({ query: transformHostQuery(`${query}`) }),
-    [query, getHosts]
-  );
+  useEffect(() => {
+    getHosts({ query: transformHostQuery(`${query}`) });
+  }, [query, getHosts]);
 
   const onClose = useCallback(() => {
     setOpen(false);
@@ -73,10 +96,17 @@ export default function ChangeHostAdmin({
   }, [setOpen, initHost]);
 
   const onConfirm = useCallback(() => {
-    updateHost({
-      hostCSEntryId: host.csEntryHost.id
-    });
-  }, [updateHost, host?.csEntryHost?.id]);
+    updateHost(
+      {
+        ioc_id: ioc.id
+      },
+      {
+        requestBody: {
+          hostCSEntryId: host.csEntryHost.id
+        }
+      }
+    );
+  }, [updateHost, ioc, host?.csEntryHost?.id]);
 
   let disabledButtonTitle = "";
   if (buttonDisabled || ioc.operationInProgress) {
@@ -142,7 +172,7 @@ export default function ChangeHostAdmin({
               <Autocomplete
                 autoHighlight
                 id="host"
-                options={hosts.hostList}
+                options={hosts?.csEntryHosts ?? []}
                 loading={loadingHosts}
                 clearOnBlur={false}
                 value={host}
diff --git a/src/components/IOC/IOCDeployDialog/IOCDeployDialog.js b/src/components/IOC/IOCDeployDialog/IOCDeployDialog.js
index 55c81f02..3f380f26 100644
--- a/src/components/IOC/IOCDeployDialog/IOCDeployDialog.js
+++ b/src/components/IOC/IOCDeployDialog/IOCDeployDialog.js
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from "react";
+import React, { useCallback, useContext, useEffect, useState } from "react";
 import {
   Button,
   TextField,
@@ -12,9 +12,10 @@ import {
   Autocomplete,
   Alert
 } from "@mui/material";
-import { useCSEntrySearch, useTagsAndCommitIds } from "../../../api/SwaggerApi";
 import { useTypingTimer } from "../../common/SearchBoxFilter/TypingTimer";
 import { formatDate, transformHostQuery } from "../../common/Helper";
+import { apiContext } from "../../../api/DeployApi";
+import { useAPIMethod } from "@ess-ics/ce-ui-common";
 
 export function IOCDeployDialog({
   open,
@@ -26,15 +27,40 @@ export function IOCDeployDialog({
   error,
   resetError
 }) {
-  function onError(message) {
-    console.error(message);
-  }
+  const client = useContext(apiContext);
+  const {
+    value: hosts,
+    wrapper: getHosts,
+    loading: loadingHosts
+  } = useAPIMethod({
+    fcn: client.apis.Hosts.listHosts,
+    call: false
+  });
+
+  const {
+    value: tagOrCommitId,
+    wrapper: callGetTagOrCommitId,
+    loading: loadingTagsAndCommitIds,
+    error: tagOrCommitIdError
+  } = useAPIMethod({
+    fcn: client.apis.Git.listTagsAndCommitIds,
+    call: false
+  });
+  const getTagOrCommitId = useCallback(
+    (gitProjectId, reference, includeAllReference, searchMethod) => {
+      callGetTagOrCommitId({
+        project_id: gitProjectId,
+        reference: reference,
+        include_all_reference: includeAllReference,
+        search_method: searchMethod
+      });
+    },
+    [callGetTagOrCommitId]
+  );
 
-  const [hosts, getHosts, , loadingHosts] = useCSEntrySearch();
   const [host, setHost] = useState(init);
   const [query, onHostKeyUp] = useTypingTimer({ interval: 500 });
-  const [tagOrCommitId, getTagOrCommitId, , loadingTagsAndCommitIds] =
-    useTagsAndCommitIds(onError);
+
   const [gitRepo, setGitRepo] = useState(init.git || "");
   const [gitVersion, setGitVersion] = useState(init.version || "");
   const [queryGitVersion, onGitVersionKeyUp] = useTypingTimer({
@@ -46,10 +72,9 @@ export function IOCDeployDialog({
     setOpen(false);
   };
 
-  useEffect(
-    () => getHosts({ query: transformHostQuery(`${query}`) }),
-    [query, getHosts]
-  );
+  useEffect(() => {
+    getHosts({ query: transformHostQuery(`${query}`) });
+  }, [query, getHosts]);
   useEffect(() => {
     getTagOrCommitId(gitProjectId, queryGitVersion, false, "CONTAINS");
   }, [queryGitVersion, gitProjectId, getTagOrCommitId]);
@@ -205,6 +230,9 @@ export function IOCDeployDialog({
                     </React.Fragment>
                   )
                 }}
+                helperText={
+                  tagOrCommitIdError ? `Error: ${tagOrCommitId?.message}` : ""
+                }
               />
             )}
             autoSelect
@@ -213,7 +241,7 @@ export function IOCDeployDialog({
           <Autocomplete
             autoHighlight
             id="host"
-            options={hosts.hostList}
+            options={hosts?.csEntryHosts}
             loading={loadingHosts}
             clearOnBlur={false}
             defaultValue={init}
diff --git a/src/mocks/fixtures/GitTagsAndCommits.json b/src/mocks/fixtures/GitTagsAndCommits.json
new file mode 100644
index 00000000..f762aa93
--- /dev/null
+++ b/src/mocks/fixtures/GitTagsAndCommits.json
@@ -0,0 +1,68 @@
+[
+  {
+    "reference": "dirty_repo",
+    "shortReference": "dirty_repo",
+    "description": "",
+    "commitDate": "2022-03-22T14:14:53.000+00:00"
+  },
+  {
+    "reference": "engineer_set",
+    "shortReference": "engineer_set",
+    "description": "",
+    "commitDate": "2022-03-22T13:32:47.000+00:00"
+  },
+  {
+    "reference": "correct_ioc",
+    "shortReference": "correct_ioc",
+    "description": "",
+    "commitDate": "2022-03-22T13:31:56.000+00:00"
+  },
+  {
+    "reference": "essioc_no_config",
+    "shortReference": "essioc_no_config",
+    "description": "",
+    "commitDate": "2022-03-22T13:31:00.000+00:00"
+  },
+  {
+    "reference": "missing_essioc",
+    "shortReference": "missing_essioc",
+    "description": "",
+    "commitDate": "2022-03-22T13:29:28.000+00:00"
+  },
+  {
+    "reference": "edeb5689a76864c75950f9da4ae546780639d333",
+    "shortReference": "edeb5689",
+    "description": "Added PVs.list\n",
+    "commitDate": "2022-03-22T14:14:53.000+00:00"
+  },
+  {
+    "reference": "a278b61cac71e35acd56ec4635b04fb1ef2627bb",
+    "shortReference": "a278b61c",
+    "description": "Set engineer\n",
+    "commitDate": "2022-03-22T13:32:47.000+00:00"
+  },
+  {
+    "reference": "d4df546cb94e9d9094d8b9a0aa8989c9576b4e36",
+    "shortReference": "d4df546c",
+    "description": "Correct essioc config\n",
+    "commitDate": "2022-03-22T13:31:56.000+00:00"
+  },
+  {
+    "reference": "e0646971a2b9b1d0db5ce35013530f0901cec033",
+    "shortReference": "e0646971",
+    "description": "Added essioc, no config\n",
+    "commitDate": "2022-03-22T13:31:00.000+00:00"
+  },
+  {
+    "reference": "556d104d2f7638a351a1b89d3ca2b2ed746e0f90",
+    "shortReference": "556d104d",
+    "description": "Incorrect essioc\n",
+    "commitDate": "2022-03-22T13:29:28.000+00:00"
+  },
+  {
+    "reference": "31405eb103a995608a5fece1e637430a6979eb9f",
+    "shortReference": "31405eb1",
+    "description": "Initial commit\n",
+    "commitDate": "2022-03-22T13:26:53.000+00:00"
+  }
+]
diff --git a/src/mocks/mockAPI.js b/src/mocks/mockAPI.js
index ba4173b6..359d7307 100644
--- a/src/mocks/mockAPI.js
+++ b/src/mocks/mockAPI.js
@@ -92,6 +92,10 @@ function listProjects(req) {
   const body = require("./fixtures/GitProjects.json");
   return { body };
 }
+function listTagsAndCommitIds(req) {
+  const body = require("./fixtures/GitTagsAndCommits.json");
+  return { body };
+}
 
 function renew(req) {
   const token = "FADEDEAD";
@@ -286,7 +290,8 @@ const mockAPI = {
   },
   git_helper: {
     infoFromUserName,
-    listProjects
+    listProjects,
+    listTagsAndCommitIds
   },
   monitoring: {
     getProcservLogs,
@@ -344,6 +349,8 @@ export const apiHandlers = [
   makeHandler("GET", qRegExp(".*/iocs"), mockAPI.iocs.listIOCs),
   makeHandler("POST", qRegExp(".*/iocs"), mockAPI.iocs.createIoc),
   makeHandler("GET", qRegExp(".*/iocs/[0-9]+"), mockAPI.iocs.getIOC),
+
+  // git helper
   makeHandler(
     "GET",
     qRegExp(".*/git_helper/user_info"),
@@ -355,6 +362,11 @@ export const apiHandlers = [
     qRegExp(".*/git_helper/projects"),
     mockAPI.git_helper.listProjects
   ),
+  makeHandler(
+    "GET",
+    qRegExp(".*/git_helper/[0-9]+/tags_and_commits"),
+    mockAPI.git_helper.listTagsAndCommitIds
+  ),
 
   // deployments
   makeHandler(
diff --git a/src/views/host/HostListView.js b/src/views/host/HostListView.js
index 6ebc6596..9c17659a 100644
--- a/src/views/host/HostListView.js
+++ b/src/views/host/HostListView.js
@@ -8,8 +8,11 @@ import React, {
 import { Container, Grid, Tabs, Tab, useMediaQuery } from "@mui/material";
 import { HostList } from "../../components/host/HostList";
 import { HostTable } from "../../components/host/HostTable";
-import { useCSEntrySearch } from "../../api/SwaggerApi";
-import { GlobalAppBarContext, RootPaper } from "@ess-ics/ce-ui-common";
+import {
+  GlobalAppBarContext,
+  RootPaper,
+  useAPIMethod
+} from "@ess-ics/ce-ui-common";
 import {
   applicationTitle,
   initRequestParams,
@@ -22,12 +25,22 @@ import {
   deserialize
 } from "../../components/common/URLState/URLState";
 import { usePagination } from "../../hooks/pagination";
+import { apiContext } from "../../api/DeployApi";
 
 export function HostListView() {
   const { setTitle } = useContext(GlobalAppBarContext);
   useEffect(() => setTitle(applicationTitle("IOC hosts")), [setTitle]);
 
-  const [hosts, getHosts /* reset*/, , loading] = useCSEntrySearch();
+  const client = useContext(apiContext);
+  const {
+    value: hosts,
+    wrapper: getHosts,
+    loading
+  } = useAPIMethod({
+    fcn: client.apis.Hosts.listHosts,
+    call: false
+  });
+
   const [urlState, setUrlState] = useUrlState(
     {
       tab: "0",
@@ -94,8 +107,8 @@ export function HostListView() {
 
   // update pagination whenever search result total pages change
   useEffect(() => {
-    setPagination({ totalCount: hosts.totalCount ?? 0 });
-  }, [setPagination, hosts.totalCount]);
+    setPagination({ totalCount: hosts?.totalCount ?? 0 });
+  }, [setPagination, hosts?.totalCount]);
 
   // whenever url state changes, update pagination
   useEffect(() => {
@@ -141,10 +154,10 @@ export function HostListView() {
         query={deserialize(urlState.query)}
         loading={loading}
       >
-        {smDown ? <HostList hosts={hosts.hostList} /> : null}
+        {smDown ? <HostList hosts={hosts?.csEntryHosts ?? []} /> : null}
         {smUp ? (
           <HostTable
-            hosts={hosts.hostList}
+            hosts={hosts?.csEntryHosts ?? []}
             loading={loading}
             pagination={pagination}
             onPage={onPage}
-- 
GitLab