Skip to content

Commit

Permalink
Merge pull request #1537 from the-deep/fix/geo-area-failure-status-tr…
Browse files Browse the repository at this point in the history
…igger

Add status in geo area
  • Loading branch information
AdityaKhatri authored Dec 5, 2024
2 parents 1dd8a6c + 42c5648 commit b265ccd
Show file tree
Hide file tree
Showing 8 changed files with 111 additions and 2 deletions.
19 changes: 19 additions & 0 deletions apps/geo/enums.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import graphene
from geo.models import Region

from utils.graphene.enums import (
convert_enum_to_graphene_enum,
get_enum_name_from_django_field,
)


class GeoAreaOrderingEnum(graphene.Enum):
Expand All @@ -8,3 +14,16 @@ class GeoAreaOrderingEnum(graphene.Enum):
# DESC
DESC_ID = f'-{ASC_ID}'
DESC_ADMIN_LEVEL = f'-{ASC_ADMIN_LEVEL}'


RegionStatusEnum = convert_enum_to_graphene_enum(
Region.Status, name='RegionStatusEnum'
)


enum_map = {
get_enum_name_from_django_field(field): enum
for field, enum in (
(Region.status, RegionStatusEnum),
)
}
18 changes: 18 additions & 0 deletions apps/geo/migrations/0044_region_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.2.25 on 2024-12-05 04:25

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('geo', '0043_create-unaccent_extension'),
]

operations = [
migrations.AddField(
model_name='region',
name='status',
field=models.PositiveSmallIntegerField(choices=[(0, 'Initiated'), (1, 'Pending'), (2, 'Completed'), (3, 'Failed')], default=1),
),
]
6 changes: 6 additions & 0 deletions apps/geo/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@


class Region(UserResource):
class Status(models.IntegerChoices):
INITIATED = 0, 'Initiated'
PENDING = 1, 'Pending'
COMPLETED = 2, 'Completed'
FAILED = 3, 'Failed'
"""
Region model
Expand All @@ -35,6 +40,7 @@ class Region(UserResource):
cache_index = models.SmallIntegerField(default=0) # Used to track cache update.
centroid = models.PointField(blank=True, null=True) # Admin level 0 centroid
geo_options = models.JSONField(default=None, blank=True, null=True)
status = models.PositiveSmallIntegerField(choices=Status.choices, default=Status.PENDING)

def __init__(self, *args, **kwargs):
self.id: Union[int, None]
Expand Down
40 changes: 40 additions & 0 deletions apps/geo/mutations.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from geo.tasks import load_geo_areas
import graphene

from geo.models import Region, AdminLevel
Expand Down Expand Up @@ -134,10 +135,49 @@ def mutate(root, info, id):
return PublishRegion(result=instance, errors=None, ok=True)


class ReTriggeredFailedRegion(graphene.Mutation):
class Arguments:
region_id = graphene.ID(required=True)
model = Region
errors = graphene.List(graphene.NonNull(CustomErrorType))
ok = graphene.Boolean()
result = graphene.Field(RegionType)

@staticmethod
def mutate(root, info, region_id):
instance = Region.objects.filter(
id=region_id
).first()
error_data = []
if instance is None:
error_data.append('Region does\'t exist')
elif instance.status == Region.Status.COMPLETED:
error_data.append('Geo Area already generated')
elif instance.created_by != info.context.user:
error_data.append('Authorized User only update region')
elif instance.is_published:
error_data.append("Published Region cannot be retiggered")

if error_data:
return ReTriggeredFailedRegion(errors=[
dict(
field='nonFieldErrors',
messages=error_data
)
], ok=False)
load_geo_areas(region_id)
return ReTriggeredFailedRegion(
result=instance,
error=None,
ok=True
)


class Mutation():
create_region = CreateRegion.Field()
update_region = UpdateRegion.Field()
create_admin_level = CreateAdminLevel.Field()
publish_region = PublishRegion.Field()
update_admin_level = UpdateAdminLevel.Field()
delete_admin_level = DeleteAdminLevel.Field()
retrigger_region = ReTriggeredFailedRegion.Field()
5 changes: 4 additions & 1 deletion apps/geo/schema.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from geo.enums import RegionStatusEnum
import graphene
from graphene_django import DjangoObjectType
from graphene_django_extras import DjangoObjectField, PageGraphqlPagination
Expand Down Expand Up @@ -53,12 +54,14 @@ def get_custom_queryset(queryset, info, **kwargs):


class RegionType(DjangoObjectType, ClientIdMixin):
status = graphene.Field(RegionStatusEnum)

class Meta:
model = Region
only_fields = (
'id', 'title', 'public', 'regional_groups',
'key_figures', 'population_data', 'media_sources',
'centroid', 'is_published',
'centroid', 'is_published', 'status'
)

@staticmethod
Expand Down
1 change: 1 addition & 0 deletions apps/geo/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ def create(self, validated_data):
admin_level.save()

region = admin_level.region
region.status = Region.Status.INITIATED
region.modified_by = self.context['request'].user
region.save()

Expand Down
8 changes: 7 additions & 1 deletion apps/geo/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,13 +210,19 @@ def load_geo_areas(region_id):
have_lock = lock.acquire(blocking=False)
if not have_lock:
return False

region = Region.objects.filter(id=region_id).first()
if not region:
logger.error("Region not found", exc_info=True)
return False
try:
return_value = _load_geo_areas(region_id)
region.status = Region.Status.COMPLETED
except Exception:
logger.error('Load Geo Areas', exc_info=True)
return_value = False
region.status = Region.Status.FAILED

region.save()
lock.release()
return return_value

Expand Down
16 changes: 16 additions & 0 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -5124,6 +5124,7 @@ type Mutation {
publishRegion(id: ID!): PublishRegion
updateAdminLevel(data: AdminLevelInputType!, id: ID!): UpdateAdminLevel
deleteAdminLevel(adminLevelId: ID!): DeleteAdminLevel
retriggerRegion(regionId: ID!): ReTriggeredFailedRegion
organizationCreate(data: OrganizationInputType!): OrganizationCreate
createAssessmentRegSummaryIssue(data: AssessmentRegistrySummaryIssueCreateInputType!): AssessmentRegistryCreateIssue
fileUpload(data: FileUploadInputType!): UploadFile
Expand Down Expand Up @@ -5970,6 +5971,12 @@ type QuestionType {
subSectorDisplay: EnumDescription
}

type ReTriggeredFailedRegion {
errors: [GenericScalar!]
ok: Boolean
result: RegionType
}

type RecentActivityType {
id: ID!
createdAt: DateTime
Expand Down Expand Up @@ -6004,6 +6011,7 @@ type RegionDetailType {
mediaSources: GenericScalar
centroid: PointScalar
clientId: ID!
status: RegionStatusEnum
adminLevels: [AdminLevelType!]!
}

Expand Down Expand Up @@ -6043,6 +6051,13 @@ input RegionProjectFilterData {
isTest: Boolean
}

enum RegionStatusEnum {
INITIATED
PENDING
COMPLETED
FAILED
}

type RegionType {
id: ID!
title: String!
Expand All @@ -6053,6 +6068,7 @@ type RegionType {
populationData: GenericScalar
mediaSources: GenericScalar
centroid: PointScalar
status: RegionStatusEnum
clientId: ID!
}

Expand Down

0 comments on commit b265ccd

Please sign in to comment.