nk20/apps/member/models.py

301 lines
9.5 KiB
Python
Raw Normal View History

2020-02-18 20:30:26 +00:00
# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
2019-07-16 10:43:23 +00:00
# SPDX-License-Identifier: GPL-3.0-or-later
2019-09-18 12:26:42 +00:00
import datetime
2019-07-16 10:43:23 +00:00
from django.conf import settings
2020-04-01 01:42:19 +00:00
from django.contrib.auth.models import User
2020-04-01 02:20:47 +00:00
from django.core.exceptions import ValidationError
2019-07-16 10:43:23 +00:00
from django.db import models
from django.template import loader
2019-08-15 19:49:32 +00:00
from django.urls import reverse, reverse_lazy
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
2020-03-07 21:28:59 +00:00
from django.utils.translation import gettext_lazy as _
from member.tokens import account_activation_token
2020-04-01 01:42:19 +00:00
from note.models import MembershipTransaction
2019-09-18 12:26:42 +00:00
2019-07-16 10:43:23 +00:00
class Profile(models.Model):
"""
An user profile
We do not want to patch the Django Contrib :model:`auth.User`model;
2019-07-16 10:43:23 +00:00
so this model add an user profile with additional information.
2019-07-16 10:43:23 +00:00
"""
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
phone_number = models.CharField(
verbose_name=_('phone number'),
max_length=50,
blank=True,
null=True,
)
section = models.CharField(
verbose_name=_('section'),
help_text=_('e.g. "1A0", "9A♥", "SAPHIRE"'),
max_length=255,
2019-07-16 11:54:32 +00:00
blank=True,
null=True,
2019-07-16 10:43:23 +00:00
)
address = models.CharField(
verbose_name=_('address'),
max_length=255,
blank=True,
null=True,
)
paid = models.BooleanField(
verbose_name=_("paid"),
help_text=_("Tells if the user receive a salary."),
default=False,
)
email_confirmed = models.BooleanField(
verbose_name=_("email confirmed"),
2019-07-16 10:43:23 +00:00
default=False,
)
class Meta:
verbose_name = _('user profile')
verbose_name_plural = _('user profile')
2020-03-11 16:10:16 +00:00
indexes = [models.Index(fields=['user'])]
2019-07-16 10:43:23 +00:00
2019-08-11 22:30:29 +00:00
def get_absolute_url(self):
2020-03-07 21:28:59 +00:00
return reverse('user_detail', args=(self.pk,))
2020-02-18 11:31:15 +00:00
def send_email_validation_link(self):
subject = "Activate your Note Kfet account"
message = loader.render_to_string('registration/account_activation_email.html',
{
'user': self.user,
'domain': "nk20.ynerant.fr",
'site_name': "La Note Kfet",
'protocol': 'https',
'token': account_activation_token.make_token(self.user),
'uid': urlsafe_base64_encode(force_bytes(self.user.pk)).decode('UTF-8'),
})
self.user.email_user(subject, message)
2019-07-16 10:43:23 +00:00
class Club(models.Model):
"""
A club is a group of people, whose membership is handle by their
:model:`member.Membership`, and gives access to right defined by a :model:`member.Role`.
2019-07-16 10:43:23 +00:00
"""
name = models.CharField(
2019-07-16 13:17:57 +00:00
verbose_name=_('name'),
2019-07-16 10:43:23 +00:00
max_length=255,
2019-07-16 13:17:57 +00:00
unique=True,
2019-07-16 10:43:23 +00:00
)
email = models.EmailField(
verbose_name=_('email'),
)
parent_club = models.ForeignKey(
'self',
null=True,
blank=True,
on_delete=models.PROTECT,
verbose_name=_('parent club'),
)
2019-07-16 10:43:23 +00:00
# Memberships
2020-03-31 14:22:11 +00:00
# When set to False, the membership system won't be used.
# Useful to create notes for activities or departments.
require_memberships = models.BooleanField(
default=True,
verbose_name=_("require memberships"),
2020-03-31 21:54:14 +00:00
help_text=_("Uncheck if this club don't require memberships."),
2020-03-31 14:22:11 +00:00
)
membership_fee_paid = models.PositiveIntegerField(
2020-03-31 14:22:11 +00:00
default=0,
verbose_name=_('membership fee (paid students)'),
)
membership_fee_unpaid = models.PositiveIntegerField(
default=0,
verbose_name=_('membership fee (unpaid students)'),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
2020-04-01 01:42:19 +00:00
membership_duration = models.PositiveIntegerField(
2020-03-31 14:22:11 +00:00
blank=True,
2019-07-16 10:43:23 +00:00
null=True,
verbose_name=_('membership duration'),
2020-03-31 21:54:14 +00:00
help_text=_('The longest time (in days) a membership can last '
2019-07-16 10:59:11 +00:00
'(NULL = infinite).'),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
membership_start = models.DateField(
2020-03-31 14:22:11 +00:00
blank=True,
2019-07-16 10:43:23 +00:00
null=True,
verbose_name=_('membership start'),
2019-07-16 10:59:11 +00:00
help_text=_('How long after January 1st the members can renew '
'their membership.'),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
membership_end = models.DateField(
2020-03-31 14:22:11 +00:00
blank=True,
2019-07-16 10:43:23 +00:00
null=True,
verbose_name=_('membership end'),
2019-07-16 10:59:11 +00:00
help_text=_('How long the membership can last after January 1st '
'of the next year after members can renew their '
'membership.'),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
def update_membership_dates(self):
"""
This function is called each time the club detail view is displayed.
Update the year of the membership dates.
"""
if not self.membership_start:
return
2020-03-31 21:54:14 +00:00
today = datetime.date.today()
if (today - self.membership_start).days >= 365:
self.membership_start = datetime.date(self.membership_start.year + 1,
self.membership_start.month, self.membership_start.day)
self.membership_end = datetime.date(self.membership_end.year + 1,
self.membership_end.month, self.membership_end.day)
self.save(force_update=True)
2020-03-31 14:22:11 +00:00
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if not self.require_memberships:
self.membership_fee_paid = 0
self.membership_fee_unpaid = 0
2020-03-31 14:22:11 +00:00
self.membership_duration = None
self.membership_start = None
self.membership_end = None
super().save(force_insert, force_update, update_fields)
2019-07-16 11:50:05 +00:00
class Meta:
verbose_name = _("club")
verbose_name_plural = _("clubs")
2019-07-16 13:17:57 +00:00
def __str__(self):
return self.name
2019-08-11 21:25:27 +00:00
def get_absolute_url(self):
2020-03-07 21:28:59 +00:00
return reverse_lazy('member:club_detail', args=(self.pk,))
2019-08-11 21:25:27 +00:00
2019-07-16 10:43:23 +00:00
class Role(models.Model):
"""
Role that an :model:`auth.User` can have in a :model:`member.Club`
2019-07-16 10:43:23 +00:00
"""
name = models.CharField(
verbose_name=_('name'),
max_length=255,
2019-07-16 13:17:57 +00:00
unique=True,
2019-07-16 10:43:23 +00:00
)
class Meta:
verbose_name = _('role')
verbose_name_plural = _('roles')
2020-02-04 00:18:03 +00:00
def __str__(self):
return str(self.name)
2019-07-16 10:43:23 +00:00
class Membership(models.Model):
2019-08-11 15:52:41 +00:00
"""
Register the membership of a user to a club, including roles and membership duration.
2019-08-11 15:52:41 +00:00
"""
2019-07-16 10:43:23 +00:00
user = models.ForeignKey(
2020-04-01 01:42:19 +00:00
User,
2020-02-18 11:31:15 +00:00
on_delete=models.PROTECT,
2020-04-01 16:47:56 +00:00
verbose_name=_("user"),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
2019-07-16 10:43:23 +00:00
club = models.ForeignKey(
Club,
2020-02-18 11:31:15 +00:00
on_delete=models.PROTECT,
2020-04-01 16:47:56 +00:00
verbose_name=_("club"),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
roles = models.ManyToManyField(
2019-07-16 10:43:23 +00:00
Role,
2020-04-01 01:42:19 +00:00
verbose_name=_("roles"),
2019-07-16 10:43:23 +00:00
)
2020-03-31 21:54:14 +00:00
2019-07-16 10:43:23 +00:00
date_start = models.DateField(
verbose_name=_('membership starts on'),
)
2020-03-31 21:54:14 +00:00
2019-07-16 10:43:23 +00:00
date_end = models.DateField(
verbose_name=_('membership ends on'),
null=True,
)
2020-03-31 21:54:14 +00:00
2019-07-16 10:43:23 +00:00
fee = models.PositiveIntegerField(
verbose_name=_('fee'),
)
2019-09-18 12:26:42 +00:00
def valid(self):
2019-09-18 14:41:01 +00:00
if self.date_end is not None:
2020-03-07 12:12:17 +00:00
return self.date_start.toordinal() <= datetime.datetime.now().toordinal() < self.date_end.toordinal()
2019-09-18 14:41:01 +00:00
else:
2020-03-07 12:12:17 +00:00
return self.date_start.toordinal() <= datetime.datetime.now().toordinal()
2019-09-18 12:26:42 +00:00
def save(self, *args, **kwargs):
if self.club.parent_club is not None:
2020-03-31 21:54:14 +00:00
if not Membership.objects.filter(user=self.user, club=self.club.parent_club).exists():
2020-04-01 01:42:19 +00:00
raise ValidationError(_('User is not a member of the parent club') + ' ' + self.club.parent_club.name)
2020-03-31 21:54:14 +00:00
created = not self.pk
if created:
2020-04-01 01:42:19 +00:00
if Membership.objects.filter(
user=self.user,
club=self.club,
date_start__lte=self.date_start,
date_end__gte=self.date_start,
2020-04-01 01:42:19 +00:00
).exists():
raise ValidationError(_('User is already a member of the club'))
if self.user.profile.paid:
self.fee = self.club.membership_fee_paid
else:
self.fee = self.club.membership_fee_unpaid
2020-04-01 16:47:56 +00:00
2020-04-01 01:42:19 +00:00
if self.club.membership_duration is not None:
self.date_end = self.date_start + datetime.timedelta(days=self.club.membership_duration)
else:
self.date_end = self.date_start + datetime.timedelta(days=424242)
2020-04-01 01:42:19 +00:00
if self.club.membership_end is not None and self.date_end > self.club.membership_end:
2020-03-31 21:54:14 +00:00
self.date_end = self.club.membership_end
super().save(*args, **kwargs)
self.make_transaction()
def make_transaction(self):
2020-04-01 02:20:47 +00:00
if not self.fee or MembershipTransaction.objects.filter(membership=self).exists():
return
if self.fee:
transaction = MembershipTransaction(
membership=self,
source=self.user.note,
destination=self.club.note,
quantity=1,
amount=self.fee,
2020-04-01 02:20:47 +00:00
reason="Adhésion " + self.club.name,
)
transaction._force_save = True
transaction.save(force_insert=True)
2020-04-01 01:42:19 +00:00
2020-04-01 02:20:47 +00:00
def __str__(self):
return _("Membership of {user} for the club {club}").format(user=self.user.username, club=self.club.name, )
2019-07-16 10:43:23 +00:00
class Meta:
verbose_name = _('membership')
verbose_name_plural = _('memberships')
2020-03-11 16:10:16 +00:00
indexes = [models.Index(fields=['user'])]