Format subscription

This commit is contained in:
Pierre Brunet 2017-06-12 10:10:42 +02:00
parent cd46e099b6
commit 113c9e696b
4 changed files with 65 additions and 67 deletions

View File

@ -26,6 +26,4 @@ from django.contrib import admin
from subscription.models import Subscription from subscription.models import Subscription
admin.site.register(Subscription) admin.site.register(Subscription)

View File

@ -35,37 +35,38 @@ from core.models import User
from core.utils import get_start_of_semester from core.utils import get_start_of_semester
def validate_type(value): def validate_type(value):
if value not in settings.SITH_SUBSCRIPTIONS.keys(): if value not in settings.SITH_SUBSCRIPTIONS.keys():
raise ValidationError(_('Bad subscription type')) raise ValidationError(_('Bad subscription type'))
def validate_payment(value): def validate_payment(value):
if value not in settings.SITH_SUBSCRIPTION_PAYMENT_METHOD: if value not in settings.SITH_SUBSCRIPTION_PAYMENT_METHOD:
raise ValidationError(_('Bad payment method')) raise ValidationError(_('Bad payment method'))
class Subscription(models.Model): class Subscription(models.Model):
member = models.ForeignKey(User, related_name='subscriptions') member = models.ForeignKey(User, related_name='subscriptions')
subscription_type = models.CharField(_('subscription type'), subscription_type = models.CharField(_('subscription type'),
max_length=255, max_length=255,
choices=((k, v['name']) for k,v in sorted(settings.SITH_SUBSCRIPTIONS.items()))) choices=((k, v['name']) for k, v in sorted(settings.SITH_SUBSCRIPTIONS.items())))
subscription_start = models.DateField(_('subscription start')) subscription_start = models.DateField(_('subscription start'))
subscription_end = models.DateField(_('subscription end')) subscription_end = models.DateField(_('subscription end'))
payment_method = models.CharField(_('payment method'), payment_method = models.CharField(_('payment method'),
max_length=255, max_length=255,
choices=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD) choices=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD)
location = models.CharField(choices=settings.SITH_SUBSCRIPTION_LOCATIONS, location = models.CharField(choices=settings.SITH_SUBSCRIPTION_LOCATIONS,
max_length=20, verbose_name=_('location')) max_length=20, verbose_name=_('location'))
class Meta: class Meta:
ordering = ['subscription_start',] ordering = ['subscription_start', ]
def clean(self): def clean(self):
try: try:
for s in Subscription.objects.filter(member=self.member).exclude(pk=self.pk).all(): for s in Subscription.objects.filter(member=self.member).exclude(pk=self.pk).all():
if s.is_valid_now(): if s.is_valid_now():
raise ValidationError(_("You can not subscribe many time for the same period")) raise ValidationError(_("You can not subscribe many time for the same period"))
except: # This should not happen, because the form should have handled the data before, but sadly, it still except: # This should not happen, because the form should have handled the data before, but sadly, it still
# calls the model validation :'( # calls the model validation :'(
# TODO see SubscriptionForm's clean method # TODO see SubscriptionForm's clean method
raise ValidationError(_("Subscription error")) raise ValidationError(_("Subscription error"))
@ -74,53 +75,53 @@ class Subscription(models.Model):
super(Subscription, self).save() super(Subscription, self).save()
from counter.models import Customer from counter.models import Customer
if not Customer.objects.filter(user=self.member).exists(): if not Customer.objects.filter(user=self.member).exists():
last_id = Customer.objects.count() + 1504 # Number to keep a continuity with the old site last_id = Customer.objects.count() + 1504 # Number to keep a continuity with the old site
Customer(user=self.member, account_id=Customer.generate_account_id(last_id+1), amount=0).save() Customer(user=self.member, account_id=Customer.generate_account_id(last_id + 1), amount=0).save()
form = PasswordResetForm({'email': self.member.email}) form = PasswordResetForm({'email': self.member.email})
if form.is_valid(): if form.is_valid():
form.save(use_https=True, email_template_name='core/new_user_email.jinja', form.save(use_https=True, email_template_name='core/new_user_email.jinja',
subject_template_name='core/new_user_email_subject.jinja', from_email="ae@utbm.fr") subject_template_name='core/new_user_email_subject.jinja', from_email="ae@utbm.fr")
self.member.make_home() self.member.make_home()
if settings.IS_OLD_MYSQL_PRESENT: if settings.IS_OLD_MYSQL_PRESENT:
import MySQLdb import MySQLdb
try: # Create subscription on the old site: TODO remove me! try: # Create subscription on the old site: TODO remove me!
LOCATION = { LOCATION = {
"SEVENANS": 5, "SEVENANS": 5,
"BELFORT": 6, "BELFORT": 6,
"MONTBELIARD": 9, "MONTBELIARD": 9,
"EBOUTIC": 5, "EBOUTIC": 5,
} }
TYPE = { TYPE = {
'un-semestre' : 0, 'un-semestre': 0,
'deux-semestres' : 1, 'deux-semestres': 1,
'cursus-tronc-commun' : 2, 'cursus-tronc-commun': 2,
'cursus-branche' : 3, 'cursus-branche': 3,
'membre-honoraire' : 4, 'membre-honoraire': 4,
'assidu' : 5, 'assidu': 5,
'amicale/doceo' : 6, 'amicale/doceo': 6,
'reseau-ut' : 7, 'reseau-ut': 7,
'crous' : 8, 'crous': 8,
'sbarro/esta' : 9, 'sbarro/esta': 9,
'cursus-alternant' : 10, 'cursus-alternant': 10,
} }
PAYMENT = { PAYMENT = {
"CHECK" : 1, "CHECK": 1,
"CARD" : 2, "CARD": 2,
"CASH" : 3, "CASH": 3,
"OTHER" : 4, "OTHER": 4,
"EBOUTIC" : 5, "EBOUTIC": 5,
"OTHER" : 0, "OTHER": 0,
} }
db = MySQLdb.connect(**settings.OLD_MYSQL_INFOS) db = MySQLdb.connect(**settings.OLD_MYSQL_INFOS)
c = db.cursor() c = db.cursor()
c.execute("""INSERT INTO ae_cotisations (id_utilisateur, date_cotis, date_fin_cotis, mode_paiement_cotis, c.execute("""INSERT INTO ae_cotisations (id_utilisateur, date_cotis, date_fin_cotis, mode_paiement_cotis,
type_cotis, id_comptoir) VALUES (%s, %s, %s, %s, %s, %s)""", (self.member.id, self.subscription_start, type_cotis, id_comptoir) VALUES (%s, %s, %s, %s, %s, %s)""", (self.member.id, self.subscription_start,
self.subscription_end, PAYMENT[self.payment_method], TYPE[self.subscription_type], self.subscription_end, PAYMENT[self.payment_method], TYPE[self.subscription_type],
LOCATION[self.location])) LOCATION[self.location]))
db.commit() db.commit()
except Exception as e: except Exception as e:
with open(settings.BASE_DIR+"/subscription_fail.log", "a") as f: with open(settings.BASE_DIR + "/subscription_fail.log", "a") as f:
print("FAIL to add subscription to %s to old site" % (self.member), file=f) print("FAIL to add subscription to %s to old site" % (self.member), file=f)
print("Reason: %s" % (repr(e)), file=f) print("Reason: %s" % (repr(e)), file=f)
db.rollback() db.rollback()
@ -130,10 +131,9 @@ class Subscription(models.Model):
def __str__(self): def __str__(self):
if hasattr(self, "member") and self.member is not None: if hasattr(self, "member") and self.member is not None:
return self.member.username+' - '+str(self.pk) return self.member.username + ' - ' + str(self.pk)
else: else:
return 'No user - '+str(self.pk) return 'No user - ' + str(self.pk)
@staticmethod @staticmethod
def compute_start(d=date.today(), duration=1): def compute_start(d=date.today(), duration=1):
@ -146,7 +146,7 @@ class Subscription(models.Model):
2015-03-17 -> 2015-02-15 2015-03-17 -> 2015-02-15
2015-01-11 -> 2014-08-15 2015-01-11 -> 2014-08-15
""" """
if duration <= 2: # Sliding subscriptions for 1 or 2 semesters if duration <= 2: # Sliding subscriptions for 1 or 2 semesters
return d return d
return get_start_of_semester(d) return get_start_of_semester(d)
@ -165,12 +165,11 @@ class Subscription(models.Model):
start = Subscription.compute_start(duration=duration) start = Subscription.compute_start(duration=duration)
# This can certainly be simplified, but it works like this # This can certainly be simplified, but it works like this
try: try:
return start.replace(month=(start.month-1+6*duration)%12+1, return start.replace(month=(start.month - 1 + 6 * duration) % 12 + 1,
year=start.year+int(duration/2)+(1 if start.month > 6 and duration%2 == 1 else 0)) year=start.year + int(duration / 2) + (1 if start.month > 6 and duration % 2 == 1 else 0))
except ValueError as e: except ValueError as e:
return start.replace(day=1, month=(start.month+6*duration)%12+1, return start.replace(day=1, month=(start.month + 6 * duration) % 12 + 1,
year=start.year+int(duration/2)+(1 if start.month > 6 and duration%2 == 1 else 0)) year=start.year + int(duration / 2) + (1 if start.month > 6 and duration % 2 == 1 else 0))
def can_be_edited_by(self, user): def can_be_edited_by(self, user):
return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP) or user.is_root return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP) or user.is_root
@ -178,10 +177,15 @@ class Subscription(models.Model):
def is_valid_now(self): def is_valid_now(self):
return self.subscription_start <= date.today() and date.today() <= self.subscription_end return self.subscription_start <= date.today() and date.today() <= self.subscription_end
def guy_test(date, duration=4): def guy_test(date, duration=4):
print(str(date)+" - "+str(duration)+" -> "+str(Subscription.compute_start(date, duration))) print(str(date) + " - " + str(duration) + " -> " + str(Subscription.compute_start(date, duration)))
def bibou_test(duration, date=date.today()): def bibou_test(duration, date=date.today()):
print(str(date)+" - "+str(duration)+" -> "+str(Subscription.compute_end(duration, Subscription.compute_start(date, duration)))) print(str(date) + " - " + str(duration) + " -> " + str(Subscription.compute_end(duration, Subscription.compute_start(date, duration))))
def guy(): def guy():
guy_test(date(2015, 7, 11)) guy_test(date(2015, 7, 11))
guy_test(date(2015, 8, 11)) guy_test(date(2015, 8, 11))
@ -191,7 +195,7 @@ def guy():
guy_test(date(2015, 2, 11)) guy_test(date(2015, 2, 11))
guy_test(date(2015, 8, 17)) guy_test(date(2015, 8, 17))
guy_test(date(2015, 9, 17)) guy_test(date(2015, 9, 17))
print('='*80) print('=' * 80)
guy_test(date(2015, 7, 11), 1) guy_test(date(2015, 7, 11), 1)
guy_test(date(2015, 8, 11), 2) guy_test(date(2015, 8, 11), 2)
guy_test(date(2015, 2, 17), 3) guy_test(date(2015, 2, 17), 3)
@ -200,7 +204,7 @@ def guy():
guy_test(date(2015, 2, 11), 2) guy_test(date(2015, 2, 11), 2)
guy_test(date(2015, 8, 17), 3) guy_test(date(2015, 8, 17), 3)
guy_test(date(2015, 9, 17), 4) guy_test(date(2015, 9, 17), 4)
print('='*80) print('=' * 80)
bibou_test(1, date(2015, 2, 18)) bibou_test(1, date(2015, 2, 18))
bibou_test(2, date(2015, 2, 18)) bibou_test(2, date(2015, 2, 18))
bibou_test(3, date(2015, 2, 18)) bibou_test(3, date(2015, 2, 18))
@ -209,7 +213,7 @@ def guy():
bibou_test(2, date(2015, 9, 18)) bibou_test(2, date(2015, 9, 18))
bibou_test(3, date(2015, 9, 18)) bibou_test(3, date(2015, 9, 18))
bibou_test(4, date(2015, 9, 18)) bibou_test(4, date(2015, 9, 18))
print('='*80) print('=' * 80)
bibou_test(1, date(2000, 2, 29)) bibou_test(1, date(2000, 2, 29))
bibou_test(2, date(2000, 2, 29)) bibou_test(2, date(2000, 2, 29))
bibou_test(1, date(2000, 5, 31)) bibou_test(1, date(2000, 5, 31))
@ -219,5 +223,6 @@ def guy():
bibou_test(3) bibou_test(3)
bibou_test(4) bibou_test(4)
if __name__ == "__main__": if __name__ == "__main__":
guy() guy()

View File

@ -31,6 +31,3 @@ urlpatterns = [
url(r'^$', NewSubscription.as_view(), name='subscription'), url(r'^$', NewSubscription.as_view(), name='subscription'),
url(r'stats', SubscriptionsStatsView.as_view(), name='stats'), url(r'stats', SubscriptionsStatsView.as_view(), name='stats'),
] ]

View File

@ -26,16 +26,13 @@ from django.views.generic.edit import CreateView, FormView
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import PermissionDenied, ValidationError from django.core.exceptions import PermissionDenied, ValidationError
from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse_lazy
from django.db import IntegrityError
from django import forms from django import forms
from django.forms import Select
from django.conf import settings from django.conf import settings
from ajax_select.fields import AutoCompleteSelectField from ajax_select.fields import AutoCompleteSelectField
import random import random
from subscription.models import Subscription from subscription.models import Subscription
from core.views import CanEditMixin, CanEditPropMixin, CanViewMixin
from core.views.forms import SelectDateTime from core.views.forms import SelectDateTime
from core.models import User from core.models import User
@ -85,9 +82,9 @@ class SubscriptionForm(forms.ModelForm):
if User.objects.filter(email=cleaned_data.get("email")).first() is not None: if User.objects.filter(email=cleaned_data.get("email")).first() is not None:
self.add_error("email", ValidationError(_("A user with that email address already exists"))) self.add_error("email", ValidationError(_("A user with that email address already exists")))
else: else:
u = User(last_name = self.cleaned_data.get("last_name"), u = User(last_name=self.cleaned_data.get("last_name"),
first_name = self.cleaned_data.get("first_name"), first_name=self.cleaned_data.get("first_name"),
email = self.cleaned_data.get("email")) email=self.cleaned_data.get("email"))
u.generate_username() u.generate_username()
u.set_password(str(random.randrange(1000000, 10000000))) u.set_password(str(random.randrange(1000000, 10000000)))
u.save() u.save()
@ -102,6 +99,7 @@ class SubscriptionForm(forms.ModelForm):
raise ValidationError(_("You must either choose an existing user or create a new one properly")) raise ValidationError(_("You must either choose an existing user or create a new one properly"))
return cleaned_data return cleaned_data
class NewSubscription(CreateView): class NewSubscription(CreateView):
template_name = 'subscription/subscription.jinja' template_name = 'subscription/subscription.jinja'
form_class = SubscriptionForm form_class = SubscriptionForm
@ -119,11 +117,11 @@ class NewSubscription(CreateView):
def form_valid(self, form): def form_valid(self, form):
form.instance.subscription_start = Subscription.compute_start( form.instance.subscription_start = Subscription.compute_start(
duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration']) duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'])
form.instance.subscription_end = Subscription.compute_end( form.instance.subscription_end = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'], duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'],
start=form.instance.subscription_start start=form.instance.subscription_start
) )
return super(NewSubscription, self).form_valid(form) return super(NewSubscription, self).form_valid(form)