-
-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathvalidators.py
1451 lines (1168 loc) · 48 KB
/
validators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# This file is part of SENAITE.CORE.
#
# SENAITE.CORE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright 2018-2021 by it's authors.
# Some rights reserved, see README and LICENSE.
import re
import string
import types
from time import strptime as _strptime
from bika.lims import api
from bika.lims import bikaMessageFactory as _
from bika.lims import logger
from bika.lims.api import APIError
from bika.lims.catalog import SETUP_CATALOG
from senaite.core.i18n import translate as _t
from bika.lims.utils import to_utf8
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import safe_unicode
from Products.validation import validation
from Products.validation.interfaces.IValidator import IValidator
from Products.ZCTextIndex.ParseTree import ParseError
from zope.interface import implements
class IdentifierTypeAttributesValidator:
"""Validate IdentifierTypeAttributes to ensure that attributes are
not duplicated.
"""
implements(IValidator)
name = "identifiertypeattributesvalidator"
def __call__(self, value, *args, **kwargs):
instance = kwargs['instance']
request = instance.REQUEST
form = request.get('form', {})
fieldname = kwargs['field'].getName()
form_value = form.get(fieldname, False)
if form_value is False:
# not required...
return True
if value == instance.get(fieldname):
# no change.
return True
return True
validation.register(IdentifierTypeAttributesValidator())
class IdentifierValidator:
"""some actual validation should go here.
I'm leaving this stub registered, but adding no extra validation.
"""
implements(IValidator)
name = "identifiervalidator"
def __call__(self, value, *args, **kwargs):
instance = kwargs['instance']
request = instance.REQUEST
form = request.get('form', {})
fieldname = kwargs['field'].getName()
form_value = form.get(fieldname, False)
if form_value is False:
# not required...
return True
if value == instance.get(fieldname):
# no change.
return True
return True
validation.register(IdentifierValidator())
class UniqueFieldValidator:
"""Verifies if a field value is unique within the same container
"""
implements(IValidator)
name = "uniquefieldvalidator"
def get_parent_objects(self, context):
"""Return all objects of the same type from the parent object
"""
parent_object = api.get_parent(context)
portal_type = api.get_portal_type(context)
return parent_object.objectValues(portal_type)
def query_parent_objects(self, context, query=None):
"""Return the objects of the same type from the parent object
:param query: Catalog query to narrow down the objects
:type query: dict
:returns: Content objects of the same portal type in the parent
"""
# return the object values if we have no catalog query
if query is None:
return self.get_parent_objects(context)
# avoid undefined reference of catalog in except...
catalog = None
# try to fetch the results via the catalog
try:
catalogs = api.get_catalogs_for(context)
catalog = catalogs[0]
return map(api.get_object, catalog(query))
except (IndexError, UnicodeDecodeError, ParseError, APIError) as e:
# fall back to the object values of the parent
logger.warn("UniqueFieldValidator: Catalog query {} failed "
"for catalog {} ({}) -> returning object values of {}"
.format(query, repr(catalog), str(e),
repr(api.get_parent(context))))
return self.get_parent_objects(context)
def make_catalog_query(self, context, field, value):
"""Create a catalog query for the field
"""
# get the catalogs for the context
catalogs = api.get_catalogs_for(context)
# context not in any catalog?
if not catalogs:
logger.warn("UniqueFieldValidator: Context '{}' is not assigned"
"to any catalog!".format(repr(context)))
return None
# take the first catalog
catalog = catalogs[0]
# Check if the field accessor is indexed
field_index = field.getName()
accessor = field.getAccessor(context)
if accessor:
field_index = accessor.__name__
# return if the field is not indexed
if field_index not in catalog.indexes():
return None
# build a catalog query
query = {
"portal_type": api.get_portal_type(context),
"path": {
"query": api.get_parent_path(context),
"depth": 1,
}
}
query[field_index] = value
logger.info("UniqueFieldValidator:Query={}".format(query))
return query
def __call__(self, value, *args, **kwargs):
context = kwargs['instance']
uid = api.get_uid(context)
field = kwargs['field']
fieldname = field.getName()
translate = getToolByName(context, 'translation_service').translate
# return directly if nothing changed
if value == field.get(context):
return True
# Fetch the parent object candidates by catalog or by objectValues
#
# N.B. We want to use the catalog to speed things up, because using
# `parent.objectValues` is very expensive if the parent object contains
# many items and causes the UI to block too long
catalog_query = self.make_catalog_query(context, field, value)
parent_objects = self.query_parent_objects(
context, query=catalog_query)
for item in parent_objects:
if hasattr(item, 'UID') and item.UID() != uid and \
fieldname in item.Schema() and \
str(item.Schema()[fieldname].get(item)) == str(value).strip():
# We have to compare them as strings because
# even if a number (as an id) is saved inside
# a string widget and string field, it will be
# returned as an int. I don't know if it is
# caused because is called with
# <item.Schema()[fieldname].get(item)>,
# but it happens...
msg = _(
"Validation failed: '${value}' is not unique",
mapping={
'value': safe_unicode(value)
})
return to_utf8(translate(msg))
return True
validation.register(UniqueFieldValidator())
class InvoiceBatch_EndDate_Validator:
""" Verifies that the End Date is after the Start Date """
implements(IValidator)
name = "invoicebatch_EndDate_validator"
def __call__(self, value, *args, **kwargs):
instance = kwargs.get('instance')
request = kwargs.get('REQUEST')
if request and request.form.get('BatchStartDate'):
startdate = _strptime(request.form.get('BatchStartDate'), '%Y-%m-%d %H:%M')
else:
startdate = _strptime(instance.getBatchStartDate(), '%Y-%m-%d %H:%M')
enddate = _strptime(value, '%Y-%m-%d %H:%M')
translate = api.get_tool('translation_service', instance).translate
if not enddate >= startdate:
msg = _("Start date must be before End Date")
return to_utf8(translate(msg))
return True
validation.register(InvoiceBatch_EndDate_Validator())
class ServiceKeywordValidator:
"""Validate AnalysisService Keywords
must match isUnixLikeName
may not be the same as another service keyword
may not be the same as any InterimField id.
"""
implements(IValidator)
name = "servicekeywordvalidator"
def __call__(self, value, *args, **kwargs):
instance = kwargs['instance']
if instance.getKeyword() == value:
# Nothing changed
return
# The validators module get imported early in __init__.py,
# and this line causes this (indirect) import error:
#
# from bika.lims.browser.fields.uidreferencefield import get_backreferences
# ImportError: cannot import name SuperModel
#
# Mental note from ramonski:
# Probably because *all* fields get imported in
# bika.lims.browser.fields.__init__.py and the ZCA is not yet fully
# initialized.
#
# https://github.com/senaite/senaite.docker/issues/14
from bika.lims.api.analysisservice import check_keyword
err_msg = check_keyword(value, instance)
if err_msg:
ts = api.get_tool("translation_service")
return to_utf8(ts.translate(err_msg))
return True
validation.register(ServiceKeywordValidator())
class InterimFieldsValidator:
"""Validating InterimField keywords.
XXX Applied as a subfield validator but validates entire field.
keyword must match isUnixLikeName
keyword may not be the same as any service keyword.
keyword must be unique in this InterimFields field
keyword must be unique for interimfields which share the same title.
title must be unique for interimfields which share the same keyword.
"""
implements(IValidator)
name = "interimfieldsvalidator"
def __call__(self, value, *args, **kwargs):
instance = kwargs['instance']
fieldname = kwargs['field'].getName()
request = kwargs.get('REQUEST', {})
form = request.form
interim_fields = form.get(fieldname, [])
translate = getToolByName(instance, 'translation_service').translate
bsc = getToolByName(instance, 'senaite_catalog_setup')
# We run through the validator once per form submit, and check all
# values
# this value in request prevents running once per subfield value.
key = instance.id + fieldname
if instance.REQUEST.get(key, False):
return True
for x in range(len(interim_fields)):
row = interim_fields[x]
keys = row.keys()
if 'title' not in keys:
instance.REQUEST[key] = to_utf8(
translate(_("Validation failed: title is required")))
return instance.REQUEST[key]
if 'keyword' not in keys:
instance.REQUEST[key] = to_utf8(
translate(_("Validation failed: keyword is required")))
return instance.REQUEST[key]
if not re.match(r"^[A-Za-z\w\d\-\_]+$", row['keyword']):
instance.REQUEST[key] = _(
"Validation failed: keyword contains invalid characters")
return instance.REQUEST[key]
# keywords and titles used once only in the submitted form
keywords = {}
titles = {}
for field in interim_fields:
if 'keyword' in field:
if field['keyword'] in keywords:
keywords[field['keyword']] += 1
else:
keywords[field['keyword']] = 1
if 'title' in field:
if field['title'] in titles:
titles[field['title']] += 1
else:
titles[field['title']] = 1
for k in [k for k in keywords.keys() if keywords[k] > 1]:
msg = _(
"Validation failed: '${keyword}': duplicate keyword",
mapping={
'keyword': safe_unicode(k)
})
instance.REQUEST[key] = to_utf8(translate(msg))
return instance.REQUEST[key]
for t in [t for t in titles.keys() if titles[t] > 1]:
msg = _(
"Validation failed: '${title}': duplicate title",
mapping={
'title': safe_unicode(t)
})
instance.REQUEST[key] = to_utf8(translate(msg))
return instance.REQUEST[key]
# check all keywords against all AnalysisService keywords for dups
services = bsc(portal_type='AnalysisService', getKeyword=value)
if services:
msg = _(
"Validation failed: '${title}': "
"This keyword is already in use by service '${used_by}'",
mapping={
'title': safe_unicode(value),
'used_by': safe_unicode(services[0].Title)
})
instance.REQUEST[key] = to_utf8(translate(msg))
return instance.REQUEST[key]
# any duplicated interimfield titles must share the same keyword
# any duplicated interimfield keywords must share the same title
calcs = bsc(portal_type='Calculation')
keyword_titles = {}
title_keywords = {}
for calc in calcs:
if calc.UID == instance.UID():
continue
calc = calc.getObject()
for field in calc.getInterimFields():
keyword_titles[field['keyword']] = field['title']
title_keywords[field['title']] = field['keyword']
for field in interim_fields:
if field['keyword'] != value:
continue
if 'title' in field and \
field['title'] in title_keywords.keys() and \
title_keywords[field['title']] != field['keyword']:
msg = _(
"Validation failed: column title '${title}' "
"must have keyword '${keyword}'",
mapping={
'title': safe_unicode(field['title']),
'keyword': safe_unicode(title_keywords[field['title']])
})
instance.REQUEST[key] = to_utf8(translate(msg))
return instance.REQUEST[key]
if 'keyword' in field and \
field['keyword'] in keyword_titles.keys() and \
keyword_titles[field['keyword']] != field['title']:
msg = _(
"Validation failed: keyword '${keyword}' "
"must have column title '${title}'",
mapping={
'keyword': safe_unicode(field['keyword']),
'title': safe_unicode(keyword_titles[field['keyword']])
})
instance.REQUEST[key] = to_utf8(translate(msg))
return instance.REQUEST[key]
# Check if choices subfield is valid
for interim in interim_fields:
message = self.validate_choices(interim)
if message:
# Not a valid choice
instance.REQUEST[key] = message
return message
instance.REQUEST[key] = True
return True
def validate_choices(self, interim):
"""Checks whether the choices are valid for the given interim
"""
result_type = interim.get("result_type", "")
choices = interim.get("choices")
if not choices:
# No choices set, result type should remain empty or multivalue
if result_type in ["", "multivalue"]:
return
return _t(_("Control type is not supported for empty choices"))
# Choices are expressed like "value0:text0|value1:text1|..|valuen:textn"
choices = choices.split("|") or []
try:
choices = dict(map(lambda ch: ch.strip().split(":"), choices))
except ValueError:
return _t(_(
"No valid format in choices field. Supported format is: "
"<value-0>:<text>|<value-1>:<text>|<value-n>:<text>"))
# Empty keys (that match with the result value) are not allowed
keys = map(lambda k: k.strip(), choices.keys())
empties = filter(None, keys)
if len(empties) != len(keys):
return _t(_("Empty keys are not supported"))
# No duplicate keys allowed
unique_keys = list(set(keys))
if len(unique_keys) != len(keys):
return _t(_("Duplicate keys in choices field"))
# We need at least 2 choices
if len(keys) < 2:
return _t(_("At least, two options for choices field are required"))
# Multivalue is not supported with choices
if result_type in ["multivalue"]:
return _t(_(
"Multiple values control type is not supported for choices"
))
validation.register(InterimFieldsValidator())
class FormulaValidator:
""" Validate keywords in calculation formula entry
"""
implements(IValidator)
name = "formulavalidator"
def __call__(self, value, *args, **kwargs):
if not value:
return True
instance = kwargs["instance"]
request = api.get_request()
form = request.form
interim_fields = form.get("InterimFields", [])
translate = getToolByName(instance, "translation_service").translate
catalog = api.get_tool(SETUP_CATALOG)
interim_keywords = filter(None, map(
lambda i: i.get("keyword"), interim_fields))
keywords = re.compile(r"\[([^\.^\]]+)\]").findall(value)
for keyword in keywords:
# Check if the service keyword exists and is active.
dep_service = catalog(getKeyword=keyword, is_active=True)
if not dep_service and keyword not in interim_keywords:
msg = _(
"Validation failed: Keyword '${keyword}' is invalid",
mapping={
'keyword': safe_unicode(keyword)
})
return to_utf8(translate(msg))
# Allow to use Wildcards, LDL and UDL values in calculations
allowedwds = ["LDL", "UDL", "BELOWLDL", "ABOVEUDL"]
keysandwildcards = re.compile(r"\[([^\]]+)\]").findall(value)
keysandwildcards = [k for k in keysandwildcards if "." in k]
keysandwildcards = [k.split(".", 1) for k in keysandwildcards]
errwilds = [k[1] for k in keysandwildcards if k[0] not in keywords]
if len(errwilds) > 0:
msg = _(
"Wildcards for interims are not allowed: ${wildcards}",
mapping={
"wildcards": safe_unicode(", ".join(errwilds))
})
return to_utf8(translate(msg))
wildcards = [k[1] for k in keysandwildcards if k[0] in keywords]
wildcards = [wd for wd in wildcards if wd not in allowedwds]
if len(wildcards) > 0:
msg = _(
"Invalid wildcards found: ${wildcards}",
mapping={
"wildcards": safe_unicode(", ".join(wildcards))
})
return to_utf8(translate(msg))
return True
validation.register(FormulaValidator())
class CoordinateValidator:
""" Validate latitude or longitude field values
"""
implements(IValidator)
name = "coordinatevalidator"
def __call__(self, value, **kwargs):
if not value:
return True
instance = kwargs['instance']
fieldname = kwargs['field'].getName()
request = instance.REQUEST
form = request.form
form_value = form.get(fieldname)
translate = getToolByName(instance, 'translation_service').translate
try:
degrees = int(form_value['degrees'])
except ValueError:
return to_utf8(
translate(_("Validation failed: degrees must be numeric")))
try:
minutes = int(form_value['minutes'])
except ValueError:
return to_utf8(
translate(_("Validation failed: minutes must be numeric")))
try:
seconds = int(form_value['seconds'])
except ValueError:
return to_utf8(
translate(_("Validation failed: seconds must be numeric")))
if not 0 <= minutes <= 59:
return to_utf8(
translate(_("Validation failed: minutes must be 0 - 59")))
if not 0 <= seconds <= 59:
return to_utf8(
translate(_("Validation failed: seconds must be 0 - 59")))
bearing = form_value['bearing']
if fieldname == 'Latitude':
if not 0 <= degrees <= 90:
return to_utf8(
translate(_("Validation failed: degrees must be 0 - 90")))
if degrees == 90:
if minutes != 0:
return to_utf8(
translate(
_("Validation failed: degrees is 90; "
"minutes must be zero")))
if seconds != 0:
return to_utf8(
translate(
_("Validation failed: degrees is 90; "
"seconds must be zero")))
if bearing.lower() not in 'sn':
return to_utf8(
translate(_("Validation failed: Bearing must be N/S")))
if fieldname == 'Longitude':
if not 0 <= degrees <= 180:
return to_utf8(
translate(_("Validation failed: degrees must be 0 - 180")))
if degrees == 180:
if minutes != 0:
return to_utf8(
translate(
_("Validation failed: degrees is 180; "
"minutes must be zero")))
if seconds != 0:
return to_utf8(
translate(
_("Validation failed: degrees is 180; "
"seconds must be zero")))
if bearing.lower() not in 'ew':
return to_utf8(
translate(_("Validation failed: Bearing must be E/W")))
return True
validation.register(CoordinateValidator())
class ResultOptionsValueValidator(object):
"""Validator for the subfield "ResultValue" of ResultOptions field
"""
implements(IValidator)
name = "result_options_value_validator"
def __call__(self, value, *args, **kwargs):
# Result Value must be floatable
if not api.is_floatable(value):
return _t(_("Result Value must be a number"))
# Get all records
instance = kwargs['instance']
field_name = kwargs['field'].getName()
request = instance.REQUEST
records = request.form.get(field_name)
# Result values must be unique
value = api.to_float(value)
values = map(lambda ro: ro.get("ResultValue"), records)
values = filter(api.is_floatable, values)
values = map(api.to_float, values)
duplicates = filter(lambda val: val == value, values)
if len(duplicates) > 1:
return _t(_("Result Value must be unique"))
return True
validation.register(ResultOptionsValueValidator())
class ResultOptionsTextValidator(object):
"""Validator for the subfield "ResultText" of ResultsOption field
"""
implements(IValidator)
name = "result_options_text_validator"
def __call__(self, value, *args, **kwargs):
# Result Text is required
if not value or not value.strip():
return _t(_("Display Value is required"))
# Get all records
instance = kwargs['instance']
field_name = kwargs['field'].getName()
request = instance.REQUEST
records = request.form.get(field_name)
# Result Text must be unique
original_texts = map(lambda ro: ro.get("ResultText"), records)
duplicates = filter(lambda text: text == value, original_texts)
if len(duplicates) > 1:
return _t(_("Display Value must be unique"))
return True
validation.register(ResultOptionsTextValidator())
class RestrictedCategoriesValidator:
""" Verifies that client Restricted categories include all categories
required by service dependencies. """
implements(IValidator)
name = "restrictedcategoriesvalidator"
def __call__(self, value, *args, **kwargs):
instance = kwargs['instance']
# fieldname = kwargs['field'].getName()
# request = kwargs.get('REQUEST', {})
# form = request.get('form', {})
translate = getToolByName(instance, 'translation_service').translate
bsc = getToolByName(instance, 'senaite_catalog_setup')
# uc = getToolByName(instance, 'uid_catalog')
failures = []
for category in value:
if not category:
continue
services = bsc(portal_type="AnalysisService", category_uid=category)
for service in services:
service = service.getObject()
calc = service.getCalculation()
deps = calc and calc.getDependentServices() or []
for dep in deps:
if dep.getCategoryUID() not in value:
title = dep.getCategoryTitle()
if title not in failures:
failures.append(title)
if failures:
msg = _(
"Validation failed: The selection requires the following "
"categories to be selected: ${categories}",
mapping={
'categories': safe_unicode(','.join(failures))
})
return to_utf8(translate(msg))
return True
validation.register(RestrictedCategoriesValidator())
class PrePreservationValidator:
""" Validate PrePreserved Containers.
User must select a Preservation.
"""
implements(IValidator)
name = "container_prepreservation_validator"
def __call__(self, value, *args, **kwargs):
# If not prepreserved, no validation required.
if not value:
return True
instance = kwargs['instance']
# fieldname = kwargs['field'].getName()
request = kwargs.get('REQUEST', {})
form = request.form
preservation = form.get('Preservation')
if type(preservation) in (list, tuple):
preservation = preservation[0]
if preservation:
return True
translate = getToolByName(instance, 'translation_service').translate
# bsc = getToolByName(instance, 'senaite_catalog_setup')
if not preservation:
msg = _("Validation failed: PrePreserved containers "
"must have a preservation selected.")
return to_utf8(translate(msg))
validation.register(PrePreservationValidator())
class StandardIDValidator:
r"""Matches against regular expression:
[^A-Za-z\w\d\-\_]
"""
implements(IValidator)
name = "standard_id_validator"
def __call__(self, value, *args, **kwargs):
regex = r"[^A-Za-z\w\d\-\_]"
instance = kwargs['instance']
# fieldname = kwargs['field'].getName()
# request = kwargs.get('REQUEST', {})
# form = request.get('form', {})
translate = getToolByName(instance, 'translation_service').translate
# check the value against all AnalysisService keywords
if re.findall(regex, value):
msg = _("Validation failed: keyword contains invalid "
"characters")
return to_utf8(translate(msg))
return True
validation.register(StandardIDValidator())
def get_record_value(request, uid, keyword, default=None):
"""Returns the value for the keyword and uid from the request"""
value = request.get(keyword)
if not value:
return default
if not isinstance(value, list):
return default
return value[0].get(uid, default) or default
class AnalysisSpecificationsValidator:
"""Min value must be below max value
Warn min value must be below min value or empty
Warn max value must above max value or empty
Percentage value must be between 0 and 100
Values must be numbers
"""
implements(IValidator)
name = "analysisspecs_validator"
def __call__(self, value, *args, **kwargs):
instance = kwargs["instance"]
request = kwargs.get("REQUEST") or {}
fieldname = kwargs["field"].getName()
# This value in request prevents running once per subfield value.
# self.name returns the name of the validator. This allows other
# subfield validators to be called if defined (eg. in other add-ons)
key = "{}-{}-{}".format(self.name, instance.getId(), fieldname)
if instance.REQUEST.get(key, False):
return True
# Walk through all AS UIDs and validate each parameter for that AS
service_uids = request.get("uids", [])
for uid in service_uids:
err_msg = self.validate_service(request, uid)
if not err_msg:
continue
# Validation failed
service = api.get_object_by_uid(uid)
title = api.get_title(service)
err_msg = "{}: {}".format(title, _(err_msg))
translate = api.get_tool("translation_service").translate
instance.REQUEST[key] = to_utf8(translate(safe_unicode(err_msg)))
return instance.REQUEST[key]
instance.REQUEST[key] = True
return True
def validate_service(self, request, uid):
"""Validates the specs values from request for the service uid. Returns
a non-translated message if the validation failed.
"""
spec_min = get_record_value(request, uid, "min")
spec_max = get_record_value(request, uid, "max")
warn_min = get_record_value(request, uid, "warn_min")
warn_max = get_record_value(request, uid, "warn_max")
if not spec_min and not spec_max:
# Neither min nor max values have been set, dismiss
return None
# Allow to have empty min/max borders, e.g. only max being set
if spec_min and not api.is_floatable(spec_min):
return _("'Min' value must be numeric")
if spec_max and not api.is_floatable(spec_max):
return _("'Max' value must be numeric")
# Check if min is smaller than max range
if spec_min and spec_max:
if api.to_float(spec_min) > api.to_float(spec_max):
return _("'Max' value must be above 'Min' value")
# Handle warn min
if warn_min and not api.is_floatable(warn_min):
return _("'Warn Min' value must be numeric or empty")
if warn_min and spec_min:
if api.to_float(warn_min) > api.to_float(spec_min):
return _("'Warn Min' value must be below 'Min' value")
# Handle warn max
if warn_max and not api.is_floatable(warn_max):
return _("'Warn Max' value must be numeric or empty")
if warn_max and spec_max:
if api.to_float(warn_max) < api.to_float(spec_max):
return _("'Warn Max' value must be above 'Max' value")
return None
validation.register(AnalysisSpecificationsValidator())
class UncertaintiesValidator:
"""Uncertainties may be specified as numeric values or percentages.
Min value must be below max value.
Uncertainty must not be < 0.
"""
implements(IValidator)
name = "uncertainties_validator"
def __call__(self, subf_value, *args, **kwargs):
instance = kwargs['instance']
request = kwargs.get('REQUEST', {})
fieldname = kwargs['field'].getName()
translate = getToolByName(instance, 'translation_service').translate
# We run through the validator once per form submit, and check all
# values
# this value in request prevents running once per subfield value.
key = instance.id + fieldname
if instance.REQUEST.get(key, False):
return True
for i, value in enumerate(request[fieldname]):
# Values must be numbers
try:
minv = float(value['intercept_min'])
except ValueError:
instance.REQUEST[key] = to_utf8(
translate(
_("Validation failed: Min values must be numeric")))
return instance.REQUEST[key]
try:
maxv = float(value['intercept_max'])
except ValueError:
instance.REQUEST[key] = to_utf8(
translate(
_("Validation failed: Max values must be numeric")))
return instance.REQUEST[key]
# values may be percentages; the rest of the numeric validation must
# still pass once the '%' is stripped off.
err = value['errorvalue']
perc = False
if err.endswith('%'):
perc = True
err = err[:-1]
try:
err = float(err)
except ValueError:
instance.REQUEST[key] = to_utf8(
translate(
_("Validation failed: Error values must be numeric")))
return instance.REQUEST[key]
if perc and (err < 0 or err > 100):
# Error percentage must be between 0 and 100
instance.REQUEST[key] = to_utf8(
translate(
_("Validation failed: Error percentage must be between 0 "
"and 100")))
return instance.REQUEST[key]
# Min value must be < max
if minv > maxv:
instance.REQUEST[key] = to_utf8(
translate(
_("Validation failed: Max values must be greater than Min "
"values")))
return instance.REQUEST[key]
# Error values must be >-1
if err < 0:
instance.REQUEST[key] = to_utf8(
translate(
_("Validation failed: Error value must be 0 or greater"
)))
return instance.REQUEST[key]
instance.REQUEST[key] = True
return True
validation.register(UncertaintiesValidator())
class DurationValidator:
"""Simple stuff - just checking for integer values.
"""
implements(IValidator)
name = "duration_validator"
def __call__(self, value, *args, **kwargs):
instance = kwargs['instance']
request = kwargs.get('REQUEST') or {}
fieldname = kwargs['field'].getName()
translate = getToolByName(instance, 'translation_service').translate
value = request.get(fieldname) or None
if value:
for v in value.values():
try:
int(v)
except Exception:
return to_utf8(
translate(_("Validation failed: Values must be numbers")))