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

Scheduling Validations #2701

Merged
merged 3 commits into from
Jan 3, 2025
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
2 changes: 1 addition & 1 deletion care/emr/api/viewsets/facility.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def get_queryset(self):
return User.objects.filter(
id__in=SchedulableUserResource.objects.filter(
facility__external_id=self.kwargs["facility_external_id"]
).values("resource_id")
).values("user_id")
)


Expand Down
11 changes: 6 additions & 5 deletions care/emr/api/viewsets/scheduling/availability.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pydantic import UUID4, BaseModel, model_validator
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response

from care.emr.api.viewsets.base import EMRBaseViewSet, EMRRetrieveMixin
Expand All @@ -26,7 +27,7 @@


class SlotsForDayRequestSpec(BaseModel):
resource: UUID4
user: UUID4
day: datetime.date


Expand All @@ -38,7 +39,7 @@ class AppointmentBookingSpec(BaseModel):
class AvailabilityStatsRequestSpec(BaseModel):
from_date: datetime.date
to_date: datetime.date
resource: UUID4
user: UUID4

@model_validator(mode="after")
def validate_period(self):
Expand Down Expand Up @@ -105,12 +106,12 @@ def get_slots_for_day(self, request, *args, **kwargs):
@classmethod
def get_slots_for_day_handler(cls, facility_external_id, request_data):
request_data = SlotsForDayRequestSpec(**request_data)
user = User.objects.filter(external_id=request_data.resource).first()
user = get_object_or_404(User, external_id=request_data.user)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove redundant check after get_object_or_404
get_object_or_404 already handles the not-found scenario, so the manual if not user check right below is never reached.

 user = get_object_or_404(User, external_id=request_data.user)
-if not user:
-    raise ValidationError("Resource does not exist")

Committable suggestion skipped: line range outside the PR's diff.

if not user:
raise ValidationError("Resource does not exist")
schedulable_resource_obj = SchedulableUserResource.objects.filter(
facility__external_id=facility_external_id,
resource=user,
user=user,
).first()
if not schedulable_resource_obj:
raise ValidationError("Resource is not schedulable")
Expand Down Expand Up @@ -214,7 +215,7 @@ def availability_stats(self, request, *args, **kwargs):
user = User.objects.filter(external_id=request_data.resource).first()
if not user:
raise ValidationError("User does not exist")
resource = SchedulableUserResource.objects.filter(resource=user).first()
resource = SchedulableUserResource.objects.filter(user=user).first()
if not resource:
raise ValidationError("Resource is not schedulable")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


class AvailabilityExceptionFilters(FilterSet):
resource = UUIDFilter(field_name="resource__resource__external_id")
user = UUIDFilter(field_name="resource__user__external_id")


class AvailabilityExceptionsViewSet(EMRModelViewSet):
Expand Down
10 changes: 5 additions & 5 deletions care/emr/api/viewsets/scheduling/booking.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ class TokenBookingFilters(FilterSet):
status = CharFilter(field_name="status")
date = DateFilter(field_name="token_slot__start_datetime__date")
slot = UUIDFilter(field_name="token_slot__external_id")
resource = UUIDFilter(method="filter_by_resource")
user = UUIDFilter(method="filter_by_user")
patient = UUIDFilter(field_name="patient__external_id")

def filter_by_resource(self, queryset, name, value):
def filter_by_user(self, queryset, name, value):
if not value:
return queryset
resource = SchedulableUserResource.objects.filter(
resource__external_id=value
user__external_id=value
).first()
if not resource:
return queryset.none()
Expand Down Expand Up @@ -90,13 +90,13 @@ def get_queryset(self):
)

@action(detail=False, methods=["GET"])
def available_doctors(self, request, *args, **kwargs):
def available_users(self, request, *args, **kwargs):
facility = Facility.objects.get(external_id=self.kwargs["facility_external_id"])
facility_users = FacilityOrganizationUser.objects.filter(
organization__facility=facility,
user_id__in=SchedulableUserResource.objects.filter(
facility=facility
).values("resource_id"),
).values("user_id"),
)

return Response(
Expand Down
4 changes: 2 additions & 2 deletions care/emr/api/viewsets/scheduling/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


class ScheduleFilters(FilterSet):
resource = UUIDFilter(field_name="resource__resource__external_id")
user = UUIDFilter(field_name="resource__user__external_id")


class ScheduleViewSet(EMRModelViewSet):
Expand Down Expand Up @@ -51,7 +51,7 @@ def validate_data(self, instance, model_obj=None):
facility = self.get_facility_obj()
schedule_user = get_object_or_404(User, external_id=instance.user)
if not FacilityOrganizationUser.objects.filter(
user=schedule_user, facility=facility
user=schedule_user, organization__facility=facility
).exists():
raise ValidationError("Schedule User is not part of the facility")

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 5.1.3 on 2025-01-03 10:23

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("emr", "0060_alter_medicationrequest_dosage_instruction"),
]

operations = [
migrations.RenameField(
model_name="schedulableuserresource",
old_name="resource",
new_name="user",
),
migrations.AlterField(
model_name="medicationrequest",
name="dosage_instruction",
field=models.JSONField(blank=True, default=list, null=True),
),
]
2 changes: 1 addition & 1 deletion care/emr/models/scheduling/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class SchedulableUserResource(EMRBaseModel):
"""A resource that can be scheduled for appointments."""

facility = models.ForeignKey("facility.Facility", on_delete=models.CASCADE)
resource = models.ForeignKey("users.User", on_delete=models.CASCADE)
user = models.ForeignKey("users.User", on_delete=models.CASCADE)

# TODO : Index with resource and facility

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ def perform_extra_deserialization(self, is_update, obj):
if not is_update:
resource = None
try:
user_resource = User.objects.get(external_id=self.resource)
user = User.objects.get(external_id=self.resource)
resource = SchedulableUserResource.objects.get(
resource=user_resource,
user=user,
Comment on lines +39 to +41
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Clarify naming to avoid mixing "resource" and "user".

The parameter self.resource is now used to fetch a User, and then assigned to obj.resource. It works, but maybe rename the incoming data field to user_id or something less confusing. It’ll save you from an extra squint in the future.

facility=Facility.objects.get(external_id=self.facility),
)
obj.resource = resource
Expand Down
2 changes: 1 addition & 1 deletion care/emr/resources/scheduling/schedule/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def perform_extra_deserialization(self, is_update, obj):

resource, _ = SchedulableUserResource.objects.get_or_create(
facility=obj.facility,
resource=user,
user=user,
)
obj.resource = resource
obj.availabilities = self.availabilities
Expand Down
2 changes: 1 addition & 1 deletion care/emr/resources/scheduling/slot/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,5 @@ def perform_extra_serialization(cls, mapping, obj):
exclude=["meta"]
)
mapping["resource"] = UserSpec.serialize(
User.objects.get(id=obj.token_slot.resource.resource_id)
User.objects.get(id=obj.token_slot.resource.user_id)
).model_dump(exclude=["meta"])
12 changes: 5 additions & 7 deletions care/security/authorization/user_schedule.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from care.emr.models.organization import FacilityOrganizationUser
from care.security.authorization import AuthorizationController
from care.security.authorization.base import (
AuthorizationHandler,
)
from care.security.authorization.base import AuthorizationHandler
from care.security.permissions.user_schedule import UserSchedulePermissions


Expand Down Expand Up @@ -42,8 +40,8 @@ def can_write_user_schedule(self, user, facility, schedule_user):
Check if the user has permission to write schedules in the facility
"""
facility_orgs = FacilityOrganizationUser.objects.filter(
user=schedule_user, facility=facility
).values_list("parent_cache")
user=schedule_user, organization__facility=facility
).values_list("organization__parent_cache", flat=True)
cache = []
for org_cache in facility_orgs:
cache.extend(org_cache)
Expand All @@ -57,8 +55,8 @@ def can_write_user_booking(self, user, facility, schedule_user):
Check if the user has permission to write schedules in the facility
"""
facility_orgs = FacilityOrganizationUser.objects.filter(
user=schedule_user, facility=facility
).values_list("parent_cache")
user=schedule_user, organization__facility=facility
).values_list("organization__parent_cache", flat=True)
cache = []
for org_cache in facility_orgs:
cache.extend(org_cache)
Expand Down
Loading