Skip to content

Commit

Permalink
Add translation logic for summary in fieldreport and event
Browse files Browse the repository at this point in the history
  • Loading branch information
susilnem committed Nov 13, 2024
1 parent 84cddc8 commit d590fa6
Show file tree
Hide file tree
Showing 13 changed files with 287 additions and 442 deletions.
5 changes: 3 additions & 2 deletions api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ class EventAdmin(CompareVersionAdmin, RegionRestrictedAdmin, TranslationAdmin):
"districts",
"parent_event",
)
readonly_fields = ("name",)

def appeals(self, instance):
if getattr(instance, "appeals").exists():
Expand Down Expand Up @@ -331,7 +332,7 @@ class FieldReportAdmin(CompareVersionAdmin, RegionRestrictedAdmin, TranslationAd
def create_events(self, request, queryset):
for report in queryset:
event = models.Event.objects.create(
name=report.summary,
title=report.title,
dtype=getattr(report, "dtype"),
disaster_start_date=getattr(report, "created_at"),
auto_generated=True,
Expand Down Expand Up @@ -431,7 +432,7 @@ class AppealAdmin(CompareVersionAdmin, RegionRestrictedAdmin, TranslationAdmin):
def create_events(self, request, queryset):
for appeal in queryset:
event = models.Event.objects.create(
name=appeal.name,
title=appeal.name,
dtype=getattr(appeal, "dtype"),
disaster_start_date=getattr(appeal, "start_date"),
auto_generated=True,
Expand Down
3 changes: 2 additions & 1 deletion api/factories/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ class EventFactory(factory.django.DjangoModelFactory):
class Meta:
model = Event

name = fuzzy.FuzzyText(length=50, prefix="event-")
name = fuzzy.FuzzyText(length=50)
title = fuzzy.FuzzyText(length=10)
slug = fuzzy.FuzzyText(length=50)
dtype = factory.SubFactory(DisasterTypeFactory)

Expand Down
1 change: 1 addition & 0 deletions api/factories/field_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class Meta:
dtype = factory.SubFactory(disaster_type.DisasterTypeFactory)
event = factory.SubFactory(event.EventFactory)
summary = fuzzy.FuzzyText(length=500)
title = fuzzy.FuzzyText(length=10, prefix="title-")
description = fuzzy.FuzzyText(length=200)
report_date = fuzzy.FuzzyDateTime(datetime.datetime(2008, 1, 1, tzinfo=pytz.utc))
# start_date is now what the user explicitly sets while filling the Field Report form.
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Generated by Django 4.2.16 on 2024-10-07 18:46

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("api", "0214_alter_profile_limit_access_to_guest"),
]

operations = [
migrations.AddField(
model_name="event",
name="title",
field=models.CharField(blank=True, max_length=256),
),
migrations.AddField(
model_name="event",
name="title_ar",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="event",
name="title_en",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="event",
name="title_es",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="event",
name="title_fr",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="fieldreport",
name="title",
field=models.CharField(blank=True, max_length=256),
),
migrations.AddField(
model_name="fieldreport",
name="title_ar",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="fieldreport",
name="title_en",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="fieldreport",
name="title_es",
field=models.CharField(blank=True, max_length=256, null=True),
),
migrations.AddField(
model_name="fieldreport",
name="title_fr",
field=models.CharField(blank=True, max_length=256, null=True),
),
]
68 changes: 49 additions & 19 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@
# from django.db.models import Prefetch
from django.dispatch import receiver
from django.utils import timezone
from django.utils.translation import activate, deactivate
from django.utils.translation import gettext_lazy as _
from modeltranslation.utils import build_localized_fieldname
from tinymce.models import HTMLField

from lang.translation import AVAILABLE_LANGUAGES

from .utils import validate_slug_number # is_user_ifrc,


Expand Down Expand Up @@ -750,7 +754,7 @@ class Event(models.Model):
)
image = models.ImageField(verbose_name=_("image"), null=True, blank=True, upload_to=snippet_image_path)
summary = HTMLField(verbose_name=_("summary"), blank=True, default="")
# title = models.CharField(max_length=256, blank=True)
title = models.CharField(max_length=256, blank=True)

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)
Expand Down Expand Up @@ -845,6 +849,16 @@ def record_type(self):
def to_dict(self):
return to_dict(self)

def generate_formatted_name(self):
country_iso3 = self.countries.first().iso3 if self.id and self.countries.first() else "N/A"
dtype = self.dtype.name if self.dtype else "N/A"
start_date = timezone.now().strftime("%m-%Y")
for lang in AVAILABLE_LANGUAGES:
activate(lang)
self.name = f"{country_iso3}: {dtype} - {start_date} - {self.title}"
deactivate()
yield build_localized_fieldname("name", lang)

def save(self, *args, **kwargs):

# Make the slug lowercase
Expand All @@ -855,6 +869,15 @@ def save(self, *args, **kwargs):
if not self.id and not self.disaster_start_date:
self.disaster_start_date = timezone.now()

updated_name_fields = list(self.generate_formatted_name())

# Updating the updated_fields with the fields that are updated
if kwargs.get("update_fields"):
kwargs["update_fields"] = (
*kwargs["update_fields"],
*updated_name_fields,
)

return super(Event, self).save(*args, **kwargs)

def __str__(self):
Expand Down Expand Up @@ -1647,32 +1670,39 @@ class Meta:
# if is_user_ifrc(user):
# filters = models.Q()

def generate_formatted_summary(self) -> str:
translations = {
"summary_en": self.title_en,
"summary_fr": self.title_fr,
"summary_es": self.title_es,
"summary_ar": self.title_ar,
}
country = self.countries.first()
disater = self.dtype
def generate_formatted_summary(self):
country_iso3 = self.countries.first().iso3 if self.id and self.countries.first() else "N/A"
dtype = self.dtype.name if self.dtype else "N/A"
start_date = self.start_date.strftime("%m-%Y")

field_report_number = FieldReport.objects.filter(countries=country).count()
date = timezone.now().strftime("%Y-%m-%d")
for summary_field, title in translations.items():
if title:
summary = f"{country.iso3}: {disater.name} - {start_date} {title} #{field_report_number} ({date})"
setattr(self, summary_field, summary)
field_report_number = FieldReport.objects.filter(countries__iso3=country_iso3).exclude(id=self.id).count() + 1
current_date = timezone.now().strftime("%Y-%m-%d")

for lang in AVAILABLE_LANGUAGES:
activate(lang)
if self.is_covid_report:
# {ISO3}: COVID-19 #{Field Report Number} ({Date})
self.summary = f"{country_iso3}: COVID-19 #{field_report_number} ({current_date})"
else:
# {ISO3}: {Disaster Type} - {Start Date} #{Field Report Number} ({Date})
self.summary = f"{country_iso3}: {dtype} - {start_date} {self.title} #{field_report_number} ({current_date})"
deactivate()
yield build_localized_fieldname("summary", lang)

def save(self, *args, **kwargs):
# On save, is report_date or start_date is not set, set it to now.
# On save, if report_date or start_date is not set, set it to now.
if not self.id and not self.report_date:
self.report_date = timezone.now()
if not self.id and not self.start_date:
self.start_date = timezone.now()
# NOTE: Overriding the summary field with translated title
self.generate_formatted_summary()
updated_summary_list = list(self.generate_formatted_summary())

# NOTE: Updating the updated_fields by translation tasks
if kwargs.get("update_fields"):
kwargs["update_fields"] = (
*kwargs["update_fields"],
*updated_summary_list,
)

return super(FieldReport, self).save(*args, **kwargs)

Expand Down
26 changes: 25 additions & 1 deletion api/receivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@

from django.db import transaction
from django.db.models import Q
from django.db.models.signals import post_delete, post_save, pre_delete, pre_save
from django.db.models.signals import (
m2m_changed,
post_delete,
post_save,
pre_delete,
pre_save,
)
from django.dispatch import receiver
from django.utils import timezone
from reversion.models import Version
Expand Down Expand Up @@ -276,3 +282,21 @@ def remove_appeal_filter(sender, instance, using, **kwargs):

appealFilter.value = ",".join(lstCodesToSkip)
appealFilter.save()


@receiver(m2m_changed, sender=Event.countries.through)
def update_event_name(sender, instance, action, **kwargs):
"""
Update the event name when the countries are changed.
"""
if action in ["post_add", "post_remove"]:
instance.save()


@receiver(m2m_changed, sender=FieldReport.countries.through)
def update_fieldreport_summary(sender, instance, action, **kwargs):
"""
Update the FieldReport summary when the countries are changed.
"""
if action in ["post_add", "post_remove"]:
instance.save()
4 changes: 3 additions & 1 deletion api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1136,6 +1136,7 @@ class Meta:
"dtype",
"countries",
"summary",
"title",
"num_affected",
"ifrc_severity_level",
"ifrc_severity_level_display",
Expand Down Expand Up @@ -1271,6 +1272,7 @@ class Meta:
"countries",
"districts",
"summary",
"title",
"num_affected",
"tab_two_title",
"tab_three_title",
Expand Down Expand Up @@ -2027,7 +2029,7 @@ class Meta:

def create_event(self, report):
event = Event.objects.create(
name=report.title,
title=report.title,
dtype=report.dtype,
summary=report.description or "",
disaster_start_date=report.start_date,
Expand Down
14 changes: 7 additions & 7 deletions api/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ class EventTest(TestCase):

def setUp(self):
dtype = models.DisasterType.objects.get(pk=1)
models.Event.objects.create(name="disaster1", summary="test disaster", dtype=dtype)
event = models.Event.objects.create(name="disaster2", summary="another test disaster", dtype=dtype)
models.Event.objects.create(title="disaster1", summary="test disaster", dtype=dtype)
event = models.Event.objects.create(title="disaster2", summary="another test disaster", dtype=dtype)
models.KeyFigure.objects.create(event=event, number=7, deck="things", source="website")
models.Snippet.objects.create(event=event, snippet="this is a snippet")

def test_disaster_create(self):
obj1 = models.Event.objects.get(name="disaster1")
obj2 = models.Event.objects.get(name="disaster2")
obj1 = models.Event.objects.get(title="disaster1")
obj2 = models.Event.objects.get(title="disaster2")
self.assertEqual(obj1.summary, "test disaster")
self.assertEqual(obj2.summary, "another test disaster")
keyfig = obj2.key_figures.all()
Expand Down Expand Up @@ -68,7 +68,7 @@ def test_profile_create(self):
class AppealTest(APITestCase):
def setUp(self):
# An appeal with needs_confirmation=True should not return the event in the API response.
event = models.Event.objects.create(name="associated event", summary="foo")
event = models.Event.objects.create(title="associated event", summary="foo")
country = models.Country.objects.create(name="country")
models.Appeal.objects.create(
aid="test1", name="appeal", atype=1, code="abc", needs_confirmation=True, event=event, country=country
Expand All @@ -87,13 +87,13 @@ class FieldReportTest(TestCase):

def setUp(self):
dtype = models.DisasterType.objects.get(pk=1)
event = models.Event.objects.create(name="disaster1", summary="test disaster", dtype=dtype)
event = models.Event.objects.create(title="disaster1", summary="test disaster", dtype=dtype)
country = models.Country.objects.create(name="country")
report = models.FieldReport.objects.create(rid="test1", event=event, dtype=dtype)
report.countries.add(country)

def test_field_report_create(self):
event = models.Event.objects.get(name="disaster1")
event = models.Event.objects.get(title="disaster1")
country = models.Country.objects.get(name="country")
self.assertEqual(event.field_reports.all()[0].countries.all()[0], country)
obj = models.FieldReport.objects.get(rid="test1")
Expand Down
Loading

0 comments on commit d590fa6

Please sign in to comment.