Skip to content

Commit

Permalink
Generate title api for field report (#2355)
Browse files Browse the repository at this point in the history
* Add generate title api for field report
* fix snapshot issue
* Changes on generate title api
  • Loading branch information
susilnem committed Jan 7, 2025
1 parent 56dc9b0 commit 2c04642
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 33 deletions.
39 changes: 38 additions & 1 deletion api/drf_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@
DistrictSerializerRMD,
ExportSerializer,
ExternalPartnerSerializer,
FieldReportGeneratedTitleSerializer,
FieldReportGenerateTitleSerializer,
FieldReportSerializer,
GoHistoricalSerializer,
HistoricalDisasterSerializer,
Expand Down Expand Up @@ -151,7 +153,7 @@
UserMeSerializer,
UserSerializer,
)
from .utils import is_user_ifrc
from .utils import generate_field_report_title, is_user_ifrc


class DeploymentsByEventViewset(viewsets.ReadOnlyModelViewSet):
Expand Down Expand Up @@ -943,6 +945,41 @@ def get_serializer_class(self):
return FieldReportSerializer
return FieldReportSerializer

@extend_schema(
request=FieldReportGenerateTitleSerializer,
responses=FieldReportGeneratedTitleSerializer,
)
@action(
detail=False,
methods=["post"],
url_path="generate-title",
permission_classes=[DenyGuestUserMutationPermission],
)
def generate_title(self, request):
"""
Generate a title for a Field Report.
"""
serializer = FieldReportGenerateTitleSerializer(data=request.data)
serializer.is_valid(raise_exception=True)

countries = serializer.validated_data.get("countries")
dtype = serializer.validated_data.get("dtype")
event = serializer.validated_data.get("event")
start_date = serializer.validated_data.get("start_date")
title = serializer.validated_data.get("title")
is_covid_report = serializer.validated_data.get("is_covid_report")

summary = generate_field_report_title(
country=countries[0], dtype=dtype, event=event, start_date=start_date, title=title, is_covid_report=is_covid_report
)
return Response(
FieldReportGeneratedTitleSerializer(
{
"title": summary,
}
).data
)


class ActionViewset(viewsets.ReadOnlyModelViewSet):
queryset = Action.objects.exclude(is_disabled=True)
Expand Down
16 changes: 0 additions & 16 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1718,22 +1718,6 @@ def generate_formatted_summary(self):
if self.id and not self.event:
self.fr_num = None

suffix = f"#{self.fr_num} ({current_date})" if self.event else ""

if self.fr_num is None and self.event and self.id:
current_fr_number = (
FieldReport.objects.filter(event=self.event, countries__iso3=country_iso3).aggregate(
max_fr_num=models.Max("fr_num")
)["max_fr_num"]
or 0
)
field_report_number = current_fr_number + 1
self.fr_num = field_report_number

# NOTE: Report number is set to None if the report is not associated with an event
if self.id and not self.event:
self.fr_num = None

suffix = ""
if self.fr_num and self.fr_num > 1:
suffix = f"#{self.fr_num} ({current_date})"
Expand Down
21 changes: 21 additions & 0 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2104,6 +2104,27 @@ def update(self, instance, validated_data):
return super().update(instance, validated_data)


class FieldReportGenerateTitleSerializer(serializers.ModelSerializer):
dtype = serializers.PrimaryKeyRelatedField(queryset=DisasterType.objects.all())
event = serializers.PrimaryKeyRelatedField(queryset=Event.objects.all(), required=False)
title = serializers.CharField(required=True)

class Meta:
model = FieldReport
fields = (
"countries",
"dtype",
"title",
"event",
"start_date",
"is_covid_report",
)


class FieldReportGeneratedTitleSerializer(serializers.Serializer):
title = serializers.CharField()


class MainContactSerializer(ModelSerializer):
class Meta:
model = MainContact
Expand Down
42 changes: 42 additions & 0 deletions api/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import base64
import typing
from typing import Optional

from django.core.exceptions import ValidationError
from django.db import models
from django.http import JsonResponse
from django.utils import timezone
from django.utils.translation import gettext

if typing.TYPE_CHECKING:
from api.models import Country, DisasterType, Event


class DebugPlaywright:
"""Basic helpers to debug PlayWright issues locally"""
Expand Down Expand Up @@ -96,3 +103,38 @@ def write(self, value):

def bad_request(message):
return JsonResponse({"statusCode": 400, "error_message": message}, status=400)


def generate_field_report_title(
country: "Country",
dtype: "DisasterType",
event: "Event",
start_date: Optional[timezone.datetime],
title: str,
is_covid_report: bool = False,
):
"""
Generates the summary based on the country, dtype, event, start_date, title and is_covid_report
"""
from api.models import FieldReport

current_date = timezone.now().strftime("%Y-%m-%d")
# NOTE: start_date is optional and setting it to current date if not provided
if start_date:
start_date = start_date.strftime("%m-%Y")
else:
start_date = timezone.now().strftime("%m-%Y")
current_fr_number = (
FieldReport.objects.filter(event=event, countries__id=country.id).aggregate(max_fr_num=models.Max("fr_num"))["max_fr_num"]
or 0
)
fr_num = current_fr_number + 1

suffix = ""
if fr_num > 1 and event:
suffix = f"#{fr_num} ({current_date})"
if is_covid_report:
summary = f"{country.iso3}: COVID-19 {suffix}"
else:
summary = f"{country.iso3}: {dtype.name} - {start_date} - {title} {suffix}"
return summary
Loading

0 comments on commit 2c04642

Please sign in to comment.