2016-09-01 00:45:44 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
from __future__ import (absolute_import, division,
|
|
|
|
print_function, unicode_literals)
|
|
|
|
from builtins import *
|
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
from django.shortcuts import render, get_object_or_404, redirect
|
2016-08-07 17:02:01 +02:00
|
|
|
from django.core.exceptions import PermissionDenied, ValidationError
|
2016-08-22 05:41:31 +02:00
|
|
|
from django.core.cache import cache
|
2016-08-04 05:21:04 +02:00
|
|
|
from django.views.generic import ListView, DetailView
|
2016-08-27 14:12:01 +02:00
|
|
|
from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView
|
2016-08-04 05:21:04 +02:00
|
|
|
from django.core.urlresolvers import reverse_lazy
|
|
|
|
from django.contrib import messages
|
|
|
|
from django.contrib.messages.views import SuccessMessageMixin
|
2016-08-20 19:35:45 +02:00
|
|
|
from django.contrib.auth import authenticate, login
|
2016-08-02 10:40:46 +02:00
|
|
|
from django.contrib.auth.decorators import login_required, permission_required
|
2016-08-21 02:53:35 +02:00
|
|
|
from django.contrib.auth.models import User, Permission, Group
|
2016-08-06 22:19:52 +02:00
|
|
|
from django.http import HttpResponse, JsonResponse, Http404
|
2016-08-27 14:12:01 +02:00
|
|
|
from django.forms import modelformset_factory, formset_factory
|
2017-02-23 22:07:38 +01:00
|
|
|
from django.forms.models import model_to_dict
|
2016-08-08 00:24:46 +02:00
|
|
|
from django.db import IntegrityError, transaction
|
2016-12-01 04:29:28 +01:00
|
|
|
from django.db.models import Q, F, Sum, Prefetch, Count, Func
|
2016-08-23 20:31:31 +02:00
|
|
|
from django.db.models.functions import Coalesce
|
2016-08-08 07:44:05 +02:00
|
|
|
from django.utils import timezone
|
2016-08-20 19:35:45 +02:00
|
|
|
from django.utils.crypto import get_random_string
|
2016-08-02 10:40:46 +02:00
|
|
|
from gestioncof.models import CofProfile, Clipper
|
2016-08-31 02:52:13 +02:00
|
|
|
from kfet.decorators import teamkfet_required
|
2016-08-11 15:14:23 +02:00
|
|
|
from kfet.models import (Account, Checkout, Article, Settings, AccountNegative,
|
2016-08-27 14:12:01 +02:00
|
|
|
CheckoutStatement, GenericTeamToken, Supplier, SupplierArticle, Inventory,
|
2016-12-01 04:29:28 +01:00
|
|
|
InventoryArticle, Order, OrderArticle, TransferGroup, Transfer)
|
2016-08-03 04:38:54 +02:00
|
|
|
from kfet.forms import *
|
2016-08-06 22:19:52 +02:00
|
|
|
from collections import defaultdict
|
2016-08-14 19:59:36 +02:00
|
|
|
from kfet import consumers
|
2016-08-28 05:39:34 +02:00
|
|
|
from datetime import timedelta
|
2016-08-20 21:08:33 +02:00
|
|
|
import django_cas_ng
|
2016-09-01 16:31:18 +02:00
|
|
|
import hashlib
|
2016-08-28 05:39:34 +02:00
|
|
|
import heapq
|
|
|
|
import statistics
|
2016-08-02 10:40:46 +02:00
|
|
|
|
|
|
|
@login_required
|
|
|
|
def home(request):
|
|
|
|
return render(request, "kfet/base.html")
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-20 19:35:45 +02:00
|
|
|
def login_genericteam(request):
|
2016-09-29 21:36:17 +02:00
|
|
|
# Check si besoin de déconnecter l'utilisateur de CAS
|
2016-08-20 21:08:33 +02:00
|
|
|
profile, _ = CofProfile.objects.get_or_create(user=request.user)
|
2016-09-29 21:36:17 +02:00
|
|
|
need_cas_logout = False
|
2016-08-20 21:08:33 +02:00
|
|
|
if profile.login_clipper:
|
2016-09-29 21:36:17 +02:00
|
|
|
need_cas_logout = True
|
|
|
|
# Récupèration de la vue de déconnexion de CAS
|
|
|
|
# Ici, car request sera modifié après
|
2016-08-20 21:08:33 +02:00
|
|
|
logout_cas = django_cas_ng.views.logout(request)
|
|
|
|
|
2016-09-29 21:36:17 +02:00
|
|
|
# Authentification du compte générique
|
2016-08-20 19:35:45 +02:00
|
|
|
token = GenericTeamToken.objects.create(token=get_random_string(50))
|
|
|
|
user = authenticate(username="kfet_genericteam", token=token.token)
|
|
|
|
login(request, user)
|
2016-08-20 21:08:33 +02:00
|
|
|
|
2016-09-29 21:36:17 +02:00
|
|
|
if need_cas_logout:
|
|
|
|
# Vue de déconnexion de CAS
|
2016-08-20 21:08:33 +02:00
|
|
|
return logout_cas
|
|
|
|
|
2016-08-20 19:35:45 +02:00
|
|
|
return render(request, "kfet/login_genericteam.html")
|
|
|
|
|
2016-08-02 10:40:46 +02:00
|
|
|
def put_cleaned_data_in_dict(dict, form):
|
|
|
|
for field in form.cleaned_data:
|
|
|
|
dict[field] = form.cleaned_data[field]
|
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
# -----
|
|
|
|
# Account views
|
|
|
|
# -----
|
|
|
|
|
|
|
|
# Account - General
|
|
|
|
|
2016-08-02 10:40:46 +02:00
|
|
|
@login_required
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-03 04:38:54 +02:00
|
|
|
def account(request):
|
2016-08-24 23:34:14 +02:00
|
|
|
accounts = Account.objects.select_related('cofprofile__user').order_by('trigramme')
|
2016-08-03 04:38:54 +02:00
|
|
|
return render(request, "kfet/account.html", { 'accounts' : accounts })
|
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
@login_required
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-04 05:21:04 +02:00
|
|
|
def account_is_validandfree_ajax(request):
|
2016-08-15 01:48:22 +02:00
|
|
|
if not request.GET.get("trigramme", ''):
|
2016-08-04 05:21:04 +02:00
|
|
|
raise Http404
|
|
|
|
trigramme = request.GET.get("trigramme")
|
|
|
|
data = Account.is_validandfree(trigramme)
|
2016-08-06 22:19:52 +02:00
|
|
|
return JsonResponse(data)
|
2016-08-04 05:21:04 +02:00
|
|
|
|
|
|
|
# Account - Create
|
|
|
|
|
2016-09-05 07:31:54 +02:00
|
|
|
@login_required
|
|
|
|
@teamkfet_required
|
|
|
|
def account_create_special(request):
|
|
|
|
|
|
|
|
# Enregistrement
|
|
|
|
if request.method == "POST":
|
|
|
|
trigramme_form = AccountTriForm(request.POST, initial={'balance':0})
|
|
|
|
balance_form = AccountBalanceForm(request.POST)
|
|
|
|
|
|
|
|
# Peuplement des forms
|
|
|
|
username = request.POST.get('username')
|
|
|
|
login_clipper = request.POST.get('login_clipper')
|
|
|
|
|
|
|
|
forms = get_account_create_forms(
|
|
|
|
request, username=username, login_clipper=login_clipper)
|
|
|
|
|
|
|
|
account_form = forms['account_form']
|
|
|
|
cof_form = forms['cof_form']
|
|
|
|
user_form = forms['user_form']
|
|
|
|
|
|
|
|
if all((user_form.is_valid(), cof_form.is_valid(),
|
|
|
|
trigramme_form.is_valid(), account_form.is_valid(),
|
|
|
|
balance_form.is_valid())):
|
|
|
|
# Checking permission
|
|
|
|
if not request.user.has_perm('kfet.special_add_account'):
|
|
|
|
messages.error(request, 'Permission refusée')
|
|
|
|
else:
|
|
|
|
data = {}
|
|
|
|
# Fill data for Account.save()
|
|
|
|
put_cleaned_data_in_dict(data, user_form)
|
|
|
|
put_cleaned_data_in_dict(data, cof_form)
|
|
|
|
|
|
|
|
try:
|
|
|
|
account = trigramme_form.save(data = data)
|
|
|
|
account_form = AccountNoTriForm(request.POST, instance=account)
|
|
|
|
account_form.save()
|
|
|
|
balance_form = AccountBalanceForm(request.POST, instance=account)
|
|
|
|
balance_form.save()
|
|
|
|
amount = balance_form.cleaned_data['balance']
|
|
|
|
checkout = Checkout.objects.get(name='Initial')
|
|
|
|
is_cof = account.is_cof
|
|
|
|
opegroup = OperationGroup.objects.create(
|
|
|
|
on_acc=account,
|
|
|
|
checkout=checkout,
|
|
|
|
amount = amount,
|
|
|
|
is_cof = account.is_cof)
|
|
|
|
ope = Operation.objects.create(
|
|
|
|
group = opegroup,
|
|
|
|
type = Operation.INITIAL,
|
|
|
|
amount = amount,
|
|
|
|
is_checkout = False)
|
|
|
|
messages.success(request, 'Compte créé : %s' % account.trigramme)
|
|
|
|
return redirect('kfet.account.create')
|
|
|
|
except Account.UserHasAccount as e:
|
|
|
|
messages.error(request, \
|
|
|
|
"Cet utilisateur a déjà un compte K-Fêt : %s" % e.trigramme)
|
|
|
|
else:
|
|
|
|
initial = { 'trigramme': request.GET.get('trigramme', '') }
|
|
|
|
trigramme_form = AccountTriForm(initial = initial)
|
|
|
|
balance_form = AccountBalanceForm(initial = {'balance': 0})
|
|
|
|
account_form = None
|
|
|
|
cof_form = None
|
|
|
|
user_form = None
|
|
|
|
|
|
|
|
return render(request, "kfet/account_create_special.html", {
|
|
|
|
'trigramme_form': trigramme_form,
|
|
|
|
'account_form': account_form,
|
|
|
|
'cof_form': cof_form,
|
|
|
|
'user_form': user_form,
|
|
|
|
'balance_form': balance_form,
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
# Account - Create
|
|
|
|
|
2016-08-03 04:38:54 +02:00
|
|
|
@login_required
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-03 04:38:54 +02:00
|
|
|
def account_create(request):
|
|
|
|
|
2016-08-02 10:40:46 +02:00
|
|
|
# Enregistrement
|
|
|
|
if request.method == "POST":
|
2016-09-01 05:01:59 +02:00
|
|
|
trigramme_form = AccountTriForm(request.POST)
|
2016-08-03 04:38:54 +02:00
|
|
|
|
2016-08-02 10:40:46 +02:00
|
|
|
# Peuplement des forms
|
|
|
|
username = request.POST.get('username')
|
2016-09-01 05:01:59 +02:00
|
|
|
login_clipper = request.POST.get('login_clipper')
|
|
|
|
|
|
|
|
forms = get_account_create_forms(
|
|
|
|
request, username=username, login_clipper=login_clipper)
|
|
|
|
|
|
|
|
account_form = forms['account_form']
|
|
|
|
cof_form = forms['cof_form']
|
|
|
|
user_form = forms['user_form']
|
2016-08-03 04:38:54 +02:00
|
|
|
|
2016-08-02 10:40:46 +02:00
|
|
|
if all((user_form.is_valid(), cof_form.is_valid(),
|
|
|
|
trigramme_form.is_valid(), account_form.is_valid())):
|
2016-09-01 05:01:59 +02:00
|
|
|
# Checking permission
|
|
|
|
if not request.user.has_perm('kfet.add_account'):
|
|
|
|
messages.error(request, 'Permission refusée')
|
|
|
|
else:
|
|
|
|
data = {}
|
|
|
|
# Fill data for Account.save()
|
|
|
|
put_cleaned_data_in_dict(data, user_form)
|
|
|
|
put_cleaned_data_in_dict(data, cof_form)
|
2016-08-02 10:40:46 +02:00
|
|
|
|
2016-09-01 05:01:59 +02:00
|
|
|
try:
|
|
|
|
account = trigramme_form.save(data = data)
|
|
|
|
account_form = AccountNoTriForm(request.POST, instance=account)
|
|
|
|
account_form.save()
|
|
|
|
messages.success(request, 'Compte créé : %s' % account.trigramme)
|
|
|
|
return redirect('kfet.account.create')
|
|
|
|
except Account.UserHasAccount as e:
|
|
|
|
messages.error(request, \
|
|
|
|
"Cet utilisateur a déjà un compte K-Fêt : %s" % e.trigramme)
|
|
|
|
else:
|
2016-09-03 15:21:26 +02:00
|
|
|
initial = { 'trigramme': request.GET.get('trigramme', '') }
|
|
|
|
trigramme_form = AccountTriForm(initial = initial)
|
2016-09-01 05:01:59 +02:00
|
|
|
account_form = None
|
|
|
|
cof_form = None
|
|
|
|
user_form = None
|
|
|
|
|
|
|
|
return render(request, "kfet/account_create.html", {
|
|
|
|
'trigramme_form': trigramme_form,
|
|
|
|
'account_form': account_form,
|
|
|
|
'cof_form': cof_form,
|
|
|
|
'user_form': user_form,
|
|
|
|
})
|
2016-08-02 10:40:46 +02:00
|
|
|
|
2016-08-03 04:38:54 +02:00
|
|
|
def account_form_set_readonly_fields(user_form, cof_form):
|
2016-08-02 10:40:46 +02:00
|
|
|
user_form.fields['username'].widget.attrs['readonly'] = True
|
|
|
|
cof_form.fields['login_clipper'].widget.attrs['readonly'] = True
|
|
|
|
cof_form.fields['is_cof'].widget.attrs['disabled'] = True
|
|
|
|
|
2016-09-01 05:01:59 +02:00
|
|
|
def get_account_create_forms(request=None, username=None, login_clipper=None):
|
2016-08-02 10:40:46 +02:00
|
|
|
user = None
|
2016-09-01 05:01:59 +02:00
|
|
|
clipper = None
|
2016-09-06 19:49:28 +02:00
|
|
|
if login_clipper and (login_clipper == username or not username):
|
2016-08-02 10:40:46 +02:00
|
|
|
# à partir d'un clipper
|
2016-08-15 01:48:22 +02:00
|
|
|
# le user associé à ce clipper ne devrait pas encore exister
|
2016-08-02 10:40:46 +02:00
|
|
|
clipper = get_object_or_404(Clipper, username = login_clipper)
|
|
|
|
try:
|
|
|
|
# Vérification que clipper ne soit pas déjà dans User
|
2016-08-03 04:38:54 +02:00
|
|
|
user = User.objects.get(username=login_clipper)
|
2016-08-02 10:40:46 +02:00
|
|
|
# Ici, on nous a menti, le user existe déjà
|
|
|
|
username = user.username
|
2016-09-05 08:19:28 +02:00
|
|
|
clipper = None
|
2016-08-02 10:40:46 +02:00
|
|
|
except User.DoesNotExist:
|
|
|
|
# Clipper (sans user déjà existant)
|
|
|
|
|
2016-09-01 05:01:59 +02:00
|
|
|
# UserForm - Prefill
|
|
|
|
user_initial = {
|
2016-08-02 10:40:46 +02:00
|
|
|
'username' : login_clipper,
|
2016-08-15 01:48:22 +02:00
|
|
|
'email' : "%s@clipper.ens.fr" % login_clipper}
|
2016-08-02 10:40:46 +02:00
|
|
|
if clipper.fullname:
|
|
|
|
# Prefill du nom et prénom
|
|
|
|
names = clipper.fullname.split()
|
|
|
|
# Le premier, c'est le prénom
|
2016-09-01 05:01:59 +02:00
|
|
|
user_initial['first_name'] = names[0]
|
2016-08-02 10:40:46 +02:00
|
|
|
if len(names) > 1:
|
|
|
|
# Si d'autres noms -> tous dans le nom de famille
|
2016-09-01 05:01:59 +02:00
|
|
|
user_initial['last_name'] = " ".join(names[1:])
|
|
|
|
# CofForm - Prefill
|
|
|
|
cof_initial = { 'login_clipper': login_clipper }
|
|
|
|
|
|
|
|
# Form créations
|
|
|
|
if request:
|
|
|
|
user_form = UserForm(request.POST, initial=user_initial, from_clipper=True)
|
|
|
|
cof_form = CofForm(request.POST, initial=cof_initial)
|
|
|
|
else:
|
2016-09-01 15:03:33 +02:00
|
|
|
user_form = UserForm(initial=user_initial, from_clipper=True)
|
2016-09-01 05:01:59 +02:00
|
|
|
cof_form = CofForm(initial=cof_initial)
|
2016-08-02 10:40:46 +02:00
|
|
|
|
|
|
|
# Protection (read-only) des champs username et login_clipper
|
2016-08-03 04:38:54 +02:00
|
|
|
account_form_set_readonly_fields(user_form, cof_form)
|
2016-09-01 15:03:33 +02:00
|
|
|
if username and not clipper:
|
2016-09-01 05:01:59 +02:00
|
|
|
try:
|
|
|
|
user = User.objects.get(username=username)
|
|
|
|
# le user existe déjà
|
|
|
|
# récupération du profil cof
|
|
|
|
(cof, _) = CofProfile.objects.get_or_create(user=user)
|
|
|
|
# UserForm + CofForm - Création à partir des instances existantes
|
|
|
|
if request:
|
|
|
|
user_form = UserForm(request.POST, instance = user)
|
|
|
|
cof_form = CofForm(request.POST, instance = cof)
|
|
|
|
else:
|
|
|
|
user_form = UserForm(instance=user)
|
|
|
|
cof_form = CofForm(instance=cof)
|
|
|
|
# Protection (read-only) des champs username, login_clipper et is_cof
|
|
|
|
account_form_set_readonly_fields(user_form, cof_form)
|
|
|
|
except User.DoesNotExist:
|
|
|
|
# le username donnée n'existe pas -> Création depuis rien
|
|
|
|
# (éventuellement en cours avec erreurs précédemment)
|
|
|
|
pass
|
|
|
|
if not user and not clipper:
|
2016-08-02 10:40:46 +02:00
|
|
|
# connaît pas du tout, faut tout remplir
|
2016-09-01 05:01:59 +02:00
|
|
|
if request:
|
|
|
|
user_form = UserForm(request.POST)
|
|
|
|
cof_form = CofForm(request.POST)
|
|
|
|
else:
|
|
|
|
user_form = UserForm()
|
|
|
|
cof_form = CofForm()
|
|
|
|
# mais on laisse le username en écriture
|
2016-08-31 00:36:23 +02:00
|
|
|
cof_form.fields['login_clipper'].widget.attrs['readonly'] = True
|
|
|
|
cof_form.fields['is_cof'].widget.attrs['disabled'] = True
|
2016-08-02 10:40:46 +02:00
|
|
|
|
2016-09-01 05:01:59 +02:00
|
|
|
if request:
|
|
|
|
account_form = AccountNoTriForm(request.POST)
|
|
|
|
else:
|
|
|
|
account_form = AccountNoTriForm()
|
|
|
|
|
|
|
|
return {
|
|
|
|
'account_form': account_form,
|
|
|
|
'cof_form': cof_form,
|
|
|
|
'user_form': user_form,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@login_required
|
|
|
|
@teamkfet_required
|
|
|
|
def account_create_ajax(request, username=None, login_clipper=None):
|
|
|
|
forms = get_account_create_forms(request=None, username=username, login_clipper=login_clipper)
|
2016-08-03 04:38:54 +02:00
|
|
|
return render(request, "kfet/account_create_form.html", {
|
2016-09-01 05:01:59 +02:00
|
|
|
'account_form' : forms['account_form'],
|
|
|
|
'cof_form' : forms['cof_form'],
|
|
|
|
'user_form' : forms['user_form'],
|
2016-08-02 10:40:46 +02:00
|
|
|
})
|
|
|
|
|
2017-02-23 22:07:38 +01:00
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
# Account - Read
|
2016-08-03 04:38:54 +02:00
|
|
|
|
|
|
|
@login_required
|
|
|
|
def account_read(request, trigramme):
|
2016-08-24 23:34:14 +02:00
|
|
|
try:
|
2017-02-23 22:07:38 +01:00
|
|
|
account = Account.objects.select_related('negative')\
|
|
|
|
.get(trigramme=trigramme)
|
2016-08-24 23:34:14 +02:00
|
|
|
except Account.DoesNotExist:
|
|
|
|
raise Http404
|
2016-08-03 04:38:54 +02:00
|
|
|
|
|
|
|
# Checking permissions
|
|
|
|
if not request.user.has_perm('kfet.is_team') \
|
2016-08-04 05:21:04 +02:00
|
|
|
and request.user != account.user:
|
2016-08-03 04:38:54 +02:00
|
|
|
raise PermissionDenied
|
|
|
|
|
2017-02-23 22:07:38 +01:00
|
|
|
if request.GET.get('format') == 'json':
|
|
|
|
data = model_to_dict(
|
|
|
|
account,
|
|
|
|
fields=['id', 'trigramme', 'firstname', 'lastname', 'email',
|
|
|
|
'is_cof', 'promo', 'balance', 'is_frozen', 'departement',
|
|
|
|
'nickname', 'trigramme']
|
|
|
|
)
|
|
|
|
data['name'] = account.name
|
|
|
|
return JsonResponse(data)
|
|
|
|
|
|
|
|
addcosts = (
|
|
|
|
OperationGroup.objects
|
|
|
|
.filter(opes__addcost_for=account, opes__canceled_at=None)
|
|
|
|
.extra({'date': "date(at)"})
|
|
|
|
.values('date')
|
|
|
|
.annotate(sum_addcosts=Sum('opes__addcost_amount'))
|
|
|
|
.order_by('-date')
|
|
|
|
)
|
2016-08-23 18:15:41 +02:00
|
|
|
|
2016-08-20 17:18:41 +02:00
|
|
|
return render(request, "kfet/account_read.html", {
|
2017-02-23 22:07:38 +01:00
|
|
|
'account': account,
|
2016-08-23 18:15:41 +02:00
|
|
|
'addcosts': addcosts,
|
2017-02-23 22:07:38 +01:00
|
|
|
'settings': {'subvention_cof': Settings.SUBVENTION_COF()},
|
2016-08-24 23:34:14 +02:00
|
|
|
})
|
2016-08-03 04:38:54 +02:00
|
|
|
|
2017-02-23 22:07:38 +01:00
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
# Account - Update
|
|
|
|
|
2016-08-03 04:38:54 +02:00
|
|
|
@login_required
|
|
|
|
def account_update(request, trigramme):
|
2016-08-15 01:48:22 +02:00
|
|
|
account = get_object_or_404(Account, trigramme=trigramme)
|
2016-08-03 04:38:54 +02:00
|
|
|
|
|
|
|
# Checking permissions
|
2016-08-04 05:21:04 +02:00
|
|
|
if not request.user.has_perm('kfet.is_team') \
|
|
|
|
and request.user != account.user:
|
2016-08-03 04:38:54 +02:00
|
|
|
raise PermissionDenied
|
|
|
|
|
2016-08-21 02:53:35 +02:00
|
|
|
if request.user.has_perm('kfet.is_team'):
|
|
|
|
user_form = UserRestrictTeamForm(instance=account.user)
|
|
|
|
group_form = UserGroupForm(instance=account.user)
|
|
|
|
account_form = AccountForm(instance=account)
|
|
|
|
cof_form = CofRestrictForm(instance=account.cofprofile)
|
2016-09-01 16:31:18 +02:00
|
|
|
pwd_form = AccountPwdForm()
|
2016-09-05 19:19:09 +02:00
|
|
|
if account.balance < 0 and not hasattr(account, 'negative'):
|
|
|
|
AccountNegative.objects.create(account=account, start=timezone.now())
|
|
|
|
account.refresh_from_db()
|
2016-08-22 20:07:01 +02:00
|
|
|
if hasattr(account, 'negative'):
|
|
|
|
negative_form = AccountNegativeForm(instance=account.negative)
|
|
|
|
else:
|
|
|
|
negative_form = None
|
2016-08-21 02:53:35 +02:00
|
|
|
else:
|
|
|
|
user_form = UserRestrictForm(instance=account.user)
|
2016-09-03 22:52:55 +02:00
|
|
|
account_form = AccountRestrictForm(instance=account)
|
2016-08-21 02:53:35 +02:00
|
|
|
cof_form = None
|
|
|
|
group_form = None
|
2016-08-22 20:07:01 +02:00
|
|
|
negative_form = None
|
2016-09-01 16:31:18 +02:00
|
|
|
pwd_form = None
|
2016-08-21 02:53:35 +02:00
|
|
|
|
2016-08-03 04:38:54 +02:00
|
|
|
if request.method == "POST":
|
|
|
|
# Update attempt
|
2016-08-21 02:53:35 +02:00
|
|
|
success = False
|
2016-09-05 01:24:38 +02:00
|
|
|
missing_perm = True
|
2016-08-03 04:38:54 +02:00
|
|
|
|
2016-08-21 02:53:35 +02:00
|
|
|
if request.user.has_perm('kfet.is_team'):
|
|
|
|
account_form = AccountForm(request.POST, instance=account)
|
|
|
|
cof_form = CofRestrictForm(request.POST, instance=account.cofprofile)
|
|
|
|
user_form = UserRestrictTeamForm(request.POST, instance=account.user)
|
|
|
|
group_form = UserGroupForm(request.POST, instance=account.user)
|
2016-09-01 16:31:18 +02:00
|
|
|
pwd_form = AccountPwdForm(request.POST)
|
2016-08-22 20:07:01 +02:00
|
|
|
if hasattr(account, 'negative'):
|
|
|
|
negative_form = AccountNegativeForm(request.POST, instance=account.negative)
|
2016-08-21 02:53:35 +02:00
|
|
|
|
|
|
|
if (request.user.has_perm('kfet.change_account')
|
|
|
|
and account_form.is_valid() and cof_form.is_valid()
|
|
|
|
and user_form.is_valid()):
|
2016-09-05 01:24:38 +02:00
|
|
|
missing_perm = False
|
2016-08-20 23:31:30 +02:00
|
|
|
data = {}
|
|
|
|
# Fill data for Account.save()
|
|
|
|
put_cleaned_data_in_dict(data, user_form)
|
|
|
|
put_cleaned_data_in_dict(data, cof_form)
|
|
|
|
|
|
|
|
# Updating
|
|
|
|
account_form.save(data = data)
|
2016-08-21 02:53:35 +02:00
|
|
|
|
2016-09-01 16:31:18 +02:00
|
|
|
# Checking perm to update password
|
|
|
|
if (request.user.has_perm('kfet.change_account_password')
|
|
|
|
and pwd_form.is_valid()):
|
|
|
|
pwd = pwd_form.cleaned_data['pwd1']
|
2016-09-06 15:30:51 +02:00
|
|
|
pwd_sha256 = hashlib.sha256(pwd.encode('utf-8')).hexdigest()
|
2016-09-01 16:31:18 +02:00
|
|
|
Account.objects.filter(pk=account.pk).update(
|
2016-09-03 02:54:02 +02:00
|
|
|
password = pwd_sha256)
|
2016-09-01 16:31:18 +02:00
|
|
|
messages.success(request, 'Mot de passe mis à jour')
|
|
|
|
|
2016-08-21 02:53:35 +02:00
|
|
|
# Checking perm to manage perms
|
|
|
|
if (request.user.has_perm('kfet.manage_perms')
|
|
|
|
and group_form.is_valid()):
|
|
|
|
group_form.save()
|
2016-08-22 20:07:01 +02:00
|
|
|
|
|
|
|
# Checking perm to manage negative
|
|
|
|
if hasattr(account, 'negative'):
|
|
|
|
balance_offset_old = 0
|
|
|
|
if account.negative.balance_offset:
|
|
|
|
balance_offset_old = account.negative.balance_offset
|
|
|
|
if (hasattr(account, 'negative')
|
|
|
|
and request.user.has_perm('kfet.change_accountnegative')
|
|
|
|
and negative_form.is_valid()):
|
|
|
|
balance_offset_new = negative_form.cleaned_data['balance_offset']
|
|
|
|
if not balance_offset_new:
|
|
|
|
balance_offset_new = 0
|
2016-09-05 19:19:09 +02:00
|
|
|
balance_offset_diff = balance_offset_new - balance_offset_old
|
2016-08-22 20:07:01 +02:00
|
|
|
Account.objects.filter(pk=account.pk).update(
|
|
|
|
balance = F('balance') + balance_offset_diff)
|
|
|
|
negative_form.save()
|
|
|
|
if not balance_offset_new and Account.objects.get(pk=account.pk).balance >= 0:
|
|
|
|
AccountNegative.objects.get(account=account).delete()
|
2016-08-21 02:53:35 +02:00
|
|
|
|
|
|
|
success = True
|
|
|
|
messages.success(request,
|
|
|
|
'Informations du compte %s mises à jour' % account.trigramme)
|
|
|
|
|
|
|
|
if request.user == account.user:
|
|
|
|
missing_perm = False
|
2016-09-05 19:19:09 +02:00
|
|
|
account.refresh_from_db()
|
2016-08-21 02:53:35 +02:00
|
|
|
user_form = UserRestrictForm(request.POST, instance=account.user)
|
2016-09-05 19:19:09 +02:00
|
|
|
account_form = AccountRestrictForm(request.POST, instance=account)
|
2016-08-21 02:53:35 +02:00
|
|
|
|
2016-09-03 22:52:55 +02:00
|
|
|
if user_form.is_valid() and account_form.is_valid():
|
2016-08-21 02:53:35 +02:00
|
|
|
user_form.save()
|
2016-09-03 22:52:55 +02:00
|
|
|
account_form.save()
|
2016-08-21 02:53:35 +02:00
|
|
|
success = True
|
|
|
|
messages.success(request, 'Vos informations ont été mises à jour')
|
|
|
|
|
|
|
|
if missing_perm:
|
2016-09-03 19:41:44 +02:00
|
|
|
messages.error(request, 'Permission refusée')
|
2016-08-21 02:53:35 +02:00
|
|
|
if success:
|
|
|
|
return redirect('kfet.account.read', account.trigramme)
|
2016-08-03 04:38:54 +02:00
|
|
|
else:
|
2016-09-03 19:41:44 +02:00
|
|
|
messages.error(request, 'Informations non mises à jour. Corrigez les erreurs')
|
2016-08-03 04:38:54 +02:00
|
|
|
|
|
|
|
return render(request, "kfet/account_update.html", {
|
2016-08-20 23:31:30 +02:00
|
|
|
'account' : account,
|
|
|
|
'account_form' : account_form,
|
|
|
|
'cof_form' : cof_form,
|
|
|
|
'user_form' : user_form,
|
2016-08-21 02:53:35 +02:00
|
|
|
'group_form' : group_form,
|
2016-08-22 20:07:01 +02:00
|
|
|
'negative_form': negative_form,
|
2016-09-01 16:31:18 +02:00
|
|
|
'pwd_form' : pwd_form,
|
2016-08-20 23:31:30 +02:00
|
|
|
})
|
2016-08-04 05:21:04 +02:00
|
|
|
|
2016-08-21 02:53:35 +02:00
|
|
|
@permission_required('kfet.manage_perms')
|
|
|
|
def account_group(request):
|
|
|
|
groups = (Group.objects
|
|
|
|
.filter(name__icontains='K-Fêt')
|
|
|
|
.prefetch_related('permissions', 'user_set__profile__account_kfet')
|
|
|
|
)
|
|
|
|
return render(request, 'kfet/account_group.html', { 'groups': groups })
|
|
|
|
|
2016-08-21 05:51:55 +02:00
|
|
|
class AccountGroupCreate(SuccessMessageMixin, CreateView):
|
|
|
|
model = Group
|
|
|
|
template_name = 'kfet/account_group_form.html'
|
|
|
|
form_class = GroupForm
|
|
|
|
success_message = 'Nouveau groupe : %(name)s'
|
|
|
|
success_url = reverse_lazy('kfet.account.group')
|
|
|
|
|
|
|
|
class AccountGroupUpdate(UpdateView):
|
|
|
|
queryset = Group.objects.filter(name__icontains='K-Fêt')
|
|
|
|
template_name = 'kfet/account_group_form.html'
|
|
|
|
form_class = GroupForm
|
|
|
|
success_message = 'Groupe modifié : %(name)s'
|
|
|
|
success_url = reverse_lazy('kfet.account.group')
|
|
|
|
|
2016-08-23 20:31:31 +02:00
|
|
|
class AccountNegativeList(ListView):
|
|
|
|
queryset = (AccountNegative.objects
|
2016-12-01 04:44:41 +01:00
|
|
|
.select_related('account', 'account__cofprofile__user')
|
|
|
|
.exclude(account__trigramme='#13'))
|
2016-08-23 20:31:31 +02:00
|
|
|
template_name = 'kfet/account_negative.html'
|
|
|
|
context_object_name = 'negatives'
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(AccountNegativeList, self).get_context_data(**kwargs)
|
|
|
|
context['settings'] = {
|
|
|
|
'overdraft_amount': Settings.OVERDRAFT_AMOUNT(),
|
|
|
|
'overdraft_duration': Settings.OVERDRAFT_DURATION(),
|
|
|
|
}
|
|
|
|
negs_sum = (AccountNegative.objects
|
2016-12-01 04:44:41 +01:00
|
|
|
.exclude(account__trigramme='#13')
|
2016-08-23 20:31:31 +02:00
|
|
|
.aggregate(
|
|
|
|
bal = Coalesce(Sum('account__balance'),0),
|
|
|
|
offset = Coalesce(Sum('balance_offset'),0),
|
|
|
|
)
|
|
|
|
)
|
2016-12-01 04:39:16 +01:00
|
|
|
context['negatives_sum'] = negs_sum['bal'] - negs_sum['offset']
|
2016-08-23 20:31:31 +02:00
|
|
|
return context
|
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
# -----
|
|
|
|
# Checkout views
|
|
|
|
# -----
|
|
|
|
|
|
|
|
# Checkout - General
|
|
|
|
|
|
|
|
class CheckoutList(ListView):
|
|
|
|
model = Checkout
|
|
|
|
template_name = 'kfet/checkout.html'
|
|
|
|
context_object_name = 'checkouts'
|
|
|
|
|
|
|
|
# Checkout - Create
|
|
|
|
|
|
|
|
class CheckoutCreate(SuccessMessageMixin, CreateView):
|
|
|
|
model = Checkout
|
|
|
|
template_name = 'kfet/checkout_create.html'
|
|
|
|
form_class = CheckoutForm
|
|
|
|
success_message = 'Nouvelle caisse : %(name)s'
|
|
|
|
|
|
|
|
# Surcharge de la validation
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
2016-08-15 01:48:22 +02:00
|
|
|
if not self.request.user.has_perm('kfet.add_checkout'):
|
2016-08-22 02:52:59 +02:00
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
2016-08-30 17:24:11 +02:00
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
# Creating
|
|
|
|
form.instance.created_by = self.request.user.profile.account_kfet
|
2016-08-30 17:24:11 +02:00
|
|
|
checkout = form.save()
|
|
|
|
|
|
|
|
# Création d'un relevé avec balance initiale
|
|
|
|
CheckoutStatement.objects.create(
|
|
|
|
checkout = checkout,
|
|
|
|
by = self.request.user.profile.account_kfet,
|
|
|
|
balance_old = checkout.balance,
|
|
|
|
balance_new = checkout.balance,
|
|
|
|
amount_taken = 0)
|
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
return super(CheckoutCreate, self).form_valid(form)
|
|
|
|
|
|
|
|
# Checkout - Read
|
|
|
|
|
|
|
|
class CheckoutRead(DetailView):
|
2016-08-04 08:23:34 +02:00
|
|
|
model = Checkout
|
2016-08-04 05:21:04 +02:00
|
|
|
template_name = 'kfet/checkout_read.html'
|
|
|
|
context_object_name = 'checkout'
|
|
|
|
|
2016-08-23 03:00:09 +02:00
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(CheckoutRead, self).get_context_data(**kwargs)
|
|
|
|
context['statements'] = context['checkout'].statements.order_by('-at')
|
|
|
|
return context
|
|
|
|
|
2016-08-04 05:21:04 +02:00
|
|
|
# Checkout - Update
|
|
|
|
|
|
|
|
class CheckoutUpdate(SuccessMessageMixin, UpdateView):
|
|
|
|
model = Checkout
|
|
|
|
template_name = 'kfet/checkout_update.html'
|
|
|
|
form_class = CheckoutRestrictForm
|
|
|
|
success_message = 'Informations mises à jour pour la caisse : %(name)s'
|
|
|
|
|
|
|
|
# Surcharge de la validation
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
2016-08-15 01:48:22 +02:00
|
|
|
if not self.request.user.has_perm('kfet.change_checkout'):
|
2016-08-22 02:52:59 +02:00
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
2016-08-04 05:21:04 +02:00
|
|
|
# Updating
|
|
|
|
return super(CheckoutUpdate, self).form_valid(form)
|
2016-08-04 08:23:34 +02:00
|
|
|
|
2016-08-11 15:14:23 +02:00
|
|
|
# -----
|
|
|
|
# Checkout Statement views
|
|
|
|
# -----
|
|
|
|
|
|
|
|
# Checkout Statement - General
|
|
|
|
|
|
|
|
class CheckoutStatementList(ListView):
|
|
|
|
model = CheckoutStatement
|
|
|
|
queryset = CheckoutStatement.objects.order_by('-at')
|
|
|
|
template_name = 'kfet/checkoutstatement.html'
|
|
|
|
context_object_name= 'checkoutstatements'
|
|
|
|
|
|
|
|
# Checkout Statement - Create
|
|
|
|
|
2016-08-23 00:15:17 +02:00
|
|
|
def getAmountTaken(data):
|
|
|
|
return Decimal(data.taken_001 * 0.01 + data.taken_002 * 0.02
|
|
|
|
+ data.taken_005 * 0.05 + data.taken_01 * 0.1
|
|
|
|
+ data.taken_02 * 0.2 + data.taken_05 * 0.5
|
|
|
|
+ data.taken_1 * 1 + data.taken_2 * 2
|
|
|
|
+ data.taken_5 * 5 + data.taken_10 * 10
|
|
|
|
+ data.taken_20 * 20 + data.taken_50 * 50
|
|
|
|
+ data.taken_100 * 100 + data.taken_200 * 200
|
2016-08-23 02:45:49 +02:00
|
|
|
+ data.taken_500 * 500 + float(data.taken_cheque))
|
2016-08-23 00:15:17 +02:00
|
|
|
|
|
|
|
def getAmountBalance(data):
|
|
|
|
return Decimal(data['balance_001'] * 0.01 + data['balance_002'] * 0.02
|
|
|
|
+ data['balance_005'] * 0.05 + data['balance_01'] * 0.1
|
|
|
|
+ data['balance_02'] * 0.2 + data['balance_05'] * 0.5
|
|
|
|
+ data['balance_1'] * 1 + data['balance_2'] * 2
|
|
|
|
+ data['balance_5'] * 5 + data['balance_10'] * 10
|
|
|
|
+ data['balance_20'] * 20 + data['balance_50'] * 50
|
|
|
|
+ data['balance_100'] * 100 + data['balance_200'] * 200
|
|
|
|
+ data['balance_500'] * 500)
|
|
|
|
|
2016-08-11 15:14:23 +02:00
|
|
|
class CheckoutStatementCreate(SuccessMessageMixin, CreateView):
|
|
|
|
model = CheckoutStatement
|
|
|
|
template_name = 'kfet/checkoutstatement_create.html'
|
2016-08-23 00:15:17 +02:00
|
|
|
form_class = CheckoutStatementCreateForm
|
2016-08-11 15:14:23 +02:00
|
|
|
success_message = 'Nouveau relevé : %(checkout)s - %(at)s'
|
|
|
|
|
|
|
|
def get_success_url(self):
|
|
|
|
return reverse_lazy('kfet.checkout.read', kwargs={'pk':self.kwargs['pk_checkout']})
|
|
|
|
|
|
|
|
def get_success_message(self, cleaned_data):
|
|
|
|
return self.success_message % dict(
|
|
|
|
cleaned_data,
|
|
|
|
checkout = self.object.checkout.name,
|
|
|
|
at = self.object.at)
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(CheckoutStatementCreate, self).get_context_data(**kwargs)
|
|
|
|
checkout = Checkout.objects.get(pk=self.kwargs['pk_checkout'])
|
|
|
|
context['checkout'] = checkout
|
|
|
|
return context
|
|
|
|
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
|
|
|
if not self.request.user.has_perm('kfet.add_checkoutstatement'):
|
2016-08-22 01:57:28 +02:00
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
2016-08-11 15:14:23 +02:00
|
|
|
# Creating
|
2016-08-23 00:15:17 +02:00
|
|
|
form.instance.amount_taken = getAmountTaken(form.instance)
|
2016-08-23 02:45:49 +02:00
|
|
|
if not form.instance.not_count:
|
|
|
|
form.instance.balance_new = getAmountBalance(form.cleaned_data)
|
2016-08-11 15:14:23 +02:00
|
|
|
form.instance.checkout_id = self.kwargs['pk_checkout']
|
|
|
|
form.instance.by = self.request.user.profile.account_kfet
|
|
|
|
return super(CheckoutStatementCreate, self).form_valid(form)
|
|
|
|
|
2016-08-23 00:15:17 +02:00
|
|
|
class CheckoutStatementUpdate(SuccessMessageMixin, UpdateView):
|
|
|
|
model = CheckoutStatement
|
|
|
|
template_name = 'kfet/checkoutstatement_update.html'
|
|
|
|
form_class = CheckoutStatementUpdateForm
|
|
|
|
success_message = 'Relevé modifié'
|
|
|
|
|
|
|
|
def get_success_url(self):
|
|
|
|
return reverse_lazy('kfet.checkout.read', kwargs={'pk':self.kwargs['pk_checkout']})
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(CheckoutStatementUpdate, self).get_context_data(**kwargs)
|
|
|
|
checkout = Checkout.objects.get(pk=self.kwargs['pk_checkout'])
|
|
|
|
context['checkout'] = checkout
|
|
|
|
return context
|
|
|
|
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
|
|
|
if not self.request.user.has_perm('kfet.change_checkoutstatement'):
|
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
|
|
|
# Updating
|
|
|
|
form.instance.amount_taken = getAmountTaken(form.instance)
|
|
|
|
return super(CheckoutStatementUpdate, self).form_valid(form)
|
|
|
|
|
2016-08-04 08:23:34 +02:00
|
|
|
# -----
|
|
|
|
# Article views
|
|
|
|
# -----
|
|
|
|
|
|
|
|
# Article - General
|
|
|
|
|
|
|
|
class ArticleList(ListView):
|
2016-08-30 18:16:57 +02:00
|
|
|
queryset = (Article.objects
|
|
|
|
.select_related('category')
|
|
|
|
.prefetch_related(Prefetch('inventories',
|
|
|
|
queryset = Inventory.objects.order_by('-at'),
|
|
|
|
to_attr = 'inventory'))
|
|
|
|
.order_by('category', '-is_sold', 'name'))
|
2016-08-04 08:23:34 +02:00
|
|
|
template_name = 'kfet/article.html'
|
|
|
|
context_object_name = 'articles'
|
|
|
|
|
|
|
|
# Article - Create
|
|
|
|
|
|
|
|
class ArticleCreate(SuccessMessageMixin, CreateView):
|
|
|
|
model = Article
|
|
|
|
template_name = 'kfet/article_create.html'
|
|
|
|
form_class = ArticleForm
|
|
|
|
success_message = 'Nouvel item : %(category)s - %(name)s'
|
|
|
|
|
|
|
|
# Surcharge de la validation
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
2016-08-21 18:10:35 +02:00
|
|
|
if not self.request.user.has_perm('kfet.add_article'):
|
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
|
|
|
|
2016-08-27 00:14:49 +02:00
|
|
|
# Save ici pour save le manytomany suppliers
|
2016-08-26 23:44:57 +02:00
|
|
|
article = form.save()
|
2016-08-27 00:14:49 +02:00
|
|
|
# Save des suppliers déjà existant
|
2016-08-26 23:44:57 +02:00
|
|
|
for supplier in form.cleaned_data['suppliers']:
|
|
|
|
SupplierArticle.objects.create(
|
|
|
|
article = article, supplier = supplier)
|
|
|
|
|
2016-08-27 00:14:49 +02:00
|
|
|
# Nouveau supplier
|
2016-08-26 23:44:57 +02:00
|
|
|
supplier_new = form.cleaned_data['supplier_new'].strip()
|
|
|
|
if supplier_new:
|
|
|
|
supplier, created = Supplier.objects.get_or_create(
|
|
|
|
name=supplier_new)
|
|
|
|
if created:
|
|
|
|
SupplierArticle.objects.create(
|
|
|
|
article = article, supplier = supplier)
|
|
|
|
|
2016-08-30 17:16:00 +02:00
|
|
|
# Inventaire avec stock initial
|
|
|
|
inventory = Inventory()
|
|
|
|
inventory.by = self.request.user.profile.account_kfet
|
|
|
|
inventory.save()
|
|
|
|
InventoryArticle.objects.create(
|
|
|
|
inventory = inventory,
|
|
|
|
article = article,
|
|
|
|
stock_old = article.stock,
|
|
|
|
stock_new = article.stock,
|
|
|
|
)
|
|
|
|
|
2016-08-04 08:23:34 +02:00
|
|
|
# Creating
|
|
|
|
return super(ArticleCreate, self).form_valid(form)
|
|
|
|
|
|
|
|
# Article - Read
|
|
|
|
|
|
|
|
class ArticleRead(DetailView):
|
|
|
|
model = Article
|
|
|
|
template_name = 'kfet/article_read.html'
|
|
|
|
context_object_name = 'article'
|
|
|
|
|
2016-08-30 18:56:42 +02:00
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(ArticleRead, self).get_context_data(**kwargs)
|
|
|
|
inventoryarts = (InventoryArticle.objects
|
|
|
|
.filter(article = self.object)
|
|
|
|
.select_related('inventory')
|
|
|
|
.order_by('-inventory__at'))
|
|
|
|
context['inventoryarts'] = inventoryarts
|
|
|
|
supplierarts = (SupplierArticle.objects
|
|
|
|
.filter(article = self.object)
|
|
|
|
.select_related('supplier')
|
|
|
|
.order_by('-at'))
|
|
|
|
context['supplierarts'] = supplierarts
|
|
|
|
return context
|
|
|
|
|
2016-08-04 08:23:34 +02:00
|
|
|
# Article - Update
|
|
|
|
|
2016-08-22 03:57:13 +02:00
|
|
|
class ArticleUpdate(SuccessMessageMixin, UpdateView):
|
2016-08-04 08:23:34 +02:00
|
|
|
model = Article
|
|
|
|
template_name = 'kfet/article_update.html'
|
|
|
|
form_class = ArticleRestrictForm
|
|
|
|
success_message = "Informations mises à jour pour l'article : %(name)s"
|
|
|
|
|
|
|
|
# Surcharge de la validation
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
2016-08-21 18:10:35 +02:00
|
|
|
if not self.request.user.has_perm('kfet.change_article'):
|
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
2016-08-27 00:14:49 +02:00
|
|
|
|
|
|
|
# Save ici pour save le manytomany suppliers
|
|
|
|
article = form.save()
|
|
|
|
# Save des suppliers déjà existant
|
|
|
|
for supplier in form.cleaned_data['suppliers']:
|
|
|
|
if supplier not in article.suppliers.all():
|
|
|
|
SupplierArticle.objects.create(
|
|
|
|
article = article, supplier = supplier)
|
|
|
|
|
|
|
|
# On vire les suppliers désélectionnés
|
|
|
|
for supplier in article.suppliers.all():
|
|
|
|
if supplier not in form.cleaned_data['suppliers']:
|
|
|
|
SupplierArticle.objects.filter(
|
|
|
|
article = article, supplier = supplier).delete()
|
|
|
|
|
|
|
|
# Nouveau supplier
|
|
|
|
supplier_new = form.cleaned_data['supplier_new'].strip()
|
|
|
|
if supplier_new:
|
|
|
|
supplier, created = Supplier.objects.get_or_create(
|
|
|
|
name=supplier_new)
|
|
|
|
if created:
|
|
|
|
SupplierArticle.objects.create(
|
|
|
|
article = article, supplier = supplier)
|
|
|
|
|
2016-08-04 08:23:34 +02:00
|
|
|
# Updating
|
|
|
|
return super(ArticleUpdate, self).form_valid(form)
|
2016-08-06 22:19:52 +02:00
|
|
|
|
|
|
|
# -----
|
|
|
|
# K-Psul
|
|
|
|
# -----
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-06 22:19:52 +02:00
|
|
|
def kpsul(request):
|
|
|
|
data = {}
|
|
|
|
data['operationgroup_form'] = KPsulOperationGroupForm()
|
|
|
|
data['trigramme_form'] = KPsulAccountForm()
|
2016-09-05 20:07:08 +02:00
|
|
|
initial = {}
|
|
|
|
try:
|
|
|
|
checkout = Checkout.objects.filter(
|
|
|
|
is_protected=False, valid_from__lte=timezone.now(),
|
|
|
|
valid_to__gte=timezone.now()).get()
|
|
|
|
initial['checkout'] = checkout
|
2016-09-12 23:24:18 +02:00
|
|
|
except (Checkout.DoesNotExist, Checkout.MultipleObjectsReturned):
|
2016-09-05 20:07:08 +02:00
|
|
|
pass
|
|
|
|
data['checkout_form'] = KPsulCheckoutForm(initial=initial)
|
2016-08-06 23:44:58 +02:00
|
|
|
operation_formset = KPsulOperationFormSet(queryset=Operation.objects.none())
|
2016-08-06 22:19:52 +02:00
|
|
|
data['operation_formset'] = operation_formset
|
|
|
|
return render(request, 'kfet/kpsul.html', data)
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-22 16:08:21 +02:00
|
|
|
def kpsul_get_settings(request):
|
|
|
|
addcost_for = Settings.ADDCOST_FOR()
|
|
|
|
data = {
|
|
|
|
'subvention_cof': Settings.SUBVENTION_COF(),
|
|
|
|
'addcost_for' : addcost_for and addcost_for.trigramme or '',
|
|
|
|
'addcost_amount': Settings.ADDCOST_AMOUNT(),
|
|
|
|
}
|
|
|
|
return JsonResponse(data)
|
|
|
|
|
2016-08-06 22:19:52 +02:00
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2017-02-23 22:07:38 +01:00
|
|
|
def kpsul_checkout_data(request, pk):
|
|
|
|
checkout = get_object_or_404(Checkout, pk=pk)
|
|
|
|
data = model_to_dict(
|
|
|
|
checkout,
|
|
|
|
fields=['id', 'name', 'balance', 'valid_from', 'valid_to']
|
|
|
|
)
|
|
|
|
|
|
|
|
if request.GET.get('last_statement'):
|
|
|
|
last_statement = checkout.statements.latest('at')
|
|
|
|
last_statement_data = model_to_dict(
|
|
|
|
last_statement,
|
|
|
|
fields=['id', 'at', 'balance_new', 'balance_old', 'by']
|
|
|
|
)
|
|
|
|
# ``at`` is not editable, so skipped by ``model_to_dict``
|
|
|
|
last_statement_data['at'] = last_statement.at
|
|
|
|
data['laststatement'] = last_statement_data
|
|
|
|
|
2016-08-06 22:19:52 +02:00
|
|
|
return JsonResponse(data)
|
|
|
|
|
2017-02-23 22:07:38 +01:00
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-22 05:41:31 +02:00
|
|
|
def kpsul_update_addcost(request):
|
|
|
|
addcost_form = AddcostForm(request.POST)
|
|
|
|
|
|
|
|
if not addcost_form.is_valid():
|
2016-08-22 16:29:12 +02:00
|
|
|
data = { 'errors': { 'addcost': list(addcost_form.errors) } }
|
|
|
|
return JsonResponse(data, status=400)
|
2016-08-22 05:41:31 +02:00
|
|
|
required_perms = ['kfet.manage_addcosts']
|
|
|
|
if not request.user.has_perms(required_perms):
|
|
|
|
data = {
|
|
|
|
'errors': {
|
|
|
|
'missing_perms': get_missing_perms(required_perms, request.user)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return JsonResponse(data, status=403)
|
|
|
|
|
|
|
|
trigramme = addcost_form.cleaned_data['trigramme']
|
|
|
|
account = trigramme and Account.objects.get(trigramme=trigramme) or None
|
|
|
|
Settings.objects.filter(name='ADDCOST_FOR').update(value_account=account)
|
|
|
|
Settings.objects.filter(name='ADDCOST_AMOUNT').update(value_decimal=addcost_form.cleaned_data['amount'])
|
|
|
|
cache.delete('ADDCOST_FOR')
|
|
|
|
cache.delete('ADDCOST_AMOUNT')
|
|
|
|
data = {
|
|
|
|
'addcost': {
|
|
|
|
'for': trigramme and account.trigramme or None,
|
|
|
|
'amount': addcost_form.cleaned_data['amount'],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
consumers.KPsul.group_send('kfet.kpsul', data)
|
|
|
|
return JsonResponse(data)
|
|
|
|
|
2016-08-09 11:02:26 +02:00
|
|
|
def get_missing_perms(required_perms, user):
|
|
|
|
missing_perms_codenames = [ (perm.split('.'))[1]
|
|
|
|
for perm in required_perms if not user.has_perm(perm)]
|
|
|
|
missing_perms = list(
|
|
|
|
Permission.objects
|
|
|
|
.filter(codename__in=missing_perms_codenames)
|
|
|
|
.values_list('name', flat=True))
|
|
|
|
return missing_perms
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-06 22:19:52 +02:00
|
|
|
def kpsul_perform_operations(request):
|
2016-08-07 17:02:01 +02:00
|
|
|
# Initializing response data
|
2016-08-14 19:59:36 +02:00
|
|
|
data = { 'operationgroup': 0, 'operations': [],
|
2016-08-11 06:13:31 +02:00
|
|
|
'warnings': {}, 'errors': {} }
|
2016-08-06 22:19:52 +02:00
|
|
|
|
2016-08-07 17:02:01 +02:00
|
|
|
# Checking operationgroup
|
|
|
|
operationgroup_form = KPsulOperationGroupForm(request.POST)
|
|
|
|
if not operationgroup_form.is_valid():
|
2016-08-11 06:13:31 +02:00
|
|
|
data['errors']['operation_group'] = list(operationgroup_form.errors)
|
2016-08-07 17:02:01 +02:00
|
|
|
|
|
|
|
# Checking operation_formset
|
|
|
|
operation_formset = KPsulOperationFormSet(request.POST)
|
|
|
|
if not operation_formset.is_valid():
|
2016-08-11 06:13:31 +02:00
|
|
|
data['errors']['operations'] = list(operation_formset.errors)
|
2016-08-07 17:02:01 +02:00
|
|
|
|
2016-08-07 23:41:46 +02:00
|
|
|
# Returning BAD REQUEST if errors
|
2016-08-11 06:13:31 +02:00
|
|
|
if data['errors']:
|
2016-08-06 22:19:52 +02:00
|
|
|
return JsonResponse(data, status=400)
|
|
|
|
|
2016-08-07 17:22:39 +02:00
|
|
|
# Pre-saving (no commit)
|
2016-08-07 17:02:01 +02:00
|
|
|
operationgroup = operationgroup_form.save(commit = False)
|
|
|
|
operations = operation_formset.save(commit = False)
|
|
|
|
|
2016-08-07 18:37:06 +02:00
|
|
|
# Retrieving COF grant
|
|
|
|
cof_grant = Settings.SUBVENTION_COF()
|
2016-08-08 02:50:04 +02:00
|
|
|
# Retrieving addcosts data
|
|
|
|
addcost_amount = Settings.ADDCOST_AMOUNT()
|
|
|
|
addcost_for = Settings.ADDCOST_FOR()
|
2016-08-07 18:37:06 +02:00
|
|
|
|
2016-08-08 02:50:04 +02:00
|
|
|
# Initializing vars
|
2016-08-11 06:13:31 +02:00
|
|
|
required_perms = set() # Required perms to perform all operations
|
2016-08-08 02:50:04 +02:00
|
|
|
cof_grant_divisor = 1 + cof_grant / 100
|
2016-08-11 06:13:31 +02:00
|
|
|
to_addcost_for_balance = 0 # For balance of addcost_for
|
|
|
|
to_checkout_balance = 0 # For balance of selected checkout
|
|
|
|
to_articles_stocks = defaultdict(lambda:0) # For stocks articles
|
2016-08-08 02:50:04 +02:00
|
|
|
is_addcost = (addcost_for and addcost_amount
|
|
|
|
and addcost_for != operationgroup.on_acc)
|
2016-08-31 01:36:58 +02:00
|
|
|
need_comment = operationgroup.on_acc.need_comment
|
2016-08-11 06:13:31 +02:00
|
|
|
|
|
|
|
# Filling data of each operations + operationgroup + calculating other stuffs
|
2016-08-06 22:19:52 +02:00
|
|
|
for operation in operations:
|
2016-08-07 17:22:39 +02:00
|
|
|
if operation.type == Operation.PURCHASE:
|
|
|
|
operation.amount = - operation.article.price * operation.article_nb
|
2016-08-08 02:50:04 +02:00
|
|
|
if is_addcost:
|
2016-08-11 06:13:31 +02:00
|
|
|
operation.addcost_for = addcost_for
|
2016-08-08 02:50:04 +02:00
|
|
|
operation.addcost_amount = addcost_amount * operation.article_nb
|
2016-08-14 19:59:36 +02:00
|
|
|
operation.amount -= operation.addcost_amount
|
2016-08-11 06:13:31 +02:00
|
|
|
to_addcost_for_balance += operation.addcost_amount
|
2016-08-08 12:46:43 +02:00
|
|
|
if operationgroup.on_acc.is_cash:
|
2016-08-31 01:36:58 +02:00
|
|
|
operation.is_checkout = True
|
2016-08-08 12:46:43 +02:00
|
|
|
to_checkout_balance += -operation.amount
|
2016-08-31 01:36:58 +02:00
|
|
|
else:
|
|
|
|
operation.is_checkout = False
|
2016-08-07 18:37:06 +02:00
|
|
|
if operationgroup.on_acc.is_cof:
|
2016-08-22 18:08:44 +02:00
|
|
|
if is_addcost:
|
|
|
|
operation.addcost_amount = operation.addcost_amount / cof_grant_divisor
|
2017-01-27 13:08:50 +01:00
|
|
|
operation.amount = operation.amount / cof_grant_divisor
|
2016-08-11 06:13:31 +02:00
|
|
|
to_articles_stocks[operation.article] -= operation.article_nb
|
2016-08-08 12:46:43 +02:00
|
|
|
else:
|
2016-08-11 06:13:31 +02:00
|
|
|
if operationgroup.on_acc.is_cash:
|
|
|
|
data['errors']['account'] = 'Charge et retrait impossible sur LIQ'
|
2016-08-08 12:46:43 +02:00
|
|
|
to_checkout_balance += operation.amount
|
2016-08-08 00:41:31 +02:00
|
|
|
operationgroup.amount += operation.amount
|
2016-08-07 23:41:46 +02:00
|
|
|
if operation.type == Operation.DEPOSIT:
|
2016-08-09 11:02:26 +02:00
|
|
|
required_perms.add('kfet.perform_deposit')
|
2016-08-31 01:36:58 +02:00
|
|
|
if (not operation.is_checkout
|
|
|
|
and operation.type in [Operation.DEPOSIT, Operation.WITHDRAW]):
|
|
|
|
required_perms.add('kfet.edit_balance_account')
|
|
|
|
need_comment = True
|
2016-08-22 18:08:44 +02:00
|
|
|
if operationgroup.on_acc.is_cof:
|
|
|
|
to_addcost_for_balance = to_addcost_for_balance / cof_grant_divisor
|
2016-08-07 23:41:46 +02:00
|
|
|
|
2016-08-11 06:13:31 +02:00
|
|
|
(perms, stop) = operationgroup.on_acc.perms_to_perform_operation(
|
|
|
|
amount = operationgroup.amount)
|
|
|
|
required_perms |= perms
|
|
|
|
|
2016-08-31 01:36:58 +02:00
|
|
|
if need_comment:
|
2016-08-23 15:43:16 +02:00
|
|
|
operationgroup.comment = operationgroup.comment.strip()
|
|
|
|
if not operationgroup.comment:
|
|
|
|
data['errors']['need_comment'] = True
|
|
|
|
return JsonResponse(data, status=400)
|
|
|
|
|
2016-08-11 06:13:31 +02:00
|
|
|
if stop or not request.user.has_perms(required_perms):
|
|
|
|
missing_perms = get_missing_perms(required_perms, request.user)
|
|
|
|
if missing_perms:
|
|
|
|
data['errors']['missing_perms'] = missing_perms
|
|
|
|
if stop:
|
2016-09-03 18:32:12 +02:00
|
|
|
data['errors']['negative'] = [operationgroup.on_acc.trigramme]
|
2016-08-11 06:13:31 +02:00
|
|
|
return JsonResponse(data, status=403)
|
|
|
|
|
|
|
|
# If 1 perm is required, filling who perform the operations
|
|
|
|
if required_perms:
|
|
|
|
operationgroup.valid_by = request.user.profile.account_kfet
|
|
|
|
# Filling cof status for statistics
|
|
|
|
operationgroup.is_cof = operationgroup.on_acc.is_cof
|
|
|
|
|
2016-08-08 03:32:48 +02:00
|
|
|
# Starting transaction to ensure data consistency
|
2016-08-11 06:13:31 +02:00
|
|
|
with transaction.atomic():
|
|
|
|
# If not cash account,
|
|
|
|
# saving account's balance and adding to Negative if not in
|
|
|
|
if not operationgroup.on_acc.is_cash:
|
|
|
|
Account.objects.filter(pk=operationgroup.on_acc.pk).update(
|
|
|
|
balance = F('balance') + operationgroup.amount)
|
|
|
|
operationgroup.on_acc.refresh_from_db()
|
|
|
|
if operationgroup.on_acc.balance < 0:
|
2016-08-20 01:20:06 +02:00
|
|
|
if hasattr(operationgroup.on_acc, 'negative'):
|
|
|
|
if not operationgroup.on_acc.negative.start:
|
|
|
|
operationgroup.on_acc.negative.start = timezone.now()
|
|
|
|
operationgroup.on_acc.negative.save()
|
|
|
|
else:
|
|
|
|
negative = AccountNegative(
|
|
|
|
account = operationgroup.on_acc, start = timezone.now())
|
|
|
|
negative.save()
|
2016-08-20 17:18:41 +02:00
|
|
|
elif (hasattr(operationgroup.on_acc, 'negative')
|
|
|
|
and not operationgroup.on_acc.negative.balance_offset):
|
|
|
|
operationgroup.on_acc.negative.delete()
|
2016-08-08 12:46:43 +02:00
|
|
|
|
2016-08-11 06:13:31 +02:00
|
|
|
# Updating checkout's balance
|
|
|
|
if to_checkout_balance:
|
|
|
|
Checkout.objects.filter(pk=operationgroup.checkout.pk).update(
|
|
|
|
balance = F('balance') + to_checkout_balance)
|
2016-08-08 07:44:05 +02:00
|
|
|
|
2016-08-11 06:13:31 +02:00
|
|
|
# Saving addcost_for with new balance if there is one
|
|
|
|
if is_addcost and to_addcost_for_balance:
|
|
|
|
Account.objects.filter(pk=addcost_for.pk).update(
|
|
|
|
balance = F('balance') + to_addcost_for_balance)
|
|
|
|
|
|
|
|
# Saving operation group
|
|
|
|
operationgroup.save()
|
|
|
|
data['operationgroup'] = operationgroup.pk
|
|
|
|
|
|
|
|
# Filling operationgroup id for each operations and saving
|
|
|
|
for operation in operations:
|
|
|
|
operation.group = operationgroup
|
|
|
|
operation.save()
|
|
|
|
data['operations'].append(operation.pk)
|
|
|
|
|
|
|
|
# Updating articles stock
|
|
|
|
for article in to_articles_stocks:
|
|
|
|
Article.objects.filter(pk=article.pk).update(
|
|
|
|
stock = F('stock') + to_articles_stocks[article])
|
2016-08-06 22:19:52 +02:00
|
|
|
|
2016-08-14 19:59:36 +02:00
|
|
|
# Websocket data
|
|
|
|
websocket_data = {}
|
|
|
|
websocket_data['opegroups'] = [{
|
|
|
|
'add': True,
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'opegroup',
|
2017-03-18 06:32:27 +01:00
|
|
|
'content': {
|
|
|
|
'id': operationgroup.pk,
|
|
|
|
'amount': operationgroup.amount,
|
|
|
|
'at': operationgroup.at,
|
|
|
|
'is_cof': operationgroup.is_cof,
|
|
|
|
'comment': operationgroup.comment,
|
|
|
|
'valid_by': (operationgroup.valid_by and
|
2017-03-19 04:29:54 +01:00
|
|
|
operationgroup.valid_by.trigramme or None),
|
2017-03-18 06:32:27 +01:00
|
|
|
'trigramme': operationgroup.on_acc.trigramme,
|
2017-03-19 04:29:54 +01:00
|
|
|
# Used to filter websocket updates
|
|
|
|
'account_id': operationgroup.on_acc.pk,
|
|
|
|
'checkout_id': operationgroup.checkout.pk,
|
2017-03-18 06:32:27 +01:00
|
|
|
},
|
|
|
|
'parent': {
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'day',
|
2017-03-18 06:32:27 +01:00
|
|
|
'content': {
|
|
|
|
'id': operationgroup.at.strftime('%Y%m%d'),
|
|
|
|
'date': operationgroup.at
|
|
|
|
},
|
|
|
|
'child_sort': 'opegroup',
|
|
|
|
},
|
|
|
|
'children': [],
|
2016-08-14 19:59:36 +02:00
|
|
|
}]
|
2017-03-18 06:32:27 +01:00
|
|
|
for ope in operations:
|
2016-08-14 19:59:36 +02:00
|
|
|
ope_data = {
|
2017-03-18 06:32:27 +01:00
|
|
|
'content': {
|
|
|
|
'id': ope.id,
|
|
|
|
'amount': ope.amount,
|
|
|
|
'canceled_at': ope.canceled_at,
|
|
|
|
'canceled_by':
|
|
|
|
ope.canceled_by and ope.canceled_by.trigramme or None,
|
|
|
|
'is_cof': operationgroup.is_cof,
|
|
|
|
'trigramme': (
|
|
|
|
operationgroup.on_acc and
|
|
|
|
operationgroup.on_acc.trigramme or None),
|
|
|
|
},
|
2016-08-14 19:59:36 +02:00
|
|
|
}
|
2017-03-18 06:32:27 +01:00
|
|
|
|
|
|
|
if ope.type == Operation.PURCHASE:
|
2017-03-20 04:36:42 +01:00
|
|
|
ope_data['modelname'] = 'purchase'
|
2017-03-18 06:32:27 +01:00
|
|
|
ope_data['content'].update({
|
|
|
|
'article_name': ope.article.name,
|
|
|
|
'article_nb': ope.article_nb,
|
|
|
|
'addcost_amount': ope.addcost_amount,
|
|
|
|
'addcost_for':
|
|
|
|
ope.addcost_for and ope.addcost_for.trigramme or None,
|
|
|
|
})
|
|
|
|
else:
|
2017-03-20 04:36:42 +01:00
|
|
|
ope_data['modelname'] = 'specialope'
|
2017-03-18 06:32:27 +01:00
|
|
|
ope_data['content'].update({
|
|
|
|
'type': ope.type,
|
|
|
|
'is_checkout': ope.is_checkout,
|
|
|
|
})
|
|
|
|
websocket_data['opegroups'][0]['children'].append(ope_data)
|
2016-08-14 23:37:05 +02:00
|
|
|
# Need refresh from db cause we used update on queryset
|
2016-08-14 19:59:36 +02:00
|
|
|
operationgroup.checkout.refresh_from_db()
|
|
|
|
websocket_data['checkouts'] = [{
|
|
|
|
'id': operationgroup.checkout.pk,
|
|
|
|
'balance': operationgroup.checkout.balance,
|
|
|
|
}]
|
2016-08-14 23:37:05 +02:00
|
|
|
websocket_data['articles'] = []
|
|
|
|
# Need refresh from db cause we used update on querysets
|
|
|
|
articles_pk = [ article.pk for article in to_articles_stocks]
|
|
|
|
articles = Article.objects.values('id', 'stock').filter(pk__in=articles_pk)
|
|
|
|
for article in articles:
|
|
|
|
websocket_data['articles'].append({
|
|
|
|
'id': article['id'],
|
|
|
|
'stock': article['stock']
|
|
|
|
})
|
2016-08-14 19:59:36 +02:00
|
|
|
consumers.KPsul.group_send('kfet.kpsul', websocket_data)
|
2016-08-06 22:19:52 +02:00
|
|
|
return JsonResponse(data)
|
2016-08-09 11:02:26 +02:00
|
|
|
|
2017-02-05 06:42:02 +01:00
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-09 11:02:26 +02:00
|
|
|
def kpsul_cancel_operations(request):
|
|
|
|
# Pour la réponse
|
2016-12-11 19:22:55 +01:00
|
|
|
data = {'canceled': {}, 'warnings': {}, 'errors': {}}
|
2016-08-09 11:02:26 +02:00
|
|
|
|
|
|
|
# Checking if BAD REQUEST (opes_pk not int or not existing)
|
|
|
|
try:
|
|
|
|
# Set pour virer les doublons
|
2017-03-25 03:57:27 +01:00
|
|
|
opes_post = set(map(lambda s: int(s),
|
|
|
|
request.POST.getlist('opes[]', [])))
|
|
|
|
transfers_post = set(map(lambda s: int(s),
|
|
|
|
request.POST.getlist('transfers[]', [])))
|
2016-08-09 11:02:26 +02:00
|
|
|
except ValueError:
|
|
|
|
return JsonResponse(data, status=400)
|
2016-12-11 19:22:55 +01:00
|
|
|
|
2016-08-09 11:06:42 +02:00
|
|
|
opes_all = (
|
|
|
|
Operation.objects
|
|
|
|
.select_related('group', 'group__on_acc', 'group__on_acc__negative')
|
|
|
|
.filter(pk__in=opes_post))
|
2017-02-05 06:42:02 +01:00
|
|
|
opes_pk = [ope.pk for ope in opes_all]
|
|
|
|
opes_notexisting = [ope for ope in opes_post if ope not in opes_pk]
|
2016-12-11 19:22:55 +01:00
|
|
|
|
|
|
|
transfers_all = (
|
|
|
|
Transfer.objects
|
|
|
|
.select_related('group', 'from_acc', 'from_acc__negative',
|
|
|
|
'to_acc', 'to_acc__negative')
|
|
|
|
.filter(pk__in=transfers_post))
|
|
|
|
transfers_pk = [transfer.pk for transfer in transfers_all]
|
|
|
|
transfers_notexisting = [transfer for transfer in transfers_post
|
2017-02-05 06:42:02 +01:00
|
|
|
if transfer not in transfers_pk]
|
2016-12-11 19:22:55 +01:00
|
|
|
|
|
|
|
if transfers_notexisting or opes_notexisting:
|
|
|
|
if transfers_notexisting:
|
|
|
|
data['errors']['transfers_notexisting'] = transfers_notexisting
|
|
|
|
if opes_notexisting:
|
|
|
|
data['errors']['opes_notexisting'] = opes_notexisting
|
2016-08-09 11:02:26 +02:00
|
|
|
return JsonResponse(data, status=400)
|
|
|
|
|
2016-12-11 19:22:55 +01:00
|
|
|
already_canceled = {} # Opération/Transfert déjà annulé
|
|
|
|
opes = [] # Pas déjà annulée
|
|
|
|
transfers = []
|
2016-08-09 11:02:26 +02:00
|
|
|
required_perms = set()
|
2017-02-05 06:42:02 +01:00
|
|
|
stop_all = False
|
2016-08-09 11:02:26 +02:00
|
|
|
cancel_duration = Settings.CANCEL_DURATION()
|
2017-02-05 06:42:02 +01:00
|
|
|
# Modifs à faire sur les balances des comptes
|
|
|
|
to_accounts_balances = defaultdict(lambda: 0)
|
|
|
|
# ------ sur les montants des groupes d'opé
|
|
|
|
to_groups_amounts = defaultdict(lambda: 0)
|
|
|
|
# ------ sur les balances de caisses
|
|
|
|
to_checkouts_balances = defaultdict(lambda: 0)
|
|
|
|
# ------ sur les stocks d'articles
|
|
|
|
to_articles_stocks = defaultdict(lambda: 0)
|
2016-08-09 11:02:26 +02:00
|
|
|
for ope in opes_all:
|
|
|
|
if ope.canceled_at:
|
|
|
|
# Opération déjà annulée, va pour un warning en Response
|
2016-12-11 19:22:55 +01:00
|
|
|
already_canceled['opes'].append(ope.pk)
|
2016-08-09 11:02:26 +02:00
|
|
|
else:
|
|
|
|
opes.append(ope.pk)
|
|
|
|
# Si opé il y a plus de CANCEL_DURATION, permission requise
|
|
|
|
if ope.group.at + cancel_duration < timezone.now():
|
|
|
|
required_perms.add('kfet.cancel_old_operations')
|
|
|
|
|
|
|
|
# Calcul de toutes modifs à faire en cas de validation
|
|
|
|
|
|
|
|
# Pour les balances de comptes
|
|
|
|
if not ope.group.on_acc.is_cash:
|
|
|
|
to_accounts_balances[ope.group.on_acc] -= ope.amount
|
|
|
|
if ope.addcost_for and ope.addcost_amount:
|
|
|
|
to_accounts_balances[ope.addcost_for] -= ope.addcost_amount
|
|
|
|
# Pour les groupes d'opés
|
|
|
|
to_groups_amounts[ope.group] -= ope.amount
|
2016-08-23 03:27:02 +02:00
|
|
|
|
2016-08-09 11:02:26 +02:00
|
|
|
# Pour les balances de caisses
|
2016-08-23 03:27:02 +02:00
|
|
|
# Les balances de caisses dont il y a eu un relevé depuis la date
|
|
|
|
# de la commande ne doivent pas être modifiées
|
2016-08-27 21:43:19 +02:00
|
|
|
# TODO : Prendre en compte le dernier relevé où la caisse a été
|
|
|
|
# comptée et donc modifier les balance_old (et amount_error)
|
|
|
|
# des relevés suivants.
|
|
|
|
# Note : Dans le cas où un CheckoutStatement est mis à jour
|
|
|
|
# par `.save()`, amount_error est recalculé automatiquement,
|
|
|
|
# ce qui n'est pas le cas en faisant un update sur queryset
|
2016-08-23 03:27:02 +02:00
|
|
|
# TODO ? : Maj les balance_old de relevés pour modifier l'erreur
|
2017-02-05 06:42:02 +01:00
|
|
|
last_statement = \
|
|
|
|
(CheckoutStatement.objects
|
|
|
|
.filter(checkout=ope.group.checkout)
|
|
|
|
.order_by('at')
|
|
|
|
.last())
|
2016-08-23 03:27:02 +02:00
|
|
|
if not last_statement or last_statement.at < ope.group.at:
|
|
|
|
if ope.type == Operation.PURCHASE:
|
|
|
|
if ope.group.on_acc.is_cash:
|
2016-12-11 19:22:55 +01:00
|
|
|
to_checkouts_balances[ope.group.checkout] -= -ope.amount
|
2016-08-23 03:27:02 +02:00
|
|
|
else:
|
|
|
|
to_checkouts_balances[ope.group.checkout] -= ope.amount
|
|
|
|
|
2016-08-09 11:02:26 +02:00
|
|
|
# Pour les stocks d'articles
|
2016-08-27 21:43:19 +02:00
|
|
|
# Les stocks d'articles dont il y a eu un inventaire depuis la date
|
|
|
|
# de la commande ne doivent pas être modifiés
|
|
|
|
# TODO : Prendre en compte le dernier inventaire où le stock a bien
|
|
|
|
# été compté (pas dans le cas d'une livraison).
|
|
|
|
# Note : si InventoryArticle est maj par .save(), stock_error
|
|
|
|
# est recalculé automatiquement
|
2016-08-09 11:02:26 +02:00
|
|
|
if ope.article and ope.article_nb:
|
2016-09-03 13:50:40 +02:00
|
|
|
last_stock = (InventoryArticle.objects
|
2016-12-11 19:22:55 +01:00
|
|
|
.select_related('inventory')
|
|
|
|
.filter(article=ope.article)
|
|
|
|
.order_by('inventory__at')
|
|
|
|
.last())
|
2016-08-27 21:43:19 +02:00
|
|
|
if not last_stock or last_stock.inventory.at < ope.group.at:
|
|
|
|
to_articles_stocks[ope.article] += ope.article_nb
|
2016-08-09 11:02:26 +02:00
|
|
|
|
2016-12-11 19:22:55 +01:00
|
|
|
for transfer in transfers_all:
|
|
|
|
if transfer.canceled_at:
|
|
|
|
# Transfert déjà annulé, va pour un warning en Response
|
|
|
|
already_canceled['transfers'].append(transfer.pk)
|
|
|
|
else:
|
|
|
|
transfers.append(transfer.pk)
|
|
|
|
# Si transfer il y a plus de CANCEL_DURATION, permission requise
|
|
|
|
if transfer.group.at + cancel_duration < timezone.now():
|
|
|
|
required_perms.add('kfet.cancel_old_operations')
|
|
|
|
|
|
|
|
# Calcul de toutes modifs à faire en cas de validation
|
|
|
|
|
|
|
|
# Pour les balances de comptes
|
|
|
|
to_accounts_balances[transfer.from_acc] += transfer.amount
|
|
|
|
to_accounts_balances[transfer.to_acc] += -transfer.amount
|
|
|
|
|
|
|
|
if not opes and not transfers:
|
|
|
|
data['warnings']['already_canceled'] = already_canceled
|
2016-08-09 11:02:26 +02:00
|
|
|
return JsonResponse(data)
|
|
|
|
|
2016-09-03 18:32:12 +02:00
|
|
|
negative_accounts = []
|
2016-08-09 11:02:26 +02:00
|
|
|
# Checking permissions or stop
|
|
|
|
for account in to_accounts_balances:
|
|
|
|
(perms, stop) = account.perms_to_perform_operation(
|
2016-12-11 19:22:55 +01:00
|
|
|
amount=to_accounts_balances[account])
|
2016-08-09 11:02:26 +02:00
|
|
|
required_perms |= perms
|
|
|
|
stop_all = stop_all or stop
|
2016-09-03 18:32:12 +02:00
|
|
|
if stop:
|
|
|
|
negative_accounts.append(account.trigramme)
|
2016-08-09 11:02:26 +02:00
|
|
|
|
|
|
|
if stop_all or not request.user.has_perms(required_perms):
|
|
|
|
missing_perms = get_missing_perms(required_perms, request.user)
|
|
|
|
if missing_perms:
|
|
|
|
data['errors']['missing_perms'] = missing_perms
|
|
|
|
if stop_all:
|
2016-09-03 18:32:12 +02:00
|
|
|
data['errors']['negative'] = negative_accounts
|
2016-08-09 11:02:26 +02:00
|
|
|
return JsonResponse(data, status=403)
|
|
|
|
|
2016-08-14 19:59:36 +02:00
|
|
|
canceled_by = required_perms and request.user.profile.account_kfet or None
|
|
|
|
canceled_at = timezone.now()
|
|
|
|
|
2016-08-09 11:02:26 +02:00
|
|
|
with transaction.atomic():
|
|
|
|
(Operation.objects.filter(pk__in=opes)
|
2016-08-14 19:59:36 +02:00
|
|
|
.update(canceled_by=canceled_by, canceled_at=canceled_at))
|
2016-12-11 19:22:55 +01:00
|
|
|
|
|
|
|
(Transfer.objects.filter(pk__in=transfers)
|
|
|
|
.update(canceled_by=canceled_by, canceled_at=canceled_at))
|
|
|
|
|
2016-08-09 11:02:26 +02:00
|
|
|
for account in to_accounts_balances:
|
|
|
|
Account.objects.filter(pk=account.pk).update(
|
2016-12-11 19:22:55 +01:00
|
|
|
balance=F('balance') + to_accounts_balances[account])
|
2016-08-09 11:02:26 +02:00
|
|
|
for checkout in to_checkouts_balances:
|
|
|
|
Checkout.objects.filter(pk=checkout.pk).update(
|
2016-12-11 19:22:55 +01:00
|
|
|
balance=F('balance') + to_checkouts_balances[checkout])
|
2016-08-09 11:02:26 +02:00
|
|
|
for group in to_groups_amounts:
|
|
|
|
OperationGroup.objects.filter(pk=group.pk).update(
|
2016-12-11 19:22:55 +01:00
|
|
|
amount=F('amount') + to_groups_amounts[group])
|
2016-08-09 11:02:26 +02:00
|
|
|
for article in to_articles_stocks:
|
|
|
|
Article.objects.filter(pk=article.pk).update(
|
2016-12-11 19:22:55 +01:00
|
|
|
stock=F('stock') + to_articles_stocks[article])
|
2016-08-09 11:02:26 +02:00
|
|
|
|
2016-08-14 19:59:36 +02:00
|
|
|
# Websocket data
|
2016-12-11 19:22:55 +01:00
|
|
|
websocket_data = {'opegroups': [], 'opes': [],
|
|
|
|
'checkouts': [], 'articles': []}
|
2016-08-14 23:37:05 +02:00
|
|
|
# Need refresh from db cause we used update on querysets
|
2016-12-11 19:22:55 +01:00
|
|
|
opegroups_pk = [opegroup.pk for opegroup in to_groups_amounts]
|
2016-08-14 23:37:05 +02:00
|
|
|
opegroups = (OperationGroup.objects
|
2016-12-11 19:22:55 +01:00
|
|
|
.values('id', 'amount', 'is_cof')
|
|
|
|
.filter(pk__in=opegroups_pk))
|
2016-08-14 23:37:05 +02:00
|
|
|
for opegroup in opegroups:
|
2016-08-14 19:59:36 +02:00
|
|
|
websocket_data['opegroups'].append({
|
|
|
|
'cancellation': True,
|
2016-08-14 23:37:05 +02:00
|
|
|
'id': opegroup['id'],
|
|
|
|
'amount': opegroup['amount'],
|
2016-08-24 19:52:07 +02:00
|
|
|
'is_cof': opegroup['is_cof'],
|
2016-08-14 19:59:36 +02:00
|
|
|
})
|
2017-03-18 06:32:27 +01:00
|
|
|
canceled_by = canceled_by and canceled_by.trigramme or None
|
2016-08-14 19:59:36 +02:00
|
|
|
for ope in opes:
|
|
|
|
websocket_data['opes'].append({
|
|
|
|
'cancellation': True,
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'ope',
|
2016-08-14 19:59:36 +02:00
|
|
|
'id': ope,
|
2017-03-18 06:32:27 +01:00
|
|
|
'canceled_by': canceled_by,
|
2016-08-14 19:59:36 +02:00
|
|
|
'canceled_at': canceled_at,
|
|
|
|
})
|
2017-02-05 05:19:20 +01:00
|
|
|
for ope in transfers:
|
|
|
|
websocket_data['opes'].append({
|
|
|
|
'cancellation': True,
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'transfer',
|
2016-08-14 19:59:36 +02:00
|
|
|
'id': ope,
|
2017-03-18 06:32:27 +01:00
|
|
|
'canceled_by': canceled_by,
|
2016-08-14 19:59:36 +02:00
|
|
|
'canceled_at': canceled_at,
|
|
|
|
})
|
2017-02-05 05:19:20 +01:00
|
|
|
|
2016-08-14 23:37:05 +02:00
|
|
|
# Need refresh from db cause we used update on querysets
|
2016-12-11 19:22:55 +01:00
|
|
|
checkouts_pk = [checkout.pk for checkout in to_checkouts_balances]
|
2016-08-14 23:37:05 +02:00
|
|
|
checkouts = (Checkout.objects
|
2016-12-11 19:22:55 +01:00
|
|
|
.values('id', 'balance')
|
|
|
|
.filter(pk__in=checkouts_pk))
|
2016-08-14 23:37:05 +02:00
|
|
|
for checkout in checkouts:
|
|
|
|
websocket_data['checkouts'].append({
|
|
|
|
'id': checkout['id'],
|
|
|
|
'balance': checkout['balance']})
|
|
|
|
# Need refresh from db cause we used update on querysets
|
2016-12-11 19:22:55 +01:00
|
|
|
articles_pk = [article.pk for articles in to_articles_stocks]
|
2016-08-14 23:37:05 +02:00
|
|
|
articles = Article.objects.values('id', 'stock').filter(pk__in=articles_pk)
|
|
|
|
for article in articles:
|
|
|
|
websocket_data['articles'].append({
|
|
|
|
'id': article['id'],
|
|
|
|
'stock': article['stock']})
|
2016-08-14 19:59:36 +02:00
|
|
|
consumers.KPsul.group_send('kfet.kpsul', websocket_data)
|
|
|
|
|
2016-12-11 19:22:55 +01:00
|
|
|
data['canceled']['opes'] = opes
|
|
|
|
data['canceled']['transfers'] = transfers
|
|
|
|
if already_canceled:
|
|
|
|
data['warnings']['already_canceled'] = already_canceled
|
2016-08-09 11:02:26 +02:00
|
|
|
return JsonResponse(data)
|
2016-08-14 19:59:36 +02:00
|
|
|
|
2017-02-05 06:42:02 +01:00
|
|
|
|
2016-08-24 23:34:14 +02:00
|
|
|
@login_required
|
2016-08-24 02:05:05 +02:00
|
|
|
def history_json(request):
|
|
|
|
# Récupération des paramètres
|
|
|
|
from_date = request.POST.get('from', None)
|
2017-02-05 06:42:02 +01:00
|
|
|
to_date = request.POST.get('to', None)
|
2016-08-24 02:05:05 +02:00
|
|
|
checkouts = request.POST.getlist('checkouts[]', None)
|
2017-02-05 06:42:02 +01:00
|
|
|
accounts = request.POST.getlist('accounts[]', None)
|
2016-12-12 02:22:14 +01:00
|
|
|
transfers_only = request.POST.get('transfersonly', None)
|
2016-08-24 02:05:05 +02:00
|
|
|
|
|
|
|
# Construction de la requête (sur les opérations) pour le prefetch
|
2016-12-01 04:29:28 +01:00
|
|
|
ope_queryset_prefetch = Operation.objects.select_related(
|
2016-08-24 02:05:05 +02:00
|
|
|
'canceled_by__trigramme', 'addcost_for__trigramme',
|
|
|
|
'article__name')
|
2016-12-01 04:29:28 +01:00
|
|
|
ope_prefetch = Prefetch('opes',
|
2017-02-05 06:42:02 +01:00
|
|
|
queryset=ope_queryset_prefetch)
|
2016-12-01 04:29:28 +01:00
|
|
|
|
|
|
|
transfer_queryset_prefetch = Transfer.objects.select_related(
|
|
|
|
'from_acc__trigramme', 'to_acc__trigramme',
|
2016-12-09 20:29:40 +01:00
|
|
|
'from_acc__id', 'to_acc__id',
|
2016-12-01 04:29:28 +01:00
|
|
|
'canceled_by__trigramme')
|
|
|
|
|
|
|
|
if accounts:
|
|
|
|
transfer_queryset_prefetch = transfer_queryset_prefetch.filter(
|
2016-12-09 20:29:40 +01:00
|
|
|
Q(from_acc__id__in=accounts) |
|
|
|
|
Q(to_acc__id__in=accounts))
|
2016-12-01 04:29:28 +01:00
|
|
|
|
|
|
|
if not request.user.has_perm('kfet.is_team'):
|
|
|
|
acc = request.user.profile.account_kfet
|
|
|
|
transfer_queryset_prefetch = transfer_queryset_prefetch.filter(
|
|
|
|
Q(from_acc=acc) | Q(to_acc=acc))
|
|
|
|
|
|
|
|
transfer_prefetch = Prefetch('transfers',
|
|
|
|
queryset=transfer_queryset_prefetch,
|
|
|
|
to_attr='filtered_transfers')
|
2016-08-24 02:05:05 +02:00
|
|
|
|
|
|
|
# Construction de la requête principale
|
2017-02-05 06:42:02 +01:00
|
|
|
opegroups = (
|
|
|
|
OperationGroup.objects
|
|
|
|
.prefetch_related(ope_prefetch)
|
|
|
|
.select_related('on_acc__trigramme',
|
|
|
|
'valid_by__trigramme')
|
|
|
|
.order_by('at')
|
2016-08-24 02:05:05 +02:00
|
|
|
)
|
2016-12-01 04:29:28 +01:00
|
|
|
|
|
|
|
transfergroups = (
|
|
|
|
TransferGroup.objects
|
|
|
|
.prefetch_related(transfer_prefetch)
|
|
|
|
.select_related('valid_by__trigramme')
|
2017-02-05 06:42:02 +01:00
|
|
|
.order_by('at')
|
2016-08-24 02:05:05 +02:00
|
|
|
)
|
2016-12-01 04:29:28 +01:00
|
|
|
|
2016-08-24 02:05:05 +02:00
|
|
|
# Application des filtres
|
|
|
|
if from_date:
|
|
|
|
opegroups = opegroups.filter(at__gte=from_date)
|
2016-12-01 04:29:28 +01:00
|
|
|
transfergroups = transfergroups.filter(at__gte=from_date)
|
2016-08-24 02:05:05 +02:00
|
|
|
if to_date:
|
|
|
|
opegroups = opegroups.filter(at__lt=to_date)
|
2016-12-01 04:29:28 +01:00
|
|
|
transfergroups = transfergroups.filter(at__lt=to_date)
|
2016-08-24 02:05:05 +02:00
|
|
|
if checkouts:
|
|
|
|
opegroups = opegroups.filter(checkout_id__in=checkouts)
|
2016-12-01 04:29:28 +01:00
|
|
|
transfergroups = TransferGroup.objects.none()
|
2016-12-12 02:22:14 +01:00
|
|
|
if transfers_only:
|
|
|
|
opegroups = OperationGroup.objects.none()
|
2016-08-24 02:05:05 +02:00
|
|
|
if accounts:
|
|
|
|
opegroups = opegroups.filter(on_acc_id__in=accounts)
|
2016-08-24 23:34:14 +02:00
|
|
|
# Un non-membre de l'équipe n'a que accès à son historique
|
|
|
|
if not request.user.has_perm('kfet.is_team'):
|
|
|
|
opegroups = opegroups.filter(on_acc=request.user.profile.account_kfet)
|
2016-08-24 02:05:05 +02:00
|
|
|
|
|
|
|
# Construction de la réponse
|
2017-03-17 19:59:21 +01:00
|
|
|
opegroup_list = []
|
2016-08-14 19:59:36 +02:00
|
|
|
for opegroup in opegroups:
|
2016-08-24 02:05:05 +02:00
|
|
|
opegroup_dict = {
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'opegroup',
|
2017-03-17 19:59:21 +01:00
|
|
|
'content': {
|
|
|
|
'id': opegroup.id,
|
|
|
|
'amount': opegroup.amount,
|
|
|
|
'at': opegroup.at,
|
|
|
|
'is_cof': opegroup.is_cof,
|
|
|
|
'comment': opegroup.comment,
|
|
|
|
'trigramme':
|
|
|
|
opegroup.on_acc and opegroup.on_acc.trigramme or None,
|
|
|
|
},
|
|
|
|
'parent': {
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'day',
|
2017-03-17 19:59:21 +01:00
|
|
|
'content': {
|
|
|
|
'id': opegroup.at.strftime('%Y%m%d'),
|
|
|
|
'date': opegroup.at
|
|
|
|
},
|
|
|
|
'child_sort': 'opegroup',
|
|
|
|
},
|
|
|
|
'children': [],
|
2016-08-24 02:05:05 +02:00
|
|
|
}
|
|
|
|
if request.user.has_perm('kfet.is_team'):
|
2017-03-17 19:59:21 +01:00
|
|
|
opegroup_dict['content']['valid_by'] = (
|
2016-08-24 02:05:05 +02:00
|
|
|
opegroup.valid_by and opegroup.valid_by.trigramme or None)
|
2017-03-17 19:59:21 +01:00
|
|
|
|
2016-08-24 02:05:05 +02:00
|
|
|
for ope in opegroup.opes.all():
|
|
|
|
ope_dict = {
|
2017-03-17 19:59:21 +01:00
|
|
|
'content': {
|
|
|
|
'id': ope.id,
|
|
|
|
'amount': ope.amount,
|
|
|
|
'canceled_at': ope.canceled_at,
|
|
|
|
'is_cof': opegroup.is_cof,
|
|
|
|
'trigramme':
|
|
|
|
opegroup.on_acc and opegroup.on_acc.trigramme or None,
|
|
|
|
},
|
2016-08-24 02:05:05 +02:00
|
|
|
}
|
|
|
|
if request.user.has_perm('kfet.is_team'):
|
2017-03-17 19:59:21 +01:00
|
|
|
ope_dict['content']['canceled_by'] = (
|
2016-08-24 02:05:05 +02:00
|
|
|
ope.canceled_by and ope.canceled_by.trigramme or None)
|
2017-03-17 19:59:21 +01:00
|
|
|
|
|
|
|
if ope.type == Operation.PURCHASE:
|
2017-03-20 04:36:42 +01:00
|
|
|
ope_dict['modelname'] = 'purchase'
|
2017-03-17 19:59:21 +01:00
|
|
|
ope_dict['content'].update({
|
|
|
|
'article_name': ope.article.name,
|
|
|
|
'article_nb': ope.article_nb,
|
|
|
|
'addcost_amount': ope.addcost_amount,
|
|
|
|
'addcost_for':
|
|
|
|
ope.addcost_for and ope.addcost_for.trigramme or None,
|
|
|
|
})
|
|
|
|
else:
|
2017-03-20 04:36:42 +01:00
|
|
|
ope_dict['modelname'] = 'specialope'
|
2017-03-17 19:59:21 +01:00
|
|
|
ope_dict['content'].update({
|
|
|
|
'type': ope.type,
|
|
|
|
'is_checkout': ope.is_checkout,
|
|
|
|
})
|
|
|
|
|
|
|
|
opegroup_dict['children'].append(ope_dict)
|
|
|
|
opegroup_list.append(opegroup_dict)
|
2016-08-14 23:37:05 +02:00
|
|
|
|
2016-12-02 03:16:40 +01:00
|
|
|
for transfergroup in transfergroups:
|
|
|
|
if transfergroup.filtered_transfers:
|
|
|
|
transfergroup_dict = {
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'transfergroup',
|
2017-03-17 19:59:21 +01:00
|
|
|
'content': {
|
|
|
|
'id': transfergroup.id,
|
|
|
|
'at': transfergroup.at,
|
|
|
|
'comment': transfergroup.comment,
|
|
|
|
},
|
|
|
|
'parent': {
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'day',
|
2017-03-17 19:59:21 +01:00
|
|
|
'content': {
|
|
|
|
'id': transfergroup.at.strftime('%Y%m%d'),
|
|
|
|
'date': transfergroup.at
|
|
|
|
},
|
|
|
|
},
|
|
|
|
'children': [],
|
2016-12-02 03:16:40 +01:00
|
|
|
}
|
2017-03-17 19:59:21 +01:00
|
|
|
|
2016-12-02 03:16:40 +01:00
|
|
|
if request.user.has_perm('kfet.is_team'):
|
2017-03-17 19:59:21 +01:00
|
|
|
transfergroup_dict['content']['valid_by'] = (
|
2017-02-05 06:42:02 +01:00
|
|
|
transfergroup.valid_by and
|
|
|
|
transfergroup.valid_by.trigramme or
|
|
|
|
None)
|
2016-12-02 03:16:40 +01:00
|
|
|
|
|
|
|
for transfer in transfergroup.filtered_transfers:
|
|
|
|
transfer_dict = {
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'transfer',
|
2017-03-17 19:59:21 +01:00
|
|
|
'content': {
|
|
|
|
'id': transfer.id,
|
|
|
|
'amount': transfer.amount,
|
|
|
|
'canceled_at': transfer.canceled_at,
|
|
|
|
'from_acc': transfer.from_acc.trigramme,
|
|
|
|
'to_acc': transfer.to_acc.trigramme,
|
|
|
|
},
|
2016-12-02 03:16:40 +01:00
|
|
|
}
|
|
|
|
if request.user.has_perm('kfet.is_team'):
|
2017-03-17 19:59:21 +01:00
|
|
|
transfer_dict['content']['canceled_by'] = (
|
2017-02-05 06:42:02 +01:00
|
|
|
transfer.canceled_by and
|
|
|
|
transfer.canceled_by.trigramme or
|
|
|
|
None)
|
2017-03-17 19:59:21 +01:00
|
|
|
transfergroup_dict['children'].append(transfer_dict)
|
|
|
|
opegroup_list.append(transfergroup_dict)
|
2016-12-02 03:16:40 +01:00
|
|
|
|
2017-03-17 19:59:21 +01:00
|
|
|
return JsonResponse(opegroup_list, safe=False)
|
2017-03-09 13:21:07 +01:00
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-14 23:37:05 +02:00
|
|
|
def kpsul_articles_data(request):
|
|
|
|
articles = (
|
|
|
|
Article.objects
|
2017-03-09 13:21:07 +01:00
|
|
|
.filter(is_sold=True)
|
|
|
|
.select_related('category'))
|
|
|
|
articlelist = []
|
|
|
|
|
|
|
|
for article in articles:
|
|
|
|
articlelist.append({
|
2017-03-20 04:26:11 +01:00
|
|
|
'modelname': 'article',
|
2017-03-16 02:39:30 +01:00
|
|
|
'content': {
|
|
|
|
'id': article.id,
|
|
|
|
'name': article.name,
|
|
|
|
'price': article.price,
|
|
|
|
'stock': article.stock,
|
|
|
|
},
|
|
|
|
'parent': {
|
2017-03-20 04:26:11 +01:00
|
|
|
'modelname': 'category',
|
2017-03-16 05:20:06 +01:00
|
|
|
'content': {
|
|
|
|
'id': article.category.id,
|
|
|
|
'name': article.category.name,
|
|
|
|
},
|
2017-03-17 16:33:43 +01:00
|
|
|
'child_sort': 'article',
|
2017-03-09 13:21:07 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
return JsonResponse(articlelist, safe=False)
|
2016-08-22 03:57:13 +02:00
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-24 19:52:07 +02:00
|
|
|
def history(request):
|
|
|
|
data = {
|
|
|
|
'filter_form': FilterHistoryForm(),
|
|
|
|
'settings': {
|
|
|
|
'subvention_cof': Settings.SUBVENTION_COF(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return render(request, 'kfet/history.html', data)
|
|
|
|
|
2016-08-22 03:57:13 +02:00
|
|
|
# -----
|
|
|
|
# Settings views
|
|
|
|
# -----
|
|
|
|
|
|
|
|
class SettingsList(ListView):
|
|
|
|
model = Settings
|
|
|
|
context_object_name = 'settings'
|
|
|
|
template_name = 'kfet/settings.html'
|
|
|
|
|
2016-08-22 04:21:10 +02:00
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
Settings.create_missing()
|
|
|
|
return super(SettingsList, self).get_context_data(**kwargs)
|
|
|
|
|
2016-08-22 03:57:13 +02:00
|
|
|
class SettingsUpdate(SuccessMessageMixin, UpdateView):
|
|
|
|
model = Settings
|
|
|
|
form_class = SettingsForm
|
|
|
|
template_name = 'kfet/settings_update.html'
|
|
|
|
success_message = 'Paramètre %(name)s mis à jour'
|
|
|
|
success_url = reverse_lazy('kfet.settings')
|
|
|
|
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
|
|
|
if not self.request.user.has_perm('kfet.change_settings'):
|
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
|
|
|
# Creating
|
2016-08-26 15:30:40 +02:00
|
|
|
Settings.empty_cache()
|
2016-08-22 03:57:13 +02:00
|
|
|
return super(SettingsUpdate, self).form_valid(form)
|
|
|
|
|
2016-08-26 15:30:40 +02:00
|
|
|
# -----
|
|
|
|
# Transfer views
|
|
|
|
# -----
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-26 20:14:00 +02:00
|
|
|
def transfers(request):
|
|
|
|
transfergroups = (TransferGroup.objects
|
|
|
|
.prefetch_related('transfers')
|
|
|
|
.order_by('-at'))
|
|
|
|
return render(request, 'kfet/transfers.html', {
|
|
|
|
'transfergroups': transfergroups,
|
|
|
|
})
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-26 20:14:00 +02:00
|
|
|
def transfers_create(request):
|
2016-08-26 15:30:40 +02:00
|
|
|
transfer_formset = TransferFormSet(queryset=Transfer.objects.none())
|
|
|
|
return render(request, 'kfet/transfers_create.html',
|
|
|
|
{ 'transfer_formset': transfer_formset })
|
|
|
|
|
2017-02-05 06:42:02 +01:00
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-26 15:30:40 +02:00
|
|
|
def perform_transfers(request):
|
2017-02-05 06:42:02 +01:00
|
|
|
data = {'errors': {}, 'transfers': [], 'transfergroup': 0}
|
2016-08-26 15:30:40 +02:00
|
|
|
|
|
|
|
# Checking transfer_formset
|
|
|
|
transfer_formset = TransferFormSet(request.POST)
|
|
|
|
if not transfer_formset.is_valid():
|
2017-02-05 06:42:02 +01:00
|
|
|
return JsonResponse({'errors': list(transfer_formset.errors)},
|
|
|
|
status=400)
|
2016-08-26 15:30:40 +02:00
|
|
|
|
2017-02-05 06:42:02 +01:00
|
|
|
transfers = transfer_formset.save(commit=False)
|
2016-08-26 15:30:40 +02:00
|
|
|
|
|
|
|
# Initializing vars
|
2017-02-05 06:42:02 +01:00
|
|
|
# Required perms to perform all transfers
|
|
|
|
required_perms = set(['kfet.add_transfer'])
|
|
|
|
# For balances of accounts
|
|
|
|
to_accounts_balances = defaultdict(lambda: 0)
|
2016-08-26 15:30:40 +02:00
|
|
|
|
|
|
|
for transfer in transfers:
|
|
|
|
to_accounts_balances[transfer.from_acc] -= transfer.amount
|
|
|
|
to_accounts_balances[transfer.to_acc] += transfer.amount
|
|
|
|
|
|
|
|
stop_all = False
|
|
|
|
|
2016-09-03 18:32:12 +02:00
|
|
|
negative_accounts = []
|
2016-08-26 15:30:40 +02:00
|
|
|
# Checking if ok on all accounts
|
|
|
|
for account in to_accounts_balances:
|
|
|
|
(perms, stop) = account.perms_to_perform_operation(
|
2017-02-05 06:42:02 +01:00
|
|
|
amount=to_accounts_balances[account])
|
2016-08-26 15:30:40 +02:00
|
|
|
required_perms |= perms
|
|
|
|
stop_all = stop_all or stop
|
2016-09-03 18:32:12 +02:00
|
|
|
if stop:
|
|
|
|
negative_accounts.append(account.trigramme)
|
2016-08-26 15:30:40 +02:00
|
|
|
|
|
|
|
if stop_all or not request.user.has_perms(required_perms):
|
|
|
|
missing_perms = get_missing_perms(required_perms, request.user)
|
|
|
|
if missing_perms:
|
|
|
|
data['errors']['missing_perms'] = missing_perms
|
|
|
|
if stop_all:
|
2016-09-03 18:32:12 +02:00
|
|
|
data['errors']['negative'] = negative_accounts
|
2016-08-26 15:30:40 +02:00
|
|
|
return JsonResponse(data, status=403)
|
|
|
|
|
2016-08-26 20:14:00 +02:00
|
|
|
# Creating transfer group
|
|
|
|
transfergroup = TransferGroup()
|
|
|
|
if required_perms:
|
|
|
|
transfergroup.valid_by = request.user.profile.account_kfet
|
|
|
|
|
|
|
|
comment = request.POST.get('comment', '')
|
|
|
|
transfergroup.comment = comment.strip()
|
|
|
|
|
2016-08-26 15:30:40 +02:00
|
|
|
with transaction.atomic():
|
|
|
|
# Updating balances accounts
|
|
|
|
for account in to_accounts_balances:
|
|
|
|
Account.objects.filter(pk=account.pk).update(
|
2017-02-05 06:42:02 +01:00
|
|
|
balance=F('balance') + to_accounts_balances[account])
|
2016-08-26 15:30:40 +02:00
|
|
|
account.refresh_from_db()
|
|
|
|
if account.balance < 0:
|
|
|
|
if hasattr(account, 'negative'):
|
|
|
|
if not account.negative.start:
|
|
|
|
account.negative.start = timezone.now()
|
|
|
|
account.negative.save()
|
|
|
|
else:
|
|
|
|
negative = AccountNegative(
|
2017-02-05 06:42:02 +01:00
|
|
|
account=account, start=timezone.now())
|
2016-08-26 15:30:40 +02:00
|
|
|
negative.save()
|
2017-02-05 06:42:02 +01:00
|
|
|
elif (hasattr(account, 'negative') and
|
|
|
|
not account.negative.balance_offset):
|
2016-08-26 15:30:40 +02:00
|
|
|
account.negative.delete()
|
|
|
|
|
2016-08-26 20:14:00 +02:00
|
|
|
# Saving transfer group
|
2016-08-26 15:30:40 +02:00
|
|
|
transfergroup.save()
|
|
|
|
data['transfergroup'] = transfergroup.pk
|
|
|
|
|
|
|
|
# Saving all transfers with group
|
|
|
|
for transfer in transfers:
|
|
|
|
transfer.group = transfergroup
|
|
|
|
transfer.save()
|
|
|
|
data['transfers'].append(transfer.pk)
|
|
|
|
|
2017-02-05 06:26:15 +01:00
|
|
|
# Websocket data
|
|
|
|
websocket_data = {}
|
|
|
|
websocket_data['opegroups'] = [{
|
|
|
|
'add': True,
|
2017-03-20 04:36:42 +01:00
|
|
|
'modelname': 'transfergroup',
|
2017-02-05 06:26:15 +01:00
|
|
|
'id': transfergroup.pk,
|
|
|
|
'at': transfergroup.at,
|
|
|
|
'comment': transfergroup.comment,
|
2017-02-05 06:42:02 +01:00
|
|
|
'valid_by__trigramme': (transfergroup.valid_by and
|
|
|
|
transfergroup.valid_by.trigramme or None),
|
2017-02-05 06:26:15 +01:00
|
|
|
'opes': [],
|
|
|
|
}]
|
|
|
|
for transfer in transfers:
|
|
|
|
ope_data = {
|
|
|
|
'id': transfer.pk,
|
|
|
|
'amount': transfer.amount,
|
|
|
|
'from_acc': transfer.from_acc.trigramme,
|
|
|
|
'to_acc': transfer.to_acc.trigramme,
|
|
|
|
'canceled_by__trigramme': None, 'canceled_at': None,
|
|
|
|
}
|
|
|
|
websocket_data['opegroups'][0]['opes'].append(ope_data)
|
2016-09-24 14:18:26 +02:00
|
|
|
|
2017-02-05 06:26:15 +01:00
|
|
|
consumers.KPsul.group_send('kfet.kpsul', websocket_data)
|
2016-09-24 14:18:26 +02:00
|
|
|
return JsonResponse(data)
|
|
|
|
|
|
|
|
|
2016-08-27 14:12:01 +02:00
|
|
|
class InventoryList(ListView):
|
|
|
|
queryset = (Inventory.objects
|
|
|
|
.select_related('by', 'order')
|
|
|
|
.annotate(nb_articles=Count('articles'))
|
|
|
|
.order_by('-at'))
|
|
|
|
template_name = 'kfet/inventory.html'
|
|
|
|
context_object_name = 'inventories'
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-27 14:12:01 +02:00
|
|
|
def inventory_create(request):
|
|
|
|
|
|
|
|
articles = (Article.objects
|
|
|
|
.select_related('category')
|
|
|
|
.order_by('category__name', 'name')
|
|
|
|
)
|
|
|
|
initial = []
|
|
|
|
for article in articles:
|
|
|
|
initial.append({
|
|
|
|
'article' : article.pk,
|
|
|
|
'stock_old': article.stock,
|
|
|
|
'name' : article.name,
|
|
|
|
'category' : article.category_id,
|
|
|
|
'category__name': article.category.name
|
|
|
|
})
|
|
|
|
|
|
|
|
cls_formset = formset_factory(
|
|
|
|
form = InventoryArticleForm,
|
|
|
|
extra = 0,
|
|
|
|
)
|
|
|
|
|
|
|
|
if request.POST:
|
|
|
|
formset = cls_formset(request.POST, initial=initial)
|
2016-08-27 22:55:31 +02:00
|
|
|
|
|
|
|
if not request.user.has_perm('kfet.add_inventory'):
|
|
|
|
messages.error(request, 'Permission refusée')
|
|
|
|
elif formset.is_valid():
|
2016-08-27 14:12:01 +02:00
|
|
|
with transaction.atomic():
|
|
|
|
|
|
|
|
articles = Article.objects.select_for_update()
|
|
|
|
inventory = Inventory()
|
|
|
|
inventory.by = request.user.profile.account_kfet
|
|
|
|
saved = False
|
|
|
|
for form in formset:
|
|
|
|
if form.cleaned_data['stock_new'] is not None:
|
|
|
|
if not saved:
|
|
|
|
inventory.save()
|
2016-08-28 05:39:34 +02:00
|
|
|
saved = True
|
2016-08-27 14:12:01 +02:00
|
|
|
|
|
|
|
article = articles.get(pk=form.cleaned_data['article'].pk)
|
|
|
|
stock_old = article.stock
|
|
|
|
stock_new = form.cleaned_data['stock_new']
|
|
|
|
InventoryArticle.objects.create(
|
|
|
|
inventory = inventory,
|
|
|
|
article = article,
|
|
|
|
stock_old = stock_old,
|
2016-08-27 21:43:19 +02:00
|
|
|
stock_new = stock_new)
|
2016-08-27 14:12:01 +02:00
|
|
|
article.stock = stock_new
|
|
|
|
article.save()
|
2016-08-27 22:55:31 +02:00
|
|
|
if saved:
|
|
|
|
messages.success(request, 'Inventaire créé')
|
|
|
|
return redirect('kfet.inventory')
|
|
|
|
messages.warning(request, 'Bah alors ? On a rien compté ?')
|
2016-08-27 14:12:01 +02:00
|
|
|
else:
|
2016-08-27 22:55:31 +02:00
|
|
|
messages.error(request, 'Pas marché')
|
2016-08-27 14:12:01 +02:00
|
|
|
else:
|
|
|
|
formset = cls_formset(initial = initial)
|
|
|
|
|
|
|
|
return render(request, 'kfet/inventory_create.html', {
|
|
|
|
'formset': formset,
|
|
|
|
})
|
2016-08-27 22:55:31 +02:00
|
|
|
|
2016-08-30 23:32:54 +02:00
|
|
|
class InventoryRead(DetailView):
|
|
|
|
model = Inventory
|
|
|
|
template_name = 'kfet/inventory_read.html'
|
|
|
|
context_object_name = 'inventory'
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(InventoryRead, self).get_context_data(**kwargs)
|
|
|
|
inventoryarticles = (InventoryArticle.objects
|
|
|
|
.select_related('article', 'article__category')
|
|
|
|
.filter(inventory = self.object)
|
|
|
|
.order_by('article__category__name', 'article__name'))
|
|
|
|
context['inventoryarts'] = inventoryarticles
|
|
|
|
return context
|
2016-08-27 22:55:31 +02:00
|
|
|
|
|
|
|
# -----
|
|
|
|
# Order views
|
|
|
|
# -----
|
|
|
|
|
|
|
|
class OrderList(ListView):
|
2016-08-30 17:07:51 +02:00
|
|
|
queryset = Order.objects.select_related('supplier', 'inventory')
|
2016-08-27 22:55:31 +02:00
|
|
|
template_name = 'kfet/order.html'
|
2016-08-28 05:39:34 +02:00
|
|
|
context_object_name = 'orders'
|
2016-08-27 22:55:31 +02:00
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(OrderList, self).get_context_data(**kwargs)
|
|
|
|
context['suppliers'] = Supplier.objects.order_by('name')
|
|
|
|
return context
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-28 05:39:34 +02:00
|
|
|
def order_create(request, pk):
|
2016-08-30 15:35:30 +02:00
|
|
|
supplier = get_object_or_404(Supplier, pk=pk)
|
2016-08-28 05:39:34 +02:00
|
|
|
|
|
|
|
articles = (Article.objects
|
|
|
|
.filter(suppliers=supplier.pk)
|
2016-12-07 21:35:27 +01:00
|
|
|
.distinct()
|
2016-08-28 05:39:34 +02:00
|
|
|
.select_related('category')
|
|
|
|
.order_by('category__name', 'name'))
|
|
|
|
|
|
|
|
initial = []
|
|
|
|
today = timezone.now().date()
|
|
|
|
sales_q = (Operation.objects
|
|
|
|
.select_related('group')
|
|
|
|
.filter(article__in=articles, canceled_at=None)
|
|
|
|
.values('article'))
|
|
|
|
sales_s1 = (sales_q
|
|
|
|
.filter(
|
|
|
|
group__at__gte = today-timedelta(weeks=5),
|
|
|
|
group__at__lt = today-timedelta(weeks=4))
|
|
|
|
.annotate(nb=Sum('article_nb'))
|
|
|
|
)
|
|
|
|
sales_s1 = { d['article']:d['nb'] for d in sales_s1 }
|
|
|
|
sales_s2 = (sales_q
|
|
|
|
.filter(
|
|
|
|
group__at__gte = today-timedelta(weeks=4),
|
|
|
|
group__at__lt = today-timedelta(weeks=3))
|
|
|
|
.annotate(nb=Sum('article_nb'))
|
|
|
|
)
|
|
|
|
sales_s2 = { d['article']:d['nb'] for d in sales_s2 }
|
|
|
|
sales_s3 = (sales_q
|
|
|
|
.filter(
|
|
|
|
group__at__gte = today-timedelta(weeks=3),
|
|
|
|
group__at__lt = today-timedelta(weeks=2))
|
|
|
|
.annotate(nb=Sum('article_nb'))
|
|
|
|
)
|
|
|
|
sales_s3 = { d['article']:d['nb'] for d in sales_s3 }
|
|
|
|
sales_s4 = (sales_q
|
|
|
|
.filter(
|
|
|
|
group__at__gte = today-timedelta(weeks=2),
|
|
|
|
group__at__lt = today-timedelta(weeks=1))
|
|
|
|
.annotate(nb=Sum('article_nb'))
|
|
|
|
)
|
|
|
|
sales_s4 = { d['article']:d['nb'] for d in sales_s4 }
|
|
|
|
sales_s5 = (sales_q
|
|
|
|
.filter(group__at__gte = today-timedelta(weeks=1))
|
|
|
|
.annotate(nb=Sum('article_nb'))
|
|
|
|
)
|
|
|
|
sales_s5 = { d['article']:d['nb'] for d in sales_s5 }
|
|
|
|
|
|
|
|
for article in articles:
|
|
|
|
v_s1 = sales_s1.get(article.pk, 0)
|
|
|
|
v_s2 = sales_s2.get(article.pk, 0)
|
|
|
|
v_s3 = sales_s3.get(article.pk, 0)
|
|
|
|
v_s4 = sales_s4.get(article.pk, 0)
|
|
|
|
v_s5 = sales_s5.get(article.pk, 0)
|
|
|
|
v_all = [v_s1, v_s2, v_s3, v_s4, v_s5]
|
|
|
|
v_3max = heapq.nlargest(3, v_all)
|
|
|
|
v_moy = statistics.mean(v_3max)
|
|
|
|
v_et = statistics.pstdev(v_3max, v_moy)
|
|
|
|
v_prev = v_moy + v_et
|
|
|
|
c_rec_tot = max(v_prev * 1.5 - article.stock, 0)
|
|
|
|
if article.box_capacity:
|
2016-08-30 15:35:30 +02:00
|
|
|
c_rec_temp = c_rec_tot / article.box_capacity
|
2016-08-28 05:39:34 +02:00
|
|
|
if c_rec_temp >= 10:
|
|
|
|
c_rec = round(c_rec_temp)
|
|
|
|
elif c_rec_temp > 5:
|
|
|
|
c_rec = 10
|
|
|
|
elif c_rec_temp > 2:
|
|
|
|
c_rec = 5
|
|
|
|
else:
|
|
|
|
c_rec = round(c_rec_temp)
|
|
|
|
initial.append({
|
|
|
|
'article': article.pk,
|
|
|
|
'name': article.name,
|
|
|
|
'category': article.category_id,
|
|
|
|
'category__name': article.category.name,
|
|
|
|
'stock': article.stock,
|
|
|
|
'box_capacity': article.box_capacity,
|
|
|
|
'v_s1': v_s1,
|
|
|
|
'v_s2': v_s2,
|
|
|
|
'v_s3': v_s3,
|
|
|
|
'v_s4': v_s4,
|
|
|
|
'v_s5': v_s5,
|
|
|
|
'v_moy': round(v_moy),
|
|
|
|
'v_et': round(v_et),
|
|
|
|
'v_prev': round(v_prev),
|
|
|
|
'c_rec': article.box_capacity and c_rec or round(c_rec_tot),
|
|
|
|
})
|
|
|
|
|
|
|
|
cls_formset = formset_factory(
|
|
|
|
form = OrderArticleForm,
|
|
|
|
extra = 0)
|
|
|
|
|
|
|
|
if request.POST:
|
|
|
|
formset = cls_formset(request.POST, initial=initial)
|
|
|
|
|
|
|
|
if not request.user.has_perm('kfet.add_order'):
|
|
|
|
messages.error(request, 'Permission refusée')
|
|
|
|
elif formset.is_valid():
|
|
|
|
order = Order()
|
|
|
|
order.supplier = supplier
|
|
|
|
saved = False
|
|
|
|
for form in formset:
|
|
|
|
if form.cleaned_data['quantity_ordered'] is not None:
|
|
|
|
if not saved:
|
|
|
|
order.save()
|
|
|
|
saved = True
|
|
|
|
|
|
|
|
article = articles.get(pk=form.cleaned_data['article'].pk)
|
|
|
|
q_ordered = form.cleaned_data['quantity_ordered']
|
|
|
|
if article.box_capacity:
|
2016-08-30 15:35:30 +02:00
|
|
|
q_ordered *= article.box_capacity
|
2016-08-28 05:39:34 +02:00
|
|
|
OrderArticle.objects.create(
|
|
|
|
order = order,
|
|
|
|
article = article,
|
|
|
|
quantity_ordered = q_ordered)
|
|
|
|
if saved:
|
|
|
|
messages.success(request, 'Commande créée')
|
|
|
|
return redirect('kfet.order.read', order.pk)
|
|
|
|
messages.warning(request, 'Rien commandé => Pas de commande')
|
|
|
|
else:
|
2016-09-03 19:41:44 +02:00
|
|
|
messages.error(request, 'Corrigez les erreurs')
|
2016-08-28 05:39:34 +02:00
|
|
|
else:
|
|
|
|
formset = cls_formset(initial=initial)
|
|
|
|
|
|
|
|
return render(request, 'kfet/order_create.html', {
|
|
|
|
'supplier': supplier,
|
|
|
|
'formset' : formset,
|
|
|
|
})
|
|
|
|
|
|
|
|
class OrderRead(DetailView):
|
|
|
|
model = Order
|
|
|
|
template_name = 'kfet/order_read.html'
|
|
|
|
context_object_name = 'order'
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(OrderRead, self).get_context_data(**kwargs)
|
|
|
|
orderarticles = (OrderArticle.objects
|
|
|
|
.select_related('article', 'article__category')
|
|
|
|
.filter(order=self.object)
|
|
|
|
.order_by('article__category__name', 'article__name')
|
|
|
|
)
|
2016-08-30 17:07:51 +02:00
|
|
|
context['orderarts'] = orderarticles
|
2016-08-28 05:39:34 +02:00
|
|
|
mail = ("Bonjour,\n\nNous voudrions pour le ##DATE## à la K-Fêt de "
|
|
|
|
"l'ENS Ulm :")
|
|
|
|
category = 0
|
|
|
|
for orderarticle in orderarticles:
|
|
|
|
if category != orderarticle.article.category:
|
|
|
|
category = orderarticle.article.category
|
|
|
|
mail += '\n'
|
|
|
|
nb = orderarticle.quantity_ordered
|
|
|
|
box = ''
|
|
|
|
if orderarticle.article.box_capacity:
|
|
|
|
nb /= orderarticle.article.box_capacity
|
|
|
|
if nb >= 2:
|
|
|
|
box = ' %ss de' % orderarticle.article.box_type
|
|
|
|
else:
|
|
|
|
box = ' %s de' % orderarticle.article.box_type
|
|
|
|
name = orderarticle.article.name.capitalize()
|
|
|
|
mail += "\n- %s%s %s" % (round(nb), box, name)
|
|
|
|
|
|
|
|
mail += ("\n\nMerci d'appeler le numéro suivant lorsque les livreurs "
|
|
|
|
"sont là : ##TELEPHONE##\nCordialement,\n##PRENOM## ##NOM## "
|
|
|
|
", pour la K-Fêt de l'ENS Ulm")
|
|
|
|
|
|
|
|
context['mail'] = mail
|
|
|
|
return context
|
|
|
|
|
2016-08-31 02:52:13 +02:00
|
|
|
@teamkfet_required
|
2016-08-30 15:35:30 +02:00
|
|
|
def order_to_inventory(request, pk):
|
|
|
|
order = get_object_or_404(Order, pk=pk)
|
|
|
|
|
|
|
|
if hasattr(order, 'inventory'):
|
|
|
|
raise Http404
|
|
|
|
|
|
|
|
articles = (Article.objects
|
|
|
|
.filter(orders=order.pk)
|
|
|
|
.select_related('category')
|
|
|
|
.prefetch_related(Prefetch('orderarticle_set',
|
|
|
|
queryset = OrderArticle.objects.filter(order=order),
|
|
|
|
to_attr = 'order'))
|
|
|
|
.prefetch_related(Prefetch('supplierarticle_set',
|
|
|
|
queryset = (SupplierArticle.objects
|
|
|
|
.filter(supplier=order.supplier)
|
|
|
|
.order_by('-at')),
|
|
|
|
to_attr = 'supplier'))
|
|
|
|
.order_by('category__name', 'name'))
|
|
|
|
|
|
|
|
initial = []
|
|
|
|
for article in articles:
|
|
|
|
initial.append({
|
|
|
|
'article': article.pk,
|
|
|
|
'name': article.name,
|
|
|
|
'category': article.category_id,
|
|
|
|
'category__name': article.category.name,
|
|
|
|
'quantity_ordered': article.order[0].quantity_ordered,
|
|
|
|
'quantity_received': article.order[0].quantity_ordered,
|
|
|
|
'price_HT': article.supplier[0].price_HT,
|
|
|
|
'TVA': article.supplier[0].TVA,
|
|
|
|
'rights': article.supplier[0].rights,
|
|
|
|
})
|
|
|
|
|
|
|
|
cls_formset = formset_factory(OrderArticleToInventoryForm, extra=0)
|
|
|
|
|
|
|
|
if request.method == 'POST':
|
|
|
|
formset = cls_formset(request.POST, initial=initial)
|
|
|
|
|
|
|
|
if not request.user.has_perm('kfet.order_to_inventory'):
|
2016-09-03 22:34:42 +02:00
|
|
|
messages.error(request, 'Permission refusée')
|
2016-08-30 15:35:30 +02:00
|
|
|
elif formset.is_valid():
|
|
|
|
with transaction.atomic():
|
|
|
|
inventory = Inventory()
|
|
|
|
inventory.order = order
|
|
|
|
inventory.by = request.user.profile.account_kfet
|
|
|
|
inventory.save()
|
|
|
|
for form in formset:
|
|
|
|
q_received = form.cleaned_data['quantity_received']
|
|
|
|
article = form.cleaned_data['article']
|
|
|
|
SupplierArticle.objects.create(
|
|
|
|
supplier = order.supplier,
|
|
|
|
article = article,
|
|
|
|
price_HT = form.cleaned_data['price_HT'],
|
|
|
|
TVA = form.cleaned_data['TVA'],
|
|
|
|
rights = form.cleaned_data['rights'])
|
|
|
|
(OrderArticle.objects
|
|
|
|
.filter(order=order, article=article)
|
|
|
|
.update(quantity_received = q_received))
|
|
|
|
InventoryArticle.objects.create(
|
|
|
|
inventory = inventory,
|
|
|
|
article = article,
|
|
|
|
stock_old = article.stock,
|
|
|
|
stock_new = article.stock + q_received)
|
|
|
|
article.stock += q_received
|
2016-08-31 01:06:48 +02:00
|
|
|
if q_received > 0:
|
|
|
|
article.is_sold = True
|
2016-08-30 15:35:30 +02:00
|
|
|
article.save()
|
|
|
|
messages.success(request, "C'est tout bon !")
|
|
|
|
return redirect('kfet.order')
|
|
|
|
else:
|
|
|
|
messages.error(request, "Corrigez les erreurs")
|
|
|
|
else:
|
|
|
|
formset = cls_formset(initial=initial)
|
|
|
|
|
|
|
|
return render(request, 'kfet/order_to_inventory.html', {
|
|
|
|
'formset': formset,
|
|
|
|
})
|
|
|
|
|
2016-08-27 22:55:31 +02:00
|
|
|
class SupplierUpdate(SuccessMessageMixin, UpdateView):
|
|
|
|
model = Supplier
|
|
|
|
template_name = 'kfet/supplier_form.html'
|
|
|
|
fields = ['name', 'address', 'email', 'phone', 'comment']
|
|
|
|
success_url = reverse_lazy('kfet.order')
|
|
|
|
sucess_message = 'Données fournisseur mis à jour'
|
|
|
|
|
|
|
|
# Surcharge de la validation
|
|
|
|
def form_valid(self, form):
|
|
|
|
# Checking permission
|
|
|
|
if not self.request.user.has_perm('kfet.change_supplier'):
|
|
|
|
form.add_error(None, 'Permission refusée')
|
|
|
|
return self.form_invalid(form)
|
|
|
|
# Updating
|
|
|
|
return super(SupplierUpdate, self).form_valid(form)
|