Skip to content

Commit

Permalink
lint care/facility/api/viewsets/
Browse files Browse the repository at this point in the history
  • Loading branch information
sainak committed Sep 24, 2024
1 parent a7c7927 commit 4cb6716
Show file tree
Hide file tree
Showing 23 changed files with 174 additions and 279 deletions.
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/ambulance.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class AmbulanceViewSet(
def get_serializer_class(self):
if self.action == "add_driver":
return AmbulanceDriverSerializer
elif self.action == "remove_driver":
if self.action == "remove_driver":
return DeleteDriverSerializer
return AmbulanceSerializer

Expand Down
48 changes: 24 additions & 24 deletions care/facility/api/viewsets/asset.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import logging
import re
from typing import TYPE_CHECKING

from django.conf import settings
from django.core.cache import cache
Expand Down Expand Up @@ -58,13 +60,18 @@
)
from care.users.models import User
from care.utils.assetintegration.asset_classes import AssetClasses
from care.utils.assetintegration.base import BaseAssetIntegration
from care.utils.cache.cache_allowed_facilities import get_accessible_facilities
from care.utils.filters.choicefilter import CareChoiceFilter, inverse_choices
from care.utils.queryset.asset_location import get_asset_location_queryset
from care.utils.queryset.facility import get_facility_queryset
from config.authentication import MiddlewareAuthentication

if TYPE_CHECKING:
from care.utils.assetintegration.base import BaseAssetIntegration

logger = logging.getLogger(__name__)


inverse_asset_type = inverse_choices(AssetTypeChoices)
inverse_asset_status = inverse_choices(StatusChoices)

Expand Down Expand Up @@ -131,9 +138,11 @@ def perform_create(self, serializer):
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
if instance.bed_set.filter(deleted=False).count():
raise ValidationError("Cannot delete a Location with associated Beds")
msg = "Cannot delete a Location with associated Beds"
raise ValidationError(msg)
if instance.asset_set.filter(deleted=False).count():
raise ValidationError("Cannot delete a Location with associated Assets")
msg = "Cannot delete a Location with associated Assets"
raise ValidationError(msg)

return super().destroy(request, *args, **kwargs)

Expand Down Expand Up @@ -243,11 +252,9 @@ def get_queryset(self):
content_type__model="asset",
object_external_id=self.kwargs["asset_external_id"],
)
else:
raise exceptions.PermissionDenied(
"You do not have access to this asset's availability records"
)
elif "asset_location_external_id" in self.kwargs:
msg = "You do not have access to this asset's availability records"
raise exceptions.PermissionDenied(msg)
if "asset_location_external_id" in self.kwargs:
asset_location = get_object_or_404(
AssetLocation, external_id=self.kwargs["asset_location_external_id"]
)
Expand All @@ -256,14 +263,10 @@ def get_queryset(self):
content_type__model="assetlocation",
object_external_id=self.kwargs["asset_location_external_id"],
)
else:
raise exceptions.PermissionDenied(
"You do not have access to this asset location's availability records"
)
else:
raise exceptions.ValidationError(
"Either asset_external_id or asset_location_external_id is required"
)
msg = "You do not have access to this asset location's availability records"
raise exceptions.PermissionDenied(msg)
msg = "Either asset_external_id or asset_location_external_id is required"
raise exceptions.ValidationError(msg)


class AssetViewSet(
Expand Down Expand Up @@ -302,7 +305,7 @@ def get_queryset(self):
queryset = queryset.filter(
current_location__facility__id__in=allowed_facilities
)
queryset = queryset.annotate(
return queryset.annotate(
latest_status=Subquery(
AvailabilityRecord.objects.filter(
content_type__model="asset",
Expand All @@ -312,7 +315,6 @@ def get_queryset(self):
.values("status")[:1]
)
)
return queryset

def list(self, request, *args, **kwargs):
if settings.CSV_REQUEST_PARAMETER in request.GET:
Expand All @@ -323,16 +325,14 @@ def list(self, request, *args, **kwargs):
queryset, field_header_map=mapping, field_serializer_map=pretty_mapping
)

return super(AssetViewSet, self).list(request, *args, **kwargs)
return super().list(request, *args, **kwargs)

def destroy(self, request, *args, **kwargs):
user = self.request.user
if user.user_type >= User.TYPE_VALUE_MAP["DistrictAdmin"]:
return super().destroy(request, *args, **kwargs)
else:
raise exceptions.AuthenticationFailed(
"Only District Admin and above can delete assets"
)
msg = "Only District Admin and above can delete assets"
raise exceptions.AuthenticationFailed(msg)

@extend_schema(
responses={200: UserDefaultAssetLocationSerializer()}, tags=["asset"]
Expand Down Expand Up @@ -416,7 +416,7 @@ def operate_assets(self, request, *args, **kwargs):
)

except Exception as e:
print(f"error: {e}")
logger.info("Failed to operate asset: %s", e)
return Response(
{"message": "Internal Server Error"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
Expand Down
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/bed.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def create(self, request, *args, **kwargs):

def destroy(self, request, *args, **kwargs):
if request.user.user_type < User.TYPE_VALUE_MAP["DistrictLabAdmin"]:
raise PermissionDenied()
raise PermissionDenied
instance = self.get_object()
if instance.is_occupied:
raise DRFValidationError(
Expand Down
5 changes: 1 addition & 4 deletions care/facility/api/viewsets/daily_round.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from care.facility.models.daily_round import DailyRound
from care.utils.queryset.consultation import get_consultation_queryset

DailyRoundAttributes = [f.name for f in DailyRound._meta.get_fields()]
DailyRoundAttributes = [f.name for f in DailyRound._meta.get_fields()] # noqa: SLF001


class DailyRoundFilterSet(filters.FilterSet):
Expand Down Expand Up @@ -98,9 +98,6 @@ def analyse(self, request, **kwargs):

page = request.data.get("page", 1)

# to_time = datetime.now() - timedelta(days=((page - 1) * self.DEFAULT_LOOKUP_DAYS))
# from_time = to_time - timedelta(days=self.DEFAULT_LOOKUP_DAYS)

consultation = get_object_or_404(
get_consultation_queryset(request.user).filter(
external_id=self.kwargs["consultation_external_id"]
Expand Down
2 changes: 0 additions & 2 deletions care/facility/api/viewsets/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ class PatientConsultationEventViewSet(ReadOnlyModelViewSet):
)
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = PatientConsultationEventFilterSet
# lookup_field = "external_id"
# lookup_url_kwarg = "external_id"

def get_consultation_obj(self):
return get_object_or_404(
Expand Down
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/facility.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def list(self, request, *args, **kwargs):
queryset, field_header_map=mapping, field_serializer_map=pretty_mapping
)

return super(FacilityViewSet, self).list(request, *args, **kwargs)
return super().list(request, *args, **kwargs)

@extend_schema(tags=["facility"])
@method_decorator(parser_classes([MultiPartParser]))
Expand Down
4 changes: 2 additions & 2 deletions care/facility/api/viewsets/facility_capacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ def get_queryset(self):
)
if user.is_superuser:
return queryset
elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]:
if self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]:
return queryset.filter(facility__state=user.state)
elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]:
if self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]:
return queryset.filter(facility__district=user.district)
return queryset.filter(facility__users__id__exact=user.id)

Expand Down
4 changes: 2 additions & 2 deletions care/facility/api/viewsets/facility_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,5 @@ def get_queryset(self):
queryset=UserSkill.objects.filter(skill__deleted=False),
),
)
except Facility.DoesNotExist:
raise ValidationError({"Facility": "Facility not found"})
except Facility.DoesNotExist as e:
raise ValidationError({"Facility": "Facility not found"}) from e
16 changes: 7 additions & 9 deletions care/facility/api/viewsets/file_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,10 @@ def has_permission(self, request, view) -> bool:
"PATIENT",
"CONSULTATION",
)
else:
return request.data.get("file_type") not in (
"PATIENT",
"CONSULTATION",
)
return request.data.get("file_type") not in (
"PATIENT",
"CONSULTATION",
)
return True

def has_object_permission(self, request, view, obj) -> bool:
Expand All @@ -67,12 +66,11 @@ class FileUploadViewSet(
def get_serializer_class(self):
if self.action == "retrieve":
return FileUploadRetrieveSerializer
elif self.action == "list":
if self.action == "list":
return FileUploadListSerializer
elif self.action == "create":
if self.action == "create":
return FileUploadCreateSerializer
else:
return FileUploadUpdateSerializer
return FileUploadUpdateSerializer

def get_queryset(self):
if "file_type" not in self.request.GET:
Expand Down
23 changes: 0 additions & 23 deletions care/facility/api/viewsets/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,26 +235,3 @@ def get_object(self):
return get_object_or_404(
self.get_queryset(), external_id=self.kwargs.get("external_id")
)


# class FacilityInventoryBurnRateFilter(filters.FilterSet):
# name = filters.CharFilter(field_name="facility__name", lookup_expr="icontains")
# item = filters.NumberFilter(field_name="item_id")


# class FacilityInventoryBurnRateViewSet(
# UserAccessMixin, ListModelMixin, RetrieveModelMixin, GenericViewSet,
# ):
# queryset = FacilityInventoryBurnRate.objects.select_related(
# "item", "item__default_unit", "facility__district"
# ).all()
# filter_backends = (filters.DjangoFilterBackend,)
# filterset_class = FacilityInventoryBurnRateFilter
# permission_classes = (IsAuthenticated, DRYPermissions)
# serializer_class = FacilityInventoryBurnRateSerializer

# def filter_queryset(self, queryset):
# queryset = super().filter_queryset(queryset)
# if self.kwargs.get("facility_external_id"):
# queryset = queryset.filter(facility__external_id=self.kwargs.get("facility_external_id"))
# return self.filter_by_user_scope(queryset)
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/mixins/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class AssetUserAccessMixin:
asset_permissions = (DRYAssetPermissions,)

def get_authenticators(self):
return [MiddlewareAssetAuthentication()] + super().get_authenticators()
return [MiddlewareAssetAuthentication(), *super().get_authenticators()]

def get_permissions(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def public_key(self, request, *args, **kwargs):
def notify(self, request, *args, **kwargs):
user = request.user
if user.user_type < User.TYPE_VALUE_MAP["Doctor"]:
raise PermissionDenied()
raise PermissionDenied
if "facility" not in request.data or request.data["facility"] == "":
raise ValidationError({"facility": "is required"})
if "message" not in request.data or request.data["message"] == "":
Expand Down
Loading

0 comments on commit 4cb6716

Please sign in to comment.