From 086fc3518841c9c2a07797f4a842000817ce8b42 Mon Sep 17 00:00:00 2001
From: Jackie Han <jkhanjob@gmail.com>
Date: Tue, 11 Jun 2024 15:02:50 -0700
Subject: [PATCH] mds feature anywhere associated detectors fix (#778)

* mds feature anywhere associated detectors fix

Signed-off-by: Jackie Han <jkhanjob@gmail.com>

* update getDetectors call in associate existing detector flyout

Signed-off-by: Jackie Han <jkhanjob@gmail.com>

---------

Signed-off-by: Jackie Han <jkhanjob@gmail.com>
---
 .../containers/AssociatedDetectors.tsx        | 42 ++++++++++++++++---
 .../AddAnomalyDetector.tsx                    |  4 +-
 .../containers/AssociateExisting.tsx          | 30 +++++++++++--
 3 files changed, 64 insertions(+), 12 deletions(-)

diff --git a/public/components/FeatureAnywhereContextMenu/AssociatedDetectors/containers/AssociatedDetectors.tsx b/public/components/FeatureAnywhereContextMenu/AssociatedDetectors/containers/AssociatedDetectors.tsx
index 1cbdbc82..bc0a6891 100644
--- a/public/components/FeatureAnywhereContextMenu/AssociatedDetectors/containers/AssociatedDetectors.tsx
+++ b/public/components/FeatureAnywhereContextMenu/AssociatedDetectors/containers/AssociatedDetectors.tsx
@@ -26,6 +26,7 @@ import {
   getSavedFeatureAnywhereLoader,
   getNotifications,
   getUISettings,
+  getSavedObjectsClient,
 } from '../../../../services';
 import {
   GET_ALL_DETECTORS_QUERY_PARAMS,
@@ -47,6 +48,7 @@ import {
 } from '../../../../../../../src/plugins/vis_augmenter/public';
 import { ASSOCIATED_DETECTOR_ACTION } from '../utils/constants';
 import { PLUGIN_AUGMENTATION_MAX_OBJECTS_SETTING } from '../../../../../public/expressions/constants';
+import { getAllDetectorsQueryParamsWithDataSourceId } from '../../../../../public/pages/utils/helpers';
 
 interface ConfirmModalState {
   isOpen: boolean;
@@ -56,6 +58,12 @@ interface ConfirmModalState {
   affectedDetector: DetectorListItem;
 }
 
+interface References {
+  id: string;
+  name: string;
+  type: string;
+}
+
 function AssociatedDetectors({ embeddable, closeFlyout, setMode }) {
   const dispatch = useDispatch();
   const allDetectors = useSelector((state: AppState) => state.ad.detectorList);
@@ -69,6 +77,20 @@ function AssociatedDetectors({ embeddable, closeFlyout, setMode }) {
     (state: AppState) => state.ad.errorMessage
   );
   const embeddableTitle = embeddable.getTitle();
+  const indexPatternId = embeddable.vis.data.aggs.indexPattern.id;
+  const [dataSourceId, setDataSourceId] = useState<string | undefined>(undefined);
+
+  async function getDataSourceId() {
+    try {
+      const indexPattern = await getSavedObjectsClient().get('index-pattern', indexPatternId);
+      const refs = indexPattern.references as References[];
+      const foundDataSourceId = refs.find(ref => ref.type === 'data-source')?.id;
+      setDataSourceId(foundDataSourceId); 
+    } catch (error) {
+      console.error("Error fetching index pattern:", error);
+    }
+  }
+
   const [selectedDetectors, setSelectedDetectors] = useState(
     [] as DetectorListItem[]
   );
@@ -135,8 +157,12 @@ function AssociatedDetectors({ embeddable, closeFlyout, setMode }) {
   }, [confirmModalState.isRequestingToClose, isLoading]);
 
   useEffect(() => {
-    getDetectors();
-  }, []);
+    async function fetchData() {
+      await getDataSourceId();
+      getDetectors();
+    }
+    fetchData();
+  }, [dataSourceId]);
 
   // Handles all changes in the assoicated detectors such as unlinking or new detectors associated
   useEffect(() => {
@@ -175,9 +201,9 @@ function AssociatedDetectors({ embeddable, closeFlyout, setMode }) {
   ) => {
     // Map all detector IDs for all the found augmented vis objects
     const savedAugmentDetectorsSet = new Set(
-      savedAugmentForThisVisualization.map((savedObject) =>
-        get(savedObject, 'pluginResource.id', '')
-      )
+      savedAugmentForThisVisualization
+        .map(savedObject => get(savedObject, 'pluginResource.id', ''))
+        .filter(id => id !== '')
     );
 
     // filter out any detectors that aren't on the set of detectors IDs from the augmented vis objects.
@@ -240,7 +266,11 @@ function AssociatedDetectors({ embeddable, closeFlyout, setMode }) {
   };
 
   const getDetectors = async () => {
-    dispatch(getDetectorList(GET_ALL_DETECTORS_QUERY_PARAMS));
+    dispatch(
+      getDetectorList(
+        getAllDetectorsQueryParamsWithDataSourceId(dataSourceId)
+      )
+    );  
   };
 
   const handleUnlinkDetectorAction = (detector: DetectorListItem) => {
diff --git a/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AddAnomalyDetector.tsx b/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AddAnomalyDetector.tsx
index 1b4fd4ba..f750f8e2 100644
--- a/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AddAnomalyDetector.tsx
+++ b/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AddAnomalyDetector.tsx
@@ -366,7 +366,7 @@ function AddAnomalyDetector({
       const detectorToCreate = formikToDetector(formikProps.values);
       await dispatch(createDetector(detectorToCreate, dataSourceId))
         .then(async (response) => {
-          dispatch(startDetector(response.response.id))
+          dispatch(startDetector(response.response.id, dataSourceId))
             .then((startDetectorResponse) => {})
             .catch((err: any) => {
               notifications.toasts.addDanger(
@@ -651,7 +651,7 @@ function AddAnomalyDetector({
                       embeddableVisId={embeddable.vis.id}
                       selectedDetector={selectedDetector}
                       setSelectedDetector={setSelectedDetector}
-                      dataSourceId={dataSourceId}
+                      indexPatternId={indexPatternId}
                     ></AssociateExisting>
                   )}
                   {mode === FLYOUT_MODES.create && (
diff --git a/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AssociateExisting/containers/AssociateExisting.tsx b/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AssociateExisting/containers/AssociateExisting.tsx
index cb3f29fd..63d53b15 100644
--- a/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AssociateExisting/containers/AssociateExisting.tsx
+++ b/public/components/FeatureAnywhereContextMenu/CreateAnomalyDetector/AssociateExisting/containers/AssociateExisting.tsx
@@ -34,6 +34,7 @@ import {
 import { getDetectorList } from '../../../../../redux/reducers/ad';
 import {
   getSavedFeatureAnywhereLoader,
+  getSavedObjectsClient,
   getUISettings,
 } from '../../../../../services';
 import {
@@ -53,7 +54,12 @@ interface AssociateExistingProps {
   embeddableVisId: string;
   selectedDetector: DetectorListItem | undefined;
   setSelectedDetector(detector: DetectorListItem | undefined): void;
-  dataSourceId: string | undefined;
+  indexPatternId: string;
+}
+interface References {
+  id: string;
+  name: string;
+  type: string;
 }
 
 export function AssociateExisting(
@@ -65,6 +71,18 @@ export function AssociateExisting(
   const isRequestingFromES = useSelector(
     (state: AppState) => state.ad.requesting
   );
+  const [dataSourceId, setDataSourceId] = useState<string | undefined>(undefined);
+
+  async function getDataSourceId() {
+    try {
+      const indexPattern = await getSavedObjectsClient().get('index-pattern', associateExistingProps.indexPatternId);
+      const refs = indexPattern.references as References[];
+      const foundDataSourceId = refs.find(ref => ref.type === 'data-source')?.id;
+      setDataSourceId(foundDataSourceId); 
+    } catch (error) {
+      console.error("Error fetching index pattern:", error);
+    }
+  }
   const uiSettings = getUISettings();
   const [isLoadingFinalDetectors, setIsLoadingFinalDetectors] =
     useState<boolean>(true);
@@ -145,11 +163,15 @@ export function AssociateExisting(
   };
 
   useEffect(() => {
-    getDetectors();
-  }, []);
+    async function fetchData() {
+      await getDataSourceId();
+      getDetectors();
+    }
+    fetchData();
+  }, [dataSourceId]);
 
   const getDetectors = async () => {
-    dispatch(getDetectorList(getAllDetectorsQueryParamsWithDataSourceId(associateExistingProps.dataSourceId)));
+    dispatch(getDetectorList(getAllDetectorsQueryParamsWithDataSourceId(dataSourceId)));
   };
 
   const selectedOptions = useMemo(() => {