Skip to content
Snippets Groups Projects
Verified Commit cc773252 authored by Jonathan Weth's avatar Jonathan Weth :keyboard:
Browse files

Remove unnecessary old stuff from SchoolApps

parent 07501abc
No related branches found
No related tags found
1 merge request!13Resolve "Support import from MySQL"
import datetime
from django.utils import timezone, formats
from schoolapps.settings import LONG_WEEK_DAYS
from untisconnect.api import TYPE_TEACHER, get_teacher_by_shortcode, TYPE_CLASS, get_class_by_name, get_all_teachers, \
get_all_classes, get_all_rooms, get_all_subjects
from userinformation import UserInformation
def get_name_for_next_week_day_from_today() -> str:
"""
Return the next week day as you would say it from today: "today", "tomorrow" or "<weekday>"
:return: Formatted date
"""
# Next weekday
next_weekday: timezone.datetime = get_next_weekday_with_time(timezone.now(), timezone.now().time())
if next_weekday.date() == timezone.now().date():
# Today
date_formatted = "heute"
elif next_weekday.date() == timezone.now().date() + timezone.timedelta(days=1):
# Tomorrow
date_formatted = "morgen"
else:
# Other weekday
date_formatted = LONG_WEEK_DAYS[next_weekday.isoweekday() - 1][0]
return date_formatted
def get_calendar_weeks(year=timezone.datetime.now().year):
weeks = []
# Get first day of year > first calendar week
first_day_of_year = timezone.datetime(year=year, month=1, day=1)
if first_day_of_year.isoweekday() != 1:
days_to_next_monday = 1 - first_day_of_year.isoweekday()
first_day_of_year += datetime.timedelta(days=days_to_next_monday)
# Go for all weeks in year and create week dict
first_day_of_week = first_day_of_year
for i in range(52):
calendar_week = i + 1
last_day_of_week = first_day_of_week + datetime.timedelta(days=4)
weeks.append({
"calendar_week": calendar_week,
"first_day": first_day_of_week,
"last_day": last_day_of_week
})
first_day_of_week += datetime.timedelta(weeks=1)
return weeks
def find_out_what_is_today(year=None, month=None, day=None):
date = timezone.datetime.now()
time = datetime.datetime.now().time()
if year is not None and day is not None and month is not None:
date = timezone.datetime(year=year, month=month, day=day)
if date != timezone.datetime.now():
time = datetime.time(0)
return date, time
def get_calendar_week(calendar_week, year=timezone.datetime.now().year):
weeks = get_calendar_weeks(year=year)
for week in weeks:
if week["calendar_week"] == calendar_week:
return week
return None
def get_next_weekday(date=None):
"""Get the next weekday by a datetime object"""
if date is None:
date = timezone.now().date()
if date.isoweekday() in {6, 7}:
if date.isoweekday() == 6:
plus = 2
else:
plus = 1
date += datetime.timedelta(days=plus)
return date
def get_next_weekday_with_time(date=None, time=None) -> datetime.datetime:
"""Get the next weekday by a datetime object"""
if date is None:
date = timezone.now().date()
if time is None:
time = timezone.now().time()
if time > datetime.time(15, 35):
date += datetime.timedelta(days=1)
if date.isoweekday() in {6, 7}:
if date.isoweekday() == 6:
plus = 2
else:
plus = 1
date += datetime.timedelta(days=plus)
return date
def calendar_week(date: datetime) -> int:
return date.isocalendar()[1]
def weekday(date: datetime) -> int:
return date.isoweekday() - 1
def format_lesson_time(time: datetime) -> str:
return formats.date_format(time, "H:i")
from dashboard.caches import DRIVE_CACHE, Cache
from .api import *
def build_drive(force_update=False):
cached = DRIVE_CACHE.get()
if cached is not False and not force_update:
print("Drive come from cache")
return cached
odrive = {
"teachers": get_all_teachers(),
"rooms": get_all_rooms(),
"classes": get_all_classes(),
"subjects": get_all_subjects(),
"corridors": get_all_corridors(),
}
drive = {}
for key, value in odrive.items():
drive[key] = {}
for el in value:
id = el.id
drive[key][id] = el
DRIVE_CACHE.update(drive)
return drive
drive = build_drive()
import datetime
from django.utils import timezone
from dashboard import plan_caches
from schoolapps import settings
from schoolapps.settings import LESSONS
from untisconnect.api import TYPE_CLASS, TYPE_TEACHER, TYPE_ROOM
from untisconnect.api import format_classes, get_today_holidays
from untisconnect.datetimeutils import format_lesson_time
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, generate_event_table
class LessonContainer(object):
"""
Needed for Django template because template language does not support dictionaries
Saves the time object and the lesson elements
"""
def __init__(self, ):
self.time = None
self.elements = []
def set_time(self, time):
self.time = time
def append(self, element):
self.elements.append(element)
class LessonElementContainer(object):
"""
Needed for Django template because template language does not support dictionaries
Saves the lesson element object and the room (from time object)
"""
def __init__(self, element, room, substitution=None):
self.element = element
self.room = room
self.substitution = substitution
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)
def parse_lesson_times():
times = []
for i, t in enumerate(LESSONS):
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)
times.append({
"number": i + 1,
"number_format": t[1],
"start": start_time,
"start_format": format_lesson_time(start_time),
"end": end_time,
"end_format": format_lesson_time(end_time)
})
return times
def get_plan(type, id, smart=False, monday_of_week=None, force_update=False):
""" Generates a plan for type (TYPE_TEACHER, TYPE_CLASS, TYPE_ROOM) and a id of the teacher (class, room)"""
# Check cache
cache = plan_caches.get_cache_for_plan(type, id, smart, monday_of_week)
cached = cache.get()
# print(cached)
if cached is not False and not force_update:
# print("Plan come from cache", cache.id)
return cached
# Get parsed lessons
lessons = parse()
times_parsed = parse_lesson_times()
hols_for_weekdays = []
if smart:
week_days = [monday_of_week + datetime.timedelta(days=i) for i in range(5)]
subs_for_weekday = []
for week_day in week_days:
subs = get_substitutions_by_date_as_dict(week_day)
subs_for_weekday.append(subs)
hols = get_today_holidays(week_day)
hols_for_weekdays.append(hols)
# Init plan array
plan = []
already_added_subs_as_ids = []
# Fill plan array with LessonContainers (show upside), WIDTH and HEIGHT are defined by Django settings
for hour_idx in range(settings.TIMETABLE_HEIGHT):
plan.append(([], times_parsed[hour_idx] if len(times_parsed) > hour_idx else None))
for day_idx in range(settings.TIMETABLE_WIDTH):
plan[hour_idx][0].append(LessonContainer())
# Fill plan with lessons
for lesson in lessons:
for i, element in enumerate(lesson.elements):
# Check if the lesson element is important for that plan (look by type and id)
found = False
if type == TYPE_CLASS:
for lclass in element.classes:
if lclass.id == id:
found = True
elif type == TYPE_TEACHER:
if element.teacher:
if element.teacher.id == id:
found = True
elif type == TYPE_ROOM:
for time in lesson.times:
for j, lroom in enumerate(time.rooms):
if lroom.id == id:
found = True
# If the lesson element is important then add it to plan array
if found:
for time in lesson.times: # Go for every time the lesson is thought
# Find matching rooms
room_index = None
for j, lroom in enumerate(time.rooms):
if lroom.id == id:
room_index = j
# Add the time object to the matching LessonContainer on the right position in the plan array
plan[time.hour - 1][0][time.day - 1].set_time(time)
# Check if there is an room for this time and lesson
try:
room = time.rooms[i]
except IndexError:
room = None
# Smart Plan: Check if there substitutions for this lesson
matching_sub = None
if smart:
# If a sub with matching lesson id and day exists
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 is not None and element.teacher is not None:
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
if matching_sub:
already_added_subs_as_ids.append(matching_sub["sub"].id)
# Create a LessonElementContainer with room and lesson element
element_container = LessonElementContainer(element, room, substitution=matching_sub)
# Important for rooms: Check if the current room is the old room
if smart and matching_sub is not None:
if matching_sub["sub"].room_new is not None:
if matching_sub["sub"].room_old is not None:
if matching_sub["sub"].room_old != matching_sub["sub"].room_new:
element_container.is_old = True
else:
element_container.is_old = True
# The rooms is empty, too, if the lesson is canceled
if matching_sub["sub"].type == TYPE_CANCELLATION:
element_container.is_old = True
# Check for holidays
if smart and hols_for_weekdays[time.day - 1]:
element_container.is_hol = True
element_container.element.holiday_reason = hols_for_weekdays[time.day - 1][0].name
if type != TYPE_ROOM or i == room_index:
# Add this container object to the LessonContainer object in the plan array
plan[time.hour - 1][0][time.day - 1].append(element_container)
# Now check subs which were not in this plan before
if smart:
for i, week_day in enumerate(week_days):
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:
if sub["sub"].classes:
for _class in sub["sub"].classes:
if _class.id == id:
found = True
elif type == TYPE_TEACHER:
if sub["sub"].teacher_new:
if sub["sub"].teacher_new.id == id:
found = True
if sub["sub"].teacher_old:
if sub["sub"].teacher_old.id == id:
found = True
elif type == TYPE_ROOM:
if sub["sub"].room_new:
if sub["sub"].room_new.id == id:
found = True
if found:
element_container = LessonElementContainer(sub["sub"].lesson_element, room, substitution=sub)
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)
cache.update((plan, hols_for_weekdays))
return plan, hols_for_weekdays
from datetime import date, time, timedelta
from typing import BinaryIO, Optional, Union
from xml.dom import Node, minidom
from django.http import HttpRequest
from django.utils.translation import ugettext as _
from untisconnect.api import TYPE_TEACHER, get_teacher_by_shortcode, TYPE_CLASS, get_class_by_name, get_all_teachers, \
get_all_classes, get_all_rooms, get_all_subjects
from untisconnect.datetimeutils import get_calendar_week, calendar_week, weekday
from untisconnect.plan import get_plan
from userinformation import UserInformation
def get_type_and_object_of_user(user):
_type = UserInformation.user_type(user)
if _type == UserInformation.TEACHER:
# Teacher
_type = TYPE_TEACHER
shortcode = user.username
el = get_teacher_by_shortcode(shortcode)
elif _type == UserInformation.STUDENT:
# Student
_type = TYPE_CLASS
_name = UserInformation.user_classes(user)[0]
el = get_class_by_name(_name)
else:
# Nothing of both
return None, None
return _type, el
def overview_dict():
return {
'teachers': get_all_teachers(),
'classes': get_all_classes(),
'rooms': get_all_rooms(),
'subjects': get_all_subjects()
}
def get_plan_for_day(_type, plan_id, date):
# Get calendar week and monday of week
monday_of_week = get_calendar_week(calendar_week(date), date.year)["first_day"]
week_day = weekday(date)
# Get plan
plan, holidays = get_plan(_type, plan_id, smart=True, monday_of_week=monday_of_week)
lessons = [(row[week_day], time) for row, time in plan]
holidays_for_date = holidays[week_day]
return lessons, holidays_for_date
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment