Big refactor: remove Subscriber class

This commit is contained in:
Skia 2016-12-10 01:58:30 +01:00
parent 0d4b697079
commit 28431ec9be
19 changed files with 51 additions and 109 deletions

View File

@ -8,7 +8,6 @@ from django.core.urlresolvers import reverse
from django.utils import timezone
from core.models import User, MetaGroup, Group, SithFile
from subscription.models import Subscriber
# Create your models here.
@ -120,7 +119,7 @@ class Club(models.Model):
"""
Method to see if that object can be seen by the given user
"""
sub = Subscriber.objects.filter(pk=user.pk).first()
sub = User.objects.filter(pk=user.pk).first()
if sub is None:
return False
return sub.is_subscribed()
@ -151,7 +150,7 @@ class Membership(models.Model):
description = models.CharField(_('description'), max_length=128, null=False, blank=True)
def clean(self):
sub = Subscriber.objects.filter(pk=self.user.pk).first()
sub = User.objects.filter(pk=self.user.pk).first()
if sub is None or not sub.is_subscribed():
raise ValidationError(_('User must be subscriber to take part to a club'))
if Membership.objects.filter(user=self.user).filter(club=self.club).filter(end_date=None).exists():

View File

@ -12,7 +12,7 @@ from django.contrib.sites.models import Site
from core.models import Group, User, Page, PageRev, SithFile
from accounting.models import GeneralJournal, BankAccount, ClubAccount, Operation, AccountingType, Company
from club.models import Club, Membership
from subscription.models import Subscription, Subscriber
from subscription.models import Subscription
from counter.models import Customer, ProductType, Product, Counter
class Command(BaseCommand):
@ -201,7 +201,7 @@ Cette page vise à documenter la syntaxe *Markdown* utilisée sur le site.
# Subscription
## Root
s = Subscription(member=Subscriber.objects.filter(pk=root.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
s = Subscription(member=User.objects.filter(pk=root.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0])
s.subscription_start = s.compute_start()
s.subscription_end = s.compute_end(
@ -209,7 +209,7 @@ Cette page vise à documenter la syntaxe *Markdown* utilisée sur le site.
start=s.subscription_start)
s.save()
## Skia
s = Subscription(member=Subscriber.objects.filter(pk=skia.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
s = Subscription(member=User.objects.filter(pk=skia.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0])
s.subscription_start = s.compute_start()
s.subscription_end = s.compute_end(
@ -217,7 +217,7 @@ Cette page vise à documenter la syntaxe *Markdown* utilisée sur le site.
start=s.subscription_start)
s.save()
## Comptable
s = Subscription(member=Subscriber.objects.filter(pk=comptable.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
s = Subscription(member=User.objects.filter(pk=comptable.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0])
s.subscription_start = s.compute_start()
s.subscription_end = s.compute_end(
@ -225,15 +225,15 @@ Cette page vise à documenter la syntaxe *Markdown* utilisée sur le site.
start=s.subscription_start)
s.save()
## Richard
s = Subscription(member=Subscriber.objects.filter(pk=r.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
s = Subscription(member=User.objects.filter(pk=r.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0])
s.subscription_start = s.compute_start()
s.subscription_end = s.compute_end(
duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]['duration'],
start=s.subscription_start)
s.save()
## Subscriber
s = Subscription(member=Subscriber.objects.filter(pk=subscriber.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
## User
s = Subscription(member=User.objects.filter(pk=subscriber.pk).first(), subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0])
s.subscription_start = s.compute_start()
s.subscription_end = s.compute_end(

View File

@ -195,6 +195,10 @@ class User(AbstractBaseUser):
def to_dict(self):
return self.__dict__
def is_subscribed(self):
s = self.subscriptions.last()
return s.is_valid_now() if s is not None else False
def is_in_group(self, group_name):
"""If the user is in the group passed in argument (as string or by id)"""
group_id = 0
@ -208,15 +212,7 @@ class User(AbstractBaseUser):
if group_id == settings.SITH_GROUP_PUBLIC_ID:
return True
if group_name == settings.SITH_MAIN_MEMBERS_GROUP: # We check the subscription if asked
if 'subscription' in settings.INSTALLED_APPS:
from subscription.models import Subscriber
s = Subscriber.objects.filter(pk=self.pk).first()
if s is not None and s.is_subscribed():
return True
else:
return False
else:
return False
return self.is_subscribed()
if group_name[-len(settings.SITH_BOARD_SUFFIX):] == settings.SITH_BOARD_SUFFIX:
from club.models import Club
name = group_name[:-len(settings.SITH_BOARD_SUFFIX)]

View File

@ -35,15 +35,15 @@
{%- endmacro %}
{% macro user_subscription(user) %}
{% trans subscription_end=get_subscriber(user).subscriptions.last().subscription_end %}Subscribed until {{ subscription_end }}{% endtrans %}<br/>
{% trans subscription_end=user.subscriptions.last().subscription_end %}Subscribed until {{ subscription_end }}{% endtrans %}<br/>
{% trans %}Account number: {% endtrans %}{{ user.customer.account_id }}<br/>
{%- endmacro %}
{% macro show_slots(user) %}
{% if get_subscriber(user).slots.filter(start_date__gte=timezone.now()).exists() %}
{% if user.slots.filter(start_date__gte=timezone.now()).exists() %}
<h5>{% trans %}Slot{% endtrans %}</h5>
<ul>
{% for i in get_subscriber(user).slots.filter(start_date__gte=timezone.now().replace(tzinfo=None)).all() %}
{% for i in user.slots.filter(start_date__gte=timezone.now().replace(tzinfo=None)).all() %}
<li>{{ i.get_type_display() }} - {{i.machine.launderette }}, {{ i.start_date|date("l j") }} : {{ i.start_date|time(DATETIME_FORMAT) }}</li>
{% endfor %}
</ul>
@ -51,10 +51,10 @@
{% endmacro %}
{% macro show_tokens(user) %}
{% if get_subscriber(user).tokens.exists() %}
{% if user.tokens.exists() %}
<h5>{% trans %}Tokens{% endtrans %}</h5>
<ul>
{% for i in get_subscriber(user).tokens.all() %}
{% for i in user.tokens.all() %}
<li>{{ i }}</li>
{% endfor %}
</ul>
@ -65,4 +65,4 @@
{% if user == profile or user.is_root or user.is_board_member %}
<a href="{{ url("core:user_godfathers_delete", user_id=profile.id, godfather_id=godfather.id, is_father=is_father) }}">{% trans %}Delete{% endtrans %}</a>
{% endif %}
{% endmacro %}
{% endmacro %}

View File

@ -54,7 +54,7 @@
{% if user.memberships.filter(end_date=None).exists() or user.is_in_group(settings.SITH_MAIN_BOARD_GROUP) or user == profile %}
{# if the user is member of a club, he can view the subscription state #}
<p>
{% if get_subscriber(profile).is_subscribed() %}
{% if profile.is_subscribed() %}
{% if user == profile or user.is_root or user.is_board_member %}
{{ user_subscription(profile) }}
{% endif %}

View File

@ -139,7 +139,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='counter',
name='sellers',
field=models.ManyToManyField(related_name='counters', to='subscription.Subscriber', blank=True, verbose_name='sellers'),
field=models.ManyToManyField(related_name='counters', to='core.User', blank=True, verbose_name='sellers'),
),
migrations.AddField(
model_name='counter',

View File

@ -16,8 +16,7 @@ import datetime
from club.models import Club
from accounting.models import CurrencyField
from core.models import Group, User, Notification
from subscription.models import Subscriber, Subscription
from subscription.views import get_subscriber
from subscription.models import Subscription
class Customer(models.Model):
"""
@ -134,7 +133,7 @@ class Counter(models.Model):
type = models.CharField(_('counter type'),
max_length=255,
choices=[('BAR',_('Bar')), ('OFFICE',_('Office')), ('EBOUTIC',_('Eboutic'))])
sellers = models.ManyToManyField(Subscriber, verbose_name=_('sellers'), related_name='counters', blank=True)
sellers = models.ManyToManyField(User, verbose_name=_('sellers'), related_name='counters', blank=True)
edit_groups = models.ManyToManyField(Group, related_name="editable_counters", blank=True)
view_groups = models.ManyToManyField(Group, related_name="viewable_counters", blank=True)
token = models.CharField(_('token'), max_length=30, null=True, blank=True)
@ -164,7 +163,7 @@ class Counter(models.Model):
def can_be_viewed_by(self, user):
if self.type == "BAR" or self.type == "EBOUTIC":
return True
sub = get_subscriber(request.user)
sub = request.user
return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP) or sub in self.sellers
def gen_token(self):
@ -349,7 +348,7 @@ class Selling(models.Model):
self.customer.save()
self.is_validated = True
if self.product and self.product.id == settings.SITH_PRODUCT_SUBSCRIPTION_ONE_SEMESTER:
s = Subscriber.objects.filter(id=self.customer.user.id).first()
s = User.objects.filter(id=self.customer.user.id).first()
sub = Subscription(
member=s,
subscription_type='un-semestre',
@ -364,7 +363,7 @@ class Selling(models.Model):
start=sub.subscription_start)
sub.save()
elif self.product and self.product.id == settings.SITH_PRODUCT_SUBSCRIPTION_TWO_SEMESTERS:
s = Subscriber.objects.filter(id=self.customer.user.id).first()
s = User.objects.filter(id=self.customer.user.id).first()
sub = Subscription(
member=s,
subscription_type='deux-semestres',

View File

@ -22,8 +22,7 @@ from ajax_select import make_ajax_form, make_ajax_field
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin, TabedViewMixin
from core.views.forms import SelectUser, LoginForm, SelectDate, SelectDateTime
from core.models import User
from subscription.models import Subscriber, Subscription
from subscription.views import get_subscriber
from subscription.models import Subscription
from counter.models import Counter, Customer, Product, Selling, Refilling, ProductType, CashRegisterSummary, CashRegisterSummaryItem, Eticket
from accounting.models import CurrencyField
@ -49,7 +48,7 @@ class GetUserForm(forms.Form):
cus = Customer.objects.filter(account_id__iexact=cleaned_data['code']).first()
elif cleaned_data['id'] is not None:
cus = Customer.objects.filter(user=cleaned_data['id']).first()
sub = get_subscriber(cus.user) if cus is not None else None
sub = cus.user if cus is not None else None
if (cus is None or sub is None or not sub.subscriptions.last() or
(date.today() - sub.subscriptions.last().subscription_end) > timedelta(days=90)):
raise forms.ValidationError(_("User not found"))

View File

@ -5,7 +5,7 @@ from django.conf import settings
from accounting.models import CurrencyField
from counter.models import Counter, Product, Customer, Selling, Refilling
from core.models import User
from subscription.models import Subscription, Subscriber
from subscription.models import Subscription
class Basket(models.Model):
"""

View File

@ -57,7 +57,7 @@ class Migration(migrations.Migration):
('type', models.CharField(choices=[('WASHING', 'Washing'), ('DRYING', 'Drying')], max_length=10, verbose_name='type')),
('borrow_date', models.DateTimeField(null=True, verbose_name='borrow date', blank=True)),
('launderette', models.ForeignKey(verbose_name='launderette', to='launderette.Launderette', related_name='tokens')),
('user', models.ForeignKey(null=True, related_name='tokens', verbose_name='user', to='subscription.Subscriber', blank=True)),
('user', models.ForeignKey(null=True, related_name='tokens', verbose_name='user', to='core.User', blank=True)),
],
options={
'verbose_name': 'Token',
@ -72,7 +72,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='slot',
name='user',
field=models.ForeignKey(verbose_name='user', to='subscription.Subscriber', related_name='slots'),
field=models.ForeignKey(verbose_name='user', to='core.User', related_name='slots'),
),
migrations.AlterUniqueTogether(
name='token',

View File

@ -5,8 +5,6 @@ from django.core.urlresolvers import reverse
from counter.models import Counter, Product
from core.models import User
from subscription.models import Subscriber
from subscription.views import get_subscriber
from club.models import Club
# Create your models here.
@ -86,7 +84,7 @@ class Token(models.Model):
launderette = models.ForeignKey(Launderette, related_name='tokens', verbose_name=_('launderette'))
type = models.CharField(_('type'), max_length=10, choices=settings.SITH_LAUNDERETTE_MACHINE_TYPES)
borrow_date = models.DateTimeField(_('borrow date'), null=True, blank=True)
user = models.ForeignKey(Subscriber, related_name='tokens', verbose_name=_('user'), null=True, blank=True)
user = models.ForeignKey(User, related_name='tokens', verbose_name=_('user'), null=True, blank=True)
class Meta:
verbose_name = _('Token')
@ -123,7 +121,7 @@ class Slot(models.Model):
type = models.CharField(_('type'), max_length=10, choices=settings.SITH_LAUNDERETTE_MACHINE_TYPES)
machine = models.ForeignKey(Machine, related_name='slots', verbose_name=_('machine'))
token = models.ForeignKey(Token, related_name='slots', verbose_name=_('token'), blank=True, null=True)
user = models.ForeignKey(Subscriber, related_name='slots', verbose_name=_('user'))
user = models.ForeignKey(User, related_name='slots', verbose_name=_('user'))
class Meta:
verbose_name = _('Slot')

View File

@ -20,8 +20,6 @@ from core.models import Page
from club.models import Club
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin
from launderette.models import Launderette, Token, Machine, Slot
from subscription.views import get_subscriber
from subscription.models import Subscriber
from counter.models import Counter, Customer, Selling
from counter.views import GetUserForm
@ -61,7 +59,7 @@ class LaunderetteBookView(CanViewMixin, DetailView):
if 'slot_type' in request.POST.keys():
self.slot_type = request.POST['slot_type']
if 'slot' in request.POST.keys() and request.user.is_authenticated():
self.subscriber = get_subscriber(request.user)
self.subscriber = request.user
if self.subscriber.is_subscribed():
self.date = dateparse.parse_datetime(request.POST['slot']).replace(tzinfo=pytz.UTC)
if self.slot_type == "WASHING":
@ -224,7 +222,7 @@ class LaunderetteAdminView(CanEditPropMixin, BaseFormView, DetailView):
class GetLaunderetteUserForm(GetUserForm):
def clean(self):
cleaned_data = super(GetLaunderetteUserForm, self).clean()
sub = get_subscriber(cleaned_data['user'])
sub = cleaned_data['user']
if sub.slots.all().count() <= 0:
raise forms.ValidationError(_("User has booked no slot"))
return cleaned_data
@ -272,10 +270,10 @@ class LaunderetteMainClickView(CanEditMixin, BaseFormView, DetailView):
class ClickTokenForm(forms.BaseForm):
def clean(self):
with transaction.atomic():
operator = Subscriber.objects.filter(id=self.operator_id).first()
operator = User.objects.filter(id=self.operator_id).first()
customer = Customer.objects.filter(user__id=self.subscriber_id).first()
counter = Counter.objects.filter(id=self.counter_id).first()
subscriber = get_subscriber(customer.user)
subscriber = customer.user
self.last_basket = {
'last_basket': [],
'last_customer': customer.user.get_display_name(),
@ -334,7 +332,7 @@ class LaunderetteClickView(CanEditMixin, DetailView, BaseFormView):
def get(self, request, *args, **kwargs):
"""Simple get view"""
self.customer = Customer.objects.filter(user__id=self.kwargs['user_id']).first()
self.subscriber = get_subscriber(self.customer.user)
self.subscriber = self.customer.user
self.operator = request.user
return super(LaunderetteClickView, self).get(request, *args, **kwargs)
@ -342,7 +340,7 @@ class LaunderetteClickView(CanEditMixin, DetailView, BaseFormView):
""" Handle the many possibilities of the post request """
self.object = self.get_object()
self.customer = Customer.objects.filter(user__id=self.kwargs['user_id']).first()
self.subscriber = get_subscriber(self.customer.user)
self.subscriber = self.customer.user
self.operator = request.user
return super(LaunderetteClickView, self).post(request, *args, **kwargs)

View File

@ -22,7 +22,7 @@ from django.core.files import File
from core.models import User, SithFile
from club.models import Club, Membership
from counter.models import Customer, Counter, Selling, Refilling, Product, ProductType, Permanency, Eticket
from subscription.models import Subscription, Subscriber
from subscription.models import Subscription
from eboutic.models import Invoice, InvoiceItem
from accounting.models import BankAccount, ClubAccount, GeneralJournal, Operation, AccountingType, Company, SimplifiedAccountingType, Label
from sas.models import Album, Picture, PeoplePictureRelation
@ -298,7 +298,7 @@ def migrate_subscriptions():
print("Customers deleted")
for r in cur:
try:
user = Subscriber.objects.filter(id=r['id_utilisateur']).first()
user = User.objects.filter(id=r['id_utilisateur']).first()
if user:
new = Subscription(
id=r['id_cotisation'],

View File

@ -8,7 +8,6 @@ from django.core.exceptions import PermissionDenied
from ajax_select.fields import AutoCompleteSelectField
from core.models import User
from subscription.models import Subscriber
from counter.models import Customer
def merge_users(u1, u2):
@ -40,8 +39,8 @@ def merge_users(u1, u2):
f.auto_now = False
u1.invoices.add(i)
u1.save()
s1 = Subscriber.objects.filter(id=u1.id).first()
s2 = Subscriber.objects.filter(id=u2.id).first()
s1 = User.objects.filter(id=u1.id).first()
s2 = User.objects.filter(id=u2.id).first()
for s in s2.subscriptions.all():
s1.subscriptions.add(s)
s1.save()

View File

@ -111,7 +111,6 @@ TEMPLATES = [
"can_edit_prop": "core.views.can_edit_prop",
"can_edit": "core.views.can_edit",
"can_view": "core.views.can_view",
"get_subscriber": "subscription.views.get_subscriber",
"settings": "sith.settings",
"Launderette": "launderette.models.Launderette",
"Counter": "counter.models.Counter",

View File

@ -1,8 +1,7 @@
from django.contrib import admin
from subscription.models import Subscriber, Subscription
from subscription.models import Subscription
admin.site.register(Subscriber)
admin.site.register(Subscription)

View File

@ -26,21 +26,9 @@ class Migration(migrations.Migration):
'ordering': ['subscription_start'],
},
),
migrations.CreateModel(
name='Subscriber',
fields=[
],
options={
'proxy': True,
},
bases=('core.user',),
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.AddField(
model_name='subscription',
name='member',
field=models.ForeignKey(to='subscription.Subscriber', related_name='subscriptions'),
field=models.ForeignKey(to='core.User', related_name='subscriptions'),
),
]

View File

@ -19,36 +19,8 @@ def validate_payment(value):
if value not in settings.SITH_SUBSCRIPTION_PAYMENT_METHOD:
raise ValidationError(_('Bad payment method'))
class Subscriber(User):
class Meta:
proxy = True
def is_subscribed(self):
s = self.subscriptions.last()
return s.is_valid_now() if s is not None else False
def save(self):
create = False
if not self.id:
create = True
super(Subscriber, self).save()
if create and settings.IS_OLD_MYSQL_PRESENT:
try: # Create user on the old site: TODO remove me!
import MySQLdb
db = MySQLdb.connect(**settings.OLD_MYSQL_INFOS)
c = db.cursor()
c.execute("""INSERT INTO utilisateurs (id_utilisateur, nom_utl, prenom_utl, email_utl, hash_utl, ae_utl) VALUES
(%s, %s, %s, %s, %s, %s)""", (self.id, self.last_name, self.first_name, self.email, "valid", "1"))
db.commit()
except Exception as e:
with open(settings.BASE_DIR+"/user_fail.log", "a") as f:
print("FAIL to add user %s (%s %s - %s) to old site" % (self.id, self.first_name.encode('utf-8'),
self.last_name.encode('utf-8'), self.email), file=f)
print("Reason: %s" % (repr(e)), file=f)
db.rollback()
class Subscription(models.Model):
member = models.ForeignKey(Subscriber, related_name='subscriptions')
member = models.ForeignKey(User, related_name='subscriptions')
subscription_type = models.CharField(_('subscription type'),
max_length=255,
choices=((k, v['name']) for k,v in sorted(settings.SITH_SUBSCRIPTIONS.items())))

View File

@ -11,14 +11,10 @@ from django.conf import settings
from ajax_select.fields import AutoCompleteSelectField
import random
from subscription.models import Subscriber, Subscription
from subscription.models import Subscription
from core.views import CanEditMixin, CanEditPropMixin, CanViewMixin
from core.models import User
def get_subscriber(user):
s = Subscriber.objects.filter(pk=user.pk).first()
return s
class SubscriptionForm(forms.ModelForm):
class Meta:
model = Subscription
@ -38,7 +34,7 @@ class SubscriptionForm(forms.ModelForm):
def clean_member(self):
subscriber = self.cleaned_data.get("member")
if subscriber:
subscriber = Subscriber.objects.filter(id=subscriber.id).first()
subscriber = User.objects.filter(id=subscriber.id).first()
return subscriber
def clean(self):
@ -50,10 +46,10 @@ class SubscriptionForm(forms.ModelForm):
self.errors.pop("member", None)
if self.errors:
return cleaned_data
if Subscriber.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")))
else:
u = Subscriber(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"),
email = self.cleaned_data.get("email"))
u.generate_username()