Code indexing in gitaly is broken and leads to code not being visible to the user. We work on the issue with highest priority.

Skip to content
Snippets Groups Projects
Commit 548a8667 authored by GotthardG's avatar GotthardG
Browse files

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.
parent 2f5cb303
No related branches found
No related tags found
No related merge requests found
Pipeline #50982 failed
......@@ -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
......
......@@ -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');
......
......@@ -14,7 +14,7 @@ const ResultsView: React.FC<ResultsViewProps> = ({activePgroup
return (
<div>
<h1>Results Page</h1>
<SampleTracker />
<SampleTracker activePgroup={activePgroup}/>
<ResultGrid activePgroup={activePgroup} />
</div>
......
%% Cell type:code id:3b7c27697a4d5c83 tags:
``` python
import json
#from nbclient.client import timestamp
import backend.aareDBclient as aareDBclient
from aareDBclient.rest import ApiException
from pprint import pprint
#from app.data.data import sample
#from aareDBclient import SamplesApi, ShipmentsApi, PucksApi
#from aareDBclient.models import SampleEventCreate, SetTellPosition
#from examples.examples import api_response
print(aareDBclient.__version__)
configuration = aareDBclient.Configuration(
#host = "https://mx-aare-test.psi.ch:1492"
host = "https://127.0.0.1:8000"
)
print(configuration.host)
configuration.verify_ssl = False # Disable SSL verification
#print(dir(SamplesApi))
```
%% Output
0.1.0a21
https://127.0.0.1:8000
%% Cell type:code id:4955b858f2cef93e tags:
``` python
## Fetch all Shipments, list corresponding dewars and pucks
from datetime import date, datetime
from aareDBclient import ShipmentsApi
from aareDBclient.models import Shipment
with aareDBclient.ApiClient(configuration) as api_client:
api_instance = aareDBclient.ShipmentsApi(api_client)
try:
# Fetch all shipments
all_shipments_response = api_instance.fetch_shipments_shipments_get()
# Print shipment names and their associated puck names
for shipment in all_shipments_response:
print(f"Shipment ID: {shipment.id}, Shipment Name: {shipment.shipment_name}")
if hasattr(shipment, 'dewars') and shipment.dewars: # Ensure 'dewars' exists
for dewar in shipment.dewars:
print(f" Dewar ID: {dewar.id}, Dewar Name: {dewar.dewar_name}, Dewar Unique ID: {dewar.unique_id} ")
if hasattr(dewar, 'pucks') and dewar.pucks: # Ensure 'pucks' exists
for puck in dewar.pucks:
print(f" Puck ID: {puck.id}, Puck Name: {puck.puck_name}")
else:
print(" No pucks found in this dewar.")
else:
print(" No dewars found in this shipment.")
except ApiException as e:
print(f"Exception when calling ShipmentsApi->fetch_shipments_shipments_get: {e}")
```
%% Cell type:code id:8fd3638bffaecd23 tags:
``` python
from datetime import date
from aareDBclient import LogisticsApi
from aareDBclient.models import LogisticsEventCreate # Import required model
with aareDBclient.ApiClient(configuration) as api_client:
api_instance = aareDBclient.LogisticsApi(api_client)
try:
# Create payload using the required model
logistics_event_create = LogisticsEventCreate(
dewar_qr_code='923db239427869be',
location_qr_code='A2-X06SA',
transaction_type='incoming',
timestamp=date.today() # Adjust if the API expects datetime
)
# Pass the payload to the API function
api_response = api_instance.scan_dewar_logistics_dewar_scan_post(
logistics_event_create=logistics_event_create # Pass as an object
)
print("API Response:", api_response)
except ApiException as e:
print(f"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}")
try:
# Create payload using the required model
logistics_event_create = LogisticsEventCreate(
dewar_qr_code='923db239427869be',
location_qr_code='A2-X06SA',
transaction_type='refill',
timestamp=date.today() # Adjust if the API expects datetime
)
# Pass the payload to the API function
api_response = api_instance.scan_dewar_logistics_dewar_scan_post(
logistics_event_create=logistics_event_create # Pass as an object
)
print("API Response:", api_response)
except ApiException as e:
print(f"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}")
try:
# Create payload using the required model
logistics_event_create = LogisticsEventCreate(
dewar_qr_code='923db239427869be',
location_qr_code='X06DA-Beamline',
transaction_type='beamline',
timestamp=date.today() # Adjust if the API expects datetime
)
# Pass the payload to the API function
api_response = api_instance.scan_dewar_logistics_dewar_scan_post(
logistics_event_create=logistics_event_create # Pass as an object
)
print("API Response:", api_response)
except ApiException as e:
print(f"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}")
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[43], line 19
15 try:
16 with open(file_path, "rb") as file_data:
17 # Use the low-level call_api method; note that the files parameter here is
18 # a dictionary with key matching the FastAPI parameter name.
---> 19 response = api_client.call_api(
20 f"/{sample_id}/upload_images",
21 "POST",
22 path_params={"sample_id": sample_id},
23 files={"uploaded_file": (filename, file_data, mime_type)}
24 )
25 print("API Response:")
26 print(response)
TypeError: ApiClient.call_api() got an unexpected keyword argument 'path_params'
%% Cell type:code id:9cf3457093751b61 tags:
``` python
# Get a list of pucks that are "at the beamline"
with aareDBclient.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = aareDBclient.PucksApi(api_client)
get_pucks_at_beamline = aareDBclient.PucksApi(api_client)
try:
# Create Return Address
api_response = api_instance.get_pucks_by_slot_pucks_slot_slot_identifier_get(slot_identifier='X06DA')
print("The response of PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get:\n")
pprint(api_response)
except ApiException as e:
print("Exception when calling PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get: %s\n" % e)
```
%% Output
The response of PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get:
[PuckWithTellPosition(id=1, puck_name='PUCK-001', puck_type='Unipuck', puck_location_in_dewar=1, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None),
PuckWithTellPosition(id=2, puck_name='PUCK002', puck_type='Unipuck', puck_location_in_dewar=2, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None),
PuckWithTellPosition(id=3, puck_name='PUCK003', puck_type='Unipuck', puck_location_in_dewar=3, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None),
PuckWithTellPosition(id=4, puck_name='PUCK004', puck_type='Unipuck', puck_location_in_dewar=4, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None),
PuckWithTellPosition(id=5, puck_name='PUCK005', puck_type='Unipuck', puck_location_in_dewar=5, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None),
PuckWithTellPosition(id=6, puck_name='PUCK006', puck_type='Unipuck', puck_location_in_dewar=6, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None),
PuckWithTellPosition(id=7, puck_name='PUCK007', puck_type='Unipuck', puck_location_in_dewar=7, dewar_id=1, dewar_name='Dewar One', pgroup='p20001, p20002', samples=None, tell_position=None)]
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
warnings.warn(
%% Cell type:code id:37e3eac6760150ee tags:
``` python
from aareDBclient import SetTellPosition, SetTellPositionRequest
with aareDBclient.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = aareDBclient.PucksApi(api_client)
# Payload with SetTellPosition objects
payload = SetTellPositionRequest(
tell="X06DA",
#pucks=[
# SetTellPosition(puck_name='PSIMX074', segment='B', puck_in_segment=1),
# SetTellPosition(puck_name='PSIMX080', segment='B', puck_in_segment=2),
# SetTellPosition(puck_name='PSIMX081', segment='C', puck_in_segment=3),
# SetTellPosition(puck_name='PSIMX084', segment='C', puck_in_segment=4),
# SetTellPosition(puck_name='PSIMX104', segment='E', puck_in_segment=5),
# SetTellPosition(puck_name='PSIMX107', segment='E', puck_in_segment=1),
# SetTellPosition(puck_name='PSIMX117', segment='F', puck_in_segment=2),
#]
#pucks=[
# SetTellPosition(puck_name='PSIMX074', segment='F', puck_in_segment=1),
# SetTellPosition(puck_name='PSIMX080', segment='F', puck_in_segment=2),
# SetTellPosition(puck_name='PSIMX107', segment='A', puck_in_segment=1),
# SetTellPosition(puck_name='PSIMX117', segment='A', puck_in_segment=2),
#]
pucks=[
SetTellPosition(puck_name='PUCK006', segment='F', puck_in_segment=1),
SetTellPosition(puck_name='PUCK003', segment='F', puck_in_segment=2),
SetTellPosition(puck_name='PUCK002', segment='A', puck_in_segment=1),
SetTellPosition(puck_name='PUCK001', segment='A', puck_in_segment=2),
]
#pucks = []
)
# Call the PUT method to update the tell_position
try:
api_response = api_instance.set_tell_positions_pucks_set_tell_positions_put(
set_tell_position_request=payload
) # Pass the entire payload as a single parameter
print("The response of PucksApi->pucks_puck_id_tell_position_put:\n")
pprint(api_response)
except Exception as e:
print(f"Exception when calling PucksApi: {e}")
```
%% Output
The response of PucksApi->pucks_puck_id_tell_position_put:
[{'message': 'Tell position updated successfully.',
'new_position': 'F1',
'previous_position': None,
'puck_name': 'PUCK006',
'status': 'updated',
'tell': 'X06DA'},
{'message': 'Tell position updated successfully.',
'new_position': 'F2',
'previous_position': None,
'puck_name': 'PUCK003',
'status': 'updated',
'tell': 'X06DA'},
{'message': 'Tell position updated successfully.',
'new_position': 'A1',
'previous_position': None,
'puck_name': 'PUCK002',
'status': 'updated',
'tell': 'X06DA'},
{'message': 'Tell position updated successfully.',
'new_position': 'A2',
'previous_position': None,
'puck_name': 'PUCK001',
'status': 'updated',
'tell': 'X06DA'}]
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
warnings.warn(
%% Cell type:code id:51578d944878db6a tags:
``` python
# Get puck_id puck_name sample_id sample_name of pucks in the tell
with aareDBclient.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = aareDBclient.PucksApi(api_client)
# GET request: Fetch all pucks in the tell
try:
# Call the API method to fetch pucks
all_pucks_response = api_instance.get_pucks_with_tell_position_pucks_with_tell_position_get(tell='X06DA')
# Debug response structure by printing it in JSON format
formatted_response = json.dumps(
[p.to_dict() for p in all_pucks_response], # Assuming the API response can be converted to dicts
indent=4 # Use indentation for readability
)
#print("The response of PucksApi->get_all_pucks_in_tell (formatted):\n")
#print(formatted_response)
# Iterate through each puck and print information
for p in all_pucks_response:
print(f"Puck ID: {p.id}, Puck Name: {p.puck_name}")
## Check if the puck has any samples
if hasattr(p, 'samples') and p.samples: # Ensure 'samples' attribute exists and is not empty
for sample in p.samples:
print(f" Sample ID: {sample.id}, Sample Name: {sample.sample_name}, Position: {sample.position}, Mount count: {sample.mount_count}")
else:
print(" No samples found in this puck.")
except ApiException as e:
print("Exception when calling PucksApi->get_all_pucks_in_tell: %s\n" % e)
```
%% Output
Puck ID: 6, Puck Name: PUCK006
Sample ID: 44, Sample Name: Sample044, Position: 2, Mount count: 1
Sample ID: 45, Sample Name: Sample045, Position: 3, Mount count: 0
Sample ID: 46, Sample Name: Sample046, Position: 4, Mount count: 0
Sample ID: 47, Sample Name: Sample047, Position: 5, Mount count: 1
Puck ID: 3, Puck Name: PUCK003
Sample ID: 24, Sample Name: Sample024, Position: 1, Mount count: 0
Sample ID: 25, Sample Name: Sample025, Position: 5, Mount count: 1
Sample ID: 26, Sample Name: Sample026, Position: 8, Mount count: 1
Sample ID: 27, Sample Name: Sample027, Position: 11, Mount count: 1
Sample ID: 28, Sample Name: Sample028, Position: 12, Mount count: 1
Puck ID: 2, Puck Name: PUCK002
Sample ID: 17, Sample Name: Sample017, Position: 4, Mount count: 1
Sample ID: 18, Sample Name: Sample018, Position: 5, Mount count: 0
Sample ID: 19, Sample Name: Sample019, Position: 7, Mount count: 1
Sample ID: 20, Sample Name: Sample020, Position: 10, Mount count: 0
Sample ID: 21, Sample Name: Sample021, Position: 11, Mount count: 1
Sample ID: 22, Sample Name: Sample022, Position: 13, Mount count: 0
Sample ID: 23, Sample Name: Sample023, Position: 16, Mount count: 1
Puck ID: 1, Puck Name: PUCK-001
Sample ID: 1, Sample Name: Sample001, Position: 1, Mount count: 1
Sample ID: 2, Sample Name: Sample002, Position: 2, Mount count: 1
Sample ID: 3, Sample Name: Sample003, Position: 3, Mount count: 0
Sample ID: 4, Sample Name: Sample004, Position: 4, Mount count: 0
Sample ID: 5, Sample Name: Sample005, Position: 5, Mount count: 0
Sample ID: 6, Sample Name: Sample006, Position: 6, Mount count: 1
Sample ID: 7, Sample Name: Sample007, Position: 7, Mount count: 0
Sample ID: 8, Sample Name: Sample008, Position: 8, Mount count: 1
Sample ID: 9, Sample Name: Sample009, Position: 9, Mount count: 1
Sample ID: 10, Sample Name: Sample010, Position: 10, Mount count: 1
Sample ID: 11, Sample Name: Sample011, Position: 11, Mount count: 1
Sample ID: 12, Sample Name: Sample012, Position: 12, Mount count: 1
Sample ID: 13, Sample Name: Sample013, Position: 13, Mount count: 0
Sample ID: 14, Sample Name: Sample014, Position: 14, Mount count: 1
Sample ID: 15, Sample Name: Sample015, Position: 15, Mount count: 0
Sample ID: 16, Sample Name: Sample016, Position: 16, Mount count: 0
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
warnings.warn(
%% Cell type:code id:4a0665f92756b486 tags:
``` python
from aareDBclient import SampleEventCreate
# Create an event for a sample
with aareDBclient.ApiClient(configuration) as api_client:
# Instance of the API client
api_instance = aareDBclient.SamplesApi(api_client)
try:
# Define the payload with only `event_type`
sample_event_create = SampleEventCreate(
sample_id=16,
event_type="Mounted" # Valid event type
)
# Debug the payload before sending
print("Payload being sent to API:")
print(sample_event_create.json()) # Ensure it matches `SampleEventCreate`
# Call the API
api_response = api_instance.create_sample_event_samples_samples_sample_id_events_post(
sample_id=16, # Ensure this matches a valid sample ID in the database
sample_event_create=sample_event_create
)
print("API response:")
#pprint(api_response)
for p in api_response:
print(p)
except ApiException as e:
print("Exception when calling post_sample_event:")
print(f"Status Code: {e.status}")
if e.body:
print(f"Error Details: {e.body}")
```
%% Output
Payload being sent to API:
{"event_type":"Mounted"}
API response:
('id', 16)
('sample_name', 'Sample016')
('position', 16)
('puck_id', 1)
('crystalname', None)
('proteinname', None)
('positioninpuck', None)
('priority', None)
('comments', None)
('data_collection_parameters', None)
('events', [SampleEventResponse(id=399, sample_id=16, event_type='Mounted', timestamp=datetime.datetime(2025, 2, 26, 13, 5, 3))])
('mount_count', 1)
('unmount_count', 0)
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
warnings.warn(
%% Cell type:code id:f1d171700d6cf7fe tags:
``` python
### not working
with aareDBclient.ApiClient(configuration) as api_client:
# Create an instance of the Samples API class
api_instance = aareDBclient.SamplesApi(api_client)
try:
# Get the last sample event
last_event_response = api_instance.get_last_sample_event_samples_samples_sample_id_events_last_get(27)
print("The response of get_last_sample_event:\n")
pprint(last_event_response)
except ApiException as e:
print("Exception when calling get_last_sample_event: %s\n" % e)
```
%% Cell type:code id:11f62976d2e7d9b1 tags:
``` python
import os
import mimetypes
import requests
# File path to the image
file_path = "backend/tests/sample_image/IMG_1942.jpg"
filename = os.path.basename(file_path)
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type is None:
mime_type = "application/octet-stream"
# Sample ID (ensure this exists on your backend)
sample_id = 16
# Build the URL for the upload endpoint.
url = f"https://127.0.0.1:8000/samples/{sample_id}/upload-images"
# Open the file and construct the files dictionary
with open(file_path, "rb") as file_data:
files = {
# Use key "uploaded_file" as required by your API
"uploaded_file": (filename, file_data, mime_type)
}
headers = {
"accept": "application/json"
}
comment = "before loop centering"
# Set verify=False to bypass certificate verification (only use in development)
response = requests.post(url, headers=headers, files=files, verify=False)
# Check the API response
print("API Response:")
print(response.status_code)
try:
print(response.json())
except Exception:
print(response.text)
```
%% Output
API Response:
200
{'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}
{'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}
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
warnings.warn(
%% Cell type:code id:cb1b99e6327fff84 tags:
``` python
help(api_instance.upload_sample_images_samples_samples_sample_id_upload_images_post)
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment