mirror of
https://github.com/ae-utbm/sith.git
synced 2026-11-20 07:59:50 +00:00
Merge pull request #1547 from ae-utbm/barman-age
Check birthdate and bans when adding users to counter sellers
This commit is contained in:
14 files changed
+271
-18
No files matched your search
@@ -769,6 +769,14 @@ class UserBan(models.Model):
|
||||
def __str__(self):
|
||||
return f"Ban of user {self.user.id}"
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if self.ban_group_id in [
|
||||
settings.SITH_GROUP_BANNED_COUNTER_ID,
|
||||
settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||
]:
|
||||
self.user.counters.clear()
|
||||
return super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class GlobalPermissionRights(models.Model):
|
||||
"""Little hack to have permissions not linked to a specific db table."""
|
||||
|
||||
+37
-2
@@ -3,7 +3,7 @@ import math
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from typing import TYPE_CHECKING, ClassVar, LiteralString
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
from django import forms
|
||||
@@ -19,7 +19,7 @@ from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
||||
|
||||
from club.models import Club
|
||||
from club.widgets.ajax_select import AutoCompleteSelectClub
|
||||
from core.models import User, UserQuerySet
|
||||
from core.models import User, UserBan, UserQuerySet
|
||||
from core.views import LoginForm
|
||||
from core.views.forms import (
|
||||
FutureDateTimeField,
|
||||
@@ -257,6 +257,41 @@ class CounterEditForm(forms.ModelForm):
|
||||
countersellers__is_regular=False
|
||||
).all()
|
||||
|
||||
def clean_sellers(self, field: LiteralString):
|
||||
sellers = self.cleaned_data[field]
|
||||
bans = [
|
||||
settings.SITH_GROUP_BANNED_COUNTER_ID,
|
||||
settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||
]
|
||||
invalid_sellers = sellers.annotate(
|
||||
is_banned=Exists(
|
||||
UserBan.objects.filter(user=OuterRef("pk"), ban_group__in=bans)
|
||||
)
|
||||
).filter(Q(is_banned=True) | Q(date_of_birth=None))
|
||||
for seller in invalid_sellers:
|
||||
if seller.is_banned:
|
||||
self.add_error(
|
||||
field,
|
||||
ValidationError(
|
||||
_("%(user)s is banned.") % {"user": seller.get_full_name()}
|
||||
),
|
||||
)
|
||||
if not seller.date_of_birth:
|
||||
self.add_error(
|
||||
field,
|
||||
ValidationError(
|
||||
_("%(user)s has not filled its birthdate.")
|
||||
% {"user": seller.get_full_name()}
|
||||
),
|
||||
)
|
||||
return sellers
|
||||
|
||||
def clean_sellers_regular(self):
|
||||
return self.clean_sellers("sellers_regular")
|
||||
|
||||
def clean_sellers_temporary(self):
|
||||
return self.clean_sellers("sellers_temporary")
|
||||
|
||||
def clean(self):
|
||||
regular: UserQuerySet = self.cleaned_data["sellers_regular"]
|
||||
temporary: UserQuerySet = self.cleaned_data["sellers_temporary"]
|
||||
|
||||
@@ -405,7 +405,7 @@ class TestCounterClick(TestFullClickBase):
|
||||
self.assertRedirects(res, self.counter.get_absolute_url())
|
||||
assert self.updated_amount(self.customer) == Decimal(8)
|
||||
|
||||
def test_click_alcool_unauthorized(self):
|
||||
def test_click_alcohol_unauthorized(self):
|
||||
self.login_in_bar()
|
||||
|
||||
for user in [self.underage_customer, self.banned_alcohol_customer]:
|
||||
@@ -423,6 +423,31 @@ class TestCounterClick(TestFullClickBase):
|
||||
|
||||
assert self.updated_amount(user) == Decimal(7)
|
||||
|
||||
def test_click_no_alcohol_if_minor_barman(self):
|
||||
"""Test that no age restricted product can be sold if the barman is minor."""
|
||||
set_age(self.barmen, 17)
|
||||
self.login_in_bar(self.barmen)
|
||||
res = self.client.get(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.customer.id},
|
||||
)
|
||||
)
|
||||
assert res.status_code == 200
|
||||
messages = list(get_messages(res.wsgi_request))
|
||||
assert len(messages) == 1
|
||||
assert messages[0].level == DEFAULT_LEVELS["WARNING"]
|
||||
assert messages[0].message == (
|
||||
"Un mineur est barman sur cet appareil, "
|
||||
"vous ne pouvez donc pas vendre d'alcool actuellement."
|
||||
)
|
||||
assert res.context_data["prices"] == [
|
||||
self.gift,
|
||||
self.snack,
|
||||
self.cons,
|
||||
self.dcons,
|
||||
]
|
||||
|
||||
def test_click_unauthorized_customer(self):
|
||||
self.login_in_bar()
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from dateutil.utils import today
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import TestCase
|
||||
@@ -6,7 +9,7 @@ from model_bakery import baker
|
||||
|
||||
from club.models import Membership
|
||||
from core.baker_recipes import subscriber_user
|
||||
from core.models import Group, User
|
||||
from core.models import Group, User, UserBan
|
||||
from counter.baker_recipes import product_recipe
|
||||
from counter.forms import CounterEditForm
|
||||
from counter.models import Counter, CounterSellers
|
||||
@@ -18,7 +21,11 @@ class TestEditCounterSellers(TestCase):
|
||||
cls.counter = baker.make(Counter, type="BAR")
|
||||
cls.products = product_recipe.make(_quantity=2, _bulk_create=True)
|
||||
cls.counter.products.add(*cls.products)
|
||||
users = subscriber_user.make(_quantity=6, _bulk_create=True)
|
||||
users = subscriber_user.make(
|
||||
date_of_birth=today() - timedelta(days=365 * 20),
|
||||
_quantity=6,
|
||||
_bulk_create=True,
|
||||
)
|
||||
cls.regular_barmen = users[:2]
|
||||
cls.tmp_barmen = users[2:4]
|
||||
cls.not_barmen = users[4:]
|
||||
@@ -128,6 +135,54 @@ class TestEditCounterSellers(TestCase):
|
||||
self.counter.sellers.filter(countersellers__is_regular=False)
|
||||
) == set(self.tmp_barmen)
|
||||
|
||||
def test_barman_without_birthdate(self):
|
||||
"""Test that users without a birthdate cannot be sellers."""
|
||||
user = subscriber_user.make()
|
||||
form = CounterEditForm(
|
||||
data={
|
||||
"sellers_regular": [*self.regular_barmen, user],
|
||||
"sellers_temporary": self.tmp_barmen,
|
||||
"products": self.products,
|
||||
},
|
||||
instance=self.counter,
|
||||
user=self.operator,
|
||||
)
|
||||
assert not form.is_valid()
|
||||
assert form.errors == {
|
||||
"sellers_regular": [
|
||||
f"{user.get_full_name()} n'a pas renseigné sa date de naissance."
|
||||
]
|
||||
}
|
||||
|
||||
def test_banned_barman_forbidden(self):
|
||||
"""Test that users with a counter ban cannot be sellers."""
|
||||
UserBan.objects.create(
|
||||
user=self.not_barmen[0],
|
||||
ban_group_id=settings.SITH_GROUP_BANNED_COUNTER_ID,
|
||||
reason="ban comptoir",
|
||||
)
|
||||
UserBan.objects.create(
|
||||
user=self.not_barmen[1],
|
||||
ban_group_id=settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||
reason="ban comptoir",
|
||||
)
|
||||
form = CounterEditForm(
|
||||
data={
|
||||
"sellers_regular": [*self.regular_barmen, *self.not_barmen[0:2]],
|
||||
"sellers_temporary": self.tmp_barmen,
|
||||
"products": self.products,
|
||||
},
|
||||
instance=self.counter,
|
||||
user=self.operator,
|
||||
)
|
||||
assert not form.is_valid()
|
||||
assert form.errors == {
|
||||
"sellers_regular": [
|
||||
f"{self.not_barmen[0].get_full_name()} est banni.",
|
||||
f"{self.not_barmen[1].get_full_name()} est banni.",
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
class TestEditCounterProducts(TestCase):
|
||||
@classmethod
|
||||
|
||||
@@ -145,7 +145,7 @@ class TestStudentCard(TestCase):
|
||||
|
||||
self.login_in_counter()
|
||||
barman = subscriber_user.make()
|
||||
self.counter.sellers.add(barman)
|
||||
self.counter.sellers.add(barman, through_defaults={"is_regular": True})
|
||||
# We want to test sending requests from another counter while
|
||||
# we are currently registered to another counter
|
||||
# so we connect to a counter and
|
||||
|
||||
+78
-4
@@ -43,8 +43,8 @@ from counter.views.mixins import CounterTabsMixin
|
||||
from counter.views.student_card import StudentCardFormFragment
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.http import HttpRequest
|
||||
from django.utils.safestring import SafeString
|
||||
from ninja.main import HttpRequest
|
||||
|
||||
from core.models import User
|
||||
|
||||
@@ -60,9 +60,70 @@ def get_operator(request: HttpRequest, counter: Counter, customer: Customer) ->
|
||||
class CounterClick(
|
||||
CounterTabsMixin, UseFragmentsMixin, CanViewMixin, SingleObjectMixin, FormView
|
||||
):
|
||||
"""The click view
|
||||
This is a detail view not to have to worry about loading the counter
|
||||
Everything is made by hand in the post method.
|
||||
"""The click view.
|
||||
|
||||
This page is reached from the counter main page, after selecting
|
||||
the user who is purchasing stuff.
|
||||
|
||||
# Counter access
|
||||
|
||||
Who can perform barman actions depends on the type of the counter :
|
||||
|
||||
- for eboutic counters, no barman access at all is granted ;
|
||||
it's just a 404, as there should be only one eboutic,
|
||||
accessible only at `/eboutic/`
|
||||
- office counters are accessible to the board members of the
|
||||
club owning the counter and to users that have been
|
||||
explicitly added to the sellers of this counter.
|
||||
- bar counters are accessible to users that have been added to
|
||||
the counter sellers and that are currently logged as barmen
|
||||
on the current device.
|
||||
|
||||
The bar case is really tricky,
|
||||
as it doesn't use the usual django auth backend.
|
||||
Barmen must not be logged in as regular users,
|
||||
but as barmen, granting the session some special privileges,
|
||||
even in the case where no regular user is logged in.
|
||||
|
||||
This is because of two reasons :
|
||||
|
||||
- we track the barmen connection, for logging,
|
||||
statistics and dick contest purposes.
|
||||
We want to know who was barman, where and when,
|
||||
as barmen are accountable of what happens during their duty.
|
||||
- multiple users must be able to log on the same device,
|
||||
while keeping the session anonymous.
|
||||
The bar PC must be a reliable way for any barman to click users,
|
||||
but without requiring a user session.
|
||||
Just imagine if someone who is superuser had to log in with
|
||||
all its privileges on a device everyone can access.
|
||||
|
||||
# Available items
|
||||
|
||||
A counter can have multiple products.
|
||||
A product can have multiple prices.
|
||||
To select what the user can buy, we select
|
||||
all the prices that can be applied to the current
|
||||
customer, among the products of the counter.
|
||||
The price selection logic is described in
|
||||
[PriceQuerySet][counter.models.PriceQuerySet].
|
||||
|
||||
On top of that, some additional rules are applied,
|
||||
because alcohol can be sold on counters :
|
||||
|
||||
- if the customer is minor (or has not filled its birthdate)
|
||||
age restricted products are removed
|
||||
([L.3342-1, Code de la santé publique](https://www.legifrance.gouv.fr/codes/article_lc/LEGIARTI000031927682))
|
||||
- if any barman on the current device is minor,
|
||||
age restricted products are also removed
|
||||
([L.3336-4, Code de la santé publique](https://www.legifrance.gouv.fr/codes/article_lc/LEGIARTI000048654800))
|
||||
|
||||
The minor barman case is a little bit unclear, legally speaking,
|
||||
as barmen are volunteers, but the law speaks only of employees and interns.
|
||||
As such, we don't apply the law to its full extent.
|
||||
It would be harsh for young students not to be able to
|
||||
be barmen at the MDE, where no alcohol at all is sold during daytime.
|
||||
However, we restrict items that can be sold as a token of good will.
|
||||
"""
|
||||
|
||||
model = Counter
|
||||
@@ -111,6 +172,19 @@ class CounterClick(
|
||||
return redirect(obj) # Redirect to counter
|
||||
|
||||
self.prices = list(obj.get_prices_for(self.customer))
|
||||
if any(user.age < 18 for user in request.barmen):
|
||||
# users without a birthdate cannot be sellers on counters,
|
||||
# so the `user.age == 0` case shouldn't happen
|
||||
filtered = [p for p in self.prices if p.product.limit_age < 18]
|
||||
if len(filtered) != len(self.prices):
|
||||
self.prices = filtered
|
||||
messages.warning(
|
||||
request,
|
||||
_(
|
||||
"A minor is barman on this on this device, "
|
||||
"so you cannot currently sell alcohol."
|
||||
),
|
||||
)
|
||||
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
::: counter.views
|
||||
@@ -0,0 +1,6 @@
|
||||
::: counter.views.click
|
||||
handler: python
|
||||
options:
|
||||
members:
|
||||
- CounterClick
|
||||
- RefillingCreateView
|
||||
@@ -0,0 +1 @@
|
||||
::: counter.views.home
|
||||
@@ -0,0 +1,7 @@
|
||||
::: counter.views.mixins
|
||||
handler: python
|
||||
options:
|
||||
heading_level: 3
|
||||
members:
|
||||
- CounterTabsMixin
|
||||
- CounterAdminTabsMixin
|
||||
@@ -0,0 +1,5 @@
|
||||
::: counter.views.admin
|
||||
::: counter.views.cash
|
||||
::: counter.views.eticket
|
||||
::: counter.views.invoice
|
||||
::: counter.views.student_card
|
||||
@@ -6,7 +6,7 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-11-06 17:22+0100\n"
|
||||
"POT-Creation-Date: 2026-11-12 15:32+0100\n"
|
||||
"PO-Revision-Date: 2016-07-18\n"
|
||||
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||
@@ -3257,6 +3257,16 @@ msgstr ""
|
||||
"Si vous souhaitez ajouter sur ce comptoir un produit qui n'appartient pas à "
|
||||
"votre club, vous devriez demander à un admin."
|
||||
|
||||
#: counter/forms.py
|
||||
#, python-format
|
||||
msgid "%(user)s is banned."
|
||||
msgstr "%(user)s est banni."
|
||||
|
||||
#: counter/forms.py
|
||||
#, python-format
|
||||
msgid "%(user)s has not filled its birthdate."
|
||||
msgstr "%(user)s n'a pas renseigné sa date de naissance."
|
||||
|
||||
#: counter/forms.py
|
||||
#, python-format
|
||||
msgid ""
|
||||
@@ -4329,6 +4339,13 @@ msgstr "Nombre de chèque"
|
||||
msgid "You cannot click users on this counter"
|
||||
msgstr "Vous ne pouvez pas cliquer des gens sur ce comptoir"
|
||||
|
||||
#: counter/views/click.py
|
||||
msgid ""
|
||||
"A minor is barman on this on this device, so you cannot currently sell "
|
||||
"alcohol."
|
||||
msgstr ""
|
||||
"Un mineur est barman sur cet appareil, vous ne pouvez donc pas vendre d'alcool actuellement."
|
||||
|
||||
#: counter/views/eticket.py
|
||||
msgid "people(s)"
|
||||
msgstr "personne(s)"
|
||||
|
||||
+5
-1
@@ -113,7 +113,11 @@ nav:
|
||||
- reference/core/auth.md
|
||||
- counter:
|
||||
- reference/counter/models.md
|
||||
- reference/counter/views.md
|
||||
- Views:
|
||||
- reference/counter/views/home.md
|
||||
- reference/counter/views/click.md
|
||||
- reference/counter/views/mixins.md
|
||||
- reference/counter/views/others.md
|
||||
- reference/counter/schemas.md
|
||||
- eboutic:
|
||||
- reference/eboutic/models.md
|
||||
|
||||
@@ -8,7 +8,10 @@ from django.utils.timezone import localtime
|
||||
from model_bakery import baker
|
||||
from pytest_django.asserts import assertRedirects
|
||||
|
||||
from core.baker_recipes import subscriber_user
|
||||
from core.models import BanGroup, User, UserBan
|
||||
from counter.models import Counter
|
||||
from sith import settings
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.test import Client
|
||||
@@ -33,11 +36,7 @@ def test_ban_user(client: Client, operator: User, expires_at: datetime):
|
||||
client.force_login(operator)
|
||||
user = baker.make(User)
|
||||
ban_group = BanGroup.objects.first()
|
||||
data = {
|
||||
"user": user.id,
|
||||
"ban_group": ban_group.id,
|
||||
"reason": "Being naughty",
|
||||
}
|
||||
data = {"user": user.id, "ban_group": ban_group.id, "reason": "Being naughty"}
|
||||
if expires_at is not None:
|
||||
data["expires_at"] = expires_at.strftime("%Y-%m-%d %H:%M")
|
||||
response = client.post(reverse("rootplace:ban_create"), data)
|
||||
@@ -49,6 +48,24 @@ def test_ban_user(client: Client, operator: User, expires_at: datetime):
|
||||
assert bans[0].ban_group == ban_group
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_ban_counter_ends_barmanship():
|
||||
user = subscriber_user.make()
|
||||
counter = baker.make(Counter)
|
||||
counter.sellers.add(user, through_defaults={"is_regular": True})
|
||||
|
||||
UserBan.objects.create(
|
||||
user=user,
|
||||
ban_group_id=settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||
reason="ban comptoir",
|
||||
)
|
||||
|
||||
# check that we did effectively delete the barmanship
|
||||
# and not the bar itself (better safe than sorry)
|
||||
assert Counter.objects.filter(id=counter.id).exists()
|
||||
assert not user.counters.exists()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_remove_ban(client: Client, operator: User):
|
||||
client.force_login(operator)
|
||||
|
||||
Reference in new issue
Block a user