Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create api for EAP create, update, get #1480

Draft
wants to merge 13 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 50 additions & 3 deletions api/drf_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
from deployments.models import Personnel
from databank.serializers import CountryOverviewSerializer

from eap.models import EAPActivation, EAP, EAPDocument

from .event_sources import SOURCES
from .exceptions import BadRequest
from .view_filters import ListFilter
Expand Down Expand Up @@ -230,11 +232,12 @@ def get_databank(self, request, pk):

class CountryFilterRMD(filters.FilterSet):
region = filters.NumberFilter(field_name='region', lookup_expr='exact')

class Meta:
model = Country
fields = ('region', 'record_type',)


class CountryRMDViewset(viewsets.ReadOnlyModelViewSet):
queryset = Country.objects.filter(is_deprecated=False).filter(iso3__isnull=False).exclude(iso3="")
filterset_class = CountryFilterRMD
Expand All @@ -245,7 +248,7 @@ class CountryRMDViewset(viewsets.ReadOnlyModelViewSet):
class DistrictRMDFilter(filters.FilterSet):
class Meta:
model = District
fields = ('country','country__name')
fields = ('country', 'country__name')


class DistrictRMDViewset(viewsets.ReadOnlyModelViewSet):
Expand Down Expand Up @@ -914,6 +917,23 @@ def create_event(self, report):
report.save()
return event

def create_eap_activation(self, data, fieldreport):
eap = EAP.objects.filter(id=data.pop('eap', None)).first()
documents_data = data.pop('documents', None)
eap_activation = EAPActivation.objects.create(
eap=eap,
field_report=fieldreport,
**data
)
if documents_data:
for data in documents_data:
document = EAPDocument.objects.filter(id=data['id']).first()
document.caption = data['caption']
document.save(update_fields=['caption'])
# save m2m
eap_activation.documents.add(document)
return eap_activation

def create(self, request, *args, **kwargs):
serializer = self.serialize(request.data)
if not serializer.is_valid():
Expand All @@ -928,7 +948,9 @@ def create(self, request, *args, **kwargs):

try:
# TODO: Use serializer to create fieldreport
eap_activation_data = data.pop('eap_activation')
fieldreport = FieldReport.objects.create(**data)
self.create_eap_activation(eap_activation_data, fieldreport) # activate respected eap for field report
CreateFieldReportSerializer.trigger_field_translation(fieldreport)
except Exception as e:
try:
Expand Down Expand Up @@ -976,6 +998,28 @@ class UpdateFieldReport(UpdateAPIView, GenericFieldReportView):
queryset = FieldReport.objects.all()
serializer_class = CreateFieldReportSerializer

# function for updating eap-activate in field report
def update_eap_activation(self, data, fieldreport):
from eap.serializers import EAPActivationSerializer

eap_id = data.pop('eap', None)
documents_data = data.pop('documents', None)
instance = EAPActivation.objects.get(field_report=fieldreport)
eap_activation = EAPActivationSerializer().update(instance, data)
instance.eap = EAP.objects.filter(id=eap_id).first()

instance.documents.clear()
if documents_data:
for data in documents_data:
document = EAPDocument.objects.filter(id=data['id']).first()
document.caption = data['caption']
document.save(update_fields=['caption'])
# save m2m
instance.documents.add(document)
instance.save(update_fields=['eap'])

return eap_activation

def partial_update(self, request, *args, **kwargs):
self.update(request, *args, **kwargs)

Expand All @@ -989,7 +1033,9 @@ def update(self, request, *args, **kwargs):
data, locations, meta, partners = self.map_many_to_many_relations(data)

try:
serializer.save()
field_report = serializer.save()
# update respected eap-activation
self.update_eap_activation(request.data['eap_activation'], field_report)
except Exception:
logger.error('Faild to update field report', exc_info=True)
raise BadRequest('Could not update field report')
Expand Down Expand Up @@ -1045,6 +1091,7 @@ class GoHistoricalViewSet(viewsets.ReadOnlyModelViewSet):
def get_queryset(self):
return Event.objects.filter(appeals__isnull=False)


class CountryOfFieldReportToReviewViewset(viewsets.ReadOnlyModelViewSet):
queryset = CountryOfFieldReportToReview.objects.order_by('country')
serializer_class = CountryOfFieldReportToReviewSerializer
Expand Down
18 changes: 18 additions & 0 deletions api/migrations/0157_auto_20220721_0754.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 2.2.28 on 2022-07-21 07:54

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('api', '0156_appealfilter_comment'),
]

operations = [
migrations.AlterField(
model_name='fieldreport',
name='status',
field=models.IntegerField(choices=[(0, 'Unknown'), (2, 'Two'), (3, 'Three'), (8, 'Early Warning'), (9, 'Event-related'), (10, 'Ten'), (11, 'EAP Activation')], default=0, verbose_name='type'),
),
]
3 changes: 2 additions & 1 deletion api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1226,6 +1226,7 @@ class Status(IntegerChoices):
EW = 8, _('Early Warning')
EVT = 9, _('Event-related')
TEN = 10, _('Ten') # legacy usage. Covid?
EAP_ACTV = 11, _('EAP Activation') # EAP Activation

user = models.ForeignKey(
settings.AUTH_USER_MODEL, verbose_name=_('user'), related_name='user',
Expand Down Expand Up @@ -1932,8 +1933,8 @@ class EmergencyOperationsFR(EmergencyOperationsBase):
raw_shelter_people_targeted = None
raw_water_sanitation_and_hygiene_people_targeted = None

# Fields for the cleaned data
date_of_disaster = models.DateField(verbose_name=_('date of disaster'), null=True, blank=True)
# Fields for the cleaned data
num_of_other_partner_involved = models.TextField(verbose_name=_('number of other partner involved'), null=True, blank=True)
num_of_partner_ns_involved = models.TextField(verbose_name=_('number of NS partner involved'), null=True, blank=True)
operation_end_date = models.DateField(verbose_name=_('operation end date'), null=True, blank=True)
Expand Down
13 changes: 13 additions & 0 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from lang.serializers import ModelSerializer
from lang.models import String


from .models import (
DisasterType,
ExternalPartner,
Expand Down Expand Up @@ -54,6 +55,7 @@
)
from notifications.models import Subscription
from deployments.models import EmergencyProject
from eap.models import EAPActivation


class GeoSerializerMixin:
Expand Down Expand Up @@ -1071,13 +1073,23 @@ class DetailFieldReportSerializer(FieldReportEnumDisplayMixin, ModelSerializer):
districts = MiniDistrictSerializer(many=True)
external_partners = ExternalPartnerSerializer(many=True)
supported_activities = SupportedActivitySerializer(many=True)
eap_activation = serializers.SerializerMethodField('get_eap_activation')

@staticmethod
def get_eap_activation(obj):
from eap.serializers import EAPActivationSerializer

eap_activation = EAPActivation.objects.get(field_report=obj)
eap_activation_data = EAPActivationSerializer(eap_activation).data
return eap_activation_data

class Meta:
model = FieldReport
fields = '__all__'


class CreateFieldReportSerializer(FieldReportEnumDisplayMixin, ModelSerializer):

class Meta:
model = FieldReport
fields = '__all__'
Expand Down Expand Up @@ -1107,6 +1119,7 @@ class Meta:
'disaster_start_date', 'created_at', 'appeals',
)


class CountryOfFieldReportToReviewSerializer(ModelSerializer):
class Meta:
model = CountryOfFieldReportToReview
Expand Down
66 changes: 65 additions & 1 deletion api/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
EventLinkFactory,
AppealFactory
)
from eap.factories import EAPFactory, EAPDocumentFactory
from eap.models import EAPActivation


class AuthTokenTest(APITestCase):
Expand Down Expand Up @@ -63,7 +65,6 @@ def test_sit_rep_types(self):

# Filter by event
response = self.client.get('/api/v2/situation_report/?limit=100&event=%s' % event1.id)
print(response)
self.assertEqual(response.status_code, 200)
count = response.json()['count']
self.assertEqual(count, 3)
Expand All @@ -82,6 +83,10 @@ class FieldReportTest(APITestCase):
def test_create_and_update(self):
user = User.objects.create(username='jo')
region = models.Region.objects.create(name=1)
eap1 = EAPFactory.create(created_by=user)
eap2 = EAPFactory.create(created_by=user)
document1 = EAPDocumentFactory.create(created_by=self.user)
document2 = EAPDocumentFactory.create(created_by=self.user)
country1 = models.Country.objects.create(name='abc', region=region)
country2 = models.Country.objects.create(name='xyz')
body = {
Expand All @@ -105,6 +110,27 @@ def test_create_and_update(self):
{'ctype': 'Originator', 'name': 'jo', 'title': 'head', 'email': '123'}
],
'user': user.id,
'eap_activation': {
'title': 'eap activation title',
'eap': eap1.id,
'description': 'test eap description',
'trigger_met_date': '2022-11-11 00:00',
'documents': [
{
"id": document1.id,
"caption": "test eap"
}
],
'originator_name': 'test name',
'originator_title': 'test originator title',
'originator_email': '[email protected]',
'nsc_name_operational': 'test name operational',
'nsc_title_operational': 'test nsc operational',
'nsc_email_operational': 'test nsc operational',
'ifrc_focal_name': 'test focal name',
'ifrc_focal_title': 'test focal title',
'ifrc_focal_email': '[email protected]'
}
}
self.client.force_authenticate(user=user)
with self.capture_on_commit_callbacks(execute=True):
Expand Down Expand Up @@ -137,6 +163,12 @@ def test_create_and_update(self):
self.aws_translator._fake_translation('test', 'es', 'en')
)

# check eap-activation data
eap_activation_obj = EAPActivation.objects.get(field_report=created)
self.assertEqual(eap_activation_obj.title, 'eap activation title')
self.assertEqual(eap_activation_obj.eap.id, eap1.id)
self.assertEqual(eap_activation_obj.field_report.id, created.id)

# created an emergency automatically
self.assertEqual(created.event.name, 'test')
event_pk = created.event.id
Expand All @@ -149,6 +181,32 @@ def test_create_and_update(self):
]
body['actions_taken'] = []
body['visibility'] = models.VisibilityChoices.PUBLIC
body['eap_activation'] = {
'title': 'eap activation title updated',
'eap': eap2.id,
'description': 'test eap description updated',
'trigger_met_date': '2022-11-11 01:00',
'documents': [
{
"id": document1.id,
"caption": "test eap updated"
},
{
"id": document2.id,
"caption": "test eap updated 2"
}
],
'originator_name': 'test name',
'originator_title': 'test originator title',
'originator_email': '[email protected]',
'nsc_name_operational': 'test name operational',
'nsc_title_operational': 'test nsc operational',
'nsc_email_operational': 'test nsc operational',
'ifrc_focal_name': 'test focal name',
'ifrc_focal_title': 'test focal title',
'ifrc_focal_email': '[email protected]'
}

response = self.client.put(f'/api/v2/update_field_report/{created.id}/', body, format='json').json()
updated = models.FieldReport.objects.get(pk=response['id'])

Expand Down Expand Up @@ -177,6 +235,12 @@ def test_create_and_update(self):
self.aws_translator._fake_translation('this is a test description', 'es', 'en'),
) # This has not been reset

# check eap-activation data
eap_activation_obj = EAPActivation.objects.get(field_report=updated)
self.assertEqual(eap_activation_obj.title, 'eap activation title updated')
self.assertEqual(eap_activation_obj.eap.id, eap2.id)
self.assertEqual(eap_activation_obj.field_report.id, updated.id)

body['summary'] = 'test [updated again]'
with self.capture_on_commit_callbacks(execute=True):
response = self.client.put(f'/api/v2/update_field_report/{created.id}/', body, format='json').json()
Expand Down
1 change: 0 additions & 1 deletion api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ def get(self, request):
}
}
}

results = ES_CLIENT.search(
index=index,
doc_type='page',
Expand Down
42 changes: 42 additions & 0 deletions eap/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,45 @@
from django.contrib import admin

# Register your models here.

from .models import (
EAP,
EAPPartner,
EAPReference,
EAPDocument,
EAPActivation,
EAPActivationReport,
)


class ReferenceAdminInline(admin.TabularInline):
model = EAPReference
extra = 0


class PartnerAdminInline(admin.TabularInline):
model = EAPPartner
extra = 0


@admin.register(EAPDocument)
class EAPDocumentAdmin(admin.ModelAdmin):
model = EAPDocument
extra = 0


@admin.register(EAP)
class EAPAdmin(admin.ModelAdmin):
list_display = ('eap_number', 'country', 'status', 'operational_timeframe',)
inlines = [ReferenceAdminInline, PartnerAdminInline]
autocomplete_fields = ('country', 'districts', 'disaster_type', 'created_by', 'modified_by')


@admin.register(EAPActivation)
class EAPActivation(admin.ModelAdmin):
model = EAPActivation


@admin.register(EAPActivationReport)
class EAPActivationReport(admin.ModelAdmin):
model = EAPActivationReport
Loading