From 548a86678b0a34c5df00412163958d3a40f15fb8 Mon Sep 17 00:00:00 2001
From: GotthardG <51994228+GotthardG@users.noreply.github.com>
Date: Thu, 27 Feb 2025 11:20:04 +0100
Subject: [PATCH] Update `SampleTracker` to support dynamic `activePgroup`

Enhanced the `SampleTracker` component to accept and utilize an `activePgroup` prop, allowing dynamic filtering of data based on the current project group. Adjusted related polling and data fetching logic to respond to changes in `activePgroup`. Removed excessive code from the test notebook for cleanup.
---
 backend/app/routers/sample.py             | 35 ++++++++++++++++++-----
 frontend/src/components/SampleTracker.tsx | 22 +++++++-------
 frontend/src/pages/ResultsView.tsx        |  2 +-
 testfunctions.ipynb                       |  9 +++---
 4 files changed, 46 insertions(+), 22 deletions(-)

diff --git a/backend/app/routers/sample.py b/backend/app/routers/sample.py
index f5a6786..20e034e 100644
--- a/backend/app/routers/sample.py
+++ b/backend/app/routers/sample.py
@@ -46,23 +46,44 @@ async def get_samples_with_events(puck_id: int, db: Session = Depends(get_db)):
 
 
 @router.get("/pucks-samples", response_model=List[PuckSchema])
-async def get_all_pucks_with_samples_and_events(db: Session = Depends(get_db)):
-    logging.info("Fetching all pucks with samples and events")
+async def get_all_pucks_with_samples_and_events(
+    active_pgroup: str, db: Session = Depends(get_db)
+):
+    logging.info(
+        "Fetching all pucks with " "samples and events for active_pgroup: %s",
+        active_pgroup,
+    )
 
     pucks = (
         db.query(PuckModel)
+        .join(PuckModel.samples)  # Join samples related to the puck
+        .join(PuckModel.dewar)  # Join the dewar from the puck
+        .join(SampleModel.events)  # Join sample events
+        .filter(DewarModel.pgroups == active_pgroup)  # Filter by the dewar's group
         .options(
-            joinedload(PuckModel.samples).joinedload(
-                SampleModel.events
-            ),  # Correct nested relationship
-            joinedload(PuckModel.events),  # If Puck has its own events relationship
+            joinedload(PuckModel.samples).joinedload(SampleModel.events),
+            joinedload(PuckModel.dewar),
         )
+        .distinct()  # Avoid duplicate puck rows if there are multiple events/samples
         .all()
     )
 
     if not pucks:
-        raise HTTPException(status_code=404, detail="No pucks found in the database")
+        raise HTTPException(
+            status_code=404,
+            detail="No pucks found with" " sample events for the active pgroup",
+        )
+
+    # Extract samples from each puck if needed
+    filtered_samples = []
+    for puck in pucks:
+        if puck.dewar and getattr(puck.dewar, "pgroups", None) == active_pgroup:
+            for sample in puck.samples:
+                filtered_samples.append(sample)
 
+    # Depending on what your endpoint expects,
+    # you may choose to return pucks or samples.
+    # For now, we're returning the list of pucks.
     return pucks
 
 
diff --git a/frontend/src/components/SampleTracker.tsx b/frontend/src/components/SampleTracker.tsx
index aba025d..c10442a 100644
--- a/frontend/src/components/SampleTracker.tsx
+++ b/frontend/src/components/SampleTracker.tsx
@@ -26,35 +26,37 @@ interface Puck {
   samples: Sample[];
 }
 
-const SampleTracker: React.FC = () => {
+interface SampleTrackerProps {
+  activePgroup: string;
+}
+
+const SampleTracker: React.FC<SampleTrackerProps> = ({ activePgroup }) => {
   const [pucks, setPucks] = useState<Puck[]>([]);
   const [hoveredSample, setHoveredSample] = useState<{ name: string; status: string } | null>(null);
 
+
   // Fetch latest sample data
   const fetchPucks = async () => {
     try {
-      const data: Puck[] = await SamplesService.getAllPucksWithSamplesAndEventsSamplesPucksSamplesGet();
-
-      console.log('Fetched Pucks:', data); // Check for dynamic mount_count and unmount_count
+      const data: Puck[] = await SamplesService.getAllPucksWithSamplesAndEventsSamplesPucksSamplesGet(activePgroup);
+      console.log('Fetched Pucks:', data);
       setPucks(data);
     } catch (error) {
       console.error('Error fetching pucks', error);
     }
   };
 
+
   // Polling logic using a 1-second interval
   useEffect(() => {
-    // Fetch data immediately on component mount
     fetchPucks();
-
-    // Set up polling every 1 second
     const interval = setInterval(() => {
       fetchPucks();
-    }, 100000);
+    }, 1000);
 
-    // Clear interval on component unmount
     return () => clearInterval(interval);
-  }, []);
+  }, [activePgroup]);
+
 
   const getSampleColor = (events: Event[] = []) => {
     const hasMounted = events.some((e) => e.event_type === 'Mounted');
diff --git a/frontend/src/pages/ResultsView.tsx b/frontend/src/pages/ResultsView.tsx
index b75db2e..5e52b59 100644
--- a/frontend/src/pages/ResultsView.tsx
+++ b/frontend/src/pages/ResultsView.tsx
@@ -14,7 +14,7 @@ const ResultsView: React.FC<ResultsViewProps> = ({activePgroup
     return (
         <div>
             <h1>Results Page</h1>
-            <SampleTracker />
+            <SampleTracker activePgroup={activePgroup}/>
             <ResultGrid activePgroup={activePgroup} />
         </div>
 
diff --git a/testfunctions.ipynb b/testfunctions.ipynb
index 24581f0..fdc21e5 100644
--- a/testfunctions.ipynb
+++ b/testfunctions.ipynb
@@ -528,8 +528,8 @@
   {
    "metadata": {
     "ExecuteTime": {
-     "end_time": "2025-02-26T13:17:13.591355Z",
-     "start_time": "2025-02-26T13:17:13.561947Z"
+     "end_time": "2025-02-26T16:15:33.052345Z",
+     "start_time": "2025-02-26T16:15:33.022632Z"
     }
    },
    "cell_type": "code",
@@ -560,6 +560,7 @@
     "    headers = {\n",
     "        \"accept\": \"application/json\"\n",
     "    }\n",
+    "    comment = \"before loop centering\"\n",
     "\n",
     "    # Set verify=False to bypass certificate verification (only use in development)\n",
     "    response = requests.post(url, headers=headers, files=files, verify=False)\n",
@@ -580,7 +581,7 @@
      "text": [
       "API Response:\n",
       "200\n",
-      "{'pgroup': 'p20001', 'sample_id': 16, 'filepath': 'images/p20001/2025-02-26/Dewar One/PUCK-001/16/IMG_1942.jpg', 'status': 'active', 'comment': None, 'id': 3}\n"
+      "{'pgroup': 'p20001', 'sample_id': 16, 'filepath': 'images/p20001/2025-02-26/Dewar One/PUCK-001/16/IMG_1942.jpg', 'status': 'active', 'comment': None, 'id': 4}\n"
      ]
     },
     {
@@ -592,7 +593,7 @@
      ]
     }
    ],
-   "execution_count": 88
+   "execution_count": 89
   },
   {
    "metadata": {},
-- 
GitLab