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 django.core.mail import send_mail from django.conf import settings from django.template import Context, loader from edt.forms import SubscribeForm from edt.models import Timetable, LastUpdate, Group, Subscription, Course from edt.utils import get_week, group_courses import datetime def index(request): timetables = Timetable.objects.all() groups = Group.objects.filter(tp__isnull=False).order_by("name") current_year, current_week, _ = timezone.now().isocalendar() start, _ = get_week(current_year, current_week) for group in groups: courses = Course.objects.get_courses_for_group(group, begin__gte=start).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, group_slug, year, week): start, end = get_week(int(year), int(week)) group = get_object_or_404(Group, slug=group_slug) courses = Course.objects.get_courses_for_group(group, begin__gte=start, begin__lt=end) last_update = LastUpdate.objects.get(timetable=group.timetable, week=week, year=year) grouped_courses = group_courses(courses) return render(request, "timetable.html", {"group": group, "courses": grouped_courses, "last_update": last_update.date, "year": year, "week": int(week)}) def subscribe(request, group_slug, year, week): group = get_object_or_404(Group, slug=group_slug) if request.method == "POST": form = SubscribeForm(request.POST) if form.is_valid(): subscription = Subscription(email=request.POST["email"], group=group) subscription.save() template = loader.get_template("mail/mail_confirm.txt") context = Context({"group": group, "admins": settings.ADMINS, "token": subscription.token}) send_mail("Confirmation de l'abonnemenent", template.render(context), settings.DEFAULT_FROM_EMAIL, [request.POST["email"]]) return redirect("timetable", group_slug=group_slug, year=year, week=int(week)) else: form = SubscribeForm() return render(request, "subscribe.html", {"year": year, "week": week, "group": group, "form": form}) 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", group_slug=subscription.group.slug, year=year, week=week) def cancel_subscription(request, token): subscription = get_object_or_404(Subscription, token=token) subscription.delete() return redirect("index")