sapiopycommons 2024.8.28a313__py3-none-any.whl → 2024.8.28a315__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 (37) hide show
  1. sapiopycommons/callbacks/callback_util.py +407 -69
  2. sapiopycommons/chem/IndigoMolecules.py +1 -0
  3. sapiopycommons/chem/Molecules.py +1 -0
  4. sapiopycommons/customreport/__init__.py +0 -0
  5. sapiopycommons/customreport/column_builder.py +60 -0
  6. sapiopycommons/customreport/custom_report_builder.py +125 -0
  7. sapiopycommons/customreport/term_builder.py +299 -0
  8. sapiopycommons/datatype/attachment_util.py +11 -10
  9. sapiopycommons/eln/experiment_handler.py +209 -48
  10. sapiopycommons/eln/experiment_report_util.py +118 -0
  11. sapiopycommons/files/complex_data_loader.py +5 -4
  12. sapiopycommons/files/file_bridge.py +31 -24
  13. sapiopycommons/files/file_bridge_handler.py +340 -0
  14. sapiopycommons/files/file_data_handler.py +2 -5
  15. sapiopycommons/files/file_util.py +50 -10
  16. sapiopycommons/files/file_validator.py +92 -6
  17. sapiopycommons/files/file_writer.py +44 -15
  18. sapiopycommons/general/accession_service.py +375 -0
  19. sapiopycommons/general/aliases.py +147 -3
  20. sapiopycommons/general/audit_log.py +196 -0
  21. sapiopycommons/general/custom_report_util.py +211 -37
  22. sapiopycommons/general/popup_util.py +17 -0
  23. sapiopycommons/general/sapio_links.py +50 -0
  24. sapiopycommons/general/time_util.py +40 -0
  25. sapiopycommons/multimodal/multimodal.py +146 -0
  26. sapiopycommons/multimodal/multimodal_data.py +486 -0
  27. sapiopycommons/processtracking/endpoints.py +22 -22
  28. sapiopycommons/recordmodel/record_handler.py +481 -97
  29. sapiopycommons/rules/eln_rule_handler.py +34 -25
  30. sapiopycommons/rules/on_save_rule_handler.py +34 -31
  31. sapiopycommons/webhook/webhook_handlers.py +147 -26
  32. sapiopycommons/webhook/webservice_handlers.py +67 -0
  33. {sapiopycommons-2024.8.28a313.dist-info → sapiopycommons-2024.8.28a315.dist-info}/METADATA +4 -2
  34. sapiopycommons-2024.8.28a315.dist-info/RECORD +50 -0
  35. sapiopycommons-2024.8.28a313.dist-info/RECORD +0 -38
  36. {sapiopycommons-2024.8.28a313.dist-info → sapiopycommons-2024.8.28a315.dist-info}/WHEEL +0 -0
  37. {sapiopycommons-2024.8.28a313.dist-info → sapiopycommons-2024.8.28a315.dist-info}/licenses/LICENSE +0 -0
@@ -1,5 +1,7 @@
1
+ from __future__ import annotations
2
+
1
3
  import io
2
- from typing import Any
4
+ from weakref import WeakValueDictionary
3
5
 
4
6
  from sapiopylib.rest.ClientCallbackService import ClientCallback
5
7
  from sapiopylib.rest.DataMgmtService import DataMgmtServer
@@ -9,20 +11,21 @@ from sapiopylib.rest.pojo.DataRecord import DataRecord
9
11
  from sapiopylib.rest.pojo.datatype.DataType import DataTypeDefinition
10
12
  from sapiopylib.rest.pojo.datatype.DataTypeLayout import DataTypeLayout
11
13
  from sapiopylib.rest.pojo.datatype.FieldDefinition import AbstractVeloxFieldDefinition, VeloxStringFieldDefinition, \
12
- VeloxIntegerFieldDefinition, VeloxDoubleFieldDefinition
14
+ VeloxIntegerFieldDefinition, VeloxDoubleFieldDefinition, FieldDefinitionParser
13
15
  from sapiopylib.rest.pojo.webhook.ClientCallbackRequest import OptionDialogRequest, ListDialogRequest, \
14
16
  FormEntryDialogRequest, InputDialogCriteria, TableEntryDialogRequest, ESigningRequestPojo, \
15
- DataRecordSelectionRequest, DataRecordDialogRequest, InputSelectionRequest, FilePromptRequest, \
16
- MultiFilePromptRequest
17
+ DataRecordDialogRequest, InputSelectionRequest, FilePromptRequest, MultiFilePromptRequest, \
18
+ TempTableSelectionRequest, DisplayPopupRequest, PopupType
17
19
  from sapiopylib.rest.pojo.webhook.ClientCallbackResult import ESigningResponsePojo
18
- from sapiopylib.rest.pojo.webhook.WebhookContext import SapioWebhookContext
19
20
  from sapiopylib.rest.pojo.webhook.WebhookEnums import FormAccessLevel, ScanToSelectCriteria, SearchType
20
21
  from sapiopylib.rest.utils.DataTypeCacheManager import DataTypeCacheManager
21
22
  from sapiopylib.rest.utils.FormBuilder import FormBuilder
22
23
  from sapiopylib.rest.utils.recorddatasinks import InMemoryRecordDataSink
23
24
  from sapiopylib.rest.utils.recordmodel.RecordModelWrapper import WrappedType
24
25
 
25
- from sapiopycommons.general.aliases import FieldMap, SapioRecord, AliasUtil, RecordIdentifier
26
+ from sapiopycommons.files.file_util import FileUtil
27
+ from sapiopycommons.general.aliases import FieldMap, SapioRecord, AliasUtil, RecordIdentifier, FieldValue, \
28
+ UserIdentifier
26
29
  from sapiopycommons.general.custom_report_util import CustomReportUtil
27
30
  from sapiopycommons.general.exceptions import SapioUserCancelledException, SapioException, SapioUserErrorException
28
31
  from sapiopycommons.recordmodel.record_handler import RecordHandler
@@ -35,26 +38,86 @@ class CallbackUtil:
35
38
  width_pixels: int | None
36
39
  width_percent: float | None
37
40
 
38
- def __init__(self, context: SapioWebhookContext | SapioUser):
41
+ __instances: WeakValueDictionary[SapioUser, CallbackUtil] = WeakValueDictionary()
42
+ __initialized: bool
43
+
44
+ def __new__(cls, context: UserIdentifier):
45
+ """
46
+ :param context: The current webhook context or a user object to send requests from.
47
+ """
48
+ user = AliasUtil.to_sapio_user(context)
49
+ obj = cls.__instances.get(user)
50
+ if not obj:
51
+ obj = object.__new__(cls)
52
+ obj.__initialized = False
53
+ cls.__instances[user] = obj
54
+ return obj
55
+
56
+ def __init__(self, context: UserIdentifier):
39
57
  """
40
58
  :param context: The current webhook context or a user object to send requests from.
41
59
  """
42
- self.user = context if isinstance(context, SapioUser) else context.user
60
+ if self.__initialized:
61
+ return
62
+ self.__initialized = True
63
+
64
+ self.user = AliasUtil.to_sapio_user(context)
43
65
  self.callback = DataMgmtServer.get_client_callback(self.user)
44
66
  self.dt_cache = DataTypeCacheManager(self.user)
45
67
  self.width_pixels = None
46
68
  self.width_percent = None
47
69
 
48
- def set_dialog_width(self, width_pixels: int | None, width_percent: float | None):
70
+ def set_dialog_width(self, width_pixels: int | None = None, width_percent: float | None = None):
49
71
  """
50
72
  Set the width that dialogs will appear as for those dialogs that support specifying their width.
51
73
 
52
74
  :param width_pixels: The number of pixels wide that dialogs will appear as.
53
- :param width_percent: The percentage of the client's screen width that dialogs will appear as.
75
+ :param width_percent: The percentage (as a value between 0 and 1) of the client's screen width that dialogs
76
+ will appear as.
54
77
  """
78
+ if width_pixels is not None and width_percent is not None:
79
+ raise SapioException("Cannot set both width_pixels and width_percent at once.")
55
80
  self.width_pixels = width_pixels
56
81
  self.width_percent = width_percent
57
-
82
+
83
+ def toaster_popup(self, message: str, title: str = "", popup_type: PopupType = PopupType.Info) -> None:
84
+ """
85
+ Display a toaster popup in the bottom right corner of the user's screen.
86
+
87
+ :param message: The message to display in the toaster.
88
+ :param title: The title to display at the top of the toaster.
89
+ :param popup_type: The popup type to use for the toaster. This controls the color that the toaster appears with.
90
+ Info is blue, Success is green, Warning is yellow, and Error is red
91
+ """
92
+ self.callback.display_popup(DisplayPopupRequest(title, message, popup_type))
93
+
94
+ def display_info(self, message: str) -> None:
95
+ """
96
+ Display an info message to the user in a dialog. Repeated calls to this function will append the new messages
97
+ to the same dialog if it is still opened by the user.
98
+
99
+ :param message: The message to display to the user.
100
+ """
101
+ self.callback.display_info(message)
102
+
103
+ def display_warning(self, message: str) -> None:
104
+ """
105
+ Display a warning message to the user in a dialog. Repeated calls to this function will append the new messages
106
+ to the same dialog if it is still opened by the user.
107
+
108
+ :param message: The message to display to the user.
109
+ """
110
+ self.callback.display_warning(message)
111
+
112
+ def display_error(self, message: str) -> None:
113
+ """
114
+ Display an error message to the user in a dialog. Repeated calls to this function will append the new messages
115
+ to the same dialog if it is still opened by the user.
116
+
117
+ :param message: The message to display to the user.
118
+ """
119
+ self.callback.display_error(message)
120
+
58
121
  def option_dialog(self, title: str, msg: str, options: list[str], default_option: int = 0,
59
122
  user_can_cancel: bool = False) -> str:
60
123
  """
@@ -69,7 +132,8 @@ class CallbackUtil:
69
132
  SapioUserCancelledException is thrown.
70
133
  :return: The name of the button that the user selected.
71
134
  """
72
- request = OptionDialogRequest(title, msg, options, default_option, user_can_cancel)
135
+ request = OptionDialogRequest(title, msg, options, default_option, user_can_cancel,
136
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
73
137
  response: int | None = self.callback.show_option_dialog(request)
74
138
  if response is None:
75
139
  raise SapioUserCancelledException()
@@ -109,16 +173,20 @@ class CallbackUtil:
109
173
  """
110
174
  return self.option_dialog(title, msg, ["Yes", "No"], 0 if default_yes else 1, False) == "Yes"
111
175
 
112
- def list_dialog(self, title: str, options: list[str], multi_select: bool = False) -> list[str]:
176
+ def list_dialog(self, title: str, options: list[str], multi_select: bool = False,
177
+ preselected_values: list[str] | None = None) -> list[str]:
113
178
  """
114
179
  Create a list dialog with the given options for the user to choose from.
115
180
 
116
181
  :param title: The title of the dialog.
117
182
  :param options: The list options that the user has to choose from.
118
183
  :param multi_select: Whether the user is able to select multiple options from the list.
184
+ :param preselected_values: A list of values that will already be selected when the list dialog is created. The
185
+ user can unselect these values if they want to.
119
186
  :return: The list of options that the user selected.
120
187
  """
121
- request = ListDialogRequest(title, multi_select, options)
188
+ request = ListDialogRequest(title, multi_select, options, preselected_values,
189
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
122
190
  response: list[str] | None = self.callback.show_list_dialog(request)
123
191
  if response is None:
124
192
  raise SapioUserCancelledException()
@@ -161,8 +229,6 @@ class CallbackUtil:
161
229
  builder = FormBuilder(data_type, display_name, plural_display_name)
162
230
  for field_def in fields:
163
231
  field_name = field_def.data_field_name
164
- if values and hasattr(field_def, "default_value"):
165
- field_def.default_value = values.get(field_name)
166
232
  column: int = 0
167
233
  span: int = 4
168
234
  if column_positions and field_name in column_positions:
@@ -171,7 +237,8 @@ class CallbackUtil:
171
237
  span = position[1]
172
238
  builder.add_field(field_def, column, span)
173
239
 
174
- request = FormEntryDialogRequest(title, msg, builder.get_temporary_data_type())
240
+ request = FormEntryDialogRequest(title, msg, builder.get_temporary_data_type(), values,
241
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
175
242
  response: FieldMap | None = self.callback.show_form_entry_dialog(request)
176
243
  if response is None:
177
244
  raise SapioUserCancelledException()
@@ -209,32 +276,33 @@ class CallbackUtil:
209
276
  type_def: DataTypeDefinition = self.dt_cache.get_data_type(data_type)
210
277
  field_defs: dict[str, AbstractVeloxFieldDefinition] = self.dt_cache.get_fields_for_type(data_type)
211
278
 
279
+ # Make everything visible, because presumably the caller gave a field name because they want it to be seen.
280
+ modifier = FieldModifier(visible=True, editable=editable)
281
+
212
282
  # Build the form using only those fields that are desired.
283
+ values: dict[str, FieldValue] = {}
213
284
  builder = FormBuilder(data_type, type_def.display_name, type_def.plural_display_name)
214
285
  for field_name in fields:
215
286
  field_def = field_defs.get(field_name)
216
287
  if field_def is None:
217
288
  raise SapioException(f"No field of name \"{field_name}\" in field definitions of type \"{data_type}\"")
218
- if editable is not None:
219
- field_def.editable = editable
220
- field_def.visible = True
221
- if hasattr(field_def, "default_value"):
222
- field_def.default_value = record.get_field_value(field_name)
289
+ values[field_name] = record.get_field_value(field_name)
223
290
  column: int = 0
224
291
  span: int = 4
225
292
  if column_positions and field_name in column_positions:
226
293
  position = column_positions.get(field_name)
227
294
  column = position[0]
228
295
  span = position[1]
229
- builder.add_field(field_def, column, span)
296
+ builder.add_field(modifier.modify_field(field_def), column, span)
230
297
 
231
- request = FormEntryDialogRequest(title, msg, builder.get_temporary_data_type())
298
+ request = FormEntryDialogRequest(title, msg, builder.get_temporary_data_type(), values,
299
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
232
300
  response: FieldMap | None = self.callback.show_form_entry_dialog(request)
233
301
  if response is None:
234
302
  raise SapioUserCancelledException()
235
303
  return response
236
304
 
237
- def input_dialog(self, title: str, msg: str, field: AbstractVeloxFieldDefinition) -> Any:
305
+ def input_dialog(self, title: str, msg: str, field: AbstractVeloxFieldDefinition) -> FieldValue:
238
306
  """
239
307
  Create an input dialog where the user must input data for a singular field.
240
308
 
@@ -243,8 +311,9 @@ class CallbackUtil:
243
311
  :param field: The definition for a field that the user must provide input to.
244
312
  :return: The response value from the user for the given field.
245
313
  """
246
- request = InputDialogCriteria(title, msg, field, self.width_pixels, self.width_percent)
247
- response: Any | None = self.callback.show_input_dialog(request)
314
+ request = InputDialogCriteria(title, msg, field,
315
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
316
+ response: FieldValue | None = self.callback.show_input_dialog(request)
248
317
  if response is None:
249
318
  raise SapioUserCancelledException()
250
319
  return response
@@ -259,7 +328,7 @@ class CallbackUtil:
259
328
  :param field_name: The name and display name of the string field.
260
329
  :param default_value: The default value to place into the string field, if any.
261
330
  :param max_length: The max length of the string value. If not provided, uses the length of the default value.
262
- If neither this or a default value are not provided, defaults to 100 characters.
331
+ If neither this nor a default value are provided, defaults to 100 characters.
263
332
  :param editable: Whether the field is editable by the user.
264
333
  :param kwargs: Any additional keyword arguments to pass to the field definition.
265
334
  :return: The string that the user input into the dialog.
@@ -320,6 +389,8 @@ class CallbackUtil:
320
389
  msg: str,
321
390
  fields: list[AbstractVeloxFieldDefinition],
322
391
  values: list[FieldMap],
392
+ group_by: str | None = None,
393
+ image_data: list[bytes] | None = None,
323
394
  *,
324
395
  data_type: str = "Default",
325
396
  display_name: str | None = None,
@@ -333,6 +404,10 @@ class CallbackUtil:
333
404
  :param fields: The definitions of the fields to display as table columns. Fields will be displayed in the order
334
405
  they are provided in this list.
335
406
  :param values: The values to set for each row of the table.
407
+ :param group_by: If provided, the created table dialog will be grouped by the field with this name by default.
408
+ The user may remove this grouping if they want to.
409
+ :param image_data: The bytes to the images that should be displayed in the rows of the table. Each element in
410
+ the image data list corresponds to the element at the same index in the values list.
336
411
  :param data_type: The data type name for the temporary data type that will be created for this table.
337
412
  :param display_name: The display name for the temporary data type. If not provided, defaults to the data type
338
413
  name.
@@ -346,11 +421,17 @@ class CallbackUtil:
346
421
  if plural_display_name is None:
347
422
  plural_display_name = display_name + "s"
348
423
 
424
+ # Key fields display their columns in order before all non-key fields.
425
+ # Unmark key fields so that the column order is respected exactly as the caller provides it.
426
+ modifier = FieldModifier(key_field=False)
427
+
349
428
  builder = FormBuilder(data_type, display_name, plural_display_name)
350
- for column in fields:
351
- builder.add_field(column)
429
+ for field in fields:
430
+ builder.add_field(modifier.modify_field(field))
352
431
 
353
- request = TableEntryDialogRequest(title, msg, builder.get_temporary_data_type(), values)
432
+ request = TableEntryDialogRequest(title, msg, builder.get_temporary_data_type(), values,
433
+ record_image_data_list=image_data, group_by_field=group_by,
434
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
354
435
  response: list[FieldMap] | None = self.callback.show_table_entry_dialog(request)
355
436
  if response is None:
356
437
  raise SapioUserCancelledException()
@@ -361,11 +442,14 @@ class CallbackUtil:
361
442
  msg: str,
362
443
  fields: list[str],
363
444
  records: list[SapioRecord],
364
- editable: bool | None = True) -> list[FieldMap]:
445
+ editable: bool | None = True,
446
+ group_by: str | None = None,
447
+ image_data: list[bytes] | None = None) -> list[FieldMap]:
365
448
  """
366
449
  Create a table dialog where the user may input data into the fields of the table. The table is constructed from
367
- a given list of records. Provided field names must match fields on the definition of the data type of the given
368
- records. The fields that are displayed will have their default value be that of the fields on the given records.
450
+ a given list of records of a singular type. Provided field names must match fields on the definition of the data
451
+ type of the given records. The fields that are displayed will have their default value be that of the fields on
452
+ the given records.
369
453
 
370
454
  Makes webservice calls to get the data type definition and fields of the given records if they weren't
371
455
  previously cached.
@@ -377,6 +461,10 @@ class CallbackUtil:
377
461
  they are provided in this list.
378
462
  :param editable: If true, all fields are displayed as editable. If false, all fields are displayed as
379
463
  uneditable. If none, only those fields that are defined as editable by the data designer will be editable.
464
+ :param group_by: If provided, the created table dialog will be grouped by the field with this name by default.
465
+ The user may remove this grouping if they want to.
466
+ :param image_data: The bytes to the images that should be displayed in the rows of the table. Each element in
467
+ the image data list corresponds to the element at the same index in the records list.
380
468
  :return: A list of dictionaries mapping the data field names of the given field definitions to the response
381
469
  value from the user for that field for each row.
382
470
  """
@@ -390,21 +478,180 @@ class CallbackUtil:
390
478
  type_def: DataTypeDefinition = self.dt_cache.get_data_type(data_type)
391
479
  field_defs: dict[str, AbstractVeloxFieldDefinition] = self.dt_cache.get_fields_for_type(data_type)
392
480
 
481
+ # Key fields display their columns in order before all non-key fields.
482
+ # Unmark key fields so that the column order is respected exactly as the caller provides it.
483
+ # Also make everything visible, because presumably the caller gave a field name because they want it to be seen.
484
+ modifier = FieldModifier(visible=True, key_field=False, editable=editable)
485
+
393
486
  # Build the form using only those fields that are desired.
394
487
  builder = FormBuilder(data_type, type_def.display_name, type_def.plural_display_name)
395
488
  for field_name in fields:
396
489
  field_def = field_defs.get(field_name)
397
490
  if field_def is None:
398
491
  raise SapioException(f"No field of name \"{field_name}\" in field definitions of type \"{data_type}\"")
399
- if editable is not None:
400
- field_def.editable = editable
401
- field_def.visible = True
402
- # Key fields display their columns in order before all non-key fields.
403
- # Unmark key fields so that the column order is respected exactly as the caller provides it.
404
- field_def.key_field = False
405
- builder.add_field(field_def)
406
-
407
- request = TableEntryDialogRequest(title, msg, builder.get_temporary_data_type(), field_map_list)
492
+ builder.add_field(modifier.modify_field(field_def))
493
+
494
+ request = TableEntryDialogRequest(title, msg, builder.get_temporary_data_type(), field_map_list,
495
+ record_image_data_list=image_data, group_by_field=group_by,
496
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
497
+ response: list[FieldMap] | None = self.callback.show_table_entry_dialog(request)
498
+ if response is None:
499
+ raise SapioUserCancelledException()
500
+ return response
501
+
502
+ def multi_type_table_dialog(self,
503
+ title: str,
504
+ msg: str,
505
+ fields: list[(str, str) | AbstractVeloxFieldDefinition],
506
+ row_contents: list[list[SapioRecord | FieldMap]],
507
+ *,
508
+ default_modifier: FieldModifier | None = None,
509
+ field_modifiers: dict[str, FieldModifier] | None = None,
510
+ data_type: str = "Default",
511
+ display_name: str | None = None,
512
+ plural_display_name: str | None = None) -> list[FieldMap]:
513
+ """
514
+ Create a table dialog where the user may input data into the fields of the table. The table is constructed from
515
+ a given list of records of multiple data types or field maps. Provided field names must match with field names
516
+ from the data type definition of the given records. The fields that are displayed will have their default value
517
+ be that of the fields on the given records or field maps.
518
+
519
+ Makes webservice calls to get the data type field definitions of the given records if they weren't
520
+ previously cached.
521
+
522
+ :param title: The title of the dialog.
523
+ :param msg: The message to display in the dialog.
524
+ :param fields: A list of objects representing the fields in the table. This could either be a two-element tuple
525
+ where the first element is a data type name and the second is a field name, or it could be a field
526
+ definition. If it is the former, a query will be made to find the field definition matching tht data type.
527
+ The data type names of the fields must match the data type names of the records in the row contents.
528
+ See the description of row_contents for what to do if you want to construct a field that pulls from a field
529
+ map.
530
+ If two fields share the same field name, an exception will be thrown. This is even true in the case where
531
+ the data type name of the fields is different. If you wish to display two fields from two data types with
532
+ the same name, then you must provide a FieldModifier for at least one of the fields where prepend_data_type
533
+ is True in order to make that field's name unique again. Note that if you do this for a field, the mapping
534
+ of record to field name will use the unedited field name, but the return results of this function will
535
+ use the edited field name in the results dictionary for a row.
536
+ :param row_contents: A list where each element is another list representing the records or a field map that will
537
+ be used to populate the columns of the table. If the data type of a given record doesn't match any of the
538
+ data type names of the given fields, then it will not be used.
539
+ This list can contain up to one field map, which are fields not tied to a record. This is so that you can
540
+ create abstract field definition not tied to a specific record in the system. If you want to define an
541
+ abstract field that pulls from the field map in the row contents, then you must set the data type name to
542
+ Default.
543
+ If a record of a given data type appears more than once in one of the inner-lists of the row contents, or
544
+ there is more than one field map, then an exception will be thrown, as there is no way of distinguishing
545
+ which record should be used for a field, and not all fields could have their values combined across multiple
546
+ records.
547
+ The row contents may have an inner-list which is missing a record of a data type that matches one of the
548
+ fields. In this case, the field value for that row under that column will be null.
549
+ The inner-list does not need to be sorted in any way, as this function will map the inner-list contents to
550
+ fields as necessary.
551
+ The inner-list may contain null elements; these will simply be discarded by this function.
552
+ :param default_modifier: A default field modifier that will be applied to the given fields. This can be used to
553
+ make field definitions from the system behave differently than their system values. If this value is None,
554
+ then a default field modifier is created that causes all specified fields to be both visible and not key
555
+ fields. (Key fields get displayed first before any non-key fields in tables, so the key field setting is
556
+ disabled by default in order to have the columns in the table respect the order of the fields as they are
557
+ provided to this function.)
558
+ :param field_modifiers: A mapping of data field name to field modifier for changes that should be applied to
559
+ the matching field. If a data field name is not present in the provided dict, or the provided dictionary is
560
+ None, then the default modifier will be used.
561
+ :param data_type: The data type name for the temporary data type that will be created for this table.
562
+ :param display_name: The display name for the temporary data type. If not provided, defaults to the data type
563
+ name.
564
+ :param plural_display_name: The plural display name for the temporary data type. If not provided, defaults to
565
+ the display name + "s".
566
+ :return: A list of dictionaries mapping the data field names of the given field definitions to the response
567
+ value from the user for that field for each row.
568
+ """
569
+ # Set the default modifier to make all fields visible and not key if no default was provided.
570
+ if default_modifier is None:
571
+ default_modifier = FieldModifier(visible=True, key_field=False)
572
+ # To make things simpler, treat null field modifiers as an empty dict.
573
+ if field_modifiers is None:
574
+ field_modifiers = {}
575
+
576
+ # Construct the final fields list from the possible field objects.
577
+ final_fields: list[AbstractVeloxFieldDefinition] = []
578
+ # Keep track of whether any given field name appears more than once, as two fields could have the same
579
+ # field name but different data types. In this case, the user should provide a field modifier or field
580
+ # definition that changes one of the field names.
581
+ field_names: list[str] = []
582
+ for field in fields:
583
+ # Find the field definition for this field object.
584
+ if isinstance(field, tuple):
585
+ field_def: AbstractVeloxFieldDefinition = self.dt_cache.get_fields_for_type(field[0]).get(field[1])
586
+ elif isinstance(field, AbstractVeloxFieldDefinition):
587
+ field_def: AbstractVeloxFieldDefinition = field
588
+ else:
589
+ raise SapioException("Unrecognized field object.")
590
+
591
+ # Locate the modifier for this field and store the modified field.
592
+ name: str = field_def.data_field_name
593
+ modifier: FieldModifier = field_modifiers.get(name, default_modifier)
594
+ field_def: AbstractVeloxFieldDefinition = modifier.modify_field(field_def)
595
+ final_fields.append(field_def)
596
+
597
+ # Verify that this field name isn't a duplicate.
598
+ # The field name may have changed due to the modifier.
599
+ name: str = field_def.data_field_name
600
+ if name in field_names:
601
+ raise SapioException(f"The field name \"{name}\" appears more than once in the given fields. "
602
+ f"If you have provided two fields with the same name but different data types, "
603
+ f"consider providing a FieldModifier where prepend_data_type is true for one of "
604
+ f"the fields so that the field names will be different.")
605
+ field_names.append(name)
606
+
607
+ # Get the values for each row.
608
+ values: list[dict[str, FieldValue]] = []
609
+ for row in row_contents:
610
+ # The final values for this row:
611
+ row_values: dict[str, FieldValue] = {}
612
+
613
+ # Map the records for this row by their data type. If a field map is provided, its data type is Default.
614
+ row_records: dict[str, SapioRecord | FieldMap] = {}
615
+ for rec in row:
616
+ # Toss out null elements.
617
+ if rec is None:
618
+ continue
619
+ # Map records to their data type name. Map field maps to Default.
620
+ dt: str = "Default" if isinstance(rec, dict) else rec.data_type_name
621
+ # Warn if the same data type name appears more than once.
622
+ if dt in row_records:
623
+ raise SapioException(f"The data type \"{dt}\" appears more than once in the given row contents.")
624
+ row_records[dt] = rec
625
+
626
+ # Get the field values from the above records.
627
+ for field in final_fields:
628
+ # Find the object that corresponds to this field given its data type name.
629
+ record: SapioRecord | FieldMap | None = row_records.get(field.data_type_name)
630
+ # This could be either a record, a field map, or null. Convert any records to field maps.
631
+ if not isinstance(record, dict) and record is not None:
632
+ record: FieldMap | None = AliasUtil.to_field_map_lists([record])[0]
633
+
634
+ # Find out if this field had its data type prepended to it. If this is the case, then we need to find
635
+ # the true data field name before retrieving the value from the field map.
636
+ name: str = field.data_field_name
637
+ if field_modifiers.get(name, default_modifier).prepend_data_type is True:
638
+ name = name.split(".")[1]
639
+
640
+ # Set the value for this particular field.
641
+ row_values[field.data_field_name] = record.get(name) if record else None
642
+ values.append(row_values)
643
+
644
+ if display_name is None:
645
+ display_name = data_type
646
+ if plural_display_name is None:
647
+ plural_display_name = display_name + "s"
648
+
649
+ builder = FormBuilder(data_type, display_name, plural_display_name)
650
+ for field in final_fields:
651
+ builder.add_field(field)
652
+
653
+ request = TableEntryDialogRequest(title, msg, builder.get_temporary_data_type(), values,
654
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
408
655
  response: list[FieldMap] | None = self.callback.show_table_entry_dialog(request)
409
656
  if response is None:
410
657
  raise SapioUserCancelledException()
@@ -453,7 +700,8 @@ class CallbackUtil:
453
700
  raise SapioException(f"The data type \"{data_type}\" does not have a layout by the name "
454
701
  f"\"{layout_name}\" in the system.")
455
702
 
456
- request = DataRecordDialogRequest(title, record, layout, minimized, access_level, plugin_path_list)
703
+ request = DataRecordDialogRequest(title, record, layout, minimized, access_level, plugin_path_list,
704
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
457
705
  response: bool = self.callback.data_record_form_view_dialog(request)
458
706
  if not response:
459
707
  raise SapioUserCancelledException()
@@ -464,7 +712,8 @@ class CallbackUtil:
464
712
  values: list[FieldMap],
465
713
  multi_select: bool = True,
466
714
  *,
467
- display_name: str = "Default",
715
+ data_type: str = "Default",
716
+ display_name: str | None = None,
468
717
  plural_display_name: str | None = None) -> list[FieldMap]:
469
718
  """
470
719
  Create a selection dialog for a list of field maps for the user to choose from. Requires that the caller
@@ -475,24 +724,31 @@ class CallbackUtil:
475
724
  they are provided in this list.
476
725
  :param values: The values to set for each row of the table.
477
726
  :param multi_select: Whether the user is able to select multiple rows from the list.
478
- :param display_name: The display name for the temporary data type that will be created.
727
+ :param data_type: The data type name for the temporary data type that will be created for this table.
728
+ :param display_name: The display name for the temporary data type. If not provided, defaults to the data type
729
+ name.
479
730
  :param plural_display_name: The plural display name for the temporary data type. If not provided, defaults to
480
731
  the display name + "s".
481
732
  :return: A list of field maps corresponding to the chosen input field maps.
482
733
  """
734
+ if display_name is None:
735
+ display_name = data_type
483
736
  if plural_display_name is None:
484
737
  plural_display_name = display_name + "s"
485
738
 
486
- # Build the form using only those fields that are desired.
487
- request = DataRecordSelectionRequest(display_name, plural_display_name,
488
- fields, values, msg, multi_select)
489
- response: list[FieldMap] | None = self.callback.show_data_record_selection_dialog(request)
739
+ builder = FormBuilder(data_type, display_name, plural_display_name)
740
+ for field in fields:
741
+ builder.add_field(field)
742
+
743
+ request = TempTableSelectionRequest(builder.get_temporary_data_type(), msg, values,
744
+ multi_select=multi_select)
745
+ response: list[FieldMap] | None = self.callback.show_temp_table_selection_dialog(request)
490
746
  if response is None:
491
747
  raise SapioUserCancelledException()
492
748
  return response
493
749
 
494
750
  def record_selection_dialog(self, msg: str, fields: list[str], records: list[SapioRecord],
495
- multi_select: bool = True) -> list[FieldMap]:
751
+ multi_select: bool = True) -> list[SapioRecord]:
496
752
  """
497
753
  Create a record selection dialog for a list of records for the user to choose from. Provided field names must
498
754
  match fields on the definition of the data type of the given records.
@@ -505,7 +761,7 @@ class CallbackUtil:
505
761
  they are provided in this list.
506
762
  :param records: The records to display as rows in the table.
507
763
  :param multi_select: Whether the user is able to select multiple records from the list.
508
- :return: A list of field maps corresponding to the chosen input records.
764
+ :return: A list of the selected records.
509
765
  """
510
766
  data_types: set[str] = {x.data_type_name for x in records}
511
767
  if len(data_types) > 1:
@@ -521,21 +777,22 @@ class CallbackUtil:
521
777
  type_def: DataTypeDefinition = self.dt_cache.get_data_type(data_type)
522
778
  field_defs: dict[str, AbstractVeloxFieldDefinition] = self.dt_cache.get_fields_for_type(data_type)
523
779
 
780
+ # Key fields display their columns in order before all non-key fields.
781
+ # Unmark key fields so that the column order is respected exactly as the caller provides it.
782
+ # Also make everything visible, because presumably the caller give a field name because they want it to be seen.
783
+ modifier = FieldModifier(visible=True, key_field=False)
784
+
524
785
  # Build the form using only those fields that are desired.
525
- field_def_list: list = []
786
+ builder = FormBuilder(data_type, type_def.display_name, type_def.plural_display_name)
526
787
  for field_name in fields:
527
788
  field_def = field_defs.get(field_name)
528
789
  if field_def is None:
529
790
  raise SapioException(f"No field of name \"{field_name}\" in field definitions of type \"{data_type}\"")
530
- field_def.visible = True
531
- # Key fields display their columns in order before all non-key fields.
532
- # Unmark key fields so that the column order is respected exactly as the caller provides it.
533
- field_def.key_field = False
534
- field_def_list.append(field_def)
535
-
536
- request = DataRecordSelectionRequest(type_def.display_name, type_def.plural_display_name,
537
- field_def_list, field_map_list, msg, multi_select)
538
- response: list[FieldMap] | None = self.callback.show_data_record_selection_dialog(request)
791
+ builder.add_field(modifier.modify_field(field_def))
792
+
793
+ request = TempTableSelectionRequest(builder.get_temporary_data_type(), msg, field_map_list,
794
+ multi_select=multi_select)
795
+ response: list[FieldMap] | None = self.callback.show_temp_table_selection_dialog(request)
539
796
  if response is None:
540
797
  raise SapioUserCancelledException()
541
798
  # Map the field maps in the response back to the record they come from, returning the chosen record instead of
@@ -602,7 +859,7 @@ class CallbackUtil:
602
859
 
603
860
  # If CustomReportCriteria was provided, it must be wrapped as a CustomReport.
604
861
  if isinstance(custom_search, CustomReportCriteria):
605
- custom_search: CustomReport = CustomReport(False, None, custom_search)
862
+ custom_search: CustomReport = CustomReport(False, [], custom_search)
606
863
  # If a string was provided, locate the report criteria for the predefined search in the system matching this
607
864
  # name.
608
865
  if isinstance(custom_search, str):
@@ -635,14 +892,15 @@ class CallbackUtil:
635
892
  for field in additional_fields:
636
893
  builder.add_field(field)
637
894
  temp_dt = builder.get_temporary_data_type()
638
- request = ESigningRequestPojo(title, msg, show_comment, temp_dt)
895
+ request = ESigningRequestPojo(title, msg, show_comment, temp_dt,
896
+ width_in_pixels=self.width_pixels, width_percentage=self.width_percent)
639
897
  response: ESigningResponsePojo | None = self.callback.show_esign_dialog(request)
640
898
  if response is None:
641
899
  raise SapioUserCancelledException()
642
900
  return response
643
901
 
644
902
  def request_file(self, title: str, exts: list[str] | None = None,
645
- show_image_editor: bool = False, show_camera_button: bool = False) -> (str, bytes):
903
+ show_image_editor: bool = False, show_camera_button: bool = False) -> tuple[str, bytes]:
646
904
  """
647
905
  Request a single file from the user.
648
906
 
@@ -675,7 +933,7 @@ class CallbackUtil:
675
933
  return file_path, sink.data
676
934
 
677
935
  def request_files(self, title: str, exts: list[str] | None = None,
678
- show_image_editor: bool = False, show_camera_button: bool = False):
936
+ show_image_editor: bool = False, show_camera_button: bool = False) -> dict[str, bytes]:
679
937
  """
680
938
  Request multiple files from the user.
681
939
 
@@ -706,7 +964,7 @@ class CallbackUtil:
706
964
  return ret_dict
707
965
 
708
966
  @staticmethod
709
- def __verify_file(file_path: str, file_bytes: bytes, allowed_extensions: list[str]):
967
+ def __verify_file(file_path: str, file_bytes: bytes, allowed_extensions: list[str]) -> None:
710
968
  """
711
969
  Verify that the provided file was read (i.e. the file path and file bytes aren't None or empty) and that it
712
970
  has the correct file extension. Raises a user error exception if something about the file is incorrect.
@@ -720,7 +978,7 @@ class CallbackUtil:
720
978
  if len(allowed_extensions) != 0:
721
979
  matches: bool = False
722
980
  for ext in allowed_extensions:
723
- if file_path.endswith("." + ext):
981
+ if file_path.endswith("." + ext.lstrip(".")):
724
982
  matches = True
725
983
  break
726
984
  if matches is False:
@@ -734,5 +992,85 @@ class CallbackUtil:
734
992
  :param file_name: The name of the file.
735
993
  :param file_data: The data of the file, provided as either a string or as a bytes array.
736
994
  """
737
- data = io.StringIO(file_data) if isinstance(file_data, str) else io.BytesIO(file_data)
995
+ data = io.BytesIO(file_data.encode() if isinstance(file_data, str) else file_data)
738
996
  self.callback.send_file(file_name, False, data)
997
+
998
+ def write_zip_file(self, zip_name: str, files: dict[str, str | bytes]) -> None:
999
+ """
1000
+ Send a collection of files to the user in a zip file.
1001
+
1002
+ :param zip_name: The name of the zip file.
1003
+ :param files: A dictionary of the files to add to the zip file.
1004
+ """
1005
+ data = io.BytesIO(FileUtil.zip_files(files))
1006
+ self.callback.send_file(zip_name, False, data)
1007
+
1008
+
1009
+ class FieldModifier:
1010
+ """
1011
+ A FieldModifier can be used to update the settings of a field definition from the system.
1012
+ """
1013
+ prepend_data_type: bool
1014
+ display_name: str | None
1015
+ required: bool | None
1016
+ editable: bool | None
1017
+ visible: bool | None
1018
+ key_field: bool | None
1019
+ column_width: int | None
1020
+
1021
+ def __init__(self, *, prepend_data_type: bool = False,
1022
+ display_name: str | None = None, required: bool | None = None, editable: bool | None = None,
1023
+ visible: bool | None = None, key_field: bool | None = None, column_width: int | None = None):
1024
+ """
1025
+ If any values are given as None then that value will not be changed on the given field.
1026
+
1027
+ :param prepend_data_type: If true, prepends the data type name of the field to the data field name. For example,
1028
+ if a field has a data type name X and a data field name Y, then the field name would become "X.Y". This is
1029
+ useful for cases where you have the same field name on two different data types and want to distinguish one
1030
+ or both of them.
1031
+ :param display_name: Change the display name.
1032
+ :param required: Change the required status.
1033
+ :param editable: Change the editable status.
1034
+ :param visible: Change the visible status.
1035
+ :param key_field: Change the key field status.
1036
+ :param column_width: Change the column width.
1037
+ """
1038
+ self.prepend_data_type = prepend_data_type
1039
+ self.display_name = display_name
1040
+ self.required = required
1041
+ self.editable = editable
1042
+ self.visible = visible
1043
+ self.key_field = key_field
1044
+ self.column_width = column_width
1045
+
1046
+ def modify_field(self, field: AbstractVeloxFieldDefinition) -> AbstractVeloxFieldDefinition:
1047
+ """
1048
+ Apply modifications to a given field.
1049
+
1050
+ :param field: The field to modify.
1051
+ :return: A copy of the input field with the modifications applied.
1052
+ """
1053
+ field = copy_field(field)
1054
+ if self.prepend_data_type is True:
1055
+ field._data_field_name = field.data_field_name + "." + field.data_field_name
1056
+ if self.display_name is not None:
1057
+ field.display_name = self.display_name
1058
+ if self.required is not None:
1059
+ field.required = self.required
1060
+ if self.editable is not None:
1061
+ field.editable = self.editable
1062
+ if self.visible is not None:
1063
+ field.visible = self.visible
1064
+ if self.key_field is not None:
1065
+ field.key_field = self.key_field
1066
+ if self.column_width is not None:
1067
+ field.default_table_column_width = self.column_width
1068
+ return field
1069
+
1070
+
1071
+ def copy_field(field: AbstractVeloxFieldDefinition) -> AbstractVeloxFieldDefinition:
1072
+ """
1073
+ Create a copy of a given field definition. This is used to modify field definitions from the server for existing
1074
+ data types without also modifying the field definition in the cache.
1075
+ """
1076
+ return FieldDefinitionParser.to_field_definition(field.to_json())