diff --git a/care/facility/api/viewsets/ambulance.py b/care/facility/api/viewsets/ambulance.py index a2dbe3de95..49387d2bce 100644 --- a/care/facility/api/viewsets/ambulance.py +++ b/care/facility/api/viewsets/ambulance.py @@ -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 diff --git a/care/facility/api/viewsets/asset.py b/care/facility/api/viewsets/asset.py index 26b9d35b34..15dd00e2aa 100644 --- a/care/facility/api/viewsets/asset.py +++ b/care/facility/api/viewsets/asset.py @@ -1,4 +1,6 @@ +import logging import re +from typing import TYPE_CHECKING from django.conf import settings from django.core.cache import cache @@ -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) @@ -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) @@ -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"] ) @@ -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( @@ -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", @@ -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: @@ -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"] @@ -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, diff --git a/care/facility/api/viewsets/bed.py b/care/facility/api/viewsets/bed.py index 2f994f108d..336b5f83c2 100644 --- a/care/facility/api/viewsets/bed.py +++ b/care/facility/api/viewsets/bed.py @@ -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( diff --git a/care/facility/api/viewsets/daily_round.py b/care/facility/api/viewsets/daily_round.py index 612c451437..9786ffb312 100644 --- a/care/facility/api/viewsets/daily_round.py +++ b/care/facility/api/viewsets/daily_round.py @@ -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): @@ -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"] diff --git a/care/facility/api/viewsets/events.py b/care/facility/api/viewsets/events.py index 8dc1678b4d..b1fedf92e4 100644 --- a/care/facility/api/viewsets/events.py +++ b/care/facility/api/viewsets/events.py @@ -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( diff --git a/care/facility/api/viewsets/facility.py b/care/facility/api/viewsets/facility.py index 222f0591fd..dd8221c0cb 100644 --- a/care/facility/api/viewsets/facility.py +++ b/care/facility/api/viewsets/facility.py @@ -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])) diff --git a/care/facility/api/viewsets/facility_capacity.py b/care/facility/api/viewsets/facility_capacity.py index dd18d13f62..6bc28fce13 100644 --- a/care/facility/api/viewsets/facility_capacity.py +++ b/care/facility/api/viewsets/facility_capacity.py @@ -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) diff --git a/care/facility/api/viewsets/facility_users.py b/care/facility/api/viewsets/facility_users.py index 5d3cb79629..fb2cf25916 100644 --- a/care/facility/api/viewsets/facility_users.py +++ b/care/facility/api/viewsets/facility_users.py @@ -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 diff --git a/care/facility/api/viewsets/file_upload.py b/care/facility/api/viewsets/file_upload.py index 5e784fafb6..bcf98282f0 100644 --- a/care/facility/api/viewsets/file_upload.py +++ b/care/facility/api/viewsets/file_upload.py @@ -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: @@ -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: diff --git a/care/facility/api/viewsets/inventory.py b/care/facility/api/viewsets/inventory.py index 7722319601..20c87650e8 100644 --- a/care/facility/api/viewsets/inventory.py +++ b/care/facility/api/viewsets/inventory.py @@ -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) diff --git a/care/facility/api/viewsets/mixins/access.py b/care/facility/api/viewsets/mixins/access.py index 09f25f6d18..314c36c360 100644 --- a/care/facility/api/viewsets/mixins/access.py +++ b/care/facility/api/viewsets/mixins/access.py @@ -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): """ diff --git a/care/facility/api/viewsets/notification.py b/care/facility/api/viewsets/notification.py index 213f1324e9..a51097f8e2 100644 --- a/care/facility/api/viewsets/notification.py +++ b/care/facility/api/viewsets/notification.py @@ -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"] == "": diff --git a/care/facility/api/viewsets/patient.py b/care/facility/api/viewsets/patient.py index 043c1046ab..72731cd6e2 100644 --- a/care/facility/api/viewsets/patient.py +++ b/care/facility/api/viewsets/patient.py @@ -1,4 +1,3 @@ -import datetime import json from json import JSONDecodeError @@ -97,7 +96,6 @@ class PatientFilterSet(filters.FilterSet): - last_consultation_field = "last_consultation" source = filters.ChoiceFilter(choices=PatientRegistration.SourceChoices) @@ -356,7 +354,7 @@ class PatientCustomOrderingFilter(BaseFilterBackend): def filter_queryset(self, request, queryset, view): ordering = request.query_params.get("ordering", "") - if ordering == "category_severity" or ordering == "-category_severity": + if ordering in ("category_severity", "-category_severity"): category_ordering = { category: index + 1 for index, (category, _) in enumerate(CATEGORY_CHOICES) @@ -507,12 +505,11 @@ def get_queryset(self): def get_serializer_class(self): if self.action == "list": return PatientListSerializer - elif self.action == "icmr_sample": + if self.action == "icmr_sample": return PatientICMRSerializer - elif self.action == "transfer": + if self.action == "transfer": return PatientTransferSerializer - else: - return self.serializer_class + return self.serializer_class def filter_queryset(self, queryset: QuerySet) -> QuerySet: if self.action == "list" and settings.CSV_REQUEST_PARAMETER in self.request.GET: @@ -586,7 +583,7 @@ def list(self, request, *args, **kwargs): field_serializer_map=PatientRegistration.CSV_MAKE_PRETTY, ) - return super(PatientViewSet, self).list(request, *args, **kwargs) + return super().list(request, *args, **kwargs) @extend_schema(tags=["patient"]) @action(detail=True, methods=["POST"]) @@ -805,9 +802,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) @@ -836,9 +833,7 @@ def list(self, request, *args, **kwargs): - entry_date_before: date in YYYY-MM-DD format, inclusive of this date """ - return super(FacilityPatientStatsHistoryViewSet, self).list( - request, *args, **kwargs - ) + return super().list(request, *args, **kwargs) class PatientSearchSetPagination(PageNumberPagination): @@ -864,62 +859,58 @@ class PatientSearchViewSet(ListModelMixin, GenericViewSet): def get_queryset(self): if self.action != "list": - return super(PatientSearchViewSet, self).get_queryset() + return super().get_queryset() + serializer = PatientSearchSerializer( + data=self.request.query_params, partial=True + ) + serializer.is_valid(raise_exception=True) + if self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: + search_keys = [ + "date_of_birth", + "year_of_birth", + "phone_number", + "name", + "age", + ] else: - serializer = PatientSearchSerializer( - data=self.request.query_params, partial=True + search_keys = [ + "date_of_birth", + "year_of_birth", + "phone_number", + "age", + ] + search_fields = { + key: serializer.validated_data[key] + for key in search_keys + if serializer.validated_data.get(key) + } + if not search_fields: + raise serializers.ValidationError( + { + "detail": [ + f"None of the search keys provided. Available: {', '.join(search_keys)}" + ] + } ) - serializer.is_valid(raise_exception=True) - if self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: - search_keys = [ - "date_of_birth", - "year_of_birth", - "phone_number", - "name", - "age", - ] - else: - search_keys = [ - "date_of_birth", - "year_of_birth", - "phone_number", - "age", - ] - search_fields = { - key: serializer.validated_data[key] - for key in search_keys - if serializer.validated_data.get(key) - } - if not search_fields: - raise serializers.ValidationError( - { - "detail": [ - f"None of the search keys provided. Available: {', '.join(search_keys)}" - ] - } - ) - - # if not self.request.user.is_superuser: - # search_fields["state_id"] = self.request.user.state_id - if "age" in search_fields: - age = search_fields.pop("age") - year_of_birth = datetime.datetime.now().year - age - search_fields["age__gte"] = year_of_birth - 5 - search_fields["age__lte"] = year_of_birth + 5 + if "age" in search_fields: + age = search_fields.pop("age") + year_of_birth = timezone.now().year - age + search_fields["age__gte"] = year_of_birth - 5 + search_fields["age__lte"] = year_of_birth + 5 - name = search_fields.pop("name", None) + name = search_fields.pop("name", None) - queryset = self.queryset.filter(**search_fields) + queryset = self.queryset.filter(**search_fields) - if name: - queryset = ( - queryset.annotate(similarity=TrigramSimilarity("name", name)) - .filter(similarity__gt=0.2) - .order_by("-similarity") - ) + if name: + queryset = ( + queryset.annotate(similarity=TrigramSimilarity("name", name)) + .filter(similarity__gt=0.2) + .order_by("-similarity") + ) - return queryset + return queryset @extend_schema(tags=["patient"]) def list(self, request, *args, **kwargs): @@ -939,7 +930,7 @@ def list(self, request, *args, **kwargs): `Eg: api/v1/patient/search/?year_of_birth=1992&phone_number=%2B917795937091` """ - return super(PatientSearchViewSet, self).list(request, *args, **kwargs) + return super().list(request, *args, **kwargs) class PatientNotesFilterSet(filters.FilterSet): diff --git a/care/facility/api/viewsets/patient_consultation.py b/care/facility/api/viewsets/patient_consultation.py index b166971dc9..8bd7145df9 100644 --- a/care/facility/api/viewsets/patient_consultation.py +++ b/care/facility/api/viewsets/patient_consultation.py @@ -70,12 +70,11 @@ class PatientConsultationViewSet( def get_serializer_class(self): if self.action == "patient_from_asset": return PatientConsultationIDSerializer - elif self.action == "discharge_patient": + if self.action == "discharge_patient": return PatientConsultationDischargeSerializer - elif self.action == "email_discharge_summary": + if self.action == "email_discharge_summary": return EmailDischargeSummarySerializer - else: - return self.serializer_class + return self.serializer_class def get_permissions(self): if self.action == "patient_from_asset": @@ -97,11 +96,11 @@ def get_queryset(self): ) if self.request.user.is_superuser: return self.queryset - elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]: + if self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]: return self.queryset.filter( patient__facility__state=self.request.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 self.queryset.filter( patient__facility__district=self.request.user.district ) @@ -304,14 +303,12 @@ def dev_preview_discharge_summary(request, consultation_id): with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file: discharge_summary.generate_discharge_summary_pdf(data, tmp_file) + tmp_file.seek(0) - with open(tmp_file.name, "rb") as pdf_file: - pdf_content = pdf_file.read() - - response = HttpResponse(pdf_content, content_type="application/pdf") - response["Content-Disposition"] = 'inline; filename="discharge_summary.pdf"' + response = HttpResponse(tmp_file, content_type="application/pdf") + response["Content-Disposition"] = 'inline; filename="discharge_summary.pdf"' - return response + return response class PatientConsentViewSet( diff --git a/care/facility/api/viewsets/patient_external_test.py b/care/facility/api/viewsets/patient_external_test.py index f5d983a9ed..e1d86cc311 100644 --- a/care/facility/api/viewsets/patient_external_test.py +++ b/care/facility/api/viewsets/patient_external_test.py @@ -28,9 +28,9 @@ from care.users.models import User -def prettyerrors(errors): +def pretty_errors(errors): pretty_errors = defaultdict(list) - for attribute in PatientExternalTest.HEADER_CSV_MAPPING.keys(): + for attribute in PatientExternalTest.HEADER_CSV_MAPPING: if attribute in errors: for error in errors.get(attribute, ""): pretty_errors[attribute].append(str(error)) @@ -46,8 +46,7 @@ def filter(self, qs, value): self.field_name + "__in": values, self.field_name + "__isnull": False, } - qs = qs.filter(**_filter) - return qs + return qs.filter(**_filter) class PatientExternalTestFilter(filters.FilterSet): @@ -113,22 +112,20 @@ def get_queryset(self): return queryset def get_serializer_class(self): - if self.action == "update" or self.action == "partial_update": + if self.action in ("update", "partial_update"): return PatientExternalTestUpdateSerializer return super().get_serializer_class() def destroy(self, request, *args, **kwargs): if self.request.user.user_type < User.TYPE_VALUE_MAP["DistrictLabAdmin"]: - raise PermissionDenied() + raise PermissionDenied return super().destroy(request, *args, **kwargs) def check_upload_permission(self): - if ( + return bool( self.request.user.is_superuser is True or self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"] - ): - return True - return False + ) def list(self, request, *args, **kwargs): if settings.CSV_REQUEST_PARAMETER in request.GET: @@ -140,18 +137,14 @@ def list(self, request, *args, **kwargs): field_header_map=mapping, field_serializer_map=pretty_mapping, ) - return super(PatientExternalTestViewSet, self).list(request, *args, **kwargs) + return super().list(request, *args, **kwargs) @extend_schema(tags=["external_result"]) @action(methods=["POST"], detail=False) def bulk_upsert(self, request, *args, **kwargs): if not self.check_upload_permission(): - raise PermissionDenied("Permission to Endpoint Denied") - # if len(request.FILES.keys()) != 1: - # raise ValidationError({"file": "Upload 1 File at a time"}) - # csv_file = request.FILES[list(request.FILES.keys())[0]] - # csv_file.seek(0) - # reader = csv.DictReader(io.StringIO(csv_file.read().decode("utf-8-sig"))) + msg = "Permission to Endpoint Denied" + raise PermissionDenied(msg) if "sample_tests" not in request.data: raise ValidationError({"sample_tests": "No Data was provided"}) if not isinstance(request.data["sample_tests"], list): @@ -163,18 +156,16 @@ def bulk_upsert(self, request, *args, **kwargs): raise ValidationError({"Error": "User must belong to same district"}) errors = [] - counter = 0 ser_objects = [] invalid = False for sample in request.data["sample_tests"]: - counter += 1 - serialiser_obj = PatientExternalTestSerializer(data=sample) - valid = serialiser_obj.is_valid() - current_error = prettyerrors(serialiser_obj._errors) + serializer = PatientExternalTestSerializer(data=sample) + valid = serializer.is_valid() + current_error = pretty_errors(serializer._errors) # noqa: SLF001 if current_error and (not valid): errors.append(current_error) invalid = True - ser_objects.append(serialiser_obj) + ser_objects.append(serializer) if invalid: return Response(errors, status=status.HTTP_400_BAD_REQUEST) for ser_object in ser_objects: diff --git a/care/facility/api/viewsets/patient_investigation.py b/care/facility/api/viewsets/patient_investigation.py index 07350e4a41..8a572de500 100644 --- a/care/facility/api/viewsets/patient_investigation.py +++ b/care/facility/api/viewsets/patient_investigation.py @@ -44,8 +44,7 @@ def filter(self, qs, value): if not value: return qs - qs = qs.filter(groups__external_id=value) - return qs + return qs.filter(groups__external_id=value) class PatientInvestigationFilter(filters.FilterSet): @@ -115,8 +114,7 @@ def get_queryset(self): queryset.filter(investigation__external_id__in=investigations.split(",")) .order_by("-session__created_date") .distinct("session__created_date")[ - (session_page - 1) - * self.SESSION_PER_PAGE : (session_page) + (session_page - 1) * self.SESSION_PER_PAGE : (session_page) * self.SESSION_PER_PAGE ] ) @@ -125,11 +123,11 @@ def get_queryset(self): queryset = queryset.filter(session_id__in=sessions.values("session_id")) if self.request.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( consultation__patient__facility__state=self.request.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( consultation__patient__facility__district=self.request.user.district ) @@ -168,11 +166,11 @@ def get_queryset(self): ) if self.request.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( consultation__patient__facility__state=self.request.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( consultation__patient__facility__district=self.request.user.district ) @@ -206,8 +204,8 @@ def get_sessions(self, request, *args, **kwargs): responses={204: "Operation successful"}, tags=["investigation"], ) - @action(detail=False, methods=["PUT"]) - def batchUpdate(self, request, *args, **kwargs): + @action(detail=False, methods=["PUT"], url_path="batchUpdate") + def batch_update(self, request, *args, **kwargs): if "investigations" not in request.data: return Response( {"investigation": "is required"}, diff --git a/care/facility/api/viewsets/patient_otp.py b/care/facility/api/viewsets/patient_otp.py index ca88d83793..bd857fcf7f 100644 --- a/care/facility/api/viewsets/patient_otp.py +++ b/care/facility/api/viewsets/patient_otp.py @@ -1,5 +1,3 @@ -from re import error - from django.conf import settings from drf_spectacular.utils import extend_schema, extend_schema_view from rest_framework import mixins @@ -28,13 +26,16 @@ class PatientMobileOTPViewSet( @action(detail=False, methods=["POST"]) def login(self, request): if "phone_number" not in request.data or "otp" not in request.data: - raise ValidationError("Request Incomplete") + msg = "Request Incomplete" + raise ValidationError(msg) phone_number = request.data["phone_number"] otp = request.data["otp"] try: mobile_validator(phone_number) - except error: - raise ValidationError({"phone_number": "Invalid phone number format"}) + except Exception as e: + raise ValidationError( + {"phone_number": "Invalid phone number format"} + ) from e if len(otp) != settings.OTP_LENGTH: raise ValidationError({"otp": "Invalid OTP"}) @@ -47,7 +48,6 @@ def login(self, request): otp_object.is_used = True otp_object.save() - # return JWT token = PatientToken() token["phone_number"] = phone_number diff --git a/care/facility/api/viewsets/patient_otp_data.py b/care/facility/api/viewsets/patient_otp_data.py index 76647ae5c5..b0f5e6d234 100644 --- a/care/facility/api/viewsets/patient_otp_data.py +++ b/care/facility/api/viewsets/patient_otp_data.py @@ -28,5 +28,4 @@ def get_queryset(self): def get_serializer_class(self): if self.action == "list": return PatientListSerializer - else: - return self.serializer_class + return self.serializer_class diff --git a/care/facility/api/viewsets/patient_sample.py b/care/facility/api/viewsets/patient_sample.py index 0c698c95a8..279fd5fcd5 100644 --- a/care/facility/api/viewsets/patient_sample.py +++ b/care/facility/api/viewsets/patient_sample.py @@ -93,7 +93,7 @@ def get_serializer_class(self): return serializer_class def get_queryset(self): - queryset = super(PatientSampleViewSet, self).get_queryset() + queryset = super().get_queryset() if self.kwargs.get("patient_external_id") is not None: queryset = queryset.filter( patient__external_id=self.kwargs.get("patient_external_id") @@ -118,7 +118,7 @@ def list(self, request, *args, **kwargs): not self.kwargs.get("patient_external_id") and request.user.user_type < User.TYPE_VALUE_MAP["Doctor"] ): - raise PermissionDenied() + raise PermissionDenied if settings.CSV_REQUEST_PARAMETER in request.GET: queryset = ( @@ -131,7 +131,7 @@ def list(self, request, *args, **kwargs): field_header_map=PatientSample.CSV_MAPPING, field_serializer_map=PatientSample.CSV_MAKE_PRETTY, ) - return super(PatientSampleViewSet, self).list(request, *args, **kwargs) + return super().list(request, *args, **kwargs) def perform_create(self, serializer): validated_data = serializer.validated_data diff --git a/care/facility/api/viewsets/prescription.py b/care/facility/api/viewsets/prescription.py index fe8914098c..8e67aa5beb 100644 --- a/care/facility/api/viewsets/prescription.py +++ b/care/facility/api/viewsets/prescription.py @@ -184,7 +184,6 @@ def administer(self, request, *args, **kwargs): class MedibaseViewSet(ViewSet): - def serialize_data(self, objects: list[MedibaseMedicine]): return [medicine.get_representation() for medicine in objects] @@ -195,8 +194,8 @@ def list(self, request): limit = 30 query = [] - if type := request.query_params.get("type"): - query.append(MedibaseMedicine.type == type) + if t := request.query_params.get("type"): + query.append(MedibaseMedicine.type == t) if q := request.query_params.get("query"): query.append( diff --git a/care/facility/api/viewsets/resources.py b/care/facility/api/viewsets/resources.py index 711f7fcac2..2197e7123f 100644 --- a/care/facility/api/viewsets/resources.py +++ b/care/facility/api/viewsets/resources.py @@ -46,7 +46,7 @@ def get_request_queryset(request, queryset): q_objects |= Q(approving_facility__state=request.user.state) q_objects |= Q(assigned_facility__state=request.user.state) return queryset.filter(q_objects) - elif request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: + if request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: q_objects = Q(origin_facility__district=request.user.district) q_objects |= Q(approving_facility__district=request.user.district) q_objects |= Q(assigned_facility__district=request.user.district) @@ -165,7 +165,7 @@ def get_queryset(self): request__assigned_facility__state=self.request.user.state ) return queryset.filter(q_objects) - elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: + if self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: q_objects = Q( request__origin_facility__district=self.request.user.district ) diff --git a/care/facility/api/viewsets/shifting.py b/care/facility/api/viewsets/shifting.py index 3111e70c30..33a1f84b13 100644 --- a/care/facility/api/viewsets/shifting.py +++ b/care/facility/api/viewsets/shifting.py @@ -35,6 +35,7 @@ DISEASE_STATUS_DICT, NewDischargeReasonEnum, ) +from care.facility.models.shifting import REVERSE_SHIFTING_STATUS_CHOICES from care.utils.cache.cache_allowed_facilities import get_accessible_facilities from care.utils.filters.choicefilter import CareChoiceFilter from care.utils.queryset.shifting import get_shifting_queryset @@ -161,33 +162,38 @@ def get_serializer_class(self): @action(detail=True, methods=["POST"]) def transfer(self, request, *args, **kwargs): shifting_obj = self.get_object() - if has_facility_permission( - request.user, shifting_obj.shifting_approving_facility - ) or has_facility_permission(request.user, shifting_obj.assigned_facility): - if shifting_obj.assigned_facility and shifting_obj.status >= 70: - if shifting_obj.patient: - patient = shifting_obj.patient - patient.facility = shifting_obj.assigned_facility - patient.is_active = True - patient.allow_transfer = False - patient.save() - shifting_obj.status = 80 - shifting_obj.save(update_fields=["status"]) - # Discharge from all other active consultations - PatientConsultation.objects.filter( - patient=patient, discharge_date__isnull=True - ).update( - discharge_date=localtime(now()), - new_discharge_reason=NewDischargeReasonEnum.REFERRED, - ) - ConsultationBed.objects.filter( - consultation=patient.last_consultation, - end_date__isnull=True, - ).update(end_date=localtime(now())) + if ( + ( + has_facility_permission( + request.user, shifting_obj.shifting_approving_facility + ) + or has_facility_permission(request.user, shifting_obj.assigned_facility) + ) + and shifting_obj.assigned_facility + and shifting_obj.status + >= REVERSE_SHIFTING_STATUS_CHOICES["TRANSFER IN PROGRESS"] + and shifting_obj.patient + ): + patient = shifting_obj.patient + patient.facility = shifting_obj.assigned_facility + patient.is_active = True + patient.allow_transfer = False + patient.save() + shifting_obj.status = REVERSE_SHIFTING_STATUS_CHOICES["COMPLETED"] + shifting_obj.save(update_fields=["status"]) + # Discharge from all other active consultations + PatientConsultation.objects.filter( + patient=patient, discharge_date__isnull=True + ).update( + discharge_date=localtime(now()), + new_discharge_reason=NewDischargeReasonEnum.REFERRED, + ) + ConsultationBed.objects.filter( + consultation=patient.last_consultation, + end_date__isnull=True, + ).update(end_date=localtime(now())) - return Response( - {"transfer": "completed"}, status=status.HTTP_200_OK - ) + return Response({"transfer": "completed"}, status=status.HTTP_200_OK) return Response( {"error": "Invalid Request"}, status=status.HTTP_400_BAD_REQUEST ) @@ -204,8 +210,7 @@ def list(self, request, *args, **kwargs): field_header_map=ShiftingRequest.CSV_MAPPING, field_serializer_map=ShiftingRequest.CSV_MAKE_PRETTY, ) - response = super().list(request, *args, **kwargs) - return response + return super().list(request, *args, **kwargs) class ShifitngRequestCommentViewSet( @@ -236,7 +241,7 @@ def get_queryset(self): request__assigned_facility__state=self.request.user.state ) return queryset.filter(q_objects) - elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: + if self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: q_objects = Q( request__origin_facility__district=self.request.user.district ) diff --git a/care/facility/api/viewsets/summary.py b/care/facility/api/viewsets/summary.py index e223a204c4..fbc60f6bb3 100644 --- a/care/facility/api/viewsets/summary.py +++ b/care/facility/api/viewsets/summary.py @@ -48,17 +48,6 @@ class FacilityCapacitySummaryViewSet( def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) - # def get_queryset(self): - # user = self.request.user - # queryset = self.queryset - # if user.is_superuser: - # return queryset - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictReadOnlyAdmin"]: - # return queryset.filter(facility__district=user.district) - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateReadOnlyAdmin"]: - # return queryset.filter(facility__state=user.state) - # return queryset.filter(facility__users__id__exact=user.id) - class TriageSummaryViewSet(ListModelMixin, GenericViewSet): lookup_field = "external_id" @@ -71,17 +60,6 @@ class TriageSummaryViewSet(ListModelMixin, GenericViewSet): filter_backends = (filters.DjangoFilterBackend,) filterset_class = FacilitySummaryFilter - # def get_queryset(self): - # user = self.request.user - # queryset = self.queryset - # if user.is_superuser: - # return queryset - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictReadOnlyAdmin"]: - # return queryset.filter(facility__district=user.district) - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateReadOnlyAdmin"]: - # return queryset.filter(facility__state=user.state) - # return queryset.filter(facility__users__id__exact=user.id) - @extend_schema(tags=["summary"]) @method_decorator(cache_page(60 * 60)) def list(self, request, *args, **kwargs): @@ -99,17 +77,6 @@ class TestsSummaryViewSet(ListModelMixin, GenericViewSet): filter_backends = (filters.DjangoFilterBackend,) filterset_class = FacilitySummaryFilter - # def get_queryset(self): - # user = self.request.user - # queryset = self.queryset - # if user.is_superuser: - # return queryset - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictReadOnlyAdmin"]: - # return queryset.filter(facility__district=user.district) - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateReadOnlyAdmin"]: - # return queryset.filter(facility__state=user.state) - # return queryset.filter(facility__users__id__exact=user.id) - @extend_schema(tags=["summary"]) @method_decorator(cache_page(60 * 60 * 10)) def list(self, request, *args, **kwargs): @@ -132,17 +99,6 @@ class PatientSummaryViewSet(ListModelMixin, GenericViewSet): def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) - # def get_queryset(self): - # user = self.request.user - # queryset = self.queryset - # if user.is_superuser: - # return queryset - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictReadOnlyAdmin"]: - # return queryset.filter(facility__district=user.district) - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateReadOnlyAdmin"]: - # return queryset.filter(facility__state=user.state) - # return queryset.filter(facility__users__id__exact=user.id) - class DistrictSummaryFilter(filters.FilterSet): start_date = filters.DateFilter(field_name="created_date", lookup_expr="gte") @@ -168,14 +124,3 @@ class DistrictPatientSummaryViewSet(ListModelMixin, GenericViewSet): @method_decorator(cache_page(60 * 10)) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) - - # def get_queryset(self): - # user = self.request.user - # queryset = self.queryset - # if user.is_superuser: - # return queryset - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictReadOnlyAdmin"]: - # return queryset.filter(facility__district=user.district) - # elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateReadOnlyAdmin"]: - # return queryset.filter(facility__state=user.state) - # return queryset.filter(facility__users__id__exact=user.id)