-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
1168 lines (943 loc) · 32.6 KB
/
models.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
import os
import threading
from django.db import models
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import timezone
from django.contrib.auth.models import User
local = threading.local()
PRIMEMODULO = 1000000000
COPRIMESECRET = int(os.environ.get('COPRIMESECRET', '383446691'))
INVERSE_COPRIME = pow(COPRIMESECRET, -1, mod=PRIMEMODULO)
def set_user_context(user):
"""
Stores a Django user context to use when updating (eg. in worker process or unit test)
"""
local.user = user
def get_user_context():
"""
Retrieves a previously stored Django user context.
"""
try:
user = local.user
return user
except AttributeError:
thread_id = threading.get_ident()
msg = f"A valid Django user context is required to save this instance. Try setting the user context via set_user_context() (thread_id='{thread_id}')."
raise ImproperlyConfigured(msg)
class SoftDeletableModel(models.Model):
"""An abstract base class that provides soft-deletable Models."""
deleted = models.BooleanField(
null=False,
default=False,
db_index=True,
help_text='Flag to indicate object is deleted'
)
def delete(self):
"""Softly delete the object."""
self.deleted = True
self.save()
def soft_delete(self):
return self.delete()
def undo_delete(self):
"""Restore previouly deleted object."""
self.deleted = False
self.save()
def hard_delete(self):
"""Remove the object from the database."""
super().delete()
class Meta:
abstract=True
class TimestampedBaseQuerySet(models.query.QuerySet):
"""
An abstract QuerySet that provides self-updating created & modified fields.
"""
class Meta:
abstract = True
def update(self, *args, **kwargs):
# see: https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once
for item in self:
item.save()
super().update(*args, **kwargs)
class TimestampedBaseModel(models.Model):
"""
An abstract Model that provides self-updating created and updated fields.
Note: these fields are by default not shown in eg. Django Admin.
"""
created = models.DateTimeField(
auto_now_add=True,
null=False,
help_text='Timestamp this instance was created.'
)
updated = models.DateTimeField(
# don't use auto_add; as this will also be set on creation of this instance - see save()
null=True,
blank=True,
help_text='Timestamp this instance was last updated.'
)
objects = TimestampedBaseQuerySet.as_manager()
class Meta:
abstract = True
# ordered in reverse-chronological order by default
ordering = ['-created', '-updated']
def save(self, *args, **kwargs):
# create vs update
if not self.id:
pass
else:
self.updated = timezone.now()
super().save(*args, **kwargs)
class IdObfuscator:
@property
def public_id(self):
return self.to_public_id(self.id) # type(self).__name__[0].lower() + str(self.id * COPRIMESECRET % PRIMEMODULO)
@classmethod
def to_public_id(cls, priv_id, override_cls=None):
return id_prefix_mapping[override_cls or cls] + str(priv_id * COPRIMESECRET % PRIMEMODULO)
@staticmethod
def to_private_id(pub_id):
return int(pub_id[1:]) * INVERSE_COPRIME % PRIMEMODULO
class AuditBaseQuerySet(TimestampedBaseQuerySet):
"""
An abstract QuerySet that provides self-updating created by & updated by fields.
"""
class Meta:
abstract = True
def update(self, *args, **kwargs):
# see: https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once
for item in self:
item.save()
super().update(*args, **kwargs)
class AuditedBaseModel(TimestampedBaseModel):
"""
An abstract Model that provides self-updating created/created by and updated/updated by fields.
Note: these fields are by default not shown in eg. Django Admin.
"""
created_by = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
on_delete=models.RESTRICT,
related_name='+',
null=False,
db_index=True,
help_text='Who created this instance'
)
updated_by = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
on_delete=models.RESTRICT,
related_name='+',
null=True,
blank=True,
db_index=True,
help_text='Who updated this instance.'
)
objects = AuditBaseQuerySet.as_manager()
class Meta:
abstract = True
def save(self, *args, **kwargs):
user = get_user_context()
# create vs update
if not self.id:
self.created_by = user
else:
self.updated_by = user
self.updated = timezone.now()
super().save(*args, **kwargs)
class Company(TimestampedBaseModel):
"""
A model to store and track Company information.
"""
id = models.AutoField(
primary_key=True,
help_text="Identifier of the Company (auto-generated)."
)
name = models.CharField(
max_length=1024,
null=False,
blank=False,
unique=True,
help_text="Name of the Company."
)
class Meta:
db_table = "ifc_company"
verbose_name = "Company"
verbose_name_plural = "Companies"
def __str__(self):
return f'{self.name}'
class AuthoringTool(TimestampedBaseModel):
"""
A model to store and track Authoring Tool information.
"""
id = models.AutoField(
primary_key=True,
help_text="Identifier of the Authoring Tool (auto-generated)."
)
company = models.ForeignKey(
to=Company,
on_delete=models.SET_NULL,
related_name='company',
null=True,
blank=True,
db_index=True,
help_text='What Company this Authoring Tool belongs to (optional).'
)
name = models.CharField(
max_length=1024,
null=False,
blank=False,
help_text="Name of the Authoring Tool."
)
version = models.CharField(
max_length=128,
null=True,
blank=True,
help_text="Alphanumeric version of the Authoring Tool (eg. '1.0-alpha')."
)
class Meta:
db_table = "ifc_authoring_tool"
verbose_name = "Authoring Tool"
verbose_name_plural = "Authoring Tools"
constraints = [
models.UniqueConstraint(fields=['name', 'version'], name='unique_name_version')
]
def __str__(self):
return f'{self.full_name}'.strip()
@property
def full_name(self):
"""
Returns full name of the Authoring Tool, concatenating company, name and version (where available).
An Authoring Tool has at least a name; company and version are optional.
"""
company_name = self.company.name if self.company else ''
full_name_without_version = f'{company_name} {self.name}'.strip()
if self.version is None:
return full_name_without_version
else:
return f'{full_name_without_version} - {self.version}'.strip()
def find_by_full_name(full_name):
"""
Look for the Authoring Tool(s) within the Company/Authoring Tool hierarchy.
Fallback to matching records without versions, dashes and/or company.
"""
def full_name_without_version_dash(full_name):
without_version = full_name.rpartition(' - ') # last dash only
return '{} {}'.format(without_version[0].strip(), without_version[2].strip())
def matches(obj, full_name):
return (full_name == obj.full_name or full_name == full_name_without_version_dash(obj.full_name))
found = [obj for obj in AuthoringTool.objects.all() if matches(obj, full_name)] # cannot use a property to filter...
if found is None or len(found) == 0:
return None
elif len(found) == 1:
return found[0]
else:
return found
class Model(TimestampedBaseModel, IdObfuscator):
"""
A model to store and track Models.
"""
class Status(models.TextChoices):
"""
The overall status of an individual Model component.
"""
VALID = 'v', 'Valid'
INVALID = 'i', 'Invalid'
NOT_VALIDATED = 'n', 'Not Validated'
WARNING = 'w', 'Warning'
NOT_APPLICABLE = '-', 'Not Applicable'
class License(models.TextChoices):
"""
The license of a Model.
"""
UNKNOWN = 'UNKNOWN', 'Unknown'
PRIVATE = 'PRIVATE', 'Private'
CC = 'CC', 'CC'
MIT = 'MIT', 'MIT'
GPL = 'GPL', 'GPL'
LGPL = 'LGPL', 'LGPL'
id = models.AutoField(
primary_key=True,
help_text="Identifier of the Model (auto-generated)."
)
produced_by = models.ForeignKey(
to=AuthoringTool,
on_delete=models.SET_NULL,
related_name='models',
null=True,
blank=True,
db_index=True,
help_text='What tool was used to create this Model.'
)
date = models.DateTimeField(
null=True,
blank=True,
help_text="Timestamp the Model was created."
)
details = models.TextField(
null=True,
blank=True,
help_text="Details of the Model."
)
file_name = models.CharField(
max_length=1024,
null=False,
blank=False,
help_text="Original name of the file that contained this Model."
)
file = models.CharField(
max_length=1024,
null=False,
blank=False,
help_text="File name as it stored."
)
size = models.PositiveIntegerField(
null=False,
help_text="Size of the model (bytes)"
)
license = models.CharField(
max_length=7,
choices=License.choices,
default=License.UNKNOWN,
db_index=True,
null=False,
blank=False,
help_text="License of the Model."
)
mvd = models.CharField(
max_length=150,
null=True,
blank=True,
help_text="MVD Classification of the Model."
)
number_of_elements = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Number of elements within the Model."
)
number_of_geometries = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Number of geometries within the Model."
)
number_of_properties = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Number of properties within the Model."
)
schema = models.CharField(
max_length=25,
null=True,
blank=True,
help_text="Schema of the Model."
)
status_bsdd = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the bSDD Validation."
)
status_ia = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the IA Validation."
)
status_ip = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the IP Validation."
)
status_ids = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the IDS Validation."
)
status_mvd = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the MVD Validation."
)
status_schema = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the Schema Validation."
)
status_syntax = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the Syntax Validation."
)
status_industry_practices = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the Industry Practices Validation."
)
status_prereq = models.CharField(
max_length=1,
choices=Status.choices,
default=Status.NOT_VALIDATED,
db_index=True,
null=False,
blank=False,
help_text="Status of the Prerequisites Validation."
)
uploaded_by = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
on_delete=models.RESTRICT,
related_name='models',
null=False,
db_index=True,
help_text='Who uploaded this Model.'
)
properties = models.JSONField(
null=True,
blank=True,
help_text="Properties of the Model."
)
class Meta:
db_table = "ifc_model"
verbose_name = "Model"
verbose_name_plural = "Models"
def __str__(self):
return f'#{self.id} - {self.created.date()} - {self.file_name}'
def reset_status(self):
self.status_bsdd = Model.Status.NOT_VALIDATED
self.status_ia = Model.Status.NOT_VALIDATED
self.status_ip = Model.Status.NOT_VALIDATED
self.status_ids = Model.Status.NOT_VALIDATED
self.status_mvd = Model.Status.NOT_VALIDATED
self.status_schema = Model.Status.NOT_VALIDATED
self.status_syntax = Model.Status.NOT_VALIDATED
self.status_industry_practices = Model.Status.NOT_VALIDATED
self.status_prereq = Model.Status.NOT_VALIDATED
self.save()
class ModelInstance(TimestampedBaseModel, IdObfuscator):
"""
A model to store and track Model Instances.
"""
id = models.AutoField(
primary_key=True,
help_text="Identifier of the Model Instance (auto-generated)."
)
model = models.ForeignKey(
to=Model,
on_delete=models.CASCADE,
related_name='instances',
blank=False,
null=False,
db_index=True,
help_text='What Model this Model Instance is a part of.'
)
stepfile_id = models.PositiveBigIntegerField(
null=False,
blank=False,
db_index=True,
help_text='id assigned within the Step File (eg. #11)'
)
ifc_type = models.CharField(
max_length=50,
null=False,
blank=False,
db_index=True,
help_text="IFC Type."
)
fields = models.JSONField(
null=True,
blank=True,
help_text="Fields of the Instance."
)
class Meta:
db_table = "ifc_model_instance"
verbose_name = "Model Instance"
verbose_name_plural = "Model Instances"
constraints = [
models.UniqueConstraint(fields=['model_id', 'stepfile_id', 'ifc_type'], name='modelid_stepfileid_ifctype')
]
def __str__(self):
return f'#{self.id} - {self.ifc_type} - {self.model.file_name}'
class ValidationRequest(AuditedBaseModel, SoftDeletableModel, IdObfuscator):
"""
A model to store and track Validation Requests.
"""
class Status(models.TextChoices):
"""
The overall status of an Validation Request.
"""
PENDING = 'PENDING', 'Pending'
INITIATED = 'INITIATED', 'Initiated'
FAILED = 'FAILED', 'Failed'
COMPLETED = 'COMPLETED', 'Completed'
id = models.AutoField(
primary_key=True,
help_text="Identifier of the Validation Request (auto-generated)."
)
file_name = models.CharField(
max_length=1024,
null=False,
blank=False,
verbose_name='file name',
help_text="Name of the file."
)
file = models.FileField(
null=False,
help_text="Path of the file."
)
size = models.PositiveIntegerField(
null=False,
help_text="Size of the file (bytes)"
)
status = models.CharField(
max_length=10,
choices=Status.choices,
default=Status.PENDING,
db_index=True,
null=False,
blank=False,
help_text="Current status of the Validation Request."
)
status_reason = models.TextField(
null=True,
blank=True,
help_text="Reason for current status."
)
started = models.DateTimeField(
null=True,
db_index=True,
verbose_name='started',
help_text="Timestamp the Validation Request was started."
)
completed = models.DateTimeField(
null=True,
db_index=True,
verbose_name='completed',
help_text="Timestamp the Validation Request completed."
)
progress = models.PositiveSmallIntegerField(
null=True,
blank=True,
db_index=True,
help_text="Overall progress (%) of the Validation Request."
)
model = models.OneToOneField(
to=Model,
on_delete=models.CASCADE,
related_name='request',
null=True,
db_index=True,
help_text='What Model is created based on this Validation Request.'
)
class Meta:
db_table = "ifc_validation_request"
indexes = [models.Index(fields=["file_name", "status"])] # only add multi-column indexes here
verbose_name = "Validation Request"
verbose_name_plural = "Validation Requests"
permissions = [
("change_status", "Can change status of Validation Request")
]
def __str__(self):
return f'#{self.id} - {self.created.date()} - {self.file_name}'
@property
def has_final_status(self):
FINAL_STATUS_LIST = [
self.Status.FAILED,
self.Status.COMPLETED
]
return self.status in FINAL_STATUS_LIST
@property
def duration(self):
if self.started and self.completed:
return (self.completed - self.started)
elif self.started:
return (timezone.now() - self.started)
else:
return None
@property
def model_public_id(self):
return IdObfuscator.to_public_id(self.model_id, override_cls=Model) if self.model_id else None
def mark_as_initiated(self, reason=None):
self.status = self.Status.INITIATED
self.status_reason = reason
self.started = timezone.now()
self.completed = None
self.progress = 0
self.save()
def mark_as_completed(self, reason=None):
self.status = self.Status.COMPLETED
self.status_reason = reason
self.completed = timezone.now()
self.progress = 100
self.save()
def mark_as_failed(self, reason=None):
self.status = self.Status.FAILED
self.status_reason = reason
self.completed = timezone.now()
self.save()
def mark_as_warning(self, reason=None):
self.status = self.Status.FAILED
self.status_reason = reason
self.completed = timezone.now()
self.progress = 100
self.save()
def mark_as_pending(self, reason=None):
self.status = self.Status.PENDING
self.status_reason = reason
self.progress = 0
self.started = None
self.ended = None
self.save()
class ValidationTask(TimestampedBaseModel, IdObfuscator):
"""
A model to store and track Validation Tasks.
"""
class Type(models.TextChoices):
"""
The type of an Validation Task.
"""
SYNTAX = 'SYNTAX', 'STEP Physical File Syntax'
SCHEMA = 'SCHEMA', 'Schema (EXPRESS language)'
MVD = 'MVD', 'Model View Definitions'
BSDD = 'BSDD', 'bSDD Compliance'
PARSE_INFO = 'INFO', 'Parse Info'
PREREQUISITES = 'PREREQ', 'Prerequisites'
NORMATIVE_IA = 'NORMATIVE_IA', 'Implementer Agreements (IA)'
NORMATIVE_IP = 'NORMATIVE_IP', 'Informal Propositions (IP)'
INDUSTRY_PRACTICES = 'INDUSTRY', 'Industry Practices'
INSTANCE_COMPLETION = 'INST_COMPLETION', 'Instance Completion'
class Status(models.TextChoices):
"""
The overall status of a Validation Task.
"""
PENDING = 'PENDING', 'Pending'
SKIPPED = 'SKIPPED', 'Skipped'
NOT_APPLICABLE = 'N/A', 'Not Applicable'
INITIATED = 'INITIATED', 'Initiated'
FAILED = 'FAILED', 'Failed'
COMPLETED = 'COMPLETED', 'Completed'
id = models.AutoField(
primary_key=True,
help_text="Identifier of the task (auto-generated)."
)
request = models.ForeignKey(
to=ValidationRequest,
on_delete=models.CASCADE,
related_name='tasks',
blank=False,
null=False,
db_index=True,
help_text='What Validation Request this Validation Task belongs to.'
)
type = models.CharField(
max_length=25,
choices=Type.choices,
db_index=True,
null=False,
blank=False,
help_text="Type of the Validation Task."
)
status = models.CharField(
max_length=15,
choices=Status.choices,
default=Status.PENDING,
db_index=True,
null=False,
blank=False,
help_text="Current status of the Validation Task."
)
status_reason = models.TextField(
null=True,
blank=True,
help_text="Reason for current status."
)
started = models.DateTimeField(
null=True,
db_index=True,
verbose_name='started',
help_text="Timestamp the Validation Task was started."
)
ended = models.DateTimeField(
null=True,
db_index=True,
verbose_name='ended',
help_text="Timestamp the Validation Task ended."
)
progress = models.PositiveSmallIntegerField(
null=True,
blank=True,
db_index=True,
help_text="Overall progress (%) of the Validation Task."
)
process_id = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Process id of subprocess executing the Validation Task."
)
process_cmd = models.TextField(
null=True,
blank=True,
help_text="Command and arguments used to launch the subprocess executing the Validation Task."
)
class Meta:
db_table = "ifc_validation_task"
verbose_name = "Validation Task"
verbose_name_plural = "Validation Tasks"
def __str__(self):
return f'#{self.id} - {self.request.file_name} - {self.type} - {self.created.date()} - {self.status}'
@property
def has_final_status(self):
FINAL_STATUS_LIST = [
self.Status.SKIPPED,
self.Status.FAILED,
self.Status.NOT_APPLICABLE,
self.Status.COMPLETED
]
return self.status in FINAL_STATUS_LIST
@property
def duration(self):
if self.started and self.ended:
return (self.ended - self.started)
elif self.started:
return (timezone.now() - self.started)
else:
return None
@property
def request_public_id(self):
return IdObfuscator.to_public_id(self.request_id, override_cls=ValidationRequest) if self.request_id else None
def mark_as_initiated(self):
self.status = self.Status.INITIATED
self.started = timezone.now()
self.ended = None
self.progress = 0
self.save()
def mark_as_completed(self, reason=None):
self.status = self.Status.COMPLETED
self.status_reason = reason
self.ended = timezone.now()
self.progress = 100
self.save()
def mark_as_failed(self, reason=None):
self.status = self.Status.FAILED
self.status_reason = reason
self.ended = timezone.now()
self.save()
def mark_as_skipped(self, reason=None):
self.status = self.Status.SKIPPED
self.status_reason = reason
self.save()
def set_process_details(self, id, cmd):
self.process_id = id
self.process_cmd = cmd
self.save()
def determine_aggregate_status(self):
"""
Aggregates Severity of all Outcomes into one final Status value.
"""
agg_status = None
for outcome in self.outcomes.iterator():
if outcome.severity == ValidationOutcome.OutcomeSeverity.NOT_APPLICABLE and agg_status is None:
agg_status = Model.Status.NOT_APPLICABLE
elif outcome.severity == ValidationOutcome.OutcomeSeverity.EXECUTED and agg_status in [None, Model.Status.NOT_APPLICABLE]:
agg_status = Model.Status.VALID
elif outcome.severity == ValidationOutcome.OutcomeSeverity.PASSED and agg_status in [None, Model.Status.NOT_APPLICABLE]:
agg_status = Model.Status.VALID
elif outcome.severity == ValidationOutcome.OutcomeSeverity.WARNING:
agg_status = Model.Status.WARNING
elif outcome.severity == ValidationOutcome.OutcomeSeverity.ERROR:
agg_status = Model.Status.INVALID
break # can't get any worse...
# assume valid if no outcomes - TODO: is this correct?
if agg_status is None:
agg_status = Model.Status.VALID
return agg_status
class ValidationOutcome(TimestampedBaseModel, IdObfuscator):
"""
A model to store and track Validation Outcome instances.
"""
class OutcomeSeverity(models.IntegerChoices):
"""
The severity of an Validation Outcome.
"""
EXECUTED = 1, 'Executed'
PASSED = 2, 'Passed'
WARNING = 3, 'Warning'
ERROR = 4, 'Error'
NOT_APPLICABLE = 0, 'N/A'
class ValidationOutcomeCode(models.TextChoices):
"""
A code representing a Validation Outcome.
"""
PASSED = "P00010", "Passed"
NOT_APPLICABLE = "N00010", "Not Applicable"
# errors