Aller au contenu

# Models

## `Club`

Bases: `Model`

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

### `president()`

Fetch the membership of the current president of this club.

Source code in `club/models.py`

    138
    139
    140
    141
    @cached_property
    def president(self) -> Membership | None:
        """Fetch the membership of the current president of this club."""
        return self.members.filter(end_date=None).order_by("role__order").first()

### `check_loop()`

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

Source code in `club/models.py`

    143
    144
    145
    146
    147
    148
    149
    150
    151
    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

### `create_default_roles()`

Create some roles that should exist by default for this club.

The created roles are : president, treasurer, active member and curious.

Source code in `club/models.py`

    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    def create_default_roles(self):
        """Create some roles that should exist by default for this club.

        The created roles are : president, treasurer, active member and curious.

        Warnings:
            When calling this method, no club must exist yet for this club.
        """
        if self.roles.exists():
            raise ProgrammingError(
                "Default roles can be created only for clubs "
                "that don't have associated roles yet"
            )
        # The names are written in French, because there is no gettext involved
        # for strings stored in database, and the majority of users are french.
        roles = [
            ClubRole(name="Président⸱e", is_board=True, is_presidency=True),
            ClubRole(name="Trésorier⸱e", is_board=True, is_presidency=False),
            ClubRole(name="Membre actif⸱ve", is_board=False, is_presidency=False),
            ClubRole(
                name="Curieux⸱euse",
                description=(
                    "Les gens qui suivent l'activité "
                    "du club sans forcément y participer"
                ),
                is_board=False,
                is_presidency=False,
            ),
        ]
        for i, role in enumerate(roles):
            role.club = self
            role.order = i
        ClubRole.objects.bulk_create(roles)

### `is_owned_by(user)`

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

Source code in `club/models.py`

    228
    229
    230
    231
    232
    def is_owned_by(self, user: User) -> bool:
        """Method to see if that object can be super edited by the given user."""
        if user.is_anonymous:
            return False
        return user.is_root or 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`

    237
    238
    239
    def can_be_edited_by(self, user: User) -> bool:
        """Method to see if that object can be edited by the given user."""
        return self.has_rights_in_club(user)

### `get_membership_for(user)`

Return the current membership of the given user.

Source code in `club/models.py`

    247
    248
    249
    250
    251
    def get_membership_for(self, user: User) -> Membership | None:
        """Return the current membership of the given user."""
        if user.is_anonymous:
            return None
        return next((m for m in self.current_members if m.user_id == user.id), None)

## `ResizedImageField(width=None, height=None, force_format=None, **kwargs)`

Bases: `ImageField`

A field that automatically resizes images to a given size.

This field is useful for profile pictures or product icons, for example.

The final size of the image is determined by the width and height parameters :

- If both are given, the image will be resized to fit in a rectangle of width x height
- If only one is given, the other will be calculated to keep the same ratio

If the force_format parameter is given, the image will be converted to this format.

Examples:

To resize an image with a height of 100px, without changing the ratio, and a format of WEBP :

    class Product(models.Model):
        icon = ResizedImageField(height=100, force_format="WEBP")

To explicitly resize an image to 100x100px (but possibly change the ratio) :

    class Product(models.Model):
        icon = ResizedImageField(width=100, height=100)

Raises:

Type | Description
--- | ---
`FieldError` | If neither width nor height is given

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`width` | `int | None` | If given, the width of the resized image | `None`
`height` | `int | None` | If given, the height of the resized image | `None`
`force_format` | `str | None` | If given, the image will be converted to this format | `None`

Source code in `core/fields.py`

    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    def __init__(
        self,
        width: int | None = None,
        height: int | None = None,
        force_format: str | None = None,
        **kwargs,
    ):
        if width is None and height is None:
            raise FieldError(
                f"{self.__class__.__name__} requires "
                "width, height or both, but got neither"
            )
        self.width = width
        self.height = height
        self.force_format = force_format
        super().__init__(**kwargs)

## `Group`

Bases: `Group`

Wrapper around django.auth.Group

## `Notification`

Bases: `Model`

## `User`

Bases: `AbstractUser`

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

### `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`

    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    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 not pk and not name:
            raise ValueError("You must either provide the id or the name of the group")
        group_id: int | None = (
            pk or Group.objects.filter(name=name).values_list("id", flat=True).first()
        )
        if group_id is None:
            return False
        return group_id in self.all_groups

### `all_groups()`

Get the list of groups this user is in.

Source code in `core/models.py`

    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    @cached_property
    def all_groups(self) -> dict[int, Group]:
        """Get the list of groups this user is in."""
        additional_groups = []
        if self.is_subscribed:
            additional_groups.append(settings.SITH_GROUP_SUBSCRIBERS_ID)
        if self.is_superuser:
            additional_groups.append(settings.SITH_GROUP_ROOT_ID)
        qs = self.groups.all()
        if additional_groups:
            # This is somewhat counter-intuitive, but this query runs way faster with
            # a UNION rather than a OR (in average, 0.25ms vs 14ms).
            # For the why, cf. https://dba.stackexchange.com/questions/293836/why-is-an-or-statement-slower-than-union
            qs = qs.union(Group.objects.filter(id__in=additional_groups))
        return {g.id: g for g in qs}

### `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`

    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    @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_short_name()`

Returns the short name for the user.

Source code in `core/models.py`

    439
    440
    441
    442
    443
    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`

    445
    446
    447
    448
    449
    450
    451
    452
    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_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`

    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    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`

    489
    490
    491
    492
    493
    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`

    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    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")
        )
        # load all usernames which could conflict with the new one.
        # we need to actually load them, instead of performing a count,
        # because we cannot be sure that two usernames refer to the
        # actual same word (eg. tmore and tmoreau)
        possible_conflicts: list[str] = list(
            User.objects.filter(username__startswith=user_name).values_list(
                "username", flat=True
            )
        )
        nb_conflicts = sum(
            1 for name in possible_conflicts if name.rstrip(string.digits) == user_name
        )
        if nb_conflicts > 0:
            user_name += str(nb_conflicts)  # exemple => exemple1
        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`

    533
    534
    535
    536
    537
    538
    539
    def is_owner(self, obj: models.Model):
        """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`

    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    def can_edit(self, obj: models.Model):
        """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"):
            if (
                hasattr(obj, "_prefetched_objects_cache")
                and "edit_groups" in obj._prefetched_objects_cache
            ):
                pks = [g.id for g in obj.edit_groups.all()]
            else:
                pks = list(obj.edit_groups.values_list("id", flat=True))
            if any(self.is_in_group(pk=pk) for pk in pks):
                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`

    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    def can_view(self, obj: models.Model):
        """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"):
            # if "view_groups" has already been prefetched, use
            # the prefetch cache, else fetch only the ids, to make
            # the query lighter.
            if (
                hasattr(obj, "_prefetched_objects_cache")
                and "view_groups" in obj._prefetched_objects_cache
            ):
                pks = [g.id for g in obj.view_groups.all()]
            else:
                pks = list(obj.view_groups.values_list("id", flat=True))
            if any(self.is_in_group(pk=pk) for pk in pks):
                return True
        return self.can_edit(obj)

### `can_be_viewed_by(user)`

Check if the given user can be viewed by this user.

Given users A and B. A can be viewed by B if :

- A and B are the same user
- or B has the permission to view hidden users
- or B can view users in general and A didn't hide its profile
- or B is in A's whitelist.

Source code in `core/models.py`

    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    def can_be_viewed_by(self, user: User) -> bool:
        """Check if the given user can be viewed by this user.

        Given users A and B. A can be viewed by B if :

        - A and B are the same user
        - or B has the permission to view hidden users
        - or B can view users in general and A didn't hide its profile
        - or B is in A's whitelist.
        """

        def is_in_whitelist(u: User):
            if (
                hasattr(self, "_prefetched_objects_cache")
                and "whitelisted_users" in self._prefetched_objects_cache
            ):
                return u in self.whitelisted_users.all()
            return self.whitelisted_users.contains(u)

        return (
            user.id == self.id
            or user.has_perm("core.view_hidden_user")
            or (
                user.has_perm("core.view_user")
                and (self.is_viewable or is_in_whitelist(user))
            )
        )

### `clubs_with_rights()`

The list of clubs where the user has rights

Source code in `core/models.py`

    639
    640
    641
    642
    643
    @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]

## `CurrencyField(*args, **kwargs)`

Bases: `DecimalField`

Custom database field used for currency.

Source code in `counter/fields.py`

    10
    11
    12
    13
    def __init__(self, *args, **kwargs):
        kwargs["max_digits"] = 12
        kwargs["decimal_places"] = 2
        super().__init__(*args, **kwargs)

## `CustomerQuerySet`

Bases: `QuerySet`

### `update_amount()`

Update the amount of all customers selected by this queryset.

The result is given as the sum of all refills minus the sum of all purchases paid with the AE account.

Returns:

Type | Description
--- | ---
`int` | The number of updated rows.

Warning

The execution time of this query grows really quickly. When updating 500 customers, it may take around a second. If you try to update all customers at once, the execution time goes up to tens of seconds. Use this either on a small subset of the `Customer` table, or execute it inside an independent task (like a Celery task or a management command).

Source code in `counter/models.py`

    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    def update_amount(self) -> int:
        """Update the amount of all customers selected by this queryset.

        The result is given as the sum of all refills
        minus the sum of all purchases paid with the AE account.

        Returns:
            The number of updated rows.

        Warning:
            The execution time of this query grows really quickly.
            When updating 500 customers, it may take around a second.
            If you try to update all customers at once, the execution time
            goes up to tens of seconds.
            Use this either on a small subset of the `Customer` table,
            or execute it inside an independent task
            (like a Celery task or a management command).
        """
        money_in = Subquery(
            Refilling.objects.filter(customer=OuterRef("pk"))
            .values("customer_id")  # group by customer
            .annotate(res=Sum(F("amount"), default=0))
            .values("res")
        )
        money_out = Subquery(
            Selling.objects.filter(
                customer=OuterRef("pk"),
                payment_method=Selling.PaymentMethod.SITH_ACCOUNT,
            )
            .values("customer_id")
            .annotate(res=Sum(F("unit_price") * F("quantity"), default=0))
            .values("res")
        )
        return self.update(amount=Coalesce(money_in - money_out, Decimal(0)))

## `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` `property`

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

### `save(*args, allow_negative=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`

    116
    117
    118
    119
    120
    121
    122
    123
    def save(self, *args, allow_negative=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 not allow_negative:
            raise ValidationError(_("Not enough money"))
        super().save(*args, **kwargs)

### `update_returnable_balance()`

Update all returnable balances of this user to their real amount.

Source code in `counter/models.py`

    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    def update_returnable_balance(self):
        """Update all returnable balances of this user to their real amount."""

        def purchases_qs(outer_ref: Literal["product_id", "returned_product_id"]):
            return (
                Selling.objects.filter(customer=self, product=OuterRef(outer_ref))
                .values("product")
                .annotate(quantity=Sum("quantity", default=0))
                .values("quantity")
            )

        balances = (
            ReturnableProduct.objects.annotate_balance_for(self)
            .annotate(
                nb_cons=Coalesce(Subquery(purchases_qs("product_id")), 0),
                nb_dcons=Coalesce(Subquery(purchases_qs("returned_product_id")), 0),
            )
            .annotate(new_balance=F("nb_cons") - F("nb_dcons"))
            .values("id", "new_balance")
        )
        updated_balances = [
            ReturnableProductBalance(
                customer=self, returnable_id=b["id"], balance=b["new_balance"]
            )
            for b in balances
        ]
        ReturnableProductBalance.objects.bulk_create(
            updated_balances,
            update_conflicts=True,
            update_fields=["balance"],
            unique_fields=["customer", "returnable"],
        )

### `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`

    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    @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

## `BillingInfo`

Bases: `Model`

Represent the billing information of a user, which are required by the 3D-Secure v2 system used by the etransaction module.

### `to_3dsv2_xml()`

Convert the data from this model into a xml usable by the online paying service of the Crédit Agricole bank. see : `https://www.ca-moncommerce.com/espace-client-mon-commerce/up2pay-e-transactions/ma-documentation/manuel-dintegration-focus-3ds-v2/principes-generaux/#integration-3dsv2-developpeur-webmaster`.

Source code in `counter/models.py`

    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    def to_3dsv2_xml(self) -> str:
        """Convert the data from this model into a xml usable
        by the online paying service of the Crédit Agricole bank.
        see : `https://www.ca-moncommerce.com/espace-client-mon-commerce/up2pay-e-transactions/ma-documentation/manuel-dintegration-focus-3ds-v2/principes-generaux/#integration-3dsv2-developpeur-webmaster`.
        """
        data = {
            "Address": {
                "FirstName": self.first_name,
                "LastName": self.last_name,
                "Address1": self.address_1,
                "ZipCode": self.zip_code,
                "City": self.city,
                "CountryCode": self.country.numeric,  # ISO-3166-1 numeric code
                "MobilePhone": self.phone_number.as_national.replace(" ", ""),
                "CountryCodeMobilePhone": f"+{self.phone_number.country_code}",
            }
        }
        if self.address_2:
            data["Address"]["Address2"] = self.address_2
        xml = dict2xml(data, wrap="Billing", newlines=False)
        return '<?xml version="1.0" encoding="UTF-8" ?>' + xml

## `AccountDumpQuerySet`

Bases: `QuerySet`

### `ongoing()`

Filter dump operations that are not completed yet.

Source code in `counter/models.py`

    270
    271
    272
    def ongoing(self) -> Self:
        """Filter dump operations that are not completed yet."""
        return self.filter(dump_operation=None)

## `AccountDump`

Bases: `Model`

The process of dumping an account.

## `ProductType`

Bases: `OrderedModel`

A product type.

Useful only for categorizing.

### `is_owned_by(user)`

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

Source code in `counter/models.py`

    349
    350
    351
    352
    353
    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
        return user.is_in_group(pk=settings.SITH_GROUP_ACCOUNTING_ADMIN_ID)

## `Product`

Bases: `Model`

A product, with all its related information.

### `is_owned_by(user)`

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

Source code in `counter/models.py`

    407
    408
    409
    410
    411
    412
    413
    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
        return user.is_in_group(
            pk=settings.SITH_GROUP_ACCOUNTING_ADMIN_ID
        ) or user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)

## `PriceQuerySet`

Bases: `QuerySet`

## `Price`

Bases: `Model`

## `ProductFormula`

Bases: `Model`

## `CounterQuerySet`

Bases: `QuerySet`

### `annotate_has_barman(user)`

Annotate the queryset with the `user_is_barman` field.

For each counter, this field has value True if the user is a barman of this counter, else False.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`user` | `User` | the user we want to check if he is a barman | required

Examples:

    sli = User.objects.get(username="sli")
    counters = (
        Counter.objects
        .annotate_has_barman(sli)  # add the user_has_barman boolean field
        .filter(has_annotated_barman=True)  # keep only counters where this user is barman
    )
    print("Sli est barman dans les comptoirs suivants :")
    for counter in counters:
        print(f"- {counter.name}")

Source code in `counter/models.py`

    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    def annotate_has_barman(self, user: User) -> Self:
        """Annotate the queryset with the `user_is_barman` field.

        For each counter, this field has value True if the user
        is a barman of this counter, else False.

        Args:
            user: the user we want to check if he is a barman

        Examples:
            ```python
            sli = User.objects.get(username="sli")
            counters = (
                Counter.objects
                .annotate_has_barman(sli)  # add the user_has_barman boolean field
                .filter(has_annotated_barman=True)  # keep only counters where this user is barman
            )
            print("Sli est barman dans les comptoirs suivants :")
            for counter in counters:
                print(f"- {counter.name}")
            ```
        """
        subquery = user.counters.filter(pk=OuterRef("pk"))
        return self.annotate(has_annotated_barman=Exists(subquery))

### `annotate_is_open()`

Annotate the queryset with the `is_open` field.

For each counter, if `is_open=True`, then the counter is currently opened. Else the counter is closed.

Source code in `counter/models.py`

    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    def annotate_is_open(self) -> Self:
        """Annotate the queryset with the `is_open` field.

        For each counter, if `is_open=True`, then the counter is currently opened.
        Else the counter is closed.
        """
        return self.annotate(
            is_open=Exists(
                Permanency.objects.filter(counter_id=OuterRef("pk"), end=None)
            )
        )

### `handle_timeout()`

Disconnect the barmen who are inactive in the given counters.

Returns:

Type | Description
--- | ---
`int` | The number of affected rows (ie, the number of timeouted permanences)

Source code in `counter/models.py`

    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    def handle_timeout(self) -> int:
        """Disconnect the barmen who are inactive in the given counters.

        Returns:
            The number of affected rows (ie, the number of timeouted permanences)
        """
        timeout = timezone.now() - timedelta(minutes=settings.SITH_BARMAN_TIMEOUT)
        return Permanency.objects.filter(
            counter__in=self, end=None, activity__lt=timeout
        ).update(end=F("activity"))

## `Counter`

Bases: `Model`

### `gen_token()`

Generate a new token for this counter.

Source code in `counter/models.py`

    615
    616
    617
    618
    619
    620
    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`

    622
    623
    624
    625
    626
    627
    @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`

    629
    630
    631
    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`

    633
    634
    635
    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`

    637
    638
    639
    640
    641
    642
    643
    def can_refill(self) -> bool:
        """Show if the counter authorize the refilling with physic money."""
        if self.type != "BAR":
            return False
        # at least one of the barmen is in the AE board
        ae = Club.objects.get(id=settings.SITH_MAIN_CLUB_ID)
        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`

    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    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
        """
        name_expr = Concat(F("user__first_name"), Value(" "), F("user__last_name"))
        return (
            self.permanencies.exclude(end=None)
            .annotate(
                name=name_expr, nickname=F("user__nick_name"), 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`

    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    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)
        name_expr = Concat(
            F("customer__user__first_name"), Value(" "), F("customer__user__last_name")
        )
        return (
            self.sellings.filter(date__gte=since)
            .annotate(
                name=name_expr,
                nickname=F("customer__user__nick_name"),
                promo=F("customer__user__promo"),
                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`

    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    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_is_barman(customer)`

Check if this counter is a `bar` and if the customer is currently logged in. This is useful to compute special prices.

Source code in `counter/models.py`

    728
    729
    730
    731
    732
    733
    734
    def customer_is_barman(self, customer: Customer | User) -> bool:
        """Check if this counter is a `bar` and if the customer is currently logged in.
        This is useful to compute special prices."""

        # Customer and User are two different tables,
        # but they share the same primary key
        return self.type == "BAR" and any(b.pk == customer.pk for b in self.barmen_list)

## `CounterSellers`

Bases: `Model`

Custom through model for the counter-sellers M2M relationship.

## `RefillingQuerySet`

Bases: `QuerySet`

### `annotate_total()`

Annotate the Queryset with the total amount.

The total is just the sum of the amounts for each row. If no grouping is involved (like in most queries), this is just the same as doing nothing and fetching the `amount` attribute.

However, it may be useful when there is a `group by` clause in the query, or when other models are queried and having a common interface is helpful (e.g. `Selling.objects.annotate_total()` and `Refilling.objects.annotate_total()` will both have the `total` field).

Source code in `counter/models.py`

    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    def annotate_total(self) -> Self:
        """Annotate the Queryset with the total amount.

        The total is just the sum of the amounts for each row.
        If no grouping is involved (like in most queries),
        this is just the same as doing nothing and fetching the
        `amount` attribute.

        However, it may be useful when there is a `group by` clause
        in the query, or when other models are queried and having
        a common interface is helpful (e.g. `Selling.objects.annotate_total()`
        and `Refilling.objects.annotate_total()` will both have the `total` field).
        """
        return self.annotate(total=Sum("amount"))

## `Refilling`

Bases: `Model`

Handle the refilling.

## `SellingQuerySet`

Bases: `QuerySet`

### `annotate_total()`

Annotate the Queryset with the total amount of the sales.

The total is considered as the sum of (unit_price * quantity).

Source code in `counter/models.py`

    861
    862
    863
    864
    865
    866
    def annotate_total(self) -> Self:
        """Annotate the Queryset with the total amount of the sales.

        The total is considered as the sum of (unit_price * quantity).
        """
        return self.annotate(total=Sum(F("unit_price") * F("quantity")))

## `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`

     928
     929
     930
     931
     932
     933
     934
     935
     936
     937
     938
     939
     940
     941
     942
     943
     944
     945
     946
     947
     948
     949
     950
     951
     952
     953
     954
     955
     956
     957
     958
     959
     960
     961
     962
     963
     964
     965
     966
     967
     968
     969
     970
     971
     972
     973
     974
     975
     976
     977
     978
     979
     980
     981
     982
     983
     984
     985
     986
     987
     988
     989
     990
     991
     992
     993
     994
     995
     996
     997
     998
     999
    1000
    1001
    1002
    1003
    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 (
            self._state.adding
            and self.payment_method == self.PaymentMethod.SITH_ACCOUNT
        ):
            self.customer.amount -= self.quantity * self.unit_price
            self.customer.save(allow_negative=allow_negative)
        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()

## `Permanency`

Bases: `Model`

A permanency of a barman, on a counter.

This aims at storing a traceability of who was barman where and when. Mainly for dick size contest establishing the top 10 barmen of the semester.

## `CashRegisterSummary`

Bases: `Model`

### `is_owned_by(user)`

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

Source code in `counter/models.py`

    1171
    1172
    1173
    1174
    1175
    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
        return user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)

## `CashRegisterSummaryItem`

Bases: `Model`

## `Eticket`

Bases: `Model`

Eticket can be linked to a product an allows PDF generation.

### `is_owned_by(user)`

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

Source code in `counter/models.py`

    1235
    1236
    1237
    1238
    1239
    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
        return user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)

## `StudentCard`

Bases: `Model`

Alternative way to connect a customer into a counter.

We are using Mifare DESFire EV1 specs since it's used for izly cards https://www.nxp.com/docs/en/application-note/AN10927.pdf UID is 7 byte long that means 14 hexa characters.

## `ReturnableProductQuerySet`

Bases: `QuerySet`

## `ReturnableProduct`

Bases: `Model`

A returnable relation between two products (consigne/déconsigne).

### `update_balances()`

Update all returnable balances linked to this object.

Call this when a ReturnableProduct is created or updated.

Warning

This function is expensive (around a few seconds), so try not to run it outside a management command or a task.

Source code in `counter/models.py`

    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377
    1378
    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    def update_balances(self):
        """Update all returnable balances linked to this object.

        Call this when a ReturnableProduct is created or updated.

        Warning:
            This function is expensive (around a few seconds),
            so try not to run it outside a management command
            or a task.
        """

        def product_balance_subquery(product_id: int):
            return Subquery(
                Selling.objects.filter(customer=OuterRef("pk"), product_id=product_id)
                .values("customer")
                .annotate(res=Sum("quantity"))
                .values("res")
            )

        old_balance_subquery = Subquery(
            ReturnableProductBalance.objects.filter(
                customer=OuterRef("pk"), returnable=self
            ).values("balance")
        )
        new_balances = (
            Customer.objects.annotate(
                nb_cons=Coalesce(product_balance_subquery(self.product_id), 0),
                nb_dcons=Coalesce(
                    product_balance_subquery(self.returned_product_id), 0
                ),
            )
            .annotate(new_balance=F("nb_cons") - F("nb_dcons"))
            .exclude(new_balance=Coalesce(old_balance_subquery, 0))
            .values("pk", "new_balance")
        )
        updates = [
            ReturnableProductBalance(
                customer_id=c["pk"], returnable=self, balance=c["new_balance"]
            )
            for c in new_balances
        ]
        ReturnableProductBalance.objects.bulk_create(
            updates,
            update_conflicts=True,
            update_fields=["balance"],
            unique_fields=["customer_id", "returnable"],
        )

## `ReturnableProductBalance`

Bases: `Model`

The returnable products balances of a customer

## `ScheduledProductAction(*args, **kwargs)`

Bases: `PeriodicTask`

Extension of celery-beat tasks dedicated to perform actions on Product.

Source code in `counter/models.py`

    1443
    1444
    1445
    def __init__(self, *args, **kwargs):
        self._meta.get_field("task").choices = get_product_actions()
        super().__init__(*args, **kwargs)

## `MonthField`

Bases: `DateField`

## `InvoiceCall`

Bases: `Model`

## `get_start_of_semester(today=None)`

Return the date of the start of the semester of the given date. If no date is given, return the start date of the current semester.

The current semester is computed as follows:

- If the date is between 15/08 and 31/12 => Autumn semester.
- If the date is between 01/01 and 15/02 => Autumn semester of the previous year.
- If the date is between 15/02 and 15/08 => Spring semester

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`today` | `date | None` | the date to use to compute the semester. If None, use today's date. | `None`

Returns:

Type | Description
--- | ---
`date` | the date of the start of the semester

Source code in `core/utils.py`

    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    def get_start_of_semester(today: date | None = None) -> date:
        """Return the date of the start of the semester of the given date.
        If no date is given, return the start date of the current semester.

        The current semester is computed as follows:

        - If the date is between 15/08 and 31/12  => Autumn semester.
        - If the date is between 01/01 and 15/02  => Autumn semester of the previous year.
        - If the date is between 15/02 and 15/08  => Spring semester

        Args:
            today: the date to use to compute the semester. If None, use today's date.

        Returns:
            the date of the start of the semester
        """
        if today is None:
            today = localdate()

        autumn = date(today.year, *settings.SITH_SEMESTER_START_AUTUMN)
        spring = date(today.year, *settings.SITH_SEMESTER_START_SPRING)

        if today >= autumn:  # between 15/08 (included) and 31/12 -> autumn semester
            return autumn
        if today >= spring:  # between 15/02 (included) and 15/08 -> spring semester
            return spring
        # between 01/01 and 15/02 -> autumn semester of the previous year
        return autumn.replace(year=autumn.year - 1)

## `get_eboutic()`

Source code in `counter/models.py`

    54
    55
    def get_eboutic() -> Counter:
        return Counter.objects.filter(type="EBOUTIC").order_by("id").first()

## `get_product_actions()`

Source code in `counter/models.py`

    1426
    1427
    1428
    1429
    1430
    def get_product_actions():
        return [
            ("counter.tasks.archive_product", _("Archiving")),
            ("counter.tasks.change_counters", _("Counters change")),
        ]