views.py 25.7 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, CreditNoteForm, 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
from reversion.models import Version
23
from fractions import Fraction
Amap's avatar
Amap committed
24

25
from amap.settings import note_server, note_port, note_id
26 27

from users.views import User
28
from django.utils import timezone
29

30
from amap.settings import MINIMUM_LEVEL, PAGINATION_LARGE_NUMBER, PAGINATION_NUMBER
31

32 33
from .note import connect, login, don

34 35 36
def form(ctx, template, request):
    c = ctx
    c.update(csrf(request))
Amap's avatar
Amap committed
37 38
    return render(
        request,
39
        template,
Amap's avatar
Amap committed
40
        c
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)
54
    commande_form = NewCommandeForm(request.POST or None, instance=commande, is_bureau=request.user.has_perms(('bureau',)))
55 56 57
    article_form = SelectArticleForm(request.POST or None)
    if commande_form.is_valid() and article_form.is_valid():
        commande = commande_form.save(commit=False)
58 59
        commande.prix_unitaire = article_form.cleaned_data['article'].prix
        commande.nom = article_form.cleaned_data['article'].nom
60
        commande.coefficient_panier = article_form.cleaned_data['article'].coefficient_panier
61 62 63 64 65 66 67 68
        # 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)
69 70 71 72 73 74
        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)
75
    return form({'article_form': article_form, 'commande_form': commande_form}, 'panier/new_commande.html', request)
76 77 78 79 80 81 82 83 84 85 86 87

@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
88
        commande = FullEditCommandeForm(request.POST or None, instance=commande_instance)
89
    else:
90 91 92
        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
93
        commande = BaseEditCommandeForm(request.POST or None, instance=commande_instance)
94
    if commande.is_valid():
Gabriel Detraz's avatar
Gabriel Detraz committed
95
        new_commande = commande.save(commit=False)
96
        if commande_instance.user.solde() - new_commande.prix() < MINIMUM_LEVEL and not request.user.has_perms(('bureau',)):
Gabriel Detraz's avatar
Gabriel Detraz committed
97 98
            messages.error(request, "Solde insuffisant pour effectuer l'operation")
            return redirect("/panier/")
99 100 101 102
        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))
103
        messages.success(request, "Commande modifiée")
104 105
        #return redirect("/panier/")
        return HttpResponseRedirect("")
106 107 108 109 110 111 112 113 114 115 116 117
    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))
118 119 120
    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))
121 122 123 124 125 126 127 128
    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
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 175 176 177 178 179
@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)

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 224 225 226 227 228
@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)

229 230 231 232 233 234 235 236 237 238 239
@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)
240
        credit.user = user
241 242 243 244 245
        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")
246
        return redirect("/users/profil/" + userid)
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 278 279 280 281 282
    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)

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
@login_required
def add_credit_note(request, userid):
    """
    Build a request to start the negociation with NoteKfet
    """
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/panier/")
    noteform = CreditNoteForm(request.POST or None)
    if noteform.is_valid():
        pseudo = noteform.cleaned_data['login']
        password = noteform.cleaned_data['password']
        montant = noteform.cleaned_data['montant']
        result, sock, err = login(note_server, note_port, pseudo, password)
        if not result:
            messages.error(request, err)
            return redirect("/users/profil/" + userid)
        else:
            result, err = don(sock, montant, note_id)
            if not result:
                messages.error(request, err)
                return redirect("/users/profil/" + userid)
        moyen = Paiement.objects.filter(moyen='Note Kfet (self)').get()
        moyen.save()
        credit = Credit(user=user,montant=montant,moyen=moyen,validite=True)
        with transaction.atomic(), reversion.create_revision():
            credit.save()
            reversion.set_user(request.user)
            reversion.set_comment("Creation")
        messages.success(request, "Le paiement par note a bien été effectué")
        return redirect("/users/profil/" + userid)
    return form({'panierform': noteform}, 'panier/panier.html', request)

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
@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)
336
    except Panier.DoesNotExist:
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        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
362 363
@login_required
@permission_required('bureau')
Amap's avatar
Amap committed
364 365 366 367 368 369 370 371 372 373 374 375
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
376 377 378 379
            with transaction.atomic(), reversion.create_revision():
                controlform.save()
                reversion.set_user(request.user)
                reversion.set_comment("Etat de livraison")
Amap's avatar
Amap committed
380
            messages.success(request, "Livraisons enregistrees")
381
            return redirect("/panier/control/")
Amap's avatar
Amap committed
382 383
        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)))
384 385
        livraison_quantite={}
        for coeff in list(Commande.objects.all().values_list('coefficient_panier', flat=True).distinct()):
386 387
            livraison_quantite[Fraction(coeff)]=Commande.objects.filter(date=Livraison.objects.filter(date=livraison_select.date)).filter(livre=False).filter(coefficient_panier=coeff).count()

388
        return render(request, 'panier/control.html', {'controlform': controlform, 'livraison_commandes': livraison_commandes, 'livraison_paniers': livraison_paniers,'livraison_quantite':livraison_quantite})
Gabriel Detraz's avatar
Gabriel Detraz committed
389

390 391 392 393 394 395 396 397 398 399 400
@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" )
401
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Amap's avatar
Amap committed
402 403
    with transaction.atomic(), reversion.create_revision():
        user_instance.sac_consignes += 1
404
        user_instance.save()
Amap's avatar
Amap committed
405 406
        reversion.set_user(request.user)
        reversion.set_comment("Ajout sac")
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    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
423 424 425 426 427
        with transaction.atomic(), reversion.create_revision():
            user_instance.sac_consignes -= 1
            user_instance.save()
            reversion.set_user(request.user)
            reversion.set_comment("Retire sac")
428 429 430 431 432
        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'))

433 434
@login_required
def history(request, object, id):
435 436 437 438 439 440 441 442 443
    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/")
444 445 446 447 448 449 450 451 452
    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/")
453
    elif object == 'paiement' and request.user.has_perms(('bureau',)):
454 455 456 457 458
        try:
             object_instance = Paiement.objects.get(pk=id)
        except Paiement.DoesNotExist:
             messages.error(request, "Paiement inexistant")
             return redirect("/panier/")
459 460 461 462 463 464
    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/")
465
    elif object == 'livraison' and request.user.has_perms(('bureau',)):
466 467 468 469 470 471 472 473
        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
474
    reversions = Version.objects.get_for_object(object_instance)
475 476 477 478 479 480 481 482 483 484 485 486 487
    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})


488 489
@login_required
def index(request):
490
    paniers_list = Commande.objects.order_by('date').reverse()
491
    credit_list = Credit.objects.order_by('pk').reverse()
492 493
    if not request.user.has_perms(('bureau',)):
        paniers_list = paniers_list.filter(user=request.user)
494
        credit_list = credit_list.filter(user=request.user)
495
    paginator_paniers = Paginator(paniers_list, PAGINATION_LARGE_NUMBER)
496
    paginator_credit = Paginator(credit_list, PAGINATION_NUMBER)
497 498
    page1 = request.GET.get('page1')
    page2 = request.GET.get('page2')
499
    try:
500
        paniers_list = paginator_paniers.page(page1)
501 502 503 504 505 506 507
    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:
508
        credit_list = paginator_credit.page(page2)
509 510
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
511
        credit_list = paginator_credit.page(1)
512 513
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
514 515
        credit_list = paginator_credit.page(paginator_credit.num_pages)

516
    management_view = request.user.has_perms(('bureau',))
517
    solde_total = sum(us.solde() for us in User.objects.all())
518 519
    user_total = len(User.objects.filter(state=0))
    user_ens = len(User.objects.filter(state=0).filter(is_ens=True))
520
    solde_moyen = round(solde_total/user_total, 2)
521
    commandes_total = len(Commande.objects.all())
Gabriel Detraz's avatar
Gabriel Detraz committed
522 523 524 525 526 527
    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)))
528
    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})
529

530 531 532 533 534
@login_required
def index_article(request):
    article_list = Panier.objects.order_by('nom')
    return render(request, 'panier/index_article.html', {'article_list':article_list})

535
@login_required
536
@permission_required('bureau')
537 538 539 540 541 542 543 544
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})
Amap's avatar
Amap committed
545 546 547 548 549 550 551

@login_required
def plusProcheLivraison(request):
    liste_livraisons = Livraison.objects.all()
    liste_delta=[abs(timezone.now()-livraison.date) for livraison in liste_livraisons]
    proche=liste_livraisons[liste_delta.index(min(liste_delta))]
    return redirect("/panier/control/"+str(proche.id))