Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from datetime import datetime, date
from django.db.models import Model, QuerySet
from aleksis.apps.untis import models as mysql_models
from aleksis.apps.untis.util.mysql.api_helper import (
date_to_untis_date,
untis_colour_to_hex,
)
from aleksis.apps.chronos import models as chronos_models
from aleksis.core import models as core_models
DB_NAME = "untis"
def run_using(obj):
return obj.using(DB_NAME)
TERM: mysql_models.Terms = None
def run_default_filter(qs: QuerySet, filter_term: bool = True) -> QuerySet:
""" Add a default filter in order to select the correct term """
global TERM
term_id, schoolyear_id, school_id, version_id = (
TERM.term_id,
TERM.schoolyear_id,
TERM.school_id,
TERM.version_id,
)
if filter_term:
return run_using(qs).filter(
school_id=school_id,
schoolyear_id=schoolyear_id,
version_id=version_id,
term_id=term_id,
)
else:
return run_using(qs).filter(
school_id=school_id, schoolyear_id=schoolyear_id, version_id=version_id
)
def get_term(date: date) -> mysql_models.Terms:
""" Get term valid for the provided date """
terms = run_using(mysql_models.Terms.objects).filter(
datefrom__lte=date_to_untis_date(date), dateto__gte=date_to_untis_date(date)
)
if not terms.exists():
raise Exception("Term needed")
return terms[0]
def untis_import_mysql():
global TERM
date = datetime.now().date()
TERM = get_term(date)
# Subjects
subjects = run_default_filter(mysql_models.Subjects.objects, filter_term=False)
for subject in subjects:
if not subject.name:
raise Exception("Short name needed.")
short_name = subject.name[:10]
name = subject.longname if subject.longname else short_name
new_subject, created = chronos_models.Subject.objects.get_or_create(
abbrev=short_name, defaults={"name": name}
)
new_subject.name = name
new_subject.colour_fg = untis_colour_to_hex(subject.forecolor)
new_subject.colour_bg = untis_colour_to_hex(subject.backcolor)
new_subject.save()
# Teachers
teachers = run_default_filter(mysql_models.Teacher.objects)
for teacher in teachers:
if not teacher.name:
raise Exception("Short name needed.")
short_name = teacher.name[:5]
first_name = teacher.firstname if teacher.firstname else "?"
last_name = teacher.longname if teacher.longname else teacher.name
new_teacher, created = core_models.Person.objects.get_or_create(
short_name=short_name,
defaults={"first_name": first_name, "last_name": last_name},
)