views.py 4.28 KB
Newer Older
1 2 3 4 5 6 7 8
# App de gestion des users pour re2o
# Goulven Kermarec, Gabriel Détraz
# Gplv2
from django.shortcuts import render, redirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.context_processors import csrf
from django.template import Context, RequestContext, loader
from django.contrib import messages
9
from django.db.models import Max, ProtectedError
10

11 12
from .models import Facture, Article, Cotisation, Article
from .forms import NewFactureForm, EditFactureForm, ArticleForm, DelArticleForm, DelPaiementForm
13
from users.models import User
14

15
from dateutil.relativedelta import relativedelta
16
from django.utils import timezone
17

18 19 20 21 22
def form(ctx, template, request):
    c = ctx
    c.update(csrf(request))
    return render_to_response(template, c, context_instance=RequestContext(request))

23 24
def end_adhesion(user):
    """ Renvoie la date de fin d'adhésion d'un user, False sinon """
25
    date_max = Cotisation.objects.all().filter(facture=Facture.objects.all().filter(user=user).exclude(valid=False)).aggregate(Max('date_end'))['date_end__max']
26 27
    return date_max

28 29 30 31 32 33 34 35 36 37
def is_adherent(user):
    """ Renvoie si un user est à jour de cotisation """
    end = end_adhesion(user)
    if not end:
        return False
    elif end < timezone.now():
        return False
    else:
        return True

38
def create_cotis(facture, user, duration):
39 40
    """ Update et crée l'objet cotisation associé à une facture, prend en argument l'user, la facture pour la quantitéi, et l'article pour la durée"""
    cotisation=Cotisation(facture=facture)
41 42 43 44
    date_max = end_adhesion(user) or timezone.now()
    if date_max < timezone.now():
        datemax = timezone.now()
    cotisation.date_start=date_max
45
    cotisation.date_end = cotisation.date_start + relativedelta(months=duration) 
46 47 48
    cotisation.save()
    return

49
def new_facture(request, userid):
50 51 52 53 54 55
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, u"Utilisateur inexistant" )
        return redirect("/cotisations/")
    facture = Facture(user=user)
56 57
    facture_form = NewFactureForm(request.POST or None, instance=facture)
    if facture_form.is_valid():
58 59
        new_facture = facture_form.save(commit=False)
        article = facture_form.cleaned_data['article']
60 61
        new_facture.prix = sum(art.prix for art in article)
        new_facture.name = ' - '.join(art.name for art in article)
62
        new_facture.save()
63 64 65
        if any(art.cotisation for art in article):
            duration = sum(art.duration*facture.number for art in article if art.cotisation)
            create_cotis(new_facture, user, duration)
66 67 68
            messages.success(request, "La cotisation a été prolongée pour l'adhérent %s " % user.name )
        else:
            messages.success(request, "La facture a été crée")
69 70 71 72 73 74 75 76 77 78 79 80 81 82
        return redirect("/cotisations/")
    return form({'factureform': facture_form}, 'cotisations/facture.html', request)

def edit_facture(request, factureid):
    try:
        facture = Facture.objects.get(pk=factureid)
    except Facture.DoesNotExist:
        messages.error(request, u"Facture inexistante" )
        return redirect("/cotisations/")
    facture_form = EditFactureForm(request.POST or None, instance=facture)
    if facture_form.is_valid():
        facture_form.save()
        messages.success(request, "La facture a bien été modifiée")
        return redirect("/cotisations/")
83
    return form({'factureform': facture_form}, 'cotisations/facture.html', request)
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
def add_article(request):
    article = ArticleForm(request.POST or None)
    if article.is_valid():
        article.save()
        messages.success(request, "L'article a été ajouté")
        return redirect("/cotisations/")
    return form({'factureform': article}, 'cotisations/facture.html', request)

def del_article(request):
    article = DelArticleForm(request.POST or None)
    if article.is_valid():
        article_del = article.cleaned_data['articles']
        article_del.delete()
        messages.success(request, "Le/les articles ont été supprimé")
        return redirect("/cotisations/")
    return form({'factureform': article}, 'cotisations/facture.html', request)

102
def index(request):
103
    facture_list = Facture.objects.order_by('date').reverse()
104
    return render(request, 'cotisations/index.html', {'facture_list': facture_list})