Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Admin panel for localunit and permission #2342

Merged
merged 3 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions local_units/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from django.core.exceptions import ValidationError
from reversion_compare.admin import CompareVersionAdmin

from dref.admin import ReadOnlyMixin

from .models import (
Affiliation,
BloodService,
Expand All @@ -14,6 +16,7 @@
HealthData,
HospitalType,
LocalUnit,
LocalUnitChangeRequest,
LocalUnitLevel,
LocalUnitType,
PrimaryHCC,
Expand Down Expand Up @@ -64,6 +67,36 @@ def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)


@admin.register(LocalUnitChangeRequest)
class LocalUnitChangeRequestAdmin(ReadOnlyMixin, admin.ModelAdmin):
autocomplete_fields = (
"local_unit",
"triggered_by",
)
search_fields = (
"local_unit__id",
"local_unit__english_branch_name",
"local_unit__local_branch_name",
)
list_filter = ("status",)
list_display = (
"local_unit",
"status",
"current_validator",
)
ordering = ("id",)

def get_queryset(self, request):
return (
super()
.get_queryset(request)
.select_related(
"local_unit",
"triggered_by",
)
)


@admin.register(DelegationOffice)
class DelegationOfficeAdmin(admin.OSMGeoAdmin):
search_fields = ("name", "city", "country__name")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 4.2.16 on 2024-11-29 11:02
# Generated by Django 4.2.16 on 2024-12-11 09:28

import django.db.models.deletion
from django.conf import settings
Expand Down Expand Up @@ -36,14 +36,12 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name="localunit",
name="is_deprecated",
field=models.BooleanField(blank=True, default=False, null=True, verbose_name="Is deprecated?"),
field=models.BooleanField(default=False, verbose_name="Is deprecated?"),
),
migrations.AddField(
model_name="localunit",
name="status",
field=models.IntegerField(
blank=True, choices=[(1, "Verified"), (2, "Unverified")], default=2, null=True, verbose_name="status"
),
name="is_locked",
field=models.BooleanField(default=False, verbose_name="Is locked?"),
),
migrations.CreateModel(
name="LocalUnitChangeRequest",
Expand All @@ -62,7 +60,7 @@ class Migration(migrations.Migration):
choices=[(1, "Local"), (2, "Regional"), (3, "Global")], default=1, verbose_name="Current validator"
),
),
("triggered_at", models.DateTimeField(auto_now=True, verbose_name="Triggered at")),
("triggered_at", models.DateTimeField(auto_now_add=True, verbose_name="Triggered at")),
("updated_at", models.DateTimeField(auto_now=True, verbose_name="Updated at")),
("rejected_data", models.JSONField(default=dict, verbose_name="Rejected data")),
("rejected_reason", models.TextField(blank=True, null=True, verbose_name="Rejected reason")),
Expand Down Expand Up @@ -96,5 +94,8 @@ class Migration(migrations.Migration):
),
),
],
options={
"ordering": ("id",),
},
),
]

This file was deleted.

This file was deleted.

9 changes: 9 additions & 0 deletions local_units/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,15 @@ def __str__(self):
branch_name = self.local_branch_name or self.english_branch_name
return f"{branch_name} ({self.country.name})"

def location_json(self):
"""
Returns location in JSON format
"""
return {
"lat": self.location.y,
"lng": self.location.x,
}


class LocalUnitChangeRequest(models.Model):

Expand Down
11 changes: 9 additions & 2 deletions local_units/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


class ValidateLocalUnitPermission(permissions.BasePermission):
message = "You need to be super user/ country admin to validate local unit"
message = "You need to be super user/ country admin/ region admin to validate local unit"

def has_object_permission(self, request, view, object):
user = request.user
Expand All @@ -16,7 +16,14 @@ def has_object_permission(self, request, view, object):
codename__startswith="country_admin_",
).values_list("codename", flat=True)
]
if object.country_id in country_admin_ids:
region_admin_ids = [
int(codename.replace("region_admin_", ""))
for codename in Permission.objects.filter(
group__user=user,
codename__startswith="region_admin_",
).values_list("codename", flat=True)
]
if object.country_id in country_admin_ids or object.region_id in region_admin_ids:
return True
return False

Expand Down
38 changes: 21 additions & 17 deletions local_units/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
)


class LocationSerializer(serializers.Serializer):
lat = serializers.FloatField(required=True)
lng = serializers.FloatField(required=True)


class GeneralMedicalServiceSerializer(serializers.ModelSerializer):
class Meta:
model = GeneralMedicalService
Expand Down Expand Up @@ -191,7 +196,7 @@ class LocalUnitDetailSerializer(serializers.ModelSerializer):
type_details = LocalUnitTypeSerializer(source="type", read_only=True)
level_details = LocalUnitLevelSerializer(source="level", read_only=True)
health = HealthDataSerializer(required=False, allow_null=True)
location_details = serializers.SerializerMethodField()
location_geojson = serializers.SerializerMethodField()
visibility_display = serializers.CharField(source="get_visibility_display", read_only=True)
validated = serializers.BooleanField(read_only=True)

Expand Down Expand Up @@ -220,13 +225,13 @@ class Meta:
"level",
"health",
"visibility_display",
"location_details",
"location_geojson",
"type_details",
"level_details",
"country_details",
)

def get_location_details(self, unit) -> dict:
def get_location_geojson(self, unit) -> dict:
return json.loads(unit.location.geojson)


Expand All @@ -235,10 +240,11 @@ class PrivateLocalUnitDetailSerializer(NestedCreateMixin, NestedUpdateMixin):
type_details = LocalUnitTypeSerializer(source="type", read_only=True)
level_details = LocalUnitLevelSerializer(source="level", read_only=True)
health = HealthDataSerializer(required=False, allow_null=True)
location_details = serializers.SerializerMethodField(read_only=True)
# NOTE: location_geojson contains the geojson of the location
location_geojson = serializers.SerializerMethodField(read_only=True)
visibility_display = serializers.CharField(source="get_visibility_display", read_only=True)
validated = serializers.BooleanField(read_only=True)
location_json = serializers.JSONField(required=True, write_only=True)
location_json = LocationSerializer(required=True)
location = serializers.CharField(required=False)
modified_by_details = LocalUnitMiniUserSerializer(source="modified_by", read_only=True)
created_by_details = LocalUnitMiniUserSerializer(source="created_by", read_only=True)
Expand Down Expand Up @@ -272,7 +278,7 @@ class Meta:
"level",
"health",
"visibility_display",
"location_details",
"location_geojson",
"type_details",
"level_details",
"country_details",
Expand All @@ -288,7 +294,7 @@ class Meta:
"is_locked",
)

def get_location_details(self, unit) -> dict:
def get_location_geojson(self, unit) -> dict:
return json.loads(unit.location.geojson)

def get_version_id(self, resource):
Expand Down Expand Up @@ -319,8 +325,6 @@ def create(self, validated_data):
location_json = validated_data.pop("location_json")
lat = location_json.get("lat")
lng = location_json.get("lng")
if not lat and not lng:
raise serializers.ValidationError(gettext("Combination of lat/lon is required"))
input_point = Point(lng, lat)
if country.bbox:
country_json = json.loads(country.countrygeoms.geom.geojson)
Expand Down Expand Up @@ -349,8 +353,6 @@ def update(self, instance, validated_data):
location_json = validated_data.pop("location_json")
lat = location_json.get("lat")
lng = location_json.get("lng")
if not lat and not lng:
raise serializers.ValidationError(gettext("Combination of lat/lon is required"))
input_point = Point(lng, lat)
if country.bbox:
country_json = json.loads(country.countrygeoms.geom.geojson)
Expand All @@ -377,7 +379,8 @@ def update(self, instance, validated_data):


class LocalUnitSerializer(serializers.ModelSerializer):
location_details = serializers.SerializerMethodField()
# NOTE: location_geojson contains the geojson of the location
location_geojson = serializers.SerializerMethodField()
country_details = LocalUnitCountrySerializer(source="country", read_only=True)
type_details = LocalUnitTypeSerializer(source="type", read_only=True)
health_details = MiniHealthDataSerializer(read_only=True, source="health")
Expand All @@ -390,7 +393,7 @@ class Meta:
"country",
"local_branch_name",
"english_branch_name",
"location_details",
"location_geojson",
"type",
"validated",
"address_loc",
Expand All @@ -401,12 +404,13 @@ class Meta:
"health_details",
)

def get_location_details(self, unit) -> dict:
def get_location_geojson(self, unit) -> dict:
return json.loads(unit.location.geojson)


class PrivateLocalUnitSerializer(serializers.ModelSerializer):
location_details = serializers.SerializerMethodField()
# NOTE: location_geojson contains the geojson of the location
location_geojson = serializers.SerializerMethodField()
country_details = LocalUnitCountrySerializer(source="country", read_only=True)
type_details = LocalUnitTypeSerializer(source="type", read_only=True)
health_details = MiniHealthDataSerializer(read_only=True, source="health")
Expand All @@ -421,7 +425,7 @@ class Meta:
"country",
"local_branch_name",
"english_branch_name",
"location_details",
"location_geojson",
"type",
"validated",
"address_loc",
Expand All @@ -439,7 +443,7 @@ class Meta:
"is_locked",
)

def get_location_details(self, unit) -> dict:
def get_location_geojson(self, unit) -> dict:
return json.loads(unit.location.geojson)


Expand Down
7 changes: 4 additions & 3 deletions local_units/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ def test_deprecate_local_unit(self):

# Test for validation
response = self.client.post(url, data=data)
self.assert_400(response)
self.assert_404(response)

self.client.force_authenticate(self.root_user)
# test revert deprecate
data = {}
url = f"/api/v2/local-units/{local_unit_obj.id}/revert-deprecate/"
Expand Down Expand Up @@ -171,7 +172,7 @@ def test_detail(self):
self.authenticate()
response = self.client.get(f"/api/v2/local-units/{local_unit.id}/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["location_details"]["coordinates"], [12, 38])
self.assertEqual(response.data["location_geojson"]["coordinates"], [12, 38])
self.assertEqual(response.data["country_details"]["name"], "Nepal")
self.assertEqual(response.data["country_details"]["iso3"], "NLP")
self.assertEqual(response.data["type_details"]["name"], "Code 0")
Expand All @@ -190,7 +191,7 @@ def test_detail(self):
local_unit = LocalUnitFactory.create(country=self.country, type=self.type, visibility=VisibilityChoices.PUBLIC)
response = self.client.get(f"/api/v2/public-local-units/{local_unit.id}/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["location_details"]["coordinates"], [12, 38])
self.assertEqual(response.data["location_geojson"]["coordinates"], [12, 38])
self.assertEqual(response.data["country_details"]["name"], "Nepal")
self.assertEqual(response.data["country_details"]["iso3"], "NLP")
self.assertEqual(response.data["type_details"]["name"], "Code 0")
Expand Down
13 changes: 0 additions & 13 deletions local_units/utils.py

This file was deleted.

Loading
Loading