shiftregister/shiftregister/team/views.py

105 lines
3.1 KiB
Python

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.db.models.fields import DateTimeField
from django.db.models import F, Count, Q, ExpressionWrapper
from .models import ShiftRegistration, Room, Shift, Helper
from django.views.generic import DetailView, ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from .forms import HelperShift
# Create your views here.
def index(request):
pass
@login_required(login_url="/admin/login/")
def shift_overview(request):
context = {}
context["running_shifts"] = [
shift
for shift in Shift.objects.annotate(
end_at=ExpressionWrapper(
F("start_at") + F("duration"),
output_field=DateTimeField(),
)
)
.filter(start_at__lte=timezone.now(), end_at__gte=timezone.now())
.order_by("start_at")
]
# probably can do some distinct/group by stuff but not sure how tih django queries
context["next_shifts"] = [
Shift.objects.filter(room=room, start_at__gt=timezone.now())
.order_by("start_at")
.first()
for room in Room.objects.all()
]
return render(request, "shift_overview.html", context)
def add_helper_shift(self):
pass
@login_required(login_url="/admin/login/")
def shift_detail(request, pk):
shift = get_object_or_404(Shift, pk=pk)
form = HelperShift()
if request.method == "POST":
form = HelperShift(request.POST)
if form.is_valid():
(reg, created) = ShiftRegistration.objects.get_or_create(
helper=form.cleaned_data["helper"], shift=shift
)
if created:
messages.add_message(
request,
messages.SUCCESS,
"Helfer erfolgreich zur Schicht hinzugefügt",
)
else:
messages.add_message(
request,
messages.WARNING,
"Helfer ist bereits für diese Schicht angemeldet",
)
return redirect("team:shift", pk=shift.pk)
context = {
"shift": shift,
"add_helper_form": form,
}
return render(request, "shift_detail.html", context)
class HelperDetail(LoginRequiredMixin, DetailView):
login_url = "/admin/login/"
template_name = "helper_detail.html"
model = Helper
class ShiftList(LoginRequiredMixin, ListView):
login_url = "/admin/login/"
template_name = "shift_list.html"
model = Shift
title = "Alle Schichten"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["title"] = self.title
return context
def get_ordering(self):
return ("start_at", "room_id")
class FreeShiftList(ShiftList):
title = "Freie Schichten"
def get_queryset(self):
return Shift.objects.annotate(reg_count=Count("shiftregistration")).filter(
start_at__gt=timezone.now(), room__required_helpers__gt=F("reg_count")
)