-
Notifications
You must be signed in to change notification settings - Fork 5
/
models.py
2485 lines (2013 loc) · 109 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 uuid
from datetime import datetime, timedelta
import pytz
import reversion
from django.conf import settings
from django.contrib.auth.signals import (
user_logged_in,
user_logged_out,
user_login_failed,
)
# from django.db import models
from django.contrib.gis.db import models
from django.contrib.postgres.fields import ArrayField
from django.core.validators import FileExtensionValidator, RegexValidator, validate_slug
from django.db.models import Q
# from django.db.models import Prefetch
from django.dispatch import receiver
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from tinymce.models import HTMLField
from main.fields import SecureFileField
from .utils import validate_slug_number # is_user_ifrc,
# Write model properties to dictionary
def to_dict(instance):
opts = instance._meta
data = {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, models.ManyToManyField):
if instance.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(instance).values())
else:
data[f.name] = f.value_from_object(instance)
return data
class DisasterType(models.Model):
"""summary of disaster"""
name = models.CharField(verbose_name=_("name"), max_length=100)
summary = models.TextField(verbose_name=_("summary"))
class Meta:
ordering = ("name",)
verbose_name = _("disaster type")
verbose_name_plural = _("disaster types")
def __str__(self):
return self.name
class RegionName(models.IntegerChoices):
AFRICA = 0, _("Africa")
AMERICAS = 1, _("Americas")
ASIA_PACIFIC = 2, _("Asia Pacific")
EUROPE = 3, _("Europe")
MENA = 4, _("Middle East & North Africa")
class Region(models.Model):
"""A region"""
name = models.IntegerField(choices=RegionName.choices, default=0, verbose_name=_("name"))
bbox = models.PolygonField(srid=4326, blank=True, null=True)
label = models.CharField(verbose_name=_("name of the region"), max_length=250, blank=True)
additional_tab_name = models.CharField(verbose_name="Label for Additional Tab", max_length=100, blank=True)
def indexing(self):
return {
"id": self.id,
"event_id": None,
"type": "region",
"name": self.label,
"keyword": None,
"visibility": None,
"ns": None,
"body": self.label,
"date": None,
}
def es_id(self):
return "region-%s" % self.id
def get_national_society_count(self):
return (
Country.objects.filter(region=self, record_type=CountryType.COUNTRY, independent=True)
.exclude(society_name_en="")
.count()
)
def get_country_cluster_count(self):
return Country.objects.filter(region=self, record_type=CountryType.CLUSTER).count()
class Meta:
ordering = ("name",)
verbose_name = _("region")
verbose_name_plural = _("regions")
def __str__(self):
return self.label
def region_name(self):
return self.get_name_display()
def logo_document_path(instance, filename):
return "logos/%s/%s" % (instance.iso, filename)
class CountryType(models.IntegerChoices):
"""
We use the Country model for some things that are not "Countries". This helps classify the type.
"""
COUNTRY = 1, _("Country")
CLUSTER = 2, _("Cluster")
REGION = 3, _("Region")
COUNTRY_OFFICE = 4, _("Country Office")
REPRESENTATIVE_OFFICE = 5, _("Representative Office")
# select name, society_name, record_type from api_country where name like '%luster%';
# select name, society_name, record_type from api_country where name like '%egion%';
# select name, society_name, record_type from api_country where name like '%ffice%'; -- no result
# update api_country set record_type=2 where name like '%luster%';
# update api_country set record_type=3 where name like '%egion%';
@reversion.register()
class Country(models.Model):
"""A country"""
name = models.CharField(verbose_name=_("name"), max_length=100)
record_type = models.IntegerField(
choices=CountryType.choices, verbose_name=_("type"), default=1, help_text=_("Type of entity")
)
iso = models.CharField(
verbose_name=_("ISO"),
max_length=2,
null=True,
blank=True,
unique=True,
validators=[RegexValidator("^[A-Z]*$", "ISO must be uppercase")],
)
iso3 = models.CharField(
verbose_name=_("ISO3"),
max_length=3,
null=True,
blank=True,
unique=True,
validators=[RegexValidator("^[A-Z]*$", "ISO must be uppercase")],
)
fdrs = models.CharField(verbose_name=_("FDRS"), max_length=6, null=True, blank=True)
society_name = models.TextField(verbose_name=_("society name"), blank=True)
society_url = models.URLField(blank=True, verbose_name=_("URL - Society"))
url_ifrc = models.URLField(blank=True, verbose_name=_("URL - IFRC"))
region = models.ForeignKey(Region, verbose_name=_("region"), null=True, blank=True, on_delete=models.SET_NULL)
overview = models.TextField(verbose_name=_("overview"), blank=True, null=True)
key_priorities = models.TextField(verbose_name=_("key priorities"), blank=True, null=True)
inform_score = models.DecimalField(verbose_name=_("inform score"), blank=True, null=True, decimal_places=2, max_digits=3)
logo = models.FileField(
blank=True,
null=True,
verbose_name=_("logo"),
upload_to=logo_document_path,
validators=[FileExtensionValidator(allowed_extensions=["png", "jpg", "gif"])],
)
centroid = models.PointField(srid=4326, blank=True, null=True)
bbox = models.PolygonField(srid=4326, blank=True, null=True)
independent = models.BooleanField(default=None, null=True, help_text=_("Is this an independent country?"))
is_deprecated = models.BooleanField(default=False, help_text=_("Is this an active, valid country?"))
sovereign_state = models.ForeignKey(
"self",
verbose_name=_("Country ID of the Sovereign State"),
null=True,
blank=True,
default=None,
on_delete=models.SET_NULL,
)
disputed = models.BooleanField(help_text=_("Is this country disputed?"), default=False)
# Population Data From WB API
wb_population = models.PositiveIntegerField(
verbose_name=_("WB population"), null=True, blank=True, help_text=_("population data from WB API")
)
wb_year = models.CharField(
verbose_name=_("WB Year"), max_length=4, null=True, blank=True, help_text=_("population data year from WB API")
)
additional_tab_name = models.CharField(verbose_name=_("Label for Additional Tab"), max_length=100, blank=True)
# Additional NS Indicator fields
nsi_income = models.IntegerField(verbose_name=_("Income (CHF)"), blank=True, null=True)
nsi_expenditures = models.IntegerField(verbose_name=_("Expenditures (CHF)"), blank=True, null=True)
nsi_branches = models.IntegerField(verbose_name=_("Branches"), blank=True, null=True)
nsi_staff = models.IntegerField(verbose_name=_("Staff"), blank=True, null=True)
nsi_volunteers = models.IntegerField(verbose_name=_("Volunteers"), blank=True, null=True)
nsi_youth = models.IntegerField(verbose_name=_("Youth - 6-19 Yrs"), blank=True, null=True)
nsi_trained_in_first_aid = models.IntegerField(verbose_name=_("Trained in First Aid"), blank=True, null=True)
nsi_gov_financial_support = models.BooleanField(verbose_name=_("Gov Financial Support"), blank=True, null=True)
nsi_domestically_generated_income = models.BooleanField(
verbose_name=_(">50% Domestically Generated Income"), blank=True, null=True
)
nsi_annual_fdrs_reporting = models.BooleanField(verbose_name=_("Annual Reporting to FDRS"), blank=True, null=True)
nsi_policy_implementation = models.BooleanField(
verbose_name=_("Your Policy / Programme Implementation"), blank=True, null=True
)
nsi_risk_management_framework = models.BooleanField(verbose_name=_("Risk Management Framework"), blank=True, null=True)
nsi_cmc_dashboard_compliance = models.BooleanField(verbose_name=_("Complying with CMC Dashboard"), blank=True, null=True)
# WASH Capacity Indicators
wash_total_staff = models.IntegerField(verbose_name=_("Total WASH Staff"), null=True, blank=True)
wash_kit2 = models.IntegerField(verbose_name=_("WASH Kit2"), null=True, blank=True)
wash_kit5 = models.IntegerField(verbose_name=_("WASH Kit5"), null=True, blank=True)
wash_kit10 = models.IntegerField(verbose_name=_("WASH Kit10"), null=True, blank=True)
wash_staff_at_hq = models.IntegerField(verbose_name=_("WASH Staff at HQ"), null=True, blank=True)
wash_staff_at_branch = models.IntegerField(verbose_name=_("WASH Staff at Branch"), null=True, blank=True)
wash_ndrt_trained = models.IntegerField(verbose_name=_("NDRT Trained"), null=True, blank=True)
wash_rdrt_trained = models.IntegerField(verbose_name=_("RDRT Trained"), null=True, blank=True)
in_search = models.BooleanField(verbose_name=_("Include in Search"), default=True)
# Used in Emergency Project
average_household_size = models.DecimalField(
verbose_name=_("Average Household Size"), null=True, blank=True, max_digits=5, decimal_places=2
)
address_1 = models.CharField(verbose_name=_("Address 1"), null=True, blank=True, max_length=255)
address_2 = models.CharField(verbose_name=_("Address 2"), null=True, blank=True, max_length=255)
city_code = models.CharField(verbose_name=_("City Code"), null=True, blank=True, max_length=255)
phone = models.CharField(verbose_name=_("Phone"), null=True, blank=True, max_length=255)
website = models.CharField(verbose_name=_("Website"), null=True, blank=True, max_length=255)
emails = ArrayField(
models.CharField(
verbose_name=_("Email"),
null=True,
blank=True,
max_length=255,
),
default=list,
null=True,
blank=True,
)
founded_date = models.DateField(verbose_name=_("Found date"), null=True, blank=True)
# disaster law url
disaster_law_url = models.CharField(verbose_name=_("Disaster law url"), null=True, blank=True, max_length=255)
def indexing(self):
return {
"id": self.id,
"event_id": None,
"type": "country",
"name": self.name,
"keyword": None,
"visibility": None,
"ns": None,
"body": "%s %s"
% (
self.name,
self.society_name,
),
"date": None,
}
def es_id(self):
return "country-%s" % self.id
class Meta:
ordering = ("name",)
verbose_name = _("country")
verbose_name_plural = _("countries")
def __str__(self):
return self.name
class District(models.Model):
"""Admin level 1 field"""
name = models.CharField(verbose_name=_("name"), max_length=100)
code = models.CharField(verbose_name=_("code"), max_length=10)
country = models.ForeignKey(Country, verbose_name=_("country"), null=True, on_delete=models.SET_NULL)
is_enclave = models.BooleanField(
verbose_name=_("is enclave?"), default=False, help_text=_("Is it an enclave away from parent country?")
) # used to mark if the district is far away from the country
centroid = models.PointField(srid=4326, blank=True, null=True)
bbox = models.PolygonField(srid=4326, blank=True, null=True)
is_deprecated = models.BooleanField(default=False, help_text=_("Is this an active, valid district?"))
# Population Data From WB API
wb_population = models.PositiveIntegerField(
verbose_name=_("WB population"), null=True, blank=True, help_text=_("population data from WB API")
)
wb_year = models.CharField(
verbose_name=_("WB year"), max_length=4, null=True, blank=True, help_text=_("population data year from WB API")
)
nuts1 = models.CharField(
verbose_name=_("nuts1"),
max_length=3,
blank=True,
null=True,
help_text=_("Nomenclature of Territorial Units for Statistics 1"),
)
nuts2 = models.CharField(
verbose_name=_("nuts2"),
max_length=4,
blank=True,
null=True,
help_text=_("Nomenclature of Territorial Units for Statistics 2"),
)
nuts3 = models.CharField(
verbose_name=_("nuts3"),
max_length=5,
blank=True,
null=True,
help_text=_("Nomenclature of Territorial Units for Statistics 3"),
)
emma_id = models.CharField(verbose_name=_("emma_id"), max_length=10, blank=True, null=True, help_text=_("Meteoalarm EMMA_ID"))
fips_code = models.PositiveIntegerField(verbose_name=_("fips_code"), blank=True, null=True, help_text=_("USA FIPS Code"))
class Meta:
ordering = ("code",)
verbose_name = _("district")
verbose_name_plural = _("districts")
def __str__(self):
country_name = self.country.name if self.country else ""
suffix = " ⚡" if self.is_deprecated else ""
return f"{country_name} - {self.name}{suffix}"
class CountryDirectory(models.Model):
country = models.ForeignKey(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
first_name = models.CharField(verbose_name=_("First Name"), max_length=255, null=True, blank=True)
last_name = models.CharField(verbose_name=_("Last Name"), max_length=255, null=True, blank=True)
position = models.CharField(verbose_name=_("Position"), max_length=255, null=True, blank=True)
class Meta:
unique_together = ("country", "first_name", "last_name", "position")
def __str__(self):
return f"{self.country.name} - {self.first_name}"
class CountrySupportingPartner(models.Model):
class SupportingPartnerType(models.IntegerChoices):
IFRC = 0, _("Ifrc")
INTERNATIONAL_PARTNERS = 1, _("International Partners")
country = models.ForeignKey(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
first_name = models.CharField(verbose_name=_("First Name"), max_length=255, null=True, blank=True)
last_name = models.CharField(verbose_name=_("Last Name"), max_length=255, null=True, blank=True)
position = models.CharField(verbose_name=_("Position"), max_length=255, null=True, blank=True)
email = models.CharField(verbose_name=_("Email"), max_length=255, null=True, blank=True)
supporting_type = models.IntegerField(
choices=SupportingPartnerType.choices, verbose_name=_("Supporting Type"), null=True, blank=True
)
def __str__(self):
return f"{self.country.name} - {self.first_name} - {self.last_name}"
class CountryKeyDocument(models.Model):
country = models.ForeignKey(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
name = models.CharField(
verbose_name=_("Name"),
max_length=255,
)
url = models.CharField(verbose_name=_("Url"), max_length=255)
thumbnail = models.CharField(verbose_name=_("Thumbnail"), max_length=255)
document_type = models.CharField(verbose_name=_("Document Type"), max_length=255)
year = models.DateField(verbose_name=_("Year"))
end_year = models.DateField(verbose_name=_("End Year"), null=True, blank=True)
year_text = models.CharField(verbose_name=_("Year Text"), max_length=255, null=True, blank=True)
class Meta:
unique_together = ("country", "url")
def __str__(self):
return f"{self.country.name} - {self.name}"
class CountryCapacityStrengthening(models.Model):
class AssessmentType(models.IntegerChoices):
OCAC = 0, _("Ocac")
BOCA = 1, _("Boca")
country = models.ForeignKey(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
assessment_code = models.CharField(verbose_name=_("Assessment Code"), max_length=255)
year = models.CharField(verbose_name=_("Year of Assessment"), max_length=25)
submission_date = models.DateTimeField(verbose_name=_("Submission Date"))
url = models.CharField(
verbose_name=_("Url"),
max_length=255,
)
assessment_type = models.IntegerField(verbose_name=_("Country Assessment Type"), choices=AssessmentType.choices)
branch_name = models.CharField(verbose_name=_("Branch Name"), max_length=255, null=True, blank=True)
class Meta:
unique_together = ("assessment_type", "assessment_code")
def __str__(self):
return f"{self.country.name} - {self.assessment_code} - {self.year}"
class CountryOrganizationalCapacity(models.Model):
country = models.OneToOneField(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
leadership_capacity = models.TextField(verbose_name=_("Leadership Capacity"), null=True, blank=True)
youth_capacity = models.TextField(verbose_name=_("Youth Capacity"), null=True, blank=True)
volunteer_capacity = models.TextField(verbose_name=_("Volunteer Capacity"), null=True, blank=True)
financial_capacity = models.TextField(verbose_name=_("Financial Capacity"), null=True, blank=True)
class NSDInitiatives(models.Model):
country = models.ForeignKey(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
title = models.CharField(verbose_name=_("Title"), max_length=255)
fund_type = models.CharField(verbose_name=_("Fund Type"), max_length=255)
allocation = models.IntegerField(verbose_name=_("Allocation in CHF"))
year = models.CharField(verbose_name=_("Year"), max_length=20)
funding_period = models.IntegerField(verbose_name=_("Funding Period in Month"))
categories = ArrayField(models.CharField(max_length=255), verbose_name=_("Funding categories"), default=list, null=True)
class Meta:
unique_together = ("country", "year", "fund_type")
def __str__(self):
return f"{self.country.name} - {self.title}"
class CountryICRCPresence(models.Model):
country = models.OneToOneField(Country, verbose_name=_("Country"), on_delete=models.CASCADE)
icrc_presence = models.BooleanField(verbose_name=_("ICRC Presence"), null=True, blank=True)
url = models.CharField(verbose_name=_("Url"), null=True, blank=True, max_length=255)
key_operation = models.BooleanField(verbose_name=_("Key Operations"), null=True, blank=True)
description = models.TextField(verbose_name=_("Description"), null=True, blank=True)
def __str__(self):
return f"{self.country.name} - {self.url}"
class Admin2(models.Model):
"""Used for admin2, District refers to admin1"""
admin1 = models.ForeignKey(District, verbose_name=_("Admin 1"), on_delete=models.PROTECT)
name = models.CharField(verbose_name=_("name"), max_length=100)
code = models.CharField(verbose_name=_("code"), max_length=64, unique=True)
centroid = models.PointField(srid=4326, blank=True, null=True)
bbox = models.PolygonField(srid=4326, blank=True, null=True)
local_name = models.CharField(verbose_name=_("Local Name"), max_length=100, blank=True, null=True)
local_name_code = models.CharField(verbose_name=_("Local Name Language Code"), max_length=10, blank=True, null=True)
alternate_name = models.CharField(verbose_name=_("Alternate Name"), max_length=100, blank=True, null=True)
alternate_name_code = models.CharField(verbose_name=_("Alternate Name Language Code"), max_length=10, blank=True, null=True)
is_deprecated = models.BooleanField(default=False, help_text=_("Is this a deprecated area?"))
created_at = models.DateTimeField(verbose_name=_("Created at"), auto_now_add=True)
class Meta:
verbose_name = _("admin2")
verbose_name_plural = _("admin2s")
ordering = ("code",)
def __str__(self):
return f"{self.admin1} - {self.name}"
class CountryGeoms(models.Model):
"""Admin0 geometries"""
geom = models.MultiPolygonField(srid=4326, blank=True, null=True)
country = models.OneToOneField(Country, verbose_name=_("country"), on_delete=models.DO_NOTHING, primary_key=True)
class DistrictGeoms(models.Model):
"""Admin1 geometries"""
geom = models.MultiPolygonField(srid=4326, blank=True, null=True)
district = models.OneToOneField(District, verbose_name=_("district"), on_delete=models.DO_NOTHING, primary_key=True)
class Admin2Geoms(models.Model):
"""Admin2 geometries"""
geom = models.GeometryField(srid=4326, blank=True, null=True)
admin2 = models.OneToOneField(Admin2, verbose_name=_("admin2"), on_delete=models.DO_NOTHING, primary_key=True)
class VisibilityChoices(models.IntegerChoices):
MEMBERSHIP = 1, _("RCRC Movement")
IFRC = 2, _("IFRC Secretariat")
PUBLIC = 3, _("Public")
IFRC_NS = 4, _("IFRC and NS")
class VisibilityCharChoices(models.TextChoices):
"""Same as VisibilityChoices but using char instead of Enum"""
MEMBERSHIP = "logged_in_user", _("RCRC Movement")
IFRC = "ifrc_only", _("IFRC Secretariat")
PUBLIC = "public", _("Public")
IFRC_NS = "ifrc_ns", _("IFRC and NS")
# Common parent class for key figures.
# Country/region variants inherit from this.
@reversion.register()
class AdminKeyFigure(models.Model):
figure = models.CharField(verbose_name=_("figure"), max_length=100)
deck = models.CharField(verbose_name=_("deck"), max_length=50)
source = models.CharField(verbose_name=_("source"), max_length=256)
visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_("visibility"), default=3)
class Meta:
ordering = ("source",)
verbose_name = _("admin key figure")
verbose_name_plural = _("admin key figures")
def __str__(self):
return self.source
class RegionKeyFigure(AdminKeyFigure):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="key_figures", on_delete=models.CASCADE)
class Meta:
verbose_name = _("region key figure")
verbose_name_plural = _("region key figures")
class CountryKeyFigure(AdminKeyFigure):
country = models.ForeignKey(Country, verbose_name=_("country"), related_name="key_figures", on_delete=models.CASCADE)
class Meta:
verbose_name = _("country key figure")
verbose_name_plural = _("country key figures")
class PositionType(models.IntegerChoices):
TOP = 1, _("Top")
HIGH = 2, _("High")
MIDDLE = 3, _("Middle")
LOW = 4, _("Low")
BOTTOM = 5, _("Bottom")
class TabNumber(models.IntegerChoices):
TAB_1 = 1, _("Tab 1")
TAB_2 = 2, _("Tab 2")
TAB_3 = 3, _("Tab 3")
@reversion.register(follow=("region",))
class RegionSnippet(models.Model):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="snippets", on_delete=models.CASCADE)
snippet = HTMLField(verbose_name=_("snippet"), null=True, blank=True)
image = models.ImageField(verbose_name=_("image"), null=True, blank=True, upload_to="regions/%Y/%m/%d/")
visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_("visibility"), default=3)
position = models.IntegerField(choices=PositionType.choices, verbose_name=_("position"), default=3)
class Meta:
ordering = (
"position",
"id",
)
verbose_name = _("region snippet")
verbose_name_plural = _("region snippets")
def __str__(self):
return (self.snippet[:80] if self.snippet else None) or (
self.image.url if getattr(self, "image", None) and self.image.url else ""
)
@reversion.register(follow=("region",))
class RegionEmergencySnippet(models.Model):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="emergency_snippets", on_delete=models.CASCADE)
title = models.CharField(max_length=255, blank=True)
snippet = HTMLField(verbose_name=_("snippet"), null=True, blank=True)
# visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_('visibility'), default=3)
position = models.IntegerField(choices=PositionType.choices, verbose_name=_("position"), default=3)
class Meta:
ordering = (
"position",
"id",
)
verbose_name = _("region emergencies snippet")
verbose_name_plural = _("region emergencies snippets")
def __str__(self):
return (self.snippet[:80] if self.snippet else None) or self.title or ""
@reversion.register(follow=("region",))
class RegionPreparednessSnippet(models.Model):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="preparedness_snippets", on_delete=models.CASCADE)
title = models.CharField(max_length=255, blank=True)
snippet = HTMLField(verbose_name=_("snippet"), null=True, blank=True)
# visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_('visibility'), default=3)
position = models.IntegerField(choices=PositionType.choices, verbose_name=_("position"), default=3)
class Meta:
ordering = (
"position",
"id",
)
verbose_name = _("region preparedness snippet")
verbose_name_plural = _("region preparedness snippets")
def __str__(self):
return (self.snippet[:80] if self.snippet else None) or self.title or ""
@reversion.register(follow=("region",))
class RegionProfileSnippet(models.Model):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="profile_snippets", on_delete=models.CASCADE)
title = models.CharField(max_length=255, blank=True)
snippet = HTMLField(verbose_name=_("snippet"), null=True, blank=True)
# visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_('visibility'), default=3)
position = models.IntegerField(choices=PositionType.choices, verbose_name=_("position"), default=3)
class Meta:
ordering = (
"position",
"id",
)
verbose_name = _("region profile snippet")
verbose_name_plural = _("region profile snippets")
def __str__(self):
return (self.snippet[:80] if self.snippet else None) or self.title or ""
# class RegionAdditionalLink(models.Model):
# region = models.ForeignKey(Region, related_name='additional_links', on_delete=models.CASCADE)
# title = models.CharField(max_length=255)
# url = models.URLField()
# show_in_go = models.BooleanField(default=False, help_text='Show link contents within GO')
# def __str__(self):
# return self.title
@reversion.register(follow=("country",))
class CountrySnippet(models.Model):
country = models.ForeignKey(Country, verbose_name=_("country"), related_name="snippets", on_delete=models.CASCADE)
snippet = HTMLField(verbose_name=_("snippet"), null=True, blank=True)
image = models.ImageField(verbose_name=_("image"), null=True, blank=True, upload_to="countries/%Y/%m/%d/")
visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_("visibility"), default=3)
position = models.IntegerField(choices=PositionType.choices, verbose_name=_("position"), default=3)
class Meta:
ordering = (
"position",
"id",
)
verbose_name = _("country snippet")
verbose_name_plural = _("country snippets")
def __str__(self):
return (self.snippet[:80] if self.snippet else None) or (
self.image.url if getattr(self, "image", None) and self.image.url else ""
)
@reversion.register()
class AdminLink(models.Model):
title = models.CharField(verbose_name=_("title"), max_length=100)
url = models.URLField(verbose_name=_("url"), max_length=300)
class Meta:
verbose_name = _("admin link")
verbose_name_plural = _("admin links")
class RegionLink(AdminLink):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="links", on_delete=models.CASCADE)
show_in_go = models.BooleanField(default=False, help_text="Show link contents within GO")
class Meta:
verbose_name = _("region link")
verbose_name_plural = _("region links")
class CountryLink(AdminLink):
country = models.ForeignKey(Country, verbose_name=_("country"), related_name="links", on_delete=models.CASCADE)
class Meta:
verbose_name = _("country link")
verbose_name_plural = _("country links")
@reversion.register()
class AdminContact(models.Model):
ctype = models.CharField(verbose_name=_("type"), max_length=100, blank=True)
name = models.CharField(verbose_name=_("name"), max_length=100)
title = models.CharField(verbose_name=_("title"), max_length=300)
email = models.CharField(verbose_name=_("email"), max_length=300)
class Meta:
verbose_name = _("admin contact")
verbose_name_plural = _("admin contacts")
def __str__(self):
return self.name
class RegionContact(AdminContact):
region = models.ForeignKey(Region, verbose_name=_("region"), related_name="contacts", on_delete=models.CASCADE)
class Meta:
verbose_name = _("region contact")
verbose_name_plural = _("region contacts")
class CountryContact(AdminContact):
country = models.ForeignKey(Country, verbose_name=_("country"), related_name="contacts", on_delete=models.CASCADE)
class Meta:
verbose_name = _("country contact")
verbose_name_plural = _("country contacts")
class AlertLevel(models.IntegerChoices):
YELLOW = 0, _("Yellow")
ORANGE = 1, _("Orange")
RED = 2, _("Red")
def snippet_image_path(instance, filename):
return "emergencies/%s/%s" % (instance.id, filename)
@reversion.register()
class Event(models.Model):
"""A disaster, which could cover multiple countries"""
name = models.CharField(verbose_name=_("name"), max_length=256)
# Obsolete: slug is not editable until we resolve https://github.com/IFRCGo/go-frontend/issues/1013
slug = models.CharField(
verbose_name=_("slug"),
max_length=50,
editable=True,
default=None,
unique=True,
null=True,
blank=True,
validators=[validate_slug, validate_slug_number],
help_text=_(
"Optional string for a clean URL. For example, go.ifrc.org/emergency/hurricane-katrina-2019."
" The string cannot start with a number and is forced to be lowercase."
" Recommend using hyphens over underscores. Special characters like # is not allowed."
),
)
dtype = models.ForeignKey(DisasterType, verbose_name=_("disaster type"), null=True, on_delete=models.SET_NULL)
districts = models.ManyToManyField(District, verbose_name=_("districts"), blank=True)
countries = models.ManyToManyField(Country, verbose_name=_("countries"))
countries_for_preview = models.ManyToManyField(
Country, verbose_name=_("countries for preview"), blank=True, related_name="countries_for_preview"
)
regions = models.ManyToManyField(Region, verbose_name=_("regions"))
parent_event = models.ForeignKey(
"self",
null=True,
blank=True,
verbose_name=_("Parent Emergency"),
on_delete=models.SET_NULL,
help_text=_(
"If needed, you have to change the connected Appeals', Field Reports',"
" etc to point to the parent Emergency manually."
),
)
image = models.ImageField(verbose_name=_("image"), null=True, blank=True, upload_to=snippet_image_path)
summary = HTMLField(verbose_name=_("summary"), blank=True, default="")
num_injured = models.IntegerField(verbose_name=_("number of injured"), null=True, blank=True)
num_dead = models.IntegerField(verbose_name=_("number of dead"), null=True, blank=True)
num_missing = models.IntegerField(verbose_name=_("number of missing"), null=True, blank=True)
num_affected = models.IntegerField(verbose_name=_("number of affected"), null=True, blank=True)
num_displaced = models.IntegerField(verbose_name=_("number of displaced"), null=True, blank=True)
ifrc_severity_level = models.IntegerField(choices=AlertLevel.choices, default=0, verbose_name=_("IFRC Severity level"))
glide = models.CharField(verbose_name=_("glide"), max_length=18, blank=True)
disaster_start_date = models.DateTimeField(verbose_name=_("disaster start date"))
created_at = models.DateTimeField(verbose_name=_("created at"), auto_now_add=True)
updated_at = models.DateTimeField(verbose_name=_("updated at"), auto_now=True)
previous_update = models.DateTimeField(verbose_name=_("previous update"), null=True, blank=True)
auto_generated = models.BooleanField(verbose_name=_("auto generated"), default=False, editable=False)
auto_generated_source = models.CharField(
verbose_name=_("auto generated source"), max_length=50, null=True, blank=True, editable=False
)
# Meant to give the organization a way of highlighting certain, important events.
is_featured = models.BooleanField(default=False, verbose_name=_("is featured on home page"))
# Allows admins to feature the Event on the region page.
is_featured_region = models.BooleanField(default=False, verbose_name=_("is featured on region page"))
hide_attached_field_reports = models.BooleanField(verbose_name=_("hide field report numeric details"), default=False)
hide_field_report_map = models.BooleanField(verbose_name=_("hide field report map"), default=False)
# Tabs. Events can have upto 3 tabs to organize snippets.
tab_one_title = models.CharField(
verbose_name=_("tab one title"), max_length=50, null=False, blank=True, default="Additional Information"
)
tab_two_title = models.CharField(verbose_name=_("tab two title"), max_length=50, null=True, blank=True)
tab_three_title = models.CharField(verbose_name=_("tab three title"), max_length=50, null=True, blank=True)
# visibility
visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_("visibility"), default=1)
emergency_response_contact_email = models.CharField(
verbose_name=_("emergency response contact email"), null=True, blank=True, max_length=255
)
class Meta:
ordering = (
"-disaster_start_date",
"id",
)
verbose_name = _("emergency")
verbose_name_plural = _("emergencies")
# @staticmethod
# def get_for(user):
# field_report_pretech = Prefetch('field_reports', queryset=FieldReport.get_for(user))
# return Event.objects.prefetch_related(field_report_pretech)
def start_date(self):
"""Get start date of first appeal"""
start_dates = [getattr(a, "start_date") for a in self.appeals.all()]
return min(start_dates) if len(start_dates) else None
def end_date(self):
"""Get latest end date of all appeals"""
end_dates = [getattr(a, "end_date") for a in self.appeals.all()]
return max(end_dates) if len(end_dates) else None
def indexing(self):
countries = [c.name for c in self.countries.all()]
ns = [c.id for c in self.countries.all()]
return {
"id": self.id,
"event_id": self.id,
"type": "event",
"name": self.name,
"keyword": None,
"visibility": self.visibility,
"ns": " ".join(map(str, ns)) if len(ns) else None,
"body": "%s %s"
% (
self.name,
" ".join(map(str, countries)) if len(countries) else None,
),
"date": self.disaster_start_date,
}
def es_id(self):
return "event-%s" % self.id
def record_type(self):
return "EVENT"
def to_dict(self):
return to_dict(self)
def save(self, *args, **kwargs):
# Make the slug lowercase
if self.slug:
self.slug = self.slug.lower()
# On save, if `disaster_start_date` is not set, make it the current time
if not self.id and not self.disaster_start_date:
self.disaster_start_date = timezone.now()
return super(Event, self).save(*args, **kwargs)
def __str__(self):
return self.name
@reversion.register()
class EventFeaturedDocument(models.Model):
event = models.ForeignKey(
Event,
verbose_name=_("event"),
on_delete=models.CASCADE,
related_name="featured_documents",
related_query_name="featured_document",
)
title = models.CharField(verbose_name=_("title"), max_length=200)
description = models.TextField(verbose_name=_("description"))
thumbnail = models.ImageField(
verbose_name=_("thumbnail"),
upload_to="event-featured-documents/thumbnail/",
help_text=_("Image should be portrait (3:4 aspect ratio) and scaled down to as close to 96x128 as the image size"),
)
file = models.FileField(
verbose_name=_("file"),
upload_to="event-featured-documents/file/",
)
@reversion.register()
class EventLink(models.Model):
"""
Used in emergency overview.
"""
event = models.ForeignKey(
Event,
verbose_name=_("event"),
on_delete=models.CASCADE,
related_name="links",
related_query_name="link",
)
title = models.CharField(verbose_name=_("title"), max_length=200)
description = models.TextField(verbose_name=_("description"))
url = models.URLField(verbose_name=_("url"))
@reversion.register()
class EventContact(models.Model):
"""Contact for event"""
ctype = models.CharField(verbose_name=_("type"), max_length=100, blank=True)
name = models.CharField(verbose_name=_("name"), max_length=100)
title = models.CharField(verbose_name=_("title"), max_length=300)
email = models.CharField(verbose_name=_("email"), max_length=300)
phone = models.CharField(verbose_name=_("phone"), max_length=100, blank=True, null=True)
event = models.ForeignKey(Event, verbose_name=_("event"), related_name="contacts", on_delete=models.CASCADE)
class Meta:
verbose_name = _("event contact")
verbose_name_plural = _("event contacts")
def __str__(self):
return "%s: %s" % (self.name, self.title)
@reversion.register()
class KeyFigure(models.Model):
event = models.ForeignKey(Event, verbose_name=_("event"), related_name="key_figures", on_delete=models.CASCADE)
number = models.CharField(verbose_name=_("number"), max_length=100, help_text=_("key figure metric"))
deck = models.CharField(verbose_name=_("deck"), max_length=50, help_text=_("key figure units"))
source = models.CharField(verbose_name=_("source"), max_length=256, help_text=_("key figure website link, publication"))
class Meta:
verbose_name = _("key figure")
verbose_name_plural = _("key figures")
ordering = ("id",)
@reversion.register(follow=("event",))
class Snippet(models.Model):
"""Snippet of text"""
snippet = HTMLField(verbose_name=_("snippet"), null=True, blank=True)
image = models.ImageField(verbose_name=_("image"), null=True, blank=True, upload_to=snippet_image_path)
event = models.ForeignKey(Event, verbose_name=_("event"), related_name="snippets", on_delete=models.CASCADE)
visibility = models.IntegerField(choices=VisibilityChoices.choices, verbose_name=_("visibility"), default=3)
position = models.IntegerField(choices=PositionType.choices, verbose_name=_("position"), default=3)
tab = models.IntegerField(choices=TabNumber.choices, verbose_name=_("tab"), default=1)
class Meta:
ordering = (
"position",
"id",
)
verbose_name = _("snippet")
verbose_name_plural = _("snippets")
def __str__(self):
return (self.snippet[:80] if self.snippet else None) or (
self.image.url if getattr(self, "image", None) and self.image.url else ""
)
class SituationReportType(models.Model):
"""Document type, to be able to filter Situation Reports"""
type = models.CharField(verbose_name=_("type"), max_length=150)
is_primary = models.BooleanField(
verbose_name=_("is primary?"),
default=False,
editable=False,
help_text=_("Ensure this type gets precedence over others that are empty"),
)
class Meta:
verbose_name = _("situation report type")
verbose_name_plural = _("situation report types")
def __str__(self):