from django.http import HttpResponse, Http404 from django.db.models import Count from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from edt.models import Timetable, LastUpdate, Group, Subscription, Course from edt.utils import get_week import datetime def index(request): timetables = Timetable.objects.all() groups = Group.objects.filter(tp__isnull=False).order_by("name") for group in groups: courses = Course.objects.get_courses_for_group(group).values("begin").annotate(count=Count("begin")) weeks = [] for course in courses: year, week, _ = course["begin"].isocalendar() date, _ = get_week(year, week) if date not in weeks: weeks.append(date) group.weeks = weeks return render(request, "index.html", {"timetables": timetables, "groups": groups}) def timetable(request, timetable_slug, year, week, group_slug): start, end = get_week(int(year), int(week)) timetable = get_object_or_404(Timetable, slug=timetable_slug) group = get_object_or_404(Group, slug=group_slug, timetable=timetable) courses = Course.objects.get_courses_for_group(group, begin__gte=start, begin__lt=end) last_update = LastUpdate.objects.get(timetable=timetable, week=week, year=year) grouped_courses = [] for i, course in enumerate(courses): if i == 0 or courses[i - 1].begin.day != course.begin.day: grouped_courses.append([course]) else: grouped_courses[-1].append(course) return render(request, "timetable.html", {"timetable": timetable, "group": group, "courses": grouped_courses, "last_update": last_update.date, "year": year, "week": week}) def subscribe(request, timetable_slug, year, week, group_slug): group = get_object_or_404(Group, slug=group_slug) if request.method == "POST": subscription = Subscription(email=request.POST["email"], group=group) subscription.save() return redirect("timetable", timetable_slug=timetable_slug, year=year, week=week, group_slug=group_slug) else: timetable = get_object_or_404(Timetable, slug=timetable_slug) return render(request, "subscribe.html", {"timetable": timetable, "year": year, "week": week, "group": group}) def confirm_subscription(request, token): subscription = get_object_or_404(Subscription, token=token) if subscription.active: raise Http404() subscription.active = True subscription.save() year, week, day = timezone.now().isocalendar() if day >= 6: year, week, _ = (timezone.now() + datetime.timedelta(weeks=1)).isocalendar() return redirect("timetable", timetable_slug=subscription.group.timetable.slug, year=year, week=week, group_slug=subscription.group.slug) def cancel_subscription(request, token): subscription = get_object_or_404(Subscription, token=token) subscription.delete() return redirect("index")