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 Oct 7, 2024
1 parent bc71f17 commit 171a66e
Show file tree
Hide file tree
Showing 12 changed files with 623 additions and 792 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
Original file line number Diff line number Diff line change
@@ -1,15 +1,40 @@
# Generated by Django 4.2.15 on 2024-09-13 08:21
# Generated by Django 4.2.16 on 2024-10-07 18:46

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('api', '0213_merge_20240807_1001'),
('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',
Expand Down
41 changes: 24 additions & 17 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
# 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 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 +753,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 +848,15 @@ def record_type(self):
def to_dict(self):
return to_dict(self)

def generate_formatted_name(self):
for translation in AVAILABLE_LANGUAGES:
activate(translation)
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")
self.name = f"{country_iso3}: {dtype} - {start_date} - {self.title}"
deactivate()

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

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

self.generate_formatted_name()

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

def __str__(self):
Expand Down Expand Up @@ -1648,22 +1662,15 @@ class Meta:
# 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
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)
for translation in AVAILABLE_LANGUAGES:
activate(translation)
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__iso3=country_iso3).count() + 1
date = timezone.now().strftime("%Y-%m-%d")
self.summary = f"{country_iso3}: {dtype} - {start_date} {self.title} #{field_report_number} ({date})"
deactivate()

def save(self, *args, **kwargs):
# On save, is report_date or start_date is not set, set it to now.
Expand Down
24 changes: 23 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,19 @@ 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.
"""
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.
"""
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 @@ -2024,7 +2026,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
21 changes: 10 additions & 11 deletions api/test_views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import json

from django.contrib.auth.models import User

import api.models as models
Expand All @@ -13,7 +11,7 @@
from api.factories.field_report import FieldReportFactory
from api.models import Profile, VisibilityChoices
from deployments.factories.user import UserFactory
from main.test_case import APITestCase, SnapshotTestCase
from main.test_case import APITestCase


class GuestUserPermissionTest(APITestCase):
Expand Down Expand Up @@ -254,20 +252,21 @@ def test_get_auth(self):
self.assertIsNotNone(response.get("expires"))


class EventSnaphostTest(SnapshotTestCase):
class EventApiTest(APITestCase):

def test_event_featured_document_api(self):
event = EventFactory()
EventFeaturedDocumentFactory.create_batch(5, event=event)
resp = self.client.get(f"/api/v2/event/{event.id}/")
self.assertEqual(resp.status_code, 200)
self.assertMatchSnapshot(json.loads(resp.content))
self.assertEqual(len(resp.json()["featured_documents"]), 5)

def test_event_link_api(self):
event = EventFactory()
EventLinkFactory.create_batch(5, event=event)
resp = self.client.get(f"/api/v2/event/{event.id}/")
self.assertEqual(resp.status_code, 200)
self.assertMatchSnapshot(json.loads(resp.content))
self.assertEqual(len(resp.json()["links"]), 5)


class SituationReportTypeTest(APITestCase):
Expand All @@ -278,7 +277,7 @@ def test_sit_rep_types(self):
type1 = models.SituationReportType.objects.create(type="Lyric")
type2 = models.SituationReportType.objects.create(type="Epic")
dtype1 = models.DisasterType.objects.get(pk=1)
event1 = models.Event.objects.create(name="disaster1", summary="test disaster1", dtype=dtype1)
event1 = models.Event.objects.create(title="disaster1", summary="test disaster1", dtype=dtype1)

models.SituationReport.objects.create(name="test1", event=event1, type=type1, visibility=3)
models.SituationReport.objects.create(name="test2", event=event1, type=type2, visibility=3)
Expand Down Expand Up @@ -311,7 +310,7 @@ def test_create_and_update(self):
body = {
"countries": [country1.id, country2.id],
"dtype": 7,
"summary": "test",
"title": "test",
"description": "this is a test description",
"bulletin": "3",
"num_assisted": 100,
Expand Down Expand Up @@ -351,12 +350,12 @@ def test_create_and_update(self):
self.assertEqual(created.contacts.count(), 1)
self.assertEqual(created.visibility, models.VisibilityChoices.IFRC)
self.assertEqual(created.dtype.id, 7)
self.assertEqual(created.summary, "test")
self.assertEqual(created.title, "test")
# Translated field test
self.assertEqual(created.summary_en, "test")
self.assertEqual(created.title_en, "test")

# created an emergency automatically
self.assertEqual(created.event.name, "test")
self.assertEqual(created.event.title, "test")
# event_pk = created.event.id

# body['countries'] = [country2.id]
Expand Down
2 changes: 1 addition & 1 deletion api/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class DisasterTypeTO(TranslationOptions):

@register(Event)
class EventTO(TranslationOptions):
fields = ("name", "summary")
fields = ("name", "summary", "title")
skip_fields = ("name",) # XXX: CUSTOM field Not used by TranslationOptions, but used in lang/tasks.py


Expand Down
Loading

0 comments on commit 171a66e

Please sign in to comment.