core -- Apply black + isort to all files

This commit is contained in:
Aurélien Delobelle 2018-10-06 12:35:49 +02:00
parent 104e71dcf6
commit fdd2b35289
196 changed files with 10727 additions and 8365 deletions

View file

@ -1 +1 @@
default_app_config = 'kfet.apps.KFetConfig'
default_app_config = "kfet.apps.KFetConfig"

View file

@ -2,7 +2,7 @@ from django.apps import AppConfig
class KFetConfig(AppConfig):
name = 'kfet'
name = "kfet"
verbose_name = "Application K-Fêt"
def ready(self):
@ -11,4 +11,5 @@ class KFetConfig(AppConfig):
def register_config(self):
import djconfig
from kfet.forms import KFetConfigForm
djconfig.register(KFetConfigForm)

View file

@ -1,4 +1,4 @@
default_app_config = 'kfet.auth.apps.KFetAuthConfig'
default_app_config = "kfet.auth.apps.KFetAuthConfig"
KFET_GENERIC_USERNAME = 'kfet_genericteam'
KFET_GENERIC_TRIGRAMME = 'GNR'
KFET_GENERIC_USERNAME = "kfet_genericteam"
KFET_GENERIC_TRIGRAMME = "GNR"

View file

@ -4,11 +4,12 @@ from django.utils.translation import ugettext_lazy as _
class KFetAuthConfig(AppConfig):
name = 'kfet.auth'
label = 'kfetauth'
name = "kfet.auth"
label = "kfetauth"
verbose_name = _("K-Fêt - Authentification et Autorisation")
def ready(self):
from . import signals # noqa
from .utils import setup_kfet_generic_user
post_migrate.connect(setup_kfet_generic_user, sender=self)

View file

@ -1,4 +1,5 @@
from django.contrib.auth import get_user_model
from kfet.models import Account, GenericTeamToken
from .utils import get_kfet_generic_user
@ -12,11 +13,7 @@ class BaseKFetBackend:
Add extra select related up to Account.
"""
try:
return (
User.objects
.select_related('profile__account_kfet')
.get(pk=user_id)
)
return User.objects.select_related("profile__account_kfet").get(pk=user_id)
except User.DoesNotExist:
return None

View file

@ -2,9 +2,6 @@ from django.contrib.auth.context_processors import PermWrapper
def temporary_auth(request):
if hasattr(request, 'real_user'):
return {
'user': request.real_user,
'perms': PermWrapper(request.real_user),
}
if hasattr(request, "real_user"):
return {"user": request.real_user, "perms": PermWrapper(request.real_user)}
return {}

View file

@ -5,15 +5,12 @@ from django.forms import widgets
class KFetPermissionsField(forms.ModelMultipleChoiceField):
def __init__(self, *args, **kwargs):
queryset = Permission.objects.filter(
content_type__in=ContentType.objects.filter(app_label="kfet"),
content_type__in=ContentType.objects.filter(app_label="kfet")
)
super().__init__(
queryset=queryset,
widget=widgets.CheckboxSelectMultiple,
*args, **kwargs
queryset=queryset, widget=widgets.CheckboxSelectMultiple, *args, **kwargs
)
def label_from_instance(self, obj):

View file

@ -8,11 +8,11 @@ class GroupForm(forms.ModelForm):
permissions = KFetPermissionsField()
def clean_name(self):
name = self.cleaned_data['name']
return 'K-Fêt %s' % name
name = self.cleaned_data["name"]
return "K-Fêt %s" % name
def clean_permissions(self):
kfet_perms = self.cleaned_data['permissions']
kfet_perms = self.cleaned_data["permissions"]
# TODO: With Django >=1.11, the QuerySet method 'difference' can be
# used.
# other_groups = self.instance.permissions.difference(
@ -21,28 +21,29 @@ class GroupForm(forms.ModelForm):
if self.instance.pk is None:
return kfet_perms
other_perms = self.instance.permissions.exclude(
pk__in=[p.pk for p in self.fields['permissions'].queryset],
pk__in=[p.pk for p in self.fields["permissions"].queryset]
)
return list(kfet_perms) + list(other_perms)
class Meta:
model = Group
fields = ['name', 'permissions']
fields = ["name", "permissions"]
class UserGroupForm(forms.ModelForm):
groups = forms.ModelMultipleChoiceField(
Group.objects.filter(name__icontains='K-Fêt'),
label='Statut équipe',
required=False)
Group.objects.filter(name__icontains="K-Fêt"),
label="Statut équipe",
required=False,
)
def clean_groups(self):
kfet_groups = self.cleaned_data.get('groups')
kfet_groups = self.cleaned_data.get("groups")
if self.instance.pk is None:
return kfet_groups
other_groups = self.instance.groups.exclude(name__icontains='K-Fêt')
other_groups = self.instance.groups.exclude(name__icontains="K-Fêt")
return list(kfet_groups) + list(other_groups)
class Meta:
model = User
fields = ['groups']
fields = ["groups"]

View file

@ -12,21 +12,19 @@ class TemporaryAuthMiddleware:
values from CofProfile and Account of this user.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated:
# avoid multiple db accesses in views and templates
request.user = (
User.objects
.select_related('profile__account_kfet')
.get(pk=request.user.pk)
request.user = User.objects.select_related("profile__account_kfet").get(
pk=request.user.pk
)
temp_request_user = AccountBackend().authenticate(
request,
kfet_password=self.get_kfet_password(request),
request, kfet_password=self.get_kfet_password(request)
)
if temp_request_user:
@ -36,7 +34,4 @@ class TemporaryAuthMiddleware:
return self.get_response(request)
def get_kfet_password(self, request):
return (
request.META.get('HTTP_KFETPASSWORD') or
request.POST.get('KFETPASSWORD')
)
return request.META.get("HTTP_KFETPASSWORD") or request.POST.get("KFETPASSWORD")

View file

@ -7,18 +7,26 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
("auth", "0006_require_contenttypes_0002"),
# Following dependency allows using Account model to set up the kfet
# generic user in post_migrate receiver.
('kfet', '0058_delete_genericteamtoken'),
("kfet", "0058_delete_genericteamtoken"),
]
operations = [
migrations.CreateModel(
name='GenericTeamToken',
name="GenericTeamToken",
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('token', models.CharField(unique=True, max_length=50)),
(
"id",
models.AutoField(
verbose_name="ID",
auto_created=True,
serialize=False,
primary_key=True,
),
),
("token", models.CharField(unique=True, max_length=50)),
],
),
)
]

View file

@ -3,7 +3,6 @@ from django.utils.crypto import get_random_string
class GenericTeamTokenManager(models.Manager):
def create_token(self):
token = get_random_string(50)
while self.filter(token=token).exists():

View file

@ -19,22 +19,26 @@ def suggest_auth_generic(sender, request, user, **kwargs):
- logged in user is a kfet staff member (except the generic user).
"""
# Filter against the next page.
if not(hasattr(request, 'GET') and 'next' in request.GET):
if not (hasattr(request, "GET") and "next" in request.GET):
return
next_page = request.GET['next']
generic_url = reverse('kfet.login.generic')
next_page = request.GET["next"]
generic_url = reverse("kfet.login.generic")
if not('k-fet' in next_page and not next_page.startswith(generic_url)):
if not ("k-fet" in next_page and not next_page.startswith(generic_url)):
return
# Filter against the logged in user.
if not(user.has_perm('kfet.is_team') and user != get_kfet_generic_user()):
if not (user.has_perm("kfet.is_team") and user != get_kfet_generic_user()):
return
# Seems legit to add message.
text = _("K-Fêt — Ouvrir une session partagée ?")
messages.info(request, mark_safe(
'<a href="#" data-url="{}" onclick="submit_url(this)">{}</a>'
.format(generic_url, text)
))
messages.info(
request,
mark_safe(
'<a href="#" data-url="{}" onclick="submit_url(this)">{}</a>'.format(
generic_url, text
)
),
)

View file

@ -1,8 +1,8 @@
from unittest import mock
from django.contrib.auth.models import AnonymousUser, Group, Permission, User
from django.core import signing
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser, Group, Permission, User
from django.test import RequestFactory, TestCase
from kfet.forms import UserGroupForm
@ -15,11 +15,11 @@ from .models import GenericTeamToken
from .utils import get_kfet_generic_user
from .views import GenericLoginView
##
# Forms
##
class UserGroupFormTests(TestCase):
"""Test suite for UserGroupForm."""
@ -31,8 +31,7 @@ class UserGroupFormTests(TestCase):
prefix_name = "K-Fêt "
names = ["Group 1", "Group 2", "Group 3"]
self.kfet_groups = [
Group.objects.create(name=prefix_name+name)
for name in names
Group.objects.create(name=prefix_name + name) for name in names
]
# create a non-K-Fêt group
@ -41,11 +40,9 @@ class UserGroupFormTests(TestCase):
def test_choices(self):
"""Only K-Fêt groups are selectable."""
form = UserGroupForm(instance=self.user)
groups_field = form.fields['groups']
groups_field = form.fields["groups"]
self.assertQuerysetEqual(
groups_field.queryset,
[repr(g) for g in self.kfet_groups],
ordered=False,
groups_field.queryset, [repr(g) for g in self.kfet_groups], ordered=False
)
def test_keep_others(self):
@ -56,9 +53,7 @@ class UserGroupFormTests(TestCase):
user.groups.add(self.other_group)
# add user to some K-Fêt groups through UserGroupForm
data = {
'groups': [group.pk for group in self.kfet_groups],
}
data = {"groups": [group.pk for group in self.kfet_groups]}
form = UserGroupForm(data, instance=user)
form.is_valid()
@ -71,7 +66,6 @@ class UserGroupFormTests(TestCase):
class KFetGenericUserTests(TestCase):
def test_exists(self):
"""
The account is set up when app is ready, so it should exist.
@ -86,44 +80,39 @@ class KFetGenericUserTests(TestCase):
# Backends
##
class AccountBackendTests(TestCase):
class AccountBackendTests(TestCase):
def setUp(self):
self.request = RequestFactory().get('/')
self.request = RequestFactory().get("/")
def test_valid(self):
acc = Account(trigramme='000')
acc.change_pwd('valid')
acc.save({'username': 'user'})
acc = Account(trigramme="000")
acc.change_pwd("valid")
acc.save({"username": "user"})
auth = AccountBackend().authenticate(
self.request, kfet_password='valid')
auth = AccountBackend().authenticate(self.request, kfet_password="valid")
self.assertEqual(auth, acc.user)
def test_invalid(self):
auth = AccountBackend().authenticate(
self.request, kfet_password='invalid')
auth = AccountBackend().authenticate(self.request, kfet_password="invalid")
self.assertIsNone(auth)
class GenericBackendTests(TestCase):
def setUp(self):
self.request = RequestFactory().get('/')
self.request = RequestFactory().get("/")
def test_valid(self):
token = GenericTeamToken.objects.create_token()
auth = GenericBackend().authenticate(
self.request, kfet_token=token.token)
auth = GenericBackend().authenticate(self.request, kfet_token=token.token)
self.assertEqual(auth, get_kfet_generic_user())
self.assertEqual(GenericTeamToken.objects.all().count(), 0)
def test_invalid(self):
auth = GenericBackend().authenticate(
self.request, kfet_token='invalid')
auth = GenericBackend().authenticate(self.request, kfet_token="invalid")
self.assertIsNone(auth)
@ -131,78 +120,74 @@ class GenericBackendTests(TestCase):
# Views
##
class GenericLoginViewTests(TestCase):
class GenericLoginViewTests(TestCase):
def setUp(self):
patcher_messages = mock.patch('gestioncof.signals.messages')
patcher_messages = mock.patch("gestioncof.signals.messages")
patcher_messages.start()
self.addCleanup(patcher_messages.stop)
user_acc = Account(trigramme='000')
user_acc.save({'username': 'user'})
user_acc = Account(trigramme="000")
user_acc.save({"username": "user"})
self.user = user_acc.user
self.user.set_password('user')
self.user.set_password("user")
self.user.save()
team_acc = Account(trigramme='100')
team_acc.save({'username': 'team'})
team_acc = Account(trigramme="100")
team_acc.save({"username": "team"})
self.team = team_acc.user
self.team.set_password('team')
self.team.set_password("team")
self.team.save()
self.team.user_permissions.add(
Permission.objects.get(
content_type__app_label='kfet', codename='is_team'),
Permission.objects.get(content_type__app_label="kfet", codename="is_team")
)
self.url = reverse('kfet.login.generic')
self.url = reverse("kfet.login.generic")
self.generic_user = get_kfet_generic_user()
def test_url(self):
self.assertEqual(self.url, '/k-fet/login/generic')
self.assertEqual(self.url, "/k-fet/login/generic")
def test_notoken_get(self):
"""
Send confirmation for user to emit POST request, instead of GET.
"""
self.client.login(username='team', password='team')
self.client.login(username="team", password="team")
r = self.client.get(self.url)
self.assertEqual(r.status_code, 200)
self.assertTemplateUsed(r, 'kfet/confirm_form.html')
self.assertTemplateUsed(r, "kfet/confirm_form.html")
def test_notoken_post(self):
"""
POST request without token in COOKIES sets a token and redirects to
logout url.
"""
self.client.login(username='team', password='team')
self.client.login(username="team", password="team")
r = self.client.post(self.url)
self.assertRedirects(
r, '/logout?next={}'.format(self.url),
fetch_redirect_response=False,
r, "/logout?next={}".format(self.url), fetch_redirect_response=False
)
def test_notoken_not_team(self):
"""
Logged in user must be a team user to initiate login as generic user.
"""
self.client.login(username='user', password='user')
self.client.login(username="user", password="user")
# With GET.
r = self.client.get(self.url)
self.assertRedirects(
r, '/login?next={}'.format(self.url),
fetch_redirect_response=False,
r, "/login?next={}".format(self.url), fetch_redirect_response=False
)
# Also with POST.
r = self.client.post(self.url)
self.assertRedirects(
r, '/login?next={}'.format(self.url),
fetch_redirect_response=False,
r, "/login?next={}".format(self.url), fetch_redirect_response=False
)
def _set_signed_cookie(self, client, key, value):
@ -216,10 +201,9 @@ class GenericLoginViewTests(TestCase):
try:
cookie = client.cookies[key]
# It also can be emptied.
self.assertEqual(cookie.value, '')
self.assertEqual(
cookie['expires'], 'Thu, 01-Jan-1970 00:00:00 GMT')
self.assertEqual(cookie['max-age'], 0)
self.assertEqual(cookie.value, "")
self.assertEqual(cookie["expires"], "Thu, 01-Jan-1970 00:00:00 GMT")
self.assertEqual(cookie["max-age"], 0)
except AssertionError:
raise AssertionError("The cookie '%s' still exists." % key)
@ -227,16 +211,16 @@ class GenericLoginViewTests(TestCase):
"""
The kfet generic user is logged in.
"""
token = GenericTeamToken.objects.create(token='valid')
token = GenericTeamToken.objects.create(token="valid")
self._set_signed_cookie(
self.client, GenericLoginView.TOKEN_COOKIE_NAME, 'valid')
self.client, GenericLoginView.TOKEN_COOKIE_NAME, "valid"
)
r = self.client.get(self.url)
self.assertRedirects(r, reverse('kfet.kpsul'))
self.assertRedirects(r, reverse("kfet.kpsul"))
self.assertEqual(r.wsgi_request.user, self.generic_user)
self._is_cookie_deleted(
self.client, GenericLoginView.TOKEN_COOKIE_NAME)
self._is_cookie_deleted(self.client, GenericLoginView.TOKEN_COOKIE_NAME)
with self.assertRaises(GenericTeamToken.DoesNotExist):
token.refresh_from_db()
@ -245,27 +229,26 @@ class GenericLoginViewTests(TestCase):
If token is invalid, delete it and try again.
"""
self._set_signed_cookie(
self.client, GenericLoginView.TOKEN_COOKIE_NAME, 'invalid')
self.client, GenericLoginView.TOKEN_COOKIE_NAME, "invalid"
)
r = self.client.get(self.url)
self.assertRedirects(r, self.url, fetch_redirect_response=False)
self.assertEqual(r.wsgi_request.user, AnonymousUser())
self._is_cookie_deleted(
self.client, GenericLoginView.TOKEN_COOKIE_NAME)
self._is_cookie_deleted(self.client, GenericLoginView.TOKEN_COOKIE_NAME)
def test_flow_ok(self):
"""
A team user is logged in as the kfet generic user.
"""
self.client.login(username='team', password='team')
next_url = '/k-fet/'
self.client.login(username="team", password="team")
next_url = "/k-fet/"
r = self.client.post(
'{}?next={}'.format(self.url, next_url), follow=True)
r = self.client.post("{}?next={}".format(self.url, next_url), follow=True)
self.assertEqual(r.wsgi_request.user, self.generic_user)
self.assertEqual(r.wsgi_request.path, '/k-fet/')
self.assertEqual(r.wsgi_request.path, "/k-fet/")
##
@ -276,10 +259,10 @@ class GenericLoginViewTests(TestCase):
# - temporary_auth context processor
##
class TemporaryAuthTests(TestCase):
class TemporaryAuthTests(TestCase):
def setUp(self):
patcher_messages = mock.patch('gestioncof.signals.messages')
patcher_messages = mock.patch("gestioncof.signals.messages")
patcher_messages.start()
self.addCleanup(patcher_messages.stop)
@ -287,22 +270,23 @@ class TemporaryAuthTests(TestCase):
self.middleware = TemporaryAuthMiddleware(mock.Mock())
user1_acc = Account(trigramme='000')
user1_acc.change_pwd('kfet_user1')
user1_acc.save({'username': 'user1'})
user1_acc = Account(trigramme="000")
user1_acc.change_pwd("kfet_user1")
user1_acc.save({"username": "user1"})
self.user1 = user1_acc.user
self.user1.set_password('user1')
self.user1.set_password("user1")
self.user1.save()
user2_acc = Account(trigramme='100')
user2_acc.change_pwd('kfet_user2')
user2_acc.save({'username': 'user2'})
user2_acc = Account(trigramme="100")
user2_acc.change_pwd("kfet_user2")
user2_acc.save({"username": "user2"})
self.user2 = user2_acc.user
self.user2.set_password('user2')
self.user2.set_password("user2")
self.user2.save()
self.perm = Permission.objects.get(
content_type__app_label='kfet', codename='is_team')
content_type__app_label="kfet", codename="is_team"
)
self.user2.user_permissions.add(self.perm)
def test_middleware_header(self):
@ -310,7 +294,7 @@ class TemporaryAuthTests(TestCase):
A user can be authenticated if ``HTTP_KFETPASSWORD`` header of a
request contains a valid kfet password.
"""
request = self.factory.get('/', HTTP_KFETPASSWORD='kfet_user2')
request = self.factory.get("/", HTTP_KFETPASSWORD="kfet_user2")
request.user = self.user1
self.middleware(request)
@ -323,7 +307,7 @@ class TemporaryAuthTests(TestCase):
A user can be authenticated if ``KFETPASSWORD`` of POST data contains
a valid kfet password.
"""
request = self.factory.post('/', {'KFETPASSWORD': 'kfet_user2'})
request = self.factory.post("/", {"KFETPASSWORD": "kfet_user2"})
request.user = self.user1
self.middleware(request)
@ -335,34 +319,33 @@ class TemporaryAuthTests(TestCase):
"""
The given password must be a password of an Account.
"""
request = self.factory.post('/', {'KFETPASSWORD': 'invalid'})
request = self.factory.post("/", {"KFETPASSWORD": "invalid"})
request.user = self.user1
self.middleware(request)
self.assertEqual(request.user, self.user1)
self.assertFalse(hasattr(request, 'real_user'))
self.assertFalse(hasattr(request, "real_user"))
def test_context_processor(self):
"""
Context variables give the real authenticated user and his permissions.
"""
self.client.login(username='user1', password='user1')
self.client.login(username="user1", password="user1")
r = self.client.get('/k-fet/accounts/', HTTP_KFETPASSWORD='kfet_user2')
r = self.client.get("/k-fet/accounts/", HTTP_KFETPASSWORD="kfet_user2")
self.assertEqual(r.context['user'], self.user1)
self.assertNotIn('kfet.is_team', r.context['perms'])
self.assertEqual(r.context["user"], self.user1)
self.assertNotIn("kfet.is_team", r.context["perms"])
def test_auth_not_persistent(self):
"""
The authentication is temporary, i.e. for one request.
"""
self.client.login(username='user1', password='user1')
self.client.login(username="user1", password="user1")
r1 = self.client.get(
'/k-fet/accounts/', HTTP_KFETPASSWORD='kfet_user2')
r1 = self.client.get("/k-fet/accounts/", HTTP_KFETPASSWORD="kfet_user2")
self.assertEqual(r1.wsgi_request.user, self.user2)
r2 = self.client.get('/k-fet/accounts/')
r2 = self.client.get("/k-fet/accounts/")
self.assertEqual(r2.wsgi_request.user, self.user1)

View file

@ -23,12 +23,9 @@ def setup_kfet_generic_user(**kwargs):
"""
generic = get_kfet_generic_user()
generic.user_permissions.add(
Permission.objects.get(
content_type__app_label='kfet',
codename='is_team',
)
Permission.objects.get(content_type__app_label="kfet", codename="is_team")
)
def hash_password(password):
return hashlib.sha256(password.encode('utf-8')).hexdigest()
return hashlib.sha256(password.encode("utf-8")).hexdigest()

View file

@ -1,17 +1,17 @@
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import Group, User
from django.contrib.auth.views import redirect_to_login
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse, reverse_lazy
from django.db.models import Prefetch
from django.http import QueryDict
from django.shortcuts import redirect, render
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.generic import View
from django.views.decorators.http import require_http_methods
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView
from .forms import GroupForm
@ -30,28 +30,33 @@ class GenericLoginView(View):
provider, which can be external. Session is unusable as it will be cleared
on logout.
"""
TOKEN_COOKIE_NAME = 'kfettoken'
@method_decorator(require_http_methods(['GET', 'POST']))
TOKEN_COOKIE_NAME = "kfettoken"
@method_decorator(require_http_methods(["GET", "POST"]))
def dispatch(self, request, *args, **kwargs):
token = request.get_signed_cookie(self.TOKEN_COOKIE_NAME, None)
if not token:
if not request.user.has_perm('kfet.is_team'):
if not request.user.has_perm("kfet.is_team"):
return redirect_to_login(request.get_full_path())
if request.method == 'POST':
if request.method == "POST":
# Step 1: set token and logout user.
return self.prepare_auth()
else:
# GET request should not change server/client states. Send a
# confirmation template to emit a POST request.
return render(request, 'kfet/confirm_form.html', {
'title': _("Ouvrir une session partagée"),
'text': _(
"Êtes-vous sûr·e de vouloir ouvrir une session "
"partagée ?"
),
})
return render(
request,
"kfet/confirm_form.html",
{
"title": _("Ouvrir une session partagée"),
"text": _(
"Êtes-vous sûr·e de vouloir ouvrir une session "
"partagée ?"
),
},
)
else:
# Step 2: validate token.
return self.validate_auth(token)
@ -62,20 +67,19 @@ class GenericLoginView(View):
# Prepare callback of logout.
here_url = reverse(login_generic)
if 'next' in self.request.GET:
if "next" in self.request.GET:
# Keep given next page.
here_qd = QueryDict(mutable=True)
here_qd['next'] = self.request.GET['next']
here_url += '?{}'.format(here_qd.urlencode())
here_qd["next"] = self.request.GET["next"]
here_url += "?{}".format(here_qd.urlencode())
logout_url = reverse('cof-logout')
logout_url = reverse("cof-logout")
logout_qd = QueryDict(mutable=True)
logout_qd['next'] = here_url
logout_url += '?{}'.format(logout_qd.urlencode(safe='/'))
logout_qd["next"] = here_url
logout_url += "?{}".format(logout_qd.urlencode(safe="/"))
resp = redirect(logout_url)
resp.set_signed_cookie(
self.TOKEN_COOKIE_NAME, token.token, httponly=True)
resp.set_signed_cookie(self.TOKEN_COOKIE_NAME, token.token, httponly=True)
return resp
def validate_auth(self, token):
@ -85,9 +89,9 @@ class GenericLoginView(View):
if user:
# Log in generic user.
login(self.request, user)
messages.success(self.request, _(
"K-Fêt — Ouverture d'une session partagée."
))
messages.success(
self.request, _("K-Fêt — Ouverture d'une session partagée.")
)
resp = redirect(self.get_next_url())
else:
# Try again.
@ -98,39 +102,34 @@ class GenericLoginView(View):
return resp
def get_next_url(self):
return self.request.GET.get('next', reverse('kfet.kpsul'))
return self.request.GET.get("next", reverse("kfet.kpsul"))
login_generic = GenericLoginView.as_view()
@permission_required('kfet.manage_perms')
@permission_required("kfet.manage_perms")
def account_group(request):
user_pre = Prefetch(
'user_set',
queryset=User.objects.select_related('profile__account_kfet'),
"user_set", queryset=User.objects.select_related("profile__account_kfet")
)
groups = (
Group.objects
.filter(name__icontains='K-Fêt')
.prefetch_related('permissions', user_pre)
groups = Group.objects.filter(name__icontains="K-Fêt").prefetch_related(
"permissions", user_pre
)
return render(request, 'kfet/account_group.html', {
'groups': groups,
})
return render(request, "kfet/account_group.html", {"groups": groups})
class AccountGroupCreate(SuccessMessageMixin, CreateView):
model = Group
template_name = 'kfet/account_group_form.html'
template_name = "kfet/account_group_form.html"
form_class = GroupForm
success_message = 'Nouveau groupe : %(name)s'
success_url = reverse_lazy('kfet.account.group')
success_message = "Nouveau groupe : %(name)s"
success_url = reverse_lazy("kfet.account.group")
class AccountGroupUpdate(SuccessMessageMixin, UpdateView):
queryset = Group.objects.filter(name__icontains='K-Fêt')
template_name = 'kfet/account_group_form.html'
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')
success_message = "Groupe modifié : %(name)s"
success_url = reverse_lazy("kfet.account.group")

View file

@ -1,8 +1,8 @@
from ldap3 import Connection
from django.shortcuts import render
from django.http import Http404
from django.db.models import Q
from django.conf import settings
from django.db.models import Q
from django.http import Http404
from django.shortcuts import render
from ldap3 import Connection
from gestioncof.models import User
from kfet.decorators import teamkfet_required
@ -25,81 +25,80 @@ def account_create(request):
raise Http404
q = request.GET.get("q")
if (len(q) == 0):
if len(q) == 0:
return render(request, "kfet/account_create_autocomplete.html")
data = {'q': q}
data = {"q": q}
queries = {}
search_words = q.split()
# Fetching data from User, CofProfile and Account tables
queries['kfet'] = Account.objects
queries['users_cof'] = User.objects.filter(profile__is_cof=True)
queries['users_notcof'] = User.objects.filter(profile__is_cof=False)
queries["kfet"] = Account.objects
queries["users_cof"] = User.objects.filter(profile__is_cof=True)
queries["users_notcof"] = User.objects.filter(profile__is_cof=False)
for word in search_words:
queries['kfet'] = queries['kfet'].filter(
queries["kfet"] = queries["kfet"].filter(
Q(cofprofile__user__username__icontains=word)
| Q(cofprofile__user__first_name__icontains=word)
| Q(cofprofile__user__last_name__icontains=word)
)
queries['users_cof'] = queries['users_cof'].filter(
queries["users_cof"] = queries["users_cof"].filter(
Q(username__icontains=word)
| Q(first_name__icontains=word)
| Q(last_name__icontains=word)
)
queries['users_notcof'] = queries['users_notcof'].filter(
queries["users_notcof"] = queries["users_notcof"].filter(
Q(username__icontains=word)
| Q(first_name__icontains=word)
| Q(last_name__icontains=word)
)
# Clearing redundancies
queries['kfet'] = queries['kfet'].distinct()
queries["kfet"] = queries["kfet"].distinct()
usernames = set(
queries['kfet'].values_list('cofprofile__user__username', flat=True))
queries['kfet'] = [
(account, account.cofprofile.user)
for account in queries['kfet']
queries["kfet"].values_list("cofprofile__user__username", flat=True)
)
queries["kfet"] = [
(account, account.cofprofile.user) for account in queries["kfet"]
]
queries['users_cof'] = \
queries['users_cof'].exclude(username__in=usernames).distinct()
queries['users_notcof'] = \
queries['users_notcof'].exclude(username__in=usernames).distinct()
usernames |= set(
queries['users_cof'].values_list('username', flat=True))
usernames |= set(
queries['users_notcof'].values_list('username', flat=True))
queries["users_cof"] = (
queries["users_cof"].exclude(username__in=usernames).distinct()
)
queries["users_notcof"] = (
queries["users_notcof"].exclude(username__in=usernames).distinct()
)
usernames |= set(queries["users_cof"].values_list("username", flat=True))
usernames |= set(queries["users_notcof"].values_list("username", flat=True))
# Fetching data from the SPI
if getattr(settings, 'LDAP_SERVER_URL', None):
if getattr(settings, "LDAP_SERVER_URL", None):
# Fetching
ldap_query = '(&{:s})'.format(''.join(
'(|(cn=*{bit:s}*)(uid=*{bit:s}*))'.format(bit=word)
for word in search_words if word.isalnum()
))
ldap_query = "(&{:s})".format(
"".join(
"(|(cn=*{bit:s}*)(uid=*{bit:s}*))".format(bit=word)
for word in search_words
if word.isalnum()
)
)
if ldap_query != "(&)":
# If none of the bits were legal, we do not perform the query
entries = None
with Connection(settings.LDAP_SERVER_URL) as conn:
conn.search(
'dc=spi,dc=ens,dc=fr', ldap_query,
attributes=['uid', 'cn']
)
conn.search("dc=spi,dc=ens,dc=fr", ldap_query, attributes=["uid", "cn"])
entries = conn.entries
# Clearing redundancies
queries['clippers'] = [
queries["clippers"] = [
Clipper(entry.uid.value, entry.cn.value)
for entry in entries
if entry.uid.value
and entry.uid.value not in usernames
if entry.uid.value and entry.uid.value not in usernames
]
# Resulting data
data.update(queries)
data['options'] = sum([len(query) for query in queries])
data["options"] = sum([len(query) for query in queries])
return render(request, "kfet/account_create_autocomplete.html", data)
@ -111,17 +110,19 @@ def account_search(request):
q = request.GET.get("q")
words = q.split()
data = {'q': q}
data = {"q": q}
for word in words:
query = Account.objects.filter(
Q(cofprofile__user__username__icontains=word) |
Q(cofprofile__user__first_name__icontains=word) |
Q(cofprofile__user__last_name__icontains=word)
).distinct()
Q(cofprofile__user__username__icontains=word)
| Q(cofprofile__user__first_name__icontains=word)
| Q(cofprofile__user__last_name__icontains=word)
).distinct()
query = [(account.trigramme, account.cofprofile.user.get_full_name())
for account in query]
query = [
(account.trigramme, account.cofprofile.user.get_full_name())
for account in query
]
data['accounts'] = query
return render(request, 'kfet/account_search_autocomplete.html', data)
data["accounts"] = query
return render(request, "kfet/account_search_autocomplete.html", data)

View file

@ -1 +1 @@
default_app_config = 'kfet.cms.apps.KFetCMSAppConfig'
default_app_config = "kfet.cms.apps.KFetCMSAppConfig"

View file

@ -2,9 +2,9 @@ from django.apps import AppConfig
class KFetCMSAppConfig(AppConfig):
name = 'kfet.cms'
label = 'kfetcms'
verbose_name = 'CMS K-Fêt'
name = "kfet.cms"
label = "kfetcms"
verbose_name = "CMS K-Fêt"
def ready(self):
from . import hooks

View file

@ -3,18 +3,14 @@ from kfet.models import Article
def get_articles(request=None):
articles = (
Article.objects
.filter(is_sold=True, hidden=False)
.select_related('category')
.order_by('category__name', 'name')
Article.objects.filter(is_sold=True, hidden=False)
.select_related("category")
.order_by("category__name", "name")
)
pressions, others = [], []
for article in articles:
if article.category.name == 'Pression':
if article.category.name == "Pression":
pressions.append(article)
else:
others.append(article)
return {
'pressions': pressions,
'articles': others,
}
return {"pressions": pressions, "articles": others}

View file

@ -1,12 +1,10 @@
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.html import format_html
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_css')
@hooks.register("insert_editor_css")
def editor_css():
return format_html(
'<link rel="stylesheet" href="{}">',
static('kfetcms/css/editor.css'),
'<link rel="stylesheet" href="{}">', static("kfetcms/css/editor.css")
)

View file

@ -1,7 +1,6 @@
from django.contrib.auth.models import Group
from django.core.management import call_command
from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page, Site
@ -9,7 +8,7 @@ class Command(BaseCommand):
help = "Importe des données pour Wagtail"
def add_arguments(self, parser):
parser.add_argument('--file', default='kfet_wagtail_17_05')
parser.add_argument("--file", default="kfet_wagtail_17_05")
def handle(self, *args, **options):
@ -18,12 +17,10 @@ class Command(BaseCommand):
# Nettoyage des données initiales posées par Wagtail dans la migration
# wagtailcore/0002
Group.objects.filter(name__in=('Moderators', 'Editors')).delete()
Group.objects.filter(name__in=("Moderators", "Editors")).delete()
try:
homepage = Page.objects.get(
title="Welcome to your new Wagtail site!"
)
homepage = Page.objects.get(title="Welcome to your new Wagtail site!")
homepage.delete()
Site.objects.filter(root_page=homepage).delete()
except Page.DoesNotExist:
@ -32,4 +29,4 @@ class Command(BaseCommand):
# Import des données
# Par défaut, il s'agit d'une copie du site K-Fêt (17-05)
call_command('loaddata', options['file'])
call_command("loaddata", options["file"])

View file

@ -1,49 +1,214 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import wagtail.wagtailsnippets.blocks
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import django.db.models.deletion
import wagtail.wagtailsnippets.blocks
from django.db import migrations, models
import kfet.cms.models
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0033_remove_golive_expiry_help_text'),
('wagtailimages', '0019_delete_filter'),
("wagtailcore", "0033_remove_golive_expiry_help_text"),
("wagtailimages", "0019_delete_filter"),
]
operations = [
migrations.CreateModel(
name='KFetPage',
name="KFetPage",
fields=[
('page_ptr', models.OneToOneField(serialize=False, primary_key=True, parent_link=True, auto_created=True, to='wagtailcore.Page', on_delete=models.CASCADE)),
('no_header', models.BooleanField(verbose_name='Sans en-tête', help_text="Coché, l'en-tête (avec le titre) de la page n'est pas affiché.", default=False)),
('content', wagtail.wagtailcore.fields.StreamField((('rich', wagtail.wagtailcore.blocks.RichTextBlock(label='Éditeur')), ('carte', kfet.cms.models.MenuBlock()), ('group_team', wagtail.wagtailcore.blocks.StructBlock((('show_only', wagtail.wagtailcore.blocks.IntegerBlock(help_text='Nombre initial de membres affichés. Laisser vide pour tou-te-s les afficher.', required=False, label='Montrer seulement')), ('members', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailsnippets.blocks.SnippetChooserBlock(kfet.cms.models.MemberTeam), classname='team-group', label='K-Fêt-eux-ses'))))), ('group', wagtail.wagtailcore.blocks.StreamBlock((('rich', wagtail.wagtailcore.blocks.RichTextBlock(label='Éditeur')), ('carte', kfet.cms.models.MenuBlock()), ('group_team', wagtail.wagtailcore.blocks.StructBlock((('show_only', wagtail.wagtailcore.blocks.IntegerBlock(help_text='Nombre initial de membres affichés. Laisser vide pour tou-te-s les afficher.', required=False, label='Montrer seulement')), ('members', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailsnippets.blocks.SnippetChooserBlock(kfet.cms.models.MemberTeam), classname='team-group', label='K-Fêt-eux-ses')))))), label='Contenu groupé'))), verbose_name='Contenu')),
('layout', models.CharField(max_length=255, choices=[('kfet/base_col_1.html', 'Une colonne : centrée sur la page'), ('kfet/base_col_2.html', 'Deux colonnes : fixe à gauche, contenu à droite'), ('kfet/base_col_mult.html', 'Contenu scindé sur plusieurs colonnes')], help_text='Comment cette page devrait être affichée ?', verbose_name='Template', default='kfet/base_col_mult.html')),
('main_size', models.CharField(max_length=255, blank=True, verbose_name='Taille de la colonne de contenu')),
('col_count', models.CharField(max_length=255, blank=True, verbose_name='Nombre de colonnes', help_text="S'applique au page dont le contenu est scindé sur plusieurs colonnes")),
(
"page_ptr",
models.OneToOneField(
serialize=False,
primary_key=True,
parent_link=True,
auto_created=True,
to="wagtailcore.Page",
on_delete=models.CASCADE,
),
),
(
"no_header",
models.BooleanField(
verbose_name="Sans en-tête",
help_text="Coché, l'en-tête (avec le titre) de la page n'est pas affiché.",
default=False,
),
),
(
"content",
wagtail.wagtailcore.fields.StreamField(
(
(
"rich",
wagtail.wagtailcore.blocks.RichTextBlock(
label="Éditeur"
),
),
("carte", kfet.cms.models.MenuBlock()),
(
"group_team",
wagtail.wagtailcore.blocks.StructBlock(
(
(
"show_only",
wagtail.wagtailcore.blocks.IntegerBlock(
help_text="Nombre initial de membres affichés. Laisser vide pour tou-te-s les afficher.",
required=False,
label="Montrer seulement",
),
),
(
"members",
wagtail.wagtailcore.blocks.ListBlock(
wagtail.wagtailsnippets.blocks.SnippetChooserBlock(
kfet.cms.models.MemberTeam
),
classname="team-group",
label="K-Fêt-eux-ses",
),
),
)
),
),
(
"group",
wagtail.wagtailcore.blocks.StreamBlock(
(
(
"rich",
wagtail.wagtailcore.blocks.RichTextBlock(
label="Éditeur"
),
),
("carte", kfet.cms.models.MenuBlock()),
(
"group_team",
wagtail.wagtailcore.blocks.StructBlock(
(
(
"show_only",
wagtail.wagtailcore.blocks.IntegerBlock(
help_text="Nombre initial de membres affichés. Laisser vide pour tou-te-s les afficher.",
required=False,
label="Montrer seulement",
),
),
(
"members",
wagtail.wagtailcore.blocks.ListBlock(
wagtail.wagtailsnippets.blocks.SnippetChooserBlock(
kfet.cms.models.MemberTeam
),
classname="team-group",
label="K-Fêt-eux-ses",
),
),
)
),
),
),
label="Contenu groupé",
),
),
),
verbose_name="Contenu",
),
),
(
"layout",
models.CharField(
max_length=255,
choices=[
(
"kfet/base_col_1.html",
"Une colonne : centrée sur la page",
),
(
"kfet/base_col_2.html",
"Deux colonnes : fixe à gauche, contenu à droite",
),
(
"kfet/base_col_mult.html",
"Contenu scindé sur plusieurs colonnes",
),
],
help_text="Comment cette page devrait être affichée ?",
verbose_name="Template",
default="kfet/base_col_mult.html",
),
),
(
"main_size",
models.CharField(
max_length=255,
blank=True,
verbose_name="Taille de la colonne de contenu",
),
),
(
"col_count",
models.CharField(
max_length=255,
blank=True,
verbose_name="Nombre de colonnes",
help_text="S'applique au page dont le contenu est scindé sur plusieurs colonnes",
),
),
],
options={
'verbose_name': 'page K-Fêt',
'verbose_name_plural': 'pages K-Fêt',
"verbose_name": "page K-Fêt",
"verbose_name_plural": "pages K-Fêt",
},
bases=('wagtailcore.page',),
bases=("wagtailcore.page",),
),
migrations.CreateModel(
name='MemberTeam',
name="MemberTeam",
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('first_name', models.CharField(blank=True, max_length=255, verbose_name='Prénom', default='')),
('last_name', models.CharField(blank=True, max_length=255, verbose_name='Nom', default='')),
('nick_name', models.CharField(verbose_name='Alias', blank=True, default='', max_length=255)),
('photo', models.ForeignKey(null=True, related_name='+', on_delete=django.db.models.deletion.SET_NULL, verbose_name='Photo', blank=True, to='wagtailimages.Image')),
(
"id",
models.AutoField(
verbose_name="ID",
auto_created=True,
serialize=False,
primary_key=True,
),
),
(
"first_name",
models.CharField(
blank=True, max_length=255, verbose_name="Prénom", default=""
),
),
(
"last_name",
models.CharField(
blank=True, max_length=255, verbose_name="Nom", default=""
),
),
(
"nick_name",
models.CharField(
verbose_name="Alias", blank=True, default="", max_length=255
),
),
(
"photo",
models.ForeignKey(
null=True,
related_name="+",
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="Photo",
blank=True,
to="wagtailimages.Image",
),
),
],
options={
'verbose_name': 'K-Fêt-eux-se',
},
options={"verbose_name": "K-Fêt-eux-se"},
),
]

View file

@ -6,14 +6,17 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfetcms', '0001_initial'),
]
dependencies = [("kfetcms", "0001_initial")]
operations = [
migrations.AlterField(
model_name='kfetpage',
name='col_count',
field=models.CharField(blank=True, max_length=255, verbose_name='Nombre de colonnes', help_text="S'applique au page dont le contenu est scindé sur plusieurs colonnes."),
),
model_name="kfetpage",
name="col_count",
field=models.CharField(
blank=True,
max_length=255,
verbose_name="Nombre de colonnes",
help_text="S'applique au page dont le contenu est scindé sur plusieurs colonnes.",
),
)
]

View file

@ -1,8 +1,10 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.edit_handlers import (
FieldPanel, FieldRowPanel, MultiFieldPanel, StreamFieldPanel
FieldPanel,
FieldRowPanel,
MultiFieldPanel,
StreamFieldPanel,
)
from wagtail.wagtailcore import blocks
from wagtail.wagtailcore.fields import StreamField
@ -17,47 +19,45 @@ from kfet.cms.context_processors import get_articles
@register_snippet
class MemberTeam(models.Model):
first_name = models.CharField(
verbose_name=_('Prénom'),
blank=True, default='', max_length=255,
verbose_name=_("Prénom"), blank=True, default="", max_length=255
)
last_name = models.CharField(
verbose_name=_('Nom'),
blank=True, default='', max_length=255,
verbose_name=_("Nom"), blank=True, default="", max_length=255
)
nick_name = models.CharField(
verbose_name=_('Alias'),
blank=True, default='', max_length=255,
verbose_name=_("Alias"), blank=True, default="", max_length=255
)
photo = models.ForeignKey(
'wagtailimages.Image',
verbose_name=_('Photo'),
"wagtailimages.Image",
verbose_name=_("Photo"),
on_delete=models.SET_NULL,
null=True, blank=True,
related_name='+',
null=True,
blank=True,
related_name="+",
)
class Meta:
verbose_name = _('K-Fêt-eux-se')
verbose_name = _("K-Fêt-eux-se")
panels = [
FieldPanel('first_name'),
FieldPanel('last_name'),
FieldPanel('nick_name'),
ImageChooserPanel('photo'),
FieldPanel("first_name"),
FieldPanel("last_name"),
FieldPanel("nick_name"),
ImageChooserPanel("photo"),
]
def __str__(self):
return self.get_full_name()
def get_full_name(self):
return '{} {}'.format(self.first_name, self.last_name).strip()
return "{} {}".format(self.first_name, self.last_name).strip()
class MenuBlock(blocks.StaticBlock):
class Meta:
icon = 'list-ul'
label = _('Carte')
template = 'kfetcms/block_menu.html'
icon = "list-ul"
label = _("Carte")
template = "kfetcms/block_menu.html"
def get_context(self, *args, **kwargs):
context = super().get_context(*args, **kwargs)
@ -67,71 +67,68 @@ class MenuBlock(blocks.StaticBlock):
class GroupTeamBlock(blocks.StructBlock):
show_only = blocks.IntegerBlock(
label=_('Montrer seulement'),
label=_("Montrer seulement"),
required=False,
help_text=_(
'Nombre initial de membres affichés. Laisser vide pour tou-te-s '
'les afficher.'
"Nombre initial de membres affichés. Laisser vide pour tou-te-s "
"les afficher."
),
)
members = blocks.ListBlock(
SnippetChooserBlock(MemberTeam),
label=_('K-Fêt-eux-ses'),
classname='team-group',
label=_("K-Fêt-eux-ses"),
classname="team-group",
)
class Meta:
icon = 'group'
label = _('Groupe de K-Fêt-eux-ses')
template = 'kfetcms/block_teamgroup.html'
icon = "group"
label = _("Groupe de K-Fêt-eux-ses")
template = "kfetcms/block_teamgroup.html"
class ChoicesStreamBlock(blocks.StreamBlock):
rich = blocks.RichTextBlock(label=_('Éditeur'))
rich = blocks.RichTextBlock(label=_("Éditeur"))
carte = MenuBlock()
group_team = GroupTeamBlock()
class KFetStreamBlock(ChoicesStreamBlock):
group = ChoicesStreamBlock(label=_('Contenu groupé'))
group = ChoicesStreamBlock(label=_("Contenu groupé"))
class KFetPage(Page):
content = StreamField(KFetStreamBlock, verbose_name=_('Contenu'))
content = StreamField(KFetStreamBlock, verbose_name=_("Contenu"))
# Layout fields
TEMPLATE_COL_1 = 'kfet/base_col_1.html'
TEMPLATE_COL_2 = 'kfet/base_col_2.html'
TEMPLATE_COL_MULT = 'kfet/base_col_mult.html'
TEMPLATE_COL_1 = "kfet/base_col_1.html"
TEMPLATE_COL_2 = "kfet/base_col_2.html"
TEMPLATE_COL_MULT = "kfet/base_col_mult.html"
no_header = models.BooleanField(
verbose_name=_('Sans en-tête'),
verbose_name=_("Sans en-tête"),
default=False,
help_text=_(
"Coché, l'en-tête (avec le titre) de la page n'est pas affiché."
),
help_text=_("Coché, l'en-tête (avec le titre) de la page n'est pas affiché."),
)
layout = models.CharField(
verbose_name=_('Template'),
verbose_name=_("Template"),
choices=[
(TEMPLATE_COL_1, _('Une colonne : centrée sur la page')),
(TEMPLATE_COL_2, _('Deux colonnes : fixe à gauche, contenu à droite')),
(TEMPLATE_COL_MULT, _('Contenu scindé sur plusieurs colonnes')),
(TEMPLATE_COL_1, _("Une colonne : centrée sur la page")),
(TEMPLATE_COL_2, _("Deux colonnes : fixe à gauche, contenu à droite")),
(TEMPLATE_COL_MULT, _("Contenu scindé sur plusieurs colonnes")),
],
default=TEMPLATE_COL_MULT, max_length=255,
help_text=_(
"Comment cette page devrait être affichée ?"
),
default=TEMPLATE_COL_MULT,
max_length=255,
help_text=_("Comment cette page devrait être affichée ?"),
)
main_size = models.CharField(
verbose_name=_('Taille de la colonne de contenu'),
blank=True, max_length=255,
verbose_name=_("Taille de la colonne de contenu"), blank=True, max_length=255
)
col_count = models.CharField(
verbose_name=_('Nombre de colonnes'),
blank=True, max_length=255,
verbose_name=_("Nombre de colonnes"),
blank=True,
max_length=255,
help_text=_(
"S'applique au page dont le contenu est scindé sur plusieurs colonnes."
),
@ -139,34 +136,29 @@ class KFetPage(Page):
# Panels
content_panels = Page.content_panels + [
StreamFieldPanel('content'),
]
content_panels = Page.content_panels + [StreamFieldPanel("content")]
layout_panel = [
FieldPanel('no_header'),
FieldPanel('layout'),
FieldRowPanel([
FieldPanel('main_size'),
FieldPanel('col_count'),
]),
FieldPanel("no_header"),
FieldPanel("layout"),
FieldRowPanel([FieldPanel("main_size"), FieldPanel("col_count")]),
]
settings_panels = [
MultiFieldPanel(layout_panel, _('Affichage'))
MultiFieldPanel(layout_panel, _("Affichage"))
] + Page.settings_panels
# Base template
template = "kfetcms/base.html"
class Meta:
verbose_name = _('page K-Fêt')
verbose_name_plural = _('pages K-Fêt')
verbose_name = _("page K-Fêt")
verbose_name_plural = _("pages K-Fêt")
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
page = context['page']
page = context["page"]
if not page.seo_title:
page.seo_title = page.title

View file

@ -1,8 +1,7 @@
import djconfig
from django.core.exceptions import ValidationError
from django.db import models
import djconfig
class KFetConfig(object):
"""kfet app configuration.
@ -10,7 +9,8 @@ class KFetConfig(object):
Enhance isolation with backend used to store config.
"""
prefix = 'kfet_'
prefix = "kfet_"
def __init__(self):
# Set this to False again to reload the config, e.g for testing
@ -28,11 +28,11 @@ class KFetConfig(object):
def __getattr__(self, key):
self._check_init()
if key == 'subvention_cof':
if key == "subvention_cof":
# Allows accessing to the reduction as a subvention
# Other reason: backward compatibility
reduction_mult = 1 - self.reduction_cof/100
return (1/reduction_mult - 1) * 100
reduction_mult = 1 - self.reduction_cof / 100
return (1 / reduction_mult - 1) * 100
return getattr(djconfig.config, self._get_dj_key(key))
def list(self):
@ -44,12 +44,15 @@ class KFetConfig(object):
"""
# prevent circular imports
from kfet.forms import KFetConfigForm
self._check_init()
return [(field.label, getattr(djconfig.config, name), )
for name, field in KFetConfigForm.base_fields.items()]
return [
(field.label, getattr(djconfig.config, name))
for name, field in KFetConfigForm.base_fields.items()
]
def _get_dj_key(self, key):
return '{}{}'.format(self.prefix, key)
return "{}{}".format(self.prefix, key)
def set(self, **kwargs):
"""Update configuration value(s).
@ -78,8 +81,9 @@ class KFetConfig(object):
cfg_form.save()
else:
raise ValidationError(
'Invalid values in kfet_config.set: %(fields)s',
params={'fields': list(cfg_form.errors)})
"Invalid values in kfet_config.set: %(fields)s",
params={"fields": list(cfg_form.errors)},
)
kfet_config = KFetConfig()

View file

@ -2,5 +2,5 @@ from .utils import DjangoJsonWebsocketConsumer, PermConsumerMixin
class KPsul(PermConsumerMixin, DjangoJsonWebsocketConsumer):
groups = ['kfet.kpsul']
perms_connect = ['kfet.is_team']
groups = ["kfet.kpsul"]
perms_connect = ["kfet.is_team"]

View file

@ -2,4 +2,4 @@ from kfet.config import kfet_config
def config(request):
return {'kfet_config': kfet_config}
return {"kfet_config": kfet_config}

View file

@ -2,6 +2,7 @@ from django.contrib.auth.decorators import user_passes_test
def kfet_is_team(user):
return user.has_perm('kfet.is_team')
return user.has_perm("kfet.is_team")
teamkfet_required = user_passes_test(kfet_is_team)

View file

@ -2,79 +2,87 @@ from datetime import timedelta
from decimal import Decimal
from django import forms
from django.core.exceptions import ValidationError
from django.core import validators
from django.contrib.auth.models import User
from django.core import validators
from django.core.exceptions import ValidationError
from django.forms import modelformset_factory
from django.utils import timezone
from djconfig.forms import ConfigForm
from kfet.models import (
Account, Checkout, Article, OperationGroup, Operation,
CheckoutStatement, ArticleCategory, AccountNegative, Transfer,
TransferGroup, Supplier)
from gestioncof.models import CofProfile
from kfet.models import (
Account,
AccountNegative,
Article,
ArticleCategory,
Checkout,
CheckoutStatement,
Operation,
OperationGroup,
Supplier,
Transfer,
TransferGroup,
)
from .auth.forms import UserGroupForm # noqa
# -----
# Widgets
# -----
class DateTimeWidget(forms.DateTimeInput):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.attrs['format'] = '%Y-%m-%d %H:%M'
self.attrs["format"] = "%Y-%m-%d %H:%M"
class Media:
css = {
'all': ('kfet/css/bootstrap-datetimepicker.min.css',)
}
js = ('kfet/js/bootstrap-datetimepicker.min.js',)
css = {"all": ("kfet/css/bootstrap-datetimepicker.min.css",)}
js = ("kfet/js/bootstrap-datetimepicker.min.js",)
# -----
# Account forms
# -----
class AccountForm(forms.ModelForm):
# Surcharge pour passer data à Account.save()
def save(self, data = {}, *args, **kwargs):
obj = super().save(commit = False, *args, **kwargs)
obj.save(data = data)
def save(self, data={}, *args, **kwargs):
obj = super().save(commit=False, *args, **kwargs)
obj.save(data=data)
return obj
class Meta:
model = Account
fields = ['trigramme', 'promo', 'nickname', 'is_frozen']
widgets = {
'trigramme': forms.TextInput(attrs={'autocomplete': 'off'}),
}
model = Account
fields = ["trigramme", "promo", "nickname", "is_frozen"]
widgets = {"trigramme": forms.TextInput(attrs={"autocomplete": "off"})}
class AccountBalanceForm(forms.ModelForm):
class Meta:
model = Account
fields = ['balance']
fields = ["balance"]
class AccountTriForm(AccountForm):
def clean_trigramme(self):
trigramme = self.cleaned_data['trigramme']
trigramme = self.cleaned_data["trigramme"]
return trigramme.upper()
class Meta(AccountForm.Meta):
fields = ['trigramme']
fields = ["trigramme"]
class AccountNoTriForm(AccountForm):
class Meta(AccountForm.Meta):
exclude = ['trigramme']
exclude = ["trigramme"]
class AccountRestrictForm(AccountForm):
class Meta(AccountForm.Meta):
fields = ['is_frozen']
fields = ["is_frozen"]
class AccountPwdForm(forms.Form):
@ -85,14 +93,12 @@ class AccountPwdForm(forms.Form):
widget=forms.PasswordInput,
)
pwd2 = forms.CharField(
label="Confirmer le mot de passe",
required=False,
widget=forms.PasswordInput,
label="Confirmer le mot de passe", required=False, widget=forms.PasswordInput
)
def clean(self):
pwd1 = self.cleaned_data.get('pwd1', '')
pwd2 = self.cleaned_data.get('pwd2', '')
pwd1 = self.cleaned_data.get("pwd1", "")
pwd2 = self.cleaned_data.get("pwd2", "")
if len(pwd1) < 8:
raise ValidationError("Mot de passe trop court")
if pwd1 != pwd2:
@ -102,63 +108,66 @@ class AccountPwdForm(forms.Form):
class CofForm(forms.ModelForm):
def clean_is_cof(self):
instance = getattr(self, 'instance', None)
instance = getattr(self, "instance", None)
if instance and instance.pk:
return instance.is_cof
else:
return False
class Meta:
model = CofProfile
fields = ['login_clipper', 'is_cof', 'departement']
model = CofProfile
fields = ["login_clipper", "is_cof", "departement"]
class CofRestrictForm(CofForm):
class Meta(CofForm.Meta):
fields = ['departement']
fields = ["departement"]
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email']
help_texts = {
'username': ''
}
fields = ["username", "first_name", "last_name", "email"]
help_texts = {"username": ""}
class UserRestrictForm(UserForm):
class Meta(UserForm.Meta):
fields = ['first_name', 'last_name']
fields = ["first_name", "last_name"]
class UserRestrictTeamForm(UserForm):
class Meta(UserForm.Meta):
fields = ['first_name', 'last_name', 'email']
fields = ["first_name", "last_name", "email"]
class AccountNegativeForm(forms.ModelForm):
class Meta:
model = AccountNegative
fields = ['authz_overdraft_amount', 'authz_overdraft_until',
'balance_offset', 'comment']
widgets = {
'authz_overdraft_until': DateTimeWidget(),
}
model = AccountNegative
fields = [
"authz_overdraft_amount",
"authz_overdraft_until",
"balance_offset",
"comment",
]
widgets = {"authz_overdraft_until": DateTimeWidget()}
# -----
# Checkout forms
# -----
class CheckoutForm(forms.ModelForm):
class Meta:
model = Checkout
fields = ['name', 'valid_from', 'valid_to', 'balance', 'is_protected']
widgets = {
'valid_from': DateTimeWidget(),
'valid_to' : DateTimeWidget(),
}
model = Checkout
fields = ["name", "valid_from", "valid_to", "balance", "is_protected"]
widgets = {"valid_from": DateTimeWidget(), "valid_to": DateTimeWidget()}
class CheckoutRestrictForm(CheckoutForm):
class Meta(CheckoutForm.Meta):
fields = ['name', 'valid_from', 'valid_to']
fields = ["name", "valid_from", "valid_to"]
class CheckoutStatementCreateForm(forms.ModelForm):
@ -180,173 +189,206 @@ class CheckoutStatementCreateForm(forms.ModelForm):
class Meta:
model = CheckoutStatement
exclude = ['by', 'at', 'checkout', 'amount_error', 'amount_taken',
'balance_old', 'balance_new']
exclude = [
"by",
"at",
"checkout",
"amount_error",
"amount_taken",
"balance_old",
"balance_new",
]
def clean(self):
not_count = self.cleaned_data['not_count']
not_count = self.cleaned_data["not_count"]
if not not_count and (
self.cleaned_data['balance_001'] is None
or self.cleaned_data['balance_002'] is None
or self.cleaned_data['balance_005'] is None
or self.cleaned_data['balance_01'] is None
or self.cleaned_data['balance_02'] is None
or self.cleaned_data['balance_05'] is None
or self.cleaned_data['balance_1'] is None
or self.cleaned_data['balance_2'] is None
or self.cleaned_data['balance_5'] is None
or self.cleaned_data['balance_10'] is None
or self.cleaned_data['balance_20'] is None
or self.cleaned_data['balance_50'] is None
or self.cleaned_data['balance_100'] is None
or self.cleaned_data['balance_200'] is None
or self.cleaned_data['balance_500'] is None):
raise ValidationError("Y'a un problème. Si tu comptes la caisse, mets au moins des 0 stp (et t'as pas idée de comment c'est long de vérifier que t'as mis des valeurs de partout...)")
self.cleaned_data["balance_001"] is None
or self.cleaned_data["balance_002"] is None
or self.cleaned_data["balance_005"] is None
or self.cleaned_data["balance_01"] is None
or self.cleaned_data["balance_02"] is None
or self.cleaned_data["balance_05"] is None
or self.cleaned_data["balance_1"] is None
or self.cleaned_data["balance_2"] is None
or self.cleaned_data["balance_5"] is None
or self.cleaned_data["balance_10"] is None
or self.cleaned_data["balance_20"] is None
or self.cleaned_data["balance_50"] is None
or self.cleaned_data["balance_100"] is None
or self.cleaned_data["balance_200"] is None
or self.cleaned_data["balance_500"] is None
):
raise ValidationError(
"Y'a un problème. Si tu comptes la caisse, mets au moins des 0 stp (et t'as pas idée de comment c'est long de vérifier que t'as mis des valeurs de partout...)"
)
super().clean()
class CheckoutStatementUpdateForm(forms.ModelForm):
class Meta:
model = CheckoutStatement
exclude = ['by', 'at', 'checkout', 'amount_error', 'amount_taken']
exclude = ["by", "at", "checkout", "amount_error", "amount_taken"]
# -----
# Category
# -----
class CategoryForm(forms.ModelForm):
class Meta:
model = ArticleCategory
fields = ['name', 'has_addcost']
fields = ["name", "has_addcost"]
# -----
# Article forms
# -----
class ArticleForm(forms.ModelForm):
category_new = forms.CharField(
label="Créer une catégorie",
max_length=45,
required = False)
label="Créer une catégorie", max_length=45, required=False
)
category = forms.ModelChoiceField(
label="Catégorie",
queryset = ArticleCategory.objects.all(),
required = False)
label="Catégorie", queryset=ArticleCategory.objects.all(), required=False
)
suppliers = forms.ModelMultipleChoiceField(
label="Fournisseurs",
queryset = Supplier.objects.all(),
required = False)
label="Fournisseurs", queryset=Supplier.objects.all(), required=False
)
supplier_new = forms.CharField(
label="Créer un fournisseur",
max_length = 45,
required = False)
label="Créer un fournisseur", max_length=45, required=False
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
self.initial['suppliers'] = self.instance.suppliers.values_list('pk', flat=True)
self.initial["suppliers"] = self.instance.suppliers.values_list(
"pk", flat=True
)
def clean(self):
category = self.cleaned_data.get('category')
category_new = self.cleaned_data.get('category_new')
category = self.cleaned_data.get("category")
category_new = self.cleaned_data.get("category_new")
if not category and not category_new:
raise ValidationError('Sélectionnez une catégorie ou créez en une')
raise ValidationError("Sélectionnez une catégorie ou créez en une")
elif not category:
category, _ = ArticleCategory.objects.get_or_create(name=category_new)
self.cleaned_data['category'] = category
self.cleaned_data["category"] = category
super().clean()
class Meta:
model = Article
fields = ['name', 'is_sold', 'hidden', 'price', 'stock', 'category', 'box_type',
'box_capacity']
model = Article
fields = [
"name",
"is_sold",
"hidden",
"price",
"stock",
"category",
"box_type",
"box_capacity",
]
class ArticleRestrictForm(ArticleForm):
class Meta(ArticleForm.Meta):
fields = ['name', 'is_sold', 'hidden', 'price', 'category', 'box_type',
'box_capacity']
fields = [
"name",
"is_sold",
"hidden",
"price",
"category",
"box_type",
"box_capacity",
]
# -----
# K-Psul forms
# -----
class KPsulOperationGroupForm(forms.ModelForm):
# FIXME(AD): Use timezone.now instead of timezone.now() to avoid using a
# fixed datetime (application boot here).
# One may even use: Checkout.objects.is_valid() if changing
# to now = timezone.now is ok in 'is_valid' definition.
checkout = forms.ModelChoiceField(
queryset = Checkout.objects.filter(
is_protected=False, valid_from__lte=timezone.now(),
valid_to__gte=timezone.now()),
widget = forms.HiddenInput())
queryset=Checkout.objects.filter(
is_protected=False,
valid_from__lte=timezone.now(),
valid_to__gte=timezone.now(),
),
widget=forms.HiddenInput(),
)
on_acc = forms.ModelChoiceField(
queryset = Account.objects.exclude(trigramme='GNR'),
widget = forms.HiddenInput())
queryset=Account.objects.exclude(trigramme="GNR"), widget=forms.HiddenInput()
)
class Meta:
model = OperationGroup
fields = ['on_acc', 'checkout', 'comment']
model = OperationGroup
fields = ["on_acc", "checkout", "comment"]
class KPsulAccountForm(forms.ModelForm):
class Meta:
model = Account
fields = ['trigramme']
model = Account
fields = ["trigramme"]
widgets = {
'trigramme': forms.TextInput(
attrs={
'autocomplete': 'off',
'spellcheck': 'false',
}),
"trigramme": forms.TextInput(
attrs={"autocomplete": "off", "spellcheck": "false"}
)
}
class KPsulCheckoutForm(forms.Form):
checkout = forms.ModelChoiceField(
queryset=None,
widget=forms.Select(attrs={'id': 'id_checkout_select'}),
queryset=None, widget=forms.Select(attrs={"id": "id_checkout_select"})
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Create the queryset on form instanciation to use the current time.
self.fields['checkout'].queryset = (
Checkout.objects.is_valid().filter(is_protected=False))
self.fields["checkout"].queryset = Checkout.objects.is_valid().filter(
is_protected=False
)
class KPsulOperationForm(forms.ModelForm):
article = forms.ModelChoiceField(
queryset=Article.objects.select_related('category').all(),
queryset=Article.objects.select_related("category").all(),
required=False,
widget = forms.HiddenInput())
widget=forms.HiddenInput(),
)
article_nb = forms.IntegerField(
required=False,
initial=None,
validators=[validators.MinValueValidator(1)],
widget=forms.HiddenInput(),
)
class Meta:
model = Operation
fields = ['type', 'amount', 'article', 'article_nb']
widgets = {
'type': forms.HiddenInput(),
'amount': forms.HiddenInput(),
}
model = Operation
fields = ["type", "amount", "article", "article_nb"]
widgets = {"type": forms.HiddenInput(), "amount": forms.HiddenInput()}
def clean(self):
super().clean()
type_ope = self.cleaned_data.get('type')
amount = self.cleaned_data.get('amount')
article = self.cleaned_data.get('article')
article_nb = self.cleaned_data.get('article_nb')
type_ope = self.cleaned_data.get("type")
amount = self.cleaned_data.get("amount")
article = self.cleaned_data.get("article")
article_nb = self.cleaned_data.get("article_nb")
errors = []
if type_ope and type_ope == Operation.PURCHASE:
if not article or article_nb is None or article_nb < 1:
errors.append(ValidationError(
"Un achat nécessite un article et une quantité"))
errors.append(
ValidationError("Un achat nécessite un article et une quantité")
)
elif type_ope and type_ope in [Operation.DEPOSIT, Operation.WITHDRAW]:
if not amount or article or article_nb:
errors.append(ValidationError("Bad request"))
@ -355,8 +397,8 @@ class KPsulOperationForm(forms.ModelForm):
errors.append(ValidationError("Charge non positive"))
elif type_ope == Operation.WITHDRAW and amount >= 0:
errors.append(ValidationError("Retrait non négatif"))
self.cleaned_data['article'] = None
self.cleaned_data['article_nb'] = None
self.cleaned_data["article"] = None
self.cleaned_data["article_nb"] = None
if errors:
raise ValidationError(errors)
@ -364,26 +406,29 @@ class KPsulOperationForm(forms.ModelForm):
KPsulOperationFormSet = modelformset_factory(
Operation,
form = KPsulOperationForm,
can_delete = True,
extra = 0,
min_num = 1, validate_min = True)
form=KPsulOperationForm,
can_delete=True,
extra=0,
min_num=1,
validate_min=True,
)
class AddcostForm(forms.Form):
trigramme = forms.CharField(required = False)
trigramme = forms.CharField(required=False)
amount = forms.DecimalField(
required = False,
max_digits=6,decimal_places=2,min_value=Decimal(0))
required=False, max_digits=6, decimal_places=2, min_value=Decimal(0)
)
def clean(self):
trigramme = self.cleaned_data.get('trigramme')
trigramme = self.cleaned_data.get("trigramme")
if trigramme:
try:
Account.objects.get(trigramme=trigramme)
except Account.DoesNotExist:
raise ValidationError('Compte invalide')
raise ValidationError("Compte invalide")
else:
self.cleaned_data['amount'] = 0
self.cleaned_data["amount"] = 0
super().clean()
@ -395,34 +440,40 @@ class AddcostForm(forms.Form):
class KFetConfigForm(ConfigForm):
kfet_reduction_cof = forms.DecimalField(
label='Réduction COF', initial=Decimal('20'),
max_digits=6, decimal_places=2,
label="Réduction COF",
initial=Decimal("20"),
max_digits=6,
decimal_places=2,
help_text="Réduction, à donner en pourcentage, appliquée lors d'un "
"achat par un-e membre du COF sur le montant en euros.",
"achat par un-e membre du COF sur le montant en euros.",
)
kfet_addcost_amount = forms.DecimalField(
label='Montant de la majoration (en €)', initial=Decimal('0'),
label="Montant de la majoration (en €)",
initial=Decimal("0"),
required=False,
max_digits=6, decimal_places=2,
max_digits=6,
decimal_places=2,
)
kfet_addcost_for = forms.ModelChoiceField(
label='Destinataire de la majoration', initial=None, required=False,
help_text='Laissez vide pour désactiver la majoration.',
queryset=(Account.objects
.select_related('cofprofile', 'cofprofile__user')
.all()),
label="Destinataire de la majoration",
initial=None,
required=False,
help_text="Laissez vide pour désactiver la majoration.",
queryset=(
Account.objects.select_related("cofprofile", "cofprofile__user").all()
),
)
kfet_overdraft_duration = forms.DurationField(
label='Durée du découvert autorisé par défaut',
initial=timedelta(days=1),
label="Durée du découvert autorisé par défaut", initial=timedelta(days=1)
)
kfet_overdraft_amount = forms.DecimalField(
label='Montant du découvert autorisé par défaut (en €)',
initial=Decimal('20'),
max_digits=6, decimal_places=2,
label="Montant du découvert autorisé par défaut (en €)",
initial=Decimal("20"),
max_digits=6,
decimal_places=2,
)
kfet_cancel_duration = forms.DurationField(
label='Durée pour annuler une commande sans mot de passe',
label="Durée pour annuler une commande sans mot de passe",
initial=timedelta(minutes=5),
)
@ -438,105 +489,98 @@ class FilterHistoryForm(forms.Form):
# Transfer forms
# -----
class TransferGroupForm(forms.ModelForm):
class Meta:
model = TransferGroup
fields = ['comment']
model = TransferGroup
fields = ["comment"]
class TransferForm(forms.ModelForm):
from_acc = forms.ModelChoiceField(
queryset = Account.objects.exclude(trigramme__in=['LIQ', '#13', 'GNR']),
widget = forms.HiddenInput()
queryset=Account.objects.exclude(trigramme__in=["LIQ", "#13", "GNR"]),
widget=forms.HiddenInput(),
)
to_acc = forms.ModelChoiceField(
queryset = Account.objects.exclude(trigramme__in=['LIQ', '#13', 'GNR']),
widget = forms.HiddenInput()
queryset=Account.objects.exclude(trigramme__in=["LIQ", "#13", "GNR"]),
widget=forms.HiddenInput(),
)
def clean_amount(self):
amount = self.cleaned_data['amount']
amount = self.cleaned_data["amount"]
if amount <= 0:
raise forms.ValidationError("Montant invalide")
return amount
class Meta:
model = Transfer
fields = ['from_acc', 'to_acc', 'amount']
model = Transfer
fields = ["from_acc", "to_acc", "amount"]
TransferFormSet = modelformset_factory(
Transfer,
form = TransferForm,
min_num = 1, validate_min = True,
extra = 9,
Transfer, form=TransferForm, min_num=1, validate_min=True, extra=9
)
# -----
# Inventory forms
# -----
class InventoryArticleForm(forms.Form):
article = forms.ModelChoiceField(
queryset = Article.objects.all(),
widget = forms.HiddenInput(),
)
queryset=Article.objects.all(), widget=forms.HiddenInput()
)
stock_new = forms.IntegerField(required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'initial' in kwargs:
self.name = kwargs['initial']['name']
self.stock_old = kwargs['initial']['stock_old']
self.category = kwargs['initial']['category']
self.category_name = kwargs['initial']['category__name']
self.box_capacity = kwargs['initial']['box_capacity']
if "initial" in kwargs:
self.name = kwargs["initial"]["name"]
self.stock_old = kwargs["initial"]["stock_old"]
self.category = kwargs["initial"]["category"]
self.category_name = kwargs["initial"]["category__name"]
self.box_capacity = kwargs["initial"]["box_capacity"]
# -----
# Order forms
# -----
class OrderArticleForm(forms.Form):
article = forms.ModelChoiceField(
queryset=Article.objects.all(),
widget=forms.HiddenInput(),
)
queryset=Article.objects.all(), widget=forms.HiddenInput()
)
quantity_ordered = forms.IntegerField(required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'initial' in kwargs:
self.name = kwargs['initial']['name']
self.stock = kwargs['initial']['stock']
self.category = kwargs['initial']['category']
self.category_name = kwargs['initial']['category__name']
self.box_capacity = kwargs['initial']['box_capacity']
self.v_all = kwargs['initial']['v_all']
self.v_moy = kwargs['initial']['v_moy']
self.v_et = kwargs['initial']['v_et']
self.v_prev = kwargs['initial']['v_prev']
self.c_rec = kwargs['initial']['c_rec']
if "initial" in kwargs:
self.name = kwargs["initial"]["name"]
self.stock = kwargs["initial"]["stock"]
self.category = kwargs["initial"]["category"]
self.category_name = kwargs["initial"]["category__name"]
self.box_capacity = kwargs["initial"]["box_capacity"]
self.v_all = kwargs["initial"]["v_all"]
self.v_moy = kwargs["initial"]["v_moy"]
self.v_et = kwargs["initial"]["v_et"]
self.v_prev = kwargs["initial"]["v_prev"]
self.c_rec = kwargs["initial"]["c_rec"]
class OrderArticleToInventoryForm(forms.Form):
article = forms.ModelChoiceField(
queryset = Article.objects.all(),
widget = forms.HiddenInput(),
)
price_HT = forms.DecimalField(
max_digits = 7, decimal_places = 4,
required = False)
TVA = forms.DecimalField(
max_digits = 7, decimal_places = 2,
required = False)
rights = forms.DecimalField(
max_digits = 7, decimal_places = 4,
required = False)
queryset=Article.objects.all(), widget=forms.HiddenInput()
)
price_HT = forms.DecimalField(max_digits=7, decimal_places=4, required=False)
TVA = forms.DecimalField(max_digits=7, decimal_places=2, required=False)
rights = forms.DecimalField(max_digits=7, decimal_places=4, required=False)
quantity_received = forms.IntegerField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'initial' in kwargs:
self.name = kwargs['initial']['name']
self.category = kwargs['initial']['category']
self.category_name = kwargs['initial']['category__name']
self.quantity_ordered = kwargs['initial']['quantity_ordered']
if "initial" in kwargs:
self.name = kwargs["initial"]["name"]
self.category = kwargs["initial"]["category"]
self.category_name = kwargs["initial"]["category__name"]
self.quantity_ordered = kwargs["initial"]["quantity_ordered"]

View file

@ -1,4 +1,3 @@
"""
Crée des opérations aléatoires réparties sur une période de temps spécifiée
"""
@ -6,29 +5,40 @@ Crée des opérations aléatoires réparties sur une période de temps spécifi
import random
from datetime import timedelta
from decimal import Decimal
from django.utils import timezone
from django.core.management.base import BaseCommand
from kfet.models import (Account, Article, OperationGroup, Operation,
Checkout, Transfer, TransferGroup)
from django.core.management.base import BaseCommand
from django.utils import timezone
from kfet.models import (
Account,
Article,
Checkout,
Operation,
OperationGroup,
Transfer,
TransferGroup,
)
class Command(BaseCommand):
help = ("Crée des opérations réparties uniformément "
"sur une période de temps")
help = "Crée des opérations réparties uniformément " "sur une période de temps"
def add_arguments(self, parser):
# Nombre d'opérations à créer
parser.add_argument('opes', type=int,
help='Number of opegroups to create')
parser.add_argument("opes", type=int, help="Number of opegroups to create")
# Période sur laquelle créer (depuis num_days avant maintenant)
parser.add_argument('days', type=int,
help='Period in which to create opegroups')
parser.add_argument(
"days", type=int, help="Period in which to create opegroups"
)
# Optionnel : nombre de transfert à créer (défaut 0)
parser.add_argument('--transfers', type=int, default=0,
help='Number of transfers to create (default 0)')
parser.add_argument(
"--transfers",
type=int,
default=0,
help="Number of transfers to create (default 0)",
)
def handle(self, *args, **options):
@ -39,19 +49,19 @@ class Command(BaseCommand):
purchases = 0
transfers = 0
num_ops = options['opes']
num_transfers = options['transfers']
num_ops = options["opes"]
num_transfers = options["transfers"]
# Convert to seconds
time = options['days'] * 24 * 3600
time = options["days"] * 24 * 3600
now = timezone.now()
checkout = Checkout.objects.first()
articles = Article.objects.all()
accounts = Account.objects.exclude(trigramme='LIQ')
liq_account = Account.objects.get(trigramme='LIQ')
accounts = Account.objects.exclude(trigramme="LIQ")
liq_account = Account.objects.get(trigramme="LIQ")
try:
con_account = Account.objects.get(
cofprofile__user__first_name='Assurancetourix'
cofprofile__user__first_name="Assurancetourix"
)
except Account.DoesNotExist:
con_account = random.choice(accounts)
@ -78,12 +88,12 @@ class Command(BaseCommand):
if random.random() < 0.2:
addcost = True
addcost_for = con_account
addcost_amount = Decimal('0.5')
addcost_amount = Decimal("0.5")
else:
addcost = False
# Initialize opegroup amount
amount = Decimal('0')
amount = Decimal("0")
# Generating operations
ope_list = []
@ -95,19 +105,18 @@ class Command(BaseCommand):
if typevar > 0.9 and account != liq_account:
ope = Operation(
type=Operation.DEPOSIT,
amount=Decimal(random.randint(1, 99)/10)
amount=Decimal(random.randint(1, 99) / 10),
)
# 0.05 probability to have a withdrawal
elif typevar > 0.85 and account != liq_account:
ope = Operation(
type=Operation.WITHDRAW,
amount=-Decimal(random.randint(1, 99)/10)
amount=-Decimal(random.randint(1, 99) / 10),
)
# 0.05 probability to have an edition
elif typevar > 0.8 and account != liq_account:
ope = Operation(
type=Operation.EDIT,
amount=Decimal(random.randint(1, 99)/10)
type=Operation.EDIT, amount=Decimal(random.randint(1, 99) / 10)
)
else:
article = random.choice(articles)
@ -115,9 +124,9 @@ class Command(BaseCommand):
ope = Operation(
type=Operation.PURCHASE,
amount=-article.price*nb,
amount=-article.price * nb,
article=article,
article_nb=nb
article_nb=nb,
)
purchases += 1
@ -130,23 +139,23 @@ class Command(BaseCommand):
ope_list.append(ope)
amount += ope.amount
opegroup_list.append(OperationGroup(
on_acc=account,
checkout=checkout,
at=at,
is_cof=account.cofprofile.is_cof,
amount=amount,
))
opegroup_list.append(
OperationGroup(
on_acc=account,
checkout=checkout,
at=at,
is_cof=account.cofprofile.is_cof,
amount=amount,
)
)
at_list.append(at)
ope_by_grp.append((at, ope_list, ))
ope_by_grp.append((at, ope_list))
OperationGroup.objects.bulk_create(opegroup_list)
# Fetch created OperationGroup objects pk by at
opegroups = (OperationGroup.objects
.filter(at__in=at_list)
.values('id', 'at'))
opegroups_by = {grp['at']: grp['id'] for grp in opegroups}
opegroups = OperationGroup.objects.filter(at__in=at_list).values("id", "at")
opegroups_by = {grp["at"]: grp["id"] for grp in opegroups}
all_ope = []
for _ in range(num_ops):
@ -175,30 +184,28 @@ class Command(BaseCommand):
else:
comment = ""
transfergroup_list.append(TransferGroup(
at=at,
comment=comment,
valid_by=random.choice(accounts),
))
transfergroup_list.append(
TransferGroup(at=at, comment=comment, valid_by=random.choice(accounts))
)
at_list.append(at)
# Randomly generate transfer
transfer_list = []
for i in range(random.randint(1, 4)):
transfer_list.append(Transfer(
from_acc=random.choice(accounts),
to_acc=random.choice(accounts),
amount=Decimal(random.randint(1, 99)/10)
))
transfer_list.append(
Transfer(
from_acc=random.choice(accounts),
to_acc=random.choice(accounts),
amount=Decimal(random.randint(1, 99) / 10),
)
)
transfer_by_grp.append((at, transfer_list, ))
transfer_by_grp.append((at, transfer_list))
TransferGroup.objects.bulk_create(transfergroup_list)
transfergroups = (TransferGroup.objects
.filter(at__in=at_list)
.values('id', 'at'))
transfergroups_by = {grp['at']: grp['id'] for grp in transfergroups}
transfergroups = TransferGroup.objects.filter(at__in=at_list).values("id", "at")
transfergroups_by = {grp["at"]: grp["id"] for grp in transfergroups}
all_transfer = []
for _ in range(num_transfers):
@ -211,9 +218,10 @@ class Command(BaseCommand):
transfers += len(all_transfer)
self.stdout.write(
"- {:d} opérations créées dont {:d} commandes d'articles"
.format(opes_created, purchases))
"- {:d} opérations créées dont {:d} commandes d'articles".format(
opes_created, purchases
)
)
if transfers:
self.stdout.write("- {:d} transferts créés"
.format(transfers))
self.stdout.write("- {:d} transferts créés".format(transfers))

View file

@ -6,18 +6,23 @@ import os
import random
from datetime import timedelta
from django.utils import timezone
from django.contrib.auth.models import User, Group, Permission, ContentType
from django.contrib.auth.models import ContentType, Group, Permission, User
from django.core.management import call_command
from django.utils import timezone
from gestioncof.management.base import MyBaseCommand
from gestioncof.models import CofProfile
from kfet.models import (Account, Checkout, CheckoutStatement, Supplier,
SupplierArticle, Article)
from kfet.models import (
Account,
Article,
Checkout,
CheckoutStatement,
Supplier,
SupplierArticle,
)
# Où sont stockés les fichiers json
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)),
'data')
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
class Command(MyBaseCommand):
@ -28,7 +33,7 @@ class Command(MyBaseCommand):
# Groupes
# ---
Group.objects.filter(name__icontains='K-Fêt').delete()
Group.objects.filter(name__icontains="K-Fêt").delete()
group_chef = Group(name="K-Fêt César")
group_boy = Group(name="K-Fêt Légionnaire")
@ -37,10 +42,11 @@ class Command(MyBaseCommand):
group_boy.save()
permissions_chef = Permission.objects.filter(
content_type__in=ContentType.objects.filter(
app_label='kfet'))
content_type__in=ContentType.objects.filter(app_label="kfet")
)
permissions_boy = Permission.objects.filter(
codename__in=['is_team', 'perform_deposit'])
codename__in=["is_team", "perform_deposit"]
)
group_chef.permissions.add(*permissions_chef)
group_boy.permissions.add(*permissions_boy)
@ -51,11 +57,11 @@ class Command(MyBaseCommand):
self.stdout.write("Création des comptes K-Fêt")
gaulois = CofProfile.objects.filter(user__last_name='Gaulois')
gaulois_trigramme = map('{:03d}'.format, range(50))
gaulois = CofProfile.objects.filter(user__last_name="Gaulois")
gaulois_trigramme = map("{:03d}".format, range(50))
romains = CofProfile.objects.filter(user__last_name='Romain')
romains_trigramme = map(lambda x: str(100+x), range(99))
romains = CofProfile.objects.filter(user__last_name="Romain")
romains_trigramme = map(lambda x: str(100 + x), range(99))
created_accounts = 0
team_accounts = 0
@ -64,18 +70,18 @@ class Command(MyBaseCommand):
account, created = Account.objects.get_or_create(
trigramme=trigramme,
cofprofile=profile,
defaults={'balance': random.randint(1, 999)/10}
defaults={"balance": random.randint(1, 999) / 10},
)
created_accounts += int(created)
if profile.user.first_name == 'Abraracourcix':
if profile.user.first_name == "Abraracourcix":
profile.user.groups.add(group_chef)
for (profile, trigramme) in zip(romains, romains_trigramme):
account, created = Account.objects.get_or_create(
trigramme=trigramme,
cofprofile=profile,
defaults={'balance': random.randint(1, 999)/10}
defaults={"balance": random.randint(1, 999) / 10},
)
created_accounts += int(created)
@ -83,47 +89,50 @@ class Command(MyBaseCommand):
profile.user.groups.add(group_boy)
team_accounts += 1
self.stdout.write("- {:d} comptes créés, {:d} dans l'équipe K-Fêt"
.format(created_accounts, team_accounts))
self.stdout.write(
"- {:d} comptes créés, {:d} dans l'équipe K-Fêt".format(
created_accounts, team_accounts
)
)
# Compte liquide
self.stdout.write("Création du compte liquide")
liq_user, _ = User.objects.get_or_create(username='liquide')
liq_user, _ = User.objects.get_or_create(username="liquide")
liq_profile, _ = CofProfile.objects.get_or_create(user=liq_user)
liq_account, _ = Account.objects.get_or_create(cofprofile=liq_profile,
trigramme='LIQ')
liq_account, _ = Account.objects.get_or_create(
cofprofile=liq_profile, trigramme="LIQ"
)
# Root account if existing
root_profile = CofProfile.objects.filter(user__username='root')
root_profile = CofProfile.objects.filter(user__username="root")
if root_profile.exists():
self.stdout.write("Création du compte K-Fêt root")
root_profile = root_profile.get()
Account.objects.get_or_create(cofprofile=root_profile,
trigramme='AAA')
Account.objects.get_or_create(cofprofile=root_profile, trigramme="AAA")
# ---
# Caisse
# ---
checkout, created = Checkout.objects.get_or_create(
created_by=Account.objects.get(trigramme='000'),
name='Chaudron',
created_by=Account.objects.get(trigramme="000"),
name="Chaudron",
defaults={
'valid_from': timezone.now(),
'valid_to': timezone.now() + timedelta(days=730)
"valid_from": timezone.now(),
"valid_to": timezone.now() + timedelta(days=730),
},
)
if created:
CheckoutStatement.objects.create(
by=Account.objects.get(trigramme='000'),
by=Account.objects.get(trigramme="000"),
checkout=checkout,
balance_old=0,
balance_new=0,
amount_taken=0,
amount_error=0
amount_error=0,
)
# ---
@ -135,10 +144,7 @@ class Command(MyBaseCommand):
articles = random.sample(list(Article.objects.all()), 40)
to_create = []
for article in articles:
to_create.append(SupplierArticle(
supplier=supplier,
article=article
))
to_create.append(SupplierArticle(supplier=supplier, article=article))
SupplierArticle.objects.bulk_create(to_create)
@ -146,10 +152,10 @@ class Command(MyBaseCommand):
# Opérations
# ---
call_command('createopes', '100', '7', '--transfers=20')
call_command("createopes", "100", "7", "--transfers=20")
# ---
# Wagtail CMS
# ---
call_command('kfet_loadwagtail')
call_command("kfet_loadwagtail")

View file

@ -1,257 +1,713 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import django.core.validators
import datetime
import django.core.validators
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestioncof', '0007_alter_club'),
]
dependencies = [("gestioncof", "0007_alter_club")]
operations = [
migrations.CreateModel(
name='Account',
name="Account",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('trigramme', models.CharField(max_length=3, validators=[django.core.validators.RegexValidator(regex='^[^a-z]{3}$')], unique=True)),
('balance', models.DecimalField(decimal_places=2, default=0, max_digits=6)),
('frozen', models.BooleanField(default=False)),
('promo', models.IntegerField(null=True, blank=True, choices=[(1980, 1980), (1981, 1981), (1982, 1982), (1983, 1983), (1984, 1984), (1985, 1985), (1986, 1986), (1987, 1987), (1988, 1988), (1989, 1989), (1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016)], default=2015)),
('nickname', models.CharField(max_length=255, blank=True, default='')),
('password', models.CharField(max_length=255, blank=True, null=True, unique=True, default=None)),
('cofprofile', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='account_kfet', to='gestioncof.CofProfile')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"trigramme",
models.CharField(
max_length=3,
validators=[
django.core.validators.RegexValidator(regex="^[^a-z]{3}$")
],
unique=True,
),
),
(
"balance",
models.DecimalField(decimal_places=2, default=0, max_digits=6),
),
("frozen", models.BooleanField(default=False)),
(
"promo",
models.IntegerField(
null=True,
blank=True,
choices=[
(1980, 1980),
(1981, 1981),
(1982, 1982),
(1983, 1983),
(1984, 1984),
(1985, 1985),
(1986, 1986),
(1987, 1987),
(1988, 1988),
(1989, 1989),
(1990, 1990),
(1991, 1991),
(1992, 1992),
(1993, 1993),
(1994, 1994),
(1995, 1995),
(1996, 1996),
(1997, 1997),
(1998, 1998),
(1999, 1999),
(2000, 2000),
(2001, 2001),
(2002, 2002),
(2003, 2003),
(2004, 2004),
(2005, 2005),
(2006, 2006),
(2007, 2007),
(2008, 2008),
(2009, 2009),
(2010, 2010),
(2011, 2011),
(2012, 2012),
(2013, 2013),
(2014, 2014),
(2015, 2015),
(2016, 2016),
],
default=2015,
),
),
("nickname", models.CharField(max_length=255, blank=True, default="")),
(
"password",
models.CharField(
max_length=255, blank=True, null=True, unique=True, default=None
),
),
(
"cofprofile",
models.OneToOneField(
on_delete=django.db.models.deletion.PROTECT,
related_name="account_kfet",
to="gestioncof.CofProfile",
),
),
],
),
migrations.CreateModel(
name='AccountNegative',
name="AccountNegative",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start', models.DateTimeField(default=datetime.datetime(2016, 8, 2, 10, 22, 1, 569492))),
('balance_offset', models.DecimalField(decimal_places=2, max_digits=6)),
('authorized_overdraft', models.DecimalField(decimal_places=2, default=0, max_digits=6)),
('comment', models.CharField(max_length=255, blank=True)),
('account', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='negative', to='kfet.Account')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"start",
models.DateTimeField(
default=datetime.datetime(2016, 8, 2, 10, 22, 1, 569492)
),
),
("balance_offset", models.DecimalField(decimal_places=2, max_digits=6)),
(
"authorized_overdraft",
models.DecimalField(decimal_places=2, default=0, max_digits=6),
),
("comment", models.CharField(max_length=255, blank=True)),
(
"account",
models.OneToOneField(
on_delete=django.db.models.deletion.PROTECT,
related_name="negative",
to="kfet.Account",
),
),
],
),
migrations.CreateModel(
name='Article',
name="Article",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=45)),
('is_sold', models.BooleanField(default=True)),
('price', models.DecimalField(decimal_places=2, max_digits=6)),
('stock', models.IntegerField(default=0)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=45)),
("is_sold", models.BooleanField(default=True)),
("price", models.DecimalField(decimal_places=2, max_digits=6)),
("stock", models.IntegerField(default=0)),
],
),
migrations.CreateModel(
name='ArticleCategory',
name="ArticleCategory",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=45)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=45)),
],
),
migrations.CreateModel(
name='ArticleRule',
name="ArticleRule",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ratio', models.PositiveSmallIntegerField()),
('article_on', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='rule_on', to='kfet.Article')),
('article_to', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='rule_to', to='kfet.Article')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("ratio", models.PositiveSmallIntegerField()),
(
"article_on",
models.OneToOneField(
on_delete=django.db.models.deletion.PROTECT,
related_name="rule_on",
to="kfet.Article",
),
),
(
"article_to",
models.OneToOneField(
on_delete=django.db.models.deletion.PROTECT,
related_name="rule_to",
to="kfet.Article",
),
),
],
),
migrations.CreateModel(
name='Checkout',
name="Checkout",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=45)),
('valid_from', models.DateTimeField()),
('valid_to', models.DateTimeField()),
('balance', models.DecimalField(decimal_places=2, max_digits=6)),
('is_protected', models.BooleanField(default=False)),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='kfet.Account')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=45)),
("valid_from", models.DateTimeField()),
("valid_to", models.DateTimeField()),
("balance", models.DecimalField(decimal_places=2, max_digits=6)),
("is_protected", models.BooleanField(default=False)),
(
"created_by",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="+",
to="kfet.Account",
),
),
],
),
migrations.CreateModel(
name='CheckoutTransfer',
name="CheckoutTransfer",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=2, max_digits=6)),
('from_checkout', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transfers_from', to='kfet.Checkout')),
('to_checkout', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transfers_to', to='kfet.Checkout')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("amount", models.DecimalField(decimal_places=2, max_digits=6)),
(
"from_checkout",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="transfers_from",
to="kfet.Checkout",
),
),
(
"to_checkout",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="transfers_to",
to="kfet.Checkout",
),
),
],
),
migrations.CreateModel(
name='Inventory',
name="Inventory",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('at', models.DateTimeField(auto_now_add=True)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("at", models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='InventoryArticle',
name="InventoryArticle",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('stock_old', models.IntegerField()),
('stock_new', models.IntegerField()),
('stock_error', models.IntegerField(default=0)),
('article', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='kfet.Article')),
('inventory', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='kfet.Inventory')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("stock_old", models.IntegerField()),
("stock_new", models.IntegerField()),
("stock_error", models.IntegerField(default=0)),
(
"article",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="kfet.Article"
),
),
(
"inventory",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="kfet.Inventory"
),
),
],
),
migrations.CreateModel(
name='Operation',
name="Operation",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(max_length=8, choices=[('purchase', 'Achat'), ('deposit', 'Charge'), ('withdraw', 'Retrait')])),
('amount', models.DecimalField(decimal_places=2, max_digits=6)),
('on_checkout', models.BooleanField(default=True)),
('canceled_at', models.DateTimeField(blank=True, null=True, default=None)),
('addcost_amount', models.DecimalField(decimal_places=2, max_digits=6)),
('addcost_for', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='addcosts', to='kfet.Account', null=True, default=None)),
('article', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='operations', to='kfet.Article', null=True, default=None)),
('canceled_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='+', to='kfet.Account', null=True, default=None)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"type",
models.CharField(
max_length=8,
choices=[
("purchase", "Achat"),
("deposit", "Charge"),
("withdraw", "Retrait"),
],
),
),
("amount", models.DecimalField(decimal_places=2, max_digits=6)),
("on_checkout", models.BooleanField(default=True)),
(
"canceled_at",
models.DateTimeField(blank=True, null=True, default=None),
),
("addcost_amount", models.DecimalField(decimal_places=2, max_digits=6)),
(
"addcost_for",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="addcosts",
to="kfet.Account",
null=True,
default=None,
),
),
(
"article",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="operations",
to="kfet.Article",
null=True,
default=None,
),
),
(
"canceled_by",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="+",
to="kfet.Account",
null=True,
default=None,
),
),
],
),
migrations.CreateModel(
name='OperationGroup',
name="OperationGroup",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('at', models.DateTimeField(auto_now_add=True)),
('amount', models.IntegerField()),
('is_cof', models.BooleanField(default=False)),
('comment', models.CharField(max_length=255, blank=True, default='')),
('checkout', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='operations', to='kfet.Checkout')),
('on_acc', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='operations', to='kfet.Account')),
('valid_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='+', to='kfet.Account', null=True, default=True)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("at", models.DateTimeField(auto_now_add=True)),
("amount", models.IntegerField()),
("is_cof", models.BooleanField(default=False)),
("comment", models.CharField(max_length=255, blank=True, default="")),
(
"checkout",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="operations",
to="kfet.Checkout",
),
),
(
"on_acc",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="operations",
to="kfet.Account",
),
),
(
"valid_by",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="+",
to="kfet.Account",
null=True,
default=True,
),
),
],
),
migrations.CreateModel(
name='Order',
name="Order",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('at', models.DateTimeField(auto_now_add=True)),
('amount', models.DecimalField(decimal_places=2, max_digits=6)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("at", models.DateTimeField(auto_now_add=True)),
("amount", models.DecimalField(decimal_places=2, max_digits=6)),
],
),
migrations.CreateModel(
name='OrderArticle',
name="OrderArticle",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quantity_ordered', models.IntegerField()),
('quantity_received', models.IntegerField()),
('article', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='kfet.Article')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='kfet.Order')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("quantity_ordered", models.IntegerField()),
("quantity_received", models.IntegerField()),
(
"article",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="kfet.Article"
),
),
(
"order",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="kfet.Order"
),
),
],
),
migrations.CreateModel(
name='Statement',
name="Statement",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('balance_old', models.DecimalField(decimal_places=2, max_digits=6)),
('balance_new', models.DecimalField(decimal_places=2, max_digits=6)),
('amount_taken', models.DecimalField(decimal_places=2, max_digits=6)),
('amount_error', models.DecimalField(decimal_places=2, max_digits=6)),
('at', models.DateTimeField(auto_now_add=True)),
('by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='kfet.Account')),
('checkout', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='statements', to='kfet.Checkout')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("balance_old", models.DecimalField(decimal_places=2, max_digits=6)),
("balance_new", models.DecimalField(decimal_places=2, max_digits=6)),
("amount_taken", models.DecimalField(decimal_places=2, max_digits=6)),
("amount_error", models.DecimalField(decimal_places=2, max_digits=6)),
("at", models.DateTimeField(auto_now_add=True)),
(
"by",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="+",
to="kfet.Account",
),
),
(
"checkout",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="statements",
to="kfet.Checkout",
),
),
],
),
migrations.CreateModel(
name='Supplier',
name="Supplier",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=45)),
('address', models.TextField()),
('email', models.EmailField(max_length=254)),
('phone', models.CharField(max_length=10)),
('comment', models.TextField()),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=45)),
("address", models.TextField()),
("email", models.EmailField(max_length=254)),
("phone", models.CharField(max_length=10)),
("comment", models.TextField()),
],
),
migrations.CreateModel(
name='SupplierArticle',
name="SupplierArticle",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('box_type', models.CharField(max_length=7, choices=[('caisse', 'Caisse'), ('carton', 'Carton'), ('palette', 'Palette'), ('fût', 'Fût')])),
('box_capacity', models.PositiveSmallIntegerField()),
('price_HT', models.DecimalField(decimal_places=4, max_digits=7)),
('TVA', models.DecimalField(decimal_places=2, max_digits=4)),
('rights', models.DecimalField(decimal_places=4, max_digits=7)),
('article', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='kfet.Article')),
('supplier', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='kfet.Supplier')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"box_type",
models.CharField(
max_length=7,
choices=[
("caisse", "Caisse"),
("carton", "Carton"),
("palette", "Palette"),
("fût", "Fût"),
],
),
),
("box_capacity", models.PositiveSmallIntegerField()),
("price_HT", models.DecimalField(decimal_places=4, max_digits=7)),
("TVA", models.DecimalField(decimal_places=2, max_digits=4)),
("rights", models.DecimalField(decimal_places=4, max_digits=7)),
(
"article",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="kfet.Article"
),
),
(
"supplier",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="kfet.Supplier"
),
),
],
),
migrations.CreateModel(
name='Transfer',
name="Transfer",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=2, max_digits=6)),
('canceled_at', models.DateTimeField(blank=True, null=True, default=None)),
('canceled_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='+', to='kfet.Account', null=True, default=None)),
('from_acc', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transfers_from', to='kfet.Account')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("amount", models.DecimalField(decimal_places=2, max_digits=6)),
(
"canceled_at",
models.DateTimeField(blank=True, null=True, default=None),
),
(
"canceled_by",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="+",
to="kfet.Account",
null=True,
default=None,
),
),
(
"from_acc",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="transfers_from",
to="kfet.Account",
),
),
],
),
migrations.CreateModel(
name='TransferGroup',
name="TransferGroup",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('at', models.DateTimeField(auto_now_add=True)),
('comment', models.CharField(max_length=255, blank=True, default='')),
('valid_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='+', to='kfet.Account', null=True, default=None)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("at", models.DateTimeField(auto_now_add=True)),
("comment", models.CharField(max_length=255, blank=True, default="")),
(
"valid_by",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="+",
to="kfet.Account",
null=True,
default=None,
),
),
],
),
migrations.AddField(
model_name='transfer',
name='group',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transfers', to='kfet.TransferGroup'),
model_name="transfer",
name="group",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="transfers",
to="kfet.TransferGroup",
),
),
migrations.AddField(
model_name='transfer',
name='to_acc',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transfers_to', to='kfet.Account'),
model_name="transfer",
name="to_acc",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="transfers_to",
to="kfet.Account",
),
),
migrations.AddField(
model_name='supplier',
name='articles',
field=models.ManyToManyField(related_name='suppliers', through='kfet.SupplierArticle', to='kfet.Article'),
model_name="supplier",
name="articles",
field=models.ManyToManyField(
related_name="suppliers",
through="kfet.SupplierArticle",
to="kfet.Article",
),
),
migrations.AddField(
model_name='order',
name='articles',
field=models.ManyToManyField(related_name='orders', through='kfet.OrderArticle', to='kfet.Article'),
model_name="order",
name="articles",
field=models.ManyToManyField(
related_name="orders", through="kfet.OrderArticle", to="kfet.Article"
),
),
migrations.AddField(
model_name='order',
name='supplier',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='orders', to='kfet.Supplier'),
model_name="order",
name="supplier",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="orders",
to="kfet.Supplier",
),
),
migrations.AddField(
model_name='operation',
name='group',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='kfet.OperationGroup'),
model_name="operation",
name="group",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="+",
to="kfet.OperationGroup",
),
),
migrations.AddField(
model_name='inventory',
name='articles',
field=models.ManyToManyField(related_name='inventories', through='kfet.InventoryArticle', to='kfet.Article'),
model_name="inventory",
name="articles",
field=models.ManyToManyField(
related_name="inventories",
through="kfet.InventoryArticle",
to="kfet.Article",
),
),
migrations.AddField(
model_name='inventory',
name='by',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='kfet.Account'),
model_name="inventory",
name="by",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="+",
to="kfet.Account",
),
),
migrations.AddField(
model_name='inventory',
name='order',
field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, blank=True, related_name='inventory', to='kfet.Order', null=True, default=None),
model_name="inventory",
name="order",
field=models.OneToOneField(
on_delete=django.db.models.deletion.PROTECT,
blank=True,
related_name="inventory",
to="kfet.Order",
null=True,
default=None,
),
),
migrations.AddField(
model_name='article',
name='category',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='articles', to='kfet.ArticleCategory'),
model_name="article",
name="category",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="articles",
to="kfet.ArticleCategory",
),
),
]

View file

@ -1,24 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0001_initial'),
]
dependencies = [("kfet", "0001_initial")]
operations = [
migrations.AlterModelOptions(
name='account',
options={'permissions': (('is_team', 'Is part of the team'),)},
name="account",
options={"permissions": (("is_team", "Is part of the team"),)},
),
migrations.AlterField(
model_name='accountnegative',
name='start',
field=models.DateTimeField(default=datetime.datetime(2016, 8, 2, 21, 39, 30, 52279)),
model_name="accountnegative",
name="start",
field=models.DateTimeField(
default=datetime.datetime(2016, 8, 2, 21, 39, 30, 52279)
),
),
]

View file

@ -1,20 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0002_auto_20160802_2139'),
]
dependencies = [("kfet", "0002_auto_20160802_2139")]
operations = [
migrations.AlterField(
model_name='accountnegative',
name='start',
model_name="accountnegative",
name="start",
field=models.DateTimeField(default=datetime.datetime.now),
),
)
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0003_auto_20160802_2142'),
]
dependencies = [("kfet", "0003_auto_20160802_2142")]
operations = [
migrations.AlterField(
model_name='accountnegative',
name='balance_offset',
model_name="accountnegative",
name="balance_offset",
field=models.DecimalField(decimal_places=2, max_digits=6, default=0),
),
)
]

View file

@ -1,28 +1,31 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0004_auto_20160802_2144'),
]
dependencies = [("kfet", "0004_auto_20160802_2144")]
operations = [
migrations.CreateModel(
name='GlobalPermissions',
name="GlobalPermissions",
fields=[
('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
verbose_name="ID",
auto_created=True,
),
)
],
options={
'permissions': (('is_team', 'Is part of the team'),),
'managed': False,
"permissions": (("is_team", "Is part of the team"),),
"managed": False,
},
),
migrations.AlterModelOptions(
name='account',
options={},
),
migrations.AlterModelOptions(name="account", options={}),
]

View file

@ -1,28 +1,23 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0005_auto_20160802_2154'),
]
dependencies = [("kfet", "0005_auto_20160802_2154")]
operations = [
migrations.AlterModelOptions(
name='checkout',
options={'ordering': ['-valid_to']},
name="checkout", options={"ordering": ["-valid_to"]}
),
migrations.RenameField(
model_name='account',
old_name='frozen',
new_name='is_frozen',
model_name="account", old_name="frozen", new_name="is_frozen"
),
migrations.AlterField(
model_name='checkout',
name='balance',
model_name="checkout",
name="balance",
field=models.DecimalField(max_digits=6, default=0, decimal_places=2),
),
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0006_auto_20160804_0600'),
]
dependencies = [("kfet", "0006_auto_20160804_0600")]
operations = [
migrations.AlterField(
model_name='article',
name='price',
model_name="article",
name="price",
field=models.DecimalField(default=0, max_digits=6, decimal_places=2),
),
)
]

View file

@ -1,20 +1,23 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0007_auto_20160804_0641'),
]
dependencies = [("kfet", "0007_auto_20160804_0641")]
operations = [
migrations.AlterField(
model_name='account',
name='trigramme',
field=models.CharField(unique=True, validators=[django.core.validators.RegexValidator(regex='^[^a-z]{3}$')], db_index=True, max_length=3),
),
model_name="account",
name="trigramme",
field=models.CharField(
unique=True,
validators=[django.core.validators.RegexValidator(regex="^[^a-z]{3}$")],
db_index=True,
max_length=3,
),
)
]

View file

@ -1,24 +1,20 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0008_auto_20160804_1736'),
]
dependencies = [("kfet", "0008_auto_20160804_1736")]
operations = [
migrations.RenameField(
model_name='operation',
old_name='on_checkout',
new_name='is_checkout',
model_name="operation", old_name="on_checkout", new_name="is_checkout"
),
migrations.AddField(
model_name='operation',
name='article_nb',
model_name="operation",
name="article_nb",
field=models.PositiveSmallIntegerField(default=None, null=True, blank=True),
),
]

View file

@ -1,30 +1,35 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0009_auto_20160805_0720'),
]
dependencies = [("kfet", "0009_auto_20160805_0720")]
operations = [
migrations.AlterField(
model_name='operation',
name='addcost_amount',
model_name="operation",
name="addcost_amount",
field=models.DecimalField(max_digits=6, default=0, decimal_places=2),
),
migrations.AlterField(
model_name='operationgroup',
name='amount',
model_name="operationgroup",
name="amount",
field=models.DecimalField(max_digits=6, default=0, decimal_places=2),
),
migrations.AlterField(
model_name='operationgroup',
name='valid_by',
field=models.ForeignKey(default=None, related_name='+', to='kfet.Account', blank=True, null=True, on_delete=django.db.models.deletion.PROTECT),
model_name="operationgroup",
name="valid_by",
field=models.ForeignKey(
default=None,
related_name="+",
to="kfet.Account",
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
),
),
]

View file

@ -1,19 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0010_auto_20160806_2343'),
]
dependencies = [("kfet", "0010_auto_20160806_2343")]
operations = [
migrations.AlterField(
model_name='operation',
name='amount',
field=models.DecimalField(decimal_places=2, max_digits=6, default=0, blank=True),
),
model_name="operation",
name="amount",
field=models.DecimalField(
decimal_places=2, max_digits=6, default=0, blank=True
),
)
]

View file

@ -1,22 +1,37 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0011_auto_20160807_1720'),
]
dependencies = [("kfet", "0011_auto_20160807_1720")]
operations = [
migrations.CreateModel(
name='Settings',
name="Settings",
fields=[
('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
('name', models.CharField(max_length=45)),
('value_decimal', models.DecimalField(null=True, max_digits=6, decimal_places=2, blank=True, default=None)),
(
"id",
models.AutoField(
serialize=False,
auto_created=True,
primary_key=True,
verbose_name="ID",
),
),
("name", models.CharField(max_length=45)),
(
"value_decimal",
models.DecimalField(
null=True,
max_digits=6,
decimal_places=2,
blank=True,
default=None,
),
),
],
),
)
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0012_settings'),
]
dependencies = [("kfet", "0012_settings")]
operations = [
migrations.AlterField(
model_name='settings',
name='name',
model_name="settings",
name="name",
field=models.CharField(unique=True, max_length=45),
),
)
]

View file

@ -1,18 +1,22 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0013_auto_20160807_1840'),
]
dependencies = [("kfet", "0013_auto_20160807_1840")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('can_perform_deposit', 'Peut effectuer une charge')), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("can_perform_deposit", "Peut effectuer une charge"),
),
"managed": False,
},
)
]

View file

@ -1,18 +1,26 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0014_auto_20160807_2314'),
]
dependencies = [("kfet", "0014_auto_20160807_2314")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('can_perform_deposit', 'Peut effectuer une charge'), ('can_perform_negative_operations', 'Peut enregistrer des commandes en négatif')), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("can_perform_deposit", "Peut effectuer une charge"),
(
"can_perform_negative_operations",
"Peut enregistrer des commandes en négatif",
),
),
"managed": False,
},
)
]

View file

@ -1,20 +1,24 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0015_auto_20160807_2324'),
]
dependencies = [("kfet", "0015_auto_20160807_2324")]
operations = [
migrations.AddField(
model_name='settings',
name='value_account',
field=models.ForeignKey(to='kfet.Account', on_delete=django.db.models.deletion.PROTECT, default=None, null=True, blank=True),
),
model_name="settings",
name="value_account",
field=models.ForeignKey(
to="kfet.Account",
on_delete=django.db.models.deletion.PROTECT,
default=None,
null=True,
blank=True,
),
)
]

View file

@ -1,19 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0016_settings_value_account'),
]
dependencies = [("kfet", "0016_settings_value_account")]
operations = [
migrations.AlterField(
model_name='operation',
name='addcost_amount',
field=models.DecimalField(blank=True, null=True, decimal_places=2, default=None, max_digits=6),
),
model_name="operation",
name="addcost_amount",
field=models.DecimalField(
blank=True, null=True, decimal_places=2, default=None, max_digits=6
),
)
]

View file

@ -1,18 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0017_auto_20160808_0234'),
]
dependencies = [("kfet", "0017_auto_20160808_0234")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('can_perform_deposit', 'Effectuer une charge'), ('can_perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte")), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("can_perform_deposit", "Effectuer une charge"),
(
"can_perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
),
"managed": False,
},
)
]

View file

@ -1,18 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0018_auto_20160808_0341'),
]
dependencies = [("kfet", "0018_auto_20160808_0341")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'managed': False, 'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"))},
),
name="globalpermissions",
options={
"managed": False,
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
),
},
)
]

View file

@ -1,20 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0019_auto_20160808_0343'),
]
dependencies = [("kfet", "0019_auto_20160808_0343")]
operations = [
migrations.AlterField(
model_name='accountnegative',
name='start',
field=models.DateTimeField(default=datetime.datetime.now, blank=True, null=True),
),
model_name="accountnegative",
name="start",
field=models.DateTimeField(
default=datetime.datetime.now, blank=True, null=True
),
)
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0020_auto_20160808_0450'),
]
dependencies = [("kfet", "0020_auto_20160808_0450")]
operations = [
migrations.AlterField(
model_name='accountnegative',
name='start',
model_name="accountnegative",
name="start",
field=models.DateTimeField(default=None, blank=True, null=True),
),
)
]

View file

@ -1,24 +1,26 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0021_auto_20160808_0506'),
]
dependencies = [("kfet", "0021_auto_20160808_0506")]
operations = [
migrations.AlterField(
model_name='accountnegative',
name='authorized_overdraft',
field=models.DecimalField(blank=True, decimal_places=2, null=True, default=None, max_digits=6),
model_name="accountnegative",
name="authorized_overdraft",
field=models.DecimalField(
blank=True, decimal_places=2, null=True, default=None, max_digits=6
),
),
migrations.AlterField(
model_name='accountnegative',
name='balance_offset',
field=models.DecimalField(blank=True, decimal_places=2, null=True, default=None, max_digits=6),
model_name="accountnegative",
name="balance_offset",
field=models.DecimalField(
blank=True, decimal_places=2, null=True, default=None, max_digits=6
),
),
]

View file

@ -1,24 +1,22 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0022_auto_20160808_0512'),
]
dependencies = [("kfet", "0022_auto_20160808_0512")]
operations = [
migrations.RenameField(
model_name='accountnegative',
old_name='authorized_overdraft',
new_name='authz_overdraft_amount',
model_name="accountnegative",
old_name="authorized_overdraft",
new_name="authz_overdraft_amount",
),
migrations.AddField(
model_name='accountnegative',
name='authz_overdraft_until',
model_name="accountnegative",
name="authz_overdraft_until",
field=models.DateTimeField(null=True, default=None, blank=True),
),
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0023_auto_20160808_0535'),
]
dependencies = [("kfet", "0023_auto_20160808_0535")]
operations = [
migrations.AddField(
model_name='settings',
name='value_duration',
model_name="settings",
name="value_duration",
field=models.DurationField(null=True, default=None, blank=True),
),
)
]

View file

@ -1,18 +1,28 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0024_settings_value_duration'),
]
dependencies = [("kfet", "0024_settings_value_duration")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes')), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
),
"managed": False,
},
)
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0025_auto_20160809_0750'),
]
dependencies = [("kfet", "0025_auto_20160809_0750")]
operations = [
migrations.AlterField(
model_name='settings',
name='name',
model_name="settings",
name="name",
field=models.CharField(db_index=True, max_length=45, unique=True),
),
)
]

View file

@ -1,39 +1,51 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0026_auto_20160809_0810'),
]
dependencies = [("kfet", "0026_auto_20160809_0810")]
operations = [
migrations.CreateModel(
name='CheckoutStatement',
name="CheckoutStatement",
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('balance_old', models.DecimalField(decimal_places=2, max_digits=6)),
('balance_new', models.DecimalField(decimal_places=2, max_digits=6)),
('amount_taken', models.DecimalField(decimal_places=2, max_digits=6)),
('amount_error', models.DecimalField(decimal_places=2, max_digits=6)),
('at', models.DateTimeField(auto_now_add=True)),
('by', models.ForeignKey(to='kfet.Account', on_delete=django.db.models.deletion.PROTECT, related_name='+')),
('checkout', models.ForeignKey(to='kfet.Checkout', on_delete=django.db.models.deletion.PROTECT, related_name='statements')),
(
"id",
models.AutoField(
verbose_name="ID",
primary_key=True,
serialize=False,
auto_created=True,
),
),
("balance_old", models.DecimalField(decimal_places=2, max_digits=6)),
("balance_new", models.DecimalField(decimal_places=2, max_digits=6)),
("amount_taken", models.DecimalField(decimal_places=2, max_digits=6)),
("amount_error", models.DecimalField(decimal_places=2, max_digits=6)),
("at", models.DateTimeField(auto_now_add=True)),
(
"by",
models.ForeignKey(
to="kfet.Account",
on_delete=django.db.models.deletion.PROTECT,
related_name="+",
),
),
(
"checkout",
models.ForeignKey(
to="kfet.Checkout",
on_delete=django.db.models.deletion.PROTECT,
related_name="statements",
),
),
],
),
migrations.RemoveField(
model_name='statement',
name='by',
),
migrations.RemoveField(
model_name='statement',
name='checkout',
),
migrations.DeleteModel(
name='Statement',
),
migrations.RemoveField(model_name="statement", name="by"),
migrations.RemoveField(model_name="statement", name="checkout"),
migrations.DeleteModel(name="Statement"),
]

View file

@ -1,30 +1,40 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0027_auto_20160811_0648'),
]
dependencies = [("kfet", "0027_auto_20160811_0648")]
operations = [
migrations.AlterField(
model_name='operation',
name='group',
field=models.ForeignKey(to='kfet.OperationGroup', on_delete=django.db.models.deletion.PROTECT, related_name='opes'),
model_name="operation",
name="group",
field=models.ForeignKey(
to="kfet.OperationGroup",
on_delete=django.db.models.deletion.PROTECT,
related_name="opes",
),
),
migrations.AlterField(
model_name='operationgroup',
name='checkout',
field=models.ForeignKey(to='kfet.Checkout', on_delete=django.db.models.deletion.PROTECT, related_name='opesgroup'),
model_name="operationgroup",
name="checkout",
field=models.ForeignKey(
to="kfet.Checkout",
on_delete=django.db.models.deletion.PROTECT,
related_name="opesgroup",
),
),
migrations.AlterField(
model_name='operationgroup',
name='on_acc',
field=models.ForeignKey(to='kfet.Account', on_delete=django.db.models.deletion.PROTECT, related_name='opesgroup'),
model_name="operationgroup",
name="on_acc",
field=models.ForeignKey(
to="kfet.Account",
on_delete=django.db.models.deletion.PROTECT,
related_name="opesgroup",
),
),
]

View file

@ -1,21 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0028_auto_20160820_0146'),
]
dependencies = [("kfet", "0028_auto_20160820_0146")]
operations = [
migrations.CreateModel(
name='GenericTeamToken',
name="GenericTeamToken",
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('token', models.CharField(unique=True, max_length=50)),
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
("token", models.CharField(unique=True, max_length=50)),
],
),
)
]

View file

@ -1,18 +1,29 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0029_genericteamtoken'),
]
dependencies = [("kfet", "0029_genericteamtoken")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('manage_perms', 'Gérer les permissions K-Fêt')), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
("manage_perms", "Gérer les permissions K-Fêt"),
),
"managed": False,
},
)
]

View file

@ -1,18 +1,30 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0030_auto_20160821_0029'),
]
dependencies = [("kfet", "0030_auto_20160821_0029")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations')), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
),
"managed": False,
},
)
]

View file

@ -1,94 +1,92 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0031_auto_20160822_0523'),
]
dependencies = [("kfet", "0031_auto_20160822_0523")]
operations = [
migrations.AddField(
model_name='checkoutstatement',
name='taken_001',
model_name="checkoutstatement",
name="taken_001",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_002',
model_name="checkoutstatement",
name="taken_002",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_005',
model_name="checkoutstatement",
name="taken_005",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_01',
model_name="checkoutstatement",
name="taken_01",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_02',
model_name="checkoutstatement",
name="taken_02",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_05',
model_name="checkoutstatement",
name="taken_05",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_1',
model_name="checkoutstatement",
name="taken_1",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_10',
model_name="checkoutstatement",
name="taken_10",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_100',
model_name="checkoutstatement",
name="taken_100",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_2',
model_name="checkoutstatement",
name="taken_2",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_20',
model_name="checkoutstatement",
name="taken_20",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_200',
model_name="checkoutstatement",
name="taken_200",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_5',
model_name="checkoutstatement",
name="taken_5",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_50',
model_name="checkoutstatement",
name="taken_50",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_500',
model_name="checkoutstatement",
name="taken_500",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name='checkoutstatement',
name='taken_cheque',
model_name="checkoutstatement",
name="taken_cheque",
field=models.PositiveSmallIntegerField(default=0),
),
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0032_auto_20160822_2350'),
]
dependencies = [("kfet", "0032_auto_20160822_2350")]
operations = [
migrations.AddField(
model_name='checkoutstatement',
name='not_count',
model_name="checkoutstatement",
name="not_count",
field=models.BooleanField(default=False),
),
)
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0033_checkoutstatement_not_count'),
]
dependencies = [("kfet", "0033_checkoutstatement_not_count")]
operations = [
migrations.AlterField(
model_name='checkoutstatement',
name='taken_cheque',
model_name="checkoutstatement",
name="taken_cheque",
field=models.DecimalField(max_digits=6, decimal_places=2, default=0),
),
)
]

View file

@ -1,18 +1,34 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0034_auto_20160823_0206'),
]
dependencies = [("kfet", "0034_auto_20160823_0206")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'managed': False, 'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'))},
),
name="globalpermissions",
options={
"managed": False,
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
),
},
)
]

View file

@ -1,18 +1,35 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0035_auto_20160823_1505'),
]
dependencies = [("kfet", "0035_auto_20160823_1505")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'managed': False, 'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'), ('view_negs', 'Voir la liste des négatifs'))},
),
name="globalpermissions",
options={
"managed": False,
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
("view_negs", "Voir la liste des négatifs"),
),
},
)
]

View file

@ -1,39 +1,54 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0036_auto_20160823_1910'),
]
dependencies = [("kfet", "0036_auto_20160823_1910")]
operations = [
migrations.AlterField(
model_name='supplierarticle',
name='TVA',
field=models.DecimalField(null=True, max_digits=4, decimal_places=2, default=None, blank=True),
model_name="supplierarticle",
name="TVA",
field=models.DecimalField(
null=True, max_digits=4, decimal_places=2, default=None, blank=True
),
),
migrations.AlterField(
model_name='supplierarticle',
name='box_capacity',
model_name="supplierarticle",
name="box_capacity",
field=models.PositiveSmallIntegerField(null=True, default=None, blank=True),
),
migrations.AlterField(
model_name='supplierarticle',
name='box_type',
field=models.CharField(null=True, max_length=7, choices=[('caisse', 'Caisse'), ('carton', 'Carton'), ('palette', 'Palette'), ('fût', 'Fût')], default=None, blank=True),
model_name="supplierarticle",
name="box_type",
field=models.CharField(
null=True,
max_length=7,
choices=[
("caisse", "Caisse"),
("carton", "Carton"),
("palette", "Palette"),
("fût", "Fût"),
],
default=None,
blank=True,
),
),
migrations.AlterField(
model_name='supplierarticle',
name='price_HT',
field=models.DecimalField(null=True, max_digits=7, decimal_places=4, default=None, blank=True),
model_name="supplierarticle",
name="price_HT",
field=models.DecimalField(
null=True, max_digits=7, decimal_places=4, default=None, blank=True
),
),
migrations.AlterField(
model_name='supplierarticle',
name='rights',
field=models.DecimalField(null=True, max_digits=7, decimal_places=4, default=None, blank=True),
model_name="supplierarticle",
name="rights",
field=models.DecimalField(
null=True, max_digits=7, decimal_places=4, default=None, blank=True
),
),
]

View file

@ -1,36 +1,36 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0037_auto_20160826_2333'),
]
dependencies = [("kfet", "0037_auto_20160826_2333")]
operations = [
migrations.AlterModelOptions(
name='inventory',
options={'ordering': ['-at']},
),
migrations.RemoveField(
model_name='supplierarticle',
name='box_capacity',
),
migrations.RemoveField(
model_name='supplierarticle',
name='box_type',
),
migrations.AlterModelOptions(name="inventory", options={"ordering": ["-at"]}),
migrations.RemoveField(model_name="supplierarticle", name="box_capacity"),
migrations.RemoveField(model_name="supplierarticle", name="box_type"),
migrations.AddField(
model_name='article',
name='box_capacity',
model_name="article",
name="box_capacity",
field=models.PositiveSmallIntegerField(blank=True, null=True, default=None),
),
migrations.AddField(
model_name='article',
name='box_type',
field=models.CharField(max_length=7, blank=True, null=True, default=None, choices=[('caisse', 'Caisse'), ('carton', 'Carton'), ('palette', 'Palette'), ('fût', 'Fût')]),
model_name="article",
name="box_type",
field=models.CharField(
max_length=7,
blank=True,
null=True,
default=None,
choices=[
("caisse", "Caisse"),
("carton", "Carton"),
("palette", "Palette"),
("fût", "Fût"),
],
),
),
]

View file

@ -1,24 +1,22 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0038_auto_20160828_0402'),
]
dependencies = [("kfet", "0038_auto_20160828_0402")]
operations = [
migrations.AlterField(
model_name='order',
name='amount',
model_name="order",
name="amount",
field=models.DecimalField(default=0, decimal_places=2, max_digits=6),
),
migrations.AlterField(
model_name='orderarticle',
name='quantity_received',
model_name="orderarticle",
name="quantity_received",
field=models.IntegerField(default=0),
),
]

View file

@ -1,31 +1,41 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('kfet', '0039_auto_20160828_0430'),
]
dependencies = [("kfet", "0039_auto_20160828_0430")]
operations = [
migrations.AlterModelOptions(
name='order',
options={'ordering': ['-at']},
),
migrations.AlterModelOptions(name="order", options={"ordering": ["-at"]}),
migrations.AddField(
model_name='supplierarticle',
name='at',
field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 8, 29, 18, 35, 3, 419033, tzinfo=utc)),
model_name="supplierarticle",
name="at",
field=models.DateTimeField(
auto_now_add=True,
default=datetime.datetime(2016, 8, 29, 18, 35, 3, 419033, tzinfo=utc),
),
preserve_default=False,
),
migrations.AlterField(
model_name='article',
name='box_type',
field=models.CharField(choices=[('caisse', 'caisse'), ('carton', 'carton'), ('palette', 'palette'), ('fût', 'fût')], null=True, max_length=7, blank=True, default=None),
model_name="article",
name="box_type",
field=models.CharField(
choices=[
("caisse", "caisse"),
("carton", "carton"),
("palette", "palette"),
("fût", "fût"),
],
null=True,
max_length=7,
blank=True,
default=None,
),
),
]

View file

@ -1,18 +1,39 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0040_auto_20160829_2035'),
]
dependencies = [("kfet", "0040_auto_20160829_2035")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'), ('view_negs', 'Voir la liste des négatifs'), ('order_to_inventory', "Générer un inventaire à partir d'une commande")), 'managed': False},
),
name="globalpermissions",
options={
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
("view_negs", "Voir la liste des négatifs"),
(
"order_to_inventory",
"Générer un inventaire à partir d'une commande",
),
),
"managed": False,
},
)
]

View file

@ -1,18 +1,40 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0041_auto_20160830_1502'),
]
dependencies = [("kfet", "0041_auto_20160830_1502")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'managed': False, 'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'), ('view_negs', 'Voir la liste des négatifs'), ('order_to_inventory', "Générer un inventaire à partir d'une commande"), ('edit_balance_account', "Modifier la balance d'un compte"))},
),
name="globalpermissions",
options={
"managed": False,
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
("view_negs", "Voir la liste des négatifs"),
(
"order_to_inventory",
"Générer un inventaire à partir d'une commande",
),
("edit_balance_account", "Modifier la balance d'un compte"),
),
},
)
]

View file

@ -1,19 +1,60 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0042_auto_20160831_0126'),
]
dependencies = [("kfet", "0042_auto_20160831_0126")]
operations = [
migrations.AlterField(
model_name='account',
name='promo',
field=models.IntegerField(blank=True, default=2016, null=True, choices=[(1980, 1980), (1981, 1981), (1982, 1982), (1983, 1983), (1984, 1984), (1985, 1985), (1986, 1986), (1987, 1987), (1988, 1988), (1989, 1989), (1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016)]),
),
model_name="account",
name="promo",
field=models.IntegerField(
blank=True,
default=2016,
null=True,
choices=[
(1980, 1980),
(1981, 1981),
(1982, 1982),
(1983, 1983),
(1984, 1984),
(1985, 1985),
(1986, 1986),
(1987, 1987),
(1988, 1988),
(1989, 1989),
(1990, 1990),
(1991, 1991),
(1992, 1992),
(1993, 1993),
(1994, 1994),
(1995, 1995),
(1996, 1996),
(1997, 1997),
(1998, 1998),
(1999, 1999),
(2000, 2000),
(2001, 2001),
(2002, 2002),
(2003, 2003),
(2004, 2004),
(2005, 2005),
(2006, 2006),
(2007, 2007),
(2008, 2008),
(2009, 2009),
(2010, 2010),
(2011, 2011),
(2012, 2012),
(2013, 2013),
(2014, 2014),
(2015, 2015),
(2016, 2016),
],
),
)
]

View file

@ -1,18 +1,44 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0043_auto_20160901_0046'),
]
dependencies = [("kfet", "0043_auto_20160901_0046")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'managed': False, 'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en n\xe9gatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non r\xe9centes'), ('manage_perms', 'G\xe9rer les permissions K-F\xeat'), ('manage_addcosts', 'G\xe9rer les majorations'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'), ('view_negs', 'Voir la liste des n\xe9gatifs'), ('order_to_inventory', "G\xe9n\xe9rer un inventaire \xe0 partir d'une commande"), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'\xe9quipe"))},
),
name="globalpermissions",
options={
"managed": False,
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en n\xe9gatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non r\xe9centes"),
("manage_perms", "G\xe9rer les permissions K-F\xeat"),
("manage_addcosts", "G\xe9rer les majorations"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
("view_negs", "Voir la liste des n\xe9gatifs"),
(
"order_to_inventory",
"G\xe9n\xe9rer un inventaire \xe0 partir d'une commande",
),
("edit_balance_account", "Modifier la balance d'un compte"),
(
"change_account_password",
"Modifier le mot de passe d'une personne de l'\xe9quipe",
),
),
},
)
]

View file

@ -1,23 +1,61 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0044_auto_20160901_1614'),
]
dependencies = [("kfet", "0044_auto_20160901_1614")]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'managed': False, 'permissions': (('is_team', 'Is part of the team'), ('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en n\xe9gatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non r\xe9centes'), ('manage_perms', 'G\xe9rer les permissions K-F\xeat'), ('manage_addcosts', 'G\xe9rer les majorations'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'), ('view_negs', 'Voir la liste des n\xe9gatifs'), ('order_to_inventory', "G\xe9n\xe9rer un inventaire \xe0 partir d'une commande"), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'\xe9quipe"), ('special_add_account', 'Cr\xe9er un compte avec une balance initiale'))},
name="globalpermissions",
options={
"managed": False,
"permissions": (
("is_team", "Is part of the team"),
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en n\xe9gatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non r\xe9centes"),
("manage_perms", "G\xe9rer les permissions K-F\xeat"),
("manage_addcosts", "G\xe9rer les majorations"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
("view_negs", "Voir la liste des n\xe9gatifs"),
(
"order_to_inventory",
"G\xe9n\xe9rer un inventaire \xe0 partir d'une commande",
),
("edit_balance_account", "Modifier la balance d'un compte"),
(
"change_account_password",
"Modifier le mot de passe d'une personne de l'\xe9quipe",
),
(
"special_add_account",
"Cr\xe9er un compte avec une balance initiale",
),
),
},
),
migrations.AlterField(
model_name='operation',
name='type',
field=models.CharField(max_length=8, choices=[('purchase', 'Achat'), ('deposit', 'Charge'), ('withdraw', 'Retrait'), ('initial', 'Initial')]),
model_name="operation",
name="type",
field=models.CharField(
max_length=8,
choices=[
("purchase", "Achat"),
("deposit", "Charge"),
("withdraw", "Retrait"),
("initial", "Initial"),
],
),
),
]

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0045_auto_20160905_0705'),
]
dependencies = [("kfet", "0045_auto_20160905_0705")]
operations = [
migrations.AddField(
model_name='account',
name='created_at',
model_name="account",
name="created_at",
field=models.DateTimeField(auto_now_add=True, null=True),
),
)
]

View file

@ -6,14 +6,56 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0046_account_created_at'),
]
dependencies = [("kfet", "0046_account_created_at")]
operations = [
migrations.AlterField(
model_name='account',
name='promo',
field=models.IntegerField(blank=True, choices=[(1980, 1980), (1981, 1981), (1982, 1982), (1983, 1983), (1984, 1984), (1985, 1985), (1986, 1986), (1987, 1987), (1988, 1988), (1989, 1989), (1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017)], default=2016, null=True),
),
model_name="account",
name="promo",
field=models.IntegerField(
blank=True,
choices=[
(1980, 1980),
(1981, 1981),
(1982, 1982),
(1983, 1983),
(1984, 1984),
(1985, 1985),
(1986, 1986),
(1987, 1987),
(1988, 1988),
(1989, 1989),
(1990, 1990),
(1991, 1991),
(1992, 1992),
(1993, 1993),
(1994, 1994),
(1995, 1995),
(1996, 1996),
(1997, 1997),
(1998, 1998),
(1999, 1999),
(2000, 2000),
(2001, 2001),
(2002, 2002),
(2003, 2003),
(2004, 2004),
(2005, 2005),
(2006, 2006),
(2007, 2007),
(2008, 2008),
(2009, 2009),
(2010, 2010),
(2011, 2011),
(2012, 2012),
(2013, 2013),
(2014, 2014),
(2015, 2015),
(2016, 2016),
(2017, 2017),
],
default=2016,
null=True,
),
)
]

View file

@ -6,14 +6,15 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0047_auto_20170104_1528'),
]
dependencies = [("kfet", "0047_auto_20170104_1528")]
operations = [
migrations.AddField(
model_name='article',
name='hidden',
field=models.BooleanField(help_text='Si oui, ne sera pas affiché au public ; par exemple sur la carte.', default=False),
),
model_name="article",
name="hidden",
field=models.BooleanField(
help_text="Si oui, ne sera pas affiché au public ; par exemple sur la carte.",
default=False,
),
)
]

View file

@ -1,25 +1,23 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0047_auto_20170104_1528'),
]
dependencies = [("kfet", "0047_auto_20170104_1528")]
operations = [
migrations.AlterField(
model_name='operationgroup',
name='at',
model_name="operationgroup",
name="at",
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AlterField(
model_name='transfergroup',
name='at',
model_name="transfergroup",
name="at",
field=models.DateTimeField(default=django.utils.timezone.now),
),
]

View file

@ -6,10 +6,6 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0048_article_hidden'),
('kfet', '0048_default_datetime'),
]
dependencies = [("kfet", "0048_article_hidden"), ("kfet", "0048_default_datetime")]
operations = [
]
operations = []

View file

@ -7,32 +7,36 @@ from django.db import migrations, models
def adapt_operation_types(apps, schema_editor):
Operation = apps.get_model("kfet", "Operation")
Operation.objects.filter(
is_checkout=False,
type__in=['withdraw', 'deposit']).update(type='edit')
is_checkout=False, type__in=["withdraw", "deposit"]
).update(type="edit")
def revert_operation_types(apps, schema_editor):
Operation = apps.get_model("kfet", "Operation")
edits = Operation.objects.filter(type='edit')
edits.filter(amount__gt=0).update(type='deposit')
edits.filter(amount__lte=0).update(type='withdraw')
edits = Operation.objects.filter(type="edit")
edits.filter(amount__gt=0).update(type="deposit")
edits.filter(amount__lte=0).update(type="withdraw")
class Migration(migrations.Migration):
dependencies = [
('kfet', '0049_merge'),
]
dependencies = [("kfet", "0049_merge")]
operations = [
migrations.AlterField(
model_name='operation',
name='type',
field=models.CharField(choices=[('purchase', 'Achat'), ('deposit', 'Charge'), ('withdraw', 'Retrait'), ('initial', 'Initial'), ('edit', 'Édition')], max_length=8),
model_name="operation",
name="type",
field=models.CharField(
choices=[
("purchase", "Achat"),
("deposit", "Charge"),
("withdraw", "Retrait"),
("initial", "Initial"),
("edit", "Édition"),
],
max_length=8,
),
),
migrations.RunPython(adapt_operation_types, revert_operation_types),
migrations.RemoveField(
model_name='operation',
name='is_checkout',
),
migrations.RemoveField(model_name="operation", name="is_checkout"),
]

View file

@ -1,210 +1,303 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0050_remove_checkout'),
]
dependencies = [("kfet", "0050_remove_checkout")]
operations = [
migrations.AlterField(
model_name='account',
name='is_frozen',
field=models.BooleanField(default=False, verbose_name='est gelé'),
model_name="account",
name="is_frozen",
field=models.BooleanField(default=False, verbose_name="est gelé"),
),
migrations.AlterField(
model_name='account',
name='nickname',
field=models.CharField(default='', max_length=255, verbose_name='surnom(s)', blank=True),
model_name="account",
name="nickname",
field=models.CharField(
default="", max_length=255, verbose_name="surnom(s)", blank=True
),
),
migrations.AlterField(
model_name='accountnegative',
name='authz_overdraft_amount',
field=models.DecimalField(max_digits=6, blank=True, default=None, null=True, verbose_name='négatif autorisé', decimal_places=2),
model_name="accountnegative",
name="authz_overdraft_amount",
field=models.DecimalField(
max_digits=6,
blank=True,
default=None,
null=True,
verbose_name="négatif autorisé",
decimal_places=2,
),
),
migrations.AlterField(
model_name='accountnegative',
name='authz_overdraft_until',
field=models.DateTimeField(default=None, null=True, verbose_name='expiration du négatif', blank=True),
model_name="accountnegative",
name="authz_overdraft_until",
field=models.DateTimeField(
default=None,
null=True,
verbose_name="expiration du négatif",
blank=True,
),
),
migrations.AlterField(
model_name='accountnegative',
name='balance_offset',
field=models.DecimalField(blank=True, max_digits=6, help_text="Montant non compris dans l'autorisation de négatif", default=None, null=True, verbose_name='décalage de balance', decimal_places=2),
model_name="accountnegative",
name="balance_offset",
field=models.DecimalField(
blank=True,
max_digits=6,
help_text="Montant non compris dans l'autorisation de négatif",
default=None,
null=True,
verbose_name="décalage de balance",
decimal_places=2,
),
),
migrations.AlterField(
model_name='accountnegative',
name='comment',
field=models.CharField(blank=True, max_length=255, verbose_name='commentaire'),
model_name="accountnegative",
name="comment",
field=models.CharField(
blank=True, max_length=255, verbose_name="commentaire"
),
),
migrations.AlterField(
model_name='article',
name='box_capacity',
field=models.PositiveSmallIntegerField(default=None, null=True, verbose_name='capacité du contenant', blank=True),
model_name="article",
name="box_capacity",
field=models.PositiveSmallIntegerField(
default=None,
null=True,
verbose_name="capacité du contenant",
blank=True,
),
),
migrations.AlterField(
model_name='article',
name='box_type',
field=models.CharField(blank=True, max_length=7, choices=[('caisse', 'caisse'), ('carton', 'carton'), ('palette', 'palette'), ('fût', 'fût')], default=None, null=True, verbose_name='type de contenant'),
model_name="article",
name="box_type",
field=models.CharField(
blank=True,
max_length=7,
choices=[
("caisse", "caisse"),
("carton", "carton"),
("palette", "palette"),
("fût", "fût"),
],
default=None,
null=True,
verbose_name="type de contenant",
),
),
migrations.AlterField(
model_name='article',
name='category',
field=models.ForeignKey(related_name='articles', to='kfet.ArticleCategory', on_delete=django.db.models.deletion.PROTECT, verbose_name='catégorie'),
model_name="article",
name="category",
field=models.ForeignKey(
related_name="articles",
to="kfet.ArticleCategory",
on_delete=django.db.models.deletion.PROTECT,
verbose_name="catégorie",
),
),
migrations.AlterField(
model_name='article',
name='hidden',
field=models.BooleanField(default=False, verbose_name='caché', help_text='Si oui, ne sera pas affiché au public ; par exemple sur la carte.'),
model_name="article",
name="hidden",
field=models.BooleanField(
default=False,
verbose_name="caché",
help_text="Si oui, ne sera pas affiché au public ; par exemple sur la carte.",
),
),
migrations.AlterField(
model_name='article',
name='is_sold',
field=models.BooleanField(default=True, verbose_name='en vente'),
model_name="article",
name="is_sold",
field=models.BooleanField(default=True, verbose_name="en vente"),
),
migrations.AlterField(
model_name='article',
name='name',
field=models.CharField(max_length=45, verbose_name='nom'),
model_name="article",
name="name",
field=models.CharField(max_length=45, verbose_name="nom"),
),
migrations.AlterField(
model_name='article',
name='price',
field=models.DecimalField(default=0, verbose_name='prix', decimal_places=2, max_digits=6),
model_name="article",
name="price",
field=models.DecimalField(
default=0, verbose_name="prix", decimal_places=2, max_digits=6
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='amount_error',
field=models.DecimalField(max_digits=6, verbose_name="montant de l'erreur", decimal_places=2),
model_name="checkoutstatement",
name="amount_error",
field=models.DecimalField(
max_digits=6, verbose_name="montant de l'erreur", decimal_places=2
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='amount_taken',
field=models.DecimalField(max_digits=6, verbose_name='montant pris', decimal_places=2),
model_name="checkoutstatement",
name="amount_taken",
field=models.DecimalField(
max_digits=6, verbose_name="montant pris", decimal_places=2
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='balance_new',
field=models.DecimalField(max_digits=6, verbose_name='nouvelle balance', decimal_places=2),
model_name="checkoutstatement",
name="balance_new",
field=models.DecimalField(
max_digits=6, verbose_name="nouvelle balance", decimal_places=2
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='balance_old',
field=models.DecimalField(max_digits=6, verbose_name='ancienne balance', decimal_places=2),
model_name="checkoutstatement",
name="balance_old",
field=models.DecimalField(
max_digits=6, verbose_name="ancienne balance", decimal_places=2
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='not_count',
field=models.BooleanField(default=False, verbose_name='caisse non comptée'),
model_name="checkoutstatement",
name="not_count",
field=models.BooleanField(default=False, verbose_name="caisse non comptée"),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_001',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 1¢'),
model_name="checkoutstatement",
name="taken_001",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 1¢"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_002',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 2¢'),
model_name="checkoutstatement",
name="taken_002",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 2¢"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_005',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 5¢'),
model_name="checkoutstatement",
name="taken_005",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 5¢"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_01',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 10¢'),
model_name="checkoutstatement",
name="taken_01",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 10¢"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_02',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 20¢'),
model_name="checkoutstatement",
name="taken_02",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 20¢"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_05',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 50¢'),
model_name="checkoutstatement",
name="taken_05",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 50¢"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_1',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 1€'),
model_name="checkoutstatement",
name="taken_1",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 1€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_10',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 10€'),
model_name="checkoutstatement",
name="taken_10",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 10€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_100',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 100€'),
model_name="checkoutstatement",
name="taken_100",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 100€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_2',
field=models.PositiveSmallIntegerField(default=0, verbose_name='pièces de 2€'),
model_name="checkoutstatement",
name="taken_2",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="pièces de 2€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_20',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 20€'),
model_name="checkoutstatement",
name="taken_20",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 20€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_200',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 200€'),
model_name="checkoutstatement",
name="taken_200",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 200€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_5',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 5€'),
model_name="checkoutstatement",
name="taken_5",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 5€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_50',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 50€'),
model_name="checkoutstatement",
name="taken_50",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 50€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_500',
field=models.PositiveSmallIntegerField(default=0, verbose_name='billets de 500€'),
model_name="checkoutstatement",
name="taken_500",
field=models.PositiveSmallIntegerField(
default=0, verbose_name="billets de 500€"
),
),
migrations.AlterField(
model_name='checkoutstatement',
name='taken_cheque',
field=models.DecimalField(default=0, verbose_name='montant des chèques', decimal_places=2, max_digits=6),
model_name="checkoutstatement",
name="taken_cheque",
field=models.DecimalField(
default=0,
verbose_name="montant des chèques",
decimal_places=2,
max_digits=6,
),
),
migrations.AlterField(
model_name='supplier',
name='address',
field=models.TextField(verbose_name='adresse'),
model_name="supplier",
name="address",
field=models.TextField(verbose_name="adresse"),
),
migrations.AlterField(
model_name='supplier',
name='comment',
field=models.TextField(verbose_name='commentaire'),
model_name="supplier",
name="comment",
field=models.TextField(verbose_name="commentaire"),
),
migrations.AlterField(
model_name='supplier',
name='email',
field=models.EmailField(max_length=254, verbose_name='adresse mail'),
model_name="supplier",
name="email",
field=models.EmailField(max_length=254, verbose_name="adresse mail"),
),
migrations.AlterField(
model_name='supplier',
name='name',
field=models.CharField(max_length=45, verbose_name='nom'),
model_name="supplier",
name="name",
field=models.CharField(max_length=45, verbose_name="nom"),
),
migrations.AlterField(
model_name='supplier',
name='phone',
field=models.CharField(max_length=10, verbose_name='téléphone'),
model_name="supplier",
name="phone",
field=models.CharField(max_length=10, verbose_name="téléphone"),
),
]

View file

@ -6,19 +6,21 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0051_verbose_names'),
]
dependencies = [("kfet", "0051_verbose_names")]
operations = [
migrations.AddField(
model_name='articlecategory',
name='has_addcost',
field=models.BooleanField(default=True, help_text="Si oui et qu'une majoration est active, celle-ci sera appliquée aux articles de cette catégorie.", verbose_name='majorée'),
model_name="articlecategory",
name="has_addcost",
field=models.BooleanField(
default=True,
help_text="Si oui et qu'une majoration est active, celle-ci sera appliquée aux articles de cette catégorie.",
verbose_name="majorée",
),
),
migrations.AlterField(
model_name='articlecategory',
name='name',
field=models.CharField(max_length=45, verbose_name='nom'),
model_name="articlecategory",
name="name",
field=models.CharField(max_length=45, verbose_name="nom"),
),
]

View file

@ -1,20 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0052_category_addcost'),
]
dependencies = [("kfet", "0052_category_addcost")]
operations = [
migrations.AlterField(
model_name='account',
name='created_at',
model_name="account",
name="created_at",
field=models.DateTimeField(default=django.utils.timezone.now),
),
)
]

View file

@ -1,14 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.db import migrations, models
from kfet.forms import KFetConfigForm
def adapt_settings(apps, schema_editor):
Settings = apps.get_model('kfet', 'Settings')
Settings = apps.get_model("kfet", "Settings")
db_alias = schema_editor.connection.alias
obj = Settings.objects.using(db_alias)
@ -22,17 +22,17 @@ def adapt_settings(apps, schema_editor):
pass
try:
subvention = obj.get(name='SUBVENTION_COF').value_decimal
subvention_mult = 1 + subvention/100
reduction = (1 - 1/subvention_mult) * 100
cfg['kfet_reduction_cof'] = reduction
subvention = obj.get(name="SUBVENTION_COF").value_decimal
subvention_mult = 1 + subvention / 100
reduction = (1 - 1 / subvention_mult) * 100
cfg["kfet_reduction_cof"] = reduction
except Settings.DoesNotExist:
pass
try_get('kfet_addcost_amount', 'ADDCOST_AMOUNT', 'value_decimal')
try_get('kfet_addcost_for', 'ADDCOST_FOR', 'value_account')
try_get('kfet_overdraft_duration', 'OVERDRAFT_DURATION', 'value_duration')
try_get('kfet_overdraft_amount', 'OVERDRAFT_AMOUNT', 'value_decimal')
try_get('kfet_cancel_duration', 'CANCEL_DURATION', 'value_duration')
try_get("kfet_addcost_amount", "ADDCOST_AMOUNT", "value_decimal")
try_get("kfet_addcost_for", "ADDCOST_FOR", "value_account")
try_get("kfet_overdraft_duration", "OVERDRAFT_DURATION", "value_duration")
try_get("kfet_overdraft_amount", "OVERDRAFT_AMOUNT", "value_decimal")
try_get("kfet_cancel_duration", "CANCEL_DURATION", "value_duration")
cfg_form = KFetConfigForm(initial=cfg)
if cfg_form.is_valid():
@ -41,18 +41,10 @@ def adapt_settings(apps, schema_editor):
class Migration(migrations.Migration):
dependencies = [
('kfet', '0053_created_at'),
('djconfig', '0001_initial'),
]
dependencies = [("kfet", "0053_created_at"), ("djconfig", "0001_initial")]
operations = [
migrations.RunPython(adapt_settings),
migrations.RemoveField(
model_name='settings',
name='value_account',
),
migrations.DeleteModel(
name='Settings',
),
migrations.RemoveField(model_name="settings", name="value_account"),
migrations.DeleteModel(name="Settings"),
]

View file

@ -6,14 +6,56 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0053_created_at'),
]
dependencies = [("kfet", "0053_created_at")]
operations = [
migrations.AlterField(
model_name='account',
name='promo',
field=models.IntegerField(blank=True, choices=[(1980, 1980), (1981, 1981), (1982, 1982), (1983, 1983), (1984, 1984), (1985, 1985), (1986, 1986), (1987, 1987), (1988, 1988), (1989, 1989), (1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017)], default=2017, null=True),
),
model_name="account",
name="promo",
field=models.IntegerField(
blank=True,
choices=[
(1980, 1980),
(1981, 1981),
(1982, 1982),
(1983, 1983),
(1984, 1984),
(1985, 1985),
(1986, 1986),
(1987, 1987),
(1988, 1988),
(1989, 1989),
(1990, 1990),
(1991, 1991),
(1992, 1992),
(1993, 1993),
(1994, 1994),
(1995, 1995),
(1996, 1996),
(1997, 1997),
(1998, 1998),
(1999, 1999),
(2000, 2000),
(2001, 2001),
(2002, 2002),
(2003, 2003),
(2004, 2004),
(2005, 2005),
(2006, 2006),
(2007, 2007),
(2008, 2008),
(2009, 2009),
(2010, 2010),
(2011, 2011),
(2012, 2012),
(2013, 2013),
(2014, 2014),
(2015, 2015),
(2016, 2016),
(2017, 2017),
],
default=2017,
null=True,
),
)
]

View file

@ -13,41 +13,42 @@ def forwards_perms(apps, schema_editor):
permissions which are assumed unused.
"""
ContentType = apps.get_model('contenttypes', 'contenttype')
ContentType = apps.get_model("contenttypes", "contenttype")
try:
ctype_global = ContentType.objects.get(
app_label="kfet", model="globalpermissions",
app_label="kfet", model="globalpermissions"
)
except ContentType.DoesNotExist:
# We are not migrating from existing data, nothing to do.
return
perms = {
'account': (
'is_team', 'manage_perms', 'manage_addcosts',
'edit_balance_account', 'change_account_password',
'special_add_account',
"account": (
"is_team",
"manage_perms",
"manage_addcosts",
"edit_balance_account",
"change_account_password",
"special_add_account",
),
'accountnegative': ('view_negs',),
'inventory': ('order_to_inventory',),
'operation': (
'perform_deposit', 'perform_negative_operations',
'override_frozen_protection', 'cancel_old_operations',
'perform_commented_operations',
"accountnegative": ("view_negs",),
"inventory": ("order_to_inventory",),
"operation": (
"perform_deposit",
"perform_negative_operations",
"override_frozen_protection",
"cancel_old_operations",
"perform_commented_operations",
),
}
Permission = apps.get_model('auth', 'permission')
Permission = apps.get_model("auth", "permission")
global_perms = Permission.objects.filter(content_type=ctype_global)
for modelname, codenames in perms.items():
model = apps.get_model('kfet', modelname)
model = apps.get_model("kfet", modelname)
ctype = ContentType.objects.get_for_model(model)
(
global_perms
.filter(codename__in=codenames)
.update(content_type=ctype)
)
(global_perms.filter(codename__in=codenames).update(content_type=ctype))
ctype_global.delete()
@ -55,27 +56,64 @@ def forwards_perms(apps, schema_editor):
class Migration(migrations.Migration):
dependencies = [
('kfet', '0054_delete_settings'),
('contenttypes', '__latest__'),
('auth', '__latest__'),
("kfet", "0054_delete_settings"),
("contenttypes", "__latest__"),
("auth", "__latest__"),
]
operations = [
migrations.AlterModelOptions(
name='account',
options={'permissions': (('is_team', 'Is part of the team'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'équipe"), ('special_add_account', 'Créer un compte avec une balance initiale'))},
name="account",
options={
"permissions": (
("is_team", "Is part of the team"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
("edit_balance_account", "Modifier la balance d'un compte"),
(
"change_account_password",
"Modifier le mot de passe d'une personne de l'équipe",
),
(
"special_add_account",
"Créer un compte avec une balance initiale",
),
)
},
),
migrations.AlterModelOptions(
name='accountnegative',
options={'permissions': (('view_negs', 'Voir la liste des négatifs'),)},
name="accountnegative",
options={"permissions": (("view_negs", "Voir la liste des négatifs"),)},
),
migrations.AlterModelOptions(
name='inventory',
options={'ordering': ['-at'], 'permissions': (('order_to_inventory', "Générer un inventaire à partir d'une commande"),)},
name="inventory",
options={
"ordering": ["-at"],
"permissions": (
(
"order_to_inventory",
"Générer un inventaire à partir d'une commande",
),
),
},
),
migrations.AlterModelOptions(
name='operation',
options={'permissions': (('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'))},
name="operation",
options={
"permissions": (
("perform_deposit", "Effectuer une charge"),
(
"perform_negative_operations",
"Enregistrer des commandes en négatif",
),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
)
},
),
migrations.RunPython(forwards_perms),
]

View file

@ -6,13 +6,27 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0055_move_permissions'),
]
dependencies = [("kfet", "0055_move_permissions")]
operations = [
migrations.AlterModelOptions(
name='account',
options={'permissions': (('is_team', 'Is part of the team'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'équipe"), ('special_add_account', 'Créer un compte avec une balance initiale'), ('can_force_close', 'Fermer manuellement la K-Fêt'))},
),
name="account",
options={
"permissions": (
("is_team", "Is part of the team"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
("edit_balance_account", "Modifier la balance d'un compte"),
(
"change_account_password",
"Modifier le mot de passe d'une personne de l'équipe",
),
(
"special_add_account",
"Créer un compte avec une balance initiale",
),
("can_force_close", "Fermer manuellement la K-Fêt"),
)
},
)
]

View file

@ -7,9 +7,8 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0056_change_account_meta'),
('kfet', '0054_update_promos'),
("kfet", "0056_change_account_meta"),
("kfet", "0054_update_promos"),
]
operations = [
]
operations = []

View file

@ -6,12 +6,6 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0057_merge'),
]
dependencies = [("kfet", "0057_merge")]
operations = [
migrations.DeleteModel(
name='GenericTeamToken',
),
]
operations = [migrations.DeleteModel(name="GenericTeamToken")]

View file

@ -15,31 +15,22 @@ def setup_kfet_generic_user(apps, schema_editor):
See also setup_kfet_generic_user from kfet.auth.utils module.
"""
User = apps.get_model('auth', 'User')
CofProfile = apps.get_model('gestioncof', 'CofProfile')
Account = apps.get_model('kfet', 'Account')
User = apps.get_model("auth", "User")
CofProfile = apps.get_model("gestioncof", "CofProfile")
Account = apps.get_model("kfet", "Account")
user, _ = User.objects.update_or_create(
username=KFET_GENERIC_USERNAME,
defaults={
'first_name': 'Compte générique K-Fêt',
},
defaults={"first_name": "Compte générique K-Fêt"},
)
profile, _ = CofProfile.objects.update_or_create(user=user)
account, _ = Account.objects.update_or_create(
cofprofile=profile,
defaults={
'trigramme': KFET_GENERIC_TRIGRAMME,
},
cofprofile=profile, defaults={"trigramme": KFET_GENERIC_TRIGRAMME}
)
class Migration(migrations.Migration):
dependencies = [
('kfet', '0058_delete_genericteamtoken'),
]
dependencies = [("kfet", "0058_delete_genericteamtoken")]
operations = [
migrations.RunPython(setup_kfet_generic_user),
]
operations = [migrations.RunPython(setup_kfet_generic_user)]

View file

@ -6,34 +6,39 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0059_create_generic'),
]
dependencies = [("kfet", "0059_create_generic")]
operations = [
migrations.AlterField(
model_name='supplier',
name='address',
field=models.TextField(verbose_name='adresse', blank=True),
model_name="supplier",
name="address",
field=models.TextField(verbose_name="adresse", blank=True),
),
migrations.AlterField(
model_name='supplier',
name='articles',
field=models.ManyToManyField(verbose_name='articles vendus', through='kfet.SupplierArticle', related_name='suppliers', to='kfet.Article'),
model_name="supplier",
name="articles",
field=models.ManyToManyField(
verbose_name="articles vendus",
through="kfet.SupplierArticle",
related_name="suppliers",
to="kfet.Article",
),
),
migrations.AlterField(
model_name='supplier',
name='comment',
field=models.TextField(verbose_name='commentaire', blank=True),
model_name="supplier",
name="comment",
field=models.TextField(verbose_name="commentaire", blank=True),
),
migrations.AlterField(
model_name='supplier',
name='email',
field=models.EmailField(max_length=254, verbose_name='adresse mail', blank=True),
model_name="supplier",
name="email",
field=models.EmailField(
max_length=254, verbose_name="adresse mail", blank=True
),
),
migrations.AlterField(
model_name='supplier',
name='phone',
field=models.CharField(max_length=20, verbose_name='téléphone', blank=True),
model_name="supplier",
name="phone",
field=models.CharField(max_length=20, verbose_name="téléphone", blank=True),
),
]

View file

@ -6,13 +6,29 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0060_amend_supplier'),
]
dependencies = [("kfet", "0060_amend_supplier")]
operations = [
migrations.AlterModelOptions(
name='account',
options={'permissions': (('is_team', 'Is part of the team'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'équipe"), ('special_add_account', 'Créer un compte avec une balance initiale'), ('can_force_close', 'Fermer manuellement la K-Fêt'), ('see_config', 'Voir la configuration K-Fêt'), ('change_config', 'Modifier la configuration K-Fêt'))},
),
name="account",
options={
"permissions": (
("is_team", "Is part of the team"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
("edit_balance_account", "Modifier la balance d'un compte"),
(
"change_account_password",
"Modifier le mot de passe d'une personne de l'équipe",
),
(
"special_add_account",
"Créer un compte avec une balance initiale",
),
("can_force_close", "Fermer manuellement la K-Fêt"),
("see_config", "Voir la configuration K-Fêt"),
("change_config", "Modifier la configuration K-Fêt"),
)
},
)
]

View file

@ -3,12 +3,6 @@ from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kfet', '0061_add_perms_config'),
]
dependencies = [("kfet", "0061_add_perms_config")]
operations = [
migrations.DeleteModel(
name='GlobalPermissions',
),
]
operations = [migrations.DeleteModel(name="GlobalPermissions")]

View file

@ -7,14 +7,57 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0062_delete_globalpermissions'),
]
dependencies = [("kfet", "0062_delete_globalpermissions")]
operations = [
migrations.AlterField(
model_name='account',
name='promo',
field=models.IntegerField(blank=True, choices=[(1980, 1980), (1981, 1981), (1982, 1982), (1983, 1983), (1984, 1984), (1985, 1985), (1986, 1986), (1987, 1987), (1988, 1988), (1989, 1989), (1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018)], default=2017, null=True),
),
model_name="account",
name="promo",
field=models.IntegerField(
blank=True,
choices=[
(1980, 1980),
(1981, 1981),
(1982, 1982),
(1983, 1983),
(1984, 1984),
(1985, 1985),
(1986, 1986),
(1987, 1987),
(1988, 1988),
(1989, 1989),
(1990, 1990),
(1991, 1991),
(1992, 1992),
(1993, 1993),
(1994, 1994),
(1995, 1995),
(1996, 1996),
(1997, 1997),
(1998, 1998),
(1999, 1999),
(2000, 2000),
(2001, 2001),
(2002, 2002),
(2003, 2003),
(2004, 2004),
(2005, 2005),
(2006, 2006),
(2007, 2007),
(2008, 2008),
(2009, 2009),
(2010, 2010),
(2011, 2011),
(2012, 2012),
(2013, 2013),
(2014, 2014),
(2015, 2015),
(2016, 2016),
(2017, 2017),
(2018, 2018),
],
default=2017,
null=True,
),
)
]

View file

@ -7,14 +7,57 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0063_promo'),
]
dependencies = [("kfet", "0063_promo")]
operations = [
migrations.AlterField(
model_name='account',
name='promo',
field=models.IntegerField(blank=True, choices=[(1980, 1980), (1981, 1981), (1982, 1982), (1983, 1983), (1984, 1984), (1985, 1985), (1986, 1986), (1987, 1987), (1988, 1988), (1989, 1989), (1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018)], default=2018, null=True),
),
model_name="account",
name="promo",
field=models.IntegerField(
blank=True,
choices=[
(1980, 1980),
(1981, 1981),
(1982, 1982),
(1983, 1983),
(1984, 1984),
(1985, 1985),
(1986, 1986),
(1987, 1987),
(1988, 1988),
(1989, 1989),
(1990, 1990),
(1991, 1991),
(1992, 1992),
(1993, 1993),
(1994, 1994),
(1995, 1995),
(1996, 1996),
(1997, 1997),
(1998, 1998),
(1999, 1999),
(2000, 2000),
(2001, 2001),
(2002, 2002),
(2003, 2003),
(2004, 2004),
(2005, 2005),
(2006, 2006),
(2007, 2007),
(2008, 2008),
(2009, 2009),
(2010, 2010),
(2011, 2011),
(2012, 2012),
(2013, 2013),
(2014, 2014),
(2015, 2015),
(2016, 2016),
(2017, 2017),
(2018, 2018),
],
default=2018,
null=True,
),
)
]

View file

@ -1,30 +1,31 @@
import re
from datetime import date
from functools import reduce
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from gestioncof.models import CofProfile
from django.urls import reverse
from django.utils.six.moves import reduce
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.db import transaction
from django.core.validators import RegexValidator
from django.db import models, transaction
from django.db.models import F
from datetime import date
import re
from django.urls import reverse
from django.utils import timezone
from django.utils.six.moves import reduce
from django.utils.translation import ugettext_lazy as _
from gestioncof.models import CofProfile
from .auth import KFET_GENERIC_TRIGRAMME
from .auth.models import GenericTeamToken # noqa
from .config import kfet_config
from .utils import to_ukf
def choices_length(choices):
return reduce(lambda m, choice: max(m, len(choice[0])), choices, 0)
def default_promo():
now = date.today()
return now.month <= 8 and now.year-1 or now.year
return now.month <= 8 and now.year - 1 or now.year
class AccountManager(models.Manager):
@ -32,8 +33,7 @@ class AccountManager(models.Manager):
def get_queryset(self):
"""Always append related data to this Account."""
return super().get_queryset().select_related('cofprofile__user',
'negative')
return super().get_queryset().select_related("cofprofile__user", "negative")
def get_generic(self):
"""
@ -48,6 +48,7 @@ class AccountManager(models.Manager):
Raises Account.DoesNotExist if no Account has this password.
"""
from .auth.utils import hash_password
if password is None:
raise self.model.DoesNotExist
return self.get(password=hash_password(password))
@ -57,69 +58,71 @@ class Account(models.Model):
objects = AccountManager()
cofprofile = models.OneToOneField(
CofProfile, on_delete = models.PROTECT,
related_name = "account_kfet")
CofProfile, on_delete=models.PROTECT, related_name="account_kfet"
)
trigramme = models.CharField(
unique = True,
max_length = 3,
validators = [RegexValidator(regex='^[^a-z]{3}$')],
db_index = True)
balance = models.DecimalField(
max_digits = 6, decimal_places = 2,
default = 0)
is_frozen = models.BooleanField("est gelé", default = False)
unique=True,
max_length=3,
validators=[RegexValidator(regex="^[^a-z]{3}$")],
db_index=True,
)
balance = models.DecimalField(max_digits=6, decimal_places=2, default=0)
is_frozen = models.BooleanField("est gelé", default=False)
created_at = models.DateTimeField(default=timezone.now)
# Optional
PROMO_CHOICES = [(r,r) for r in range(1980, date.today().year+1)]
PROMO_CHOICES = [(r, r) for r in range(1980, date.today().year + 1)]
promo = models.IntegerField(
choices = PROMO_CHOICES,
blank = True, null = True, default = default_promo())
nickname = models.CharField(
"surnom(s)",
max_length = 255,
blank = True, default = "")
choices=PROMO_CHOICES, blank=True, null=True, default=default_promo()
)
nickname = models.CharField("surnom(s)", max_length=255, blank=True, default="")
password = models.CharField(
max_length = 255,
unique = True,
blank = True, null = True, default = None)
max_length=255, unique=True, blank=True, null=True, default=None
)
class Meta:
permissions = (
('is_team', 'Is part of the team'),
('manage_perms', 'Gérer les permissions K-Fêt'),
('manage_addcosts', 'Gérer les majorations'),
('edit_balance_account', "Modifier la balance d'un compte"),
('change_account_password',
"Modifier le mot de passe d'une personne de l'équipe"),
('special_add_account',
"Créer un compte avec une balance initiale"),
('can_force_close', "Fermer manuellement la K-Fêt"),
('see_config', "Voir la configuration K-Fêt"),
('change_config', "Modifier la configuration K-Fêt"),
("is_team", "Is part of the team"),
("manage_perms", "Gérer les permissions K-Fêt"),
("manage_addcosts", "Gérer les majorations"),
("edit_balance_account", "Modifier la balance d'un compte"),
(
"change_account_password",
"Modifier le mot de passe d'une personne de l'équipe",
),
("special_add_account", "Créer un compte avec une balance initiale"),
("can_force_close", "Fermer manuellement la K-Fêt"),
("see_config", "Voir la configuration K-Fêt"),
("change_config", "Modifier la configuration K-Fêt"),
)
def __str__(self):
return '%s (%s)' % (self.trigramme, self.name)
return "%s (%s)" % (self.trigramme, self.name)
# Propriétés pour accéder aux attributs de cofprofile et user
@property
def user(self):
return self.cofprofile.user
@property
def username(self):
return self.cofprofile.user.username
@property
def first_name(self):
return self.cofprofile.user.first_name
@property
def last_name(self):
return self.cofprofile.user.last_name
@property
def email(self):
return self.cofprofile.user.email
@property
def departement(self):
return self.cofprofile.departement
@property
def is_cof(self):
return self.cofprofile.is_cof
@ -131,7 +134,7 @@ class Account(models.Model):
@property
def real_balance(self):
if hasattr(self, 'negative') and self.negative.balance_offset:
if hasattr(self, "negative") and self.negative.balance_offset:
return self.balance - self.negative.balance_offset
return self.balance
@ -141,29 +144,29 @@ class Account(models.Model):
@property
def is_cash(self):
return self.trigramme == 'LIQ'
return self.trigramme == "LIQ"
@property
def need_comment(self):
return self.trigramme == '#13'
return self.trigramme == "#13"
@property
def readable(self):
return self.trigramme != 'GNR'
return self.trigramme != "GNR"
@property
def is_team(self):
return self.has_perm('kfet.is_team')
return self.has_perm("kfet.is_team")
@staticmethod
def is_validandfree(trigramme):
data = { 'is_valid' : False, 'is_free' : False }
data = {"is_valid": False, "is_free": False}
pattern = re.compile("^[^a-z]{3}$")
data['is_valid'] = pattern.match(trigramme) and True or False
data["is_valid"] = pattern.match(trigramme) and True or False
try:
account = Account.objects.get(trigramme=trigramme)
except Account.DoesNotExist:
data['is_free'] = True
data["is_free"] = True
return data
def perms_to_perform_operation(self, amount):
@ -176,31 +179,34 @@ class Account(models.Model):
# Yes, so no perms and no stop
return set(), False
if self.need_comment:
perms.add('kfet.perform_commented_operations')
perms.add("kfet.perform_commented_operations")
# Checking is frozen account
if self.is_frozen:
perms.add('kfet.override_frozen_protection')
perms.add("kfet.override_frozen_protection")
new_balance = self.balance + amount
if new_balance < 0 and amount < 0:
# Retrieving overdraft amount limit
if (hasattr(self, 'negative')
and self.negative.authz_overdraft_amount is not None):
overdraft_amount = - self.negative.authz_overdraft_amount
if (
hasattr(self, "negative")
and self.negative.authz_overdraft_amount is not None
):
overdraft_amount = -self.negative.authz_overdraft_amount
else:
overdraft_amount = - overdraft_amount_max
overdraft_amount = -overdraft_amount_max
# Retrieving overdraft datetime limit
if (hasattr(self, 'negative')
and self.negative.authz_overdraft_until is not None):
if (
hasattr(self, "negative")
and self.negative.authz_overdraft_until is not None
):
overdraft_until = self.negative.authz_overdraft_until
elif hasattr(self, 'negative'):
overdraft_until = \
self.negative.start + overdraft_duration_max
elif hasattr(self, "negative"):
overdraft_until = self.negative.start + overdraft_duration_max
else:
overdraft_until = timezone.now() + overdraft_duration_max
# Checking it doesn't break 1 rule
if new_balance < overdraft_amount or timezone.now() > overdraft_until:
stop_ope = True
perms.add('kfet.perform_negative_operations')
perms.add("kfet.perform_negative_operations")
return perms, stop_ope
# Surcharge Méthode save() avec gestions de User et CofProfile
@ -209,7 +215,7 @@ class Account(models.Model):
# Action:
# - Enregistre User, CofProfile à partir de "data"
# - Enregistre Account
def save(self, data = {}, *args, **kwargs):
def save(self, data={}, *args, **kwargs):
if self.pk and data:
# Account update
@ -217,8 +223,8 @@ class Account(models.Model):
# Updating User with data
user = self.user
user.first_name = data.get("first_name", user.first_name)
user.last_name = data.get("last_name", user.last_name)
user.email = data.get("email", user.email)
user.last_name = data.get("last_name", user.last_name)
user.email = data.get("email", user.email)
user.save()
# Updating CofProfile with data
cof = self.cofprofile
@ -240,18 +246,18 @@ class Account(models.Model):
# Creating or updating User instance
(user, _) = User.objects.get_or_create(username=username)
if "first_name" in data:
user.first_name = data['first_name']
user.first_name = data["first_name"]
if "last_name" in data:
user.last_name = data['last_name']
user.last_name = data["last_name"]
if "email" in data:
user.email = data['email']
user.email = data["email"]
user.save()
# Creating or updating CofProfile instance
(cof, _) = CofProfile.objects.get_or_create(user=user)
if "login_clipper" in data:
cof.login_clipper = data['login_clipper']
cof.login_clipper = data["login_clipper"]
if "departement" in data:
cof.departement = data['departement']
cof.departement = data["departement"]
cof.save()
if data:
self.cofprofile = cof
@ -259,6 +265,7 @@ class Account(models.Model):
def change_pwd(self, clear_password):
from .auth.utils import hash_password
self.password = hash_password(clear_password)
# Surcharge de delete
@ -269,23 +276,21 @@ class Account(models.Model):
def update_negative(self):
if self.real_balance < 0:
if hasattr(self, 'negative') and not self.negative.start:
if hasattr(self, "negative") and not self.negative.start:
self.negative.start = timezone.now()
self.negative.save()
elif not hasattr(self, 'negative'):
self.negative = (
AccountNegative.objects.create(
account=self, start=timezone.now(),
)
elif not hasattr(self, "negative"):
self.negative = AccountNegative.objects.create(
account=self, start=timezone.now()
)
elif hasattr(self, 'negative'):
elif hasattr(self, "negative"):
# self.real_balance >= 0
balance_offset = self.negative.balance_offset
if balance_offset:
(
Account.objects
.filter(pk=self.pk)
.update(balance=F('balance')-balance_offset)
Account.objects.filter(pk=self.pk).update(
balance=F("balance") - balance_offset
)
)
self.refresh_from_db()
self.negative.delete()
@ -299,41 +304,40 @@ class AccountNegativeManager(models.Manager):
"""Manager for AccountNegative model."""
def get_queryset(self):
return (
super().get_queryset()
.select_related('account__cofprofile__user')
)
return super().get_queryset().select_related("account__cofprofile__user")
class AccountNegative(models.Model):
objects = AccountNegativeManager()
account = models.OneToOneField(
Account, on_delete=models.PROTECT,
related_name="negative",
Account, on_delete=models.PROTECT, related_name="negative"
)
start = models.DateTimeField(blank=True, null=True, default=None)
balance_offset = models.DecimalField(
"décalage de balance",
help_text="Montant non compris dans l'autorisation de négatif",
max_digits=6, decimal_places=2,
blank=True, null=True, default=None,
max_digits=6,
decimal_places=2,
blank=True,
null=True,
default=None,
)
authz_overdraft_amount = models.DecimalField(
"négatif autorisé",
max_digits=6, decimal_places=2,
blank=True, null=True, default=None,
max_digits=6,
decimal_places=2,
blank=True,
null=True,
default=None,
)
authz_overdraft_until = models.DateTimeField(
"expiration du négatif",
blank=True, null=True, default=None,
"expiration du négatif", blank=True, null=True, default=None
)
comment = models.CharField("commentaire", max_length=255, blank=True)
class Meta:
permissions = (
('view_negs', 'Voir la liste des négatifs'),
)
permissions = (("view_negs", "Voir la liste des négatifs"),)
@property
def until_default(self):
@ -341,31 +345,26 @@ class AccountNegative(models.Model):
class CheckoutQuerySet(models.QuerySet):
def is_valid(self):
now = timezone.now()
return self.filter(valid_from__lte=now, valid_to__gte=now)
class Checkout(models.Model):
created_by = models.ForeignKey(
Account, on_delete = models.PROTECT,
related_name = "+")
name = models.CharField(max_length = 45)
created_by = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="+")
name = models.CharField(max_length=45)
valid_from = models.DateTimeField()
valid_to = models.DateTimeField()
balance = models.DecimalField(
max_digits = 6, decimal_places = 2,
default = 0)
is_protected = models.BooleanField(default = False)
valid_to = models.DateTimeField()
balance = models.DecimalField(max_digits=6, decimal_places=2, default=0)
is_protected = models.BooleanField(default=False)
objects = CheckoutQuerySet.as_manager()
def get_absolute_url(self):
return reverse('kfet.checkout.read', kwargs={'pk': self.pk})
return reverse("kfet.checkout.read", kwargs={"pk": self.pk})
class Meta:
ordering = ['-valid_to']
ordering = ["-valid_to"]
def __str__(self):
return self.name
@ -388,31 +387,30 @@ class Checkout(models.Model):
class CheckoutTransfer(models.Model):
from_checkout = models.ForeignKey(
Checkout, on_delete = models.PROTECT,
related_name = "transfers_from")
Checkout, on_delete=models.PROTECT, related_name="transfers_from"
)
to_checkout = models.ForeignKey(
Checkout, on_delete = models.PROTECT,
related_name = "transfers_to")
amount = models.DecimalField(
max_digits = 6, decimal_places = 2)
Checkout, on_delete=models.PROTECT, related_name="transfers_to"
)
amount = models.DecimalField(max_digits=6, decimal_places=2)
class CheckoutStatement(models.Model):
by = models.ForeignKey(
Account, on_delete = models.PROTECT,
related_name = "+")
by = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="+")
checkout = models.ForeignKey(
Checkout, on_delete = models.PROTECT,
related_name = "statements")
balance_old = models.DecimalField("ancienne balance",
max_digits = 6, decimal_places = 2)
balance_new = models.DecimalField("nouvelle balance",
max_digits = 6, decimal_places = 2)
amount_taken = models.DecimalField("montant pris",
max_digits = 6, decimal_places = 2)
amount_error = models.DecimalField("montant de l'erreur",
max_digits = 6, decimal_places = 2)
at = models.DateTimeField(auto_now_add = True)
Checkout, on_delete=models.PROTECT, related_name="statements"
)
balance_old = models.DecimalField(
"ancienne balance", max_digits=6, decimal_places=2
)
balance_new = models.DecimalField(
"nouvelle balance", max_digits=6, decimal_places=2
)
amount_taken = models.DecimalField("montant pris", max_digits=6, decimal_places=2)
amount_error = models.DecimalField(
"montant de l'erreur", max_digits=6, decimal_places=2
)
at = models.DateTimeField(auto_now_add=True)
not_count = models.BooleanField("caisse non comptée", default=False)
taken_001 = models.PositiveSmallIntegerField("pièces de 1¢", default=0)
@ -431,68 +429,76 @@ class CheckoutStatement(models.Model):
taken_200 = models.PositiveSmallIntegerField("billets de 200€", default=0)
taken_500 = models.PositiveSmallIntegerField("billets de 500€", default=0)
taken_cheque = models.DecimalField(
"montant des chèques",
default=0, max_digits=6, decimal_places=2)
"montant des chèques", default=0, max_digits=6, decimal_places=2
)
def __str__(self):
return '%s %s' % (self.checkout, self.at)
return "%s %s" % (self.checkout, self.at)
def save(self, *args, **kwargs):
if not self.pk:
checkout_id = self.checkout_id
self.balance_old = (Checkout.objects
.values_list('balance', flat=True).get(pk=checkout_id))
self.balance_old = Checkout.objects.values_list("balance", flat=True).get(
pk=checkout_id
)
if self.not_count:
self.balance_new = self.balance_old - self.amount_taken
self.amount_error = (
self.balance_new + self.amount_taken - self.balance_old)
self.amount_error = self.balance_new + self.amount_taken - self.balance_old
with transaction.atomic():
Checkout.objects.filter(pk=checkout_id).update(balance=self.balance_new)
super().save(*args, **kwargs)
else:
self.amount_error = (
self.balance_new + self.amount_taken - self.balance_old)
self.amount_error = self.balance_new + self.amount_taken - self.balance_old
# Si on modifie le dernier relevé d'une caisse et que la nouvelle
# balance est modifiée alors on modifie la balance actuelle de la caisse
last_statement = (CheckoutStatement.objects
.filter(checkout=self.checkout)
.order_by('at')
.last())
if (last_statement.pk == self.pk
and last_statement.balance_new != self.balance_new):
last_statement = (
CheckoutStatement.objects.filter(checkout=self.checkout)
.order_by("at")
.last()
)
if (
last_statement.pk == self.pk
and last_statement.balance_new != self.balance_new
):
Checkout.objects.filter(pk=self.checkout_id).update(
balance=F('balance') - last_statement.balance_new + self.balance_new)
balance=F("balance") - last_statement.balance_new + self.balance_new
)
super().save(*args, **kwargs)
class ArticleCategory(models.Model):
name = models.CharField("nom", max_length=45)
has_addcost = models.BooleanField("majorée", default=True,
help_text="Si oui et qu'une majoration "
"est active, celle-ci sera "
"appliquée aux articles de "
"cette catégorie.")
has_addcost = models.BooleanField(
"majorée",
default=True,
help_text="Si oui et qu'une majoration "
"est active, celle-ci sera "
"appliquée aux articles de "
"cette catégorie.",
)
def __str__(self):
return self.name
class Article(models.Model):
name = models.CharField("nom", max_length = 45)
is_sold = models.BooleanField("en vente", default = True)
hidden = models.BooleanField("caché",
default=False,
help_text="Si oui, ne sera pas affiché "
"au public ; par exemple "
"sur la carte.")
price = models.DecimalField(
"prix",
max_digits = 6, decimal_places = 2,
default = 0)
stock = models.IntegerField(default = 0)
name = models.CharField("nom", max_length=45)
is_sold = models.BooleanField("en vente", default=True)
hidden = models.BooleanField(
"caché",
default=False,
help_text="Si oui, ne sera pas affiché "
"au public ; par exemple "
"sur la carte.",
)
price = models.DecimalField("prix", max_digits=6, decimal_places=2, default=0)
stock = models.IntegerField(default=0)
category = models.ForeignKey(
ArticleCategory, on_delete = models.PROTECT,
related_name = "articles", verbose_name='catégorie')
ArticleCategory,
on_delete=models.PROTECT,
related_name="articles",
verbose_name="catégorie",
)
BOX_TYPE_CHOICES = (
("caisse", "caisse"),
("carton", "carton"),
@ -501,18 +507,21 @@ class Article(models.Model):
)
box_type = models.CharField(
"type de contenant",
choices = BOX_TYPE_CHOICES,
max_length = choices_length(BOX_TYPE_CHOICES),
blank = True, null = True, default = None)
choices=BOX_TYPE_CHOICES,
max_length=choices_length(BOX_TYPE_CHOICES),
blank=True,
null=True,
default=None,
)
box_capacity = models.PositiveSmallIntegerField(
"capacité du contenant",
blank = True, null = True, default = None)
"capacité du contenant", blank=True, null=True, default=None
)
def __str__(self):
return '%s - %s' % (self.category.name, self.name)
return "%s - %s" % (self.category.name, self.name)
def get_absolute_url(self):
return reverse('kfet.article.read', kwargs={'pk': self.pk})
return reverse("kfet.article.read", kwargs={"pk": self.pk})
def price_ukf(self):
return to_ukf(self.price)
@ -520,43 +529,43 @@ class Article(models.Model):
class ArticleRule(models.Model):
article_on = models.OneToOneField(
Article, on_delete = models.PROTECT,
related_name = "rule_on")
Article, on_delete=models.PROTECT, related_name="rule_on"
)
article_to = models.OneToOneField(
Article, on_delete = models.PROTECT,
related_name = "rule_to")
Article, on_delete=models.PROTECT, related_name="rule_to"
)
ratio = models.PositiveSmallIntegerField()
class Inventory(models.Model):
articles = models.ManyToManyField(
Article,
through = 'InventoryArticle',
related_name = "inventories")
by = models.ForeignKey(
Account, on_delete = models.PROTECT,
related_name = "+")
at = models.DateTimeField(auto_now_add = True)
Article, through="InventoryArticle", related_name="inventories"
)
by = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="+")
at = models.DateTimeField(auto_now_add=True)
# Optional
order = models.OneToOneField(
'Order', on_delete = models.PROTECT,
related_name = "inventory",
blank = True, null = True, default = None)
"Order",
on_delete=models.PROTECT,
related_name="inventory",
blank=True,
null=True,
default=None,
)
class Meta:
ordering = ['-at']
ordering = ["-at"]
permissions = (
('order_to_inventory', "Générer un inventaire à partir d'une commande"),
("order_to_inventory", "Générer un inventaire à partir d'une commande"),
)
class InventoryArticle(models.Model):
inventory = models.ForeignKey(
Inventory, on_delete = models.PROTECT)
article = models.ForeignKey(
Article, on_delete = models.PROTECT)
stock_old = models.IntegerField()
stock_new = models.IntegerField()
stock_error = models.IntegerField(default = 0)
inventory = models.ForeignKey(Inventory, on_delete=models.PROTECT)
article = models.ForeignKey(Article, on_delete=models.PROTECT)
stock_old = models.IntegerField()
stock_new = models.IntegerField()
stock_error = models.IntegerField(default=0)
def save(self, *args, **kwargs):
# S'il s'agit d'un inventaire provenant d'une livraison, il n'y a pas
@ -570,8 +579,8 @@ class Supplier(models.Model):
articles = models.ManyToManyField(
Article,
verbose_name=_("articles vendus"),
through='SupplierArticle',
related_name='suppliers',
through="SupplierArticle",
related_name="suppliers",
)
name = models.CharField(_("nom"), max_length=45)
address = models.TextField(_("adresse"), blank=True)
@ -584,175 +593,187 @@ class Supplier(models.Model):
class SupplierArticle(models.Model):
supplier = models.ForeignKey(
Supplier, on_delete = models.PROTECT)
article = models.ForeignKey(
Article, on_delete = models.PROTECT)
at = models.DateTimeField(auto_now_add = True)
supplier = models.ForeignKey(Supplier, on_delete=models.PROTECT)
article = models.ForeignKey(Article, on_delete=models.PROTECT)
at = models.DateTimeField(auto_now_add=True)
price_HT = models.DecimalField(
max_digits = 7, decimal_places = 4,
blank = True, null = True, default = None)
max_digits=7, decimal_places=4, blank=True, null=True, default=None
)
TVA = models.DecimalField(
max_digits = 4, decimal_places = 2,
blank = True, null = True, default = None)
max_digits=4, decimal_places=2, blank=True, null=True, default=None
)
rights = models.DecimalField(
max_digits = 7, decimal_places = 4,
blank = True, null = True, default = None)
max_digits=7, decimal_places=4, blank=True, null=True, default=None
)
class Order(models.Model):
supplier = models.ForeignKey(
Supplier, on_delete = models.PROTECT,
related_name = "orders")
Supplier, on_delete=models.PROTECT, related_name="orders"
)
articles = models.ManyToManyField(
Article,
through = "OrderArticle",
related_name = "orders")
at = models.DateTimeField(auto_now_add = True)
amount = models.DecimalField(
max_digits = 6, decimal_places = 2, default = 0)
Article, through="OrderArticle", related_name="orders"
)
at = models.DateTimeField(auto_now_add=True)
amount = models.DecimalField(max_digits=6, decimal_places=2, default=0)
class Meta:
ordering = ['-at']
ordering = ["-at"]
class OrderArticle(models.Model):
order = models.ForeignKey(
Order, on_delete = models.PROTECT)
article = models.ForeignKey(
Article, on_delete = models.PROTECT)
order = models.ForeignKey(Order, on_delete=models.PROTECT)
article = models.ForeignKey(Article, on_delete=models.PROTECT)
quantity_ordered = models.IntegerField()
quantity_received = models.IntegerField(default = 0)
quantity_received = models.IntegerField(default=0)
class TransferGroup(models.Model):
at = models.DateTimeField(default=timezone.now)
# Optional
comment = models.CharField(
max_length = 255,
blank = True, default = "")
comment = models.CharField(max_length=255, blank=True, default="")
valid_by = models.ForeignKey(
Account, on_delete = models.PROTECT,
related_name = "+",
blank = True, null = True, default = None)
Account,
on_delete=models.PROTECT,
related_name="+",
blank=True,
null=True,
default=None,
)
class Transfer(models.Model):
group = models.ForeignKey(
TransferGroup, on_delete=models.PROTECT,
related_name="transfers")
TransferGroup, on_delete=models.PROTECT, related_name="transfers"
)
from_acc = models.ForeignKey(
Account, on_delete=models.PROTECT,
related_name="transfers_from")
Account, on_delete=models.PROTECT, related_name="transfers_from"
)
to_acc = models.ForeignKey(
Account, on_delete=models.PROTECT,
related_name="transfers_to")
Account, on_delete=models.PROTECT, related_name="transfers_to"
)
amount = models.DecimalField(max_digits=6, decimal_places=2)
# Optional
canceled_by = models.ForeignKey(
Account, on_delete=models.PROTECT,
null=True, blank=True, default=None,
related_name="+")
canceled_at = models.DateTimeField(
null=True, blank=True, default=None)
Account,
on_delete=models.PROTECT,
null=True,
blank=True,
default=None,
related_name="+",
)
canceled_at = models.DateTimeField(null=True, blank=True, default=None)
def __str__(self):
return '{} -> {}: {}'.format(self.from_acc, self.to_acc, self.amount)
return "{} -> {}: {}".format(self.from_acc, self.to_acc, self.amount)
class OperationGroup(models.Model):
on_acc = models.ForeignKey(
Account, on_delete = models.PROTECT,
related_name = "opesgroup")
Account, on_delete=models.PROTECT, related_name="opesgroup"
)
checkout = models.ForeignKey(
Checkout, on_delete = models.PROTECT,
related_name = "opesgroup")
Checkout, on_delete=models.PROTECT, related_name="opesgroup"
)
at = models.DateTimeField(default=timezone.now)
amount = models.DecimalField(
max_digits = 6, decimal_places = 2,
default = 0)
is_cof = models.BooleanField(default = False)
amount = models.DecimalField(max_digits=6, decimal_places=2, default=0)
is_cof = models.BooleanField(default=False)
# Optional
comment = models.CharField(
max_length = 255,
blank = True, default = "")
comment = models.CharField(max_length=255, blank=True, default="")
valid_by = models.ForeignKey(
Account, on_delete = models.PROTECT,
related_name = "+",
blank = True, null = True, default = None)
Account,
on_delete=models.PROTECT,
related_name="+",
blank=True,
null=True,
default=None,
)
def __str__(self):
return ', '.join(map(str, self.opes.all()))
return ", ".join(map(str, self.opes.all()))
class Operation(models.Model):
PURCHASE = 'purchase'
DEPOSIT = 'deposit'
WITHDRAW = 'withdraw'
INITIAL = 'initial'
EDIT = 'edit'
PURCHASE = "purchase"
DEPOSIT = "deposit"
WITHDRAW = "withdraw"
INITIAL = "initial"
EDIT = "edit"
TYPE_ORDER_CHOICES = (
(PURCHASE, 'Achat'),
(DEPOSIT, 'Charge'),
(WITHDRAW, 'Retrait'),
(INITIAL, 'Initial'),
(EDIT, 'Édition'),
(PURCHASE, "Achat"),
(DEPOSIT, "Charge"),
(WITHDRAW, "Retrait"),
(INITIAL, "Initial"),
(EDIT, "Édition"),
)
group = models.ForeignKey(
OperationGroup, on_delete=models.PROTECT,
related_name="opes")
OperationGroup, on_delete=models.PROTECT, related_name="opes"
)
type = models.CharField(
choices=TYPE_ORDER_CHOICES,
max_length=choices_length(TYPE_ORDER_CHOICES))
amount = models.DecimalField(
max_digits=6, decimal_places=2,
blank=True, default=0)
choices=TYPE_ORDER_CHOICES, max_length=choices_length(TYPE_ORDER_CHOICES)
)
amount = models.DecimalField(max_digits=6, decimal_places=2, blank=True, default=0)
# Optional
article = models.ForeignKey(
Article, on_delete=models.PROTECT,
Article,
on_delete=models.PROTECT,
related_name="operations",
blank=True, null=True, default=None)
article_nb = models.PositiveSmallIntegerField(
blank=True, null=True, default=None)
blank=True,
null=True,
default=None,
)
article_nb = models.PositiveSmallIntegerField(blank=True, null=True, default=None)
canceled_by = models.ForeignKey(
Account, on_delete=models.PROTECT,
Account,
on_delete=models.PROTECT,
related_name="+",
blank=True, null=True, default=None)
canceled_at = models.DateTimeField(
blank=True, null=True, default=None)
blank=True,
null=True,
default=None,
)
canceled_at = models.DateTimeField(blank=True, null=True, default=None)
addcost_for = models.ForeignKey(
Account, on_delete=models.PROTECT,
Account,
on_delete=models.PROTECT,
related_name="addcosts",
blank=True, null=True, default=None)
blank=True,
null=True,
default=None,
)
addcost_amount = models.DecimalField(
max_digits=6, decimal_places=2,
blank=True, null=True, default=None)
max_digits=6, decimal_places=2, blank=True, null=True, default=None
)
class Meta:
permissions = (
('perform_deposit', 'Effectuer une charge'),
('perform_negative_operations',
'Enregistrer des commandes en négatif'),
('override_frozen_protection', "Forcer le gel d'un compte"),
('cancel_old_operations', 'Annuler des commandes non récentes'),
('perform_commented_operations',
'Enregistrer des commandes avec commentaires'),
("perform_deposit", "Effectuer une charge"),
("perform_negative_operations", "Enregistrer des commandes en négatif"),
("override_frozen_protection", "Forcer le gel d'un compte"),
("cancel_old_operations", "Annuler des commandes non récentes"),
(
"perform_commented_operations",
"Enregistrer des commandes avec commentaires",
),
)
@property
def is_checkout(self):
return (self.type == Operation.DEPOSIT or
self.type == Operation.WITHDRAW or
(self.type == Operation.PURCHASE and self.group.on_acc.is_cash)
)
return (
self.type == Operation.DEPOSIT
or self.type == Operation.WITHDRAW
or (self.type == Operation.PURCHASE and self.group.on_acc.is_cash)
)
def __str__(self):
templates = {
self.PURCHASE: "{nb} {article.name} ({amount}€)",
self.DEPOSIT: "charge ({amount}€)",
self.WITHDRAW: "retrait ({amount}€)",
self.INITIAL: "initial ({amount}€)",
self.EDIT: "édition ({amount}€)",
}
return templates[self.type].format(nb=self.article_nb,
article=self.article,
amount=self.amount)
self.PURCHASE: "{nb} {article.name} ({amount}€)",
self.DEPOSIT: "charge ({amount}€)",
self.WITHDRAW: "retrait ({amount}€)",
self.INITIAL: "initial ({amount}€)",
self.EDIT: "édition ({amount}€)",
}
return templates[self.type].format(
nb=self.article_nb, article=self.article, amount=self.amount
)

View file

@ -1,6 +1,5 @@
from ..decorators import kfet_is_team
from ..utils import DjangoJsonWebsocketConsumer, PermConsumerMixin
from .open import kfet_open
@ -16,8 +15,8 @@ class OpenKfetConsumer(PermConsumerMixin, DjangoJsonWebsocketConsumer):
def connection_groups(self, user, **kwargs):
"""Select which group the user should be connected."""
if kfet_is_team(user):
return ['kfet.open.team']
return ['kfet.open.base']
return ["kfet.open.team"]
return ["kfet.open.base"]
def connect(self, message, *args, **kwargs):
"""Send current status on connect."""

View file

@ -15,23 +15,20 @@ class OpenKfet(CachedMixin, object):
Current state persists through cache.
"""
# status is unknown after this duration
time_unknown = timedelta(minutes=15)
# status
OPENED = 'opened'
CLOSED = 'closed'
UNKNOWN = 'unknown'
OPENED = "opened"
CLOSED = "closed"
UNKNOWN = "unknown"
# admin status
FAKE_CLOSED = 'fake_closed'
FAKE_CLOSED = "fake_closed"
# cached attributes config
cached = {
'_raw_open': False,
'_last_update': None,
'force_close': False,
}
cache_prefix = 'kfetopen'
cached = {"_raw_open": False, "_last_update": None, "force_close": False}
cache_prefix = "kfetopen"
@property
def raw_open(self):
@ -54,8 +51,10 @@ class OpenKfet(CachedMixin, object):
return False if self.force_close else self.raw_open
def status(self):
if (self.last_update is None or
timezone.now() - self.last_update >= self.time_unknown):
if (
self.last_update is None
or timezone.now() - self.last_update >= self.time_unknown
):
return self.UNKNOWN
return self.OPENED if self.is_open else self.CLOSED
@ -78,12 +77,10 @@ class OpenKfet(CachedMixin, object):
"""
status = self.status()
base = {
'status': status,
}
base = {"status": status}
restrict = {
'admin_status': self.admin_status(status),
'force_close': self.force_close,
"admin_status": self.admin_status(status),
"force_close": self.force_close,
}
return base, dict(base, **restrict)
@ -101,9 +98,10 @@ class OpenKfet(CachedMixin, object):
def send_ws(self):
"""Send internal state to websocket channels."""
from .consumers import OpenKfetConsumer
base, team = self._export()
OpenKfetConsumer.group_send('kfet.open.base', base)
OpenKfetConsumer.group_send('kfet.open.team', team)
OpenKfetConsumer.group_send("kfet.open.base", base)
OpenKfetConsumer.group_send("kfet.open.team", team)
kfet_open = OpenKfet()

Some files were not shown because too many files have changed in this diff Show more