views.py 21.4 KB
Newer Older
Amap's avatar
Amap committed
1
# coding: utf8
2 3 4 5 6 7 8 9 10 11 12 13
# App de gestion des paniers pour Amap
# Gabriel Détraz
# Gplv2

from django.shortcuts import render_to_response, get_object_or_404, render, redirect
from django.core.context_processors import csrf
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, DelLivraisonForm
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
22 23

from users.views import User
24
from django.utils import timezone
25

26
from amap.settings import MINIMUM_LEVEL, PAGINATION_NUMBER
27 28 29 30 31 32 33 34 35 36

def form(ctx, template, request):
    c = ctx
    c.update(csrf(request))
    return render_to_response(
        template,
        c,
        context_instance=RequestContext(request)
    )

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
@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)
52 53 54 55 56 57 58 59 60 61
        commande.prix_unitaire = article_form.cleaned_data['article'].prix
        commande.nom = article_form.cleaned_data['article'].nom
        # 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)
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        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
81
        commande = FullEditCommandeForm(request.POST or None, instance=commande_instance)
82
    else:
83 84 85
        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
86
        commande = BaseEditCommandeForm(request.POST or None, instance=commande_instance)
87
    if commande.is_valid():
Gabriel Detraz's avatar
Gabriel Detraz committed
88
        new_commande = commande.save(commit=False)
89
        if commande_instance.user.solde() - new_commande.prix() < MINIMUM_LEVEL and not request.user.has_perms(('bureau',)):
Gabriel Detraz's avatar
Gabriel Detraz committed
90 91
            messages.error(request, "Solde insuffisant pour effectuer l'operation")
            return redirect("/panier/")
92 93 94 95
        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))
96
        messages.success(request, "Commande modifiée")
97 98 99 100 101 102 103 104 105 106 107 108 109
        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))
110 111 112
    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))
113 114 115 116 117 118 119 120
    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)

121 122 123 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
@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")
149
        return redirect("/panier/index_livraison/")
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 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
    return form({'panierform': livraison}, 'panier/panier.html', request)

@login_required
@permission_required('bureau')
def del_livraison(request):
    livraison = DelLivraisonForm(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)

@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)

221 222 223 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
@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)

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
@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)
293
    except Panier.DoesNotExist:
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        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
319 320 321 322 323 324 325 326 327 328 329 330
@login_required
@permission_required('bureau')
def control(request):
    commande_list = Commande.objects.order_by('date').reverse()
    controlform_set = modelformset_factory(Commande, fields=('livre',), extra=0)
    controlform = controlform_set(request.POST or None, queryset=commande_list)
    if controlform.is_valid():
        controlform.save()
        messages.success(request, "Livraisons enregistrees")
        return redirect("/panier/")
    return render(request, 'panier/control.html', {'controlform': controlform})

331 332 333 334 335 336 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 362 363 364 365 366 367
@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'))   
    user_instance.sac_consignes += 1
    user_instance.save() 
    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:
        user_instance.sac_consignes -= 1
        user_instance.save()
        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'))

368 369
@login_required
def history(request, object, id):
370 371 372 373 374 375 376 377 378
    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/")
379 380 381 382 383 384 385 386 387
    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/")
388
    elif object == 'paiement' and request.user.has_perms(('bureau',)):
389 390 391 392 393
        try:
             object_instance = Paiement.objects.get(pk=id)
        except Paiement.DoesNotExist:
             messages.error(request, "Paiement inexistant")
             return redirect("/panier/")
394 395 396 397 398 399
    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/")
400
    elif object == 'livraison' and request.user.has_perms(('bureau',)):
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        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/")
    reversions = reversion.get_for_object(object_instance)
    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})


423 424
@login_required
def index(request):
425
    paniers_list = Commande.objects.order_by('pk')
426
    credit_list = Credit.objects.order_by('pk')
427 428
    if not request.user.has_perms(('bureau',)):
        paniers_list = paniers_list.filter(user=request.user)
429 430 431
        credit_list = credit_list.filter(user=request.user)
    paginator_paniers = Paginator(paniers_list, PAGINATION_NUMBER)
    paginator_credit = Paginator(credit_list, PAGINATION_NUMBER)
432 433
    page = request.GET.get('page')
    try:
434 435 436 437 438 439 440 441 442
        paniers_list = paginator_paniers.page(page)
    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:
        credit_list = paginator_credit.page(page)
443 444
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
445
        credit_list = paginator_credit.page(1)
446 447
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
448 449
        credit_list = paginator_credit.page(paginator_credit.num_pages)

450 451 452 453
    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))
454
    solde_moyen = round(solde_total/user_total, 2)
455
    commandes_total = len(Commande.objects.all())
Amap's avatar
Amap committed
456 457 458 459
    try:
        next_livraison = Livraison.objects.order_by('date').filter(date__gt=timezone.now())[0]
    except IndexError:
        next_livraison = None
460
    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})
461

462 463 464 465 466
@login_required
def index_article(request):
    article_list = Panier.objects.order_by('nom')
    return render(request, 'panier/index_article.html', {'article_list':article_list})

467
@login_required
468
@permission_required('bureau')
469 470 471 472 473 474 475 476
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})