2024-05-02 11:13:34 +02:00
|
|
|
from django.views.generic import DetailView, FormView, RedirectView
|
|
|
|
from django.views.generic.detail import SingleObjectMixin
|
|
|
|
from django.contrib import messages
|
|
|
|
from django.shortcuts import redirect
|
|
|
|
from inventory.models import Game
|
|
|
|
from .models import AbstractLoan
|
|
|
|
from .forms import BorrowForm
|
|
|
|
|
|
|
|
|
|
|
|
class ReturnView(SingleObjectMixin, RedirectView):
|
|
|
|
# Inherited classes should contain:
|
|
|
|
# model = LoanModel
|
|
|
|
# pattern_name =
|
|
|
|
redirect_slug_field = "slug"
|
|
|
|
|
|
|
|
permanent = False
|
|
|
|
|
|
|
|
def get_redirect_url(self, *args, **kwargs):
|
|
|
|
loan = self.get_object()
|
|
|
|
loan.return_object()
|
|
|
|
kwargs[self.redirect_slug_field] = getattr(loan.lent_object,
|
|
|
|
loan.lent_object_slug_field)
|
|
|
|
messages.success(self.request, "Rendu effectué.")
|
2024-05-06 16:24:16 +02:00
|
|
|
if "next" in self.request.GET:
|
|
|
|
return self.request.GET["next"]
|
2024-05-02 11:13:34 +02:00
|
|
|
return super().get_redirect_url(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class BorrowView(SingleObjectMixin, FormView):
|
|
|
|
# Inherited classes should contain:
|
|
|
|
# model = LentObjectModel
|
|
|
|
# loan_model = LoanModel
|
|
|
|
# template_name = "path/to/template.html"
|
|
|
|
form_class = BorrowForm # Update this for a more complex form
|
|
|
|
|
|
|
|
def get_initial(self):
|
|
|
|
initial = super().get_initial()
|
|
|
|
if "loan_mail" in self.request.session:
|
|
|
|
initial["mail"] = self.request.session["loan_mail"]
|
|
|
|
return initial
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
self.object = self.get_object()
|
|
|
|
return super().get_context_data(**kwargs)
|
|
|
|
|
|
|
|
def form_valid(self, form):
|
|
|
|
obj = self.get_object()
|
|
|
|
ongoing = self.loan_model.ongoing_loans(obj)
|
|
|
|
if ongoing.exists():
|
|
|
|
ongoing.get().return_object()
|
|
|
|
loan = self.loan_model(lent_object=obj, mail=form.cleaned_data["mail"])
|
|
|
|
loan.save()
|
|
|
|
self.request.session["loan_mail"] = loan.mail
|
|
|
|
messages.success(self.request, "Votre emprunt est enregistré.")
|
|
|
|
return redirect(self.success_pattern_name,
|
|
|
|
getattr(obj, loan.lent_object_slug_field))
|
|
|
|
|
|
|
|
class DetailLoanView(DetailView):
|
|
|
|
# Inherited classes should contain:
|
|
|
|
# model = LentObjectModel
|
|
|
|
# loan_model = LoanModel
|
|
|
|
# template_name = "path/to/template.html"
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super().get_context_data(**kwargs)
|
|
|
|
loans = self.loan_model.ongoing_loans(self.get_object())
|
|
|
|
is_borrowed = loans.exists()
|
|
|
|
context["is_borrowed"] = is_borrowed
|
|
|
|
if is_borrowed:
|
|
|
|
context["loan"] = loans.get()
|
|
|
|
return context
|
|
|
|
|