Aller au contenu

Views

Club

Bases: Model

The Club class, made as a tree to allow nice tidy organization.

check_loop()

Raise a validation error when a loop is found within the parent list.

Source code in club/models.py
def check_loop(self):
    """Raise a validation error when a loop is found within the parent list."""
    objs = []
    cur = self
    while cur.parent is not None:
        if cur in objs:
            raise ValidationError(_("You can not make loops in clubs"))
        objs.append(cur)
        cur = cur.parent

is_owned_by(user)

Method to see if that object can be super edited by the given user.

Source code in club/models.py
def is_owned_by(self, user):
    """Method to see if that object can be super edited by the given user."""
    if user.is_anonymous:
        return False
    return user.is_board_member

can_be_edited_by(user)

Method to see if that object can be edited by the given user.

Source code in club/models.py
def can_be_edited_by(self, user):
    """Method to see if that object can be edited by the given user."""
    return self.has_rights_in_club(user)

can_be_viewed_by(user)

Method to see if that object can be seen by the given user.

Source code in club/models.py
def can_be_viewed_by(self, user):
    """Method to see if that object can be seen by the given user."""
    sub = User.objects.filter(pk=user.pk).first()
    if sub is None:
        return False
    return sub.was_subscribed

get_membership_for(user)

Return the current membership the given user.

Note

The result is cached.

Source code in club/models.py
def get_membership_for(self, user: User) -> Membership | None:
    """Return the current membership the given user.

    Note:
        The result is cached.
    """
    if user.is_anonymous:
        return None
    membership = cache.get(f"membership_{self.id}_{user.id}")
    if membership == "not_member":
        return None
    if membership is None:
        membership = self.members.filter(user=user, end_date=None).first()
        if membership is None:
            cache.set(f"membership_{self.id}_{user.id}", "not_member")
        else:
            cache.set(f"membership_{self.id}_{user.id}", membership)
    return membership

Page

Bases: Model

The page class to build a Wiki Each page may have a parent and it's URL is of the form my.site/page/// It has an ID field, but don't use it, since it's only there for DB part, and because compound primary key is awkward! Prefere querying pages with Page.get_page_by_full_name().

Be careful with the _full_name attribute: this field may not be valid until you call save(). It's made for fast query, but don't rely on it when playing with a Page object, use get_full_name() instead!

save(*args, **kwargs)

Performs some needed actions before and after saving a page in database.

Source code in core/models.py
def save(self, *args, **kwargs):
    """Performs some needed actions before and after saving a page in database."""
    locked = kwargs.pop("force_lock", False)
    if not locked:
        locked = self.is_locked()
    if not locked:
        raise NotLocked("The page is not locked and thus can not be saved")
    self.full_clean()
    if not self.id:
        super().save(
            *args, **kwargs
        )  # Save a first time to correctly set _full_name
    # This reset the _full_name just before saving to maintain a coherent field quicker for queries than the
    # recursive method
    # It also update all the children to maintain correct names
    self._full_name = self.get_full_name()
    for c in self.children.all():
        c.save()
    super().save(*args, **kwargs)
    self.unset_lock()

get_page_by_full_name(name) staticmethod

Quicker to get a page with that method rather than building the request every time.

Source code in core/models.py
@staticmethod
def get_page_by_full_name(name):
    """Quicker to get a page with that method rather than building the request every time."""
    return Page.objects.filter(_full_name=name).first()

clean()

Cleans up only the name for the moment, but this can be used to make any treatment before saving the object.

Source code in core/models.py
def clean(self):
    """Cleans up only the name for the moment, but this can be used to make any treatment before saving the object."""
    if "/" in self.name:
        self.name = self.name.split("/")[-1]
    if (
        Page.objects.exclude(pk=self.pk)
        .filter(_full_name=self.get_full_name())
        .exists()
    ):
        raise ValidationError(_("Duplicate page"), code="duplicate")
    super().clean()
    if self.parent is not None and self in self.get_parent_list():
        raise ValidationError(_("Loop in page tree"), code="loop")

is_locked()

Is True if the page is locked, False otherwise.

This is where the timeout is handled, so a locked page for which the timeout is reach will be unlocked and this function will return False.

Source code in core/models.py
def is_locked(self):
    """Is True if the page is locked, False otherwise.

    This is where the timeout is handled,
    so a locked page for which the timeout is reach will be unlocked and this
    function will return False.
    """
    if self.lock_timeout and (
        timezone.now() - self.lock_timeout > timedelta(minutes=5)
    ):
        self.unset_lock()
    return (
        self.lock_user
        and self.lock_timeout
        and (timezone.now() - self.lock_timeout < timedelta(minutes=5))
    )

set_lock(user)

Sets a lock on the current page or raise an AlreadyLocked exception.

Source code in core/models.py
def set_lock(self, user):
    """Sets a lock on the current page or raise an AlreadyLocked exception."""
    if self.is_locked() and self.get_lock() != user:
        raise AlreadyLocked("The page is already locked by someone else")
    self.lock_user = user
    self.lock_timeout = timezone.now()
    super().save()

set_lock_recursive(user)

Locks recursively all the child pages for editing properties.

Source code in core/models.py
def set_lock_recursive(self, user):
    """Locks recursively all the child pages for editing properties."""
    for p in self.children.all():
        p.set_lock_recursive(user)
    self.set_lock(user)

unset_lock_recursive()

Unlocks recursively all the child pages.

Source code in core/models.py
def unset_lock_recursive(self):
    """Unlocks recursively all the child pages."""
    for p in self.children.all():
        p.unset_lock_recursive()
    self.unset_lock()

unset_lock()

Always try to unlock, even if there is no lock.

Source code in core/models.py
def unset_lock(self):
    """Always try to unlock, even if there is no lock."""
    self.lock_user = None
    self.lock_timeout = None
    super().save()

get_lock()

Returns the page's mutex containing the time and the user in a dict.

Source code in core/models.py
def get_lock(self):
    """Returns the page's mutex containing the time and the user in a dict."""
    if self.lock_user:
        return self.lock_user
    raise NotLocked("The page is not locked and thus can not return its user")

get_full_name()

Computes the real full_name of the page based on its name and its parent's name You can and must rely on this function when working on a page object that is not freshly fetched from the DB (For example when treating a Page object coming from a form).

Source code in core/models.py
def get_full_name(self):
    """Computes the real full_name of the page based on its name and its parent's name
    You can and must rely on this function when working on a page object that is not freshly fetched from the DB
    (For example when treating a Page object coming from a form).
    """
    if self.parent is None:
        return self.name
    return f"{self.parent.get_full_name()}/{self.name}"

User

Bases: AbstractBaseUser

Defines the base user class, useable in every app.

This is almost the same as the auth module AbstractUser since it inherits from it, but some fields are required, and the username is generated automatically with the name of the user (see generate_username()).

Added field: nick_name, date_of_birth Required fields: email, first_name, last_name, date_of_birth

cached_groups: list[Group] property

Get the list of groups this user is in.

The result is cached for the default duration (should be 5 minutes)

Returns: A list of all the groups this user is in.

is_in_group(*, pk=None, name=None)

Check if this user is in the given group. Either a group id or a group name must be provided. If both are passed, only the id will be considered.

The group will be fetched using the given parameter. If no group is found, return False. If a group is found, check if this user is in the latter.

Returns:

Type Description
bool

True if the user is the group, else False

Source code in core/models.py
def is_in_group(self, *, pk: int | None = None, name: str | None = None) -> bool:
    """Check if this user is in the given group.
    Either a group id or a group name must be provided.
    If both are passed, only the id will be considered.

    The group will be fetched using the given parameter.
    If no group is found, return False.
    If a group is found, check if this user is in the latter.

    Returns:
         True if the user is the group, else False
    """
    if pk is not None:
        group: Optional[Group] = get_group(pk=pk)
    elif name is not None:
        group: Optional[Group] = get_group(name=name)
    else:
        raise ValueError("You must either provide the id or the name of the group")
    if group is None:
        return False
    if group.id == settings.SITH_GROUP_PUBLIC_ID:
        return True
    if group.id == settings.SITH_GROUP_SUBSCRIBERS_ID:
        return self.is_subscribed
    if group.id == settings.SITH_GROUP_OLD_SUBSCRIBERS_ID:
        return self.was_subscribed
    if group.id == settings.SITH_GROUP_ROOT_ID:
        return self.is_root
    if group.is_meta:
        # check if this group is associated with a club
        group.__class__ = MetaGroup
        club = group.associated_club
        if club is None:
            return False
        membership = club.get_membership_for(self)
        if membership is None:
            return False
        if group.name.endswith(settings.SITH_MEMBER_SUFFIX):
            return True
        return membership.role > settings.SITH_MAXIMUM_FREE_ROLE
    return group in self.cached_groups

age()

Return the age this user has the day the method is called. If the user has not filled his age, return 0.

Source code in core/models.py
@cached_property
def age(self) -> int:
    """Return the age this user has the day the method is called.
    If the user has not filled his age, return 0.
    """
    if self.date_of_birth is None:
        return 0
    today = timezone.now()
    age = today.year - self.date_of_birth.year
    # remove a year if this year's birthday is yet to come
    age -= (today.month, today.day) < (
        self.date_of_birth.month,
        self.date_of_birth.day,
    )
    return age

get_full_name()

Returns the first_name plus the last_name, with a space in between.

Source code in core/models.py
def get_full_name(self):
    """Returns the first_name plus the last_name, with a space in between."""
    full_name = "%s %s" % (self.first_name, self.last_name)
    return full_name.strip()

get_short_name()

Returns the short name for the user.

Source code in core/models.py
def get_short_name(self):
    """Returns the short name for the user."""
    if self.nick_name:
        return self.nick_name
    return self.first_name + " " + self.last_name

get_display_name()

Returns the display name of the user.

A nickname if possible, otherwise, the full name.

Source code in core/models.py
def get_display_name(self) -> str:
    """Returns the display name of the user.

    A nickname if possible, otherwise, the full name.
    """
    if self.nick_name:
        return "%s (%s)" % (self.get_full_name(), self.nick_name)
    return self.get_full_name()

get_age()

Returns the age.

Source code in core/models.py
def get_age(self):
    """Returns the age."""
    today = timezone.now()
    born = self.date_of_birth
    return (
        today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    )

get_family(godfathers_depth=4, godchildren_depth=4)

Get the family of the user, with the given depth.

Parameters:

Name Type Description Default
godfathers_depth NonNegativeInt

The number of generations of godfathers to fetch

4
godchildren_depth NonNegativeInt

The number of generations of godchildren to fetch

4

Returns:

Type Description
set[through]

A list of family relationships in this user's family

Source code in core/models.py
def get_family(
    self,
    godfathers_depth: NonNegativeInt = 4,
    godchildren_depth: NonNegativeInt = 4,
) -> set[User.godfathers.through]:
    """Get the family of the user, with the given depth.

    Args:
        godfathers_depth: The number of generations of godfathers to fetch
        godchildren_depth: The number of generations of godchildren to fetch

    Returns:
        A list of family relationships in this user's family
    """
    res = []
    for depth, key, reverse_key in [
        (godfathers_depth, "from_user_id", "to_user_id"),
        (godchildren_depth, "to_user_id", "from_user_id"),
    ]:
        if depth == 0:
            continue
        links = list(User.godfathers.through.objects.filter(**{key: self.id}))
        res.extend(links)
        for _ in range(1, depth):  # noqa: F402 we don't care about gettext here
            ids = [getattr(c, reverse_key) for c in links]
            links = list(
                User.godfathers.through.objects.filter(
                    **{f"{key}__in": ids}
                ).exclude(id__in=[r.id for r in res])
            )
            if not links:
                break
            res.extend(links)
    return set(res)

email_user(subject, message, from_email=None, **kwargs)

Sends an email to this User.

Source code in core/models.py
def email_user(self, subject, message, from_email=None, **kwargs):
    """Sends an email to this User."""
    if from_email is None:
        from_email = settings.DEFAULT_FROM_EMAIL
    send_mail(subject, message, from_email, [self.email], **kwargs)

generate_username()

Generates a unique username based on the first and last names.

For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

Returns:

Type Description
str

The generated username.

Source code in core/models.py
def generate_username(self) -> str:
    """Generates a unique username based on the first and last names.

    For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

    Returns:
        The generated username.
    """

    def remove_accents(data):
        return "".join(
            x
            for x in unicodedata.normalize("NFKD", data)
            if unicodedata.category(x)[0] == "L"
        ).lower()

    user_name = (
        remove_accents(self.first_name[0] + self.last_name)
        .encode("ascii", "ignore")
        .decode("utf-8")
    )
    un_set = [u.username for u in User.objects.all()]
    if user_name in un_set:
        i = 1
        while user_name + str(i) in un_set:
            i += 1
        user_name += str(i)
    self.username = user_name
    return user_name

is_owner(obj)

Determine if the object is owned by the user.

Source code in core/models.py
def is_owner(self, obj):
    """Determine if the object is owned by the user."""
    if hasattr(obj, "is_owned_by") and obj.is_owned_by(self):
        return True
    if hasattr(obj, "owner_group") and self.is_in_group(pk=obj.owner_group.id):
        return True
    return self.is_root

can_edit(obj)

Determine if the object can be edited by the user.

Source code in core/models.py
def can_edit(self, obj):
    """Determine if the object can be edited by the user."""
    if hasattr(obj, "can_be_edited_by") and obj.can_be_edited_by(self):
        return True
    if hasattr(obj, "edit_groups"):
        for pk in obj.edit_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    if isinstance(obj, User) and obj == self:
        return True
    return self.is_owner(obj)

can_view(obj)

Determine if the object can be viewed by the user.

Source code in core/models.py
def can_view(self, obj):
    """Determine if the object can be viewed by the user."""
    if hasattr(obj, "can_be_viewed_by") and obj.can_be_viewed_by(self):
        return True
    if hasattr(obj, "view_groups"):
        for pk in obj.view_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    return self.can_edit(obj)

clubs_with_rights()

The list of clubs where the user has rights

Source code in core/models.py
@cached_property
def clubs_with_rights(self) -> list[Club]:
    """The list of clubs where the user has rights"""
    memberships = self.memberships.ongoing().board().select_related("club")
    return [m.club for m in memberships]

CanCreateMixin

Bases: View

Protect any child view that would create an object.

Raises:

Type Description
PermissionDenied

If the user has not the necessary permission to create the object of the view.

CanEditMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has permission to edit this view's object.

Raises:

Type Description
PermissionDenied

if the user cannot edit this view's object.

CanEditPropMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has owner permissions on the child view object.

In other word, you can make a view with this view as parent, and it will be retricted to the users that are in the object's owner_group or that pass the obj.can_be_viewed_by test.

Raises:

Type Description
PermissionDenied

If the user cannot see the object

CanViewMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has permission to view this view's object.

Raises:

Type Description
PermissionDenied

if the user cannot edit this view's object.

GetUserForm

Bases: Form

The Form class aims at providing a valid user_id field in its cleaned data, in order to pass it to some view, reverse function, or any other use.

The Form implements a nice JS widget allowing the user to type a customer account id, or search the database with some nickname, first name, or last name (TODO)

Counter

Bases: Model

gen_token()

Generate a new token for this counter.

Source code in counter/models.py
def gen_token(self) -> None:
    """Generate a new token for this counter."""
    self.token = "".join(
        random.choice(string.ascii_letters + string.digits) for _ in range(30)
    )
    self.save()

barmen_list()

Returns the barman list as list of User.

Source code in counter/models.py
@cached_property
def barmen_list(self) -> list[User]:
    """Returns the barman list as list of User."""
    return [
        p.user for p in self.permanencies.filter(end=None).select_related("user")
    ]

get_random_barman()

Return a random user being currently a barman.

Source code in counter/models.py
def get_random_barman(self) -> User:
    """Return a random user being currently a barman."""
    return random.choice(self.barmen_list)

update_activity()

Update the barman activity to prevent timeout.

Source code in counter/models.py
def update_activity(self) -> None:
    """Update the barman activity to prevent timeout."""
    self.permanencies.filter(end=None).update(activity=timezone.now())

can_refill()

Show if the counter authorize the refilling with physic money.

Source code in counter/models.py
def can_refill(self) -> bool:
    """Show if the counter authorize the refilling with physic money."""
    if self.type != "BAR":
        return False
    if self.id in SITH_COUNTER_OFFICES:
        # If the counter is either 'AE' or 'BdF', refills are authorized
        return True
    # at least one of the barmen is in the AE board
    ae = Club.objects.get(unix_name=SITH_MAIN_CLUB["unix_name"])
    return any(ae.get_membership_for(barman) for barman in self.barmen_list)

get_top_barmen()

Return a QuerySet querying the office hours stats of all the barmen of all time of this counter, ordered by descending number of hours.

Each element of the QuerySet corresponds to a barman and has the following data
  • the full name (first name + last name) of the barman
  • the nickname of the barman
  • the promo of the barman
  • the total number of office hours the barman did attend
Source code in counter/models.py
def get_top_barmen(self) -> QuerySet:
    """Return a QuerySet querying the office hours stats of all the barmen of all time
    of this counter, ordered by descending number of hours.

    Each element of the QuerySet corresponds to a barman and has the following data :
        - the full name (first name + last name) of the barman
        - the nickname of the barman
        - the promo of the barman
        - the total number of office hours the barman did attend
    """
    return (
        self.permanencies.exclude(end=None)
        .annotate(
            name=Concat(F("user__first_name"), Value(" "), F("user__last_name"))
        )
        .annotate(nickname=F("user__nick_name"))
        .annotate(promo=F("user__promo"))
        .values("user", "name", "nickname", "promo")
        .annotate(perm_sum=Sum(F("end") - F("start")))
        .exclude(perm_sum=None)
        .order_by("-perm_sum")
    )

get_top_customers(since=None)

Return a QuerySet querying the money spent by customers of this counter since the specified date, ordered by descending amount of money spent.

Each element of the QuerySet corresponds to a customer and has the following data :

  • the full name (first name + last name) of the customer
  • the nickname of the customer
  • the amount of money spent by the customer

Parameters:

Name Type Description Default
since datetime | date | None

timestamp from which to perform the calculation

None
Source code in counter/models.py
def get_top_customers(self, since: datetime | date | None = None) -> QuerySet:
    """Return a QuerySet querying the money spent by customers of this counter
    since the specified date, ordered by descending amount of money spent.

    Each element of the QuerySet corresponds to a customer and has the following data :

    - the full name (first name + last name) of the customer
    - the nickname of the customer
    - the amount of money spent by the customer

    Args:
        since: timestamp from which to perform the calculation
    """
    if since is None:
        since = get_start_of_semester()
    if isinstance(since, date):
        since = datetime(since.year, since.month, since.day, tzinfo=tz.utc)
    return (
        self.sellings.filter(date__gte=since)
        .annotate(
            name=Concat(
                F("customer__user__first_name"),
                Value(" "),
                F("customer__user__last_name"),
            )
        )
        .annotate(nickname=F("customer__user__nick_name"))
        .annotate(promo=F("customer__user__promo"))
        .annotate(user=F("customer__user"))
        .values("user", "promo", "name", "nickname")
        .annotate(
            selling_sum=Sum(
                F("unit_price") * F("quantity"), output_field=CurrencyField()
            )
        )
        .filter(selling_sum__gt=0)
        .order_by("-selling_sum")
    )

get_total_sales(since=None)

Compute and return the total turnover of this counter since the given date.

By default, the date is the start of the current semester.

Parameters:

Name Type Description Default
since datetime | date | None

timestamp from which to perform the calculation

None

Returns:

Type Description
CurrencyField

Total revenue earned at this counter.

Source code in counter/models.py
def get_total_sales(self, since: datetime | date | None = None) -> CurrencyField:
    """Compute and return the total turnover of this counter since the given date.

    By default, the date is the start of the current semester.

    Args:
        since: timestamp from which to perform the calculation

    Returns:
        Total revenue earned at this counter.
    """
    if since is None:
        since = get_start_of_semester()
    if isinstance(since, date):
        since = datetime(since.year, since.month, since.day, tzinfo=tz.utc)
    return self.sellings.filter(date__gte=since).aggregate(
        total=Sum(
            F("quantity") * F("unit_price"),
            default=0,
            output_field=CurrencyField(),
        )
    )["total"]

Customer

Bases: Model

Customer data of a User.

It adds some basic customers' information, such as the account ID, and is used by other accounting classes as reference to the customer, rather than using User.

can_buy: bool property

Check if whether this customer has the right to purchase any item.

This must be not confused with the Product.can_be_sold_to(user) method as the present method returns an information about a customer whereas the other tells something about the relation between a User (not a Customer, don't mix them) and a Product.

save(*args, allow_negative=False, is_selling=False, **kwargs)

is_selling : tell if the current action is a selling allow_negative : ignored if not a selling. Allow a selling to put the account in negative Those two parameters avoid blocking the save method of a customer if his account is negative.

Source code in counter/models.py
def save(self, *args, allow_negative=False, is_selling=False, **kwargs):
    """is_selling : tell if the current action is a selling
    allow_negative : ignored if not a selling. Allow a selling to put the account in negative
    Those two parameters avoid blocking the save method of a customer if his account is negative.
    """
    if self.amount < 0 and (is_selling and not allow_negative):
        raise ValidationError(_("Not enough money"))
    super().save(*args, **kwargs)

get_or_create(user) classmethod

Work in pretty much the same way as the usual get_or_create method, but with the default field replaced by some under the hood.

If the user has an account, return it as is. Else create a new account with no money on it and a new unique account id

Example : ::

user = User.objects.get(pk=1)
account, created = Customer.get_or_create(user)
if created:
    print(f"created a new account with id {account.id}")
else:
    print(f"user has already an account, with {account.id} € on it"
Source code in counter/models.py
@classmethod
def get_or_create(cls, user: User) -> Tuple[Customer, bool]:
    """Work in pretty much the same way as the usual get_or_create method,
    but with the default field replaced by some under the hood.

    If the user has an account, return it as is.
    Else create a new account with no money on it and a new unique account id

    Example : ::

        user = User.objects.get(pk=1)
        account, created = Customer.get_or_create(user)
        if created:
            print(f"created a new account with id {account.id}")
        else:
            print(f"user has already an account, with {account.id} € on it"
    """
    if hasattr(user, "customer"):
        return user.customer, False

    # account_id are always a number with a letter appended
    account_id = (
        Customer.objects.order_by(Length("account_id"), "account_id")
        .values("account_id")
        .last()
    )
    if account_id is None:
        # legacy from the old site
        account = cls.objects.create(user=user, account_id="1504a")
        return account, True

    account_id = account_id["account_id"]
    account_num = int(account_id[:-1])
    while Customer.objects.filter(account_id=account_id).exists():
        # when entering the first iteration, we are using an already existing account id
        # so the loop should always execute at least one time
        account_num += 1
        account_id = f"{account_num}{random.choice(string.ascii_lowercase)}"

    account = cls.objects.create(user=user, account_id=account_id)
    return account, True

Selling

Bases: Model

Handle the sellings.

save(*args, allow_negative=False, **kwargs)

allow_negative : Allow this selling to use more money than available for this user.

Source code in counter/models.py
def save(self, *args, allow_negative=False, **kwargs):
    """allow_negative : Allow this selling to use more money than available for this user."""
    if not self.date:
        self.date = timezone.now()
    self.full_clean()
    if not self.is_validated:
        self.customer.amount -= self.quantity * self.unit_price
        self.customer.save(allow_negative=allow_negative, is_selling=True)
        self.is_validated = True
    user = self.customer.user
    if user.was_subscribed:
        if (
            self.product
            and self.product.id == settings.SITH_PRODUCT_SUBSCRIPTION_ONE_SEMESTER
        ):
            sub = Subscription(
                member=user,
                subscription_type="un-semestre",
                payment_method="EBOUTIC",
                location="EBOUTIC",
            )
            sub.subscription_start = Subscription.compute_start()
            sub.subscription_start = Subscription.compute_start(
                duration=settings.SITH_SUBSCRIPTIONS[sub.subscription_type][
                    "duration"
                ]
            )
            sub.subscription_end = Subscription.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[sub.subscription_type][
                    "duration"
                ],
                start=sub.subscription_start,
            )
            sub.save()
        elif (
            self.product
            and self.product.id == settings.SITH_PRODUCT_SUBSCRIPTION_TWO_SEMESTERS
        ):
            sub = Subscription(
                member=user,
                subscription_type="deux-semestres",
                payment_method="EBOUTIC",
                location="EBOUTIC",
            )
            sub.subscription_start = Subscription.compute_start()
            sub.subscription_start = Subscription.compute_start(
                duration=settings.SITH_SUBSCRIPTIONS[sub.subscription_type][
                    "duration"
                ]
            )
            sub.subscription_end = Subscription.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[sub.subscription_type][
                    "duration"
                ],
                start=sub.subscription_start,
            )
            sub.save()
    if user.preferences.notify_on_click:
        Notification(
            user=user,
            url=reverse(
                "core:user_account_detail",
                kwargs={
                    "user_id": user.id,
                    "year": self.date.year,
                    "month": self.date.month,
                },
            ),
            param="%d x %s" % (self.quantity, self.label),
            type="SELLING",
        ).save()
    super().save(*args, **kwargs)
    if hasattr(self.product, "eticket"):
        self.send_mail_customer()

Launderette

Bases: Model

is_owned_by(user)

Method to see if that object can be edited by the given user.

Source code in launderette/models.py
def is_owned_by(self, user):
    """Method to see if that object can be edited by the given user."""
    if user.is_anonymous:
        return False
    launderette_club = Club.objects.filter(
        unix_name=settings.SITH_LAUNDERETTE_MANAGER["unix_name"]
    ).first()
    m = launderette_club.get_membership_for(user)
    return bool(m and m.role >= 9)

Machine

Bases: Model

is_owned_by(user)

Method to see if that object can be edited by the given user.

Source code in launderette/models.py
def is_owned_by(self, user):
    """Method to see if that object can be edited by the given user."""
    if user.is_anonymous:
        return False
    launderette_club = Club.objects.filter(
        unix_name=settings.SITH_LAUNDERETTE_MANAGER["unix_name"]
    ).first()
    m = launderette_club.get_membership_for(user)
    return bool(m and m.role >= 9)

Slot

Bases: Model

Token

Bases: Model

is_owned_by(user)

Method to see if that object can be edited by the given user.

Source code in launderette/models.py
def is_owned_by(self, user):
    """Method to see if that object can be edited by the given user."""
    if user.is_anonymous:
        return False
    launderette_club = Club.objects.filter(
        unix_name=settings.SITH_LAUNDERETTE_MANAGER["unix_name"]
    ).first()
    m = launderette_club.get_membership_for(user)
    return bool(m and m.role >= 9)

LaunderetteMainView

Bases: TemplateView

Main presentation view.

get_context_data(**kwargs)

Add page to the context.

Source code in launderette/views.py
def get_context_data(self, **kwargs):
    """Add page to the context."""
    kwargs = super().get_context_data(**kwargs)
    kwargs["page"] = Page.objects.filter(name="launderette").first()
    return kwargs

LaunderetteBookMainView

Bases: CanViewMixin, ListView

Choose which launderette to book.

LaunderetteBookView

Bases: CanViewMixin, DetailView

Display the launderette schedule.

get_context_data(**kwargs)

Add page to the context.

Source code in launderette/views.py
def get_context_data(self, **kwargs):
    """Add page to the context."""
    kwargs = super().get_context_data(**kwargs)
    kwargs["planning"] = OrderedDict()
    kwargs["slot_type"] = self.slot_type
    start_date = datetime.now().replace(
        hour=0, minute=0, second=0, microsecond=0, tzinfo=tz.utc
    )
    for date in LaunderetteBookView.date_iterator(
        start_date, start_date + timedelta(days=6), timedelta(days=1)
    ):
        kwargs["planning"][date] = []
        for h in LaunderetteBookView.date_iterator(
            date, date + timedelta(days=1), timedelta(hours=1)
        ):
            free = False
            if (
                (
                    self.slot_type == "BOTH"
                    and self.check_slot("WASHING", h)
                    and self.check_slot("DRYING", h + timedelta(hours=1))
                )
                or self.slot_type == "WASHING"
                and self.check_slot("WASHING", h)
                or self.slot_type == "DRYING"
                and self.check_slot("DRYING", h)
            ):
                free = True
            if free and datetime.now().replace(tzinfo=tz.utc) < h:
                kwargs["planning"][date].append(h)
            else:
                kwargs["planning"][date].append(None)
    return kwargs

SlotDeleteView

Bases: CanEditPropMixin, DeleteView

Delete a slot.

LaunderetteListView

Bases: CanEditPropMixin, ListView

Choose which launderette to administer.

LaunderetteEditView

Bases: CanEditPropMixin, UpdateView

Edit a launderette.

LaunderetteCreateView

Bases: CanCreateMixin, CreateView

Create a new launderette.

ManageTokenForm

Bases: Form

LaunderetteAdminView

Bases: CanEditPropMixin, BaseFormView, DetailView

The admin page of the launderette.

form_valid(form)

We handle here the redirection, passing the user id of the asked customer.

Source code in launderette/views.py
def form_valid(self, form):
    """We handle here the redirection, passing the user id of the asked customer."""
    form.process(self.object)
    if form.is_valid():
        return super().form_valid(form)
    else:
        return super().form_invalid(form)

get_context_data(**kwargs)

We handle here the login form for the barman.

Source code in launderette/views.py
def get_context_data(self, **kwargs):
    """We handle here the login form for the barman."""
    kwargs = super().get_context_data(**kwargs)
    if self.request.method == "GET":
        kwargs["form"] = self.get_form()
    return kwargs

GetLaunderetteUserForm

Bases: GetUserForm

LaunderetteMainClickView

Bases: CanEditMixin, BaseFormView, DetailView

The click page of the launderette.

form_valid(form)

We handle here the redirection, passing the user id of the asked customer.

Source code in launderette/views.py
def form_valid(self, form):
    """We handle here the redirection, passing the user id of the asked customer."""
    self.kwargs["user_id"] = form.cleaned_data["user_id"]
    return super().form_valid(form)

get_context_data(**kwargs)

We handle here the login form for the barman.

Source code in launderette/views.py
def get_context_data(self, **kwargs):
    """We handle here the login form for the barman."""
    kwargs = super().get_context_data(**kwargs)
    kwargs["counter"] = self.object.counter
    kwargs["form"] = self.get_form()
    kwargs["barmen"] = [self.request.user]
    if "last_basket" in self.request.session:
        kwargs["last_basket"] = self.request.session.pop("last_basket", None)
        kwargs["last_customer"] = self.request.session.pop("last_customer", None)
        kwargs["last_total"] = self.request.session.pop("last_total", None)
        kwargs["new_customer_amount"] = self.request.session.pop(
            "new_customer_amount", None
        )
    return kwargs

ClickTokenForm

Bases: BaseForm

LaunderetteClickView

Bases: CanEditMixin, DetailView, BaseFormView

The click page of the launderette.

get(request, *args, **kwargs)

Simple get view.

Source code in launderette/views.py
def get(self, request, *args, **kwargs):
    """Simple get view."""
    self.customer = Customer.objects.filter(user__id=self.kwargs["user_id"]).first()
    self.subscriber = self.customer.user
    self.operator = request.user
    return super().get(request, *args, **kwargs)

post(request, *args, **kwargs)

Handle the many possibilities of the post request.

Source code in launderette/views.py
def post(self, request, *args, **kwargs):
    """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 = self.customer.user
    self.operator = request.user
    return super().post(request, *args, **kwargs)

form_valid(form)

We handle here the redirection, passing the user id of the asked customer.

Source code in launderette/views.py
def form_valid(self, form):
    """We handle here the redirection, passing the user id of the asked customer."""
    self.request.session.update(form.last_basket)
    return super().form_valid(form)

get_context_data(**kwargs)

We handle here the login form for the barman.

Source code in launderette/views.py
def get_context_data(self, **kwargs):
    """We handle here the login form for the barman."""
    kwargs = super().get_context_data(**kwargs)
    if "form" not in kwargs:
        kwargs["form"] = self.get_form()
    kwargs["counter"] = self.object.counter
    kwargs["customer"] = self.customer
    return kwargs

MachineEditView

Bases: CanEditPropMixin, UpdateView

Edit a machine.

MachineDeleteView

Bases: CanEditPropMixin, DeleteView

Edit a machine.

MachineCreateView

Bases: CanCreateMixin, CreateView

Create a new machine.