From b245dfe4c607feeac1928f9ab1896bfcaef94a88 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=B6rn=20K=C3=BCnsem=C3=B6ller?=
 <jkuensem@physik.uni-bielefeld.de>
Date: Thu, 28 Oct 2021 19:29:30 +0200
Subject: [PATCH] TMSS-605: filter for overlap of reservation and SUB times

---
 .../backend/src/tmss/tmssapp/models/specification.py | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/SAS/TMSS/backend/src/tmss/tmssapp/models/specification.py b/SAS/TMSS/backend/src/tmss/tmssapp/models/specification.py
index 51807426e83..31dbd3efcb8 100644
--- a/SAS/TMSS/backend/src/tmss/tmssapp/models/specification.py
+++ b/SAS/TMSS/backend/src/tmss/tmssapp/models/specification.py
@@ -1435,10 +1435,16 @@ class Reservation(NamedCommon, TemplateSchemaMixin):
             return None
 
     def _prevent_reserving_stations_that_are_used_in_active_units(self):
-        # todo: we cannot filter for status in SQL because is a property, find a way to reduce the queryset reasonably
-        # todo: filter for the time range of the reservation?
+        # Determine active scheduling units that overlap in time with the reservation
+        # Note: we cannot filter for status and on sky times in SQL because these are properties
+        # todo: find a way to reduce the initial queryset reasonably
         subs = SchedulingUnitBlueprint.objects.all()
-        active_subs = [x for x in subs if x.status in [SchedulingUnitBlueprint.Status.OBSERVING.value, SchedulingUnitBlueprint.Status.SCHEDULED.value]]
+        active_subs = [x for x in subs if (x.status in [SchedulingUnitBlueprint.Status.OBSERVING.value, SchedulingUnitBlueprint.Status.SCHEDULED.value]
+                                       and x.scheduled_on_sky_stop_time >= self.start_time)]
+        if self.stop_time:
+            active_subs = [x for x in active_subs if self.scheduled_on_sky_start_time <= self.stop_time]
+
+        # Raise an exception if any of these scheduling units uses a station that shall be reserved
         if "resources" in self.specifications_doc and "stations" in self.specifications_doc["resources"]:
             stations_to_reserve = self.specifications_doc['resources']['stations']
             for sub in active_subs:
-- 
GitLab