Skip to content

Commit

Permalink
Add update mutation and add test cases
Browse files Browse the repository at this point in the history
* Optimize testcases and error messages
  • Loading branch information
sudan45 authored and AdityaKhatri committed Aug 16, 2024
1 parent 78b2a24 commit 3013525
Show file tree
Hide file tree
Showing 5 changed files with 190 additions and 116 deletions.
60 changes: 41 additions & 19 deletions apps/geo/mutations.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import graphene
from django.utils.translation import gettext

from geo.models import Region, AdminLevel
from geo.schema import RegionType, RegionDetailType, AdminLevelType
Expand Down Expand Up @@ -29,7 +28,7 @@ class Arguments:
@classmethod
def check_permissions(cls, info, **_):
return True # global permission is always true
# NOTE: Region permission is checked using serializers
# NOTE: Project permission is checked using serializers


class CreateAdminLevel(GrapheneMutation):
Expand All @@ -45,6 +44,19 @@ def check_permissions(cls, info, **_):
# NOTE: Region permission is checked using serializers


class UpdateRegion(GrapheneMutation):
class Arguments:
data = RegionInputType(required=True)
id = graphene.ID(required=True)
model = Region
serializer_class = RegionGqSerializer
result = graphene.Field(RegionDetailType)

@classmethod
def check_permissions(cls, info, **_):
return True # global permission is always true


class UpdateAdminLevel(GrapheneMutation):
class Arguments:
data = AdminLevelInputType(required=True)
Expand All @@ -68,21 +80,26 @@ class Arguments:

@staticmethod
def mutate(root, info, admin_level_id):
admin_level_qs = AdminLevel.objects.filter(
admin_level = AdminLevel.objects.filter(
id=admin_level_id,
region__is_published=False
)
if not admin_level_qs:
).first()

error_data = []
if admin_level is None:
error_data.append("AdminLevel doesn't exist")
elif admin_level.region.created_by_id != info.context.user.id:
error_data.append("Only region owner can delete admin level")
elif admin_level.region.is_published:
error_data.append("Published region can't be changed. Please contact system admin")
if error_data:
return DeleteAdminLevel(errors=[
dict(
field='nonFieldErrors',
messages=gettext(
'You should be Region owner to delete admin level or region is published'
),
messages=error_data
)
], ok=False)
admin_level_qs.delete()
return DeleteAdminLevel(result=admin_level_qs, errors=None, ok=True)
admin_level.delete()
return DeleteAdminLevel(errors=None, ok=True)


class PublishRegion(graphene.Mutation):
Expand All @@ -95,27 +112,32 @@ class Arguments:

@staticmethod
def mutate(root, info, id):
try:
instance = Region.objects.get(
created_by=info.context.user,
id=id
)
except Region.DoesNotExist:
instance = Region.objects.filter(
id=id
).first()

error_data = []
if instance is None:
error_data.append('Region does\'t exist')
elif instance.created_by != info.context.user:
error_data.append('Authorized User can only published the region')
if error_data:
return PublishRegion(errors=[
dict(
field='nonFieldErrors',
messages="Authorized User can only published the region"
messages=error_data
)
], ok=False)

instance.is_published = True
instance.save(update_fields=['is_published'])
return PublishRegion(result=instance, errors=None, ok=True)


class Mutation():
create_region = CreateRegion.Field()
update_region = UpdateRegion.Field()
create_admin_level = CreateAdminLevel.Field()
publish_region = PublishRegion.Field()
create_admin_level = CreateAdminLevel.Field()
update_admin_level = UpdateAdminLevel.Field()
delete_admin_level = DeleteAdminLevel.Field()
2 changes: 1 addition & 1 deletion apps/geo/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def get_geo_area_queryset_for_project_geo_area_type(queryset=None, defer_fields=
return _queryset


class AdminLevelType(DjangoObjectType):
class AdminLevelType(DjangoObjectType, ClientIdMixin):
class Meta:
model = AdminLevel
only_fields = (
Expand Down
37 changes: 9 additions & 28 deletions apps/geo/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from drf_dynamic_fields import DynamicFieldsMixin

from deep.serializers import (
ProjectPropertySerializerMixin,
RemoveNullFieldsMixin,
TempClientIdMixin,
URLCachedFileField,
Expand Down Expand Up @@ -161,15 +160,13 @@ class RegionGqSerializer(UserResourceSerializer, TempClientIdMixin):
help_text="Project is only used while creating region"
)

client_id = serializers.CharField(required=False)

class Meta:
model = Region
fields = ['title', 'code', 'project', 'client_id']

def validate_project(self, project):
if not project.can_modify(self.context['request'].user):
raise serializers.ValidationError('Permission Denied')
raise serializers.ValidationError('You Don\'t have permission in project')
return project

def validate(self, data):
Expand All @@ -178,13 +175,13 @@ def validate(self, data):
return data

def create(self, validated_data):
project = validated_data.pop('project', None)
project = validated_data.pop('project')
region = super().create(validated_data)
project.regions.add(region)
return region


class AdminLevelGqlSerializer(UserResourceSerializer):
class AdminLevelGqlSerializer(UserResourceSerializer, TempClientIdMixin):
region = serializers.PrimaryKeyRelatedField(queryset=Region.objects.all())
parent_code_prop = serializers.CharField(required=False, allow_null=True, allow_blank=True)
parent_name_prop = serializers.CharField(required=False, allow_null=True, allow_blank=True)
Expand All @@ -201,20 +198,21 @@ class Meta:
'parent_code_prop',
'parent_name_prop',
'geo_shape_file',
'geo_shape_file',
'bounds_file',
'client_id',
]

def validate(self, data):
region = data.get('region', (self.instance and self.instance.region))
if not region.can_modify(self.context['request'].user):
raise serializers.ValidationError('You don\'t have the access to the region or region is published')
if region.created_by != self.context['request'].user:
raise serializers.ValidationError('You don\'t have the access to the region')
if region.is_published:
raise serializers.ValidationError('Published region can\'t be changed. Please contact Admin')
return data

def create(self, validated_data):
admin_level = super().create(validated_data)

transaction.on_commit(lambda: load_geo_areas.delay(admin_level.region.id))
transaction.on_commit(lambda: load_geo_areas.delay(admin_level.region_id))

return admin_level

Expand All @@ -230,20 +228,3 @@ def update(self, instance, validated_data):
transaction.on_commit(lambda: load_geo_areas.delay(region.id))

return admin_level


class PublishRegionGqSerializer(ProjectPropertySerializerMixin, UserResourceSerializer):

class Meta:
model = Region
fields = ['is_published']

def validate(self, data):
if not self.instance.can_publish(self.context['request'].user):
raise serializers.ValidationError("Authorized User can only published the region")
return data

def update(self, instance, validated_data):
instance.is_published = True
data = super().update(instance, validated_data)
return data
Loading

0 comments on commit 3013525

Please sign in to comment.