nk20/apps/note/models/notes.py

250 lines
7.3 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
import unicodedata
2019-07-24 20:03:07 +00:00
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
2019-07-16 10:43:23 +00:00
from django.db import models
from django.utils.translation import gettext_lazy as _
2019-07-17 09:17:50 +00:00
from polymorphic.models import PolymorphicModel
2020-03-07 21:28:59 +00:00
2019-07-16 10:43:23 +00:00
"""
Defines each note types
"""
2019-07-17 09:17:50 +00:00
class Note(PolymorphicModel):
2019-07-16 10:43:23 +00:00
"""
Gives transactions capabilities. Note is a Polymorphic Model, use as based
for the models :model:`note.NoteUser` and :model:`note.NoteClub`.
A Note principaly store the actual balance of someone/some club.
A Note can be searched find throught an :model:`note.Alias`
2019-07-16 10:43:23 +00:00
"""
balance = models.IntegerField(
verbose_name=_('account balance'),
help_text=_('in centimes, money credited for this instance'),
default=0,
2019-07-16 10:43:23 +00:00
)
2020-03-07 21:28:59 +00:00
last_negative = models.DateTimeField(
2020-02-25 13:15:36 +00:00
verbose_name=_('last negative date'),
help_text=_('last time the balance was negative'),
null=True,
blank=True,
)
2019-07-16 10:43:23 +00:00
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this note should be treated as active. '
2020-02-18 11:31:15 +00:00
'Unselect this instead of deleting notes.'),
2019-07-16 10:43:23 +00:00
)
2019-07-16 13:22:38 +00:00
display_image = models.ImageField(
verbose_name=_('display image'),
max_length=255,
2020-03-04 15:34:12 +00:00
blank=False,
null=False,
upload_to='pic/',
2020-03-03 13:24:07 +00:00
default='pic/default.png'
2019-07-16 13:22:38 +00:00
)
2019-07-17 10:14:23 +00:00
created_at = models.DateTimeField(
verbose_name=_('created at'),
auto_now_add=True,
)
2019-07-16 10:43:23 +00:00
2019-07-16 11:50:05 +00:00
class Meta:
verbose_name = _("note")
verbose_name_plural = _("notes")
2019-07-24 20:03:07 +00:00
def pretty(self):
"""
:return: Pretty name of this note
"""
2019-07-24 20:40:31 +00:00
return str(self)
2019-07-24 20:03:07 +00:00
pretty.short_description = _('Note')
def save(self, *args, **kwargs):
"""
Save note with it's alias (called in polymorphic children)
"""
aliases = Alias.objects.filter(name=str(self))
if aliases.exists():
# Alias exists, so check if it is linked to this note
if aliases.first().note != self:
2020-02-23 12:46:25 +00:00
raise ValidationError(_('This alias is already taken.'),
code="same_alias")
2019-07-24 20:03:07 +00:00
# Save note
super().save(*args, **kwargs)
else:
# Alias does not exist yet, so check if it can exist
a = Alias(name=str(self))
a.clean()
# Save note and alias
super().save(*args, **kwargs)
a.note = self
a.save(force_insert=True)
2019-07-24 20:40:31 +00:00
def clean(self, *args, **kwargs):
"""
Verify alias (simulate save)
"""
2020-02-18 11:31:15 +00:00
aliases = Alias.objects.filter(
normalized_name=Alias.normalize(str(self)))
2019-07-24 20:40:31 +00:00
if aliases.exists():
# Alias exists, so check if it is linked to this note
if aliases.first().note != self:
2020-02-23 12:46:25 +00:00
raise ValidationError(_('This alias is already taken.'),
2020-03-07 21:28:59 +00:00
code="same_alias", )
2019-07-24 20:40:31 +00:00
else:
# Alias does not exist yet, so check if it can exist
a = Alias(name=str(self))
a.clean()
2019-07-16 10:43:23 +00:00
class NoteUser(Note):
"""
A :model:`note.Note` associated to an unique :model:`auth.User`.
2019-07-16 10:43:23 +00:00
"""
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name='note',
2019-07-17 10:14:23 +00:00
verbose_name=_('user'),
2019-07-16 10:43:23 +00:00
)
class Meta:
verbose_name = _("one's note")
verbose_name_plural = _("users note")
2019-07-17 09:17:50 +00:00
def __str__(self):
2019-07-24 20:03:07 +00:00
return str(self.user)
2019-07-17 09:17:50 +00:00
2019-07-24 20:03:07 +00:00
def pretty(self):
return _("%(user)s's note") % {'user': str(self.user)}
2019-07-19 13:00:44 +00:00
2019-07-16 10:43:23 +00:00
class NoteClub(Note):
"""
A :model:`note.Note` associated to an unique :model:`member.Club`
2019-07-16 10:43:23 +00:00
"""
2019-07-16 12:38:52 +00:00
club = models.OneToOneField(
2019-07-16 10:43:23 +00:00
'member.Club',
on_delete=models.PROTECT,
related_name='note',
2019-07-17 10:14:23 +00:00
verbose_name=_('club'),
2019-07-16 10:43:23 +00:00
)
class Meta:
verbose_name = _("club note")
verbose_name_plural = _("clubs notes")
2019-07-17 10:14:23 +00:00
def __str__(self):
2019-07-24 20:03:07 +00:00
return str(self.club)
2019-07-17 10:14:23 +00:00
2019-07-24 20:03:07 +00:00
def pretty(self):
return _("Note of %(club)s club") % {'club': str(self.club)}
2019-07-19 13:00:44 +00:00
2019-07-16 10:43:23 +00:00
class NoteSpecial(Note):
"""
A :model:`note.Note` for special accounts, where real money enter or leave the system
2019-07-16 10:43:23 +00:00
- bank check
- credit card
- bank transfer
- cash
- refund
This Type of Note is not associated to a :model:`auth.User` or :model:`member.Club` .
2019-07-16 10:43:23 +00:00
"""
special_type = models.CharField(
verbose_name=_('type'),
max_length=255,
unique=True,
)
2019-07-16 11:50:05 +00:00
class Meta:
verbose_name = _("special note")
verbose_name_plural = _("special notes")
2019-07-17 10:14:23 +00:00
def __str__(self):
return self.special_type
2019-07-16 10:43:23 +00:00
class Alias(models.Model):
"""
points toward a :model:`note.NoteUser` or :model;`note.NoteClub` instance.
Alias are unique, but a :model:`note.NoteUser` or :model:`note.NoteClub` can
have multiples aliases.
Aliases name are also normalized, two differents :model:`note.Note` can not
have the same normalized alias, to avoid confusion when referring orally to
it.
2019-07-16 10:43:23 +00:00
"""
name = models.CharField(
verbose_name=_('name'),
max_length=255,
unique=True,
validators=[
RegexValidator(
regex=settings.ALIAS_VALIDATOR_REGEX,
2020-02-18 11:31:15 +00:00
message=_('Invalid alias'),
)
2020-02-18 11:31:15 +00:00
] if settings.ALIAS_VALIDATOR_REGEX else [],
)
normalized_name = models.CharField(
max_length=255,
unique=True,
default='',
2020-02-18 11:31:15 +00:00
editable=False,
2019-07-16 10:43:23 +00:00
)
note = models.ForeignKey(
Note,
on_delete=models.PROTECT,
)
2019-07-16 11:50:05 +00:00
class Meta:
verbose_name = _("alias")
verbose_name_plural = _("aliases")
indexes = [
models.Index(fields=['name']),
models.Index(fields=['normalized_name']),
]
2019-07-17 11:03:10 +00:00
def __str__(self):
return self.name
@staticmethod
def normalize(string):
"""
Normalizes a string: removes most diacritics and does casefolding
"""
return ''.join(
2020-02-18 11:31:15 +00:00
char for char in unicodedata.normalize('NFKD', string.casefold())
2019-07-24 20:03:07 +00:00
if all(not unicodedata.category(char).startswith(cat)
2020-02-18 11:31:15 +00:00
for cat in {'M', 'P', 'Z', 'C'})).casefold()
def clean(self):
normalized_name = Alias.normalize(self.name)
if len(normalized_name) >= 255:
2020-02-23 12:46:25 +00:00
raise ValidationError(_('Alias is too long.'),
code='alias_too_long')
try:
2020-02-23 12:46:25 +00:00
sim_alias = Alias.objects.get(normalized_name=normalized_name)
if self != sim_alias:
2020-03-01 12:42:22 +00:00
raise ValidationError(_('An alias with a similar name already exists: {} '.format(sim_alias)),
2020-03-07 21:28:59 +00:00
code="same_alias"
)
except Alias.DoesNotExist:
pass
2020-03-01 12:42:22 +00:00
self.normalized_name = normalized_name
2020-03-07 21:28:59 +00:00
def delete(self, using=None, keep_parents=False):
if self.name == str(self.note):
2020-02-23 12:46:25 +00:00
raise ValidationError(_("You can't delete your main alias."),
code="cant_delete_main_alias")
return super().delete(using, keep_parents)