sapiopycommons 2025.4.9a150__py3-none-any.whl → 2025.4.9a476__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of sapiopycommons might be problematic. Click here for more details.

Files changed (42) hide show
  1. sapiopycommons/callbacks/callback_util.py +1262 -392
  2. sapiopycommons/callbacks/field_builder.py +2 -0
  3. sapiopycommons/chem/Molecules.py +0 -2
  4. sapiopycommons/customreport/auto_pagers.py +281 -0
  5. sapiopycommons/customreport/term_builder.py +1 -1
  6. sapiopycommons/datatype/attachment_util.py +4 -2
  7. sapiopycommons/datatype/data_fields.py +23 -1
  8. sapiopycommons/eln/experiment_cache.py +173 -0
  9. sapiopycommons/eln/experiment_handler.py +933 -279
  10. sapiopycommons/eln/experiment_report_util.py +15 -10
  11. sapiopycommons/eln/experiment_step_factory.py +474 -0
  12. sapiopycommons/eln/experiment_tags.py +7 -0
  13. sapiopycommons/eln/plate_designer.py +159 -59
  14. sapiopycommons/eln/step_creation.py +235 -0
  15. sapiopycommons/files/file_bridge.py +76 -0
  16. sapiopycommons/files/file_bridge_handler.py +325 -110
  17. sapiopycommons/files/file_data_handler.py +2 -2
  18. sapiopycommons/files/file_util.py +40 -15
  19. sapiopycommons/files/file_validator.py +6 -5
  20. sapiopycommons/files/file_writer.py +1 -1
  21. sapiopycommons/flowcyto/flow_cyto.py +1 -1
  22. sapiopycommons/general/accession_service.py +3 -3
  23. sapiopycommons/general/aliases.py +51 -28
  24. sapiopycommons/general/audit_log.py +2 -2
  25. sapiopycommons/general/custom_report_util.py +24 -1
  26. sapiopycommons/general/data_structure_util.py +115 -0
  27. sapiopycommons/general/directive_util.py +86 -0
  28. sapiopycommons/general/exceptions.py +41 -2
  29. sapiopycommons/general/popup_util.py +2 -2
  30. sapiopycommons/multimodal/multimodal.py +1 -0
  31. sapiopycommons/processtracking/custom_workflow_handler.py +46 -30
  32. sapiopycommons/recordmodel/record_handler.py +547 -159
  33. sapiopycommons/rules/eln_rule_handler.py +41 -30
  34. sapiopycommons/rules/on_save_rule_handler.py +41 -30
  35. sapiopycommons/samples/aliquot.py +48 -0
  36. sapiopycommons/webhook/webhook_handlers.py +448 -55
  37. sapiopycommons/webhook/webservice_handlers.py +2 -2
  38. {sapiopycommons-2025.4.9a150.dist-info → sapiopycommons-2025.4.9a476.dist-info}/METADATA +1 -1
  39. sapiopycommons-2025.4.9a476.dist-info/RECORD +67 -0
  40. sapiopycommons-2025.4.9a150.dist-info/RECORD +0 -59
  41. {sapiopycommons-2025.4.9a150.dist-info → sapiopycommons-2025.4.9a476.dist-info}/WHEEL +0 -0
  42. {sapiopycommons-2025.4.9a150.dist-info → sapiopycommons-2025.4.9a476.dist-info}/licenses/LICENSE +0 -0
@@ -443,6 +443,8 @@ class FieldBuilder:
443
443
  raise SapioException("Unable to set multiple list modes at once for a selection list.")
444
444
  # Static values don't have a list mode. Evaluate this last so that the multiple list modes check doesn't
445
445
  # need to be more complex.
446
+ # PR-47531: Even though static values don't use an existing list mode, a list mode must still be set.
447
+ list_mode = ListMode.USER
446
448
 
447
449
  if not list_mode and static_values is None:
448
450
  raise SapioException("A list mode must be chosen for selection list fields.")
@@ -1,6 +1,5 @@
1
1
  # Author Yechen Qiao
2
2
  # Common Molecule Utilities for Molecule Transfers with Sapio
3
- from typing import cast
4
3
 
5
4
  from rdkit import Chem
6
5
  from rdkit.Chem import Crippen, MolToInchi
@@ -9,7 +8,6 @@ from rdkit.Chem import rdMolDescriptors
9
8
  from rdkit.Chem.EnumerateStereoisomers import StereoEnumerationOptions, EnumerateStereoisomers
10
9
  from rdkit.Chem.MolStandardize import rdMolStandardize
11
10
  from rdkit.Chem.SaltRemover import SaltRemover
12
- from rdkit.Chem.rdChemReactions import ChemicalReaction
13
11
  from rdkit.Chem.rdchem import Mol, RWMol, Bond
14
12
 
15
13
  from sapiopycommons.chem.IndigoMolecules import indigo, renderer, indigo_inchi
@@ -0,0 +1,281 @@
1
+ from abc import ABC
2
+ from copy import copy
3
+ from queue import Queue
4
+
5
+ from sapiopylib.rest.CustomReportService import CustomReportManager
6
+ from sapiopylib.rest.DataMgmtService import DataMgmtServer
7
+ from sapiopylib.rest.pojo.CustomReport import CustomReportCriteria, CustomReport, RawReportTerm, ReportColumn
8
+ from sapiopylib.rest.pojo.datatype.FieldDefinition import FieldType
9
+ # noinspection PyProtectedMember
10
+ from sapiopylib.rest.utils.autopaging import SapioPyAutoPager, PagerResultCriteriaType, _default_report_page_size, \
11
+ _default_record_page_size
12
+ from sapiopylib.rest.utils.recordmodel.PyRecordModel import PyRecordModel
13
+ from sapiopylib.rest.utils.recordmodel.RecordModelWrapper import WrappedType
14
+
15
+ from sapiopycommons.general.aliases import FieldValue, UserIdentifier, AliasUtil, RecordModel
16
+ from sapiopycommons.general.custom_report_util import CustomReportUtil
17
+ from sapiopycommons.general.exceptions import SapioException
18
+ from sapiopycommons.recordmodel.record_handler import RecordHandler
19
+
20
+
21
+ # FR-47389: Create auto pagers for running custom/system/quick reports that return dictionaries or records for each row.
22
+ class _DictReportPagerBase(SapioPyAutoPager[CustomReportCriteria, dict[str, FieldValue]], ABC):
23
+ """
24
+ A base class for automatically paging through a report and returning the results as a list of dictionaries.
25
+ """
26
+ _columns: list[ReportColumn]
27
+ _report_man: CustomReportManager
28
+
29
+ def __init__(self, user: UserIdentifier, first_page_criteria: CustomReportCriteria):
30
+ self._columns = first_page_criteria.column_list
31
+ super().__init__(AliasUtil.to_sapio_user(user), first_page_criteria)
32
+ self._report_man = DataMgmtServer.get_custom_report_manager(self.user)
33
+
34
+ def get_all_at_once(self) -> list[dict[str, FieldValue]]:
35
+ """
36
+ Get the results of all pages. Be cautious of client memory usage.
37
+ """
38
+ if self.has_iterated:
39
+ raise BrokenPipeError("Cannot use this method if the iterator has already been used.")
40
+ return [x for x in self]
41
+
42
+ def default_first_page_criteria(self) -> PagerResultCriteriaType:
43
+ raise ValueError("Cannot generate a default first page criteria for custom reports.")
44
+
45
+ def get_next_page_result(self) -> tuple[CustomReportCriteria | None, Queue[dict[str, FieldValue]]]:
46
+ report: CustomReport = self._report_man.run_custom_report(self.next_page_criteria)
47
+ queue: Queue[dict[str, FieldValue]] = Queue()
48
+ for row in _process_results(report.result_table, self._columns):
49
+ queue.put(row)
50
+ if report.has_next_page:
51
+ next_page_criteria = copy(self.next_page_criteria)
52
+ next_page_criteria.page_number += 1
53
+ return next_page_criteria, queue
54
+ else:
55
+ return None, queue
56
+
57
+
58
+ class CustomReportDictAutoPager(_DictReportPagerBase):
59
+ """
60
+ A class that automatically pages through a custom report and returns the results as a list of dictionaries.
61
+ """
62
+ def __init__(self, user: UserIdentifier, report_criteria: CustomReportCriteria,
63
+ page_number: int = 0, page_size: int = _default_report_page_size):
64
+ """
65
+ :param user: The current webhook context or a user object to send requests from.
66
+ :param report_criteria: The custom report criteria to run.
67
+ :param page_number: The page number to start on. The first page is page 0.
68
+ :param page_size: The number of results to return per page.
69
+ """
70
+ first_page_criteria: CustomReportCriteria = copy(report_criteria)
71
+ first_page_criteria.page_number = page_number
72
+ first_page_criteria.page_size = page_size
73
+ super().__init__(user, first_page_criteria)
74
+
75
+
76
+ class SystemReportDictAutoPager(_DictReportPagerBase):
77
+ """
78
+ A class that automatically pages through a system report and returns the results as a list of dictionaries.
79
+
80
+ System reports are also known as predefined searches in the system and must be defined in the data designer for
81
+ a specific data type. That is, saved searches created by users cannot be run using this function.
82
+ """
83
+ def __init__(self, user: UserIdentifier, report_name: str,
84
+ page_number: int = 0, page_size: int = _default_report_page_size):
85
+ """
86
+ :param user: The current webhook context or a user object to send requests from.
87
+ :param report_name: The name of the system report to run.
88
+ :param page_number: The page number to start on. The first page is page 0.
89
+ :param page_size: The number of results to return per page.
90
+ """
91
+ first_page_criteria: CustomReportCriteria = CustomReportUtil.get_system_report_criteria(user, report_name)
92
+ first_page_criteria.page_number = page_number
93
+ first_page_criteria.page_size = page_size
94
+ super().__init__(user, first_page_criteria)
95
+
96
+
97
+ class QuickReportDictAutoPager(_DictReportPagerBase):
98
+ """
99
+ A class that automatically pages through a quick report and returns the results as a list of dictionaries.
100
+ """
101
+ def __init__(self, user: UserIdentifier, report_term: RawReportTerm,
102
+ page_number: int = 0, page_size: int = _default_report_page_size):
103
+ """
104
+ :param user: The current webhook context or a user object to send requests from.
105
+ :param report_term: The raw report term to use for the quick report.
106
+ :param page_number: The page number to start on. The first page is page 0.
107
+ :param page_size: The number of results to return per page.
108
+ """
109
+ first_page_criteria: CustomReportCriteria = CustomReportUtil.get_quick_report_criteria(user, report_term)
110
+ first_page_criteria.page_number = page_number
111
+ first_page_criteria.page_size = page_size
112
+ super().__init__(user, first_page_criteria)
113
+
114
+
115
+ # CR-47491: Support providing a data type name string to receive PyRecordModels instead of requiring a WrapperType.
116
+ class _RecordReportPagerBase(SapioPyAutoPager[CustomReportCriteria, WrappedType | PyRecordModel], ABC):
117
+ """
118
+ A base class for automatically paging through a report and returning the results as a list of records.
119
+ """
120
+ _columns: list[ReportColumn]
121
+ _query_type: type[WrappedType] | str
122
+ _data_type: str
123
+ _rec_handler: RecordHandler
124
+ _report_man: CustomReportManager
125
+
126
+ def __init__(self, user: UserIdentifier, first_page_criteria: CustomReportCriteria,
127
+ wrapper_type: type[WrappedType] | str):
128
+ self._columns = first_page_criteria.column_list
129
+ self._query_type = wrapper_type
130
+ self._data_type = AliasUtil.to_data_type_name(wrapper_type)
131
+ self._rec_handler = RecordHandler(user)
132
+ super().__init__(AliasUtil.to_sapio_user(user), first_page_criteria)
133
+ self._report_man = DataMgmtServer.get_custom_report_manager(self.user)
134
+
135
+ def get_all_at_once(self) -> list[RecordModel]:
136
+ """
137
+ Get the results of all pages. Be cautious of client memory usage.
138
+ """
139
+ if self.has_iterated:
140
+ raise BrokenPipeError("Cannot use this method if the iterator has already been used.")
141
+ return [x for x in self]
142
+
143
+ def default_first_page_criteria(self) -> PagerResultCriteriaType:
144
+ raise ValueError("Cannot generate a default first page criteria for custom reports.")
145
+
146
+ def get_next_page_result(self) -> tuple[CustomReportCriteria | None, Queue[WrappedType] | Queue[PyRecordModel]]:
147
+ report: CustomReport = self._report_man.run_custom_report(self.next_page_criteria)
148
+ queue = Queue()
149
+ id_index: int = -1
150
+ for i, column in enumerate(self._columns):
151
+ if column.data_type_name == self._data_type and column.data_field_name == "RecordId":
152
+ id_index = i
153
+ break
154
+ if id_index == -1:
155
+ raise SapioException(f"This report does not contain a Record ID column for the given record model type "
156
+ f"{self._data_type}.")
157
+ ids: set[int] = {row[id_index] for row in report.result_table}
158
+ for row in self._rec_handler.query_models_by_id(self._query_type, ids, page_size=report.page_size):
159
+ queue.put(row)
160
+ if report.has_next_page:
161
+ next_page_criteria = copy(self.next_page_criteria)
162
+ next_page_criteria.page_number += 1
163
+ return next_page_criteria, queue
164
+ else:
165
+ return None, queue
166
+
167
+
168
+ class CustomReportRecordAutoPager(_RecordReportPagerBase):
169
+ """
170
+ A class that automatically pages through a custom report and returns the results as a list of records.
171
+ """
172
+ def __init__(self, user: UserIdentifier, report_criteria: CustomReportCriteria,
173
+ wrapper_type: type[WrappedType] | str, page_number: int = 0,
174
+ page_size: int = _default_record_page_size):
175
+ """
176
+ :param user: The current webhook context or a user object to send requests from.
177
+ :param report_criteria: The custom report criteria to run.
178
+ :param wrapper_type: The record model wrapper type or data type name of the records being searched for.
179
+ If a data type name was used instead of a model wrapper, then the returned records will be PyRecordModels
180
+ instead of WrappedRecordModels.
181
+ :param page_number: The page number to start on. The first page is page 0.
182
+ :param page_size: The number of results to return per page.
183
+ """
184
+ first_page_criteria: CustomReportCriteria = copy(report_criteria)
185
+ _add_record_id_column(first_page_criteria, wrapper_type)
186
+ first_page_criteria.page_number = page_number
187
+ first_page_criteria.page_size = page_size
188
+ super().__init__(user, first_page_criteria, wrapper_type)
189
+
190
+
191
+ class SystemReportRecordAutoPager(_RecordReportPagerBase):
192
+ """
193
+ A class that automatically pages through a system report and returns the results as a list of records.
194
+
195
+ System reports are also known as predefined searches in the system and must be defined in the data designer for
196
+ a specific data type. That is, saved searches created by users cannot be run using this function.
197
+ """
198
+ def __init__(self, user: UserIdentifier, report_name: str, wrapper_type: type[WrappedType] | str,
199
+ page_number: int = 0, page_size: int = _default_record_page_size):
200
+ """
201
+ :param user: The current webhook context or a user object to send requests from.
202
+ :param report_name: The name of the system report to run.
203
+ :param wrapper_type: The record model wrapper type or data type name of the records being searched for.
204
+ If a data type name was used instead of a model wrapper, then the returned records will be PyRecordModels
205
+ instead of WrappedRecordModels.
206
+ :param page_number: The page number to start on. The first page is page 0.
207
+ :param page_size: The number of results to return per page.
208
+ """
209
+ first_page_criteria: CustomReportCriteria = CustomReportUtil.get_system_report_criteria(user, report_name)
210
+ _add_record_id_column(first_page_criteria, wrapper_type)
211
+ first_page_criteria.page_number = page_number
212
+ first_page_criteria.page_size = page_size
213
+ super().__init__(user, first_page_criteria, wrapper_type)
214
+
215
+
216
+ class QuickReportRecordAutoPager(_RecordReportPagerBase):
217
+ """
218
+ A class that automatically pages through a quick report and returns the results as a list of records.
219
+ """
220
+ def __init__(self, user: UserIdentifier, report_term: RawReportTerm, wrapper_type: type[WrappedType] | str,
221
+ page_number: int = 0, page_size: int = _default_record_page_size):
222
+ """
223
+ :param user: The current webhook context or a user object to send requests from.
224
+ :param report_term: The raw report term to use for the quick report.
225
+ :param wrapper_type: The record model wrapper type or data type name of the records being searched for.
226
+ If a data type name was used instead of a model wrapper, then the returned records will be PyRecordModels
227
+ instead of WrappedRecordModels.
228
+ :param page_number: The page number to start on. The first page is page 0.
229
+ :param page_size: The number of results to return per page.
230
+ """
231
+ if report_term.data_type_name != AliasUtil.to_data_type_name(wrapper_type):
232
+ raise SapioException("The data type name of the report term must match the data type name of the wrapper type.")
233
+ first_page_criteria: CustomReportCriteria = CustomReportUtil.get_quick_report_criteria(user, report_term)
234
+ first_page_criteria.page_number = page_number
235
+ first_page_criteria.page_size = page_size
236
+ super().__init__(user, first_page_criteria, wrapper_type)
237
+
238
+
239
+ def _add_record_id_column(report: CustomReportCriteria, wrapper_type: type[WrappedType] | str) -> None:
240
+ """
241
+ Given a custom report criteria, ensure that the report contains a Record ID column for the given record model's
242
+ data type. Add one if it is missing.
243
+ """
244
+ dt: str = AliasUtil.to_data_type_name(wrapper_type)
245
+ # Ensure that the root data type is the one we're looking for.
246
+ report.root_data_type = dt
247
+ # Enforce that the given custom report has a record ID column.
248
+ if not any([x.data_type_name == dt and x.data_field_name == "RecordId" for x in report.column_list]):
249
+ report.column_list.append(ReportColumn(dt, "RecordId", FieldType.LONG))
250
+
251
+
252
+ def _process_results(rows: list[list[FieldValue]], columns: list[ReportColumn]) -> list[dict[str, FieldValue]]:
253
+ """
254
+ Given the results of a report as a list of row values and the report's columns, combine these lists to
255
+ result in a singular list of dictionaries for each row in the results.
256
+ """
257
+ # It may be the case that two columns have the same data field name but differing data type names.
258
+ # If this occurs, then we need to be able to differentiate these columns in the resulting dictionary.
259
+ prepend_dt: set[str] = set()
260
+ encountered_names: list[str] = []
261
+ for column in columns:
262
+ field_name: str = column.data_field_name
263
+ if field_name in encountered_names:
264
+ prepend_dt.add(field_name)
265
+ else:
266
+ encountered_names.append(field_name)
267
+
268
+ ret: list[dict[str, FieldValue]] = []
269
+ for row in rows:
270
+ row_data: dict[str, FieldValue] = {}
271
+ filter_row: bool = False
272
+ for value, column in zip(row, columns):
273
+ header: str = column.data_field_name
274
+ # If two columns share the same data field name, prepend the data type name of the column to the
275
+ # data field name.
276
+ if header in prepend_dt:
277
+ header = column.data_type_name + "." + header
278
+ row_data.update({header: value})
279
+ if filter_row is False:
280
+ ret.append(row_data)
281
+ return ret
@@ -279,7 +279,7 @@ class TermBuilder:
279
279
 
280
280
  :param a: The first term in the operation.
281
281
  :param b: The second term in the operation.
282
- :param is_negated: Whether the returned term should be negated (i.e. turn this into an xnor operation).
282
+ :param is_negated: Whether the returned term should be negated (i.e. turn this into an XNOR operation).
283
283
  :return: A composite report term for "A xor B".
284
284
  """
285
285
  return TermBuilder.and_terms(TermBuilder.or_terms(a, b),
@@ -1,6 +1,7 @@
1
1
  import io
2
2
 
3
3
  from sapiopylib.rest.DataMgmtService import DataMgmtServer
4
+ from sapiopylib.rest.utils.recordmodel.PyRecordModel import PyRecordModel
4
5
  from sapiopylib.rest.utils.recordmodel.RecordModelWrapper import WrappedType
5
6
 
6
7
  from sapiopycommons.general.aliases import AliasUtil, SapioRecord, UserIdentifier
@@ -49,9 +50,10 @@ class AttachmentUtil:
49
50
  with io.BytesIO(file_bytes) as stream:
50
51
  dr_man.set_attachment_data(attachment, file_name, stream)
51
52
 
53
+ # CR-47491: Support providing a data type name string to receive PyRecordModels instead of requiring a WrapperType.
52
54
  @staticmethod
53
55
  def create_attachment(context: UserIdentifier, file_name: str, file_bytes: bytes,
54
- wrapper_type: type[WrappedType]) -> WrappedType:
56
+ wrapper_type: type[WrappedType] | str) -> WrappedType | PyRecordModel:
55
57
  """
56
58
  Create an attachment data type and initialize its attachment bytes at the same time.
57
59
  Makes a webservice call to create the attachment record and a second to set its bytes.
@@ -62,6 +64,6 @@ class AttachmentUtil:
62
64
  :param wrapper_type: The attachment type to create.
63
65
  :return: A record model for the newly created attachment.
64
66
  """
65
- attachment: WrappedType = RecordHandler(context).create_models(wrapper_type, 1)[0]
67
+ attachment: WrappedType | PyRecordModel = RecordHandler(context).create_models(wrapper_type, 1)[0]
66
68
  AttachmentUtil.set_attachment_bytes(context, attachment, file_name, file_bytes)
67
69
  return attachment
@@ -58,4 +58,26 @@ class ProcessWorkflowTrackingFields:
58
58
  WORKFLOW_PROCESS_TAT__FIELD = WrapperField("WorkflowProcessTAT", FieldType.DOUBLE)
59
59
  WORKFLOW_START_USER_ID__FIELD = WrapperField("WorkflowStartUserId", FieldType.STRING)
60
60
  WORKFLOW_TAT__FIELD = WrapperField("WorkflowTAT", FieldType.DOUBLE)
61
- WORKFLOW_VERSION__FIELD = WrapperField("WorkflowVersion", FieldType.LONG)
61
+ WORKFLOW_VERSION__FIELD = WrapperField("WorkflowVersion", FieldType.LONG)
62
+
63
+ class PlateDesignerWellElementFields:
64
+ DATA_TYPE_NAME = 'PlateDesignerWellElement'
65
+ ACTUAL_VOLUME_REMOVED__FIELD = WrapperField("ActualVolumeRemoved", FieldType.DOUBLE)
66
+ ALIQUOT_SAMPLE_RECORD_ID__FIELD = WrapperField("AliquotSampleRecordId", FieldType.LONG)
67
+ COL_POSITION__FIELD = WrapperField("ColPosition", FieldType.SELECTION)
68
+ CONCENTRATION__FIELD = WrapperField("Concentration", FieldType.DOUBLE)
69
+ CONCENTRATION_UNITS__FIELD = WrapperField("ConcentrationUnits", FieldType.STRING)
70
+ CONTROL_TYPE__FIELD = WrapperField("ControlType", FieldType.STRING)
71
+ DILUTION_SCHEME__FIELD = WrapperField("DilutionScheme", FieldType.DOUBLE)
72
+ IS_CONTROL__FIELD = WrapperField("IsControl", FieldType.BOOLEAN)
73
+ LAYER__FIELD = WrapperField("Layer", FieldType.INTEGER)
74
+ PLATE_RECORD_ID__FIELD = WrapperField("PlateRecordId", FieldType.LONG)
75
+ ROW_POSITION__FIELD = WrapperField("RowPosition", FieldType.SELECTION)
76
+ SOURCE_DATA_TYPE_NAME__FIELD = WrapperField("SourceDataTypeName", FieldType.STRING)
77
+ SOURCE_RECORD_ID__FIELD = WrapperField("SourceRecordId", FieldType.LONG)
78
+ SOURCE_SAMPLE_CONCENTRATION__FIELD = WrapperField("SourceSampleConcentration", FieldType.DOUBLE)
79
+ SOURCE_SAMPLE_MASS__FIELD = WrapperField("SourceSampleMass", FieldType.DOUBLE)
80
+ SOURCE_SAMPLE_VOLUME__FIELD = WrapperField("SourceSampleVolume", FieldType.DOUBLE)
81
+ SOURCE_VOLUME_TO_REMOVE__FIELD = WrapperField("SourceVolumeToRemove", FieldType.DOUBLE)
82
+ TARGET_MASS__FIELD = WrapperField("TargetMass", FieldType.DOUBLE)
83
+ VOLUME__FIELD = WrapperField("Volume", FieldType.DOUBLE)
@@ -0,0 +1,173 @@
1
+ from __future__ import annotations
2
+
3
+ from weakref import WeakValueDictionary
4
+
5
+ from sapiopylib.rest.ELNService import ElnManager
6
+ from sapiopylib.rest.User import SapioUser
7
+ from sapiopylib.rest.pojo.datatype.FieldDefinition import AbstractVeloxFieldDefinition
8
+ from sapiopylib.rest.pojo.eln.ElnExperiment import ElnTemplate, TemplateExperimentQuery
9
+ from sapiopylib.rest.pojo.eln.SapioELNEnums import ElnBaseDataType
10
+ from sapiopylib.rest.pojo.eln.field_set import ElnFieldSetInfo
11
+ from sapiopylib.rest.pojo.eln.protocol_template import ProtocolTemplateInfo, ProtocolTemplateQuery
12
+
13
+ from sapiopycommons.general.aliases import UserIdentifier, AliasUtil
14
+ from sapiopycommons.general.exceptions import SapioException
15
+
16
+
17
+ # FR-47530: Created a class that caches experiment template and predefined field information.
18
+ class ExperimentCacheManager:
19
+ """
20
+ A class to manage the caching of experiment-related information.
21
+ """
22
+ user: SapioUser
23
+ eln_man: ElnManager
24
+
25
+ _templates: list[ElnTemplate]
26
+ """A list of experiment templates. Only cached when first accessed."""
27
+ _protocols: list[ProtocolTemplateInfo]
28
+ """A list of protocol templates. Only cached when first accessed."""
29
+ _field_sets: dict[str, ElnFieldSetInfo]
30
+ """A dictionary of field set name to field set. Only cached when first accessed."""
31
+ _field_set_fields: dict[int, list[AbstractVeloxFieldDefinition]]
32
+ """A dictionary of field set ID to field definitions. Only cached when first accessed."""
33
+ _predefined_fields: dict[str, dict[str, AbstractVeloxFieldDefinition]]
34
+ """A dictionary of ELN data type name to predefined field definitions. Only cached when first accessed."""
35
+
36
+ __instances: WeakValueDictionary[SapioUser, ExperimentCacheManager] = WeakValueDictionary()
37
+ __initialized: bool
38
+
39
+ def __new__(cls, context: UserIdentifier):
40
+ """
41
+ :param context: The current webhook context or a user object to send requests from.
42
+ """
43
+ user = AliasUtil.to_sapio_user(context)
44
+ obj = cls.__instances.get(user)
45
+ if not obj:
46
+ obj = object.__new__(cls)
47
+ obj.__initialized = False
48
+ cls.__instances[user] = obj
49
+ return obj
50
+
51
+ def __init__(self, context: UserIdentifier):
52
+ """
53
+ :param context: The current webhook context or a user object to send requests from.
54
+ """
55
+ if self.__initialized:
56
+ return
57
+ self.__initialized = True
58
+
59
+ self.user = AliasUtil.to_sapio_user(context)
60
+ self.eln_man = ElnManager(self.user)
61
+
62
+ self._field_set_fields = {}
63
+ self._predefined_fields = {}
64
+
65
+ def get_experiment_template(self, name: str, active: bool = True, version: int | None = None,
66
+ first_match: bool = False) -> ElnTemplate:
67
+ """
68
+ Get the experiment template with the given information.
69
+
70
+ :param name: The name of the template.
71
+ :param active: Whether the template is marked as active.
72
+ :param version: The version of the template to get. If None, the latest version will be returned.
73
+ :param first_match: If true, returns the first match found. If false, raises an exception.
74
+ :return: The experiment template with the given information.
75
+ """
76
+ if not hasattr(self, "_templates"):
77
+ query = TemplateExperimentQuery()
78
+ query.active_templates_only = False
79
+ query.latest_version_only = False
80
+ self._templates = self.eln_man.get_template_experiment_list(query)
81
+ return self._find_template(self._templates, name, active, version, first_match)
82
+
83
+
84
+ def get_protocol_template(self, name: str, active: bool = True, version: int | None = None,
85
+ first_match: bool = False) -> ProtocolTemplateInfo:
86
+ """
87
+ Get the protocol template with the given information. Will throw an exception if multiple templates match
88
+ the given information.
89
+
90
+ :param name: The name of the template.
91
+ :param active: Whether the template is marked as active.
92
+ :param version: The version of the template to get. If None, the latest version will be returned.
93
+ :param first_match: If true, returns the first match found. If false, raises an exception.
94
+ :return: The protocol template with the given information.
95
+ """
96
+ if not hasattr(self, "_protocols"):
97
+ query = ProtocolTemplateQuery()
98
+ query.active_templates_only = False
99
+ query.latest_version_only = False
100
+ self._protocols = self.eln_man.get_protocol_template_info_list(query)
101
+ return self._find_template(self._protocols, name, active, version, first_match)
102
+
103
+ @staticmethod
104
+ def _find_template(templates: list[ElnTemplate] | list[ProtocolTemplateInfo], name: str, active: bool,
105
+ version: int, first_match: bool) -> ElnTemplate | ProtocolTemplateInfo:
106
+ """
107
+ Find the experiment or protocol template with the given information.
108
+ """
109
+ matches = []
110
+ for template in templates:
111
+ if template.template_name != name:
112
+ continue
113
+ if template.active != active:
114
+ continue
115
+ if version is not None and template.template_version != version:
116
+ continue
117
+ matches.append(template)
118
+ if not matches:
119
+ raise SapioException(f"No template with the name \"{name}\"" +
120
+ ("" if version is None else f" and the version {version}") +
121
+ f" found.")
122
+ if not version:
123
+ return max(matches, key=lambda x: x.template_version)
124
+ if len(matches) > 1 and not first_match:
125
+ raise SapioException(f"Multiple templates with the name \"{name}\" found.")
126
+ return matches[0]
127
+
128
+ def get_predefined_field(self, field_name: str, data_type: ElnBaseDataType) -> AbstractVeloxFieldDefinition:
129
+ """
130
+ Get the predefined field of the given name for the given ELN data type.
131
+
132
+ :param field_name: The name of the field.
133
+ :param data_type: The ELN data type of the field.
134
+ :return: The predefined field of the given name for the given ELN data type.
135
+ """
136
+ return self.get_predefined_fields(data_type)[field_name]
137
+
138
+ def get_predefined_fields(self, data_type: ElnBaseDataType) -> dict[str, AbstractVeloxFieldDefinition]:
139
+ """
140
+ Get the predefined fields for the given ELN data type.
141
+
142
+ :param data_type: The ELN data type to get the predefined fields for.
143
+ :return: A dictionary of field name to field definition for the given ELN data type.
144
+ """
145
+ if data_type.data_type_name not in self._predefined_fields:
146
+ fields: list[AbstractVeloxFieldDefinition] = self.eln_man.get_predefined_fields(data_type)
147
+ self._predefined_fields[data_type.data_type_name] = {x.data_field_name: x for x in fields}
148
+ return self._predefined_fields[data_type.data_type_name]
149
+
150
+ def get_field_set(self, name: str) -> ElnFieldSetInfo:
151
+ """
152
+ Get the field set with the given name.
153
+
154
+ :param name: The name of the field set.
155
+ :return: The field set with the given name.
156
+ """
157
+ if not hasattr(self, "_field_sets"):
158
+ self._field_sets = {x.field_set_name: x for x in self.eln_man.get_field_set_info_list()}
159
+ return self._field_sets[name]
160
+
161
+ def get_field_set_fields(self, field_set: ElnFieldSetInfo | int) -> list[AbstractVeloxFieldDefinition]:
162
+ """
163
+ Get the fields of the given field set.
164
+
165
+ :param field_set: The field set to get the fields from. Can be either an ElnFieldSetInfo object or an integer
166
+ for the set ID.
167
+ :return: The fields of the given field set.
168
+ """
169
+ field_set: int = field_set if isinstance(field_set, int) else field_set.field_set_id
170
+ if field_set in self._field_set_fields:
171
+ return self._field_set_fields[field_set]
172
+ self._field_set_fields[field_set] = self.eln_man.get_predefined_fields_from_field_set_id(field_set)
173
+ return self._field_set_fields[field_set]