Skip to content

Commit

Permalink
Feat cabi message csv (#232)
Browse files Browse the repository at this point in the history
* model to send prise message schedule

* add prise message to csv

* add priority to message schedule

* add tests

* add test generator

* add test

* add export to json of farm_group_fields

* fix flake

* remove phone number from message template
  • Loading branch information
danangmassandy authored Oct 28, 2024
1 parent f9636b3 commit d41f1bf
Show file tree
Hide file tree
Showing 20 changed files with 794 additions and 55 deletions.
25 changes: 24 additions & 1 deletion django_project/gap/admin/farm.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
.. note:: Farms admin
"""

import json
from django.contrib import admin, messages
from django.utils.html import format_html
from django.http import HttpResponse
from django.core.serializers.json import DjangoJSONEncoder

from core.admin import AbstractDefinitionAdmin
from gap.models import (
Expand All @@ -30,6 +33,24 @@ def recreate_farm_group_fields(modeladmin, request, queryset):
group.prepare_fields()


@admin.action(description='Download fields as json')
def download_farm_group_fields(modeladmin, request, queryset):
"""Download farm group fields."""
data = {}
for group in queryset.all():
fields = group.farmgroupcropinsightfield_set.all()
fields_to_include = ['field', 'column_number', 'label', 'active']
data[group.name] = list(fields.values(*fields_to_include))

# Convert the data to JSON
response_data = json.dumps(data, cls=DjangoJSONEncoder)

# Create the HttpResponse with the correct content_type for JSON
response = HttpResponse(response_data, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename=farm_groups.json'
return response


@admin.action(description='Run crop insight')
def run_crop_insight(modeladmin, request, queryset):
"""Run crop insight."""
Expand All @@ -46,7 +67,9 @@ class FarmGroupAdmin(AbstractDefinitionAdmin):

filter_horizontal = ('farms', 'users')
inlines = (FarmGroupCropInsightFieldInline,)
actions = (recreate_farm_group_fields, run_crop_insight)
actions = (
recreate_farm_group_fields, run_crop_insight,
download_farm_group_fields)
readonly_fields = ('displayed_headers',)

def farm_count(self, obj: FarmGroup):
Expand Down
6 changes: 4 additions & 2 deletions django_project/gap/fixtures/10.pest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"description": "Beanfly (On bean)",
"scientific_name": "Ophiomyia",
"taxonomic_rank": "genus",
"link": "https://en.wikipedia.org/wiki/Ophiomyia"
"link": "https://en.wikipedia.org/wiki/Ophiomyia",
"short_name": "bean_fly"
}
},
{
Expand All @@ -18,7 +19,8 @@
"description": "Fall Armyworm (on maize and other hosts)",
"scientific_name": "Spodoptera frugiperda",
"taxonomic_rank": "species",
"link": "https://en.wikipedia.org/wiki/Fall_armyworm"
"link": "https://en.wikipedia.org/wiki/Fall_armyworm",
"short_name": "faw"
}
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.2.7 on 2024-10-28 06:39

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('gap', '0034_pest_link_pest_scientific_name_pest_taxonomic_rank'),
]

operations = [
migrations.AlterField(
model_name='collectorsession',
name='ingestor_type',
field=models.CharField(choices=[('Tahmo', 'Tahmo'), ('Farm', 'Farm'), ('CBAM', 'CBAM'), ('Salient', 'Salient'), ('Tomorrow.io', 'Tomorrow.io'), ('Arable', 'Arable'), ('Grid', 'Grid'), ('Tahmo API', 'Tahmo API'), ('Tio Forecast Collector', 'Tio Forecast Collector'), ('WindBorne Systems API', 'WindBorne Systems API'), ('Cabi Prise Excel', 'Cabi Prise Excel')], default='Tahmo', max_length=512),
),
migrations.AlterField(
model_name='ingestorsession',
name='ingestor_type',
field=models.CharField(choices=[('Tahmo', 'Tahmo'), ('Farm', 'Farm'), ('CBAM', 'CBAM'), ('Salient', 'Salient'), ('Tomorrow.io', 'Tomorrow.io'), ('Arable', 'Arable'), ('Grid', 'Grid'), ('Tahmo API', 'Tahmo API'), ('Tio Forecast Collector', 'Tio Forecast Collector'), ('WindBorne Systems API', 'WindBorne Systems API'), ('Cabi Prise Excel', 'Cabi Prise Excel')], default='Tahmo', max_length=512),
),
]
18 changes: 18 additions & 0 deletions django_project/gap/migrations/0036_pest_short_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.7 on 2024-10-28 06:46

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('gap', '0035_alter_collectorsession_ingestor_type_and_more'),
]

operations = [
migrations.AddField(
model_name='pest',
name='short_name',
field=models.CharField(blank=True, max_length=20, null=True),
),
]
20 changes: 20 additions & 0 deletions django_project/gap/models/crop_insight.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from gap.models.lookup import RainfallClassification
from gap.models.measurement import DatasetAttribute
from gap.models.preferences import Preferences
from gap.models.pest import Pest
from spw.models import SPWOutput

User = get_user_model()
Expand Down Expand Up @@ -387,9 +388,16 @@ def forecast_fields_used():
'rainAccumulationType'
]

@staticmethod
def prise_message_key(pest: Pest, field_num):
"""Return key for prise message field."""
return f'prise_{pest.short_name}_{field_num}'

@property
def data(self) -> dict:
"""Return the data."""
from prise.generator import generate_prise_message

# ---------------------------------------
# Spw data
spw_top_message = ''
Expand Down Expand Up @@ -464,6 +472,18 @@ def data(self) -> dict:
day_n, 'rainAccumulationType'
)
] = _class.name

# ----------------------------------------
# Prise message
for pest in Pest.objects.all():
prise_messages = (
generate_prise_message(self.farm, pest, self.generated_date)
)
for idx, prise_message in enumerate(prise_messages):
output[
CropPlanData.prise_message_key(pest, idx + 1)
] = prise_message

return output


Expand Down
20 changes: 20 additions & 0 deletions django_project/gap/models/farm_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def save(self, *args, **kwargs):
def prepare_fields(self):
"""Prepare fields."""
from gap.models.crop_insight import CropPlanData
from gap.models.pest import Pest
from gap.providers.tio import TomorrowIODatasetReader
TomorrowIODatasetReader.init_provider()

Expand Down Expand Up @@ -94,6 +95,25 @@ def prepare_fields(self):
)
column_num += 1

# create message for pest recommendation
for pest in Pest.objects.all():
# reserve 5 message columns for each pest
max_pest_message = 5
active = False # enable only for Kalro in admin
for idx in range(max_pest_message):
field = CropPlanData.prise_message_key(pest, idx + 1)
FarmGroupCropInsightField.objects.update_or_create(
farm_group=self,
field=field,
defaults={
'column_number': column_num,
'label': None,
'active': active
}
)
column_num += 1


@property
def headers(self):
"""Return headers."""
Expand Down
4 changes: 4 additions & 0 deletions django_project/gap/models/pest.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,7 @@ class Pest(Definition):
link = models.URLField(
null=True, blank=True
)
short_name = models.CharField(
max_length=20,
null=True, blank=True
)
Loading

0 comments on commit d41f1bf

Please sign in to comment.