From 3348bae0ccba1623ef0ed61424dea85c34054102 Mon Sep 17 00:00:00 2001
From: Jonathan Weth <git@jonathanweth.de>
Date: Sun, 28 Jul 2019 14:28:14 +0200
Subject: [PATCH] Show events in SMART PLAN

---
 biscuit/apps/untis/events.py | 24 +++++++++++++++---
 biscuit/apps/untis/plan.py   | 48 +++++++++++++++++++++++++++---------
 biscuit/apps/untis/sub.py    | 42 ++++++++++++++++++-------------
 3 files changed, 83 insertions(+), 31 deletions(-)

diff --git a/biscuit/apps/untis/events.py b/biscuit/apps/untis/events.py
index 6df6dfc..2d13314 100644
--- a/biscuit/apps/untis/events.py
+++ b/biscuit/apps/untis/events.py
@@ -1,10 +1,12 @@
 from django.conf import settings
 
+from schoolapps.settings import TIMETABLE_HEIGHT
 from .drive import drive
 from .api_helper import untis_date_to_date, date_to_untis_date
 from .api import row_by_row_helper, run_all
 from . import models
 
+
 #########
 # EVENT #
 #########
@@ -12,10 +14,11 @@ from . import models
 class Event(object):
     def __init__(self):
         self.filled = None
+        self.id = None
         self.text = None
         self.teachers = []
-        self.classes  = []
-        self.rooms    = []
+        self.classes = []
+        self.rooms = []
         self.absences = []
         self.from_date = None
         self.to_date = None
@@ -26,6 +29,8 @@ class Event(object):
     def create(self, db_obj):
         """0~0~19~0~1859~0,0~0~65~0~1860~0,0~0~21~0~1861~0,0~0~3~0~1862~0"""
         self.filled = True
+        self.id = db_obj.event_id
+
         event_parsed = db_obj.eventelement1.split(",")
         elements = []
         for element in event_parsed:
@@ -62,4 +67,17 @@ class Event(object):
 def get_all_events_by_date(date):
     d_i = int(date_to_untis_date(date))
     db_rows = run_all(models.Event.objects.filter(dateto__gte=d_i, datefrom__lte=d_i, deleted=0), filter_term=False)
-    return row_by_row_helper(db_rows, Event)
+    rows = row_by_row_helper(db_rows, Event)
+
+    # Remap the lesson numbers matching for the given date
+    for i, event in enumerate(rows):
+        if event.from_date != event.to_date:
+            if event.from_date == date:
+                event.to_lesson = TIMETABLE_HEIGHT
+            elif event.to_date == date:
+                event.from_lesson = 1
+            else:
+                event.from_lesson = 1
+                event.to_lesson = TIMETABLE_HEIGHT
+
+    return rows
diff --git a/biscuit/apps/untis/plan.py b/biscuit/apps/untis/plan.py
index f6f492a..48a2c12 100644
--- a/biscuit/apps/untis/plan.py
+++ b/biscuit/apps/untis/plan.py
@@ -5,8 +5,9 @@ from django.utils import timezone
 from schoolapps import settings
 from schoolapps.settings import LESSONS
 from untisconnect.api import format_classes, TYPE_CLASS, TYPE_TEACHER, TYPE_ROOM
+from untisconnect.events import get_all_events_by_date
 from untisconnect.parse import parse
-from untisconnect.sub import get_substitutions_by_date_as_dict, TYPE_CANCELLATION
+from untisconnect.sub import get_substitutions_by_date_as_dict, TYPE_CANCELLATION, generate_event_table
 
 
 class LessonContainer(object):
@@ -36,7 +37,9 @@ class LessonElementContainer(object):
         self.element = element
         self.room = room
         self.substitution = substitution
-        self.is_old = False
+        self.is_old = False  #
+
+        self.is_event = substitution["table"].is_event if substitution is not None else False
         if self.element is not None:
             self.classes_formatted = format_classes(self.element.classes)
 
@@ -47,8 +50,6 @@ def parse_lesson_times():
         start_split = t[0].split(":")
         start_time = timezone.datetime(year=2000, day=1, month=1, hour=int(start_split[0]), minute=int(start_split[1]))
         end_time = start_time + timezone.timedelta(minutes=45)
-        # print(start_time)
-        # print(end_time)
         times.append({
             "number": i + 1,
             "number_format": t[1],
@@ -66,16 +67,12 @@ def get_plan(type, id, smart=False, monday_of_week=None):
     times_parsed = parse_lesson_times()
 
     if smart:
-        # print("Get substitutions for smart plan")
         week_days = [monday_of_week + datetime.timedelta(days=i) for i in range(5)]
-        # print(week_days)
         subs_for_weekday = []
         for week_day in week_days:
-            # print(week_day)
             subs = get_substitutions_by_date_as_dict(week_day)
             subs_for_weekday.append(subs)
-            # print(subs)
-            # print(len(subs))
+
     # Init plan array
     plan = []
     already_added_subs_as_ids = []
@@ -106,7 +103,6 @@ def get_plan(type, id, smart=False, monday_of_week=None):
                 for time in lesson.times:
                     for j, lroom in enumerate(time.rooms):
                         if lroom.id == id:
-                            # print(lroom.name)
                             found = True
 
             # If the lesson element is important then add it to plan array
@@ -135,7 +131,8 @@ def get_plan(type, id, smart=False, monday_of_week=None):
                         if subs_for_weekday[time.day - 1].get(lesson.id, None) is not None:
                             for sub in subs_for_weekday[time.day - 1][lesson.id]:
                                 # ... check whether the sub has the right old teacher and the right lesson number
-                                if sub["sub"].teacher_old.id == element.teacher.id and sub["sub"].lesson == time.hour:
+                                if sub["sub"].teacher_old.id == element.teacher.id and \
+                                        sub["sub"].lesson == time.hour and sub["table"].is_event is False:
                                     matching_sub = sub
 
                         # If the lesson matches, add it to the list of already added subs
@@ -168,6 +165,7 @@ def get_plan(type, id, smart=False, monday_of_week=None):
             subs_for_this_weekday = subs_for_weekday[i]
             for lesson_id, subs in subs_for_this_weekday.items():
                 for sub in subs:
+
                     found = False
                     room = sub["sub"].room_old
                     if type == TYPE_CLASS:
@@ -193,4 +191,32 @@ def get_plan(type, id, smart=False, monday_of_week=None):
                         if sub["sub"].id not in already_added_subs_as_ids:
                             plan[sub["sub"].lesson - 1][0][i].append(element_container)
 
+            # Get all events for this week day
+            events = get_all_events_by_date(week_day)
+            event_table = generate_event_table(events)
+
+            for event in event_table:
+                found = False
+                # Check if event is relevant for type and id
+                if type == TYPE_CLASS:
+                    for _class in event.event.classes:
+                        if _class.id == id:
+                            found = True
+                elif type == TYPE_TEACHER:
+                    for teacher in event.teachers:
+                        if teacher.id == id:
+                            found = True
+
+                elif type == TYPE_ROOM:
+                    for room in event.rooms:
+                        if room.id == id:
+                            found = True
+
+                if found:
+                    # Add event to plan
+                    element_container = LessonElementContainer(None, None,
+                                                               substitution={"sub": None, "table": event})
+                    for j in range(event.event.from_lesson - 1, event.event.to_lesson):
+                        plan[j][0][i].append(element_container)
+
     return plan
diff --git a/biscuit/apps/untis/sub.py b/biscuit/apps/untis/sub.py
index 75dd550..50e59d7 100644
--- a/biscuit/apps/untis/sub.py
+++ b/biscuit/apps/untis/sub.py
@@ -156,6 +156,30 @@ class SubRow(object):
         self.text = ""
         self.extra = ""
         self.is_event = False
+        self.event = None
+
+
+def generate_event_table(events):
+    sub_rows = []
+    for event in events:
+        sub_row = SubRow()
+        sub_row.is_event = True
+        sub_row.event = event
+
+        if event.from_lesson != event.to_lesson:
+            sub_row.lesson = "{}.-{}.".format(event.from_lesson, event.to_lesson)
+
+        sub_row.classes = format_classes(event.classes)
+        sub_row.teachers = event.teachers
+        sub_row.rooms = event.rooms
+        sub_row.absences = event.absences
+
+        sub_row.color = "purple"
+        sub_row.text = event.text
+
+        sub_rows.append(sub_row)
+
+    return sub_rows
 
 
 def generate_sub_table(subs, events=[]):
@@ -203,23 +227,7 @@ def generate_sub_table(subs, events=[]):
 
         sub_rows.append(sub_row)
 
-    for event in events:
-        sub_row = SubRow()
-        sub_row.is_event = True
-
-        if event.from_lesson != event.to_lesson:
-            sub_row.lesson = "{}.-{}.".format(event.from_lesson, event.to_lesson)
-
-        sub_row.classes = format_classes(event.classes)
-        sub_row.teachers = event.teachers
-        sub_row.rooms = event.rooms
-        sub_row.absences = event.absences
-
-        sub_row.color = "purple"
-        sub_row.text = event.text
-
-        sub_rows.append(sub_row)
-
+    sub_rows += generate_event_table(events)
     sub_rows.sort(key=substitutions_sorter)
 
     return sub_rows
-- 
GitLab