views.py 19.7 KB
Newer Older
1 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 15
from django.db import transaction
from reversion import revisions as reversion
16
from .models import Panier, Paiement, Commande, Credit, Livraison
17
from .forms import PaiementForm, CreditForm, CreditFullForm, DelPaiementForm, LivraisonForm, DelLivraisonForm
Gabriel Detraz's avatar
Gabriel Detraz committed
18 19
from .forms import PanierForm, DelPanierForm, SelectArticleForm, FullEditCommandeForm, BaseEditCommandeForm, NewCommandeForm
from django.forms import modelformset_factory, formset_factory
20 21

from users.views import User
22
from django.utils import timezone
23

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

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

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

119 120 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
@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")
147
        return redirect("/panier/index_livraison/")
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 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
    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)

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

273 274 275 276 277 278 279 280 281 282 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
@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)
    except Article.DoesNotExist:
        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
317 318 319 320 321 322 323 324 325 326 327 328
@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})

329 330
@login_required
def history(request, object, id):
331 332 333 334 335 336 337 338 339
    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/")
340 341 342 343 344 345 346 347 348
    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/")
349
    elif object == 'paiement' and request.user.has_perms(('bureau',)):
350 351 352 353 354
        try:
             object_instance = Paiement.objects.get(pk=id)
        except Paiement.DoesNotExist:
             messages.error(request, "Paiement inexistant")
             return redirect("/panier/")
355 356 357 358 359 360
    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/")
361
    elif object == 'livraison' and request.user.has_perms(('bureau',)):
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        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})


384 385
@login_required
def index(request):
386
    paniers_list = Commande.objects.order_by('pk')
387
    credit_list = Credit.objects.order_by('pk')
388 389
    if not request.user.has_perms(('bureau',)):
        paniers_list = paniers_list.filter(user=request.user)
390 391 392
        credit_list = credit_list.filter(user=request.user)
    paginator_paniers = Paginator(paniers_list, PAGINATION_NUMBER)
    paginator_credit = Paginator(credit_list, PAGINATION_NUMBER)
393 394
    page = request.GET.get('page')
    try:
395 396 397 398 399 400 401 402 403
        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)
404 405
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
406
        credit_list = paginator_credit.page(1)
407 408
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
409 410
        credit_list = paginator_credit.page(paginator_credit.num_pages)

411 412 413 414 415 416 417 418
    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))
    solde_moyen = solde_total/user_total
    commandes_total = len(Commande.objects.all())
    next_livraison = Livraison.objects.order_by('date').filter(date__gt=timezone.now())[0]
    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})
419

420 421 422 423 424
@login_required
def index_article(request):
    article_list = Panier.objects.order_by('nom')
    return render(request, 'panier/index_article.html', {'article_list':article_list})

425
@login_required
426
@permission_required('bureau')
427 428 429 430 431 432 433 434
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})