views.py 23.3 KB
Newer Older
Amap's avatar
Amap committed
1
# coding: utf8
2 3 4 5 6
# App de gestion des paniers pour Amap
# Gabriel Détraz
# Gplv2

from django.shortcuts import render_to_response, get_object_or_404, render, redirect
Amap's avatar
Amap committed
7
from django.template.context_processors import csrf
8 9 10 11 12 13
from django.template import Context, RequestContext, loader
from django.contrib import messages
from django.db import IntegrityError
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required, permission_required
14
from django.http import HttpResponseRedirect
15

16 17
from django.db import transaction
from reversion import revisions as reversion
18
from .models import Panier, Paiement, Commande, Credit, Livraison
19
from .forms import PaiementForm, CreditForm, CreditFullForm, DelPaiementForm, LivraisonForm, SelectOneLivraisonForm, SelectLivraisonForm
Gabriel Detraz's avatar
Gabriel Detraz committed
20 21
from .forms import PanierForm, DelPanierForm, SelectArticleForm, FullEditCommandeForm, BaseEditCommandeForm, NewCommandeForm
from django.forms import modelformset_factory, formset_factory
Amap's avatar
Amap committed
22 23
from reversion.models import Version

24 25

from users.views import User
26
from django.utils import timezone
27

28
from amap.settings import MINIMUM_LEVEL, PAGINATION_LARGE_NUMBER, PAGINATION_NUMBER
29 30 31 32

def form(ctx, template, request):
    c = ctx
    c.update(csrf(request))
Amap's avatar
Amap committed
33 34
    return render(
        request,
35
        template,
Amap's avatar
Amap committed
36
        c
37 38
    )

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
@login_required
def new_commande(request, userid):
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, u"Utilisateur inexistant" )
        return redirect("/panier/")
    if not request.user.has_perms(('bureau',)) and user != request.user:
        messages.error(request, "Vous ne pouvez pas commander pour quelqu'un d'autre !")
        return redirect("/users/profil/" + str(request.user.id))
    commande = Commande(user=user)
    commande_form = NewCommandeForm(request.POST or None, instance=commande)
    article_form = SelectArticleForm(request.POST or None)
    if commande_form.is_valid() and article_form.is_valid():
        commande = commande_form.save(commit=False)
54 55
        commande.prix_unitaire = article_form.cleaned_data['article'].prix
        commande.nom = article_form.cleaned_data['article'].nom
56
        commande.coefficient_panier = article_form.cleaned_data['article'].coefficient_panier
57 58 59 60 61 62 63 64
        # Si non surdroits, check solde et date
        if not request.user.has_perms(('bureau',)):
            if timezone.now() > commande.date.date_modif:
                messages.error(request, "Vous ne pouvez plus passer commande, livraison proche")
                return redirect("/users/profil/" + str(request.user.id))
            if user.solde() - commande.prix() < MINIMUM_LEVEL:
                messages.error(request, "Solde insuffisant pour effectuer l'operation")
                return redirect("/users/profil/" + userid)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        with transaction.atomic(), reversion.create_revision():
            commande.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
        messages.success(request, "La commande est enregistree")
        return redirect("/users/profil/" + userid)
    return form({'article_form': article_form, 'commande_form': commande_form}, 'panier/new_commande.html', request) 

@login_required
def edit_commande(request, commandeid):
    try:
        commande_instance = Commande.objects.get(pk=commandeid)
    except Commande.DoesNotExist:
        messages.error(request, u"Entrée inexistante" )
        return redirect("/panier/")
    if not request.user.has_perms(('bureau',)) and commande_instance.user != request.user:
        messages.error(request, "Vous ne pouvez pas commander pour quelqu'un d'autre !")
        return redirect("/users/profil/" + str(request.user.id))
    if request.user.has_perms(('bureau',)):
Gabriel Detraz's avatar
Gabriel Detraz committed
84
        commande = FullEditCommandeForm(request.POST or None, instance=commande_instance)
85
    else:
86 87 88
        if timezone.now() > commande_instance.date.date_modif:
            messages.error(request, "Vous ne pouvez plus modifier la commande, livraison proche")
            return redirect("/users/profil/" + str(request.user.id))
Gabriel Detraz's avatar
Gabriel Detraz committed
89
        commande = BaseEditCommandeForm(request.POST or None, instance=commande_instance)
90
    if commande.is_valid():
Gabriel Detraz's avatar
Gabriel Detraz committed
91
        new_commande = commande.save(commit=False)
92
        if commande_instance.user.solde() - new_commande.prix() < MINIMUM_LEVEL and not request.user.has_perms(('bureau',)):
Gabriel Detraz's avatar
Gabriel Detraz committed
93 94
            messages.error(request, "Solde insuffisant pour effectuer l'operation")
            return redirect("/panier/")
95 96 97 98
        with transaction.atomic(), reversion.create_revision():
            commande.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in commande.changed_data))
99
        messages.success(request, "Commande modifiée")
100 101 102 103 104 105 106 107 108 109 110 111 112
        return redirect("/panier/")
    return form({'panierform': commande}, 'panier/panier.html', request)

@login_required
def del_commande(request, commandeid):
    try:
        commande = Commande.objects.get(pk=commandeid)
    except Commande.DoesNotExist:
        messages.error(request, u"Credit inexistant" )
        return redirect("/panier/")
    if not request.user.has_perms(('bureau',)) and commande.user != request.user:
        messages.error(request, "Vous ne pouvez pas commander pour quelqu'un d'autre !")
        return redirect("/users/profil/" + str(request.user.id))
113 114 115
    if timezone.now() > commande.date.date_modif and not request.user.has_perms(('bureau',)):
        messages.error(request, "Vous ne pouvez plus supprimer la commande, livraison proche")
        return redirect("/users/profil/" + str(request.user.id))
116 117 118 119 120 121 122 123
    if request.method == "POST":
        with transaction.atomic(), reversion.create_revision():
            commande.delete()
            reversion.set_user(request.user)
        messages.success(request, "La commande a été détruite")
        return redirect("/panier/")
    return form({'objet': commande, 'objet_name': 'commande'}, 'panier/delete.html', request)

Amap's avatar
Amap committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
@login_required
@permission_required('bureau')
def add_livraison(request):
    livraison = LivraisonForm(request.POST or None)
    if livraison.is_valid():
        with transaction.atomic(), reversion.create_revision():
            livraison.save()
            reversion.set_user(request.user)
            reversion.set_comment("Creation")
        messages.success(request, "La date de livraison a ete ajoutee")
        return redirect("/panier/index_livraison/")
    return form({'panierform': livraison}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def edit_livraison(request, livraisonid):
    try:
        livraison_instance = Livraison.objects.get(pk=livraisonid)
    except Livraison.DoesNotExist:
        messages.error(request, u"Entrée inexistante" )
        return redirect("/panier/")
    livraison = LivraisonForm(request.POST or None, instance=livraison_instance)
    if livraison.is_valid():
        with transaction.atomic(), reversion.create_revision():
            livraison.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in livraison.changed_data))
        messages.success(request, "Date modifiee")
        return redirect("/panier/index_livraison/")
    return form({'panierform': livraison}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def del_livraison(request):
    livraison = SelectLivraisonForm(request.POST or None)
    if livraison.is_valid():
        livraison_dels = livraison.cleaned_data['date']
        for livraison_del in livraison_dels:
            try:
                with transaction.atomic(), reversion.create_revision():
                    livraison_del.delete()
                    reversion.set_comment("Destruction")
                messages.success(request, "La date de livraison a ete supprimee")
            except ProtectedError:
                messages.error(
                    request,
                    "La livraison est affectee a au moins une commande, \
                        vous ne pouvez pas le supprimer" % livraison_del)
        return redirect("/panier/index_livraison/")
    return form({'panierform': livraison}, 'panier/panier.html', request)

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
@login_required
@permission_required('bureau')
def add_paiement(request):
    paiement = PaiementForm(request.POST or None)
    if paiement.is_valid():
        with transaction.atomic(), reversion.create_revision():
            paiement.save()
            reversion.set_user(request.user)
            reversion.set_comment("Creation")
        messages.success(request, "Le moyen de paiement a ete ajoute")
        return redirect("/panier/index_paiement/")
    return form({'panierform': paiement}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def edit_paiement(request, paiementid):
    try:
        paiement_instance = Paiement.objects.get(pk=paiementid)
    except Paiement.DoesNotExist:
        messages.error(request, "Entrée inexistante" )
        return redirect("/panier/index_paiement/")
    paiement = PaiementForm(request.POST or None, instance=paiement_instance)
    if paiement.is_valid():
        with transaction.atomic(), reversion.create_revision():
            paiement.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in paiement.changed_data))
        messages.success(request, "Type de paiement modifié")
        return redirect("/panier/index_paiement/")
    return form({'panierform': paiement}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def del_paiement(request):
    paiement = DelPaiementForm(request.POST or None)
    if paiement.is_valid():
        paiement_dels = paiement.cleaned_data['paiements']
        for paiement_del in paiement_dels:
            try:
                with transaction.atomic(), reversion.create_revision():
                    paiement_del.delete()
                    reversion.set_user(request.user)
                    reversion.set_comment("Destruction")
                messages.success(request, "Le moyen de paiement a été supprimé")
            except ProtectedError:
                messages.error(request, "Le moyen de paiement %s est affecté à au moins une facture, vous ne pouvez pas le supprimer" % paiement_del)
        return redirect("/panier/index_paiement/")
    return form({'panierform': paiement}, 'panier/panier.html', request)

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
@login_required
@permission_required('bureau')
def add_credit(request, userid):
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/panier/")
    credit = CreditForm(request.POST or None)
    if credit.is_valid():
        credit = credit.save(commit=False)
        credit.user = user 
        with transaction.atomic(), reversion.create_revision():
            credit.save()
            reversion.set_user(request.user)
            reversion.set_comment("Creation")
        messages.success(request, "Le credit a ete ajoute")
        return redirect("/panier/")
    return form({'panierform': credit}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def edit_credit(request, creditid):
    try:
        credit_instance = Credit.objects.get(pk=creditid)
    except Credit.DoesNotExist:
        messages.error(request, u"Entrée inexistante" )
        return redirect("/panier/")
    credit = CreditFullForm(request.POST or None, instance=credit_instance)
    if credit.is_valid():
        with transaction.atomic(), reversion.create_revision():
            credit.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in credit.changed_data))
        messages.success(request, "Date modifiee")
        return redirect("/panier/")
    return form({'panierform': credit}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def del_credit(request, creditid):
    try:
        credit = Credit.objects.get(pk=creditid)
    except Credit.DoesNotExist:
        messages.error(request, u"Credit inexistant" )
        return redirect("/panier/")
    if request.method == "POST":
        with transaction.atomic(), reversion.create_revision():
            credit.delete()
            reversion.set_user(request.user)
        messages.success(request, "Le credit a été détrite")
        return redirect("/panier/")
    return form({'objet': credit, 'objet_name': 'credit'}, 'panier/delete.html', request)

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
@login_required
@permission_required('bureau')
def add_article(request):
    article = PanierForm(request.POST or None)
    if article.is_valid():
        with transaction.atomic(), reversion.create_revision():
            article.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
        messages.success(request, "L'article a été ajouté")
        return redirect("/panier/index_article/")
    return form({'panierform': article}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def edit_article(request, articleid):
    try:
        article_instance = Panier.objects.get(pk=articleid)
296
    except Panier.DoesNotExist:
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        messages.error(request, u"Entrée inexistante" )
        return redirect("/panier/index_article/")
    article = PanierForm(request.POST or None, instance=article_instance)
    if article.is_valid():
        with transaction.atomic(), reversion.create_revision():
            article.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in article.changed_data))
        messages.success(request, "Type d'article modifié")
        return redirect("/panier/index_article/")
    return form({'panierform': article}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def del_article(request):
    article = DelPanierForm(request.POST or None)
    if article.is_valid():
        article_del = article.cleaned_data['paniers']
        with transaction.atomic(), reversion.create_revision():
            article_del.delete()
            reversion.set_user(request.user)
        messages.success(request, "Le/les articles ont été supprimé")
        return redirect("/panier/index_article")
    return form({'panierform': article}, 'panier/panier.html', request)

Gabriel Detraz's avatar
Gabriel Detraz committed
322 323
@login_required
@permission_required('bureau')
Amap's avatar
Amap committed
324 325 326 327 328 329 330 331 332 333 334 335
def control(request, livraisonid=False):
    if not livraisonid:
        livraison = SelectOneLivraisonForm(request.POST or None)
        if livraison.is_valid():
            return redirect("/panier/control/" + str(livraison.cleaned_data['date'].id))
        return render(request, 'panier/control.html', {'livraisonform': livraison})
    else:
        livraison_select = Livraison.objects.get(id=livraisonid)
        commande_list = Commande.objects.filter(date=livraison_select).order_by('date')
        controlform_set = modelformset_factory(Commande, fields=('livre',), extra=0)
        controlform = controlform_set(request.POST or None, queryset=commande_list)
        if controlform.is_valid():
Amap's avatar
Amap committed
336 337 338 339
            with transaction.atomic(), reversion.create_revision():
                controlform.save()
                reversion.set_user(request.user)
                reversion.set_comment("Etat de livraison")
Amap's avatar
Amap committed
340 341 342 343 344
            messages.success(request, "Livraisons enregistrees")
            return redirect("/panier/")
        livraison_commandes = len(Commande.objects.filter(date=Livraison.objects.filter(date=livraison_select.date)))
        livraison_paniers = sum(pan.coefficient_panier*pan.quantite for pan in Commande.objects.filter(date=Livraison.objects.filter(date=livraison_select.date)))
        return render(request, 'panier/control.html', {'controlform': controlform, 'livraison_commandes': livraison_commandes, 'livraison_paniers': livraison_paniers})
Gabriel Detraz's avatar
Gabriel Detraz committed
345

346 347 348 349 350 351 352 353 354 355 356 357
@login_required
@permission_required('bureau')
def add_sac(request, userid):
    try:
        user_instance = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, u"User inexistante" )
    try:
        article_instance = Panier.objects.get(nom="Sac")
    except Panier.DoesNotExist:
        messages.error(request, u"Merci de créer une entrée Sac" )
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))   
Amap's avatar
Amap committed
358 359 360 361 362
    with transaction.atomic(), reversion.create_revision():
        user_instance.sac_consignes += 1
        user_instance.save() 
        reversion.set_user(request.user)
        reversion.set_comment("Ajout sac")
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    messages.success(request, u"Sac ajouté à %s (dispose actuellement de %s sacs)" % (user_instance.get_full_name(), user_instance.sac_consignes) )
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

@login_required
@permission_required('bureau')
def del_sac(request, userid):
    try:
        user_instance = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, u"User inexistante" )
    try:
        article_instance = Panier.objects.get(nom="Sac")
    except Panier.DoesNotExist:
        messages.error(request, u"Merci de créer une entrée Sac" )
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    if user_instance.sac_consignes > 0:
Amap's avatar
Amap committed
379 380 381 382 383
        with transaction.atomic(), reversion.create_revision():
            user_instance.sac_consignes -= 1
            user_instance.save()
            reversion.set_user(request.user)
            reversion.set_comment("Retire sac")
384 385 386 387 388
        messages.success(request, u"Sac retiré à %s (dispose actuellement de %s sacs)" % (user_instance.get_full_name(), user_instance.sac_consignes) )
    else:
        messages.error(request, u"Nombre de sac nul !" )
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

389 390
@login_required
def history(request, object, id):
391 392 393 394 395 396 397 398 399
    if object == 'credit':
        try:
             object_instance = Credit.objects.get(pk=id)
        except Credit.DoesNotExist:
             messages.error(request, "Credit inexistant")
             return redirect("/panier/")
        if not request.user.has_perms(('bureau',)) and object_instance.user != request.user:
             messages.error(request, "Vous ne pouvez pas afficher l'historique d'une facture d'un autre user que vous sans droit ")
             return redirect("/panier/")
400 401 402 403 404 405 406 407 408
    elif object == 'commande':
        try:
             object_instance = Commande.objects.get(pk=id)
        except Commande.DoesNotExist:
             messages.error(request, "Commande inexistante")
             return redirect("/panier/")
        if not request.user.has_perms(('bureau',)) and object_instance.user != request.user:
             messages.error(request, "Vous ne pouvez pas afficher l'historique d'une commande d'un autre user que vous sans droit ")
             return redirect("/panier/")
409
    elif object == 'paiement' and request.user.has_perms(('bureau',)):
410 411 412 413 414
        try:
             object_instance = Paiement.objects.get(pk=id)
        except Paiement.DoesNotExist:
             messages.error(request, "Paiement inexistant")
             return redirect("/panier/")
415 416 417 418 419 420
    elif object == 'article' and request.user.has_perms(('bureau',)):
        try:
             object_instance = Panier.objects.get(pk=id)
        except Panier.DoesNotExist:
             messages.error(request, "Paiement inexistant")
             return redirect("/panier/")
421
    elif object == 'livraison' and request.user.has_perms(('bureau',)):
422 423 424 425 426 427 428 429
        try:
             object_instance = Livraison.objects.get(pk=id)
        except Livraison.DoesNotExist:
             messages.error(request, "Livraison inexistante")
             return redirect("/panier/")
    else:
        messages.error(request, "Objet  inconnu")
        return redirect("/panier/")
Amap's avatar
Amap committed
430
    reversions = Version.objects.get_for_object(object_instance)
431 432 433 434 435 436 437 438 439 440 441 442 443
    paginator = Paginator(reversions, PAGINATION_NUMBER)
    page = request.GET.get('page')
    try:
        reversions = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        reversions = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        reversions = paginator.page(paginator.num_pages)
    return render(request, 'amap/history.html', {'reversions': reversions, 'object': object_instance})


444 445
@login_required
def index(request):
446
    paniers_list = Commande.objects.order_by('date').reverse()
447
    credit_list = Credit.objects.order_by('pk').reverse()
448 449
    if not request.user.has_perms(('bureau',)):
        paniers_list = paniers_list.filter(user=request.user)
450
        credit_list = credit_list.filter(user=request.user)
451
    paginator_paniers = Paginator(paniers_list, PAGINATION_LARGE_NUMBER)
452
    paginator_credit = Paginator(credit_list, PAGINATION_NUMBER)
453 454
    page1 = request.GET.get('page1')
    page2 = request.GET.get('page2')
455
    try:
456
        paniers_list = paginator_paniers.page(page1)
457 458 459 460 461 462 463
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        paniers_list = paginator_paniers.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        paniers_list = paginator_paniers.page(paginator_paniers.num_pages)
    try:
464
        credit_list = paginator_credit.page(page2)
465 466
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
467
        credit_list = paginator_credit.page(1)
468 469
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
470 471
        credit_list = paginator_credit.page(paginator_credit.num_pages)

472 473 474 475
    management_view = request.user.has_perms(('bureau',))
    solde_total = sum(us.solde() for us in User.objects.all()) 
    user_total = len(User.objects.filter(state=0))
    user_ens = len(User.objects.filter(state=0).filter(is_ens=True))
476
    solde_moyen = round(solde_total/user_total, 2)
477
    commandes_total = len(Commande.objects.all())
Gabriel Detraz's avatar
Gabriel Detraz committed
478 479 480 481 482 483
    next_livraison = Livraison.objects.order_by('date').filter(date__gt=timezone.now()).first()
    next_livraison_commandes = 0
    next_livraison_paniers = 0
    if next_livraison:
        next_livraison_commandes = Commande.objects.filter(date=Livraison.objects.filter(date=next_livraison.date)).count()
        next_livraison_paniers = sum(pan.coefficient_panier*pan.quantite for pan in Commande.objects.filter(date=Livraison.objects.filter(date=next_livraison.date)))
484
    return render(request, 'panier/index.html', {'paniers_list': paniers_list, 'management_view': management_view, 'credit_list': credit_list, 'solde_total': solde_total, 'user_total': user_total, 'user_ens': user_ens, 'solde_moyen': solde_moyen, 'commandes_total': commandes_total, 'next_livraison': next_livraison, 'next_livraison_commandes': next_livraison_commandes, 'next_livraison_paniers': next_livraison_paniers})
485

486 487 488 489 490
@login_required
def index_article(request):
    article_list = Panier.objects.order_by('nom')
    return render(request, 'panier/index_article.html', {'article_list':article_list})

491
@login_required
492
@permission_required('bureau')
493 494 495 496 497 498 499 500
def index_paiement(request):
    paiement_list = Paiement.objects.order_by('moyen')
    return render(request, 'panier/index_paiement.html', {'paiement_list':paiement_list})

@login_required
def index_livraison(request):
    livraison_list = Livraison.objects.order_by('date')
    return render(request, 'panier/index_livraison.html', {'livraison_list':livraison_list})