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 Reschedule API and serialize Facility in TokenBooking #2738

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
5 changes: 4 additions & 1 deletion care/emr/api/viewsets/scheduling/availability.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ def convert_availability_to_slots(availabilities):
return slots


def lock_create_appointment(token_slot, patient, created_by, reason_for_visit):
def lock_create_appointment(
token_slot, patient, created_by, reason_for_visit, previous_booking=None
):
with Lock(f"booking:resource:{token_slot.resource.id}"), transaction.atomic():
if token_slot.allocated >= token_slot.availability.tokens_per_slot:
raise ValidationError("Slot is already full")
Expand All @@ -90,6 +92,7 @@ def lock_create_appointment(token_slot, patient, created_by, reason_for_visit):
booked_by=created_by,
reason_for_visit=reason_for_visit,
status="booked",
previous_booking=previous_booking,
)


Expand Down
44 changes: 42 additions & 2 deletions care/emr/api/viewsets/scheduling/booking.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.db import transaction
from django_filters import CharFilter, DateFromToRangeFilter, FilterSet, UUIDFilter
from django_filters.rest_framework import DjangoFilterBackend
from pydantic import BaseModel
from pydantic import UUID4, BaseModel
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
from rest_framework.generics import get_object_or_404
Expand All @@ -15,6 +15,8 @@
EMRRetrieveMixin,
EMRUpdateMixin,
)
from care.emr.api.viewsets.scheduling import lock_create_appointment
from care.emr.models import TokenSlot
from care.emr.models.scheduling import SchedulableUserResource, TokenBooking
from care.emr.resources.scheduling.slot.spec import (
CANCELLED_STATUS_CHOICES,
Expand All @@ -29,10 +31,16 @@

class CancelBookingSpec(BaseModel):
reason: Literal[
BookingStatusChoices.cancelled, BookingStatusChoices.entered_in_error
BookingStatusChoices.cancelled,
BookingStatusChoices.entered_in_error,
BookingStatusChoices.rescheduled,
]


class RescheduleBookingSpec(BaseModel):
new_slot: UUID4


class TokenBookingFilters(FilterSet):
status = CharFilter(field_name="status")
date = DateFromToRangeFilter(field_name="token_slot__start_datetime__date")
Expand Down Expand Up @@ -117,6 +125,38 @@ def cancel(self, request, *args, **kwargs):
self.authorize_update({}, instance)
return self.cancel_appointment_handler(instance, request.data, request.user)

@action(detail=True, methods=["POST"])
def reschedule(self, request, *args, **kwargs):
request_data = RescheduleBookingSpec(**request.data)
existing_booking = self.get_object()
facility = self.get_facility_obj()
self.authorize_update({}, existing_booking)
if not AuthorizationController.call(
"can_create_appointment", self.request.user, facility
):
raise PermissionDenied("You do not have permission to create appointments")
new_slot = get_object_or_404(
TokenSlot,
external_id=request_data.new_slot,
resource=existing_booking.token_slot.resource,
)
with transaction.atomic():
self.cancel_appointment_handler(
existing_booking,
{"reason": BookingStatusChoices.rescheduled},
request.user,
)
appointment = lock_create_appointment(
new_slot,
existing_booking.patient,
request.user,
existing_booking.reason_for_visit,
previous_booking=existing_booking,
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

The transaction handling looks good, but consider adding capacity validation.

While the transaction ensures atomicity, we should verify that the new slot has available capacity before canceling the existing booking.

 with transaction.atomic():
+    if new_slot.allocated >= new_slot.availability.tokens_per_slot:
+        raise ValidationError("Selected slot is already at capacity")
     self.cancel_appointment_handler(
         existing_booking,
         {"reason": BookingStatusChoices.rescheduled},
         request.user,
     )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with transaction.atomic():
self.cancel_appointment_handler(
existing_booking,
{"reason": BookingStatusChoices.rescheduled},
request.user,
)
appointment = lock_create_appointment(
new_slot,
existing_booking.patient,
request.user,
existing_booking.reason_for_visit,
previous_booking=existing_booking,
)
with transaction.atomic():
if new_slot.allocated >= new_slot.availability.tokens_per_slot:
raise ValidationError("Selected slot is already at capacity")
self.cancel_appointment_handler(
existing_booking,
{"reason": BookingStatusChoices.rescheduled},
request.user,
)
appointment = lock_create_appointment(
new_slot,
existing_booking.patient,
request.user,
existing_booking.reason_for_visit,
previous_booking=existing_booking,
)

return Response(
TokenBookingReadSpec.serialize(appointment).model_dump(exclude=["meta"])
)

@action(detail=False, methods=["GET"])
def available_users(self, request, *args, **kwargs):
facility = Facility.objects.get(external_id=self.kwargs["facility_external_id"])
Expand Down
24 changes: 24 additions & 0 deletions care/emr/migrations/0007_tokenbooking_previous_booking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 5.1.3 on 2025-01-14 09:37

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("emr", "0006_alter_patient_blood_group"),
]

operations = [
migrations.AddField(
model_name="tokenbooking",
name="previous_booking",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="emr.tokenbooking",
),
),
]
3 changes: 3 additions & 0 deletions care/emr/models/scheduling/booking.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@ class TokenBooking(EMRBaseModel):
booked_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
status = models.CharField()
reason_for_visit = models.TextField(null=True, blank=True)
previous_booking = models.ForeignKey(
"TokenBooking", on_delete=models.SET_NULL, null=True, blank=True
)
10 changes: 9 additions & 1 deletion care/emr/resources/scheduling/slot/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
from care.emr.models.scheduling.booking import TokenSlot
from care.emr.models.scheduling.schedule import Availability
from care.emr.resources.base import EMRResource
from care.emr.resources.facility.spec import FacilityBareMinimumSpec
from care.emr.resources.patient.otp_based_flow import PatientOTPReadSpec
from care.emr.resources.user.spec import UserSpec
from care.facility.models import Facility
from care.users.models import User


Expand Down Expand Up @@ -52,17 +54,19 @@ class BookingStatusChoices(str, Enum):
checked_in = "checked_in"
waitlist = "waitlist"
in_consultation = "in_consultation"
rescheduled = "rescheduled"


CANCELLED_STATUS_CHOICES = [
BookingStatusChoices.entered_in_error.value,
BookingStatusChoices.cancelled.value,
BookingStatusChoices.rescheduled.value,
]


class TokenBookingBaseSpec(EMRResource):
__model__ = TokenBooking
__exclude__ = ["token_slot", "patient"]
__exclude__ = ["token_slot", "patient", "previous_booking"]


class TokenBookingWriteSpec(TokenBookingBaseSpec):
Expand All @@ -83,6 +87,7 @@ class TokenBookingReadSpec(TokenBookingBaseSpec):
status: str
reason_for_visit: str
user: dict = {}
facility: dict = {}

@classmethod
def perform_extra_serialization(cls, mapping, obj):
Expand All @@ -96,3 +101,6 @@ def perform_extra_serialization(cls, mapping, obj):
mapping["user"] = UserSpec.serialize(
User.objects.get(id=obj.token_slot.resource.user_id)
).model_dump(exclude=["meta"])
mapping["facility"] = FacilityBareMinimumSpec.serialize(
Facility.objects.get(id=obj.token_slot.resource.facility_id)
).model_dump(exclude=["meta"])
rithviknishad marked this conversation as resolved.
Show resolved Hide resolved
Loading