-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmodels.py
3748 lines (3281 loc) · 130 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 datetime
import decimal
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import ArrayField
from django.core.validators import MinValueValidator
from django.db import connection, models, transaction
from django.db.models import Case, CharField, Count, Exists, F, Max, Min, OuterRef, Prefetch, Q, Subquery, Sum, When
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import gettext, gettext_lazy as _
from django_fsm import FSMField, transition
from model_utils import Choices, FieldTracker
from model_utils.models import TimeStampedModel
from unicef_attachments.models import Attachment, FileType as AttachmentFileType
from unicef_djangolib.fields import CodedGenericRelation
from unicef_snapshot.models import Activity
from etools.applications.core.permissions import import_permissions
from etools.applications.environment.helpers import tenant_switch_is_active
from etools.applications.environment.notifications import send_notification_with_template
from etools.applications.funds.models import FundsReservationHeader
from etools.applications.locations.models import Location
from etools.applications.organizations.models import Organization, OrganizationType
from etools.applications.partners.amendment_utils import (
calculate_difference,
copy_instance,
INTERVENTION_AMENDMENT_COPY_POST_EFFECTS,
INTERVENTION_AMENDMENT_DEFAULTS,
INTERVENTION_AMENDMENT_DIFF_POST_EFFECTS,
INTERVENTION_AMENDMENT_IGNORED_FIELDS,
INTERVENTION_AMENDMENT_MERGE_POST_EFFECTS,
INTERVENTION_AMENDMENT_RELATED_FIELDS,
merge_instance,
)
from etools.applications.partners.validation import (
agreements as agreement_validation,
interventions as intervention_validation,
)
from etools.applications.partners.validation.agreements import (
agreement_transition_to_ended_valid,
agreement_transition_to_signed_valid,
agreements_illegal_transition,
)
from etools.applications.reports.models import CountryProgramme, Indicator, Office, Result, Section
from etools.applications.t2f.models import Travel, TravelActivity, TravelType
from etools.applications.tpm.models import TPMActivity, TPMVisit
from etools.applications.users.mixins import PARTNER_ACTIVE_GROUPS
from etools.applications.users.models import Realm, User
from etools.libraries.djangolib.fields import CurrencyField
from etools.libraries.djangolib.models import MaxDistinct, StringConcat
from etools.libraries.djangolib.utils import get_environment
from etools.libraries.pythonlib.datetime import get_current_year, get_quarter
from etools.libraries.pythonlib.encoders import CustomJSONEncoder
def _get_partner_base_path(partner):
return '/'.join([
connection.schema_name,
'file_attachments',
'partner_organization',
str(partner.id),
])
def get_agreement_path(instance, filename):
return '/'.join([
_get_partner_base_path(instance.partner),
'agreements',
str(instance.agreement_number),
filename
])
def get_assessment_path(instance, filename):
return '/'.join([
_get_partner_base_path(instance.partner),
'assesments',
str(instance.id),
filename
])
def get_intervention_file_path(instance, filename):
return '/'.join([
_get_partner_base_path(instance.agreement.partner),
'agreements',
str(instance.agreement.id),
'interventions',
str(instance.id),
filename
])
def get_prc_intervention_file_path(instance, filename):
return '/'.join([
_get_partner_base_path(instance.agreement.partner),
'agreements',
str(instance.agreement.id),
'interventions',
str(instance.id),
'prc',
filename
])
def get_intervention_amendment_file_path(instance, filename):
return '/'.join([
_get_partner_base_path(instance.intervention.agreement.partner),
str(instance.intervention.agreement.partner.id),
'agreements',
str(instance.intervention.agreement.id),
'interventions',
str(instance.intervention.id),
'amendments',
str(instance.id),
filename
])
def get_intervention_attachments_file_path(instance, filename):
return '/'.join([
_get_partner_base_path(instance.intervention.agreement.partner),
'agreements',
str(instance.intervention.agreement.id),
'interventions',
str(instance.intervention.id),
'attachments',
str(instance.id),
filename
])
def get_agreement_amd_file_path(instance, filename):
return '/'.join([
connection.schema_name,
'file_attachments',
'partner_org',
str(instance.agreement.partner.id),
'agreements',
instance.agreement.base_number,
'amendments',
str(instance.number),
filename
])
class WorkspaceFileType(models.Model):
"""
Represents a file type
"""
name = models.CharField(max_length=64, unique=True, verbose_name=_('Name'))
def __str__(self):
return self.name
def hact_default():
return {
'audits': {
'minimum_requirements': 0,
'completed': 0,
},
'spot_checks': {
'minimum_requirements': 0,
'completed': {
'q1': 0,
'q2': 0,
'q3': 0,
'q4': 0,
'total': 0,
},
'follow_up_required': 0,
},
'programmatic_visits': {
'minimum_requirements': 0,
'planned': {
'q1': 0,
'q2': 0,
'q3': 0,
'q4': 0,
'total': 0,
},
'completed': {
'q1': 0,
'q2': 0,
'q3': 0,
'q4': 0,
'total': 0,
},
},
'outstanding_findings': 0,
'assurance_coverage': PartnerOrganization.ASSURANCE_VOID
}
class PartnerOrganizationQuerySet(models.QuerySet):
def active(self, *args, **kwargs):
return self.filter(
Q(partner_type=OrganizationType.CIVIL_SOCIETY_ORGANIZATION, agreements__interventions__status__in=[
Intervention.ACTIVE, Intervention.SIGNED, Intervention.SUSPENDED, Intervention.ENDED]) |
Q(total_ct_cp__gt=0), hidden=False, *args, **kwargs)
def hact_active(self, *args, **kwargs):
return self.filter(Q(reported_cy__gt=0) | Q(total_ct_cy__gt=0), *args, **kwargs)
def not_programmatic_visit_compliant(self, *args, **kwargs):
return self.hact_active(net_ct_cy__gt=PartnerOrganization.CT_MR_AUDIT_TRIGGER_LEVEL,
hact_values__programmatic_visits__completed__total=0,
*args, **kwargs)
def not_spot_check_compliant(self, *args, **kwargs):
return self.hact_active(Q(reported_cy__gt=PartnerOrganization.CT_CP_AUDIT_TRIGGER_LEVEL) |
Q(planned_engagement__spot_check_planned_q1__gt=0) |
Q(planned_engagement__spot_check_planned_q2__gt=0) |
Q(planned_engagement__spot_check_planned_q3__gt=0) |
Q(planned_engagement__spot_check_planned_q4__gt=0), # aka required
hact_values__spot_checks__completed__total=0,
hact_values__audits__completed=0, *args, **kwargs)
def not_assurance_compliant(self, *args, **kwargs):
return self.not_programmatic_visit_compliant().not_spot_check_compliant(*args, **kwargs)
class PartnerOrganizationManager(models.Manager.from_queryset(PartnerOrganizationQuerySet)):
def get_queryset(self):
return super().get_queryset()\
.select_related('organization')\
.annotate(name=F('organization__name')) \
.annotate(vendor_number=F('organization__vendor_number')) \
.annotate(partner_type=F('organization__organization_type')) \
.annotate(cso_type=F('organization__cso_type')) \
.order_by('organization__name')
class PartnerOrganization(TimeStampedModel):
"""
Represents a partner organization
related models:
Organization: "organization"
Assessment: "assessments"
"""
# When cash transferred to a country programme exceeds CT_CP_AUDIT_TRIGGER_LEVEL, an audit is triggered.
EXPIRING_ASSESSMENT_LIMIT_YEAR = 4
CT_CP_AUDIT_TRIGGER_LEVEL = decimal.Decimal('50000.00')
CT_MR_AUDIT_TRIGGER_LEVEL = decimal.Decimal('2500.00')
CT_MR_AUDIT_TRIGGER_LEVEL2 = decimal.Decimal('100000.00')
CT_MR_AUDIT_TRIGGER_LEVEL3 = decimal.Decimal('500000.00')
RATING_HIGH = 'High'
RATING_SIGNIFICANT = 'Significant'
RATING_MEDIUM = 'Medium'
RATING_LOW = 'Low'
RATING_NOT_REQUIRED = 'Not Required'
RISK_RATINGS = (
(RATING_HIGH, _('High')),
(RATING_SIGNIFICANT, _('Significant')),
(RATING_MEDIUM, _('Medium')),
(RATING_LOW, _('Low')),
(RATING_NOT_REQUIRED, _('Not Required')),
)
# PSEA Risk Ratings
PSEA_RATING_HIGH = 'Low Capacity (High Risk)'
PSEA_RATING_MEDIUM = 'Medium Capacity (Moderate Risk)'
PSEA_RATING_LOW = 'Full Capacity (Low Risk)'
RATING_HIGH_RISK_ASSUMED = 'Low Capacity Assumed - Emergency'
RATING_LOW_RISK_ASSUMED = 'No Contact with Beneficiaries'
RATING_NOT_ASSESSED = 'Not Assessed'
PSEA_RISK_RATINGS = (
(PSEA_RATING_HIGH, _('Low Capacity (High Risk)')),
(PSEA_RATING_MEDIUM, _('Medium Capacity (Moderate Risk)')),
(PSEA_RATING_LOW, _('Full Capacity (Low Risk)')),
(RATING_HIGH_RISK_ASSUMED, _('Low Capacity Assumed - Emergency')),
(RATING_LOW_RISK_ASSUMED, _('No Contact with Beneficiaries')),
(RATING_NOT_ASSESSED, _('Not Assessed'))
)
ALL_COMBINED_RISK_RATING = RISK_RATINGS + PSEA_RISK_RATINGS
MICRO_ASSESSMENT = 'MICRO ASSESSMENT'
HIGH_RISK_ASSUMED = 'HIGH RISK ASSUMED'
LOW_RISK_ASSUMED = 'LOW RISK ASSUMED'
NEGATIVE_AUDIT_RESULTS = 'NEGATIVE AUDIT RESULTS'
SIMPLIFIED_CHECKLIST = 'SIMPLIFIED CHECKLIST'
OTHERS = 'OTHERS'
# maybe at some point this can become a type_of_assessment can became a choice
TYPE_OF_ASSESSMENT = (
(MICRO_ASSESSMENT, 'Micro Assessment'),
(HIGH_RISK_ASSUMED, 'High Risk Assumed'),
(LOW_RISK_ASSUMED, 'Low Risk Assumed'),
(NEGATIVE_AUDIT_RESULTS, 'Negative Audit Results'),
(SIMPLIFIED_CHECKLIST, 'Simplified Checklist'),
(OTHERS, 'Others'),
)
AGENCY_CHOICES = Choices(
('DPKO', 'DPKO'),
('ECA', 'ECA'),
('ECLAC', 'ECLAC'),
('ESCWA', 'ESCWA'),
('FAO', 'FAO'),
('ILO', 'ILO'),
('IOM', 'IOM'),
('OHCHR', 'OHCHR'),
('UN', 'UN'),
('UN Women', 'UN Women'),
('UNAIDS', 'UNAIDS'),
('UNDP', 'UNDP'),
('UNESCO', 'UNESCO'),
('UNFPA', 'UNFPA'),
('UN - Habitat', 'UN - Habitat'),
('UNHCR', 'UNHCR'),
('UNODC', 'UNODC'),
('UNOPS', 'UNOPS'),
('UNRWA', 'UNRWA'),
('UNSC', 'UNSC'),
('UNU', 'UNU'),
('WB', 'WB'),
('WFP', 'WFP'),
('WHO', 'WHO')
)
ASSURANCE_VOID = 'void'
ASSURANCE_PARTIAL = 'partial'
ASSURANCE_COMPLETE = 'complete'
organization = models.OneToOneField(
Organization,
on_delete=models.CASCADE,
related_name='partner'
)
description = models.CharField(
verbose_name=_("Description"),
max_length=256,
blank=True
)
shared_with = ArrayField(
models.CharField(max_length=20, blank=True, choices=AGENCY_CHOICES),
verbose_name=_("Shared Partner"),
blank=True,
null=True
)
street_address = models.CharField(
verbose_name=_("Street Address"),
max_length=500,
blank=True,
null=True,
)
city = models.CharField(
verbose_name=_("City"),
max_length=64,
blank=True,
null=True,
)
postal_code = models.CharField(
verbose_name=_("Postal Code"),
max_length=32,
blank=True,
null=True,
)
country = models.CharField(
verbose_name=_("Country"),
max_length=64,
blank=True,
null=True,
)
# TODO: remove this when migration to the new fields is done. check for references
# BEGIN REMOVE
address = models.TextField(
verbose_name=_("Address"),
blank=True,
null=True
)
# END REMOVE
email = models.CharField(
verbose_name=_("Email Address"),
max_length=255,
blank=True, null=True
)
phone_number = models.CharField(
verbose_name=_("Phone Number"),
max_length=64,
blank=True,
null=True,
)
alternate_id = models.IntegerField(
verbose_name=_("Alternate ID"),
blank=True,
null=True
)
alternate_name = models.CharField(
verbose_name=_("Alternate Name"),
max_length=255,
blank=True,
null=True
)
rating = models.CharField(
verbose_name=_('Risk Rating'),
max_length=50,
choices=RISK_RATINGS,
null=True,
blank=True
)
type_of_assessment = models.CharField(
verbose_name=_("Assessment Type"),
max_length=50,
null=True,
)
last_assessment_date = models.DateField(
verbose_name=_("Last Assessment Date"),
blank=True,
null=True,
)
core_values_assessment_date = models.DateField(
verbose_name=_('Date positively assessed against core values'),
blank=True,
null=True,
)
vision_synced = models.BooleanField(
verbose_name=_("VISION Synced"),
default=False,
)
blocked = models.BooleanField(verbose_name=_("Blocked"), default=False)
deleted_flag = models.BooleanField(
verbose_name=_('Marked for deletion'),
default=False,
)
manually_blocked = models.BooleanField(verbose_name=_("Manually Hidden"), default=False)
hidden = models.BooleanField(verbose_name=_("Hidden"), default=False)
total_ct_cp = models.DecimalField(
verbose_name=_("Total Cash Transferred for Country Programme"),
decimal_places=2,
max_digits=20,
blank=True,
null=True,
help_text='Total Cash Transferred for Country Programme'
)
total_ct_cy = models.DecimalField(
verbose_name=_("Total Cash Transferred per Current Year"),
decimal_places=2,
max_digits=20,
blank=True,
null=True,
help_text='Total Cash Transferred per Current Year'
)
net_ct_cy = models.DecimalField(
decimal_places=2, max_digits=20, blank=True, null=True,
help_text='Net Cash Transferred per Current Year',
verbose_name=_('Net Cash Transferred')
)
reported_cy = models.DecimalField(
decimal_places=2, max_digits=20, blank=True, null=True,
help_text='Liquidations 1 Oct - 30 Sep',
verbose_name=_('Liquidation')
)
total_ct_ytd = models.DecimalField(
decimal_places=2, max_digits=20, blank=True, null=True,
help_text='Cash Transfers Jan - Dec',
verbose_name=_('Cash Transfer Jan - Dec')
)
outstanding_dct_amount_6_to_9_months_usd = models.DecimalField(
decimal_places=2, max_digits=20, blank=True, null=True,
help_text='Outstanding DCT 6/9 months',
verbose_name=_('Outstanding DCT 6/9 months')
)
outstanding_dct_amount_more_than_9_months_usd = models.DecimalField(
decimal_places=2, max_digits=20, blank=True, null=True,
help_text='Outstanding DCT more than 9 months',
verbose_name=_('Outstanding DCT more than 9 months')
)
hact_values = models.JSONField(blank=True, null=True, default=hact_default, verbose_name='HACT', encoder=CustomJSONEncoder)
basis_for_risk_rating = models.CharField(
verbose_name=_("Basis for Risk Rating"), max_length=50, default='', blank=True)
psea_assessment_date = models.DateTimeField(
verbose_name=_("Last PSEA Assess. Date"),
null=True,
blank=True,
)
sea_risk_rating_name = models.CharField(
max_length=150,
verbose_name=_("PSEA Risk Rating"),
blank=True,
default='',
)
highest_risk_rating_type = models.CharField(
max_length=150,
verbose_name=_("Highest Risk Rating Type"),
blank=True,
default='',
)
highest_risk_rating_name = models.CharField(
max_length=150,
verbose_name=_("Highest Risk Rating Name"),
choices=ALL_COMBINED_RISK_RATING,
blank=True,
default='',
)
lead_office = models.ForeignKey(Office, verbose_name=_("Lead Office"),
blank=True, null=True, on_delete=models.SET_NULL)
lead_section = models.ForeignKey(Section, verbose_name=_("Lead Section"),
blank=True, null=True, on_delete=models.SET_NULL)
tracker = FieldTracker()
objects = PartnerOrganizationManager()
class Meta:
base_manager_name = 'objects'
def __str__(self):
return self.organization.name if self.organization and self.organization.name else self.vendor_number
@cached_property
def name(self):
return self.organization.name if self.organization and self.organization.name else ''
@cached_property
def short_name(self):
return self.organization.short_name if self.organization and self.organization.short_name else ''
@cached_property
def vendor_number(self):
return self.organization.vendor_number if self.organization and self.organization.vendor_number else ''
@cached_property
def partner_type(self):
return self.organization.organization_type
@cached_property
def cso_type(self):
return self.organization.cso_type
@cached_property
def context_realms(self):
return Realm.objects.filter(
organization=self.organization,
country=connection.tenant,
group__name__in=PARTNER_ACTIVE_GROUPS,
)
@cached_property
def all_staff_members(self):
user_qs = User.objects \
.base_qs() \
.select_related('profile') \
.filter(realms__in=self.context_realms)
return user_qs\
.annotate(has_active_realm=Exists(self.context_realms.filter(user=OuterRef('pk'), is_active=True)))\
.distinct()
@cached_property
def active_staff_members(self):
return self.all_staff_members\
.filter(is_active=True, has_active_realm=True)\
.distinct()
def get_object_url(self):
return reverse("partners_api:partner-detail", args=[self.pk])
def latest_assessment(self, type):
return self.assessments.filter(type=type).order_by('completed_date').last()
@cached_property
def partner_type_slug(self):
slugs = {
OrganizationType.BILATERAL_MULTILATERAL: 'Multi',
OrganizationType.CIVIL_SOCIETY_ORGANIZATION: 'CSO',
OrganizationType.GOVERNMENT: 'Gov',
OrganizationType.UN_AGENCY: 'UN',
}
return slugs.get(self.partner_type, self.partner_type)
@cached_property
def get_last_pca(self):
# exclude Agreements that were not signed
return self.agreements.filter(
agreement_type=Agreement.PCA
).exclude(
signed_by_unicef_date__isnull=True,
signed_by_partner_date__isnull=True,
status__in=[Agreement.DRAFT, Agreement.TERMINATED]
).order_by('signed_by_unicef_date').last()
@cached_property
def expiring_assessment_flag(self):
if self.last_assessment_date:
last_assessment_age = datetime.date.today().year - self.last_assessment_date.year
return last_assessment_age >= PartnerOrganization.EXPIRING_ASSESSMENT_LIMIT_YEAR
return False
@cached_property
def expiring_psea_assessment_flag(self):
if self.psea_assessment_date:
psea_assessment_age = datetime.date.today().year - self.psea_assessment_date.year
return psea_assessment_age >= PartnerOrganization.EXPIRING_ASSESSMENT_LIMIT_YEAR
return False
@cached_property
def approaching_threshold_flag(self):
total_ct_ytd = self.total_ct_ytd or 0
not_required = self.highest_risk_rating_name == PartnerOrganization.RATING_NOT_REQUIRED
ct_year_overflow = total_ct_ytd > PartnerOrganization.CT_CP_AUDIT_TRIGGER_LEVEL
return not_required and ct_year_overflow
@cached_property
def flags(self):
return {
'expiring_assessment_flag': self.expiring_assessment_flag,
'approaching_threshold_flag': self.approaching_threshold_flag,
'expiring_psea_assessment_flag': self.expiring_psea_assessment_flag,
}
@cached_property
def min_req_programme_visits(self):
programme_visits = 0
if self.partner_type not in [OrganizationType.BILATERAL_MULTILATERAL, OrganizationType.UN_AGENCY]:
ct = self.net_ct_cy or 0 # Must be integer, but net_ct_cy could be None
if ct <= PartnerOrganization.CT_MR_AUDIT_TRIGGER_LEVEL:
programme_visits = 0
elif PartnerOrganization.CT_MR_AUDIT_TRIGGER_LEVEL < ct <= PartnerOrganization.CT_MR_AUDIT_TRIGGER_LEVEL2:
programme_visits = 1
elif PartnerOrganization.CT_MR_AUDIT_TRIGGER_LEVEL2 < ct <= PartnerOrganization.CT_MR_AUDIT_TRIGGER_LEVEL3:
if self.highest_risk_rating_name in [PartnerOrganization.RATING_HIGH,
PartnerOrganization.PSEA_RATING_HIGH,
PartnerOrganization.RATING_HIGH_RISK_ASSUMED,
PartnerOrganization.RATING_SIGNIFICANT]:
programme_visits = 3
elif self.highest_risk_rating_name in [PartnerOrganization.RATING_MEDIUM,
PartnerOrganization.PSEA_RATING_MEDIUM]:
programme_visits = 2
elif self.highest_risk_rating_name in [PartnerOrganization.RATING_LOW,
PartnerOrganization.RATING_LOW_RISK_ASSUMED,
PartnerOrganization.PSEA_RATING_LOW]:
programme_visits = 1
else:
if self.highest_risk_rating_name in [PartnerOrganization.RATING_HIGH,
PartnerOrganization.PSEA_RATING_HIGH,
PartnerOrganization.RATING_HIGH_RISK_ASSUMED,
PartnerOrganization.RATING_SIGNIFICANT]:
programme_visits = 4
elif self.highest_risk_rating_name in [PartnerOrganization.RATING_MEDIUM,
PartnerOrganization.PSEA_RATING_MEDIUM]:
programme_visits = 3
elif self.highest_risk_rating_name in [PartnerOrganization.RATING_LOW,
PartnerOrganization.RATING_LOW_RISK_ASSUMED,
PartnerOrganization.PSEA_RATING_LOW]:
programme_visits = 2
return programme_visits
@cached_property
def min_req_spot_checks(self):
# reported_cy can be None
reported_cy = self.reported_cy or 0
if self.partner_type in [OrganizationType.BILATERAL_MULTILATERAL, OrganizationType.UN_AGENCY]:
return 0
if self.type_of_assessment == 'Low Risk Assumed' or reported_cy <= PartnerOrganization.CT_CP_AUDIT_TRIGGER_LEVEL:
return 0
try:
self.planned_engagement
except PlannedEngagement.DoesNotExist:
pass
else:
if self.planned_engagement.scheduled_audit:
return 0
return 1
@cached_property
def min_req_audits(self):
if self.partner_type in [OrganizationType.BILATERAL_MULTILATERAL, OrganizationType.UN_AGENCY]:
return 0
return self.planned_engagement.required_audit if getattr(self, 'planned_engagement', None) else 0
@cached_property
def hact_min_requirements(self):
return {
'programmatic_visits': self.min_req_programme_visits,
'spot_checks': self.min_req_spot_checks,
'audits': self.min_req_audits,
}
@cached_property
def assurance_coverage(self):
pv = self.hact_values['programmatic_visits']['completed']['total']
sc = self.hact_values['spot_checks']['completed']['total']
au = self.hact_values['audits']['completed']
if (pv >= self.min_req_programme_visits) & (sc >= self.min_req_spot_checks) & (au >= self.min_req_audits):
return PartnerOrganization.ASSURANCE_COMPLETE
elif pv + sc + au == 0:
return PartnerOrganization.ASSURANCE_VOID
else:
return PartnerOrganization.ASSURANCE_PARTIAL
@cached_property
def current_core_value_assessment(self):
return self.core_values_assessments.filter(archived=False).first()
def update_planned_visits_to_hact(self):
"""For current year sum all programmatic values of planned visits records for partner"""
year = datetime.date.today().year
if self.partner_type != 'Government':
pv = InterventionPlannedVisits.objects.filter(
intervention__agreement__partner=self,
year=year,
).exclude(
intervention__status__in=[
Intervention.DRAFT,
Intervention.CANCELLED,
],
)
pvq1 = pv.aggregate(models.Sum('programmatic_q1'))['programmatic_q1__sum'] or 0
pvq2 = pv.aggregate(models.Sum('programmatic_q2'))['programmatic_q2__sum'] or 0
pvq3 = pv.aggregate(models.Sum('programmatic_q3'))['programmatic_q3__sum'] or 0
pvq4 = pv.aggregate(models.Sum('programmatic_q4'))['programmatic_q4__sum'] or 0
else:
try:
pv = self.planned_visits.get(year=year)
pvq1 = pv.programmatic_q1
pvq2 = pv.programmatic_q2
pvq3 = pv.programmatic_q3
pvq4 = pv.programmatic_q4
except PartnerPlannedVisits.DoesNotExist:
pvq1 = pvq2 = pvq3 = pvq4 = 0
self.hact_values['programmatic_visits']['planned']['q1'] = pvq1
self.hact_values['programmatic_visits']['planned']['q2'] = pvq2
self.hact_values['programmatic_visits']['planned']['q3'] = pvq3
self.hact_values['programmatic_visits']['planned']['q4'] = pvq4
self.hact_values['programmatic_visits']['planned']['total'] = pvq1 + pvq2 + pvq3 + pvq4
self.save()
@cached_property
def programmatic_visits(self):
# Avoid circular imports
from etools.applications.field_monitoring.planning.models import MonitoringActivity, MonitoringActivityGroup
pv_year = Travel.objects.filter(
activities__travel_type=TravelType.PROGRAMME_MONITORING,
traveler=F('activities__primary_traveler'),
status=Travel.COMPLETED,
end_date__year=timezone.now().year,
activities__partner=self
)
tpmv = TPMActivity.objects.filter(is_pv=True, partner=self, tpm_visit__status=TPMVisit.UNICEF_APPROVED,
date__year=datetime.datetime.now().year)
fmvgs = MonitoringActivityGroup.objects.filter(
partner=self,
monitoring_activities__status="completed",
).annotate(
end_date=Max('monitoring_activities__end_date'),
).filter(
end_date__year=datetime.datetime.now().year
).distinct()
# field monitoring activities qualify as programmatic visits if during a monitoring activity the hact
# question was answered with an overall rating and the visit is completed
grouped_activities = MonitoringActivityGroup.objects.filter(
partner=self
).values_list('monitoring_activities__id', flat=True)
fmvqs = MonitoringActivity.objects.filter(
end_date__year=datetime.datetime.now().year,
).filter_hact_for_partner(self.id).exclude(
id__in=grouped_activities,
)
return {
't2f': pv_year,
'tpm': tpmv,
'fm_group': fmvgs,
'fm': fmvqs
}
def update_programmatic_visits(self, event_date=None, update_one=False):
"""
:return: all completed programmatic visits
"""
pv = self.hact_values['programmatic_visits']['completed']['total']
if update_one and event_date:
quarter_name = get_quarter(event_date)
pvq = self.hact_values['programmatic_visits']['completed'][quarter_name]
pv += 1
pvq += 1
self.hact_values['programmatic_visits']['completed'][quarter_name] = pvq
self.hact_values['programmatic_visits']['completed']['total'] = pv
else:
pv_year = self.programmatic_visits['t2f']
pv = pv_year.count()
pvq1 = pv_year.filter(end_date__quarter=1).count()
pvq2 = pv_year.filter(end_date__quarter=2).count()
pvq3 = pv_year.filter(end_date__quarter=3).count()
pvq4 = pv_year.filter(end_date__quarter=4).count()
tpmv = self.programmatic_visits['tpm']
tpmv1 = tpmv.filter(date__quarter=1).count()
tpmv2 = tpmv.filter(date__quarter=2).count()
tpmv3 = tpmv.filter(date__quarter=3).count()
tpmv4 = tpmv.filter(date__quarter=4).count()
tpm_total = tpmv1 + tpmv2 + tpmv3 + tpmv4
fmvgs = self.programmatic_visits['fm_group']
fmgv1 = fmvgs.filter(end_date__quarter=1).count()
fmgv2 = fmvgs.filter(end_date__quarter=2).count()
fmgv3 = fmvgs.filter(end_date__quarter=3).count()
fmgv4 = fmvgs.filter(end_date__quarter=4).count()
fmgv_total = fmgv1 + fmgv2 + fmgv3 + fmgv4
fmvqs = self.programmatic_visits['fm']
fmvq1 = fmvqs.filter(end_date__quarter=1).count()
fmvq2 = fmvqs.filter(end_date__quarter=2).count()
fmvq3 = fmvqs.filter(end_date__quarter=3).count()
fmvq4 = fmvqs.filter(end_date__quarter=4).count()
fmv_total = fmvq1 + fmvq2 + fmvq3 + fmvq4
self.hact_values['programmatic_visits']['completed']['q1'] = pvq1 + tpmv1 + fmgv1 + fmvq1
self.hact_values['programmatic_visits']['completed']['q2'] = pvq2 + tpmv2 + fmgv2 + fmvq2
self.hact_values['programmatic_visits']['completed']['q3'] = pvq3 + tpmv3 + fmgv3 + fmvq3
self.hact_values['programmatic_visits']['completed']['q4'] = pvq4 + tpmv4 + fmgv4 + fmvq4
self.hact_values['programmatic_visits']['completed']['total'] = pv + tpm_total + fmgv_total + fmv_total
self.save()
@cached_property
def spot_checks(self):
from etools.applications.audit.models import Engagement, SpotCheck
return SpotCheck.objects.filter(
partner=self, date_of_draft_report_to_ip__year=datetime.datetime.now().year
).exclude(status=Engagement.CANCELLED)
def update_spot_checks(self, event_date=None, update_one=False):
"""
:return: all completed spot checks
"""
if not event_date:
event_date = datetime.datetime.today()
if update_one:
quarter_name = get_quarter(event_date)
self.hact_values['spot_checks']['completed']['total'] += 1
self.hact_values['spot_checks']['completed'][quarter_name] += 1
else:
audit_spot_check = self.spot_checks
asc1 = audit_spot_check.filter(date_of_draft_report_to_ip__quarter=1).count()
asc2 = audit_spot_check.filter(date_of_draft_report_to_ip__quarter=2).count()
asc3 = audit_spot_check.filter(date_of_draft_report_to_ip__quarter=3).count()
asc4 = audit_spot_check.filter(date_of_draft_report_to_ip__quarter=4).count()
self.hact_values['spot_checks']['completed']['q1'] = asc1
self.hact_values['spot_checks']['completed']['q2'] = asc2
self.hact_values['spot_checks']['completed']['q3'] = asc3
self.hact_values['spot_checks']['completed']['q4'] = asc4
self.hact_values['spot_checks']['completed']['total'] = audit_spot_check.count() # TODO 1.1.9c add spot checks from field monitoring
self.save(update_fields=['hact_values'])
@cached_property
def audits_completed(self):
from etools.applications.audit.models import Audit, Engagement, SpecialAudit
audits = Audit.objects.filter(
partner=self,
year_of_audit=datetime.datetime.now().year,
date_of_draft_report_to_ip__isnull=False,
).exclude(status=Engagement.CANCELLED)
s_audits = SpecialAudit.objects.filter(
partner=self,
year_of_audit=datetime.datetime.now().year,
date_of_draft_report_to_ip__isnull=False,
).exclude(status=Engagement.CANCELLED)
return audits, s_audits
def update_audits_completed(self, update_one=False):
"""
:param partner: Partner Organization
:param update_one: if True will increase by one the value, if False would recalculate the value
:return: all completed audit (including special audit)
"""
audits, s_audits = self.audits_completed
completed_audit = self.hact_values['audits']['completed']
if update_one:
completed_audit += 1
else:
completed_audit = audits.count() + s_audits.count()
self.hact_values['audits']['completed'] = completed_audit
self.save()
def update_hact_support(self):
audits, _ = self.audits_completed
self.hact_values['outstanding_findings'] = sum([
audit.pending_unsupported_amount for audit in audits if audit.pending_unsupported_amount])
self.hact_values['assurance_coverage'] = self.assurance_coverage
self.save()
def update_min_requirements(self):
updated = []
for hact_eng in ['programmatic_visits', 'spot_checks', 'audits']:
if self.hact_values[hact_eng]['minimum_requirements'] != self.hact_min_requirements[hact_eng]:
self.hact_values[hact_eng]['minimum_requirements'] = self.hact_min_requirements[hact_eng]
updated.append(hact_eng)
if updated:
self.save()
return updated
def get_admin_url(self):
admin_url_name = 'admin:partners_partnerorganization_change'
return reverse(admin_url_name, args=(self.id,))
def user_is_staff_member(self, user):
return user.id in self.active_staff_members.values_list('id', flat=True)
class CoreValuesAssessment(TimeStampedModel):
partner = models.ForeignKey(PartnerOrganization, verbose_name=_("Partner"), related_name='core_values_assessments',
on_delete=models.CASCADE)
date = models.DateField(verbose_name=_('Date positively assessed against core values'), blank=True, null=True)
assessment = models.FileField(verbose_name=_("Core Values Assessment"), blank=True, null=True,
upload_to='partners/core_values/', max_length=1024,
help_text='Only required for CSO partners')
attachment = CodedGenericRelation(Attachment, verbose_name=_('Core Values Assessment'), blank=True, null=True,
code='partners_partner_assessment', help_text='Only required for CSO partners')
archived = models.BooleanField(default=False)
class PartnerStaffMemberManager(models.Manager):
def get_queryset(self):
return super().get_queryset().select_related('partner')
class PlannedEngagement(TimeStampedModel):
""" class to handle partner's engagement for current year """
partner = models.OneToOneField(PartnerOrganization, verbose_name=_("Partner"), related_name='planned_engagement',
on_delete=models.CASCADE)
spot_check_follow_up = models.IntegerField(verbose_name=_("Spot Check Follow Up Required"), default=0)
spot_check_planned_q1 = models.IntegerField(verbose_name=_("Spot Check Q1"), default=0)
spot_check_planned_q2 = models.IntegerField(verbose_name=_("Spot Check Q2"), default=0)
spot_check_planned_q3 = models.IntegerField(verbose_name=_("Spot Check Q3"), default=0)
spot_check_planned_q4 = models.IntegerField(verbose_name=_("Spot Check Q4"), default=0)
scheduled_audit = models.BooleanField(verbose_name=_("Scheduled Audit"), default=False)
special_audit = models.BooleanField(verbose_name=_("Special Audit"), default=False)
@cached_property
def total_spot_check_planned(self):
return sum([
self.spot_check_planned_q1, self.spot_check_planned_q2,
self.spot_check_planned_q3, self.spot_check_planned_q4
])
@cached_property
def spot_check_required(self):
completed_audit = self.partner.hact_values['audits']['completed']
required = self.spot_check_follow_up + self.partner.min_req_spot_checks - completed_audit
return max(0, required)
@cached_property
def required_audit(self):
return sum([self.scheduled_audit, self.special_audit])
def reset(self):
"""this is used to reset the values of the object at the end of the year"""
self.spot_check_follow_up = 0
self.spot_check_planned_q1 = 0
self.spot_check_planned_q2 = 0
self.spot_check_planned_q3 = 0