From e79635fab3c6e1934e760070e9f4e70eac067141 Mon Sep 17 00:00:00 2001
From: Jabar Jeremy <24471994+jabahum@users.noreply.github.com>
Date: Mon, 18 Dec 2023 09:06:14 +0300
Subject: [PATCH] feat(stock) : U4X-289 Deleting stocksources (#47)

---
 .../add-stock-sources.component.tsx           |  4 +-
 .../edit-stock-source.component.tsx           | 47 ++++++------
 .../stock-sources-delete.component.tsx        | 76 +++++++++++++++----
 .../stock-sources-items-table.component.tsx   | 38 +++-------
 4 files changed, 96 insertions(+), 69 deletions(-)

diff --git a/src/stock-sources/add-stock-sources/add-stock-sources.component.tsx b/src/stock-sources/add-stock-sources/add-stock-sources.component.tsx
index 733b5d87..f991a747 100644
--- a/src/stock-sources/add-stock-sources/add-stock-sources.component.tsx
+++ b/src/stock-sources/add-stock-sources/add-stock-sources.component.tsx
@@ -28,7 +28,7 @@ const StockSourcesAddOrUpdate: React.FC<AddStockSourceProps> = ({ model }) => {
   // get stock sources
   const { items } = useConceptById(STOCK_SOURCE_TYPE_CODED_CONCEPT_ID);
 
-  const [formModel, setFormModel] = useState<StockSource>();
+  const [formModel, setFormModel] = useState<StockSource>({ ...model });
 
   const onNameChanged = (evt: React.ChangeEvent<HTMLInputElement>): void => {
     model ? (model.name = evt.target.value) : "";
@@ -78,7 +78,7 @@ const StockSourcesAddOrUpdate: React.FC<AddStockSourceProps> = ({ model }) => {
         )
         .catch();
     },
-    [formModel, t]
+    [formModel, model, t]
   );
   return (
     <div>
diff --git a/src/stock-sources/edit-stock-source/edit-stock-source.component.tsx b/src/stock-sources/edit-stock-source/edit-stock-source.component.tsx
index f3537e7b..d12784e6 100644
--- a/src/stock-sources/edit-stock-source/edit-stock-source.component.tsx
+++ b/src/stock-sources/edit-stock-source/edit-stock-source.component.tsx
@@ -1,32 +1,35 @@
-import { Button, Tooltip } from "@carbon/react";
+import React, { useCallback } from "react";
+import { Button } from "@carbon/react";
 import { Edit } from "@carbon/react/icons";
-import { interpolateUrl, navigate } from "@openmrs/esm-framework";
 
-import React, { AnchorHTMLAttributes } from "react";
 import { useTranslation } from "react-i18next";
+import { launchOverlay } from "../../core/components/overlay/hook";
+import StockSourcesAddOrUpdate from "../add-stock-sources/add-stock-sources.component";
+import { StockSource } from "../../core/api/types/stockOperation/StockSource";
 
-interface NameLinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
-  to: string;
-  from: string;
+interface EditStockSourcesActionMenuProps {
+  data?: StockSource;
 }
 
-const EditSourceActionsMenu: React.FC<NameLinkProps> = ({ from, to }) => {
+const EditStockSourceActionsMenu: React.FC<EditStockSourcesActionMenuProps> = ({
+  data,
+}) => {
   const { t } = useTranslation();
-  const handleNameClick = (event: MouseEvent, to: string) => {
-    event.preventDefault();
-    navigate({ to });
-    localStorage.setItem("fromPage", from);
-  };
+  const handleClick = useCallback(() => {
+    launchOverlay(
+      "Edit Stock Source",
+      <StockSourcesAddOrUpdate model={data} />
+    );
+  }, [data]);
+
   return (
-    <Tooltip align="bottom" label="Edit Patient">
-      <Button
-        kind="ghost"
-        onClick={(e) => handleNameClick(e, to)}
-        href={interpolateUrl(to)}
-        iconDescription={t("editSource", "Edit Source")}
-        renderIcon={(props) => <Edit size={16} {...props} />}
-      ></Button>
-    </Tooltip>
+    <Button
+      kind="ghost"
+      size="md"
+      onClick={() => handleClick()}
+      iconDescription={t("editStockItem", "Edit Stock Item")}
+      renderIcon={(props) => <Edit size={16} {...props} />}
+    />
   );
 };
-export default EditSourceActionsMenu;
+export default EditStockSourceActionsMenu;
diff --git a/src/stock-sources/stock-sources-delete/stock-sources-delete.component.tsx b/src/stock-sources/stock-sources-delete/stock-sources-delete.component.tsx
index dab6c235..55ceeddc 100644
--- a/src/stock-sources/stock-sources-delete/stock-sources-delete.component.tsx
+++ b/src/stock-sources/stock-sources-delete/stock-sources-delete.component.tsx
@@ -1,20 +1,64 @@
-import React from "react";
-import { Button, Form, ModalFooter, ModalHeader } from "@carbon/react";
+import React, { useState } from "react";
+import { Button, InlineLoading } from "@carbon/react";
+import { useTranslation } from "react-i18next";
+import { TrashCan } from "@carbon/react/icons";
+import { deleteStockSource } from "../stock-sources.resource";
+import { showNotification, showToast } from "@openmrs/esm-framework";
 
-const StockSourcesDelete: React.FC = () => {
-  return (
-    <div>
-      <Form>
-        <ModalHeader />
-        <ModalFooter>
-          <Button kind="secondary">Cancel</Button>
-          <Button kind="danger" type="submit">
-            Delete
-          </Button>
-        </ModalFooter>
-      </Form>
-    </div>
+interface StockSourcesDeleteActionMenuProps {
+  uuid: string;
+}
+
+const StockSourcesDeleteActionMenu: React.FC<
+  StockSourcesDeleteActionMenuProps
+> = ({ uuid }) => {
+  const { t } = useTranslation();
+
+  const [deletingSource, setDeletingSource] = useState(false);
+
+  const handleClick = (e) => {
+    e.preventDefault();
+    setDeletingSource(true);
+    const ids = [];
+    ids.push(uuid);
+    deleteStockSource(ids)
+      .then(
+        () => {
+          setDeletingSource(false);
+          showToast({
+            critical: true,
+            title: t("deletingSource", "Delete Source"),
+            kind: "success",
+            description: t(
+              "stocksourcedeletedsuccessfully",
+              "Stock Source Deleted Successfully"
+            ),
+          });
+        },
+        (error) => {
+          setDeletingSource(false);
+          showNotification({
+            title: t(`errorDeletingSource', 'error deleting a source`),
+            kind: "error",
+            critical: true,
+            description: error?.message,
+          });
+        }
+      )
+      .catch();
+  };
+
+  const deleteButton = (
+    <Button
+      kind="ghost"
+      size="md"
+      onClick={handleClick}
+      iconDescription={t("deleteSource", "Delete Source")}
+      renderIcon={(props) => <TrashCan size={16} {...props} />}
+    />
   );
+
+  return deletingSource ? <InlineLoading /> : deleteButton;
 };
 
-export default StockSourcesDelete;
+export default StockSourcesDeleteActionMenu;
diff --git a/src/stock-sources/stock-sources-items-table.component.tsx b/src/stock-sources/stock-sources-items-table.component.tsx
index a4d8ce34..178ccd07 100644
--- a/src/stock-sources/stock-sources-items-table.component.tsx
+++ b/src/stock-sources/stock-sources-items-table.component.tsx
@@ -16,19 +16,16 @@ import {
   TableToolbarMenu,
   DataTableSkeleton,
   TableToolbarSearch,
-  Button,
-  Tooltip,
 } from "@carbon/react";
 import { isDesktop } from "@openmrs/esm-framework";
-import { Edit } from "@carbon/react/icons";
 import useStockSourcesPage from "./stock-sources-items-table.resource";
 import { ResourceRepresentation } from "../core/api/api";
 import AddStockSourceActionButton from "./add-stock-source-button.component";
 import StockSourcesFilter from "./stock-sources-filter/stock-sources-filter.component";
 import styles from "./stock-sources.scss";
 import { useTranslation } from "react-i18next";
-import { launchOverlay } from "../core/components/overlay/hook";
-import StockSourcesAddOrUpdate from "./add-stock-sources/add-stock-sources.component";
+import StockSourcesDeleteActionMenu from "./stock-sources-delete/stock-sources-delete.component";
+import EditStockSourceActionsMenu from "./edit-stock-source/edit-stock-source.component";
 
 function StockSourcesItems() {
   const { t } = useTranslation();
@@ -49,31 +46,8 @@ function StockSourcesItems() {
     totalCount: true,
   });
 
-  const handleClick = useCallback((data: any) => {
-    launchOverlay(
-      "Edit Stock Source",
-      <StockSourcesAddOrUpdate model={data} />
-    );
-  }, []);
-
-  if (items) {
-    items.forEach((row) => {
-      row["actions"] = (
-        <Tooltip align="bottom" label="Edit Stock Item">
-          <Button
-            kind="ghost"
-            size="md"
-            onClick={() => handleClick(row)}
-            iconDescription={t("editStockItem", "Edit Stock Item")}
-            renderIcon={(props) => <Edit size={16} {...props} />}
-          ></Button>
-        </Tooltip>
-      );
-    });
-  }
-
   const tableRows = useMemo(() => {
-    return items?.map((entry) => {
+    return items?.map((entry, index) => {
       return {
         ...entry,
         id: entry?.uuid,
@@ -82,6 +56,12 @@ function StockSourcesItems() {
         name: entry?.name,
         acronym: entry?.acronym,
         sourceType: entry?.sourceType?.display,
+        actions: (
+          <>
+            <EditStockSourceActionsMenu data={items[index]} />
+            <StockSourcesDeleteActionMenu uuid={items[index].uuid} />
+          </>
+        ),
       };
     });
   }, [items]);