From 45cf4b0e8069c580a9fb240e2502592123d906fc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?L=C3=A9o=20Banno-Cloutier?=
 <leo.banno-cloutier@savoirfairelinux.com>
Date: Mon, 12 Jun 2023 14:58:58 -0400
Subject: [PATCH] jams-react-client: function refactoring to remove duplicates

Change-Id: If0408ca1e11257d7eadc474368f077aa375b0026
---
 jams-react-client/src/api.js                  |  13 +-
 .../LanguagePicker/LanguagePicker.js          |   1 +
 .../src/components/Sidebar/Sidebar.js         |  27 ++--
 jams-react-client/src/i18n.js                 |   2 +-
 .../src/views/Contacts/Contacts.js            | 118 +++++++-----------
 .../src/views/Groups/EditGroup.js             |  25 +---
 jams-react-client/src/views/Groups/Groups.js  |  29 ++---
 .../src/views/Groups/getBlueprintsOptions.js  |  10 ++
 8 files changed, 83 insertions(+), 142 deletions(-)
 create mode 100644 jams-react-client/src/views/Groups/getBlueprintsOptions.js

diff --git a/jams-react-client/src/api.js b/jams-react-client/src/api.js
index d4325371..a2f3a744 100644
--- a/jams-react-client/src/api.js
+++ b/jams-react-client/src/api.js
@@ -85,16 +85,13 @@ export default function configApiCall(
         config["data"] = data;
       }
     } else {
+      config["header"] = {
+        "Content-type": "application/json",
+      };
+
       if (window.localStorage.getItem("access_token")) {
         const jwt = localStorage.getItem("access_token");
-
-        config["headers"] = {
-          Authorization: "Bearer " + jwt,
-        };
-      } else {
-        config["headers"] = {
-          "Content-type": "application/json",
-        };
+        config["headers"]["Authorization"] = "Bearer " + jwt;
       }
 
       config["data"] = JSON.stringify(data);
diff --git a/jams-react-client/src/components/LanguagePicker/LanguagePicker.js b/jams-react-client/src/components/LanguagePicker/LanguagePicker.js
index bafb5212..c504e136 100644
--- a/jams-react-client/src/components/LanguagePicker/LanguagePicker.js
+++ b/jams-react-client/src/components/LanguagePicker/LanguagePicker.js
@@ -63,6 +63,7 @@ export default function LanguagePicker(props) {
               if (option.code === language) {
                 return option.name;
               }
+              return null;
             })}
           </Button>
           <Menu {...bindMenu(popupState)}>
diff --git a/jams-react-client/src/components/Sidebar/Sidebar.js b/jams-react-client/src/components/Sidebar/Sidebar.js
index 06f49395..7166b0a0 100755
--- a/jams-react-client/src/components/Sidebar/Sidebar.js
+++ b/jams-react-client/src/components/Sidebar/Sidebar.js
@@ -3,6 +3,7 @@ import { Link, useHistory } from "react-router-dom";
 import classNames from "classnames";
 import PropTypes from "prop-types";
 import { NavLink } from "react-router-dom";
+
 // @material-ui/core components
 import { makeStyles } from "@material-ui/core/styles";
 import Drawer from "@material-ui/core/Drawer";
@@ -11,15 +12,14 @@ import List from "@material-ui/core/List";
 import ListItem from "@material-ui/core/ListItem";
 import ListItemText from "@material-ui/core/ListItemText";
 import Icon from "@material-ui/core/Icon";
+import Snackbar from "@material-ui/core/Snackbar/Snackbar";
 
-// core components
 import ExitToAppIcon from "@material-ui/icons/ExitToApp";
 import UpdateIcon from "@material-ui/icons/Update";
 
 import styles from "assets/jss/material-dashboard-react/components/sidebarStyle.js";
 
 import auth from "auth";
-import Snackbar from "@material-ui/core/Snackbar/Snackbar";
 
 import i18next from "i18next";
 
@@ -60,24 +60,17 @@ export default function Sidebar(props) {
         <hr />
       </div>
       {routes.map((prop, key) => {
-        if (prop.admin && !auth.hasAdminScope()) return;
+        if (prop.admin && !auth.hasAdminScope()) return null;
         if (!prop.admin && auth.hasAdminScope() && prop.path === "/user/admin")
-          return;
-        var activePro = " ";
-        var listItemClasses;
-        if (prop.path === "/upgrade-to-pro") {
-          activePro = classes.activePro + " ";
-          listItemClasses = classNames({
-            [" " + classes[color]]: true,
-          });
-        } else {
-          listItemClasses = classNames({
-            [" " + classes[color]]: activeRoute(prop.layout + prop.path),
-          });
-        }
+          return null;
+
+        const listItemClasses = classNames({
+          [" " + classes[color]]: activeRoute(prop.layout + prop.path),
+        });
         const whiteFontClasses = classNames({
           [" " + classes.whiteFont]: activeRoute(prop.layout + prop.path),
         });
+
         return (
           <div className={classes.wrapper} key={key}>
             {props.updating && (
@@ -91,7 +84,7 @@ export default function Sidebar(props) {
 
             <NavLink
               to={prop.layout + prop.path}
-              className={activePro + classes.item}
+              className={classes.item}
               activeClassName="active"
               key={key}
             >
diff --git a/jams-react-client/src/i18n.js b/jams-react-client/src/i18n.js
index 34cce348..d251bfcb 100644
--- a/jams-react-client/src/i18n.js
+++ b/jams-react-client/src/i18n.js
@@ -12,7 +12,7 @@ i18next
     lookupCookie: "i18next",
     lookupLocalStorage: "i18nextLng",
     lookupSessionStorage: "i18nextLng",
-    debug: true,
+    debug: false,
     detection: {
       order: ["cookie", "localStorage", "sessionStorage", "navigator"],
       cache: ["cookie"],
diff --git a/jams-react-client/src/views/Contacts/Contacts.js b/jams-react-client/src/views/Contacts/Contacts.js
index c169a52e..85a6067e 100644
--- a/jams-react-client/src/views/Contacts/Contacts.js
+++ b/jams-react-client/src/views/Contacts/Contacts.js
@@ -132,98 +132,64 @@ export default function Users(props) {
   };
 
   const getAllContacts = () => {
+    let request;
+
     if (auth.hasAdminScope()) {
-      axios(
+      request = axios(
         configApiCall(
           api_path_get_admin_contacts + "?username=" + props.username,
           "GET",
           null,
           null
         )
-      )
-        .then((response) => {
-          /*
-                    TODO: Include the username of the user of witch we want to display contacts
-                    at the moment the admin sees his contacts in each user profile he visits
-                */
-          let orginalContacts = response.data;
-          for (const contact of orginalContacts) {
-            contact.display = "";
-            axios(
-              configApiCall(
-                api_path_get_ns_name_from_addr + contact.uri,
-                null,
-                null
-              )
-            ).then((response) => {
-              contact.username = response.data.name;
-              axios(
-                configApiCall(
-                  api_path_get_user_profile + contact.username,
-                  "GET",
-                  null,
-                  null
-                )
-              ).then((response) => {
-                contact.profilePicture = response.data.profilePicture;
-                contact.firstName = response.data.firstName;
-                contact.lastName = response.data.lastName;
-                contact.organization = response.data.organization;
-              });
-            });
-          }
-          setContacts(orginalContacts);
-          setLoading(false);
-        })
-        .catch((error) => {
-          if (error.response.status === 401) {
-            auth.authenticated = false;
-            history.push("/");
-          }
-        });
+      );
     } else {
-      axios(configApiCall(api_path_get_auth_contacts, "GET", null, null))
-        .then((response) => {
-          /*
-                    TODO: Include the username of the user of witch we want to display contacts
-                    at the moment the admin sees his contacts in each user profile he visits
-                */
-          let orginalContacts = response.data;
-          orginalContacts.map((contact) => {
-            contact.display = "";
+      request = axios(
+        configApiCall(api_path_get_auth_contacts, "GET", null, null)
+      );
+    }
+
+    request
+      .then((response) => {
+        /*
+          TODO: Include the username of the user of which we want to display contacts
+          at the moment the admin sees his contacts in each user profile he visits
+        */
+        const originalContacts = response.data;
+        for (const contact of originalContacts) {
+          contact.display = "";
+          axios(
+            configApiCall(
+              api_path_get_ns_name_from_addr + contact.uri,
+              null,
+              null
+            )
+          ).then((response) => {
+            contact.username = response.data.name;
             axios(
               configApiCall(
-                api_path_get_ns_name_from_addr + contact.uri,
+                api_path_get_user_profile + contact.username,
+                "GET",
                 null,
                 null
               )
             ).then((response) => {
-              contact.username = response.data.name;
-              axios(
-                configApiCall(
-                  api_path_get_user_profile + contact.username,
-                  "GET",
-                  null,
-                  null
-                )
-              ).then((response) => {
-                contact.profilePicture = response.data.profilePicture;
-                contact.firstName = response.data.firstName;
-                contact.lastName = response.data.lastName;
-                contact.organization = response.data.organization;
-              });
+              contact.profilePicture = response.data.profilePicture;
+              contact.firstName = response.data.firstName;
+              contact.lastName = response.data.lastName;
+              contact.organization = response.data.organization;
             });
           });
-          setContacts(orginalContacts);
-          setLoading(false);
-        })
-        .catch((error) => {
-          if (error.response.status === 401) {
-            auth.authenticated = false;
-            history.push("/signin");
-          }
-        });
-    }
+        }
+        setContacts(originalContacts);
+        setLoading(false);
+      })
+      .catch((error) => {
+        if (error.response.status === 401) {
+          auth.authenticated = false;
+          history.push("/signin");
+        }
+      });
   };
 
   const addContactToUser = (value) => {
diff --git a/jams-react-client/src/views/Groups/EditGroup.js b/jams-react-client/src/views/Groups/EditGroup.js
index 0c0c24e8..64c7c1ec 100644
--- a/jams-react-client/src/views/Groups/EditGroup.js
+++ b/jams-react-client/src/views/Groups/EditGroup.js
@@ -63,6 +63,8 @@ import auth from "auth.js";
 
 import { debounce } from "lodash";
 
+import { getBlueprintsOptions } from "./getBlueprintsOptions";
+
 const useStyles = makeStyles((theme) => ({
   ...devicesStyle,
   ...dashboardStyle,
@@ -203,20 +205,6 @@ export default function EditGroup(props) {
       });
   };
 
-  const getBlueprintsOptions = (inputs) => {
-    let blueprintsOptions = [];
-    let index = 0;
-    if (blueprints.length === 0)
-      blueprintsOptions.push({ value: index, label: "No blueprint found" });
-    else {
-      blueprints.map((blueprint) => {
-        blueprintsOptions.push({ value: index, label: blueprint.name });
-        index += 1;
-      });
-    }
-    return blueprintsOptions;
-  };
-
   const blueprintsOptionsItems = tool.buildSelectMenuItems(
     getBlueprintsOptions(blueprints)
   );
@@ -333,12 +321,9 @@ export default function EditGroup(props) {
   };
 
   const handleBlueprintsChange = (e) => {
-    updateGroup(
-      getBlueprintsOptions()[e.target.value].label !== "No blueprint found"
-        ? getBlueprintsOptions()[e.target.value].label
-        : ""
-    );
-    setSelectedBlueprint(getBlueprintsOptions()[e.target.value]);
+    const option = getBlueprintsOptions(blueprints)[e.target.value];
+    updateGroup(option.label !== "No blueprint found" ? option.label : "");
+    setSelectedBlueprint(option);
   };
 
   const initCheckGroupNameExists = useCallback(
diff --git a/jams-react-client/src/views/Groups/Groups.js b/jams-react-client/src/views/Groups/Groups.js
index ac133643..a19bb244 100644
--- a/jams-react-client/src/views/Groups/Groups.js
+++ b/jams-react-client/src/views/Groups/Groups.js
@@ -53,6 +53,8 @@ import LinearProgress from "@material-ui/core/LinearProgress";
 
 import i18next from "i18next";
 
+import { getBlueprintsOptions } from "./getBlueprintsOptions";
+
 const styles = {
   cardCategoryWhite: {
     color: "rgba(255,255,255,.62)",
@@ -113,7 +115,7 @@ export default function Groups() {
     id: 0,
     name: "groupeName",
   });
-  const [openRemoveDialog, setOpenRemoveDialog] = useState();
+  const [openRemoveDialog, setOpenRemoveDialog] = useState(false);
 
   const [disableCreate, setDisableCreate] = useState(true);
 
@@ -143,25 +145,11 @@ export default function Groups() {
     history.push("/groups");
   };
 
-  const getBlueprintsOptions = () => {
-    let blueprintsOptions = [];
-    let index = 0;
-    if (blueprints.length === 0)
-      blueprintsOptions.push({ value: index, label: "No blueprint found" });
-    else {
-      blueprints.map((blueprint) => {
-        blueprintsOptions.push({ value: index, label: blueprint.name });
-        index += 1;
-      });
-    }
-    return blueprintsOptions;
-  };
-
   const getBlueprints = () => {
     axios(configApiCall(api_path_blueprints + "?name=*", "GET", null, null))
       .then((response) => {
         setBlueprints(response.data);
-        setSelectedBlueprint(getBlueprintsOptions()[0]);
+        setSelectedBlueprint(getBlueprintsOptions(blueprints)[0]);
       })
       .catch((error) => {
         if (error.response.status === 401) {
@@ -300,7 +288,7 @@ export default function Groups() {
   };
 
   const blueprintsOptionsItems = tool.buildSelectMenuItems(
-    getBlueprintsOptions()
+    getBlueprintsOptions(blueprints)
   );
 
   const [selectedBlueprint, setSelectedBlueprint] = useState({
@@ -309,7 +297,7 @@ export default function Groups() {
   });
 
   const handleBlueprintsChange = (e) => {
-    setSelectedBlueprint(getBlueprintsOptions()[e.target.value]);
+    setSelectedBlueprint(getBlueprintsOptions(blueprints)[e.target.value]);
   };
 
   if (!auth.hasAdminScope()) {
@@ -388,9 +376,10 @@ export default function Groups() {
                     value={selectedBlueprint.value}
                     onChange={handleBlueprintsChange}
                     variant="outlined"
-                    children={blueprintsOptionsItems}
                     disabled={blueprints.length === 0}
-                  />
+                  >
+                    {blueprintsOptionsItems}
+                  </Select>
                 </Grid>
               </Grid>
             </DialogContentText>
diff --git a/jams-react-client/src/views/Groups/getBlueprintsOptions.js b/jams-react-client/src/views/Groups/getBlueprintsOptions.js
new file mode 100644
index 00000000..535ab788
--- /dev/null
+++ b/jams-react-client/src/views/Groups/getBlueprintsOptions.js
@@ -0,0 +1,10 @@
+export const getBlueprintsOptions = (blueprints) => {
+  if (blueprints.length === 0) {
+    return [{ value: 0, label: "No blueprint found" }];
+  }
+
+  return blueprints.map((blueprint, i) => ({
+    value: i,
+    label: blueprint.name,
+  }));
+};
-- 
GitLab