Skip to content

Commit aa3d4c7

Browse files
authored
Merge pull request #2068 from IFRCGo/fix/country-page
Fix/country page
2 parents 832e0a8 + f2048e7 commit aa3d4c7

20 files changed

+354
-166
lines changed

Population.GO.Admin1.Matched.xlsx

232 KB
Binary file not shown.

api/drf_views.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@
6363
UserCountry,
6464
CountryOfFieldReportToReview,
6565
Export,
66-
GDACSEvent,
6766
CountryKeyDocument,
6867
AppealType,
6968
CountrySupportingPartner
@@ -123,7 +122,6 @@
123122
GoHistoricalSerializer,
124123
CountryOfFieldReportToReviewSerializer,
125124
ExportSerializer,
126-
GDACSEventSerializer,
127125
CountryKeyDocumentSerializer,
128126
CountryKeyFigureInputSerializer,
129127
CountryDisasterTypeCountSerializer,
@@ -149,7 +147,6 @@
149147
AppealDocumentFilter,
150148
FieldReportFilter,
151149
GoHistoricalFilter,
152-
GDACSEventFileterSet,
153150
CountryKeyDocumentFilter,
154151
CountrySupportingPartnerFilter
155152
)
@@ -1272,16 +1269,6 @@ def get_queryset(self):
12721269
return Export.objects.filter(requested_by=user).distinct()
12731270

12741271

1275-
class GDACSEventViewSet(viewsets.ReadOnlyModelViewSet):
1276-
serializer_class = GDACSEventSerializer
1277-
filterset_class = GDACSEventFileterSet
1278-
1279-
def get_queryset(self):
1280-
today = timezone.now()
1281-
thirty_days_before = today + timedelta(days=-30)
1282-
return GDACSEvent.objects.filter(publication_date__gte=thirty_days_before)
1283-
1284-
12851272
class CountrySupportingPartnerViewSet(viewsets.ModelViewSet):
12861273
serializer_class = CountrySupportingPartnerSerializer
12871274
filterset_class = CountrySupportingPartnerFilter

api/filter_set.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
AppealHistory,
2020
AppealDocument,
2121
FieldReport,
22-
GDACSEvent,
2322
CountryKeyDocument,
2423
CountrySupportingPartner
2524

@@ -332,27 +331,6 @@ class Meta:
332331
fields = ()
333332

334333

335-
class GDACSEventFileterSet(filters.FilterSet):
336-
countries = filters.ModelMultipleChoiceFilter(
337-
field_name="countries",
338-
queryset=Country.objects.all(),
339-
widget=filters.widgets.CSVWidget,
340-
method='filter_countries'
341-
)
342-
disaster_type = filters.NumberFilter(field_name="disaster_type", lookup_expr="exact")
343-
publication_date__lte = filters.DateFilter(field_name="publication_date", lookup_expr="lte", input_formats=["%Y-%m-%d"])
344-
publication_date__gte = filters.DateFilter(field_name="publication_date", lookup_expr="gte", input_formats=["%Y-%m-%d"])
345-
346-
class Meta:
347-
model = GDACSEvent
348-
fields = ()
349-
350-
def filter_countries(self, queryset, name, country):
351-
if len(country):
352-
return queryset.filter(countries__in=country).distinct()
353-
return queryset
354-
355-
356334
class CountrySupportingPartnerFilter(filters.FilterSet):
357335
country = filters.ModelMultipleChoiceFilter(field_name="country", queryset=Country.objects.all())
358336

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import pandas as pd
2+
3+
from django.core.management.base import BaseCommand
4+
5+
from api.models import Country, District
6+
from api.logger import logger
7+
8+
9+
class Command(BaseCommand):
10+
help = "Population Data for District To run, python manage.py ingest_admin1_population Population.GO.Admin1.Matched.xlsx"
11+
12+
def add_arguments(self, parser):
13+
parser.add_argument("filename", nargs="+", type=str)
14+
15+
def handle(self, *args, **kwargs):
16+
logger.info("Updating population data for District")
17+
filename = kwargs["filename"][0]
18+
district_df = pd.read_excel(filename, usecols=['GO Names', 'ISO3', '2016'])
19+
district_df = district_df.rename(columns={'GO Names': 'District'})
20+
count = 0
21+
for index, row in district_df.iterrows():
22+
district = District.objects.filter(name=row['District'].strip(), country__iso3=row['ISO3']).first()
23+
if district:
24+
count += 1
25+
district.wb_population = row['2016']
26+
district.wb_year = '2016' # Get this from excel file
27+
district.save(update_fields=['wb_population', 'wb_year'])
28+
logger.info(f'Updated population data for {count} district')
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Generated by Django 3.2.24 on 2024-03-11 10:44
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
dependencies = [
9+
('api', '0206_alter_export_export_type'),
10+
]
11+
12+
operations = [
13+
migrations.AddField(
14+
model_name='export',
15+
name='per_country',
16+
field=models.IntegerField(blank=True, null=True, verbose_name='Per Country Id'),
17+
),
18+
migrations.AlterField(
19+
model_name='export',
20+
name='export_type',
21+
field=models.CharField(choices=[('dref-applications', 'Dref Applications'), ('dref-operational-updates', 'Dref Operational Updates'), ('dref-final-reports', 'Dref Final Reports'), ('per', 'Per')], max_length=255, verbose_name='Export Type'),
22+
),
23+
]

api/models.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2454,7 +2454,7 @@ class ExportType(models.TextChoices):
24542454
DREF = 'dref-applications', _('Dref Applications')
24552455
OPS_UPDATE = 'dref-operational-updates', _('Dref Operational Updates')
24562456
FINAL_REPORT = 'dref-final-reports', _('Dref Final Reports')
2457-
PER = 'per-process', _('Per Process')
2457+
PER = 'per', _('Per')
24582458

24592459
export_id = models.IntegerField(verbose_name=_('Export Id'))
24602460
export_type = models.CharField(
@@ -2492,6 +2492,11 @@ class ExportType(models.TextChoices):
24922492
null=True, blank=True,
24932493
on_delete=models.SET_NULL,
24942494
)
2495+
per_country = models.IntegerField(
2496+
verbose_name=_('Per Country Id'),
2497+
null=True,
2498+
blank=True
2499+
)
24952500

24962501
def __str__(self):
24972502
return f'{self.url} - {self.token}'

api/serializers.py

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@
5555
CountryOfFieldReportToReview,
5656
Export,
5757
UserCountry,
58-
GDACSEvent,
5958
CountryDirectory,
6059
CountryKeyDocument,
6160
NSDInitiatives,
@@ -2358,6 +2357,7 @@ class Meta:
23582357
def create(self, validated_data):
23592358
export_id = validated_data.get('export_id')
23602359
export_type = validated_data.get('export_type')
2360+
country_id = validated_data.get('per_country')
23612361
if export_type == Export.ExportType.DREF:
23622362
title = Dref.objects.filter(
23632363
id=export_id
@@ -2378,7 +2378,10 @@ def create(self, validated_data):
23782378
else:
23792379
title = "Export"
23802380
user = self.context['request'].user
2381-
validated_data['url'] = f'https://{settings.FRONTEND_URL}/{export_type}/{export_id}/export/'
2381+
if export_type == Export.ExportType.PER:
2382+
validated_data['url'] = f'https://{settings.FRONTEND_URL}/countries/{country_id}/{export_type}/{export_id}/export/'
2383+
else:
2384+
validated_data['url'] = f'https://{settings.FRONTEND_URL}/{export_type}/{export_id}/export/'
23822385
validated_data['requested_by'] = user
23832386
export = super().create(validated_data)
23842387
if export.url:
@@ -2395,24 +2398,6 @@ def update(self, instance, validated_data):
23952398
raise serializers.ValidationError("Update is not allowed")
23962399

23972400

2398-
class GDACSEventSerializer(serializers.ModelSerializer):
2399-
population_value = serializers.IntegerField()
2400-
countries = MiniCountrySerializer(many=True)
2401-
disaster_type = DisasterTypeSerializer()
2402-
class Meta:
2403-
model = GDACSEvent
2404-
fields = (
2405-
"id",
2406-
"eventid",
2407-
"title",
2408-
"countries",
2409-
"population_unit",
2410-
"population_value",
2411-
"disaster_type",
2412-
"publication_date"
2413-
)
2414-
2415-
24162401
class CountrySupportingPartnerSerializer(serializers.ModelSerializer):
24172402
supporting_type_display = serializers.CharField(
24182403
source="get_supporting_type_display",

databank/management/commands/ingest_climate.py

Lines changed: 33 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -13,66 +13,42 @@
1313
class Command(BaseCommand):
1414
help = 'Add minimum, maximum and Average temperature of country temperature data from source api'
1515

16-
def add_arguments(self, parser):
17-
parser.add_argument(
18-
'--start_date',
19-
action='store',
20-
help='Start date to fetch temperature data in the format YYYY-MM-DD'
21-
)
22-
parser.add_argument(
23-
'--end_date',
24-
action='store',
25-
help='End date to fetch temperature data in the format YYYY-MM-DD'
26-
)
2716

2817
def handle(self, *args, **options):
29-
for co in CountryOverview.objects.filter(country__record_type=CountryType.COUNTRY).all():
30-
centroid = getattr(co.country, 'centroid', None)
31-
if centroid:
32-
centroid = json.loads(centroid.geojson)
33-
34-
lat = centroid.get("coordinates", [])[1]
35-
lon = centroid.get("coordinates", [])[0]
36-
if options['start_date'] and options['end_date']:
37-
response = requests.get(f'https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}&start_date={options["start_date"]}&end_date={options["end_date"]}&daily=temperature_2m_max,temperature_2m_min,temperature_2m_mean,precipitation_sum,precipitation_hours')
38-
else:
39-
response = requests.get(f'https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}&start_date=2023-01-01&end_date=2023-12-31&daily=temperature_2m_max,temperature_2m_min,temperature_2m_mean,precipitation_sum,precipitation_hours')
40-
if response.status_code != 200:
41-
continue
18+
for co in CountryOverview.objects.filter(country__record_type=CountryType.COUNTRY, country__iso3__isnull=False).all():
19+
country_iso3 = co.country.iso3
20+
if country_iso3:
21+
response = requests.get(f'https://climateknowledgeportal.worldbank.org/api/v1/cru-x0.5_climatology_tasmin,tas,tasmax,pr_climatology_monthly_1991-2020_mean_historical_cru_ts4.07_mean/{country_iso3}?_format=json')
4222
response.raise_for_status()
43-
try:
44-
data = response.json()
45-
daily_data = data.get('daily', {})
46-
if daily_data:
47-
monthly_temperatures = defaultdict(list)
48-
49-
for i, date_str in enumerate(daily_data.get('time', [])):
50-
max_temp = daily_data.get('temperature_2m_max')[i]
51-
min_temp = daily_data.get('temperature_2m_min')[i]
52-
precipitation = daily_data.get('precipitation_sum')[i]
53-
if date_str and max_temp is not None and min_temp is not None:
54-
date = datetime.strptime(date_str, '%Y-%m-%d')
55-
month_key = (date.year, date.month)
56-
monthly_temperatures[month_key].append((max_temp, min_temp, precipitation))
57-
# Calculate min, max, and avg temperatures for each month
58-
for month_key, temps in monthly_temperatures.items():
59-
year, month = month_key
60-
max_temp_monthly = max(temps, key=lambda x: x[0])[0]
61-
min_temp_monthly = min(temps, key=lambda x: x[1])[1]
62-
avg_temp_monthly = (max_temp_monthly + min_temp_monthly) / 2
63-
precipitation_monthly = sum([x[2] for x in temps])
64-
23+
try:
24+
response_data = response.json()
25+
data = response_data.get('data', {})
26+
if data:
27+
precipation = data.get('pr', {})
28+
average_temp = data.get('tas', {})
29+
min_temp = data.get('tasmin', {})
30+
max_temp = data.get('tasmax', {})
31+
merged_data = {
32+
country: {
33+
date: (precipation[country][date], average_temp[country][date], min_temp[country][date], max_temp[country][date])
34+
for date in precipation[country]
35+
} for country in precipation
36+
}
37+
for key , value in merged_data.items():
38+
for k, v in value.items():
39+
year_month = k.split('-')
40+
data = {
41+
'year': year_month[0],
42+
'month': year_month[1],
43+
'max_temp' : v[3],
44+
'min_temp' : v[2],
45+
'avg_temp': v[1],
46+
'precipitation' :v[0]
47+
}
6548
CountryKeyClimate.objects.create(
6649
overview=co,
67-
year=year,
68-
month=month,
69-
max_temp=max_temp_monthly,
70-
min_temp=min_temp_monthly,
71-
avg_temp=avg_temp_monthly,
72-
precipitation=precipitation_monthly
50+
**data
7351
)
74-
logger.info('Minimum, maximum and Average temperature of country temperature data added successfully')
75-
76-
except Exception as ex:
77-
logger.error(f'Error in ingesting climate data: {ex}')
78-
continue
52+
except Exception as ex:
53+
logger.error(f'Error in ingesting climate data',exc_info=True)
54+
continue

databank/management/commands/ingest_worldbank.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ def handle(self, *args, **kwargs):
5252
'page': page,
5353
})
5454
except requests.exceptions.HTTPError as err:
55-
print(err.response.text)
5655
continue
5756
try:
5857
data_list = response.json()[1]
@@ -94,8 +93,8 @@ def handle(self, *args, **kwargs):
9493
overview.world_bank_gni = indicators[5][0]
9594
overview.world_bank_gender_inequality_index = indicators[6][0]
9695
overview.world_bank_life_expectancy = indicators[7][0]
97-
overview.world_bank_literacy_rate = indicators[0][0]
98-
overview.world_bank_poverty_rate = indicators[1][0]
96+
overview.world_bank_literacy_rate = indicators[8][0]
97+
overview.world_bank_poverty_rate = indicators[9][0]
9998
overview.save(
10099
update_fields=[
101100
'world_bank_population',

deploy/helm/ifrcgo-helm/values.yaml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,7 @@ cronjobs:
119119
schedule: '1 0 * * *'
120120
- command: 'update_surge_alert_status'
121121
schedule: '1 */12 * * *'
122-
- command: 'ingest_gdacs'
123-
schedule: '1 */12 * * *'
122+
124123

125124
elasticsearch:
126125
enabled: true

0 commit comments

Comments
 (0)