From 11779231e1d72cdfbbbd18cd9d2c80820615d1af Mon Sep 17 00:00:00 2001 From: imperosol Date: Tue, 31 Mar 2026 16:58:26 +0200 Subject: [PATCH] put roles at the right place when they are created --- club/models.py | 14 ++++++++++++++ club/tests/test_clubrole.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 club/tests/test_clubrole.py diff --git a/club/models.py b/club/models.py index 58d9c139..ddf7c04c 100644 --- a/club/models.py +++ b/club/models.py @@ -278,6 +278,7 @@ class ClubRole(OrderedModel): ) if ( self.is_board + and self.order and self.club.roles.filter(is_board=False, order__lt=self.order).exists() ): errors.append( @@ -290,6 +291,19 @@ class ClubRole(OrderedModel): raise ValidationError(errors) return super().clean() + def save(self, *args, **kwargs): + auto_order = self.order is None and self.is_board + if not auto_order: + super().save(*args, **kwargs) + return + filters = Q(is_board=False) + if self.is_presidency: + filters |= Q(is_board=True, is_presidency=False) + next_role = self.club.roles.filter(filters).order_by("order").first() + super().save(*args, **kwargs) + if next_role: + self.above(next_role) + class MembershipQuerySet(models.QuerySet): def ongoing(self) -> Self: diff --git a/club/tests/test_clubrole.py b/club/tests/test_clubrole.py new file mode 100644 index 00000000..54067862 --- /dev/null +++ b/club/tests/test_clubrole.py @@ -0,0 +1,33 @@ +import pytest +from model_bakery import baker, seq +from model_bakery.recipe import Recipe + +from club.models import Club, ClubRole + + +@pytest.mark.django_db +def test_order_auto(): + """Test that newly created roles are put in the right place.""" + club = baker.make(Club) + recipe = Recipe(ClubRole, club=club, name=seq("role ")) + # bulk create initial roles + roles = recipe.make( + is_board=iter([True, True, False]), + is_presidency=iter([True, False, False]), + order=iter([1, 2, 3]), + _quantity=3, + _bulk_create=True, + ) + # then create the remaining roles one by one (like they will be in prod) + # each new role should be placed at the end of its category + role_a = recipe.make(is_board=True, is_presidency=True, order=None) + role_b = recipe.make(is_board=True, is_presidency=False, order=None) + role_c = recipe.make(is_board=False, is_presidency=False, order=None) + assert list(club.roles.order_by("order")) == [ + roles[0], + role_a, + roles[1], + role_b, + roles[2], + role_c, + ]