diff --git a/application_form/api/sales/views.py b/application_form/api/sales/views.py index ea6dc398..366c32a5 100644 --- a/application_form/api/sales/views.py +++ b/application_form/api/sales/views.py @@ -57,6 +57,7 @@ ApplicationTimeNotFinishedException, ) from application_form.services.lottery.machine import distribute_apartments +from application_form.services.queue import _adjust_positions from application_form.services.reservation import ( transfer_reservation_to_another_customer, ) @@ -243,15 +244,38 @@ def set_state(self, request, pk=None): queue_position = state_change_event_serializer.validated_data.get( "queue_position", None ) - if queue_position is not None: - reservation.queue_position = queue_position + new_state = state_change_event_serializer.validated_data.get("state") + + if ( + queue_position is not None + and new_state != ApartmentReservationState.CANCELED + ): + # conver queue_position from string to number + if isinstance(queue_position, str): + queue_position = int(queue_position.lstrip("0")) + + # position correction in queue + _adjust_positions( + ApartmentReservation.objects.filter( + apartment_uuid=reservation.apartment_uuid + ), + "queue_position", + queue_position, + by=1, + ) + # set state and position state_change_event = reservation.set_state( **state_change_event_serializer.validated_data, user=request.user, ) - if queue_position is not None: + if ( + queue_position is not None + and new_state != ApartmentReservationState.CANCELED + ): + # save new position to database + reservation.queue_position = queue_position reservation.save(update_fields=["queue_position"]) return Response( diff --git a/application_form/models/reservation.py b/application_form/models/reservation.py index 81427781..b2bc7aa7 100644 --- a/application_form/models/reservation.py +++ b/application_form/models/reservation.py @@ -135,6 +135,8 @@ def set_state( ) if queue_position is not None: + if isinstance(queue_position, str): + queue_position = int(queue_position.lstrip("0")) self.queue_position = queue_position state_change_event = ApartmentReservationStateChangeEvent.objects.create(