-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdrf_views.py
More file actions
1577 lines (1377 loc) · 59.1 KB
/
Copy pathdrf_views.py
File metadata and controls
1577 lines (1377 loc) · 59.1 KB
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
from datetime import timedelta
from django.contrib.auth.models import Group, User
from django.db import models
from django.db.models import (
Avg,
Case,
Count,
ExpressionWrapper,
F,
OuterRef,
Prefetch,
Q,
Subquery,
Sum,
When,
)
from django.db.models.fields import IntegerField
from django.db.models.functions import Coalesce, TruncMonth
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django_filters import rest_framework as rest_filters
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import filters, mixins, serializers, viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from api.filter_set import (
Admin2Filter,
AppealDocumentFilter,
AppealHistoryFilter,
CountryFilter,
CountryFilterRMD,
CountryKeyDocumentFilter,
CountryKeyFigureFilter,
CountrySnippetFilter,
CountrySupportingPartnerFilter,
DistrictFilter,
DistrictRMDFilter,
EventFilter,
EventSeverityLevelHistoryFilter,
EventSnippetFilter,
FieldReportFilter,
GoHistoricalFilter,
RegionKeyFigureFilter,
RegionSnippetFilter,
SituationReportFilter,
UserFilterSet,
)
from api.visibility_class import (
ReadOnlyVisibilityViewset,
ReadOnlyVisibilityViewsetMixin,
)
from country_plan.models import CountryPlan
from databank.serializers import CountryOverviewSerializer
from deployments.models import ERU, Personnel
from deployments.serializers import ListDeployedERUByEventSerializer
from main.enums import GlobalEnumSerializer, get_enum_values
from main.filters import NullsLastOrderingFilter
from main.permissions import DenyGuestUserMutationPermission, DenyGuestUserPermission
from main.utils import is_tableau
from per.models import Overview
from per.serializers import CountryLatestOverviewSerializer
from .exceptions import BadRequest
from .models import (
Action,
Admin2,
Appeal,
AppealDocument,
AppealHistory,
AppealType,
Country,
CountryKeyDocument,
CountryKeyFigure,
CountryOfFieldReportToReview,
CountrySnippet,
CountrySupportingPartner,
DisasterType,
District,
Event,
EventContact,
EventFeaturedDocument,
EventSeverityLevelHistory,
Export,
ExternalPartner,
FieldReport,
MainContact,
Profile,
Region,
RegionKeyFigure,
RegionSnippet,
SituationReport,
SituationReportType,
Snippet,
SupportedActivity,
UserCountry,
VisibilityChoices,
)
from .serializers import ( # AppealSerializer,; Tableau Serializers; AppealTableauSerializer,; Go Historical
ActionSerializer,
Admin2Serializer,
AppealDocumentSerializer,
AppealDocumentTableauSerializer,
AppealHistorySerializer,
AppealHistoryTableauSerializer,
CountryDisasterTypeCountSerializer,
CountryDisasterTypeMonthlySerializer,
CountryGeoSerializer,
CountryKeyDocumentSerializer,
CountryKeyFigureInputSerializer,
CountryKeyFigureSerializer,
CountryOfFieldReportToReviewSerializer,
CountryRelationSerializer,
CountrySerializerRMD,
CountrySnippetSerializer,
CountrySnippetTableauSerializer,
CountrySupportingPartnerSerializer,
CountryTableauSerializer,
DeploymentsByEventSerializer,
DetailEventSerializer,
DisasterTypeSerializer,
DistrictSerializer,
DistrictSerializerRMD,
EventSeverityLevelHistorySerializer,
ExportSerializer,
ExternalPartnerSerializer,
FieldReportGeneratedTitleSerializer,
FieldReportGenerateTitleSerializer,
FieldReportSerializer,
GoHistoricalSerializer,
HistoricalDisasterSerializer,
ListEventCsvSerializer,
ListEventDeploymentsSerializer,
ListEventSerializer,
ListEventTableauSerializer,
ListFieldReportCsvSerializer,
ListFieldReportTableauSerializer,
ListMiniEventSerializer,
MainContactSerializer,
MiniCountrySerializer,
MiniDistrictGeoSerializer,
NsSerializer,
ProfileSerializer,
RegionGeoSerializer,
RegionKeyFigureSerializer,
RegionRelationSerializer,
RegionSnippetSerializer,
RegionSnippetTableauSerializer,
SituationReportSerializer,
SituationReportTableauSerializer,
SituationReportTypeSerializer,
SnippetSerializer,
SupportedActivitySerializer,
UserMeSerializer,
UserSerializer,
)
from .utils import generate_field_report_title, is_user_ifrc
class DeploymentsByEventViewset(viewsets.ReadOnlyModelViewSet):
serializer_class = DeploymentsByEventSerializer
def get_queryset(self):
today = timezone.now().date().strftime("%Y-%m-%d")
active_personnel_prefetch = models.Prefetch(
"personneldeployment_set__personnel_set",
queryset=(
Personnel.objects.filter(
type=Personnel.TypeChoices.RR,
start_date__date__lte=today,
end_date__date__gte=today,
is_active=True,
).select_related("country_from")
),
)
return (
Event.objects.filter(
personneldeployment__isnull=False,
personneldeployment__personnel__type=Personnel.TypeChoices.RR,
personneldeployment__personnel__is_active=True,
personneldeployment__personnel__start_date__date__lte=today,
personneldeployment__personnel__end_date__date__gte=today,
)
.prefetch_related(
active_personnel_prefetch,
"personneldeployment_set__country_deployed_to",
"appeals",
)
.order_by(
"-disaster_start_date",
)
.distinct()
)
# These two should give the same result: ^ v
class EventDeploymentsViewset(viewsets.ReadOnlyModelViewSet):
serializer_class = ListEventDeploymentsSerializer
def get_queryset(self):
today = timezone.now().date().strftime("%Y-%m-%d")
return (
Personnel.objects.filter(start_date__date__lte=today, end_date__date__gte=today, is_active=True)
.order_by()
.values(
"deployment__event_deployed_to",
"type",
)
.annotate(id=models.F("deployment__event_deployed_to"), deployments=models.Count("type"))
.values("id", "type", "deployments")
)
class EventSeverityLevelHistoryViewSet(viewsets.ReadOnlyModelViewSet):
queryset = EventSeverityLevelHistory.objects.select_related("event", "created_by").order_by("-created_at")
serializer_class = EventSeverityLevelHistorySerializer
filter_class = EventSeverityLevelHistoryFilter
class DeployedERUFilter(rest_filters.FilterSet):
eru_type = rest_filters.NumberFilter(field_name="eru__type", lookup_expr="exact")
class DeployedERUByEventViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = ListDeployedERUByEventSerializer
filterset_class = DeployedERUFilter
def get_queryset(self):
today = timezone.now().date().strftime("%Y-%m-%d")
active_eru_prefetch = models.Prefetch(
"eru_set",
queryset=(
ERU.objects.filter(
deployed_to__isnull=False,
start_date__date__lte=today,
end_date__date__gte=today,
).select_related(
"eru_owner__national_society_country",
)
),
)
return (
Event.objects.filter(
eru__deployed_to__isnull=False,
eru__start_date__date__lte=today,
eru__end_date__date__gte=today,
)
.prefetch_related(
active_eru_prefetch,
"appeals",
)
.order_by(
"-disaster_start_date",
)
.distinct()
)
class DisasterTypeViewset(viewsets.ReadOnlyModelViewSet):
queryset = DisasterType.objects.all()
serializer_class = DisasterTypeSerializer
search_fields = ("name",) # for /docs
class RegionViewset(viewsets.ReadOnlyModelViewSet):
"""Region endpoint with snippet visibility filtering."""
queryset = Region.objects.annotate(
country_plan_count=Count("country__country_plan", filter=Q(country__country_plan__is_publish=True))
)
def get_queryset(self):
"""Apply snippet visibility filtering at the queryset level.
This removes the need for serializer-side filtering. Rules:
- Anonymous / guest: only PUBLIC
- IFRC user: all visibilities
- Auth non-IFRC: exclude IFRC; include IFRC_NS only if user has a country whose region matches the snippet's region.
- MEMBERSHIP available to any authenticated non-guest user (already covered by exclude-only logic)
We implement the IFRC_NS conditional by computing the set of region IDs the user is linked to via UserCountry/Profile
and excluding IFRC_NS snippets for regions not in that set.
"""
from .models import (
Country,
Profile,
RegionSnippet,
UserCountry,
VisibilityChoices,
)
from .utils import is_user_ifrc
user = getattr(self.request, "user", None)
power_bi_embed = Q(snippet__contains='data-snippet-type="power_bi"')
if not user or not user.is_authenticated:
# Guests: only PUBLIC; exclude power_bi embeds
snip_qs = RegionSnippet.objects.filter(visibility=VisibilityChoices.PUBLIC).exclude(power_bi_embed)
else:
profile = getattr(user, "profile", None)
if profile and profile.limit_access_to_guest:
snip_qs = RegionSnippet.objects.filter(visibility=VisibilityChoices.PUBLIC).exclude(power_bi_embed)
elif is_user_ifrc(user):
snip_qs = RegionSnippet.objects.all()
else:
# User-linked countries (Profile.country is optional)
user_country_ids = UserCountry.objects.filter(user=user.id).values_list("country", flat=True)
profile_country_ids = Profile.objects.filter(user=user.id).values_list("country", flat=True)
combined_country_ids = list(user_country_ids.union(profile_country_ids))
# Regions the user is associated with via countries
allowed_region_ids_for_ifrc_ns = Country.objects.filter(
id__in=combined_country_ids, region__isnull=False
).values_list("region_id", flat=True)
snip_qs = RegionSnippet.objects.exclude(visibility=VisibilityChoices.IFRC)
# Exclude IFRC_NS snippets whose region not in allowed set
snip_qs = snip_qs.exclude(
Q(visibility=VisibilityChoices.IFRC_NS) & ~Q(region_id__in=allowed_region_ids_for_ifrc_ns)
)
# Exclude power_bi embedded snippets when user is not IFRC
snip_qs = snip_qs.exclude(power_bi_embed)
return self.queryset.prefetch_related(models.Prefetch("snippets", queryset=snip_qs))
def get_serializer_class(self):
if self.action == "list":
return RegionGeoSerializer
return RegionRelationSerializer
class CountryViewset(viewsets.ReadOnlyModelViewSet):
queryset = Country.objects.filter(is_deprecated=False).annotate(
has_country_plan=models.Exists(CountryPlan.objects.filter(country=OuterRef("pk"), is_publish=True))
)
filterset_class = CountryFilter
ordering_fields = "__all__"
search_fields = ("name",) # for /docs
def get_object(self):
# NOTE: kwargs is accepting pk for now
# TODO: Can kwargs be other than pk??
pk = self.kwargs["pk"]
try:
country = get_object_or_404(Country, pk=int(pk))
return self.get_queryset().filter(id=country.id).first()
except ValueError:
raise Exception("An error occured", "Country key is unusable", pk)
def get_serializer_class(self):
if self.request.GET.get("mini", "false").lower() == "true":
return MiniCountrySerializer
if is_tableau(self.request) is True:
return CountryTableauSerializer
if self.action == "list":
return CountryGeoSerializer
return CountryRelationSerializer
@extend_schema(
request=None,
responses=CountryOverviewSerializer,
)
@action(
detail=True,
url_path="databank",
# Only for Documentation
serializer_class=CountryOverviewSerializer,
pagination_class=None,
)
def get_databank(self, request, pk):
country = self.get_object()
if hasattr(country, "countryoverview"):
return Response(CountryOverviewSerializer(country.countryoverview).data)
raise Http404
# Country property
@extend_schema(
request=None,
parameters=[CountryKeyFigureInputSerializer],
responses=CountryKeyFigureSerializer,
)
@action(
detail=True,
url_path="figure",
)
def get_country_figure(self, request, pk):
country = self.get_object()
now = timezone.now()
start_date_from = request.GET.get("start_date_from", timezone.now() + timedelta(days=-2 * 365))
start_date_to = request.GET.get("start_date_to", timezone.now())
appeal_conditions = Q(atype=AppealType.APPEAL) | Q(atype=AppealType.INTL)
all_appealhistory = AppealHistory.objects.select_related("appeal").filter(
country=country,
appeal__code__isnull=False,
valid_from__lt=now, # TODO: Allow user to provide this?
valid_to__gt=now, # TODO: Allow user to provide this?
)
if start_date_from and start_date_to:
all_appealhistory = all_appealhistory.filter(
start_date__gte=start_date_from,
start_date__lte=start_date_to,
)
appeals_aggregated = all_appealhistory.annotate(
appeal_with_dref=Count(
Case(
When(Q(atype=AppealType.DREF), then=1),
output_field=IntegerField(),
)
),
appeal_without_dref=Count(Case(When(appeal_conditions, then=1), output_field=IntegerField())),
total_population=(
Case(
When(appeal_conditions | Q(atype=AppealType.DREF), then=F("num_beneficiaries")),
output_field=IntegerField(),
)
),
amount_requested_all=(
Case(
When(appeal_conditions, then=F("amount_requested")),
output_field=IntegerField(),
)
),
amordref=(
Case(
When(appeal_conditions | Q(atype=AppealType.DREF), then=F("amount_requested")),
output_field=IntegerField(),
)
),
amof=(
Case(
When(appeal_conditions, then=F("amount_funded")),
output_field=IntegerField(),
)
),
amofdref=(
Case(
When(appeal_conditions | Q(atype=AppealType.DREF), then=F("amount_funded")),
output_field=IntegerField(),
)
),
emergencies_count=Count(F("appeal__event_id"), distinct=True),
).aggregate(
active_drefs=Sum("appeal_with_dref"),
active_appeals=Sum("appeal_without_dref"),
target_population=Sum("total_population"),
amount_requested=Sum("amount_requested_all"),
amount_requested_dref_included=Sum("amordref"),
amount_funded=Sum("amof"),
amount_funded_dref_included=Sum("amofdref"),
emergencies=Sum("emergencies_count"),
)
return Response(CountryKeyFigureSerializer(appeals_aggregated).data)
@extend_schema(
request=None,
parameters=[CountryKeyFigureInputSerializer],
methods=["GET"],
responses=CountryDisasterTypeCountSerializer(many=True),
)
@action(detail=True, url_path="disaster-count", pagination_class=None)
def get_country_disaster_count(self, request, pk):
country = self.get_object()
start_date_from = request.GET.get("start_date_from", timezone.now() + timedelta(days=-2 * 365))
start_date_to = request.GET.get("start_date_to", timezone.now())
queryset = (
Event.objects.filter(
countries__in=[country.id],
dtype__isnull=False,
)
.values("countries", "dtype__name")
.annotate(
count=Count("id"),
disaster_name=F("dtype__name"),
disaster_id=F("dtype__id"),
)
.order_by("countries", "dtype__name")
)
if start_date_from and start_date_to:
queryset = queryset.filter(
disaster_start_date__gte=start_date_from,
disaster_start_date__lte=start_date_to,
)
return Response(CountryDisasterTypeCountSerializer(queryset, many=True).data)
@extend_schema(
request=None,
parameters=[CountryKeyFigureInputSerializer],
responses=CountryDisasterTypeMonthlySerializer(many=True),
)
@action(detail=True, url_path="disaster-monthly-count", pagination_class=None)
def get_country_disaster_monthly_count(self, request, pk):
country = self.get_object()
start_date_from = request.GET.get("start_date_from", timezone.now() + timedelta(days=-2 * 365))
start_date_to = request.GET.get("start_date_to", timezone.now())
queryset = (
Event.objects.filter(
countries__in=[country.id],
dtype__isnull=False,
)
.annotate(date=TruncMonth("disaster_start_date"))
.values("date", "countries", "dtype")
.annotate(
appeal_targeted_population=Coalesce(
Avg(
"appeals__num_beneficiaries",
filter=models.Q(appeals__num_beneficiaries__isnull=False),
output_field=models.IntegerField(),
),
0,
),
latest_field_report_affected=Coalesce(
Subquery(
FieldReport.objects.filter(event=OuterRef("pk"))
.order_by()
.values("event")
.annotate(c=models.F("num_affected"))
.values("c")[:1],
output_field=models.IntegerField(),
),
0,
),
disaster_name=F("dtype__name"),
disaster_id=F("dtype__id"),
)
.annotate(
targeted_population=ExpressionWrapper(
(F("appeal_targeted_population") + F("latest_field_report_affected")), output_field=models.IntegerField()
)
)
.order_by("date", "countries", "dtype__name")
)
if start_date_from and start_date_to:
queryset = queryset.filter(
disaster_start_date__gte=start_date_from,
disaster_start_date__lte=start_date_to,
)
return Response(CountryDisasterTypeMonthlySerializer(queryset, many=True).data)
@extend_schema(
request=None,
parameters=[CountryKeyFigureInputSerializer],
responses=HistoricalDisasterSerializer(many=True),
)
@action(detail=True, url_path="historical-disaster", pagination_class=None)
def get_country_historical_disaster(self, request, pk):
country = self.get_object()
start_date_from = request.GET.get("start_date_from", timezone.now() + timedelta(days=-2 * 365))
start_date_to = request.GET.get("start_date_to", timezone.now())
dtype = request.GET.get("dtype", None)
queryset = (
Event.objects.filter(
countries__in=[country.id],
dtype__isnull=False,
)
.annotate(date=TruncMonth("disaster_start_date"))
.values("date", "dtype", "countries")
.annotate(
appeal_targeted_population=Coalesce(
Avg(
"appeals__num_beneficiaries",
filter=models.Q(appeals__num_beneficiaries__isnull=False),
output_field=models.IntegerField(),
),
0,
),
latest_field_report_affected=Coalesce(
Subquery(
FieldReport.objects.filter(event=OuterRef("pk"))
.order_by()
.values("event")
.annotate(c=models.F("num_affected"))
.values("c")[:1],
output_field=models.IntegerField(),
),
0,
),
disaster_name=F("dtype__name"),
disaster_id=F("dtype__id"),
amount_funded=F("appeals__amount_funded"),
amount_requested=F("appeals__amount_requested"),
)
.annotate(
targeted_population=ExpressionWrapper(
(F("appeal_targeted_population") + F("latest_field_report_affected")), output_field=models.IntegerField()
)
)
.order_by("date", "countries", "dtype__name")
)
if start_date_from and start_date_to:
queryset = queryset.filter(
disaster_start_date__gte=start_date_from,
disaster_start_date__lte=start_date_to,
)
if dtype:
queryset = queryset.filter(dtype=dtype)
return Response(HistoricalDisasterSerializer(queryset, many=True).data)
@extend_schema(request=None, responses=CountryLatestOverviewSerializer)
@action(detail=True, url_path="latest-per-overview", serializer_class=CountryLatestOverviewSerializer, pagination_class=None)
def get_latest_per_overview(self, request, pk):
country = self.get_object()
queryset = (
Overview.objects.filter(country_id=country.id)
.select_related("country", "type_of_assessment")
.order_by("-created_at")
.first()
)
return Response(CountryLatestOverviewSerializer(queryset).data)
class CountryRMDViewset(viewsets.ReadOnlyModelViewSet):
queryset = Country.objects.filter(is_deprecated=False).filter(iso3__isnull=False).exclude(iso3="")
filterset_class = CountryFilterRMD
search_fields = ("name",)
serializer_class = CountrySerializerRMD
class CountryKeyDocumentViewSet(viewsets.ReadOnlyModelViewSet):
queryset = CountryKeyDocument.objects.select_related("country")
serializer_class = CountryKeyDocumentSerializer
search_fields = ("name",)
ordering_fields = (
"year",
"end_year",
)
# permission_classes = (IsAuthenticated,)
filterset_class = CountryKeyDocumentFilter
filter_backends = (NullsLastOrderingFilter, rest_filters.DjangoFilterBackend, filters.SearchFilter)
class DistrictRMDViewset(viewsets.ReadOnlyModelViewSet):
queryset = District.objects.select_related("country").filter(is_deprecated=False)
filterset_class = DistrictRMDFilter
search_fields = (
"name",
"country__name",
)
serializer_class = DistrictSerializerRMD
class RegionKeyFigureViewset(ReadOnlyVisibilityViewset):
authentication_classes = (TokenAuthentication,)
serializer_class = RegionKeyFigureSerializer
filterset_class = RegionKeyFigureFilter
visibility_model_class = RegionKeyFigure
class CountryKeyFigureViewset(ReadOnlyVisibilityViewset):
authentication_classes = (TokenAuthentication,)
serializer_class = CountryKeyFigureSerializer
filterset_class = CountryKeyFigureFilter
visibility_model_class = CountryKeyFigure
class RegionSnippetViewset(ReadOnlyVisibilityViewset):
authentication_classes = (TokenAuthentication,)
serializer_class = RegionSnippetSerializer
filterset_class = RegionSnippetFilter
visibility_model_class = RegionSnippet
def get_serializer_class(self):
if is_tableau(self.request) is True:
return RegionSnippetTableauSerializer
return RegionSnippetSerializer
def get_queryset(self):
qs = super().get_queryset()
user = getattr(self.request, "user", None)
power_bi_embed = Q(snippet__contains='data-snippet-type="power_bi"')
if not user or not user.is_authenticated or (getattr(user, "profile", None) and user.profile.limit_access_to_guest):
return qs.exclude(power_bi_embed)
# Non-IFRC auth users: still exclude power_bi embeds
if not is_user_ifrc(user):
return qs.exclude(power_bi_embed)
return qs
class CountrySnippetViewset(ReadOnlyVisibilityViewset):
authentication_classes = (TokenAuthentication,)
serializer_class = CountrySnippetSerializer
filterset_class = CountrySnippetFilter
visibility_model_class = CountrySnippet
def get_serializer_class(self):
if is_tableau(self.request) is True:
return CountrySnippetTableauSerializer
return CountrySnippetSerializer
def get_queryset(self):
qs = super().get_queryset()
user = getattr(self.request, "user", None)
power_bi_embed = Q(snippet__contains='data-snippet-type="power_bi"')
if not user or not user.is_authenticated or (getattr(user, "profile", None) and user.profile.limit_access_to_guest):
return qs.exclude(power_bi_embed)
if not is_user_ifrc(user):
return qs.exclude(power_bi_embed)
return qs
class DistrictViewset(viewsets.ReadOnlyModelViewSet):
queryset = District.objects.select_related("country").filter(country__is_deprecated=False).filter(is_deprecated=False)
filterset_class = DistrictFilter
search_fields = (
"name",
"country__name",
) # for /docs
def get_serializer_class(self):
if self.action == "list":
return MiniDistrictGeoSerializer
else:
return DistrictSerializer
class Admin2Viewset(viewsets.ReadOnlyModelViewSet):
filterset_class = Admin2Filter
search_fields = ("name", "district__name", "district__country__name")
serializer_class = Admin2Serializer
def get_queryset(self):
return (
Admin2.objects.select_related("admin1")
.filter(admin1__country__is_deprecated=False)
.filter(admin1__is_deprecated=False)
.filter(is_deprecated=False)
)
class EventViewset(ReadOnlyVisibilityViewset):
ordering_fields = (
"disaster_start_date",
"created_at",
"dtype",
"name",
"summary",
"num_affected",
"glide",
"ifrc_severity_level",
)
filterset_class = EventFilter
visibility_model_class = Event
search_fields = (
"name",
"countries__name",
"dtype__name",
) # for /docs
def get_queryset(self, *args, **kwargs):
# import pdb; pdb.set_trace();
today = timezone.now().date().strftime("%Y-%m-%d")
qset = super().get_queryset()
if self.action == "mini_events":
# return Event.objects.filter(parent_event__isnull=True).select_related('dtype')
return qset.filter(parent_event__isnull=True).select_related("dtype")
if self.action == "response_activity_events":
return (
qset.filter(parent_event__isnull=True)
.filter(Q(auto_generated=False) | Q(auto_generated_source="New field report"))
.select_related("dtype")
)
return (
# Event.objects.filter(parent_event__isnull=True)
qset.filter(parent_event__isnull=True)
.select_related("dtype")
.prefetch_related(
"regions",
Prefetch("appeals", queryset=Appeal.objects.select_related("dtype", "event", "country", "region")),
Prefetch("countries", queryset=Country.objects.select_related("region")),
Prefetch("districts", queryset=District.objects.select_related("country")),
Prefetch("contacts", queryset=EventContact.objects.order_by("id")),
Prefetch(
"field_reports",
queryset=FieldReport.objects.select_related("user", "dtype", "event").prefetch_related(
"districts", "countries", "regions", "contacts"
),
),
Prefetch("featured_documents", queryset=EventFeaturedDocument.objects.order_by("-id")),
)
.annotate(
active_deployments=Count(
"personneldeployment__personnel",
filter=Q(
personneldeployment__personnel__type=Personnel.TypeChoices.RR,
personneldeployment__personnel__start_date__date__lte=today,
personneldeployment__personnel__end_date__date__gte=today,
personneldeployment__personnel__is_active=True,
),
)
)
)
def get_serializer_class(self):
if self.action == "mini_events":
return ListMiniEventSerializer
elif self.action == "list":
request_format_type = self.request.GET.get("format", "json")
if request_format_type == "csv":
return ListEventCsvSerializer
elif is_tableau(self.request) is True:
return ListEventTableauSerializer
else:
return ListEventSerializer
else:
return DetailEventSerializer
# Overwrite 'retrieve' because by default we filter to only non-merged Emergencies in 'get_queryset()'
def retrieve(self, request, pk=None, *args, **kwargs):
if pk:
try:
prefetches = [
"regions",
Prefetch("appeals", queryset=Appeal.objects.select_related("dtype", "event", "country", "region")),
Prefetch("countries", queryset=Country.objects.select_related("region")),
Prefetch("districts", queryset=District.objects.select_related("country")),
Prefetch("contacts", queryset=EventContact.objects.order_by("id")),
Prefetch("field_reports", queryset=FieldReport.objects.prefetch_related("countries", "contacts")),
Prefetch("featured_documents", queryset=EventFeaturedDocument.objects.order_by("-id")),
]
if self.request.user.is_authenticated and not self.request.user.profile.limit_access_to_guest:
if is_user_ifrc(self.request.user):
instance = Event.objects.prefetch_related(*prefetches).get(pk=pk)
else:
user_countries = (
UserCountry.objects.filter(user=request.user.id)
.values("country")
.union(Profile.objects.filter(user=request.user.id).values("country"))
)
instance = (
Event.objects.prefetch_related(*prefetches)
.exclude(visibility=VisibilityChoices.IFRC)
.exclude(Q(visibility=VisibilityChoices.IFRC_NS) & ~Q(countries__id__in=user_countries))
.get(pk=pk)
)
else:
instance = Event.objects.prefetch_related(*prefetches).filter(visibility=VisibilityChoices.PUBLIC).get(pk=pk)
# instance = Event.get_for(request.user).get(pk=pk)
except Exception:
raise Http404
elif kwargs["slug"]:
instance = Event.objects.filter(slug=kwargs["slug"]).first()
# instance = Event.get_for(request.user).filter(slug=kwargs['slug']).first()
if not instance:
raise Http404
else:
raise BadRequest("Emergency ID or Slug parameters are missing")
serializer = self.get_serializer(instance)
# Hide the "affected" values that are kept only for history – see (¤) in other code parts
if "field_reports" in serializer.data:
for j, fr in enumerate(serializer.data["field_reports"]):
if "recent_affected" in fr: # should always be True
for i, field in enumerate(
[
"num_affected",
"gov_num_affected",
"other_num_affected",
"num_potentially_affected",
"gov_num_potentially_affected",
"other_num_potentially_affected",
]
):
if fr["recent_affected"] - 1 != i and field in serializer.data["field_reports"][j]:
del serializer.data["field_reports"][j][field]
del serializer.data["field_reports"][j]["recent_affected"]
return Response(serializer.data)
@extend_schema(
request=None,
responses=ListMiniEventSerializer(many=True),
)
@action(methods=["get"], detail=False, url_path="mini")
def mini_events(self, request):
queryset = self.filter_queryset(self.get_queryset())
serializer = ListMiniEventSerializer(queryset, many=True)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
return Response(serializer.data)
@extend_schema(
request=None,
responses=ListEventSerializer(many=True),
)
@action(methods=["get"], detail=False, url_path="response-activity")
def response_activity_events(self, request):
return super().list(request)
class EventSnippetViewset(ReadOnlyVisibilityViewset):
authentication_classes = (TokenAuthentication,)
serializer_class = SnippetSerializer
filterset_class = EventSnippetFilter
visibility_model_class = Snippet
ordering_fields = "__all__"
def get_queryset(self):
qs = super().get_queryset()
user = getattr(self.request, "user", None)
power_bi_embed = Q(snippet__contains='data-snippet-type="power_bi"')
if not user or not user.is_authenticated or (getattr(user, "profile", None) and user.profile.limit_access_to_guest):
return qs.exclude(power_bi_embed)
if not is_user_ifrc(user):
return qs.exclude(power_bi_embed)
return qs
class SituationReportTypeViewset(viewsets.ReadOnlyModelViewSet):
queryset = SituationReportType.objects.all()
serializer_class = SituationReportTypeSerializer
ordering_fields = ("type",)
search_fields = ("type",) # for /docs
class SituationReportViewset(ReadOnlyVisibilityViewsetMixin, viewsets.ReadOnlyModelViewSet):
queryset = SituationReport.objects.select_related("type").order_by("-is_pinned", "-created_at")
authentication_classes = (TokenAuthentication,)
serializer_class = SituationReportSerializer
ordering_fields = (
"created_at",
"is_pinned",
"name",
)
filterset_class = SituationReportFilter
visibility_model_class = SituationReport
search_fields = (
"name",
"event__name",
) # for /docs
def get_serializer_class(self):
if is_tableau(self.request) is True:
return SituationReportTableauSerializer
return SituationReportSerializer
# Instead of viewsets.ReadOnlyModelViewSet:
class AppealViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
"""Used to get Appeals from AppealHistory. Has no 'read' option, just 'list'."""
queryset = AppealHistory.objects.select_related(
"appeal__event",
"dtype",
"country",
"region",
).filter(appeal__code__isnull=False)
serializer_class = AppealHistorySerializer
ordering_fields = "__all__"
filterset_class = AppealHistoryFilter
search_fields = (
"appeal__name",
"code",
) # for /docs
def get_serializer_class(self):
if is_tableau(self.request) is True:
return AppealHistoryTableauSerializer
return AppealHistorySerializer
def remove_unconfirmed_event(self, obj):
if obj["needs_confirmation"]:
obj["event"] = None
return obj
def remove_unconfirmed_events(self, objs):
return [self.remove_unconfirmed_event(obj) for obj in objs]
# Overwrite to exclude the events which require confirmation
def list(self, request, *args, **kwargs):
date = request.GET.get("date", timezone.now())
queryset = self.filter_queryset(
self.get_queryset().filter(
valid_from__lt=date,
valid_to__gt=date,
)
)