mirror of
https://github.com/ae-utbm/sith.git
synced 2026-05-13 20:48:06 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2922725fe4 | |||
| 2796f9b213 | |||
| f26a47c48d | |||
| 3cf843a197 | |||
| 228902e5e0 |
@@ -12,7 +12,7 @@ runs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Install apt packages
|
- name: Install apt packages
|
||||||
if: ${{ inputs.full == 'true' }}
|
if: ${{ inputs.full == 'true' }}
|
||||||
uses: awalsh128/cache-apt-pkgs-action@v1.6.0
|
uses: awalsh128/cache-apt-pkgs-action@v1.4.3
|
||||||
with:
|
with:
|
||||||
packages: gettext
|
packages: gettext
|
||||||
version: 1.0 # increment to reset cache
|
version: 1.0 # increment to reset cache
|
||||||
@@ -23,29 +23,26 @@ runs:
|
|||||||
with:
|
with:
|
||||||
redis-version: "7.x"
|
redis-version: "7.x"
|
||||||
|
|
||||||
|
- name: Install uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
version: "0.5.14"
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: "uv.lock"
|
||||||
|
|
||||||
- name: "Set up Python"
|
- name: "Set up Python"
|
||||||
uses: actions/setup-python@v6
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version-file: ".python-version"
|
python-version-file: ".python-version"
|
||||||
|
|
||||||
- name: Install uv
|
|
||||||
uses: astral-sh/setup-uv@v8.1.0
|
|
||||||
with:
|
|
||||||
version: "0.11.8"
|
|
||||||
enable-cache: false
|
|
||||||
cache-dependency-glob: "uv.lock"
|
|
||||||
|
|
||||||
- name: Restore cached virtualenv
|
- name: Restore cached virtualenv
|
||||||
uses: actions/cache@v5
|
uses: actions/cache/restore@v4
|
||||||
with:
|
with:
|
||||||
|
key: venv-${{ runner.os }}-${{ hashFiles('.python-version') }}-${{ hashFiles('pyproject.toml') }}-${{ env.CACHE_SUFFIX }}
|
||||||
path: .venv
|
path: .venv
|
||||||
key: uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
|
|
||||||
restore-keys: |
|
|
||||||
uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
|
|
||||||
uv-${{ runner.os }}
|
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: uv sync --locked
|
run: uv sync
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Install Xapian
|
- name: Install Xapian
|
||||||
@@ -53,6 +50,15 @@ runs:
|
|||||||
run: uv run ./manage.py install_xapian
|
run: uv run ./manage.py install_xapian
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
|
# compiling xapian accounts for almost the entirety of the virtualenv setup,
|
||||||
|
# so we save the virtual environment only on workflows where it has been installed
|
||||||
|
- name: Save cached virtualenv
|
||||||
|
if: ${{ inputs.full == 'true' }}
|
||||||
|
uses: actions/cache/save@v4
|
||||||
|
with:
|
||||||
|
key: venv-${{ runner.os }}-${{ hashFiles('.python-version') }}-${{ hashFiles('pyproject.toml') }}-${{ env.CACHE_SUFFIX }}
|
||||||
|
path: .venv
|
||||||
|
|
||||||
- name: Compile gettext messages
|
- name: Compile gettext messages
|
||||||
if: ${{ inputs.full == 'true' }}
|
if: ${{ inputs.full == 'true' }}
|
||||||
run: uv run ./manage.py compilemessages
|
run: uv run ./manage.py compilemessages
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ jobs:
|
|||||||
name: Launch pre-commits checks (ruff)
|
name: Launch pre-commits checks (ruff)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-python@v6
|
- uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version-file: ".python-version"
|
python-version-file: ".python-version"
|
||||||
- uses: pre-commit/action@v3.0.1
|
- uses: pre-commit/action@v3.0.1
|
||||||
@@ -35,7 +35,7 @@ jobs:
|
|||||||
pytest-mark: [not slow]
|
pytest-mark: [not slow]
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repository
|
- name: Check out repository
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v4
|
||||||
- uses: ./.github/actions/setup_project
|
- uses: ./.github/actions/setup_project
|
||||||
with:
|
with:
|
||||||
full: true
|
full: true
|
||||||
@@ -49,7 +49,7 @@ jobs:
|
|||||||
uv run coverage report
|
uv run coverage report
|
||||||
uv run coverage html
|
uv run coverage html
|
||||||
- name: Archive code coverage results
|
- name: Archive code coverage results
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: coverage-report-${{ matrix.pytest-mark }}
|
name: coverage-report-${{ matrix.pytest-mark }}
|
||||||
path: coverage_report
|
path: coverage_report
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: SSH Remote Commands
|
- name: SSH Remote Commands
|
||||||
uses: appleboy/ssh-action@v1.2.5
|
uses: appleboy/ssh-action@v1.1.0
|
||||||
with:
|
with:
|
||||||
# Proxy
|
# Proxy
|
||||||
proxy_host : ${{secrets.PROXY_HOST}}
|
proxy_host : ${{secrets.PROXY_HOST}}
|
||||||
@@ -29,6 +29,8 @@ jobs:
|
|||||||
username : ${{secrets.USER}}
|
username : ${{secrets.USER}}
|
||||||
key: ${{secrets.KEY}}
|
key: ${{secrets.KEY}}
|
||||||
|
|
||||||
|
script_stop: true
|
||||||
|
|
||||||
# See https://github.com/ae-utbm/sith/wiki/GitHub-Actions#deployment-action
|
# See https://github.com/ae-utbm/sith/wiki/GitHub-Actions#deployment-action
|
||||||
script: |
|
script: |
|
||||||
cd ${{secrets.SITH_PATH}}
|
cd ${{secrets.SITH_PATH}}
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ jobs:
|
|||||||
deploy:
|
deploy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v4
|
||||||
- uses: ./.github/actions/setup_project
|
- uses: ./.github/actions/setup_project
|
||||||
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
|
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
|
||||||
- uses: actions/cache@v5
|
- uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
key: mkdocs-material-${{ env.cache_id }}
|
key: mkdocs-material-${{ env.cache_id }}
|
||||||
path: .cache
|
path: .cache
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: SSH Remote Commands
|
- name: SSH Remote Commands
|
||||||
uses: appleboy/ssh-action@v1.2.5
|
uses: appleboy/ssh-action@v1.1.0
|
||||||
with:
|
with:
|
||||||
# Proxy
|
# Proxy
|
||||||
proxy_host : ${{secrets.PROXY_HOST}}
|
proxy_host : ${{secrets.PROXY_HOST}}
|
||||||
@@ -28,6 +28,8 @@ jobs:
|
|||||||
username : ${{secrets.USER}}
|
username : ${{secrets.USER}}
|
||||||
key: ${{secrets.KEY}}
|
key: ${{secrets.KEY}}
|
||||||
|
|
||||||
|
script_stop: true
|
||||||
|
|
||||||
# See https://github.com/ae-utbm/sith/wiki/GitHub-Actions#deployment-action
|
# See https://github.com/ae-utbm/sith/wiki/GitHub-Actions#deployment-action
|
||||||
script: |
|
script: |
|
||||||
cd ${{secrets.SITH_PATH}}
|
cd ${{secrets.SITH_PATH}}
|
||||||
|
|||||||
@@ -24,9 +24,6 @@ node_modules/
|
|||||||
# compiled documentation
|
# compiled documentation
|
||||||
site/
|
site/
|
||||||
|
|
||||||
# rollup-bundle-visualizer report
|
|
||||||
.bundle-size-report.html
|
|
||||||
|
|
||||||
### Redis ###
|
### Redis ###
|
||||||
|
|
||||||
# Ignore redis binary dump (dump.rdb) files
|
# Ignore redis binary dump (dump.rdb) files
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
# Ruff version.
|
# Ruff version.
|
||||||
rev: v0.15.5
|
rev: v0.15.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff-check # just check the code, and print the errors
|
- id: ruff-check # just check the code, and print the errors
|
||||||
- id: ruff-check # actually fix the fixable errors, but print nothing
|
- id: ruff-check # actually fix the fixable errors, but print nothing
|
||||||
@@ -12,7 +12,7 @@ repos:
|
|||||||
rev: v0.6.1
|
rev: v0.6.1
|
||||||
hooks:
|
hooks:
|
||||||
- id: biome-check
|
- id: biome-check
|
||||||
additional_dependencies: ["@biomejs/biome@2.4.6"]
|
additional_dependencies: ["@biomejs/biome@2.3.14"]
|
||||||
- repo: https://github.com/rtts/djhtml
|
- repo: https://github.com/rtts/djhtml
|
||||||
rev: 3.0.10
|
rev: 3.0.10
|
||||||
hooks:
|
hooks:
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
},
|
},
|
||||||
"files": {
|
"files": {
|
||||||
"ignoreUnknown": false,
|
"ignoreUnknown": false,
|
||||||
"includes": ["**/static/**", "vite.config.mts"]
|
"includes": ["**/static/**"]
|
||||||
},
|
},
|
||||||
"formatter": {
|
"formatter": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
|
|||||||
+1
-28
@@ -13,10 +13,8 @@
|
|||||||
#
|
#
|
||||||
#
|
#
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.forms.models import ModelForm
|
|
||||||
from django.http import HttpRequest
|
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Club)
|
@admin.register(Club)
|
||||||
@@ -31,31 +29,6 @@ class ClubAdmin(admin.ModelAdmin):
|
|||||||
"page",
|
"page",
|
||||||
)
|
)
|
||||||
|
|
||||||
def save_model(
|
|
||||||
self,
|
|
||||||
request: HttpRequest,
|
|
||||||
obj: Club,
|
|
||||||
form: ModelForm,
|
|
||||||
change: bool, # noqa: FBT001
|
|
||||||
):
|
|
||||||
super().save_model(request, obj, form, change)
|
|
||||||
if not change:
|
|
||||||
obj.create_default_roles()
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(ClubRole)
|
|
||||||
class ClubRoleAdmin(admin.ModelAdmin):
|
|
||||||
list_display = ("name", "club", "is_board", "is_presidency")
|
|
||||||
search_fields = ("name",)
|
|
||||||
autocomplete_fields = ("club",)
|
|
||||||
list_select_related = ("club",)
|
|
||||||
list_filter = (
|
|
||||||
"is_board",
|
|
||||||
"is_presidency",
|
|
||||||
("club", admin.RelatedOnlyFieldListFilter),
|
|
||||||
)
|
|
||||||
show_facets = admin.ModelAdmin.show_facets.ALWAYS
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Membership)
|
@admin.register(Membership)
|
||||||
class MembershipAdmin(admin.ModelAdmin):
|
class MembershipAdmin(admin.ModelAdmin):
|
||||||
|
|||||||
+6
-30
@@ -6,15 +6,9 @@ from ninja_extra.pagination import PageNumberPaginationExtra
|
|||||||
from ninja_extra.schemas import PaginatedResponseSchema
|
from ninja_extra.schemas import PaginatedResponseSchema
|
||||||
|
|
||||||
from api.auth import ApiKeyAuth
|
from api.auth import ApiKeyAuth
|
||||||
from api.permissions import CanView, HasPerm
|
from api.permissions import CanAccessLookup, HasPerm
|
||||||
from club.models import Club, Membership
|
from club.models import Club, Membership
|
||||||
from club.schemas import (
|
from club.schemas import ClubSchema, ClubSearchFilterSchema, SimpleClubSchema
|
||||||
ClubSchema,
|
|
||||||
ClubSearchFilterSchema,
|
|
||||||
SimpleClubSchema,
|
|
||||||
UserMembershipSchema,
|
|
||||||
)
|
|
||||||
from core.models import User
|
|
||||||
|
|
||||||
|
|
||||||
@api_controller("/club")
|
@api_controller("/club")
|
||||||
@@ -22,11 +16,13 @@ class ClubController(ControllerBase):
|
|||||||
@route.get(
|
@route.get(
|
||||||
"/search",
|
"/search",
|
||||||
response=PaginatedResponseSchema[SimpleClubSchema],
|
response=PaginatedResponseSchema[SimpleClubSchema],
|
||||||
|
auth=[ApiKeyAuth(), SessionAuth()],
|
||||||
|
permissions=[CanAccessLookup],
|
||||||
url_name="search_club",
|
url_name="search_club",
|
||||||
)
|
)
|
||||||
@paginate(PageNumberPaginationExtra, page_size=50)
|
@paginate(PageNumberPaginationExtra, page_size=50)
|
||||||
def search_club(self, filters: Query[ClubSearchFilterSchema]):
|
def search_club(self, filters: Query[ClubSearchFilterSchema]):
|
||||||
return filters.filter(Club.objects.order_by("name")).values()
|
return filters.filter(Club.objects.all())
|
||||||
|
|
||||||
@route.get(
|
@route.get(
|
||||||
"/{int:club_id}",
|
"/{int:club_id}",
|
||||||
@@ -37,28 +33,8 @@ class ClubController(ControllerBase):
|
|||||||
)
|
)
|
||||||
def fetch_club(self, club_id: int):
|
def fetch_club(self, club_id: int):
|
||||||
prefetch = Prefetch(
|
prefetch = Prefetch(
|
||||||
"members",
|
"members", queryset=Membership.objects.ongoing().select_related("user")
|
||||||
queryset=Membership.objects.ongoing().select_related("user", "role"),
|
|
||||||
)
|
)
|
||||||
return self.get_object_or_exception(
|
return self.get_object_or_exception(
|
||||||
Club.objects.prefetch_related(prefetch), id=club_id
|
Club.objects.prefetch_related(prefetch), id=club_id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@api_controller("/user/{int:user_id}/club")
|
|
||||||
class UserClubController(ControllerBase):
|
|
||||||
@route.get(
|
|
||||||
"",
|
|
||||||
response=list[UserMembershipSchema],
|
|
||||||
auth=[ApiKeyAuth(), SessionAuth()],
|
|
||||||
permissions=[CanView],
|
|
||||||
url_name="fetch_user_clubs",
|
|
||||||
)
|
|
||||||
def fetch_user_clubs(self, user_id: int):
|
|
||||||
"""Get all the active memberships of the given user."""
|
|
||||||
user = self.get_object_or_exception(User, id=user_id)
|
|
||||||
return (
|
|
||||||
Membership.objects.ongoing()
|
|
||||||
.filter(user=user)
|
|
||||||
.select_related("club", "user", "role")
|
|
||||||
)
|
|
||||||
|
|||||||
+27
-42
@@ -23,12 +23,13 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.db.models import Exists, OuterRef, Q, QuerySet
|
from django.conf import settings
|
||||||
|
from django.db.models import Exists, OuterRef, Q
|
||||||
from django.db.models.functions import Lower
|
from django.db.models.functions import Lower
|
||||||
from django.utils.functional import cached_property
|
from django.utils.functional import cached_property
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Mailing, MailingSubscription, Membership
|
from club.models import Club, Mailing, MailingSubscription, Membership
|
||||||
from core.models import User
|
from core.models import User
|
||||||
from core.views.forms import SelectDateTime
|
from core.views.forms import SelectDateTime
|
||||||
from core.views.widgets.ajax_select import (
|
from core.views.widgets.ajax_select import (
|
||||||
@@ -214,7 +215,9 @@ class ClubOldMemberForm(forms.Form):
|
|||||||
|
|
||||||
def __init__(self, *args, user: User, club: Club, **kwargs):
|
def __init__(self, *args, user: User, club: Club, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self.fields["members_old"].queryset = club.members.ongoing().editable_by(user)
|
self.fields["members_old"].queryset = (
|
||||||
|
Membership.objects.ongoing().filter(club=club).editable_by(user)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ClubMemberForm(forms.ModelForm):
|
class ClubMemberForm(forms.ModelForm):
|
||||||
@@ -232,14 +235,19 @@ class ClubMemberForm(forms.ModelForm):
|
|||||||
self.request_user = request_user
|
self.request_user = request_user
|
||||||
self.request_user_membership = self.club.get_membership_for(self.request_user)
|
self.request_user_membership = self.club.get_membership_for(self.request_user)
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self.fields["role"].queryset = self.available_roles
|
self.fields["role"].required = True
|
||||||
|
self.fields["role"].choices = [
|
||||||
|
(value, name)
|
||||||
|
for value, name in settings.SITH_CLUB_ROLES.items()
|
||||||
|
if value <= self.max_available_role
|
||||||
|
]
|
||||||
self.instance.club = club
|
self.instance.club = club
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def available_roles(self) -> QuerySet[ClubRole]:
|
def max_available_role(self):
|
||||||
"""The roles that will be obtainable with this form."""
|
"""The greatest role that will be obtainable with this form."""
|
||||||
# this is unreachable, because it will be overridden by subclasses
|
# this is unreachable, because it will be overridden by subclasses
|
||||||
return ClubRole.objects.none() # pragma: no cover
|
return -1 # pragma: no cover
|
||||||
|
|
||||||
|
|
||||||
class ClubAddMemberForm(ClubMemberForm):
|
class ClubAddMemberForm(ClubMemberForm):
|
||||||
@@ -250,22 +258,21 @@ class ClubAddMemberForm(ClubMemberForm):
|
|||||||
widgets = {"user": AutoCompleteSelectUser}
|
widgets = {"user": AutoCompleteSelectUser}
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def available_roles(self):
|
def max_available_role(self):
|
||||||
"""The roles that will be obtainable with this form.
|
"""The greatest role that will be obtainable with this form.
|
||||||
|
|
||||||
Admins and the club president can attribute any role.
|
Admins and the club president can attribute any role.
|
||||||
Board members can attribute roles lower than their own.
|
Board members can attribute roles lower than their own.
|
||||||
Other users cannot attribute roles with this form
|
Other users cannot attribute roles with this form
|
||||||
"""
|
"""
|
||||||
qs = self.club.roles.filter(is_active=True)
|
|
||||||
if self.request_user.has_perm("club.add_membership"):
|
if self.request_user.has_perm("club.add_membership"):
|
||||||
return qs.all()
|
return settings.SITH_CLUB_ROLES_ID["President"]
|
||||||
membership = self.request_user_membership
|
membership = self.request_user_membership
|
||||||
if membership is None or not membership.role.is_board:
|
if membership is None or membership.role <= settings.SITH_MAXIMUM_FREE_ROLE:
|
||||||
return ClubRole.objects.none()
|
return -1
|
||||||
if membership.role.is_presidency:
|
if membership.role == settings.SITH_CLUB_ROLES_ID["President"]:
|
||||||
return qs.all()
|
return membership.role
|
||||||
return qs.above_instance(membership.role)
|
return membership.role - 1
|
||||||
|
|
||||||
def clean_user(self):
|
def clean_user(self):
|
||||||
"""Check that the user is not trying to add a user already in the club.
|
"""Check that the user is not trying to add a user already in the club.
|
||||||
@@ -289,11 +296,13 @@ class JoinClubForm(ClubMemberForm):
|
|||||||
|
|
||||||
def __init__(self, *args, club: Club, request_user: User, **kwargs):
|
def __init__(self, *args, club: Club, request_user: User, **kwargs):
|
||||||
super().__init__(*args, club=club, request_user=request_user, **kwargs)
|
super().__init__(*args, club=club, request_user=request_user, **kwargs)
|
||||||
|
# this form doesn't manage the user who will join the club,
|
||||||
|
# so we must set this here to avoid errors
|
||||||
self.instance.user = self.request_user
|
self.instance.user = self.request_user
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def available_roles(self):
|
def max_available_role(self):
|
||||||
return self.club.roles.filter(is_board=False, is_active=True)
|
return settings.SITH_MAXIMUM_FREE_ROLE
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
"""Check that the user is subscribed and isn't already in the club."""
|
"""Check that the user is subscribed and isn't already in the club."""
|
||||||
@@ -306,27 +315,3 @@ class JoinClubForm(ClubMemberForm):
|
|||||||
_("You are already a member of this club"), code="invalid"
|
_("You are already a member of this club"), code="invalid"
|
||||||
)
|
)
|
||||||
return super().clean()
|
return super().clean()
|
||||||
|
|
||||||
|
|
||||||
class ClubSearchForm(forms.ModelForm):
|
|
||||||
class Meta:
|
|
||||||
model = Club
|
|
||||||
fields = ["name"]
|
|
||||||
widgets = {"name": forms.SearchInput(attrs={"autocomplete": "off"})}
|
|
||||||
|
|
||||||
club_status = forms.NullBooleanField(
|
|
||||||
label=_("Club status"),
|
|
||||||
widget=forms.RadioSelect(
|
|
||||||
choices=[(True, _("Active")), (False, _("Inactive")), ("", _("All clubs"))],
|
|
||||||
),
|
|
||||||
initial=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
def __init__(self, *args, data: dict | None = None, **kwargs):
|
|
||||||
super().__init__(*args, data=data, **kwargs)
|
|
||||||
if data is not None and "club_status" not in data:
|
|
||||||
# if the key is missing, it is considered as None,
|
|
||||||
# even though we want the default True value to be applied in such a case
|
|
||||||
# so we enforce it.
|
|
||||||
self.fields["club_status"].value = True
|
|
||||||
self.fields["name"].required = False
|
|
||||||
|
|||||||
@@ -2,15 +2,12 @@
|
|||||||
|
|
||||||
import django.db.models.deletion
|
import django.db.models.deletion
|
||||||
import django.db.models.functions.datetime
|
import django.db.models.functions.datetime
|
||||||
|
from django.conf import settings
|
||||||
from django.db import migrations, models
|
from django.db import migrations, models
|
||||||
from django.db.migrations.state import StateApps
|
from django.db.migrations.state import StateApps
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from django.utils.timezone import localdate
|
from django.utils.timezone import localdate
|
||||||
|
|
||||||
# Before the club role rework, the maximum free role
|
|
||||||
# was the hardcoded highest non-board role
|
|
||||||
MAXIMUM_FREE_ROLE = 1
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_meta_groups(apps: StateApps, schema_editor):
|
def migrate_meta_groups(apps: StateApps, schema_editor):
|
||||||
"""Attach the existing meta groups to the clubs.
|
"""Attach the existing meta groups to the clubs.
|
||||||
@@ -49,7 +46,10 @@ def migrate_meta_groups(apps: StateApps, schema_editor):
|
|||||||
).select_related("user")
|
).select_related("user")
|
||||||
club.members_group.users.set([m.user for m in memberships])
|
club.members_group.users.set([m.user for m in memberships])
|
||||||
club.board_group.users.set(
|
club.board_group.users.set(
|
||||||
[m.user for m in memberships.filter(role__gt=MAXIMUM_FREE_ROLE)]
|
[
|
||||||
|
m.user
|
||||||
|
for m in memberships.filter(role__gt=settings.SITH_MAXIMUM_FREE_ROLE)
|
||||||
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,158 +0,0 @@
|
|||||||
# Generated by Django 5.2.3 on 2025-06-21 21:59
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
from django.db.migrations.state import StateApps
|
|
||||||
from django.db.models import Case, When
|
|
||||||
|
|
||||||
PRESIDENCY_ROLES = [10, 9]
|
|
||||||
MAXIMUM_FREE_ROLE = 1
|
|
||||||
SITH_CLUB_ROLES = {
|
|
||||||
10: "Président⸱e",
|
|
||||||
9: "Vice-Président⸱e",
|
|
||||||
7: "Trésorier⸱e",
|
|
||||||
5: "Responsable communication",
|
|
||||||
4: "Secrétaire",
|
|
||||||
3: "Responsable info",
|
|
||||||
2: "Membre du bureau",
|
|
||||||
1: "Membre actif⸱ve",
|
|
||||||
0: "Curieux⸱euse",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_roles(apps: StateApps, schema_editor):
|
|
||||||
ClubRole = apps.get_model("club", "ClubRole")
|
|
||||||
Membership = apps.get_model("club", "Membership")
|
|
||||||
|
|
||||||
updates = []
|
|
||||||
for club_id, role in Membership.objects.values_list("club", "role").distinct():
|
|
||||||
new_role = ClubRole.objects.create(
|
|
||||||
name=SITH_CLUB_ROLES[role],
|
|
||||||
is_board=role > MAXIMUM_FREE_ROLE,
|
|
||||||
is_presidency=role in PRESIDENCY_ROLES,
|
|
||||||
club_id=club_id,
|
|
||||||
order=max(SITH_CLUB_ROLES) - role,
|
|
||||||
)
|
|
||||||
updates.append(When(role=role, then=new_role.id))
|
|
||||||
# all updates must happen at the same time
|
|
||||||
# otherwise, the 10 first created ClubRole would be
|
|
||||||
# re-modified after their initial creation, and it would
|
|
||||||
# result in an incoherent state.
|
|
||||||
# To avoid that, all updates are wrapped in a single giant Case(When) statement
|
|
||||||
# cf. https://docs.djangoproject.com/fr/stable/ref/models/conditional-expressions/#conditional-update
|
|
||||||
Membership.objects.update(role=Case(*updates))
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("club", "0014_alter_club_options_rename_unix_name_club_slug_name_and_more"),
|
|
||||||
("core", "0047_alter_notification_date_alter_notification_type"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="club",
|
|
||||||
name="page",
|
|
||||||
field=models.OneToOneField(
|
|
||||||
blank=True,
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="club",
|
|
||||||
to="core.page",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="ClubRole",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.AutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"order",
|
|
||||||
models.PositiveIntegerField(
|
|
||||||
db_index=True, editable=False, verbose_name="order"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"club",
|
|
||||||
models.ForeignKey(
|
|
||||||
help_text="The club with which this role is associated",
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
related_name="roles",
|
|
||||||
to="club.club",
|
|
||||||
verbose_name="club",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
("name", models.CharField(max_length=50, verbose_name="name")),
|
|
||||||
(
|
|
||||||
"description",
|
|
||||||
models.TextField(
|
|
||||||
default="", blank=True, verbose_name="description"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"is_board",
|
|
||||||
models.BooleanField(default=False, verbose_name="Board role"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"is_presidency",
|
|
||||||
models.BooleanField(default=False, verbose_name="Presidency role"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"is_active",
|
|
||||||
models.BooleanField(
|
|
||||||
default=True,
|
|
||||||
help_text=(
|
|
||||||
"If the role is inactive, people joining the club "
|
|
||||||
"won't be able to get it."
|
|
||||||
),
|
|
||||||
verbose_name="is active",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
"ordering": ("order",),
|
|
||||||
"verbose_name": "club role",
|
|
||||||
"verbose_name_plural": "club roles",
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="club",
|
|
||||||
name="board_group",
|
|
||||||
field=models.OneToOneField(
|
|
||||||
editable=False,
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="club_board",
|
|
||||||
to="core.group",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="club",
|
|
||||||
name="members_group",
|
|
||||||
field=models.OneToOneField(
|
|
||||||
editable=False,
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="club",
|
|
||||||
to="core.group",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AddConstraint(
|
|
||||||
model_name="clubrole",
|
|
||||||
constraint=models.CheckConstraint(
|
|
||||||
condition=models.Q(
|
|
||||||
("is_presidency", False), ("is_board", True), _connector="OR"
|
|
||||||
),
|
|
||||||
name="clubrole_presidency_implies_board",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.RunPython(migrate_roles, migrations.RunPython.noop),
|
|
||||||
# because Postgres migrations run in a single transaction,
|
|
||||||
# we cannot change the actual values of Membership.role
|
|
||||||
# and apply the FOREIGN KEY constraint in the same migration.
|
|
||||||
# The constraint is created in the next migration
|
|
||||||
]
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
# Generated by Django 5.2.3 on 2025-09-27 09:57
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [("club", "0015_clubrole_alter_membership_role")]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
# because Postgres migrations run in a single transaction,
|
|
||||||
# we cannot change the actual values of Membership.role
|
|
||||||
# and apply the FOREIGN KEY constraint in the same migration.
|
|
||||||
# The data migration was made in the previous migration.
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="membership",
|
|
||||||
name="role",
|
|
||||||
field=models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="members",
|
|
||||||
to="club.clubrole",
|
|
||||||
verbose_name="role",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
+29
-163
@@ -28,15 +28,15 @@ from typing import Iterable, Self
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
||||||
from django.core.validators import RegexValidator, validate_email
|
from django.core.validators import RegexValidator, validate_email
|
||||||
from django.db import ProgrammingError, models, transaction
|
from django.db import models, transaction
|
||||||
from django.db.models import Exists, F, OuterRef, Q
|
from django.db.models import Exists, F, OuterRef, Q, Value
|
||||||
|
from django.db.models.functions import Greatest
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.utils.functional import cached_property
|
from django.utils.functional import cached_property
|
||||||
from django.utils.text import slugify
|
from django.utils.text import slugify
|
||||||
from django.utils.timezone import localdate
|
from django.utils.timezone import localdate
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from ordered_model.models import OrderedModel
|
|
||||||
|
|
||||||
from core.fields import ResizedImageField
|
from core.fields import ResizedImageField
|
||||||
from core.models import Group, Notification, Page, SithFile, User
|
from core.models import Group, Notification, Page, SithFile, User
|
||||||
@@ -89,13 +89,13 @@ class Club(models.Model):
|
|||||||
on_delete=models.SET_NULL,
|
on_delete=models.SET_NULL,
|
||||||
)
|
)
|
||||||
page = models.OneToOneField(
|
page = models.OneToOneField(
|
||||||
Page, related_name="club", blank=True, on_delete=models.PROTECT
|
Page, related_name="club", blank=True, on_delete=models.CASCADE
|
||||||
)
|
)
|
||||||
members_group = models.OneToOneField(
|
members_group = models.OneToOneField(
|
||||||
Group, related_name="club", on_delete=models.PROTECT, editable=False
|
Group, related_name="club", on_delete=models.PROTECT
|
||||||
)
|
)
|
||||||
board_group = models.OneToOneField(
|
board_group = models.OneToOneField(
|
||||||
Group, related_name="club_board", on_delete=models.PROTECT, editable=False
|
Group, related_name="club_board", on_delete=models.PROTECT
|
||||||
)
|
)
|
||||||
|
|
||||||
objects = ClubQuerySet.as_manager()
|
objects = ClubQuerySet.as_manager()
|
||||||
@@ -138,7 +138,9 @@ class Club(models.Model):
|
|||||||
@cached_property
|
@cached_property
|
||||||
def president(self) -> Membership | None:
|
def president(self) -> Membership | None:
|
||||||
"""Fetch the membership of the current president of this club."""
|
"""Fetch the membership of the current president of this club."""
|
||||||
return self.members.filter(end_date=None).order_by("role__order").first()
|
return self.members.filter(
|
||||||
|
role=settings.SITH_CLUB_ROLES_ID["President"], end_date=None
|
||||||
|
).first()
|
||||||
|
|
||||||
def check_loop(self):
|
def check_loop(self):
|
||||||
"""Raise a validation error when a loop is found within the parent list."""
|
"""Raise a validation error when a loop is found within the parent list."""
|
||||||
@@ -183,40 +185,6 @@ class Club(models.Model):
|
|||||||
self.page.parent = self.parent.page
|
self.page.parent = self.parent.page
|
||||||
self.page.save(force_lock=True)
|
self.page.save(force_lock=True)
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
def delete(self, *args, **kwargs) -> tuple[int, dict[str, int]]:
|
def delete(self, *args, **kwargs) -> tuple[int, dict[str, int]]:
|
||||||
self.board_group.delete()
|
self.board_group.delete()
|
||||||
self.members_group.delete()
|
self.members_group.delete()
|
||||||
@@ -240,9 +208,7 @@ class Club(models.Model):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def current_members(self) -> list[Membership]:
|
def current_members(self) -> list[Membership]:
|
||||||
return list(
|
return list(self.members.ongoing().select_related("user").order_by("-role"))
|
||||||
self.members.ongoing().select_related("user", "role").order_by("-role")
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_membership_for(self, user: User) -> Membership | None:
|
def get_membership_for(self, user: User) -> Membership | None:
|
||||||
"""Return the current membership of the given user."""
|
"""Return the current membership of the given user."""
|
||||||
@@ -254,105 +220,6 @@ class Club(models.Model):
|
|||||||
return user.is_in_group(pk=self.board_group_id)
|
return user.is_in_group(pk=self.board_group_id)
|
||||||
|
|
||||||
|
|
||||||
class ClubRole(OrderedModel):
|
|
||||||
club = models.ForeignKey(
|
|
||||||
Club,
|
|
||||||
verbose_name=_("club"),
|
|
||||||
help_text=_("The club with which this role is associated"),
|
|
||||||
related_name="roles",
|
|
||||||
on_delete=models.CASCADE,
|
|
||||||
)
|
|
||||||
name = models.CharField(_("name"), max_length=50)
|
|
||||||
description = models.TextField(_("description"), blank=True, default="")
|
|
||||||
is_board = models.BooleanField(_("Board role"), default=False)
|
|
||||||
is_presidency = models.BooleanField(_("Presidency role"), default=False)
|
|
||||||
is_active = models.BooleanField(
|
|
||||||
_("is active"),
|
|
||||||
default=True,
|
|
||||||
help_text=_(
|
|
||||||
"If the role is inactive, people joining the club won't be able to get it."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
order_with_respect_to = "club"
|
|
||||||
|
|
||||||
class Meta(OrderedModel.Meta):
|
|
||||||
verbose_name = _("club role")
|
|
||||||
verbose_name_plural = _("club roles")
|
|
||||||
constraints = [
|
|
||||||
# presidency IMPLIES board <=> NOT presidency OR board
|
|
||||||
# cf. MT1 :)
|
|
||||||
models.CheckConstraint(
|
|
||||||
condition=Q(is_presidency=False) | Q(is_board=True),
|
|
||||||
name="clubrole_presidency_implies_board",
|
|
||||||
)
|
|
||||||
]
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.name
|
|
||||||
|
|
||||||
def get_display_name(self):
|
|
||||||
return f"{self.name} - {self.club.name}"
|
|
||||||
|
|
||||||
def get_absolute_url(self):
|
|
||||||
return reverse("club:club_roles", kwargs={"club_id": self.club_id})
|
|
||||||
|
|
||||||
def clean(self):
|
|
||||||
errors = []
|
|
||||||
if self.is_presidency and not self.is_board:
|
|
||||||
errors.append(
|
|
||||||
ValidationError(
|
|
||||||
_(
|
|
||||||
"Role %(name)s was declared as a presidency role "
|
|
||||||
"without being a board role"
|
|
||||||
)
|
|
||||||
% {"name": self.name}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
roles = list(self.club.roles.all())
|
|
||||||
if (
|
|
||||||
self.is_board
|
|
||||||
and self.order
|
|
||||||
and any(r.order < self.order and not r.is_board for r in roles)
|
|
||||||
):
|
|
||||||
errors.append(
|
|
||||||
ValidationError(
|
|
||||||
_("Role %(role)s cannot be placed below a member role")
|
|
||||||
% {"role": self.name}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if (
|
|
||||||
self.is_presidency
|
|
||||||
and self.order
|
|
||||||
and any(r.order < self.order and not r.is_presidency for r in roles)
|
|
||||||
):
|
|
||||||
errors.append(
|
|
||||||
ValidationError(
|
|
||||||
_("Role %(role)s cannot be placed below a non-presidency role")
|
|
||||||
% {"role": self.name}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if errors:
|
|
||||||
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
|
|
||||||
# get the role that should be placed after the role we are dealing with.
|
|
||||||
# So, if this is role is presidency, get the first board role ;
|
|
||||||
# if it is a board role, get the first member role ;
|
|
||||||
# and if it is a member role, get nothing (OrderedModel.save will
|
|
||||||
# automatically put it in the last position anyway)
|
|
||||||
filters = {"is_board": self.is_presidency, "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):
|
class MembershipQuerySet(models.QuerySet):
|
||||||
def ongoing(self) -> Self:
|
def ongoing(self) -> Self:
|
||||||
"""Filter all memberships which are not finished yet."""
|
"""Filter all memberships which are not finished yet."""
|
||||||
@@ -365,10 +232,9 @@ class MembershipQuerySet(models.QuerySet):
|
|||||||
are included, even if there are no more members.
|
are included, even if there are no more members.
|
||||||
|
|
||||||
If you want to get the users who are currently in the board,
|
If you want to get the users who are currently in the board,
|
||||||
mind combining this with the [MembershipQuerySet.ongoing][]
|
mind combining this with the `ongoing` queryset method
|
||||||
queryset method
|
|
||||||
"""
|
"""
|
||||||
return self.filter(role__is_board=True)
|
return self.filter(role__gt=settings.SITH_MAXIMUM_FREE_ROLE)
|
||||||
|
|
||||||
def editable_by(self, user: User) -> Self:
|
def editable_by(self, user: User) -> Self:
|
||||||
"""Filter Memberships that this user can edit.
|
"""Filter Memberships that this user can edit.
|
||||||
@@ -391,16 +257,21 @@ class MembershipQuerySet(models.QuerySet):
|
|||||||
"""
|
"""
|
||||||
if user.has_perm("club.change_membership"):
|
if user.has_perm("club.change_membership"):
|
||||||
return self.all()
|
return self.all()
|
||||||
return self.ongoing().filter(
|
return self.filter(
|
||||||
Q(user=user)
|
Q(user=user)
|
||||||
| Exists(
|
| Exists(
|
||||||
Membership.objects.ongoing().filter(
|
Membership.objects.filter(
|
||||||
|
Q(
|
||||||
|
role__gt=Greatest(
|
||||||
|
OuterRef("role"), Value(settings.SITH_MAXIMUM_FREE_ROLE)
|
||||||
|
)
|
||||||
|
),
|
||||||
user=user,
|
user=user,
|
||||||
|
end_date=None,
|
||||||
club=OuterRef("club"),
|
club=OuterRef("club"),
|
||||||
role__is_board=True,
|
|
||||||
role__order__lt=OuterRef("role__order"),
|
|
||||||
)
|
)
|
||||||
)
|
),
|
||||||
|
end_date=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
def update(self, **kwargs) -> int:
|
def update(self, **kwargs) -> int:
|
||||||
@@ -470,11 +341,10 @@ class Membership(models.Model):
|
|||||||
)
|
)
|
||||||
start_date = models.DateField(_("start date"), default=timezone.now)
|
start_date = models.DateField(_("start date"), default=timezone.now)
|
||||||
end_date = models.DateField(_("end date"), null=True, blank=True)
|
end_date = models.DateField(_("end date"), null=True, blank=True)
|
||||||
role = models.ForeignKey(
|
role = models.IntegerField(
|
||||||
ClubRole,
|
_("role"),
|
||||||
verbose_name=_("role"),
|
choices=sorted(settings.SITH_CLUB_ROLES.items()),
|
||||||
related_name="members",
|
default=sorted(settings.SITH_CLUB_ROLES.items())[0][0],
|
||||||
on_delete=models.PROTECT,
|
|
||||||
)
|
)
|
||||||
description = models.CharField(
|
description = models.CharField(
|
||||||
_("description"), max_length=128, null=False, blank=True
|
_("description"), max_length=128, null=False, blank=True
|
||||||
@@ -492,7 +362,7 @@ class Membership(models.Model):
|
|||||||
def __str__(self):
|
def __str__(self):
|
||||||
return (
|
return (
|
||||||
f"{self.club.name} - {self.user.username} "
|
f"{self.club.name} - {self.user.username} "
|
||||||
f"- {self.role.name} "
|
f"- {settings.SITH_CLUB_ROLES[self.role]} "
|
||||||
f"- {str(_('past member')) if self.end_date is not None else ''}"
|
f"- {str(_('past member')) if self.end_date is not None else ''}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -521,11 +391,7 @@ class Membership(models.Model):
|
|||||||
if user.is_root or user.is_board_member:
|
if user.is_root or user.is_board_member:
|
||||||
return True
|
return True
|
||||||
membership = self.club.get_membership_for(user)
|
membership = self.club.get_membership_for(user)
|
||||||
if not membership:
|
return membership is not None and membership.role >= self.role
|
||||||
return False
|
|
||||||
return membership.user_id == user.id or (
|
|
||||||
membership.is_board and membership.role.order < self.role.order
|
|
||||||
)
|
|
||||||
|
|
||||||
def delete(self, *args, **kwargs):
|
def delete(self, *args, **kwargs):
|
||||||
self._remove_club_groups([self])
|
self._remove_club_groups([self])
|
||||||
@@ -601,7 +467,7 @@ class Membership(models.Model):
|
|||||||
group_id=membership.club.members_group_id,
|
group_id=membership.club.members_group_id,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if membership.role.is_board:
|
if membership.role > settings.SITH_MAXIMUM_FREE_ROLE:
|
||||||
club_groups.append(
|
club_groups.append(
|
||||||
User.groups.through(
|
User.groups.through(
|
||||||
user_id=membership.user_id,
|
user_id=membership.user_id,
|
||||||
|
|||||||
+3
-23
@@ -3,7 +3,7 @@ from typing import Annotated
|
|||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from ninja import FilterLookup, FilterSchema, ModelSchema
|
from ninja import FilterLookup, FilterSchema, ModelSchema
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.schemas import NonEmptyStr, SimpleUserSchema
|
from core.schemas import NonEmptyStr, SimpleUserSchema
|
||||||
|
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ class ClubProfileSchema(ModelSchema):
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Club
|
model = Club
|
||||||
fields = ["id", "name", "logo", "is_active", "short_description"]
|
fields = ["id", "name", "logo"]
|
||||||
|
|
||||||
url: str
|
url: str
|
||||||
|
|
||||||
@@ -39,21 +39,12 @@ class ClubProfileSchema(ModelSchema):
|
|||||||
return obj.get_absolute_url()
|
return obj.get_absolute_url()
|
||||||
|
|
||||||
|
|
||||||
class ClubRoleSchema(ModelSchema):
|
|
||||||
class Meta:
|
|
||||||
model = ClubRole
|
|
||||||
fields = ["id", "name", "is_presidency", "is_board"]
|
|
||||||
|
|
||||||
|
|
||||||
class ClubMemberSchema(ModelSchema):
|
class ClubMemberSchema(ModelSchema):
|
||||||
"""A schema to represent all memberships in a club."""
|
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Membership
|
model = Membership
|
||||||
fields = ["start_date", "end_date", "description"]
|
fields = ["start_date", "end_date", "role", "description"]
|
||||||
|
|
||||||
user: SimpleUserSchema
|
user: SimpleUserSchema
|
||||||
role: ClubRoleSchema
|
|
||||||
|
|
||||||
|
|
||||||
class ClubSchema(ModelSchema):
|
class ClubSchema(ModelSchema):
|
||||||
@@ -62,14 +53,3 @@ class ClubSchema(ModelSchema):
|
|||||||
fields = ["id", "name", "logo", "is_active", "short_description", "address"]
|
fields = ["id", "name", "logo", "is_active", "short_description", "address"]
|
||||||
|
|
||||||
members: list[ClubMemberSchema]
|
members: list[ClubMemberSchema]
|
||||||
|
|
||||||
|
|
||||||
class UserMembershipSchema(ModelSchema):
|
|
||||||
"""A schema to represent the active club memberships of a user."""
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Membership
|
|
||||||
fields = ["id", "start_date", "description"]
|
|
||||||
|
|
||||||
club: SimpleClubSchema
|
|
||||||
role: ClubRoleSchema
|
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
#club-list {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 2em;
|
|
||||||
padding: 2em;
|
|
||||||
|
|
||||||
.card {
|
|
||||||
display: block;
|
|
||||||
background-color: unset;
|
|
||||||
|
|
||||||
.club-image {
|
|
||||||
float: left;
|
|
||||||
margin-right: 2rem;
|
|
||||||
margin-bottom: .5rem;
|
|
||||||
width: 150px;
|
|
||||||
height: 150px;
|
|
||||||
border-radius: 10%;
|
|
||||||
background-color: rgba(173, 173, 173, 0.2);
|
|
||||||
|
|
||||||
@media screen and (max-width: 500px) {
|
|
||||||
width: 100px;
|
|
||||||
height: 100px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
i.club-image {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
justify-content: center;
|
|
||||||
color: black;
|
|
||||||
}
|
|
||||||
|
|
||||||
.content {
|
|
||||||
display: block;
|
|
||||||
text-align: justify;
|
|
||||||
|
|
||||||
h4 {
|
|
||||||
margin-top: 0;
|
|
||||||
margin-right: .5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
font-size: 100%;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -26,9 +26,10 @@
|
|||||||
{% if club.logo %}
|
{% if club.logo %}
|
||||||
<div class="club_logo"><img src="{{ club.logo.url }}" alt="{{ club.name }}"></div>
|
<div class="club_logo"><img src="{{ club.logo.url }}" alt="{{ club.name }}"></div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<h3>{{ club.name }}</h3>
|
|
||||||
{% if page_revision %}
|
{% if page_revision %}
|
||||||
{{ page_revision|markdown }}
|
{{ page_revision|markdown }}
|
||||||
|
{% else %}
|
||||||
|
<h3>{{ club.name }}</h3>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,83 +1,52 @@
|
|||||||
{% if is_fragment %}
|
{% extends "core/base.jinja" %}
|
||||||
{% extends "core/base_fragment.jinja" %}
|
|
||||||
|
|
||||||
{% block metatags %}
|
{% block title -%}
|
||||||
<meta property="og:url" content="{{ request.build_absolute_uri() }}" />
|
{% trans %}Club list{% endtrans %}
|
||||||
<meta property="og:type" content="website" />
|
{%- endblock %}
|
||||||
<meta property="og:title" content="Liste des clubs et assos" />
|
|
||||||
<meta property="og:image" content="{{ request.build_absolute_uri(static("core/img/logo_no_text.png")) }}" />
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{# Don't display tabs and errors #}
|
{% block description -%}
|
||||||
{% block tabs %}
|
{% trans %}The list of all clubs existing at UTBM.{% endtrans %}
|
||||||
{% endblock %}
|
{%- endblock %}
|
||||||
{% block errors %}
|
|
||||||
{% endblock %}
|
|
||||||
{% else %}
|
|
||||||
{% extends "core/base.jinja" %}
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("club/list.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
{% block description -%}
|
|
||||||
{% trans %}The list of all clubs existing at UTBM.{% endtrans %}
|
|
||||||
{%- endblock %}
|
|
||||||
{% block title -%}
|
|
||||||
{% trans %}Club list{% endtrans %}
|
|
||||||
{%- endblock %}
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% from "core/macros.jinja" import paginate_htmx %}
|
{% macro display_club(club) -%}
|
||||||
|
|
||||||
|
{% if club.is_active or user.is_root %}
|
||||||
|
|
||||||
|
<li><a href="{{ url('club:club_view', club_id=club.id) }}">{{ club.name }}</a>
|
||||||
|
|
||||||
|
{% if not club.is_active %}
|
||||||
|
({% trans %}inactive{% endtrans %})
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if club.president %} - <a href="{{ url('core:user_profile', user_id=club.president.user.id) }}">{{ club.president.user }}</a>{% endif %}
|
||||||
|
{% if club.short_description %}<p>{{ club.short_description|markdown }}</p>{% endif %}
|
||||||
|
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{%- if club.children.all()|length != 0 %}
|
||||||
|
<ul>
|
||||||
|
{%- for c in club.children.order_by('name').prefetch_related("children") %}
|
||||||
|
{{ display_club(c) }}
|
||||||
|
{%- endfor %}
|
||||||
|
</ul>
|
||||||
|
{%- endif -%}
|
||||||
|
</li>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<main>
|
{% if user.is_root %}
|
||||||
<h3>{% trans %}Filters{% endtrans %}</h3>
|
<p><a href="{{ url('club:club_new') }}">{% trans %}New club{% endtrans %}</a></p>
|
||||||
<form
|
{% endif %}
|
||||||
id="club-list-filters"
|
{% if club_list %}
|
||||||
hx-get="{{ url("club:club_list") }}"
|
|
||||||
hx-target="#content"
|
|
||||||
hx-swap="outerHtml"
|
|
||||||
hx-push-url="true"
|
|
||||||
>
|
|
||||||
<div class="row gap-4x">
|
|
||||||
{{ form }}
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-blue margin-bottom">
|
|
||||||
<i class="fa fa-magnifying-glass"></i>{% trans %}Search{% endtrans %}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
<h3>{% trans %}Club list{% endtrans %}</h3>
|
<h3>{% trans %}Club list{% endtrans %}</h3>
|
||||||
{% if user.has_perm("club.add_club") %}
|
<ul>
|
||||||
<br>
|
{%- for club in club_list %}
|
||||||
<a href="{{ url('club:club_new') }}" class="btn btn-blue">
|
{{ display_club(club) }}
|
||||||
<i class="fa fa-plus"></i> {% trans %}New club{% endtrans %}
|
{%- endfor %}
|
||||||
</a>
|
</ul>
|
||||||
{% endif %}
|
{% else %}
|
||||||
<section class="aria-busy-grow" id="club-list">
|
{% trans %}There is no club in this website.{% endtrans %}
|
||||||
{% for club in object_list %}
|
{% endif %}
|
||||||
<div class="card">
|
|
||||||
{% set club_url = club.get_absolute_url() %}
|
|
||||||
<a href="{{ club_url }}">
|
|
||||||
{% if club.logo %}
|
|
||||||
<img class="club-image" src="{{ club.logo.url }}" alt="logo {{ club.name }}">
|
|
||||||
{% else %}
|
|
||||||
<i class="fa-regular fa-image fa-4x club-image"></i>
|
|
||||||
{% endif %}
|
|
||||||
</a>
|
|
||||||
<div class="content">
|
|
||||||
<a href="{{ club_url }}">
|
|
||||||
<h4>
|
|
||||||
{{ club.name }} {% if not club.is_active %}({% trans %}inactive{% endtrans %}){% endif %}
|
|
||||||
</h4>
|
|
||||||
</a>
|
|
||||||
{{ club.short_description|markdown }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
</section>
|
|
||||||
{% if is_paginated %}
|
|
||||||
{{ paginate_htmx(request, page_obj, paginator) }}
|
|
||||||
{% endif %}
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
{% extends "core/base.jinja" %}
|
{% extends "core/base.jinja" %}
|
||||||
{% from 'core/macros.jinja' import user_profile_link, select_all_checkbox %}
|
{% from 'core/macros.jinja' import user_profile_link, select_all_checkbox %}
|
||||||
|
|
||||||
|
{% block additional_js %}
|
||||||
|
<script type="module" src="{{ static("bundled/core/components/ajax-select-index.ts") }}"></script>
|
||||||
|
{% endblock %}
|
||||||
{% block additional_css %}
|
{% block additional_css %}
|
||||||
|
<link rel="stylesheet" href="{{ static("bundled/core/components/ajax-select-index.css") }}">
|
||||||
<link rel="stylesheet" href="{{ static("club/members.scss") }}">
|
<link rel="stylesheet" href="{{ static("club/members.scss") }}">
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -41,7 +45,7 @@
|
|||||||
{% for m in members %}
|
{% for m in members %}
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{ user_profile_link(m.user) }}</td>
|
<td>{{ user_profile_link(m.user) }}</td>
|
||||||
<td>{{ m.role.name }}</td>
|
<td>{{ settings.SITH_CLUB_ROLES[m.role] }}</td>
|
||||||
<td>{{ m.description }}</td>
|
<td>{{ m.description }}</td>
|
||||||
<td>{{ m.start_date }}</td>
|
<td>{{ m.start_date }}</td>
|
||||||
{%- if can_end_membership -%}
|
{%- if can_end_membership -%}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
{% for member in old_members %}
|
{% for member in old_members %}
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{ user_profile_link(member.user) }}</td>
|
<td>{{ user_profile_link(member.user) }}</td>
|
||||||
<td>{{ member.role.name }}</td>
|
<td>{{ settings.SITH_CLUB_ROLES[member.role] }}</td>
|
||||||
<td>{{ member.description }}</td>
|
<td>{{ member.description }}</td>
|
||||||
<td>{{ member.start_date }}</td>
|
<td>{{ member.start_date }}</td>
|
||||||
<td>{{ member.end_date }}</td>
|
<td>{{ member.end_date }}</td>
|
||||||
|
|||||||
+5
-15
@@ -8,7 +8,7 @@ from django.utils.timezone import now
|
|||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from model_bakery.recipe import Recipe
|
from model_bakery.recipe import Recipe
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.baker_recipes import old_subscriber_user, subscriber_user
|
from core.baker_recipes import old_subscriber_user, subscriber_user
|
||||||
from core.models import User
|
from core.models import User
|
||||||
|
|
||||||
@@ -43,11 +43,6 @@ class TestClub(TestCase):
|
|||||||
|
|
||||||
cls.ae = Club.objects.get(pk=settings.SITH_MAIN_CLUB_ID)
|
cls.ae = Club.objects.get(pk=settings.SITH_MAIN_CLUB_ID)
|
||||||
cls.club = baker.make(Club)
|
cls.club = baker.make(Club)
|
||||||
cls.president_role = baker.make(
|
|
||||||
ClubRole, club=cls.club, is_board=True, is_presidency=True, order=0
|
|
||||||
)
|
|
||||||
cls.board_role = baker.make(ClubRole, club=cls.club, is_board=True, order=1)
|
|
||||||
cls.member_role = baker.make(ClubRole, club=cls.club, order=2)
|
|
||||||
cls.new_members_url = reverse(
|
cls.new_members_url = reverse(
|
||||||
"club:club_new_members", kwargs={"club_id": cls.club.id}
|
"club:club_new_members", kwargs={"club_id": cls.club.id}
|
||||||
)
|
)
|
||||||
@@ -56,17 +51,12 @@ class TestClub(TestCase):
|
|||||||
yesterday = now() - timedelta(days=1)
|
yesterday = now() - timedelta(days=1)
|
||||||
membership_recipe = Recipe(Membership, club=cls.club)
|
membership_recipe = Recipe(Membership, club=cls.club)
|
||||||
membership_recipe.make(
|
membership_recipe.make(
|
||||||
user=cls.simple_board_member, start_date=a_month_ago, role=cls.board_role
|
user=cls.simple_board_member, start_date=a_month_ago, role=3
|
||||||
)
|
|
||||||
membership_recipe.make(user=cls.richard, role=cls.member_role)
|
|
||||||
membership_recipe.make(
|
|
||||||
user=cls.president, start_date=a_month_ago, role=cls.president_role
|
|
||||||
)
|
)
|
||||||
|
membership_recipe.make(user=cls.richard, role=1)
|
||||||
|
membership_recipe.make(user=cls.president, start_date=a_month_ago, role=10)
|
||||||
membership_recipe.make( # sli was a member but isn't anymore
|
membership_recipe.make( # sli was a member but isn't anymore
|
||||||
user=cls.sli,
|
user=cls.sli, start_date=a_month_ago, end_date=yesterday, role=2
|
||||||
start_date=a_month_ago,
|
|
||||||
end_date=yesterday,
|
|
||||||
role=cls.board_role,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|||||||
+5
-105
@@ -1,18 +1,12 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django.conf import settings
|
|
||||||
from django.db import ProgrammingError
|
|
||||||
from django.test import Client
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.utils.timezone import localdate
|
from django.utils.timezone import localdate
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from model_bakery.recipe import Recipe
|
from model_bakery.recipe import Recipe
|
||||||
from pytest_django.asserts import assertRedirects
|
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import User
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -22,106 +16,12 @@ def test_club_queryset_having_board_member():
|
|||||||
membership_recipe = Recipe(
|
membership_recipe = Recipe(
|
||||||
Membership, user=user, start_date=localdate() - timedelta(days=3)
|
Membership, user=user, start_date=localdate() - timedelta(days=3)
|
||||||
)
|
)
|
||||||
|
membership_recipe.make(club=clubs[0], role=1)
|
||||||
|
membership_recipe.make(club=clubs[1], role=3)
|
||||||
|
membership_recipe.make(club=clubs[2], role=7)
|
||||||
membership_recipe.make(
|
membership_recipe.make(
|
||||||
club=clubs[0], role=baker.make(ClubRole, club=clubs[0], is_board=False)
|
club=clubs[3], role=3, end_date=localdate() - timedelta(days=1)
|
||||||
)
|
|
||||||
membership_recipe.make(
|
|
||||||
club=clubs[1], role=baker.make(ClubRole, club=clubs[1], is_board=True)
|
|
||||||
)
|
|
||||||
membership_recipe.make(
|
|
||||||
club=clubs[2], role=baker.make(ClubRole, club=clubs[2], is_board=True)
|
|
||||||
)
|
|
||||||
membership_recipe.make(
|
|
||||||
club=clubs[3],
|
|
||||||
role=baker.make(ClubRole, club=clubs[3], is_board=True),
|
|
||||||
end_date=localdate() - timedelta(days=1),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
club_ids = Club.objects.having_board_member(user).values_list("id", flat=True)
|
club_ids = Club.objects.having_board_member(user).values_list("id", flat=True)
|
||||||
assert set(club_ids) == {clubs[1].id, clubs[2].id}
|
assert set(club_ids) == {clubs[1].id, clubs[2].id}
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("nb_additional_clubs", [10, 30])
|
|
||||||
@pytest.mark.parametrize("is_fragment", [True, False])
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_club_list(client: Client, nb_additional_clubs: int, is_fragment):
|
|
||||||
client.force_login(baker.make(User))
|
|
||||||
baker.make(Club, _quantity=nb_additional_clubs)
|
|
||||||
headers = {"HX-Request": True} if is_fragment else {}
|
|
||||||
res = client.get(reverse("club:club_list"), headers=headers)
|
|
||||||
assert res.status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
def assert_club_created(club_name: str):
|
|
||||||
club = Club.objects.last()
|
|
||||||
assert club.name == club_name
|
|
||||||
assert club.board_group.name == f"{club_name} - Bureau"
|
|
||||||
assert club.members_group.name == f"{club_name} - Membres"
|
|
||||||
# default roles should be added on club creation,
|
|
||||||
# whether the creation happens on the admin site or on the user site
|
|
||||||
assert list(club.roles.values("name", "is_presidency", "is_board")) == [
|
|
||||||
{"name": "Président⸱e", "is_presidency": True, "is_board": True},
|
|
||||||
{"name": "Trésorier⸱e", "is_presidency": False, "is_board": True},
|
|
||||||
{"name": "Membre actif⸱ve", "is_presidency": False, "is_board": False},
|
|
||||||
{"name": "Curieux⸱euse", "is_presidency": False, "is_board": False},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_create_view(admin_client: Client):
|
|
||||||
"""Test that the club creation view works well"""
|
|
||||||
res = admin_client.get(reverse("club:club_new"))
|
|
||||||
assert res.status_code == 200
|
|
||||||
res = admin_client.post(
|
|
||||||
reverse("club:club_new"),
|
|
||||||
data={"name": "foo", "parent": settings.SITH_MAIN_CLUB_ID},
|
|
||||||
)
|
|
||||||
club = Club.objects.last()
|
|
||||||
assertRedirects(res, club.get_absolute_url())
|
|
||||||
assert_club_created("foo")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_default_roles_for_club_with_roles_fails():
|
|
||||||
"""Test that an Error is raised if trying to create
|
|
||||||
default roles for a club that already has roles.
|
|
||||||
"""
|
|
||||||
club = baker.make(Club)
|
|
||||||
baker.make(ClubRole, club=club)
|
|
||||||
with pytest.raises(ProgrammingError):
|
|
||||||
club.create_default_roles()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
class TestAdminInterface:
|
|
||||||
def test_create(self, admin_client: Client):
|
|
||||||
"""Test the creation of a club via the admin interface."""
|
|
||||||
res = admin_client.post(
|
|
||||||
reverse("admin:club_club_add"),
|
|
||||||
data={
|
|
||||||
"name": "foo",
|
|
||||||
"parent": settings.SITH_MAIN_CLUB_ID,
|
|
||||||
"address": "Rome",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assertRedirects(res, reverse("admin:club_club_changelist"))
|
|
||||||
assert_club_created("foo")
|
|
||||||
|
|
||||||
def test_change(self, admin_client: Client):
|
|
||||||
"""Test the edition of a club via the admin interface."""
|
|
||||||
club = baker.make(Club)
|
|
||||||
res = admin_client.post(
|
|
||||||
reverse("admin:club_club_change", kwargs={"object_id": club.id}),
|
|
||||||
data={
|
|
||||||
"name": "foo",
|
|
||||||
"page": club.page_id,
|
|
||||||
"home": club.home_id,
|
|
||||||
"address": club.address,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assertRedirects(res, reverse("admin:club_club_changelist"))
|
|
||||||
club.refresh_from_db()
|
|
||||||
assert club.name == "foo"
|
|
||||||
# Club roles shouldn't be modified when editing the club on the admin interface
|
|
||||||
# This club had no roles beforehand, therefore it shouldn't have roles now.
|
|
||||||
assert not club.roles.exists()
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django.conf import settings
|
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.test import Client, TestCase
|
from django.test import Client, TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
@@ -9,7 +8,7 @@ from model_bakery import baker
|
|||||||
from model_bakery.recipe import Recipe
|
from model_bakery.recipe import Recipe
|
||||||
from pytest_django.asserts import assertNumQueries
|
from pytest_django.asserts import assertNumQueries
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import Group, Page, User
|
from core.models import Group, Page, User
|
||||||
|
|
||||||
@@ -27,10 +26,8 @@ class TestClubSearch(TestCase):
|
|||||||
"id", flat=True
|
"id", flat=True
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
Membership.objects.all().delete()
|
Page.objects.exclude(club=None).delete()
|
||||||
ClubRole.objects.all().delete()
|
|
||||||
Club.objects.all().delete()
|
Club.objects.all().delete()
|
||||||
Page.objects.exclude(name=settings.SITH_CLUB_ROOT_PAGE).delete()
|
|
||||||
Group.objects.filter(id__in=groups).delete()
|
Group.objects.filter(id__in=groups).delete()
|
||||||
|
|
||||||
cls.clubs = baker.make(
|
cls.clubs = baker.make(
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
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 (1 presidency, 1 board, 1 member)
|
|
||||||
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,
|
|
||||||
]
|
|
||||||
+3
-13
@@ -4,7 +4,7 @@ from django.urls import reverse
|
|||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertRedirects
|
from pytest_django.asserts import assertRedirects
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
|
|
||||||
|
|
||||||
@@ -12,12 +12,7 @@ from core.baker_recipes import subscriber_user
|
|||||||
def test_club_board_member_cannot_edit_club_properties(client: Client):
|
def test_club_board_member_cannot_edit_club_properties(client: Client):
|
||||||
user = subscriber_user.make()
|
user = subscriber_user.make()
|
||||||
club = baker.make(Club, name="old name", is_active=True, address="old address")
|
club = baker.make(Club, name="old name", is_active=True, address="old address")
|
||||||
baker.make(
|
baker.make(Membership, club=club, user=user, role=7)
|
||||||
Membership,
|
|
||||||
club=club,
|
|
||||||
user=user,
|
|
||||||
role=baker.make(ClubRole, club=club, is_board=True),
|
|
||||||
)
|
|
||||||
client.force_login(user)
|
client.force_login(user)
|
||||||
res = client.post(
|
res = client.post(
|
||||||
reverse("club:club_edit", kwargs={"club_id": club.id}),
|
reverse("club:club_edit", kwargs={"club_id": club.id}),
|
||||||
@@ -37,12 +32,7 @@ def test_edit_club_page_doesnt_crash(client: Client):
|
|||||||
"""crash test for club:club_edit"""
|
"""crash test for club:club_edit"""
|
||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
user = subscriber_user.make()
|
user = subscriber_user.make()
|
||||||
baker.make(
|
baker.make(Membership, club=club, user=user, role=3)
|
||||||
Membership,
|
|
||||||
club=club,
|
|
||||||
user=user,
|
|
||||||
role=baker.make(ClubRole, club=club, is_board=True),
|
|
||||||
)
|
|
||||||
client.force_login(user)
|
client.force_login(user)
|
||||||
res = client.get(reverse("club:club_edit", kwargs={"club_id": club.id}))
|
res = client.get(reverse("club:club_edit", kwargs={"club_id": club.id}))
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
|
|||||||
@@ -3,10 +3,9 @@ from django.test import TestCase
|
|||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.utils.translation import gettext as _
|
from django.utils.translation import gettext as _
|
||||||
from model_bakery import baker
|
|
||||||
|
|
||||||
from club.forms import MailingForm
|
from club.forms import MailingForm
|
||||||
from club.models import Club, ClubRole, Mailing, Membership
|
from club.models import Club, Mailing, Membership
|
||||||
from core.models import User
|
from core.models import User
|
||||||
|
|
||||||
|
|
||||||
@@ -26,7 +25,7 @@ class TestMailingForm(TestCase):
|
|||||||
user=cls.rbatsbak,
|
user=cls.rbatsbak,
|
||||||
club=cls.club,
|
club=cls.club,
|
||||||
start_date=timezone.now(),
|
start_date=timezone.now(),
|
||||||
role=baker.make(ClubRole, club=cls.club, is_board=True),
|
role=settings.SITH_CLUB_ROLES_ID["Board member"],
|
||||||
).save()
|
).save()
|
||||||
|
|
||||||
def test_mailing_list_add_no_moderation(self):
|
def test_mailing_list_add_no_moderation(self):
|
||||||
|
|||||||
+90
-159
@@ -1,20 +1,20 @@
|
|||||||
import itertools
|
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
|
from django.conf import settings
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.db.models import Max
|
from django.db.models import Max
|
||||||
from django.test import Client, TestCase
|
from django.test import Client, TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.timezone import localdate, localtime, now
|
from django.utils.timezone import localdate, localtime, now
|
||||||
from model_bakery import baker, seq
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertRedirects
|
from pytest_django.asserts import assertRedirects
|
||||||
|
|
||||||
from club.forms import ClubAddMemberForm, JoinClubForm
|
from club.forms import ClubAddMemberForm, JoinClubForm
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from club.tests.base import TestClub
|
from club.tests.base import TestClub
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import AnonymousUser, User
|
from core.models import AnonymousUser, User
|
||||||
@@ -75,22 +75,17 @@ class TestMembershipQuerySet(TestClub):
|
|||||||
def test_update_change_club_groups(self):
|
def test_update_change_club_groups(self):
|
||||||
"""Test that `update` set the user groups accordingly."""
|
"""Test that `update` set the user groups accordingly."""
|
||||||
user = baker.make(User)
|
user = baker.make(User)
|
||||||
board_role, member_role = baker.make(
|
membership = baker.make(Membership, end_date=None, user=user, role=5)
|
||||||
ClubRole, is_board=iter([True, False]), _quantity=2, _bulk_create=True
|
|
||||||
)
|
|
||||||
membership = baker.make(
|
|
||||||
Membership, end_date=None, user=user, role=board_role, club=board_role.club
|
|
||||||
)
|
|
||||||
members_group = membership.club.members_group
|
members_group = membership.club.members_group
|
||||||
board_group = membership.club.board_group
|
board_group = membership.club.board_group
|
||||||
assert user.groups.contains(members_group)
|
assert user.groups.contains(members_group)
|
||||||
assert user.groups.contains(board_group)
|
assert user.groups.contains(board_group)
|
||||||
|
|
||||||
user.memberships.update(role=member_role) # from board to simple member
|
user.memberships.update(role=1) # from board to simple member
|
||||||
assert user.groups.contains(members_group)
|
assert user.groups.contains(members_group)
|
||||||
assert not user.groups.contains(board_group)
|
assert not user.groups.contains(board_group)
|
||||||
|
|
||||||
user.memberships.update(role=board_role) # from member to board
|
user.memberships.update(role=5) # from member to board
|
||||||
assert user.groups.contains(members_group)
|
assert user.groups.contains(members_group)
|
||||||
assert user.groups.contains(board_group)
|
assert user.groups.contains(board_group)
|
||||||
|
|
||||||
@@ -101,17 +96,7 @@ class TestMembershipQuerySet(TestClub):
|
|||||||
def test_delete_remove_from_groups(self):
|
def test_delete_remove_from_groups(self):
|
||||||
"""Test that `delete` removes from club groups"""
|
"""Test that `delete` removes from club groups"""
|
||||||
user = baker.make(User)
|
user = baker.make(User)
|
||||||
club = baker.make(Club)
|
memberships = baker.make(Membership, role=iter([1, 5]), user=user, _quantity=2)
|
||||||
roles = baker.make(
|
|
||||||
ClubRole,
|
|
||||||
is_board=iter([False, True]),
|
|
||||||
club=club,
|
|
||||||
_quantity=2,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
memberships = baker.make(
|
|
||||||
Membership, club=club, role=iter(roles), user=user, _quantity=2
|
|
||||||
)
|
|
||||||
club_groups = {
|
club_groups = {
|
||||||
memberships[0].club.members_group,
|
memberships[0].club.members_group,
|
||||||
memberships[1].club.members_group,
|
memberships[1].club.members_group,
|
||||||
@@ -127,20 +112,13 @@ class TestMembershipEditableBy(TestCase):
|
|||||||
def setUpTestData(cls):
|
def setUpTestData(cls):
|
||||||
Membership.objects.all().delete()
|
Membership.objects.all().delete()
|
||||||
cls.club_a, cls.club_b = baker.make(Club, _quantity=2)
|
cls.club_a, cls.club_b = baker.make(Club, _quantity=2)
|
||||||
roles = baker.make(
|
|
||||||
ClubRole,
|
|
||||||
is_presidency=itertools.cycle([True, False, False, False]),
|
|
||||||
is_board=itertools.cycle([True, True, True, False]),
|
|
||||||
order=itertools.cycle(range(4)),
|
|
||||||
club=iter(
|
|
||||||
[*itertools.repeat(cls.club_a, 4), *itertools.repeat(cls.club_b, 4)]
|
|
||||||
),
|
|
||||||
_quantity=8,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
cls.memberships = [
|
cls.memberships = [
|
||||||
*baker.make(Membership, role=iter(roles[:4]), club=cls.club_a, _quantity=4),
|
*baker.make(
|
||||||
*baker.make(Membership, role=iter(roles[4:]), club=cls.club_b, _quantity=4),
|
Membership, role=iter([7, 3, 3, 1]), club=cls.club_a, _quantity=4
|
||||||
|
),
|
||||||
|
*baker.make(
|
||||||
|
Membership, role=iter([7, 3, 3, 1]), club=cls.club_b, _quantity=4
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
def test_admin_user(self):
|
def test_admin_user(self):
|
||||||
@@ -162,7 +140,7 @@ class TestMembershipEditableBy(TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class TestMembership(TestClub):
|
class TestMembership(TestClub):
|
||||||
def assert_membership_started_today(self, user: User, role: ClubRole):
|
def assert_membership_started_today(self, user: User, role: int):
|
||||||
"""Assert that the given membership is active and started today."""
|
"""Assert that the given membership is active and started today."""
|
||||||
membership = user.memberships.ongoing().filter(club=self.club).first()
|
membership = user.memberships.ongoing().filter(club=self.club).first()
|
||||||
assert membership is not None
|
assert membership is not None
|
||||||
@@ -211,27 +189,21 @@ class TestMembership(TestClub):
|
|||||||
"Marquer comme ancien",
|
"Marquer comme ancien",
|
||||||
]
|
]
|
||||||
rows = table.find("tbody").find_all("tr")
|
rows = table.find("tbody").find_all("tr")
|
||||||
memberships = (
|
memberships = self.club.members.ongoing().order_by("-role")
|
||||||
self.club.members.ongoing()
|
for row, membership in zip(
|
||||||
.order_by("role__order")
|
rows, memberships.select_related("user"), strict=False
|
||||||
.select_related("user", "role")
|
):
|
||||||
)
|
|
||||||
user_role = ClubRole.objects.get(members__user=self.simple_board_member)
|
|
||||||
for row, membership in zip(rows, memberships, strict=False):
|
|
||||||
user = membership.user
|
user = membership.user
|
||||||
user_url = reverse("core:user_profile", args=[user.id])
|
user_url = reverse("core:user_profile", args=[user.id])
|
||||||
cols = row.find_all("td")
|
cols = row.find_all("td")
|
||||||
user_link = cols[0].find("a")
|
user_link = cols[0].find("a")
|
||||||
assert user_link.attrs["href"] == user_url
|
assert user_link.attrs["href"] == user_url
|
||||||
assert user_link.text == user.get_display_name()
|
assert user_link.text == user.get_display_name()
|
||||||
assert cols[1].text == membership.role.name
|
assert cols[1].text == settings.SITH_CLUB_ROLES[membership.role]
|
||||||
assert cols[2].text == membership.description
|
assert cols[2].text == membership.description
|
||||||
assert cols[3].text == str(membership.start_date)
|
assert cols[3].text == str(membership.start_date)
|
||||||
|
|
||||||
if (
|
if membership.role < 3 or membership.user_id == self.simple_board_member.id:
|
||||||
membership.role.order > user_role.order
|
|
||||||
or membership.user_id == self.simple_board_member.id
|
|
||||||
):
|
|
||||||
# 3 is the role of simple_board_member
|
# 3 is the role of simple_board_member
|
||||||
form_input = cols[4].find("input")
|
form_input = cols[4].find("input")
|
||||||
expected_attrs = {
|
expected_attrs = {
|
||||||
@@ -247,15 +219,14 @@ class TestMembership(TestClub):
|
|||||||
"""Test that root users can add members to clubs"""
|
"""Test that root users can add members to clubs"""
|
||||||
self.client.force_login(self.root)
|
self.client.force_login(self.root)
|
||||||
response = self.client.post(
|
response = self.client.post(
|
||||||
self.new_members_url,
|
self.new_members_url, {"user": self.subscriber.id, "role": 3}
|
||||||
{"user": self.subscriber.id, "role": self.board_role.id},
|
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.headers.get("HX-Redirect", "") == reverse(
|
assert response.headers.get("HX-Redirect", "") == reverse(
|
||||||
"club:club_members", kwargs={"club_id": self.club.id}
|
"club:club_members", kwargs={"club_id": self.club.id}
|
||||||
)
|
)
|
||||||
self.subscriber.refresh_from_db()
|
self.subscriber.refresh_from_db()
|
||||||
self.assert_membership_started_today(self.subscriber, role=self.board_role)
|
self.assert_membership_started_today(self.subscriber, role=3)
|
||||||
|
|
||||||
def test_add_unauthorized_members(self):
|
def test_add_unauthorized_members(self):
|
||||||
"""Test that users who are not currently subscribed
|
"""Test that users who are not currently subscribed
|
||||||
@@ -263,7 +234,7 @@ class TestMembership(TestClub):
|
|||||||
"""
|
"""
|
||||||
for user in self.public, self.old_subscriber:
|
for user in self.public, self.old_subscriber:
|
||||||
form = ClubAddMemberForm(
|
form = ClubAddMemberForm(
|
||||||
data={"user": user.id, "role": self.member_role},
|
data={"user": user.id, "role": 1},
|
||||||
request_user=self.root,
|
request_user=self.root,
|
||||||
club=self.club,
|
club=self.club,
|
||||||
)
|
)
|
||||||
@@ -284,7 +255,7 @@ class TestMembership(TestClub):
|
|||||||
nb_memberships = self.simple_board_member.memberships.count()
|
nb_memberships = self.simple_board_member.memberships.count()
|
||||||
self.client.post(
|
self.client.post(
|
||||||
self.members_url,
|
self.members_url,
|
||||||
{"users": self.simple_board_member.id, "role": self.member_role},
|
{"users": self.simple_board_member.id, "role": current_membership.role + 1},
|
||||||
)
|
)
|
||||||
self.simple_board_member.refresh_from_db()
|
self.simple_board_member.refresh_from_db()
|
||||||
assert nb_memberships == self.simple_board_member.memberships.count()
|
assert nb_memberships == self.simple_board_member.memberships.count()
|
||||||
@@ -303,7 +274,7 @@ class TestMembership(TestClub):
|
|||||||
max_id = User.objects.aggregate(id=Max("id"))["id"]
|
max_id = User.objects.aggregate(id=Max("id"))["id"]
|
||||||
for members in [max_id + 1], [max_id + 1, self.subscriber.id]:
|
for members in [max_id + 1], [max_id + 1, self.subscriber.id]:
|
||||||
form = ClubAddMemberForm(
|
form = ClubAddMemberForm(
|
||||||
data={"user": members, "role": self.member_role},
|
data={"user": members, "role": 1},
|
||||||
request_user=self.root,
|
request_user=self.root,
|
||||||
club=self.club,
|
club=self.club,
|
||||||
)
|
)
|
||||||
@@ -317,6 +288,44 @@ class TestMembership(TestClub):
|
|||||||
self.club.refresh_from_db()
|
self.club.refresh_from_db()
|
||||||
assert self.club.members.count() == nb_memberships
|
assert self.club.members.count() == nb_memberships
|
||||||
|
|
||||||
|
def test_president_add_members(self):
|
||||||
|
"""Test that the president of the club can add members."""
|
||||||
|
president = self.club.members.get(role=10).user
|
||||||
|
nb_club_membership = self.club.members.count()
|
||||||
|
nb_subscriber_memberships = self.subscriber.memberships.count()
|
||||||
|
self.client.force_login(president)
|
||||||
|
response = self.client.post(
|
||||||
|
self.new_members_url, {"user": self.subscriber.id, "role": 9}
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.headers.get("HX-Redirect", "") == reverse(
|
||||||
|
"club:club_members", kwargs={"club_id": self.club.id}
|
||||||
|
)
|
||||||
|
self.club.refresh_from_db()
|
||||||
|
self.subscriber.refresh_from_db()
|
||||||
|
assert self.club.members.count() == nb_club_membership + 1
|
||||||
|
assert self.subscriber.memberships.count() == nb_subscriber_memberships + 1
|
||||||
|
self.assert_membership_started_today(self.subscriber, role=9)
|
||||||
|
|
||||||
|
def test_add_member_greater_role(self):
|
||||||
|
"""Test that a member of the club member cannot create
|
||||||
|
a membership with a greater role than its own.
|
||||||
|
"""
|
||||||
|
form = ClubAddMemberForm(
|
||||||
|
data={"user": self.subscriber.id, "role": 10},
|
||||||
|
request_user=self.simple_board_member,
|
||||||
|
club=self.club,
|
||||||
|
)
|
||||||
|
nb_memberships = self.club.members.count()
|
||||||
|
|
||||||
|
assert not form.is_valid()
|
||||||
|
assert form.errors == {
|
||||||
|
"role": ["Sélectionnez un choix valide. 10 n\u2019en fait pas partie."]
|
||||||
|
}
|
||||||
|
self.club.refresh_from_db()
|
||||||
|
assert nb_memberships == self.club.members.count()
|
||||||
|
assert not self.subscriber.memberships.filter(club=self.club).exists()
|
||||||
|
|
||||||
def test_add_member_without_role(self):
|
def test_add_member_without_role(self):
|
||||||
"""Test that trying to add members without specifying their role fails."""
|
"""Test that trying to add members without specifying their role fails."""
|
||||||
form = ClubAddMemberForm(
|
form = ClubAddMemberForm(
|
||||||
@@ -327,9 +336,8 @@ class TestMembership(TestClub):
|
|||||||
assert form.errors == {"role": ["Ce champ est obligatoire."]}
|
assert form.errors == {"role": ["Ce champ est obligatoire."]}
|
||||||
|
|
||||||
def test_add_member_already_there(self):
|
def test_add_member_already_there(self):
|
||||||
role = ClubRole.objects.get(members__user=self.simple_board_member)
|
|
||||||
form = ClubAddMemberForm(
|
form = ClubAddMemberForm(
|
||||||
data={"user": self.simple_board_member, "role": role.id},
|
data={"user": self.simple_board_member, "role": 3},
|
||||||
request_user=self.root,
|
request_user=self.root,
|
||||||
club=self.club,
|
club=self.club,
|
||||||
)
|
)
|
||||||
@@ -340,27 +348,22 @@ class TestMembership(TestClub):
|
|||||||
|
|
||||||
def test_add_other_member_forbidden(self):
|
def test_add_other_member_forbidden(self):
|
||||||
non_member = subscriber_user.make()
|
non_member = subscriber_user.make()
|
||||||
simple_member = baker.make(
|
simple_member = baker.make(Membership, club=self.club, role=1).user
|
||||||
Membership, club=self.club, role=self.member_role
|
|
||||||
).user
|
|
||||||
for user in non_member, simple_member:
|
for user in non_member, simple_member:
|
||||||
form = ClubAddMemberForm(
|
form = ClubAddMemberForm(
|
||||||
data={"user": subscriber_user.make(), "role": self.member_role.id},
|
data={"user": subscriber_user.make(), "role": 1},
|
||||||
request_user=user,
|
request_user=user,
|
||||||
club=self.club,
|
club=self.club,
|
||||||
)
|
)
|
||||||
assert not form.is_valid()
|
assert not form.is_valid()
|
||||||
assert form.errors == {
|
assert form.errors == {
|
||||||
"role": [
|
"role": ["Sélectionnez un choix valide. 1 n\u2019en fait pas partie."]
|
||||||
"Sélectionnez un choix valide. "
|
|
||||||
"Ce choix ne fait pas partie de ceux disponibles."
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def test_simple_members_dont_see_form_anymore(self):
|
def test_simple_members_dont_see_form_anymore(self):
|
||||||
"""Test that simple club members don't see the form to add members"""
|
"""Test that simple club members don't see the form to add members"""
|
||||||
user = subscriber_user.make()
|
user = subscriber_user.make()
|
||||||
baker.make(Membership, club=self.club, user=user, role=self.member_role)
|
baker.make(Membership, club=self.club, user=user, role=1)
|
||||||
self.client.force_login(user)
|
self.client.force_login(user)
|
||||||
res = self.client.get(self.members_url)
|
res = self.client.get(self.members_url)
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
@@ -379,10 +382,9 @@ class TestMembership(TestClub):
|
|||||||
"""Test that board members of the club can end memberships
|
"""Test that board members of the club can end memberships
|
||||||
of users with lower roles.
|
of users with lower roles.
|
||||||
"""
|
"""
|
||||||
|
# reminder : simple_board_member has role 3
|
||||||
self.client.force_login(self.simple_board_member)
|
self.client.force_login(self.simple_board_member)
|
||||||
role = baker.make(ClubRole, club=self.club, is_board=True)
|
membership = baker.make(Membership, club=self.club, role=2, end_date=None)
|
||||||
role.below(self.board_role)
|
|
||||||
membership = baker.make(Membership, club=self.club, role=role)
|
|
||||||
response = self.client.post(self.members_url, {"members_old": [membership.id]})
|
response = self.client.post(self.members_url, {"members_old": [membership.id]})
|
||||||
self.assertRedirects(response, self.members_url)
|
self.assertRedirects(response, self.members_url)
|
||||||
self.club.refresh_from_db()
|
self.club.refresh_from_db()
|
||||||
@@ -392,9 +394,7 @@ class TestMembership(TestClub):
|
|||||||
"""Test that board members of the club cannot end memberships
|
"""Test that board members of the club cannot end memberships
|
||||||
of users with higher roles.
|
of users with higher roles.
|
||||||
"""
|
"""
|
||||||
membership = self.president.memberships.filter(
|
membership = self.president.memberships.filter(club=self.club).first()
|
||||||
club=self.club, end_date=None
|
|
||||||
).first()
|
|
||||||
self.client.force_login(self.simple_board_member)
|
self.client.force_login(self.simple_board_member)
|
||||||
self.client.post(self.members_url, {"members_old": [membership.id]})
|
self.client.post(self.members_url, {"members_old": [membership.id]})
|
||||||
self.club.refresh_from_db()
|
self.club.refresh_from_db()
|
||||||
@@ -436,9 +436,7 @@ class TestMembership(TestClub):
|
|||||||
def test_remove_from_club_group(self):
|
def test_remove_from_club_group(self):
|
||||||
"""Test that when a membership ends, the user is removed from club groups."""
|
"""Test that when a membership ends, the user is removed from club groups."""
|
||||||
user = baker.make(User)
|
user = baker.make(User)
|
||||||
baker.make(
|
baker.make(Membership, user=user, club=self.club, end_date=None, role=3)
|
||||||
Membership, user=user, club=self.club, end_date=None, role=self.board_role
|
|
||||||
)
|
|
||||||
assert user.groups.contains(self.club.members_group)
|
assert user.groups.contains(self.club.members_group)
|
||||||
assert user.groups.contains(self.club.board_group)
|
assert user.groups.contains(self.club.board_group)
|
||||||
user.memberships.update(end_date=localdate())
|
user.memberships.update(end_date=localdate())
|
||||||
@@ -449,20 +447,18 @@ class TestMembership(TestClub):
|
|||||||
"""Test that when a membership begins, the user is added to the club group."""
|
"""Test that when a membership begins, the user is added to the club group."""
|
||||||
assert not self.subscriber.groups.contains(self.club.members_group)
|
assert not self.subscriber.groups.contains(self.club.members_group)
|
||||||
assert not self.subscriber.groups.contains(self.club.board_group)
|
assert not self.subscriber.groups.contains(self.club.board_group)
|
||||||
baker.make(
|
baker.make(Membership, club=self.club, user=self.subscriber, role=3)
|
||||||
Membership, club=self.club, user=self.subscriber, role=self.board_role
|
|
||||||
)
|
|
||||||
assert self.subscriber.groups.contains(self.club.members_group)
|
assert self.subscriber.groups.contains(self.club.members_group)
|
||||||
assert self.subscriber.groups.contains(self.club.board_group)
|
assert self.subscriber.groups.contains(self.club.board_group)
|
||||||
|
|
||||||
def test_change_position_in_club(self):
|
def test_change_position_in_club(self):
|
||||||
"""Test that when moving from board to members, club group change"""
|
"""Test that when moving from board to members, club group change"""
|
||||||
membership = baker.make(
|
membership = baker.make(
|
||||||
Membership, club=self.club, user=self.subscriber, role=self.board_role
|
Membership, club=self.club, user=self.subscriber, role=3
|
||||||
)
|
)
|
||||||
assert self.subscriber.groups.contains(self.club.members_group)
|
assert self.subscriber.groups.contains(self.club.members_group)
|
||||||
assert self.subscriber.groups.contains(self.club.board_group)
|
assert self.subscriber.groups.contains(self.club.board_group)
|
||||||
membership.role = self.member_role
|
membership.role = 1
|
||||||
membership.save()
|
membership.save()
|
||||||
assert self.subscriber.groups.contains(self.club.members_group)
|
assert self.subscriber.groups.contains(self.club.members_group)
|
||||||
assert not self.subscriber.groups.contains(self.club.board_group)
|
assert not self.subscriber.groups.contains(self.club.board_group)
|
||||||
@@ -475,11 +471,7 @@ class TestMembership(TestClub):
|
|||||||
|
|
||||||
# make sli a board member
|
# make sli a board member
|
||||||
self.sli.memberships.all().delete()
|
self.sli.memberships.all().delete()
|
||||||
Membership(
|
Membership(club=self.ae, user=self.sli, role=3).save()
|
||||||
club=self.ae,
|
|
||||||
user=self.sli,
|
|
||||||
role=baker.make(ClubRole, club=self.ae, is_board=True),
|
|
||||||
).save()
|
|
||||||
assert self.club.is_owned_by(self.sli)
|
assert self.club.is_owned_by(self.sli)
|
||||||
|
|
||||||
def test_change_club_name(self):
|
def test_change_club_name(self):
|
||||||
@@ -505,7 +497,7 @@ class TestMembership(TestClub):
|
|||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_membership_set_old(client: Client):
|
def test_membership_set_old(client: Client):
|
||||||
membership = baker.make(Membership, end_date=None, user=subscriber_user.make())
|
membership = baker.make(Membership, end_date=None, user=(subscriber_user.make()))
|
||||||
client.force_login(membership.user)
|
client.force_login(membership.user)
|
||||||
response = client.post(
|
response = client.post(
|
||||||
reverse("club:membership_set_old", kwargs={"membership_id": membership.id})
|
reverse("club:membership_set_old", kwargs={"membership_id": membership.id})
|
||||||
@@ -532,50 +524,6 @@ def test_membership_delete(client: Client):
|
|||||||
assert not Membership.objects.filter(id=membership.id).exists()
|
assert not Membership.objects.filter(id=membership.id).exists()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
class TestAddMemberForm(TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpTestData(cls):
|
|
||||||
cls.club = baker.make(Club)
|
|
||||||
cls.roles = baker.make(
|
|
||||||
ClubRole,
|
|
||||||
club=cls.club,
|
|
||||||
is_board=iter([True, True, True, True, False, False]),
|
|
||||||
is_presidency=iter([True, True, False, False, False, False]),
|
|
||||||
order=seq(0),
|
|
||||||
_quantity=6,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
cls.roles[-1].is_active = False
|
|
||||||
cls.roles[-1].save()
|
|
||||||
|
|
||||||
def test_admin(self):
|
|
||||||
"""Test that admin users can give any active role."""
|
|
||||||
user = baker.make(
|
|
||||||
User, user_permissions=[Permission.objects.get(codename="add_membership")]
|
|
||||||
)
|
|
||||||
form = ClubAddMemberForm(request_user=user, club=self.club)
|
|
||||||
assert list(form.fields["role"].queryset) == self.roles[:-1]
|
|
||||||
|
|
||||||
def test_president(self):
|
|
||||||
"""Test that someone with a presidency role can give any active role."""
|
|
||||||
user = baker.make(Membership, club=self.club, role=self.roles[0]).user
|
|
||||||
form = ClubAddMemberForm(request_user=user, club=self.club)
|
|
||||||
assert list(form.fields["role"].queryset) == self.roles[:-1]
|
|
||||||
|
|
||||||
def test_board_member(self):
|
|
||||||
"""Test that someone with a board role can give lower active role."""
|
|
||||||
user = baker.make(Membership, club=self.club, role=self.roles[2]).user
|
|
||||||
form = ClubAddMemberForm(request_user=user, club=self.club)
|
|
||||||
assert list(form.fields["role"].queryset) == self.roles[3:-1]
|
|
||||||
|
|
||||||
def test_simple_member(self):
|
|
||||||
"""Test that someone with a non-board role cannot give roles."""
|
|
||||||
user = baker.make(Membership, club=self.club, role=self.roles[4]).user
|
|
||||||
form = ClubAddMemberForm(request_user=user, club=self.club)
|
|
||||||
assert list(form.fields["role"].queryset) == []
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
class TestJoinClub:
|
class TestJoinClub:
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
@@ -583,64 +531,55 @@ class TestJoinClub:
|
|||||||
cache.clear()
|
cache.clear()
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
("user_factory", "board_role", "errors"),
|
("user_factory", "role", "errors"),
|
||||||
[
|
[
|
||||||
(
|
(
|
||||||
subscriber_user.make,
|
subscriber_user.make,
|
||||||
True,
|
2,
|
||||||
{
|
{
|
||||||
"role": [
|
"role": [
|
||||||
"Sélectionnez un choix valide. "
|
"Sélectionnez un choix valide. 2 n\u2019en fait pas partie."
|
||||||
"Ce choix ne fait pas partie de ceux disponibles."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
lambda: baker.make(User),
|
lambda: baker.make(User),
|
||||||
False,
|
1,
|
||||||
{"__all__": ["Vous devez être cotisant pour faire partie d'un club"]},
|
{"__all__": ["Vous devez être cotisant pour faire partie d'un club"]},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_join_club_errors(
|
def test_join_club_errors(
|
||||||
self, user_factory: Callable[[], User], board_role, errors: dict
|
self, user_factory: Callable[[], User], role: int, errors: dict
|
||||||
):
|
):
|
||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
user = user_factory()
|
user = user_factory()
|
||||||
role = baker.make(ClubRole, club=club, is_board=board_role)
|
form = JoinClubForm(club=club, request_user=user, data={"role": role})
|
||||||
form = JoinClubForm(club=club, request_user=user, data={"role": role.id})
|
|
||||||
assert not form.is_valid()
|
assert not form.is_valid()
|
||||||
assert form.errors == errors
|
assert form.errors == errors
|
||||||
|
|
||||||
def test_user_already_in_club(self):
|
def test_user_already_in_club(self):
|
||||||
|
club = baker.make(Club)
|
||||||
user = subscriber_user.make()
|
user = subscriber_user.make()
|
||||||
role = baker.make(ClubRole, is_board=False)
|
baker.make(Membership, user=user, club=club)
|
||||||
baker.make(Membership, user=user, club=role.club)
|
form = JoinClubForm(club=club, request_user=user, data={"role": 1})
|
||||||
form = JoinClubForm(club=role.club, request_user=user, data={"role": role.id})
|
|
||||||
assert not form.is_valid()
|
assert not form.is_valid()
|
||||||
assert form.errors == {"__all__": ["Vous êtes déjà membre de ce club."]}
|
assert form.errors == {"__all__": ["Vous êtes déjà membre de ce club."]}
|
||||||
|
|
||||||
def test_ok(self):
|
def test_ok(self):
|
||||||
|
club = baker.make(Club)
|
||||||
user = subscriber_user.make()
|
user = subscriber_user.make()
|
||||||
role = baker.make(ClubRole, is_board=False)
|
form = JoinClubForm(club=club, request_user=user, data={"role": 1})
|
||||||
form = JoinClubForm(club=role.club, request_user=user, data={"role": role.id})
|
|
||||||
assert form.is_valid()
|
assert form.is_valid()
|
||||||
form.save()
|
form.save()
|
||||||
assert Membership.objects.ongoing().filter(user=user, club=role.club).exists()
|
assert Membership.objects.ongoing().filter(user=user, club=club).exists()
|
||||||
|
|
||||||
|
|
||||||
class TestOldMembersView(TestCase):
|
class TestOldMembersView(TestCase):
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpTestData(cls):
|
def setUpTestData(cls):
|
||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
roles = baker.make(
|
roles = [1, 1, 1, 2, 2, 4, 4, 5, 7, 9, 10]
|
||||||
ClubRole,
|
|
||||||
club=club,
|
|
||||||
is_board=itertools.cycle([True, True, False]),
|
|
||||||
order=seq(0),
|
|
||||||
_quantity=10,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
cls.memberships = baker.make(
|
cls.memberships = baker.make(
|
||||||
Membership,
|
Membership,
|
||||||
role=iter(roles),
|
role=iter(roles),
|
||||||
@@ -665,11 +604,3 @@ class TestOldMembersView(TestCase):
|
|||||||
self.client.force_login(baker.make(User))
|
self.client.force_login(baker.make(User))
|
||||||
res = self.client.get(self.url)
|
res = self.client.get(self.url)
|
||||||
assert res.status_code == 403
|
assert res.status_code == 403
|
||||||
|
|
||||||
def test_context_data(self):
|
|
||||||
# mark a membership as not ended, to make sure it is excluded from the result
|
|
||||||
self.memberships[0].end_date = None
|
|
||||||
self.memberships[0].save()
|
|
||||||
self.client.force_login(subscriber_user.make())
|
|
||||||
res = self.client.get(self.url)
|
|
||||||
assert list(res.context_data.get("old_members")) == self.memberships[1:]
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from django.urls import reverse
|
|||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.markdown import markdown
|
from core.markdown import markdown
|
||||||
from core.models import PageRev, User
|
from core.models import PageRev, User
|
||||||
@@ -59,12 +59,7 @@ def test_page_revision(client: Client):
|
|||||||
def test_edit_page(client: Client):
|
def test_edit_page(client: Client):
|
||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
user = subscriber_user.make()
|
user = subscriber_user.make()
|
||||||
baker.make(
|
baker.make(Membership, user=user, club=club, role=3)
|
||||||
Membership,
|
|
||||||
user=user,
|
|
||||||
club=club,
|
|
||||||
role=baker.make(ClubRole, club=club, is_board=True),
|
|
||||||
)
|
|
||||||
client.force_login(user)
|
client.force_login(user)
|
||||||
url = reverse("club:club_edit_page", kwargs={"club_id": club.id})
|
url = reverse("club:club_edit_page", kwargs={"club_id": club.id})
|
||||||
content = "# foo\nLorem ipsum dolor sit amet"
|
content = "# foo\nLorem ipsum dolor sit amet"
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
from django.test import TestCase
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.utils.timezone import localdate
|
|
||||||
from model_bakery import baker
|
|
||||||
from model_bakery.recipe import Recipe
|
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
|
||||||
from club.schemas import UserMembershipSchema
|
|
||||||
from core.baker_recipes import subscriber_user
|
|
||||||
from core.models import Page
|
|
||||||
|
|
||||||
|
|
||||||
class TestFetchClub(TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpTestData(cls):
|
|
||||||
cls.user = subscriber_user.make()
|
|
||||||
pages = baker.make(Page, _quantity=3, _bulk_create=True)
|
|
||||||
clubs = baker.make(Club, page=iter(pages), _quantity=3, _bulk_create=True)
|
|
||||||
recipe = Recipe(
|
|
||||||
Membership,
|
|
||||||
user=cls.user,
|
|
||||||
start_date=localdate() - timedelta(days=2),
|
|
||||||
role=baker.make(ClubRole),
|
|
||||||
)
|
|
||||||
cls.members = Membership.objects.bulk_create(
|
|
||||||
[
|
|
||||||
recipe.prepare(club=clubs[0]),
|
|
||||||
recipe.prepare(club=clubs[1], end_date=localdate() - timedelta(days=1)),
|
|
||||||
recipe.prepare(club=clubs[1]),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_fetch_memberships(self):
|
|
||||||
self.client.force_login(subscriber_user.make())
|
|
||||||
res = self.client.get(
|
|
||||||
reverse("api:fetch_user_clubs", kwargs={"user_id": self.user.id})
|
|
||||||
)
|
|
||||||
assert res.status_code == 200
|
|
||||||
assert [UserMembershipSchema.model_validate(m) for m in res.json()] == [
|
|
||||||
UserMembershipSchema.from_orm(m) for m in (self.members[0], self.members[2])
|
|
||||||
]
|
|
||||||
|
|
||||||
def test_fetch_club_nb_queries(self):
|
|
||||||
self.client.force_login(subscriber_user.make())
|
|
||||||
with self.assertNumQueries(6):
|
|
||||||
# - 5 queries for authentication
|
|
||||||
# - 1 query for the actual data
|
|
||||||
res = self.client.get(
|
|
||||||
reverse("api:fetch_user_clubs", kwargs={"user_id": self.user.id})
|
|
||||||
)
|
|
||||||
assert res.status_code == 200
|
|
||||||
+18
-57
@@ -28,6 +28,7 @@ import csv
|
|||||||
import itertools
|
import itertools
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
|
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
|
||||||
from django.contrib.messages.views import SuccessMessageMixin
|
from django.contrib.messages.views import SuccessMessageMixin
|
||||||
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
|
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
|
||||||
@@ -43,19 +44,13 @@ from django.utils.translation import gettext
|
|||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from django.views.generic import DetailView, ListView, View
|
from django.views.generic import DetailView, ListView, View
|
||||||
from django.views.generic.detail import SingleObjectMixin
|
from django.views.generic.detail import SingleObjectMixin
|
||||||
from django.views.generic.edit import (
|
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||||
CreateView,
|
|
||||||
DeleteView,
|
|
||||||
FormMixin,
|
|
||||||
UpdateView,
|
|
||||||
)
|
|
||||||
|
|
||||||
from club.forms import (
|
from club.forms import (
|
||||||
ClubAddMemberForm,
|
ClubAddMemberForm,
|
||||||
ClubAdminEditForm,
|
ClubAdminEditForm,
|
||||||
ClubEditForm,
|
ClubEditForm,
|
||||||
ClubOldMemberForm,
|
ClubOldMemberForm,
|
||||||
ClubSearchForm,
|
|
||||||
JoinClubForm,
|
JoinClubForm,
|
||||||
MailingForm,
|
MailingForm,
|
||||||
SellingsForm,
|
SellingsForm,
|
||||||
@@ -71,12 +66,7 @@ from com.views import (
|
|||||||
from core.auth.mixins import CanEditMixin, PermissionOrClubBoardRequiredMixin
|
from core.auth.mixins import CanEditMixin, PermissionOrClubBoardRequiredMixin
|
||||||
from core.models import Page, PageRev
|
from core.models import Page, PageRev
|
||||||
from core.views import BasePageEditView, DetailFormView, UseFragmentsMixin
|
from core.views import BasePageEditView, DetailFormView, UseFragmentsMixin
|
||||||
from core.views.mixins import (
|
from core.views.mixins import FragmentMixin, FragmentRenderer, TabedViewMixin
|
||||||
AllowFragment,
|
|
||||||
FragmentMixin,
|
|
||||||
FragmentRenderer,
|
|
||||||
TabedViewMixin,
|
|
||||||
)
|
|
||||||
from counter.models import Selling
|
from counter.models import Selling
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@@ -190,41 +180,15 @@ class ClubTabsMixin(TabedViewMixin):
|
|||||||
return tab_list
|
return tab_list
|
||||||
|
|
||||||
|
|
||||||
class ClubListView(AllowFragment, FormMixin, ListView):
|
class ClubListView(ListView):
|
||||||
"""List the clubs of the AE, with a form to perform basic search.
|
"""List the Clubs."""
|
||||||
|
|
||||||
Notes:
|
|
||||||
This view is fully public, because we want to advertise as much as possible
|
|
||||||
the cultural life of the AE.
|
|
||||||
In accordance with that matter, searching and listing the clubs is done
|
|
||||||
entirely server-side (no AlpineJS involved) ;
|
|
||||||
this is done this way in order to be sure the page is the most accessible
|
|
||||||
and SEO-friendly possible, even if it makes the UX slightly less smooth.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
model = Club
|
||||||
template_name = "club/club_list.jinja"
|
template_name = "club/club_list.jinja"
|
||||||
form_class = ClubSearchForm
|
queryset = (
|
||||||
queryset = Club.objects.order_by("name")
|
Club.objects.filter(parent=None).order_by("name").prefetch_related("children")
|
||||||
paginate_by = 20
|
)
|
||||||
|
context_object_name = "club_list"
|
||||||
def get_form_kwargs(self):
|
|
||||||
res = super().get_form_kwargs()
|
|
||||||
# if request.GET is empty, the form will interpret club_status as None,
|
|
||||||
# even though we want it to be initially True,
|
|
||||||
# so we force a defaut True value.
|
|
||||||
res["data"] = {"club_status": True} | self.request.GET.dict()
|
|
||||||
return res
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
form: ClubSearchForm = self.get_form()
|
|
||||||
qs = self.queryset
|
|
||||||
if not form.is_valid():
|
|
||||||
return qs.none()
|
|
||||||
if name := form.cleaned_data.get("name"):
|
|
||||||
qs = qs.filter(name__icontains=name)
|
|
||||||
if (is_active := form.cleaned_data.get("club_status")) is not None:
|
|
||||||
qs = qs.filter(is_active=is_active)
|
|
||||||
return qs
|
|
||||||
|
|
||||||
|
|
||||||
class ClubView(ClubTabsMixin, DetailView):
|
class ClubView(ClubTabsMixin, DetailView):
|
||||||
@@ -354,7 +318,7 @@ class ClubMembersView(
|
|||||||
membership = self.object.get_membership_for(self.request.user)
|
membership = self.object.get_membership_for(self.request.user)
|
||||||
if (
|
if (
|
||||||
membership
|
membership
|
||||||
and not membership.role.is_board
|
and membership.role <= settings.SITH_MAXIMUM_FREE_ROLE
|
||||||
and not self.request.user.has_perm("club.add_membership")
|
and not self.request.user.has_perm("club.add_membership")
|
||||||
):
|
):
|
||||||
# Simple club members won't see the form anymore.
|
# Simple club members won't see the form anymore.
|
||||||
@@ -379,8 +343,8 @@ class ClubMembersView(
|
|||||||
kwargs["members"] = list(
|
kwargs["members"] = list(
|
||||||
self.object.members.ongoing()
|
self.object.members.ongoing()
|
||||||
.annotate(is_editable=Q(id__in=editable))
|
.annotate(is_editable=Q(id__in=editable))
|
||||||
.order_by("role__order")
|
.order_by("-role")
|
||||||
.select_related("user", "role")
|
.select_related("user")
|
||||||
)
|
)
|
||||||
kwargs["can_end_membership"] = len(editable) > 0
|
kwargs["can_end_membership"] = len(editable) > 0
|
||||||
return kwargs
|
return kwargs
|
||||||
@@ -408,8 +372,8 @@ class ClubOldMembersView(ClubTabsMixin, PermissionRequiredMixin, DetailView):
|
|||||||
return super().get_context_data(**kwargs) | {
|
return super().get_context_data(**kwargs) | {
|
||||||
"old_members": (
|
"old_members": (
|
||||||
self.object.members.exclude(end_date=None)
|
self.object.members.exclude(end_date=None)
|
||||||
.order_by("role__order", "description", "-end_date")
|
.order_by("-role", "description", "-end_date")
|
||||||
.select_related("user", "role")
|
.select_related("user")
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,11 +544,6 @@ class ClubCreateView(PermissionRequiredMixin, CreateView):
|
|||||||
template_name = "core/create.jinja"
|
template_name = "core/create.jinja"
|
||||||
permission_required = "club.add_club"
|
permission_required = "club.add_club"
|
||||||
|
|
||||||
def form_valid(self, form):
|
|
||||||
res = super().form_valid(form)
|
|
||||||
self.object.create_default_roles()
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
class MembershipSetOldView(CanEditMixin, SingleObjectMixin, View):
|
class MembershipSetOldView(CanEditMixin, SingleObjectMixin, View):
|
||||||
"""Set a membership as being old."""
|
"""Set a membership as being old."""
|
||||||
@@ -765,7 +724,9 @@ class MailingAutoGenerationView(View):
|
|||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
club = self.mailing.club
|
club = self.mailing.club
|
||||||
self.mailing.subscriptions.all().delete()
|
self.mailing.subscriptions.all().delete()
|
||||||
members = club.members.ongoing().filter(role__is_board=True)
|
members = club.members.filter(
|
||||||
|
role__gte=settings.SITH_CLUB_ROLES_ID["Board member"]
|
||||||
|
).exclude(end_date__lte=timezone.now())
|
||||||
for member in members.all():
|
for member in members.all():
|
||||||
MailingSubscription(user=member.user, mailing=self.mailing).save()
|
MailingSubscription(user=member.user, mailing=self.mailing).save()
|
||||||
return redirect("club:mailing", club_id=club.id)
|
return redirect("club:mailing", club_id=club.id)
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
|
|
||||||
#news {
|
#news {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 1em;
|
|
||||||
|
|
||||||
@media (max-width: 800px) {
|
@media (max-width: 800px) {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -27,14 +26,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
h3 {
|
h3 {
|
||||||
--box-shadow: rgb(60 64 67 / 30%) 0 1px 3px 0, rgb(60 64 67 / 15%) 0 3px 7px 2px;
|
background: $second-color;
|
||||||
background: lighten($second-color, 5%);
|
box-shadow: $shadow-color 1px 1px 1px;
|
||||||
box-shadow: var(--box-shadow);
|
padding: 0.4em;
|
||||||
padding: .75rem;
|
|
||||||
margin: 0 0 0.5em 0;
|
margin: 0 0 0.5em 0;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
font-size: 17px;
|
font-size: 17px;
|
||||||
border-radius: 10px;
|
|
||||||
|
|
||||||
&:not(:first-of-type) {
|
&:not(:first-of-type) {
|
||||||
margin: 2em 0 1em 0;
|
margin: 2em 0 1em 0;
|
||||||
@@ -42,11 +39,12 @@
|
|||||||
|
|
||||||
.feed {
|
.feed {
|
||||||
float: right;
|
float: right;
|
||||||
color: #e25512;
|
color: #f26522;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media screen and (max-width: $small-devices) {
|
@media screen and (max-width: $small-devices) {
|
||||||
|
|
||||||
#left_column,
|
#left_column,
|
||||||
#right_column {
|
#right_column {
|
||||||
flex: 100%;
|
flex: 100%;
|
||||||
@@ -59,7 +57,6 @@
|
|||||||
max-height: 600px;
|
max-height: 600px;
|
||||||
overflow-y: scroll;
|
overflow-y: scroll;
|
||||||
overflow-x: clip;
|
overflow-x: clip;
|
||||||
margin-top: 1em;
|
|
||||||
|
|
||||||
#load-more-news-button {
|
#load-more-news-button {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
@@ -79,11 +76,15 @@
|
|||||||
font-size: 70%;
|
font-size: 70%;
|
||||||
margin-bottom: 1em;
|
margin-bottom: 1em;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
#links_content {
|
#links_content {
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
box-shadow: $shadow-color 1px 1px 1px;
|
box-shadow: $shadow-color 1px 1px 1px;
|
||||||
min-height: 20em;
|
min-height: 20em;
|
||||||
padding: 1em;
|
padding-bottom: 1em;
|
||||||
|
|
||||||
h4 {
|
h4 {
|
||||||
margin-left: 5px;
|
margin-left: 5px;
|
||||||
@@ -120,8 +121,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
#birthdays_content {
|
#birthdays_content {
|
||||||
box-shadow: $shadow-color 1px 1px 1px;
|
|
||||||
padding: 1em;
|
|
||||||
ul.birthdays_year {
|
ul.birthdays_year {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
list-style-type: none;
|
list-style-type: none;
|
||||||
@@ -136,7 +135,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
ul {
|
ul {
|
||||||
margin: .5em 0 0 1em;
|
margin: 0;
|
||||||
|
margin-left: 1em;
|
||||||
list-style-type: square;
|
list-style-type: square;
|
||||||
list-style-position: inside;
|
list-style-position: inside;
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
@@ -150,13 +150,9 @@
|
|||||||
/* EVENTS TODAY AND NEXT FEW DAYS */
|
/* EVENTS TODAY AND NEXT FEW DAYS */
|
||||||
.news_events_group {
|
.news_events_group {
|
||||||
box-shadow: $shadow-color 1px 1px 1px;
|
box-shadow: $shadow-color 1px 1px 1px;
|
||||||
margin-left: 0;
|
margin-left: 1em;
|
||||||
margin-bottom: 0.5em;
|
margin-bottom: 0.5em;
|
||||||
|
|
||||||
@media screen and (max-width: $small-devices) {
|
|
||||||
margin-left: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.news_events_group_date {
|
.news_events_group_date {
|
||||||
display: table-cell;
|
display: table-cell;
|
||||||
padding: 0.6em;
|
padding: 0.6em;
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
<a target="#" href="{{ url("com:news_feed") }}"><i class="fa fa-rss feed"></i></a>
|
<a target="#" href="{{ url("com:news_feed") }}"><i class="fa fa-rss feed"></i></a>
|
||||||
</h3>
|
</h3>
|
||||||
{% if user.is_authenticated and (user.is_com_admin or user.memberships.board().ongoing().exists()) %}
|
{% if user.is_authenticated and (user.is_com_admin or user.memberships.board().ongoing().exists()) %}
|
||||||
<a class="btn btn-blue" href="{{ url("com:news_new") }}">
|
<a class="btn btn-blue margin-bottom" href="{{ url("com:news_new") }}">
|
||||||
<i class="fa fa-plus"></i>
|
<i class="fa fa-plus"></i>
|
||||||
{% trans %}Create news{% endtrans %}
|
{% trans %}Create news{% endtrans %}
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from model_bakery import baker
|
|||||||
|
|
||||||
from com.models import News, NewsDate
|
from com.models import News, NewsDate
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import Group, Notification, SithFile, User
|
from core.models import Group, Notification, User
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -18,7 +18,6 @@ def test_notification_created():
|
|||||||
past_news = baker.make(News, is_published=False)
|
past_news = baker.make(News, is_published=False)
|
||||||
baker.make(NewsDate, news=past_news, start_date=now() - timedelta(days=1))
|
baker.make(NewsDate, news=past_news, start_date=now() - timedelta(days=1))
|
||||||
com_admin_group = Group.objects.get(pk=settings.SITH_GROUP_COM_ADMIN_ID)
|
com_admin_group = Group.objects.get(pk=settings.SITH_GROUP_COM_ADMIN_ID)
|
||||||
SithFile.objects.filter(owner__in=com_admin_group.users.all()).delete()
|
|
||||||
com_admin_group.users.all().delete()
|
com_admin_group.users.all().delete()
|
||||||
Notification.objects.all().delete()
|
Notification.objects.all().delete()
|
||||||
com_admin = baker.make(User, groups=[com_admin_group])
|
com_admin = baker.make(User, groups=[com_admin_group])
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ from django.utils.translation import gettext as _
|
|||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertNumQueries, assertRedirects
|
from pytest_django.asserts import assertNumQueries, assertRedirects
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from com.models import News, NewsDate, Poster, Sith, Weekmail, WeekmailArticle
|
from com.models import News, NewsDate, Poster, Sith, Weekmail, WeekmailArticle
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import AnonymousUser, Group, User
|
from core.models import AnonymousUser, Group, User
|
||||||
@@ -214,8 +214,7 @@ class TestNewsCreation(TestCase):
|
|||||||
def setUpTestData(cls):
|
def setUpTestData(cls):
|
||||||
cls.club = baker.make(Club)
|
cls.club = baker.make(Club)
|
||||||
cls.user = subscriber_user.make()
|
cls.user = subscriber_user.make()
|
||||||
role = baker.make(ClubRole, club=cls.club, is_board=True)
|
baker.make(Membership, user=cls.user, club=cls.club, role=5)
|
||||||
baker.make(Membership, user=cls.user, club=cls.club, role=role)
|
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.client.force_login(self.user)
|
self.client.force_login(self.user)
|
||||||
|
|||||||
+3
-2
@@ -244,8 +244,9 @@ class NewsListView(TemplateView):
|
|||||||
.filter(
|
.filter(
|
||||||
date_of_birth__month=localdate().month,
|
date_of_birth__month=localdate().month,
|
||||||
date_of_birth__day=localdate().day,
|
date_of_birth__day=localdate().day,
|
||||||
role__in=["STUDENT", "FORMER STUDENT"],
|
is_viewable=True,
|
||||||
)
|
)
|
||||||
|
.filter(role__in=["STUDENT", "FORMER STUDENT"])
|
||||||
.order_by("-date_of_birth"),
|
.order_by("-date_of_birth"),
|
||||||
key=lambda u: u.date_of_birth.year,
|
key=lambda u: u.date_of_birth.year,
|
||||||
)
|
)
|
||||||
@@ -503,7 +504,7 @@ class WeekmailArticleCreateView(CreateView):
|
|||||||
self.object = form.instance
|
self.object = form.instance
|
||||||
form.is_valid() # Valid a first time to populate club field
|
form.is_valid() # Valid a first time to populate club field
|
||||||
m = form.instance.club.get_membership_for(request.user)
|
m = form.instance.club.get_membership_for(request.user)
|
||||||
if m is None or not m.role.is_board:
|
if m is None or m.role <= settings.SITH_MAXIMUM_FREE_ROLE:
|
||||||
form.add_error(
|
form.add_error(
|
||||||
"club",
|
"club",
|
||||||
ValidationError(
|
ValidationError(
|
||||||
|
|||||||
+2
-3
@@ -63,7 +63,6 @@ class UserAdmin(admin.ModelAdmin):
|
|||||||
"scrub_pict",
|
"scrub_pict",
|
||||||
"user_permissions",
|
"user_permissions",
|
||||||
"groups",
|
"groups",
|
||||||
"whitelisted_users",
|
|
||||||
)
|
)
|
||||||
inlines = (UserBanInline,)
|
inlines = (UserBanInline,)
|
||||||
search_fields = ["first_name", "last_name", "username"]
|
search_fields = ["first_name", "last_name", "username"]
|
||||||
@@ -99,9 +98,9 @@ class PageAdmin(admin.ModelAdmin):
|
|||||||
|
|
||||||
@admin.register(SithFile)
|
@admin.register(SithFile)
|
||||||
class SithFileAdmin(admin.ModelAdmin):
|
class SithFileAdmin(admin.ModelAdmin):
|
||||||
list_display = ("name", "owner", "size", "date", "is_in_sas")
|
list_display = ("name", "owner", "size", "date")
|
||||||
autocomplete_fields = ("parent", "owner", "moderator")
|
autocomplete_fields = ("parent", "owner", "moderator")
|
||||||
search_fields = ("name", "parent__name")
|
search_fields = ("name",)
|
||||||
|
|
||||||
|
|
||||||
@admin.register(OperationLog)
|
@admin.register(OperationLog)
|
||||||
|
|||||||
+2
-2
@@ -110,7 +110,7 @@ class SithFileController(ControllerBase):
|
|||||||
)
|
)
|
||||||
@paginate(PageNumberPaginationExtra, page_size=50)
|
@paginate(PageNumberPaginationExtra, page_size=50)
|
||||||
def search_files(self, search: Annotated[str, MinLen(1)]):
|
def search_files(self, search: Annotated[str, MinLen(1)]):
|
||||||
return SithFile.objects.filter(is_in_sas=False).filter(name__icontains=search)
|
return SithFile.objects.filter(name__icontains=search)
|
||||||
|
|
||||||
|
|
||||||
@api_controller("/group")
|
@api_controller("/group")
|
||||||
@@ -123,7 +123,7 @@ class GroupController(ControllerBase):
|
|||||||
)
|
)
|
||||||
@paginate(PageNumberPaginationExtra, page_size=50)
|
@paginate(PageNumberPaginationExtra, page_size=50)
|
||||||
def search_group(self, search: Annotated[str, MinLen(1)]):
|
def search_group(self, search: Annotated[str, MinLen(1)]):
|
||||||
return Group.objects.filter(name__icontains=search).order_by("name").values()
|
return Group.objects.filter(name__icontains=search).values()
|
||||||
|
|
||||||
|
|
||||||
DepthValue = Annotated[int, Ge(0), Le(10)]
|
DepthValue = Annotated[int, Ge(0), Le(10)]
|
||||||
|
|||||||
+2
-3
@@ -307,7 +307,6 @@ class PermissionOrClubBoardRequiredMixin(PermissionRequiredMixin):
|
|||||||
return False
|
return False
|
||||||
if super().has_permission():
|
if super().has_permission():
|
||||||
return True
|
return True
|
||||||
return (
|
return self.club is not None and any(
|
||||||
self.club is not None
|
g.id == self.club.board_group_id for g in self.request.user.cached_groups
|
||||||
and self.club.board_group_id in self.request.user.all_groups
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ from dateutil.relativedelta import relativedelta
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.utils.timezone import localdate, now
|
from django.utils.timezone import localdate, now
|
||||||
from model_bakery import seq
|
from model_bakery import seq
|
||||||
from model_bakery.recipe import Recipe, foreign_key, related
|
from model_bakery.recipe import Recipe, related
|
||||||
|
|
||||||
from club.models import ClubRole, Membership
|
from club.models import Membership
|
||||||
from core.models import Group, User
|
from core.models import Group, User
|
||||||
from subscription.models import Subscription
|
from subscription.models import Subscription
|
||||||
|
|
||||||
@@ -52,9 +52,7 @@ ae_board_membership = Recipe(
|
|||||||
Membership,
|
Membership,
|
||||||
start_date=now() - timedelta(days=30),
|
start_date=now() - timedelta(days=30),
|
||||||
club_id=settings.SITH_MAIN_CLUB_ID,
|
club_id=settings.SITH_MAIN_CLUB_ID,
|
||||||
role=foreign_key(
|
role=settings.SITH_CLUB_ROLES_ID["Board member"],
|
||||||
Recipe(ClubRole, club_id=settings.SITH_MAIN_CLUB_ID, is_board=True)
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
board_user = Recipe(
|
board_user = Recipe(
|
||||||
|
|||||||
@@ -39,16 +39,12 @@ class Command(BaseCommand):
|
|||||||
return None
|
return None
|
||||||
return xapian.version_string()
|
return xapian.version_string()
|
||||||
|
|
||||||
def _desired_version(self) -> tuple[str, str, str]:
|
def _desired_version(self) -> str:
|
||||||
with open(
|
with open(
|
||||||
Path(__file__).parent.parent.parent.parent / "pyproject.toml", "rb"
|
Path(__file__).parent.parent.parent.parent / "pyproject.toml", "rb"
|
||||||
) as f:
|
) as f:
|
||||||
pyproject = tomli.load(f)
|
pyproject = tomli.load(f)
|
||||||
return (
|
return pyproject["tool"]["xapian"]["version"]
|
||||||
pyproject["tool"]["xapian"]["version"],
|
|
||||||
pyproject["tool"]["xapian"]["core-sha256"],
|
|
||||||
pyproject["tool"]["xapian"]["bindings-sha256"],
|
|
||||||
)
|
|
||||||
|
|
||||||
def handle(self, *args, force: bool, **options):
|
def handle(self, *args, force: bool, **options):
|
||||||
if not os.environ.get("VIRTUAL_ENV", None):
|
if not os.environ.get("VIRTUAL_ENV", None):
|
||||||
@@ -57,7 +53,7 @@ class Command(BaseCommand):
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
desired, core_checksum, bindings_checksum = self._desired_version()
|
desired = self._desired_version()
|
||||||
if desired == self._current_version():
|
if desired == self._current_version():
|
||||||
if not force:
|
if not force:
|
||||||
self.stdout.write(
|
self.stdout.write(
|
||||||
@@ -69,12 +65,7 @@ class Command(BaseCommand):
|
|||||||
f"Installing xapian version {desired} at {os.environ['VIRTUAL_ENV']}"
|
f"Installing xapian version {desired} at {os.environ['VIRTUAL_ENV']}"
|
||||||
)
|
)
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[
|
[str(Path(__file__).parent / "install_xapian.sh"), desired],
|
||||||
str(Path(__file__).parent / "install_xapian.sh"),
|
|
||||||
desired,
|
|
||||||
core_checksum,
|
|
||||||
bindings_checksum,
|
|
||||||
],
|
|
||||||
env=dict(os.environ),
|
env=dict(os.environ),
|
||||||
check=True,
|
check=True,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Originates from https://gist.github.com/jorgecarleitao/ab6246c86c936b9c55fd
|
# Originates from https://gist.github.com/jorgecarleitao/ab6246c86c936b9c55fd
|
||||||
# first argument of the script is Xapian version (e.g. 1.2.19)
|
# first argument of the script is Xapian version (e.g. 1.2.19)
|
||||||
# second argument of the script is core sha256
|
|
||||||
# second argument of the script is binding sha256
|
|
||||||
VERSION="$1"
|
VERSION="$1"
|
||||||
CORE_SHA256="$2"
|
|
||||||
BINDINGS_SHA256="$3"
|
|
||||||
|
|
||||||
# Cleanup env vars for auto discovery mechanism
|
# Cleanup env vars for auto discovery mechanism
|
||||||
unset CPATH
|
unset CPATH
|
||||||
@@ -25,15 +21,9 @@ BINDINGS=xapian-bindings-$VERSION
|
|||||||
|
|
||||||
# download
|
# download
|
||||||
echo "Downloading source..."
|
echo "Downloading source..."
|
||||||
curl -O "https://oligarchy.co.uk/xapian/$VERSION/${CORE}.tar.xz" || exit 1
|
curl -O "https://oligarchy.co.uk/xapian/$VERSION/${CORE}.tar.xz"
|
||||||
|
|
||||||
echo "${CORE_SHA256} ${CORE}.tar.xz" | sha256sum -c - || exit 1
|
|
||||||
|
|
||||||
curl -O "https://oligarchy.co.uk/xapian/$VERSION/${BINDINGS}.tar.xz"
|
curl -O "https://oligarchy.co.uk/xapian/$VERSION/${BINDINGS}.tar.xz"
|
||||||
|
|
||||||
echo "${BINDINGS_SHA256} ${BINDINGS}.tar.xz" | sha256sum -c - || exit 1
|
|
||||||
|
|
||||||
|
|
||||||
# extract
|
# extract
|
||||||
echo "Extracting source..."
|
echo "Extracting source..."
|
||||||
tar xf "${CORE}.tar.xz"
|
tar xf "${CORE}.tar.xz"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
# details.
|
# details.
|
||||||
#
|
#
|
||||||
# You should have received a copy of the GNU General Public License along with
|
# You should have received a copy of the GNU General Public License along with
|
||||||
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
|
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
|
||||||
# Place - Suite 330, Boston, MA 02111-1307, USA.
|
# Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
@@ -36,19 +36,12 @@ from django.utils import timezone
|
|||||||
from django.utils.timezone import localdate
|
from django.utils.timezone import localdate
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from com.ics_calendar import IcsCalendar
|
from com.ics_calendar import IcsCalendar
|
||||||
from com.models import News, NewsDate, Sith, Weekmail
|
from com.models import News, NewsDate, Sith, Weekmail
|
||||||
from core.models import BanGroup, Group, Page, PageRev, SithFile, User
|
from core.models import BanGroup, Group, Page, PageRev, SithFile, User
|
||||||
from core.utils import resize_image
|
from core.utils import resize_image
|
||||||
from counter.models import (
|
from counter.models import Counter, Product, ProductType, ReturnableProduct, StudentCard
|
||||||
Counter,
|
|
||||||
Price,
|
|
||||||
Product,
|
|
||||||
ProductType,
|
|
||||||
ReturnableProduct,
|
|
||||||
StudentCard,
|
|
||||||
)
|
|
||||||
from election.models import Candidature, Election, ElectionList, Role
|
from election.models import Candidature, Election, ElectionList, Role
|
||||||
from forum.models import Forum
|
from forum.models import Forum
|
||||||
from pedagogy.models import UE
|
from pedagogy.models import UE
|
||||||
@@ -69,13 +62,6 @@ class PopulatedGroups(NamedTuple):
|
|||||||
campus_admin: Group
|
campus_admin: Group
|
||||||
|
|
||||||
|
|
||||||
class PopulatedClubs(NamedTuple):
|
|
||||||
ae: Club
|
|
||||||
troll: Club
|
|
||||||
pdf: Club
|
|
||||||
refound: Club
|
|
||||||
|
|
||||||
|
|
||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
ROOT_PATH: ClassVar[Path] = Path(__file__).parent.parent.parent.parent
|
ROOT_PATH: ClassVar[Path] = Path(__file__).parent.parent.parent.parent
|
||||||
SAS_FIXTURE_PATH: ClassVar[Path] = (
|
SAS_FIXTURE_PATH: ClassVar[Path] = (
|
||||||
@@ -124,19 +110,28 @@ class Command(BaseCommand):
|
|||||||
p.save(force_lock=True)
|
p.save(force_lock=True)
|
||||||
|
|
||||||
club_root = SithFile.objects.create(name="clubs", owner=root)
|
club_root = SithFile.objects.create(name="clubs", owner=root)
|
||||||
sas = SithFile.objects.create(
|
main_club = Club.objects.create(
|
||||||
name="SAS", owner=root, id=settings.SITH_SAS_ROOT_DIR_ID
|
id=1, name="AE", address="6 Boulevard Anatole France, 90000 Belfort"
|
||||||
|
)
|
||||||
|
main_club.board_group.permissions.add(
|
||||||
|
*Permission.objects.filter(
|
||||||
|
codename__in=["view_subscription", "add_subscription"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
bar_club = Club.objects.create(
|
||||||
|
id=settings.SITH_PDF_CLUB_ID,
|
||||||
|
name="PdF",
|
||||||
|
address="6 Boulevard Anatole France, 90000 Belfort",
|
||||||
)
|
)
|
||||||
clubs = self._create_clubs()
|
|
||||||
|
|
||||||
self.reset_index("club")
|
self.reset_index("club")
|
||||||
for bar_id, bar_name in settings.SITH_COUNTER_BARS:
|
for bar_id, bar_name in settings.SITH_COUNTER_BARS:
|
||||||
Counter(id=bar_id, name=bar_name, club=clubs.pdf, type="BAR").save()
|
Counter(id=bar_id, name=bar_name, club=bar_club, type="BAR").save()
|
||||||
self.reset_index("counter")
|
self.reset_index("counter")
|
||||||
counters = [
|
counters = [
|
||||||
Counter(name="Eboutic", club=clubs.ae, type="EBOUTIC"),
|
Counter(name="Eboutic", club=main_club, type="EBOUTIC"),
|
||||||
Counter(name="AE", club=clubs.ae, type="OFFICE"),
|
Counter(name="AE", club=main_club, type="OFFICE"),
|
||||||
Counter(name="Vidage comptes AE", club=clubs.ae, type="OFFICE"),
|
Counter(name="Vidage comptes AE", club=main_club, type="OFFICE"),
|
||||||
]
|
]
|
||||||
Counter.objects.bulk_create(counters)
|
Counter.objects.bulk_create(counters)
|
||||||
bar_groups = []
|
bar_groups = []
|
||||||
@@ -319,55 +314,178 @@ class Command(BaseCommand):
|
|||||||
self._create_subscription(tutu)
|
self._create_subscription(tutu)
|
||||||
StudentCard(uid="9A89B82018B0A0", customer=sli.customer).save()
|
StudentCard(uid="9A89B82018B0A0", customer=sli.customer).save()
|
||||||
|
|
||||||
Membership.objects.create(
|
# Clubs
|
||||||
user=skia, club=clubs.ae, role=clubs.ae.roles.get(name="Respo Info")
|
Club.objects.create(
|
||||||
|
name="Bibo'UT", address="46 de la Boustifaille", parent=main_club
|
||||||
)
|
)
|
||||||
|
guyut = Club.objects.create(
|
||||||
|
name="Guy'UT", address="42 de la Boustifaille", parent=main_club
|
||||||
|
)
|
||||||
|
Club.objects.create(name="Woenzel'UT", address="Woenzel", parent=guyut)
|
||||||
|
troll = Club.objects.create(
|
||||||
|
name="Troll Penché", address="Terre Du Milieu", parent=main_club
|
||||||
|
)
|
||||||
|
refound = Club.objects.create(
|
||||||
|
name="Carte AE", address="Jamais imprimée", parent=main_club
|
||||||
|
)
|
||||||
|
|
||||||
|
Membership.objects.create(user=skia, club=main_club, role=3)
|
||||||
Membership.objects.create(
|
Membership.objects.create(
|
||||||
user=comunity,
|
user=comunity,
|
||||||
club=clubs.pdf,
|
club=bar_club,
|
||||||
start_date=localdate(),
|
start_date=localdate(),
|
||||||
role=clubs.pdf.roles.get(name="Membre du bureau"),
|
role=settings.SITH_CLUB_ROLES_ID["Board member"],
|
||||||
)
|
)
|
||||||
Membership.objects.create(
|
Membership.objects.create(
|
||||||
user=sli,
|
user=sli,
|
||||||
club=clubs.troll,
|
club=troll,
|
||||||
role=clubs.troll.roles.get(name="Vice-Président⸱e"),
|
role=9,
|
||||||
description="Padawan Troll",
|
description="Padawan Troll",
|
||||||
start_date=localdate() - timedelta(days=17),
|
start_date=localdate() - timedelta(days=17),
|
||||||
)
|
)
|
||||||
Membership.objects.create(
|
Membership.objects.create(
|
||||||
user=krophil,
|
user=krophil,
|
||||||
club=clubs.troll,
|
club=troll,
|
||||||
role=clubs.troll.roles.get(name="Président⸱e"),
|
role=10,
|
||||||
description="Maitre Troll",
|
description="Maitre Troll",
|
||||||
start_date=localdate() - timedelta(days=200),
|
start_date=localdate() - timedelta(days=200),
|
||||||
)
|
)
|
||||||
Membership.objects.create(
|
Membership.objects.create(
|
||||||
user=skia,
|
user=skia,
|
||||||
club=clubs.troll,
|
club=troll,
|
||||||
role=clubs.troll.roles.get(name="Membre du bureau"),
|
role=2,
|
||||||
description="Grand Ancien Troll",
|
description="Grand Ancien Troll",
|
||||||
start_date=localdate() - timedelta(days=400),
|
start_date=localdate() - timedelta(days=400),
|
||||||
end_date=localdate() - timedelta(days=86),
|
end_date=localdate() - timedelta(days=86),
|
||||||
)
|
)
|
||||||
Membership.objects.create(
|
Membership.objects.create(
|
||||||
user=richard,
|
user=richard,
|
||||||
club=clubs.troll,
|
club=troll,
|
||||||
role=clubs.troll.roles.get(name="Membre du bureau"),
|
role=2,
|
||||||
description="",
|
description="",
|
||||||
start_date=localdate() - timedelta(days=200),
|
start_date=localdate() - timedelta(days=200),
|
||||||
end_date=localdate() - timedelta(days=100),
|
end_date=localdate() - timedelta(days=100),
|
||||||
)
|
)
|
||||||
|
|
||||||
self._create_products(groups, clubs)
|
p = ProductType.objects.create(name="Bières bouteilles")
|
||||||
|
c = ProductType.objects.create(name="Cotisations")
|
||||||
|
r = ProductType.objects.create(name="Rechargements")
|
||||||
|
verre = ProductType.objects.create(name="Verre")
|
||||||
|
cotis = Product.objects.create(
|
||||||
|
name="Cotis 1 semestre",
|
||||||
|
code="1SCOTIZ",
|
||||||
|
product_type=c,
|
||||||
|
purchase_price="15",
|
||||||
|
selling_price="15",
|
||||||
|
special_selling_price="15",
|
||||||
|
club=main_club,
|
||||||
|
)
|
||||||
|
cotis2 = Product.objects.create(
|
||||||
|
name="Cotis 2 semestres",
|
||||||
|
code="2SCOTIZ",
|
||||||
|
product_type=c,
|
||||||
|
purchase_price="28",
|
||||||
|
selling_price="28",
|
||||||
|
special_selling_price="28",
|
||||||
|
club=main_club,
|
||||||
|
)
|
||||||
|
refill = Product.objects.create(
|
||||||
|
name="Rechargement 15 €",
|
||||||
|
code="15REFILL",
|
||||||
|
product_type=r,
|
||||||
|
purchase_price="15",
|
||||||
|
selling_price="15",
|
||||||
|
special_selling_price="15",
|
||||||
|
club=main_club,
|
||||||
|
)
|
||||||
|
barb = Product.objects.create(
|
||||||
|
name="Barbar",
|
||||||
|
code="BARB",
|
||||||
|
product_type=p,
|
||||||
|
purchase_price="1.50",
|
||||||
|
selling_price="1.7",
|
||||||
|
special_selling_price="1.6",
|
||||||
|
club=main_club,
|
||||||
|
limit_age=18,
|
||||||
|
)
|
||||||
|
cble = Product.objects.create(
|
||||||
|
name="Chimay Bleue",
|
||||||
|
code="CBLE",
|
||||||
|
product_type=p,
|
||||||
|
purchase_price="1.50",
|
||||||
|
selling_price="1.7",
|
||||||
|
special_selling_price="1.6",
|
||||||
|
club=main_club,
|
||||||
|
limit_age=18,
|
||||||
|
)
|
||||||
|
cons = Product.objects.create(
|
||||||
|
name="Consigne Eco-cup",
|
||||||
|
code="CONS",
|
||||||
|
product_type=verre,
|
||||||
|
purchase_price="1",
|
||||||
|
selling_price="1",
|
||||||
|
special_selling_price="1",
|
||||||
|
club=main_club,
|
||||||
|
)
|
||||||
|
dcons = Product.objects.create(
|
||||||
|
name="Déconsigne Eco-cup",
|
||||||
|
code="DECO",
|
||||||
|
product_type=verre,
|
||||||
|
purchase_price="-1",
|
||||||
|
selling_price="-1",
|
||||||
|
special_selling_price="-1",
|
||||||
|
club=main_club,
|
||||||
|
)
|
||||||
|
cors = Product.objects.create(
|
||||||
|
name="Corsendonk",
|
||||||
|
code="CORS",
|
||||||
|
product_type=p,
|
||||||
|
purchase_price="1.50",
|
||||||
|
selling_price="1.7",
|
||||||
|
special_selling_price="1.6",
|
||||||
|
club=main_club,
|
||||||
|
limit_age=18,
|
||||||
|
)
|
||||||
|
carolus = Product.objects.create(
|
||||||
|
name="Carolus",
|
||||||
|
code="CARO",
|
||||||
|
product_type=p,
|
||||||
|
purchase_price="1.50",
|
||||||
|
selling_price="1.7",
|
||||||
|
special_selling_price="1.6",
|
||||||
|
club=main_club,
|
||||||
|
limit_age=18,
|
||||||
|
)
|
||||||
|
Product.objects.create(
|
||||||
|
name="remboursement",
|
||||||
|
code="REMBOURS",
|
||||||
|
purchase_price="0",
|
||||||
|
selling_price="0",
|
||||||
|
special_selling_price="0",
|
||||||
|
club=refound,
|
||||||
|
)
|
||||||
|
groups.subscribers.products.add(
|
||||||
|
cotis, cotis2, refill, barb, cble, cors, carolus
|
||||||
|
)
|
||||||
|
groups.old_subscribers.products.add(cotis, cotis2)
|
||||||
|
|
||||||
Counter.objects.create(name="Carte AE", club=clubs.refound, type="OFFICE")
|
mde = Counter.objects.get(name="MDE")
|
||||||
|
mde.products.add(barb, cble, cons, dcons)
|
||||||
|
|
||||||
|
eboutic = Counter.objects.get(name="Eboutic")
|
||||||
|
eboutic.products.add(barb, cotis, cotis2, refill)
|
||||||
|
|
||||||
|
Counter.objects.create(name="Carte AE", club=refound, type="OFFICE")
|
||||||
|
|
||||||
|
ReturnableProduct.objects.create(
|
||||||
|
product=cons, returned_product=dcons, max_return=3
|
||||||
|
)
|
||||||
|
|
||||||
# Add barman to counter
|
# Add barman to counter
|
||||||
Counter.sellers.through.objects.bulk_create(
|
Counter.sellers.through.objects.bulk_create(
|
||||||
[
|
[
|
||||||
Counter.sellers.through(counter_id=1, user=skia), # MDE
|
Counter.sellers.through(counter_id=2, user=krophil),
|
||||||
Counter.sellers.through(counter_id=2, user=krophil), # Foyer
|
Counter.sellers.through(counter=mde, user=skia),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -381,7 +499,7 @@ class Command(BaseCommand):
|
|||||||
end_date="7942-06-12 10:28:45+01",
|
end_date="7942-06-12 10:28:45+01",
|
||||||
)
|
)
|
||||||
el.view_groups.add(groups.public)
|
el.view_groups.add(groups.public)
|
||||||
el.edit_groups.add(clubs.ae.board_group)
|
el.edit_groups.add(main_club.board_group)
|
||||||
el.candidature_groups.add(groups.subscribers)
|
el.candidature_groups.add(groups.subscribers)
|
||||||
el.vote_groups.add(groups.subscribers)
|
el.vote_groups.add(groups.subscribers)
|
||||||
liste = ElectionList.objects.create(title="Candidature Libre", election=el)
|
liste = ElectionList.objects.create(title="Candidature Libre", election=el)
|
||||||
@@ -454,7 +572,7 @@ class Command(BaseCommand):
|
|||||||
title="Apero barman",
|
title="Apero barman",
|
||||||
summary="Viens boire un coup avec les barmans",
|
summary="Viens boire un coup avec les barmans",
|
||||||
content="Glou glou glou glou glou glou glou",
|
content="Glou glou glou glou glou glou glou",
|
||||||
club=clubs.pdf,
|
club=bar_club,
|
||||||
author=subscriber,
|
author=subscriber,
|
||||||
is_published=True,
|
is_published=True,
|
||||||
moderator=skia,
|
moderator=skia,
|
||||||
@@ -472,7 +590,7 @@ class Command(BaseCommand):
|
|||||||
content=(
|
content=(
|
||||||
"Viens donc t'enjailler avec les autres barmans aux frais du BdF! \\o/"
|
"Viens donc t'enjailler avec les autres barmans aux frais du BdF! \\o/"
|
||||||
),
|
),
|
||||||
club=clubs.pdf,
|
club=bar_club,
|
||||||
author=subscriber,
|
author=subscriber,
|
||||||
is_published=True,
|
is_published=True,
|
||||||
moderator=skia,
|
moderator=skia,
|
||||||
@@ -488,7 +606,7 @@ class Command(BaseCommand):
|
|||||||
title="Repas fromager",
|
title="Repas fromager",
|
||||||
summary="Wien manger du l'bon fromeug'",
|
summary="Wien manger du l'bon fromeug'",
|
||||||
content="Fô viendre mangey d'la bonne fondue!",
|
content="Fô viendre mangey d'la bonne fondue!",
|
||||||
club=clubs.pdf,
|
club=bar_club,
|
||||||
author=subscriber,
|
author=subscriber,
|
||||||
is_published=True,
|
is_published=True,
|
||||||
moderator=skia,
|
moderator=skia,
|
||||||
@@ -504,7 +622,7 @@ class Command(BaseCommand):
|
|||||||
title="SdF",
|
title="SdF",
|
||||||
summary="Enjoy la fin des finaux!",
|
summary="Enjoy la fin des finaux!",
|
||||||
content="Viens faire la fête avec tout plein de gens!",
|
content="Viens faire la fête avec tout plein de gens!",
|
||||||
club=clubs.pdf,
|
club=bar_club,
|
||||||
author=subscriber,
|
author=subscriber,
|
||||||
is_published=True,
|
is_published=True,
|
||||||
moderator=skia,
|
moderator=skia,
|
||||||
@@ -522,7 +640,7 @@ class Command(BaseCommand):
|
|||||||
summary="Viens jouer!",
|
summary="Viens jouer!",
|
||||||
content="Rejoins la fine équipe du Troll Penché et viens "
|
content="Rejoins la fine équipe du Troll Penché et viens "
|
||||||
"t'amuser le Vendredi soir!",
|
"t'amuser le Vendredi soir!",
|
||||||
club=clubs.troll,
|
club=troll,
|
||||||
author=subscriber,
|
author=subscriber,
|
||||||
is_published=True,
|
is_published=True,
|
||||||
moderator=skia,
|
moderator=skia,
|
||||||
@@ -575,32 +693,21 @@ class Command(BaseCommand):
|
|||||||
# SAS
|
# SAS
|
||||||
for f in self.SAS_FIXTURE_PATH.glob("*"):
|
for f in self.SAS_FIXTURE_PATH.glob("*"):
|
||||||
if f.is_dir():
|
if f.is_dir():
|
||||||
album = Album(
|
album = Album.objects.create(name=f.name, is_moderated=True)
|
||||||
parent=sas,
|
|
||||||
name=f.name,
|
|
||||||
owner=root,
|
|
||||||
is_folder=True,
|
|
||||||
is_in_sas=True,
|
|
||||||
is_moderated=True,
|
|
||||||
)
|
|
||||||
album.clean()
|
|
||||||
album.save()
|
|
||||||
for p in f.iterdir():
|
for p in f.iterdir():
|
||||||
file = resize_image(Image.open(p), 1000, "WEBP")
|
file = resize_image(Image.open(p), 1000, "WEBP")
|
||||||
pict = Picture(
|
pict = Picture(
|
||||||
parent=album,
|
parent=album,
|
||||||
name=p.name,
|
name=p.name,
|
||||||
file=file,
|
original=file,
|
||||||
owner=root,
|
owner=root,
|
||||||
is_folder=False,
|
|
||||||
is_in_sas=True,
|
|
||||||
is_moderated=True,
|
is_moderated=True,
|
||||||
mime_type="image/webp",
|
|
||||||
size=file.size,
|
|
||||||
)
|
)
|
||||||
pict.file.name = p.name
|
pict.original.name = pict.name
|
||||||
|
pict.generate_thumbnails()
|
||||||
pict.full_clean()
|
pict.full_clean()
|
||||||
pict.generate_thumbnails(save=True)
|
pict.save()
|
||||||
|
album.generate_thumbnail()
|
||||||
|
|
||||||
img_skia = Picture.objects.get(name="skia.jpg")
|
img_skia = Picture.objects.get(name="skia.jpg")
|
||||||
img_sli = Picture.objects.get(name="sli.jpg")
|
img_sli = Picture.objects.get(name="sli.jpg")
|
||||||
@@ -622,129 +729,6 @@ class Command(BaseCommand):
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
def _create_products(self, groups: PopulatedGroups, clubs: PopulatedClubs):
|
|
||||||
beers_type, cotis_type, refill_type, verre_type = (
|
|
||||||
ProductType.objects.bulk_create(
|
|
||||||
[
|
|
||||||
ProductType(name="Bières bouteilles"),
|
|
||||||
ProductType(name="Cotisations"),
|
|
||||||
ProductType(name="Rechargements"),
|
|
||||||
ProductType(name="Verre"),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
cotis = Product.objects.create(
|
|
||||||
name="Cotis 1 semestre",
|
|
||||||
code="1SCOTIZ",
|
|
||||||
product_type=cotis_type,
|
|
||||||
purchase_price=15,
|
|
||||||
club=clubs.ae,
|
|
||||||
)
|
|
||||||
cotis2 = Product.objects.create(
|
|
||||||
name="Cotis 2 semestres",
|
|
||||||
code="2SCOTIZ",
|
|
||||||
product_type=cotis_type,
|
|
||||||
purchase_price="28",
|
|
||||||
club=clubs.ae,
|
|
||||||
)
|
|
||||||
refill = Product.objects.create(
|
|
||||||
name="Rechargement 15 €",
|
|
||||||
code="15REFILL",
|
|
||||||
product_type=refill_type,
|
|
||||||
purchase_price=15,
|
|
||||||
club=clubs.ae,
|
|
||||||
)
|
|
||||||
barb = Product.objects.create(
|
|
||||||
name="Barbar",
|
|
||||||
code="BARB",
|
|
||||||
product_type=beers_type,
|
|
||||||
purchase_price="1.50",
|
|
||||||
club=clubs.pdf,
|
|
||||||
limit_age=18,
|
|
||||||
)
|
|
||||||
cble = Product.objects.create(
|
|
||||||
name="Chimay Bleue",
|
|
||||||
code="CBLE",
|
|
||||||
product_type=beers_type,
|
|
||||||
purchase_price="1.50",
|
|
||||||
club=clubs.pdf,
|
|
||||||
limit_age=18,
|
|
||||||
)
|
|
||||||
cons = Product.objects.create(
|
|
||||||
name="Consigne Eco-cup",
|
|
||||||
code="CONS",
|
|
||||||
product_type=verre_type,
|
|
||||||
purchase_price="1",
|
|
||||||
club=clubs.pdf,
|
|
||||||
)
|
|
||||||
dcons = Product.objects.create(
|
|
||||||
name="Déconsigne Eco-cup",
|
|
||||||
code="DECO",
|
|
||||||
product_type=verre_type,
|
|
||||||
purchase_price="-1",
|
|
||||||
club=clubs.pdf,
|
|
||||||
)
|
|
||||||
cors = Product.objects.create(
|
|
||||||
name="Corsendonk",
|
|
||||||
code="CORS",
|
|
||||||
product_type=beers_type,
|
|
||||||
purchase_price="1.50",
|
|
||||||
club=clubs.pdf,
|
|
||||||
limit_age=18,
|
|
||||||
)
|
|
||||||
carolus = Product.objects.create(
|
|
||||||
name="Carolus",
|
|
||||||
code="CARO",
|
|
||||||
product_type=beers_type,
|
|
||||||
purchase_price="1.50",
|
|
||||||
club=clubs.pdf,
|
|
||||||
limit_age=18,
|
|
||||||
)
|
|
||||||
Product.objects.create(
|
|
||||||
name="remboursement",
|
|
||||||
code="REMBOURS",
|
|
||||||
purchase_price=0,
|
|
||||||
club=clubs.refound,
|
|
||||||
)
|
|
||||||
ReturnableProduct.objects.create(
|
|
||||||
product=cons, returned_product=dcons, max_return=3
|
|
||||||
)
|
|
||||||
mde = Counter.objects.get(name="MDE")
|
|
||||||
mde.products.add(barb, cble, cons, dcons)
|
|
||||||
eboutic = Counter.objects.get(name="Eboutic")
|
|
||||||
eboutic.products.add(barb, cotis, cotis2, refill)
|
|
||||||
|
|
||||||
cotis, cotis2, refill, barb, cble, cors, carolus, cons, dcons = (
|
|
||||||
Price.objects.bulk_create(
|
|
||||||
[
|
|
||||||
Price(product=cotis, amount=15),
|
|
||||||
Price(product=cotis2, amount=28),
|
|
||||||
Price(product=refill, amount=15),
|
|
||||||
Price(product=barb, amount=1.7),
|
|
||||||
Price(product=cble, amount=1.7),
|
|
||||||
Price(product=cors, amount=1.7),
|
|
||||||
Price(product=carolus, amount=1.7),
|
|
||||||
Price(product=cons, amount=1),
|
|
||||||
Price(product=dcons, amount=-1),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
Price.groups.through.objects.bulk_create(
|
|
||||||
[
|
|
||||||
Price.groups.through(price=cotis, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=cotis2, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=refill, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=barb, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=cble, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=cors, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=carolus, group=groups.subscribers),
|
|
||||||
Price.groups.through(price=cotis, group=groups.old_subscribers),
|
|
||||||
Price.groups.through(price=cotis2, group=groups.old_subscribers),
|
|
||||||
Price.groups.through(price=cons, group=groups.old_subscribers),
|
|
||||||
Price.groups.through(price=dcons, group=groups.old_subscribers),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
def _create_profile_pict(self, user: User):
|
def _create_profile_pict(self, user: User):
|
||||||
path = self.SAS_FIXTURE_PATH / "Family" / f"{user.username}.jpg"
|
path = self.SAS_FIXTURE_PATH / "Family" / f"{user.username}.jpg"
|
||||||
file = resize_image(Image.open(path), 400, "WEBP")
|
file = resize_image(Image.open(path), 400, "WEBP")
|
||||||
@@ -781,57 +765,6 @@ class Command(BaseCommand):
|
|||||||
)
|
)
|
||||||
s.save()
|
s.save()
|
||||||
|
|
||||||
def _create_clubs(self) -> PopulatedClubs:
|
|
||||||
ae = Club.objects.create(
|
|
||||||
id=1, name="AE", address="6 Boulevard Anatole France, 90000 Belfort"
|
|
||||||
)
|
|
||||||
ae.board_group.permissions.add(
|
|
||||||
*Permission.objects.filter(
|
|
||||||
codename__in=[
|
|
||||||
"view_subscription",
|
|
||||||
"add_subscription",
|
|
||||||
"add_membership",
|
|
||||||
"view_hidden_user",
|
|
||||||
]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
pdf = Club.objects.create(
|
|
||||||
id=settings.SITH_PDF_CLUB_ID,
|
|
||||||
name="PdF",
|
|
||||||
address="6 Boulevard Anatole France, 90000 Belfort",
|
|
||||||
)
|
|
||||||
troll = Club.objects.create(
|
|
||||||
name="Troll Penché", address="Terre Du Milieu", parent=ae
|
|
||||||
)
|
|
||||||
refound = Club.objects.create(
|
|
||||||
name="Carte AE", address="Jamais imprimée", parent=ae
|
|
||||||
)
|
|
||||||
roles = []
|
|
||||||
presidency_roles = ["Président⸱e", "Vice-Président⸱e"]
|
|
||||||
board_roles = [
|
|
||||||
"Trésorier⸱e",
|
|
||||||
"Secrétaire",
|
|
||||||
"Respo Info",
|
|
||||||
"Respo Com",
|
|
||||||
"Membre du bureau",
|
|
||||||
]
|
|
||||||
simple_roles = ["Membre actif⸱ve", "Curieux⸱euse"]
|
|
||||||
for club in ae, pdf, troll, refound:
|
|
||||||
for i, role in enumerate(presidency_roles):
|
|
||||||
roles.append(
|
|
||||||
ClubRole(
|
|
||||||
club=club, order=i, name=role, is_presidency=True, is_board=True
|
|
||||||
)
|
|
||||||
)
|
|
||||||
for i, role in enumerate(board_roles, start=len(presidency_roles)):
|
|
||||||
roles.append(ClubRole(club=club, order=i, name=role, is_board=True))
|
|
||||||
for i, role in enumerate(
|
|
||||||
simple_roles, start=len(presidency_roles) + len(board_roles)
|
|
||||||
):
|
|
||||||
roles.append(ClubRole(club=club, order=i, name=role))
|
|
||||||
ClubRole.objects.bulk_create(roles)
|
|
||||||
return PopulatedClubs(ae=ae, troll=troll, pdf=pdf, refound=refound)
|
|
||||||
|
|
||||||
def _create_groups(self) -> PopulatedGroups:
|
def _create_groups(self) -> PopulatedGroups:
|
||||||
perms = Permission.objects.all()
|
perms = Permission.objects.all()
|
||||||
|
|
||||||
|
|||||||
@@ -11,13 +11,12 @@ from django.db.models import Count, Exists, Min, OuterRef, Subquery
|
|||||||
from django.utils.timezone import localdate, make_aware, now
|
from django.utils.timezone import localdate, make_aware, now
|
||||||
from faker import Faker
|
from faker import Faker
|
||||||
|
|
||||||
from club.models import Club, ClubRole, Membership
|
from club.models import Club, Membership
|
||||||
from core.models import Group, User, UserBan
|
from core.models import Group, User, UserBan
|
||||||
from counter.models import (
|
from counter.models import (
|
||||||
Counter,
|
Counter,
|
||||||
Customer,
|
Customer,
|
||||||
Permanency,
|
Permanency,
|
||||||
Price,
|
|
||||||
Product,
|
Product,
|
||||||
ProductType,
|
ProductType,
|
||||||
Refilling,
|
Refilling,
|
||||||
@@ -173,25 +172,20 @@ class Command(BaseCommand):
|
|||||||
Customer.objects.bulk_create(customers, ignore_conflicts=True)
|
Customer.objects.bulk_create(customers, ignore_conflicts=True)
|
||||||
|
|
||||||
def make_club(self, club: Club, members: list[User], old_members: list[User]):
|
def make_club(self, club: Club, members: list[User], old_members: list[User]):
|
||||||
roles: list[ClubRole] = list(club.roles.all())
|
def zip_roles(users: list[User]) -> Iterator[tuple[User, int]]:
|
||||||
|
roles = iter(sorted(settings.SITH_CLUB_ROLES.keys(), reverse=True))
|
||||||
def zip_roles(users: list[User]) -> Iterator[tuple[User, ClubRole]]:
|
|
||||||
important_roles = [r for r in roles if r.is_board]
|
|
||||||
important_roles.sort(key=lambda r: r.order)
|
|
||||||
simple_board_role = important_roles.pop()
|
|
||||||
member_roles = [r for r in roles if not r.is_board]
|
|
||||||
user_idx = 0
|
user_idx = 0
|
||||||
for _role in important_roles:
|
while (role := next(roles)) > 2:
|
||||||
# one member for each major role
|
# one member for each major role
|
||||||
yield users[user_idx], _role
|
yield users[user_idx], role
|
||||||
user_idx += 1
|
user_idx += 1
|
||||||
for _ in range(int(0.3 * (len(users) - user_idx))):
|
for _ in range(int(0.3 * (len(users) - user_idx))):
|
||||||
# 30% of the remaining in the board
|
# 30% of the remaining in the board
|
||||||
yield users[user_idx], simple_board_role
|
yield users[user_idx], 2
|
||||||
user_idx += 1
|
user_idx += 1
|
||||||
for remaining in users[user_idx + 1 :]:
|
for remaining in users[user_idx + 1 :]:
|
||||||
# everything else is a simple member
|
# everything else is a simple member
|
||||||
yield remaining, random.choices(member_roles, weights=(0.8, 0.2))[0]
|
yield remaining, 1
|
||||||
|
|
||||||
memberships = []
|
memberships = []
|
||||||
old_members = old_members.copy()
|
old_members = old_members.copy()
|
||||||
@@ -203,14 +197,19 @@ class Command(BaseCommand):
|
|||||||
start_date=start,
|
start_date=start,
|
||||||
end_date=self.faker.past_date(start),
|
end_date=self.faker.past_date(start),
|
||||||
user=old,
|
user=old,
|
||||||
role=random.choice(roles),
|
role=random.choice(list(settings.SITH_CLUB_ROLES.keys())),
|
||||||
club=club,
|
club=club,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
for member, role in zip_roles(members):
|
for member, role in zip_roles(members):
|
||||||
start = self.faker.past_date("-1y")
|
start = self.faker.past_date("-1y")
|
||||||
memberships.append(
|
memberships.append(
|
||||||
Membership(start_date=start, user=member, role=role, club=club)
|
Membership(
|
||||||
|
start_date=start,
|
||||||
|
user=member,
|
||||||
|
role=role,
|
||||||
|
club=club,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
memberships = Membership.objects.bulk_create(memberships)
|
memberships = Membership.objects.bulk_create(memberships)
|
||||||
Membership._add_club_groups(memberships)
|
Membership._add_club_groups(memberships)
|
||||||
@@ -279,7 +278,6 @@ class Command(BaseCommand):
|
|||||||
# 2/3 of the products are owned by AE
|
# 2/3 of the products are owned by AE
|
||||||
clubs = [ae, ae, ae, ae, ae, ae, *other_clubs]
|
clubs = [ae, ae, ae, ae, ae, ae, *other_clubs]
|
||||||
products = []
|
products = []
|
||||||
prices = []
|
|
||||||
buying_groups = []
|
buying_groups = []
|
||||||
selling_places = []
|
selling_places = []
|
||||||
for _ in range(200):
|
for _ in range(200):
|
||||||
@@ -290,28 +288,25 @@ class Command(BaseCommand):
|
|||||||
product_type=random.choice(categories),
|
product_type=random.choice(categories),
|
||||||
code="".join(self.faker.random_letters(length=random.randint(4, 8))),
|
code="".join(self.faker.random_letters(length=random.randint(4, 8))),
|
||||||
purchase_price=price,
|
purchase_price=price,
|
||||||
|
selling_price=price,
|
||||||
|
special_selling_price=price - min(0.5, price),
|
||||||
club=random.choice(clubs),
|
club=random.choice(clubs),
|
||||||
limit_age=0 if random.random() > 0.2 else 18,
|
limit_age=0 if random.random() > 0.2 else 18,
|
||||||
archived=self.faker.boolean(60),
|
archived=bool(random.random() > 0.7),
|
||||||
)
|
)
|
||||||
products.append(product)
|
products.append(product)
|
||||||
for i in range(random.randint(0, 3)):
|
# there will be products without buying groups
|
||||||
product_price = Price(
|
# but there are also such products in the real database
|
||||||
amount=price, product=product, is_always_shown=self.faker.boolean()
|
buying_groups.extend(
|
||||||
)
|
Product.buying_groups.through(product=product, group=group)
|
||||||
# prices for non-subscribers will be higher than for subscribers
|
for group in random.sample(groups, k=random.randint(0, 3))
|
||||||
price *= 1.2
|
)
|
||||||
prices.append(product_price)
|
|
||||||
buying_groups.append(
|
|
||||||
Price.groups.through(price=product_price, group=groups[i])
|
|
||||||
)
|
|
||||||
selling_places.extend(
|
selling_places.extend(
|
||||||
Counter.products.through(counter=counter, product=product)
|
Counter.products.through(counter=counter, product=product)
|
||||||
for counter in random.sample(counters, random.randint(0, 4))
|
for counter in random.sample(counters, random.randint(0, 4))
|
||||||
)
|
)
|
||||||
Product.objects.bulk_create(products)
|
Product.objects.bulk_create(products)
|
||||||
Price.objects.bulk_create(prices)
|
Product.buying_groups.through.objects.bulk_create(buying_groups)
|
||||||
Price.groups.through.objects.bulk_create(buying_groups)
|
|
||||||
Counter.products.through.objects.bulk_create(selling_places)
|
Counter.products.through.objects.bulk_create(selling_places)
|
||||||
|
|
||||||
def create_sales(self, sellers: list[User]):
|
def create_sales(self, sellers: list[User]):
|
||||||
@@ -325,7 +320,7 @@ class Command(BaseCommand):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
prices = list(Price.objects.select_related("product").all())
|
products = list(Product.objects.all())
|
||||||
counters = list(
|
counters = list(
|
||||||
Counter.objects.filter(name__in=["Foyer", "MDE", "La Gommette"])
|
Counter.objects.filter(name__in=["Foyer", "MDE", "La Gommette"])
|
||||||
)
|
)
|
||||||
@@ -335,14 +330,14 @@ class Command(BaseCommand):
|
|||||||
# the longer the customer has existed, the higher the mean of nb_products
|
# the longer the customer has existed, the higher the mean of nb_products
|
||||||
mu = 5 + (now().year - customer.since.year) * 2
|
mu = 5 + (now().year - customer.since.year) * 2
|
||||||
nb_sales = max(0, int(random.normalvariate(mu=mu, sigma=mu * 5)))
|
nb_sales = max(0, int(random.normalvariate(mu=mu, sigma=mu * 5)))
|
||||||
favoured_prices = random.sample(prices, k=(random.randint(1, 5)))
|
favoured_products = random.sample(products, k=(random.randint(1, 5)))
|
||||||
favoured_counter = random.choice(counters)
|
favoured_counter = random.choice(counters)
|
||||||
this_customer_sales = []
|
this_customer_sales = []
|
||||||
for _ in range(nb_sales):
|
for _ in range(nb_sales):
|
||||||
price = (
|
product = (
|
||||||
random.choice(favoured_prices)
|
random.choice(favoured_products)
|
||||||
if random.random() > 0.7
|
if random.random() > 0.7
|
||||||
else random.choice(prices)
|
else random.choice(products)
|
||||||
)
|
)
|
||||||
counter = (
|
counter = (
|
||||||
favoured_counter
|
favoured_counter
|
||||||
@@ -351,11 +346,11 @@ class Command(BaseCommand):
|
|||||||
)
|
)
|
||||||
this_customer_sales.append(
|
this_customer_sales.append(
|
||||||
Selling(
|
Selling(
|
||||||
product=price.product,
|
product=product,
|
||||||
counter=counter,
|
counter=counter,
|
||||||
club_id=price.product.club_id,
|
club_id=product.club_id,
|
||||||
quantity=random.randint(1, 5),
|
quantity=random.randint(1, 5),
|
||||||
unit_price=price.amount,
|
unit_price=product.selling_price,
|
||||||
seller=random.choice(sellers),
|
seller=random.choice(sellers),
|
||||||
customer=customer,
|
customer=customer,
|
||||||
date=make_aware(
|
date=make_aware(
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Generated by Django 4.2.17 on 2025-01-26 15:01
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
from django.db.migrations.state import StateApps
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
import core.models
|
||||||
|
|
||||||
|
|
||||||
|
def remove_sas_sithfiles(apps: StateApps, schema_editor):
|
||||||
|
SithFile: type[core.models.SithFile] = apps.get_model("core", "SithFile")
|
||||||
|
SithFile.objects.filter(is_in_sas=True).delete()
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("core", "0048_alter_user_options"),
|
||||||
|
("sas", "0007_alter_peoplepicturerelation_picture_and_more"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(
|
||||||
|
remove_sas_sithfiles, reverse_code=migrations.RunPython.noop, elidable=True
|
||||||
|
)
|
||||||
|
]
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
# Generated by Django 5.2.12 on 2026-03-14 08:39
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [("core", "0048_alter_user_options")]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="user",
|
|
||||||
name="whitelisted_users",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True,
|
|
||||||
help_text=(
|
|
||||||
"Even if this profile is hidden, "
|
|
||||||
"the users in this list will still be able to see it."
|
|
||||||
),
|
|
||||||
related_name="visible_by_whitelist",
|
|
||||||
to=settings.AUTH_USER_MODEL,
|
|
||||||
verbose_name="whitelisted users",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="preferences",
|
|
||||||
name="show_my_stats",
|
|
||||||
field=models.BooleanField(
|
|
||||||
default=False,
|
|
||||||
help_text=(
|
|
||||||
"Allow subscribers (or whitelisted users "
|
|
||||||
"if your profile is hidden) to access your AE account stats."
|
|
||||||
),
|
|
||||||
verbose_name="show your stats to others",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
# Generated by Django 5.2.12 on 2026-05-01 08:59
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
from django.db.migrations.state import StateApps
|
|
||||||
from django.db.models import F
|
|
||||||
|
|
||||||
|
|
||||||
def set_updated_at(apps: StateApps, schema_editor):
|
|
||||||
SithFile = apps.get_model("core", "SithFile")
|
|
||||||
SithFile.objects.update(updated_at=F("date"))
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [("core", "0049_user_whitelisted_users")]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="sithfile",
|
|
||||||
name="moderator",
|
|
||||||
field=models.ForeignKey(
|
|
||||||
blank=True,
|
|
||||||
null=True,
|
|
||||||
on_delete=django.db.models.deletion.SET_NULL,
|
|
||||||
related_name="moderated_files",
|
|
||||||
to=settings.AUTH_USER_MODEL,
|
|
||||||
verbose_name="owner",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="sithfile",
|
|
||||||
name="owner",
|
|
||||||
field=models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="owned_files",
|
|
||||||
to=settings.AUTH_USER_MODEL,
|
|
||||||
verbose_name="owner",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="sithfile",
|
|
||||||
name="updated_at",
|
|
||||||
field=models.DateTimeField(auto_now=True, verbose_name="updated at"),
|
|
||||||
),
|
|
||||||
migrations.RunPython(set_updated_at, reverse_code=migrations.RunPython.noop),
|
|
||||||
]
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Generated by Django 4.2.17 on 2025-02-14 11:58
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [("core", "0049_remove_sithfiles")]
|
||||||
|
|
||||||
|
operations = [migrations.RemoveField(model_name="sithfile", name="is_in_sas")]
|
||||||
+28
-101
@@ -131,9 +131,7 @@ class UserQuerySet(models.QuerySet):
|
|||||||
if user.has_perm("core.view_hidden_user"):
|
if user.has_perm("core.view_hidden_user"):
|
||||||
return self
|
return self
|
||||||
if user.has_perm("core.view_user"):
|
if user.has_perm("core.view_user"):
|
||||||
return self.filter(
|
return self.filter(is_viewable=True)
|
||||||
Q(is_viewable=True) | Q(whitelisted_users=user) | Q(pk=user.pk)
|
|
||||||
)
|
|
||||||
if user.is_anonymous:
|
if user.is_anonymous:
|
||||||
return self.none()
|
return self.none()
|
||||||
return self.filter(id=user.id)
|
return self.filter(id=user.id)
|
||||||
@@ -281,16 +279,6 @@ class User(AbstractUser):
|
|||||||
),
|
),
|
||||||
default=True,
|
default=True,
|
||||||
)
|
)
|
||||||
whitelisted_users = models.ManyToManyField(
|
|
||||||
"User",
|
|
||||||
related_name="visible_by_whitelist",
|
|
||||||
verbose_name=_("whitelisted users"),
|
|
||||||
help_text=_(
|
|
||||||
"Even if this profile is hidden, "
|
|
||||||
"the users in this list will still be able to see it."
|
|
||||||
),
|
|
||||||
blank=True,
|
|
||||||
)
|
|
||||||
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
||||||
|
|
||||||
objects = CustomUserManager()
|
objects = CustomUserManager()
|
||||||
@@ -368,27 +356,23 @@ class User(AbstractUser):
|
|||||||
)
|
)
|
||||||
if group_id is None:
|
if group_id is None:
|
||||||
return False
|
return False
|
||||||
return group_id in self.all_groups
|
if group_id == settings.SITH_GROUP_SUBSCRIBERS_ID:
|
||||||
|
return self.is_subscribed
|
||||||
|
if group_id == settings.SITH_GROUP_ROOT_ID:
|
||||||
|
return self.is_root
|
||||||
|
return any(g.id == group_id for g in self.cached_groups)
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def all_groups(self) -> dict[int, Group]:
|
def cached_groups(self) -> list[Group]:
|
||||||
"""Get the list of groups this user is in."""
|
"""Get the list of groups this user is in."""
|
||||||
additional_groups = []
|
return list(self.groups.all())
|
||||||
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}
|
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def is_root(self) -> bool:
|
def is_root(self) -> bool:
|
||||||
return self.is_superuser or settings.SITH_GROUP_ROOT_ID in self.all_groups
|
if self.is_superuser:
|
||||||
|
return True
|
||||||
|
root_id = settings.SITH_GROUP_ROOT_ID
|
||||||
|
return any(g.id == root_id for g in self.cached_groups)
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def is_board_member(self) -> bool:
|
def is_board_member(self) -> bool:
|
||||||
@@ -530,7 +514,7 @@ class User(AbstractUser):
|
|||||||
self.username = user_name
|
self.username = user_name
|
||||||
return user_name
|
return user_name
|
||||||
|
|
||||||
def is_owner(self, obj: models.Model):
|
def is_owner(self, obj):
|
||||||
"""Determine if the object is owned by the user."""
|
"""Determine if the object is owned by the user."""
|
||||||
if hasattr(obj, "is_owned_by") and obj.is_owned_by(self):
|
if hasattr(obj, "is_owned_by") and obj.is_owned_by(self):
|
||||||
return True
|
return True
|
||||||
@@ -538,7 +522,7 @@ class User(AbstractUser):
|
|||||||
return True
|
return True
|
||||||
return self.is_root
|
return self.is_root
|
||||||
|
|
||||||
def can_edit(self, obj: models.Model):
|
def can_edit(self, obj):
|
||||||
"""Determine if the object can be edited by the user."""
|
"""Determine if the object can be edited by the user."""
|
||||||
if hasattr(obj, "can_be_edited_by") and obj.can_be_edited_by(self):
|
if hasattr(obj, "can_be_edited_by") and obj.can_be_edited_by(self):
|
||||||
return True
|
return True
|
||||||
@@ -552,9 +536,11 @@ class User(AbstractUser):
|
|||||||
pks = list(obj.edit_groups.values_list("id", flat=True))
|
pks = list(obj.edit_groups.values_list("id", flat=True))
|
||||||
if any(self.is_in_group(pk=pk) for pk in pks):
|
if any(self.is_in_group(pk=pk) for pk in pks):
|
||||||
return True
|
return True
|
||||||
|
if isinstance(obj, User) and obj == self:
|
||||||
|
return True
|
||||||
return self.is_owner(obj)
|
return self.is_owner(obj)
|
||||||
|
|
||||||
def can_view(self, obj: models.Model):
|
def can_view(self, obj):
|
||||||
"""Determine if the object can be viewed by the user."""
|
"""Determine if the object can be viewed by the user."""
|
||||||
if hasattr(obj, "can_be_viewed_by") and obj.can_be_viewed_by(self):
|
if hasattr(obj, "can_be_viewed_by") and obj.can_be_viewed_by(self):
|
||||||
return True
|
return True
|
||||||
@@ -573,35 +559,14 @@ class User(AbstractUser):
|
|||||||
return True
|
return True
|
||||||
return self.can_edit(obj)
|
return self.can_edit(obj)
|
||||||
|
|
||||||
def can_be_edited_by(self, user: User):
|
def can_be_edited_by(self, user):
|
||||||
return user == self or user.is_root or user.is_board_member
|
return user.is_root or user.is_board_member
|
||||||
|
|
||||||
def can_be_viewed_by(self, user: User) -> bool:
|
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 (
|
return (
|
||||||
user.id == self.id
|
user.id == self.id
|
||||||
or user.has_perm("core.view_hidden_user")
|
or user.has_perm("core.view_hidden_user")
|
||||||
or (
|
or (user.has_perm("core.view_user") and self.is_viewable)
|
||||||
user.has_perm("core.view_user")
|
|
||||||
and (self.is_viewable or is_in_whitelist(user))
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_mini_item(self):
|
def get_mini_item(self):
|
||||||
@@ -781,14 +746,7 @@ class Preferences(models.Model):
|
|||||||
User, related_name="_preferences", on_delete=models.CASCADE
|
User, related_name="_preferences", on_delete=models.CASCADE
|
||||||
)
|
)
|
||||||
receive_weekmail = models.BooleanField(_("receive the Weekmail"), default=False)
|
receive_weekmail = models.BooleanField(_("receive the Weekmail"), default=False)
|
||||||
show_my_stats = models.BooleanField(
|
show_my_stats = models.BooleanField(_("show your stats to others"), default=False)
|
||||||
_("show your stats to others"),
|
|
||||||
help_text=_(
|
|
||||||
"Allow subscribers (or whitelisted users "
|
|
||||||
"if your profile is hidden) to access your AE account stats."
|
|
||||||
),
|
|
||||||
default=False,
|
|
||||||
)
|
|
||||||
notify_on_click = models.BooleanField(
|
notify_on_click = models.BooleanField(
|
||||||
_("get a notification for every click"), default=False
|
_("get a notification for every click"), default=False
|
||||||
)
|
)
|
||||||
@@ -853,7 +811,7 @@ class SithFile(models.Model):
|
|||||||
User,
|
User,
|
||||||
related_name="owned_files",
|
related_name="owned_files",
|
||||||
verbose_name=_("owner"),
|
verbose_name=_("owner"),
|
||||||
on_delete=models.PROTECT,
|
on_delete=models.CASCADE,
|
||||||
)
|
)
|
||||||
edit_groups = models.ManyToManyField(
|
edit_groups = models.ManyToManyField(
|
||||||
Group, related_name="editable_files", verbose_name=_("edit group"), blank=True
|
Group, related_name="editable_files", verbose_name=_("edit group"), blank=True
|
||||||
@@ -865,7 +823,6 @@ class SithFile(models.Model):
|
|||||||
mime_type = models.CharField(_("mime type"), max_length=30)
|
mime_type = models.CharField(_("mime type"), max_length=30)
|
||||||
size = models.IntegerField(_("size"), default=0)
|
size = models.IntegerField(_("size"), default=0)
|
||||||
date = models.DateTimeField(_("date"), default=timezone.now)
|
date = models.DateTimeField(_("date"), default=timezone.now)
|
||||||
updated_at = models.DateTimeField(_("updated at"), auto_now=True)
|
|
||||||
is_moderated = models.BooleanField(_("is moderated"), default=False)
|
is_moderated = models.BooleanField(_("is moderated"), default=False)
|
||||||
moderator = models.ForeignKey(
|
moderator = models.ForeignKey(
|
||||||
User,
|
User,
|
||||||
@@ -873,12 +830,9 @@ class SithFile(models.Model):
|
|||||||
verbose_name=_("owner"),
|
verbose_name=_("owner"),
|
||||||
null=True,
|
null=True,
|
||||||
blank=True,
|
blank=True,
|
||||||
on_delete=models.SET_NULL,
|
on_delete=models.CASCADE,
|
||||||
)
|
)
|
||||||
asked_for_removal = models.BooleanField(_("asked for removal"), default=False)
|
asked_for_removal = models.BooleanField(_("asked for removal"), default=False)
|
||||||
is_in_sas = models.BooleanField(
|
|
||||||
_("is in the SAS"), default=False, db_index=True
|
|
||||||
) # Allows to query this flag, updated at each call to save()
|
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("file")
|
verbose_name = _("file")
|
||||||
@@ -887,24 +841,10 @@ class SithFile(models.Model):
|
|||||||
return self.get_parent_path() + "/" + self.name
|
return self.get_parent_path() + "/" + self.name
|
||||||
|
|
||||||
def save(self, *args, **kwargs):
|
def save(self, *args, **kwargs):
|
||||||
sas_id = settings.SITH_SAS_ROOT_DIR_ID
|
|
||||||
self.is_in_sas = self.id == sas_id or any(
|
|
||||||
p.id == sas_id for p in self.get_parent_list()
|
|
||||||
)
|
|
||||||
adding = self._state.adding
|
adding = self._state.adding
|
||||||
super().save(*args, **kwargs)
|
super().save(*args, **kwargs)
|
||||||
if adding:
|
if adding:
|
||||||
self.copy_rights()
|
self.copy_rights()
|
||||||
if self.is_in_sas:
|
|
||||||
for user in User.objects.filter(
|
|
||||||
groups__id__in=[settings.SITH_GROUP_SAS_ADMIN_ID]
|
|
||||||
):
|
|
||||||
Notification(
|
|
||||||
user=user,
|
|
||||||
url=reverse("sas:moderation"),
|
|
||||||
type="SAS_MODERATION",
|
|
||||||
param="1",
|
|
||||||
).save()
|
|
||||||
|
|
||||||
def is_owned_by(self, user: User) -> bool:
|
def is_owned_by(self, user: User) -> bool:
|
||||||
if user.is_anonymous:
|
if user.is_anonymous:
|
||||||
@@ -917,8 +857,6 @@ class SithFile(models.Model):
|
|||||||
return user.is_board_member
|
return user.is_board_member
|
||||||
if user.is_com_admin:
|
if user.is_com_admin:
|
||||||
return True
|
return True
|
||||||
if self.is_in_sas and user.is_in_group(pk=settings.SITH_GROUP_SAS_ADMIN_ID):
|
|
||||||
return True
|
|
||||||
return user.id == self.owner_id
|
return user.id == self.owner_id
|
||||||
|
|
||||||
def can_be_viewed_by(self, user: User) -> bool:
|
def can_be_viewed_by(self, user: User) -> bool:
|
||||||
@@ -945,8 +883,6 @@ class SithFile(models.Model):
|
|||||||
super().clean()
|
super().clean()
|
||||||
if "/" in self.name:
|
if "/" in self.name:
|
||||||
raise ValidationError(_("Character '/' not authorized in name"))
|
raise ValidationError(_("Character '/' not authorized in name"))
|
||||||
if self == self.parent:
|
|
||||||
raise ValidationError(_("Loop in folder tree"), code="loop")
|
|
||||||
if self == self.parent or (
|
if self == self.parent or (
|
||||||
self.parent is not None and self in self.get_parent_list()
|
self.parent is not None and self in self.get_parent_list()
|
||||||
):
|
):
|
||||||
@@ -1027,18 +963,6 @@ class SithFile(models.Model):
|
|||||||
def is_file(self):
|
def is_file(self):
|
||||||
return not self.is_folder
|
return not self.is_folder
|
||||||
|
|
||||||
@cached_property
|
|
||||||
def as_picture(self):
|
|
||||||
from sas.models import Picture
|
|
||||||
|
|
||||||
return Picture.objects.filter(id=self.id).first()
|
|
||||||
|
|
||||||
@cached_property
|
|
||||||
def as_album(self):
|
|
||||||
from sas.models import Album
|
|
||||||
|
|
||||||
return Album.objects.filter(id=self.id).first()
|
|
||||||
|
|
||||||
def get_parent_list(self):
|
def get_parent_list(self):
|
||||||
parents = []
|
parents = []
|
||||||
current = self.parent
|
current = self.parent
|
||||||
@@ -1144,7 +1068,10 @@ class PageQuerySet(models.QuerySet):
|
|||||||
return self.filter(view_groups=settings.SITH_GROUP_PUBLIC_ID)
|
return self.filter(view_groups=settings.SITH_GROUP_PUBLIC_ID)
|
||||||
if user.has_perm("core.view_page"):
|
if user.has_perm("core.view_page"):
|
||||||
return self.all()
|
return self.all()
|
||||||
return self.filter(view_groups__in=user.all_groups)
|
groups_ids = [g.id for g in user.cached_groups]
|
||||||
|
if user.is_subscribed:
|
||||||
|
groups_ids.append(settings.SITH_GROUP_SUBSCRIBERS_ID)
|
||||||
|
return self.filter(view_groups__in=groups_ids)
|
||||||
|
|
||||||
|
|
||||||
# This function prevents generating migration upon settings change
|
# This function prevents generating migration upon settings change
|
||||||
@@ -1418,7 +1345,7 @@ class PageRev(models.Model):
|
|||||||
return self.page.can_be_edited_by(user)
|
return self.page.can_be_edited_by(user)
|
||||||
|
|
||||||
def is_owned_by(self, user: User) -> bool:
|
def is_owned_by(self, user: User) -> bool:
|
||||||
return self.page.owner_group_id in user.all_groups
|
return any(g.id == self.page.owner_group_id for g in user.cached_groups)
|
||||||
|
|
||||||
def similarity_ratio(self, text: str) -> float:
|
def similarity_ratio(self, text: str) -> float:
|
||||||
"""Similarity ratio between this revision's content and the given text.
|
"""Similarity ratio between this revision's content and the given text.
|
||||||
|
|||||||
@@ -1,136 +1,18 @@
|
|||||||
import {
|
import { inheritHtmlElement, registerComponent } from "#core:utils/web-components.ts";
|
||||||
type InheritedHtmlElement,
|
|
||||||
inheritHtmlElement,
|
|
||||||
registerComponent,
|
|
||||||
} from "#core:utils/web-components.ts";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ElementOnce web components
|
|
||||||
*
|
|
||||||
* Those elements ensures that their content is always included only once on a document
|
|
||||||
* They are compatible with elements that are not managed with our Web Components
|
|
||||||
**/
|
|
||||||
export interface ElementOnce<K extends keyof HTMLElementTagNameMap>
|
|
||||||
extends InheritedHtmlElement<K> {
|
|
||||||
getElementQuerySelector(): string;
|
|
||||||
refresh(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create an abstract class for ElementOnce types Web Components
|
|
||||||
**/
|
|
||||||
export function elementOnce<K extends keyof HTMLElementTagNameMap>(tagName: K) {
|
|
||||||
abstract class ElementOnceImpl
|
|
||||||
extends inheritHtmlElement(tagName)
|
|
||||||
implements ElementOnce<K>
|
|
||||||
{
|
|
||||||
abstract getElementQuerySelector(): string;
|
|
||||||
|
|
||||||
clearNode() {
|
|
||||||
while (this.firstChild) {
|
|
||||||
this.removeChild(this.lastChild);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
refresh() {
|
|
||||||
this.clearNode();
|
|
||||||
if (document.querySelectorAll(this.getElementQuerySelector()).length === 0) {
|
|
||||||
this.appendChild(this.node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connectedCallback() {
|
|
||||||
super.connectedCallback(false);
|
|
||||||
this.refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
disconnectedCallback() {
|
|
||||||
// The MutationObserver can't see web components being removed
|
|
||||||
// It also can't see if something is removed inside after the component gets deleted
|
|
||||||
// We need to manually clear the containing node to trigger the observer
|
|
||||||
this.clearNode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ElementOnceImpl;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set of ElementOnce type components to refresh with the observer
|
|
||||||
const registeredComponents: Set<string> = new Set();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper to register ElementOnce types Web Components
|
|
||||||
* It's a wrapper around registerComponent that registers that component on
|
|
||||||
* a MutationObserver that activates a refresh on them when elements are removed
|
|
||||||
*
|
|
||||||
* You are not supposed to unregister an element
|
|
||||||
**/
|
|
||||||
export function registerElementOnce(name: string, options?: ElementDefinitionOptions) {
|
|
||||||
registeredComponents.add(name);
|
|
||||||
return registerComponent(name, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refresh all ElementOnce components on the document based on the tag name of the removed element
|
|
||||||
const refreshElement = <
|
|
||||||
T extends keyof HTMLElementTagNameMap,
|
|
||||||
K extends keyof HTMLElementTagNameMap,
|
|
||||||
>(
|
|
||||||
components: HTMLCollectionOf<ElementOnce<T>>,
|
|
||||||
removedTagName: K,
|
|
||||||
) => {
|
|
||||||
for (const element of components) {
|
|
||||||
// We can't guess if an element is compatible before we get one
|
|
||||||
// We exit the function completely if it's not compatible
|
|
||||||
if (element.inheritedTagName.toUpperCase() !== removedTagName.toUpperCase()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
element.refresh();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Since we need to pause the observer, we make an helper to start it with consistent arguments
|
|
||||||
const startObserver = (observer: MutationObserver) => {
|
|
||||||
observer.observe(document, {
|
|
||||||
// We want to also listen for elements contained in the header (eg: link)
|
|
||||||
subtree: true,
|
|
||||||
childList: true,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Refresh ElementOnce components when changes happens
|
|
||||||
const observer = new MutationObserver((mutations: MutationRecord[]) => {
|
|
||||||
// To avoid infinite recursion, we need to pause the observer while manipulation nodes
|
|
||||||
observer.disconnect();
|
|
||||||
for (const mutation of mutations) {
|
|
||||||
for (const node of mutation.removedNodes) {
|
|
||||||
if (node.nodeType !== node.ELEMENT_NODE) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
for (const registered of registeredComponents) {
|
|
||||||
refreshElement(
|
|
||||||
document.getElementsByTagName(registered) as HTMLCollectionOf<
|
|
||||||
ElementOnce<"html"> // The specific tag doesn't really matter
|
|
||||||
>,
|
|
||||||
(node as HTMLElement).tagName as keyof HTMLElementTagNameMap,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// We then resume the observer
|
|
||||||
startObserver(observer);
|
|
||||||
});
|
|
||||||
|
|
||||||
startObserver(observer);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Web component used to import css files only once
|
* Web component used to import css files only once
|
||||||
* If called multiple times or the file was already imported, it does nothing
|
* If called multiple times or the file was already imported, it does nothing
|
||||||
**/
|
**/
|
||||||
@registerElementOnce("link-once")
|
@registerComponent("link-once")
|
||||||
export class LinkOnce extends elementOnce("link") {
|
export class LinkOnce extends inheritHtmlElement("link") {
|
||||||
getElementQuerySelector(): string {
|
connectedCallback() {
|
||||||
|
super.connectedCallback(false);
|
||||||
// We get href from node.attributes instead of node.href to avoid getting the domain part
|
// We get href from node.attributes instead of node.href to avoid getting the domain part
|
||||||
return `link[href='${this.node.attributes.getNamedItem("href").nodeValue}']`;
|
const href = this.node.attributes.getNamedItem("href").nodeValue;
|
||||||
|
if (document.querySelectorAll(`link[href='${href}']`).length === 0) {
|
||||||
|
this.appendChild(this.node);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,10 +20,14 @@ export class LinkOnce extends elementOnce("link") {
|
|||||||
* Web component used to import javascript files only once
|
* Web component used to import javascript files only once
|
||||||
* If called multiple times or the file was already imported, it does nothing
|
* If called multiple times or the file was already imported, it does nothing
|
||||||
**/
|
**/
|
||||||
@registerElementOnce("script-once")
|
@registerComponent("script-once")
|
||||||
export class ScriptOnce extends inheritHtmlElement("script") {
|
export class ScriptOnce extends inheritHtmlElement("script") {
|
||||||
getElementQuerySelector(): string {
|
connectedCallback() {
|
||||||
// We get href from node.attributes instead of node.src to avoid getting the domain part
|
super.connectedCallback(false);
|
||||||
return `script[src='${this.node.attributes.getNamedItem("src").nodeValue}']`;
|
// We get src from node.attributes instead of node.src to avoid getting the domain part
|
||||||
|
const src = this.node.attributes.getNamedItem("src").nodeValue;
|
||||||
|
if (document.querySelectorAll(`script[src='${src}']`).length === 0) {
|
||||||
|
this.appendChild(this.node);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ export class NfcInput extends inheritHtmlElement("input") {
|
|||||||
window.alert(gettext("Unsupported NFC card"));
|
window.alert(gettext("Unsupported NFC card"));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// biome-ignore lint/correctness/noUndeclaredVariables: browser API
|
||||||
ndef.addEventListener("reading", (event: NDEFReadingEvent) => {
|
ndef.addEventListener("reading", (event: NDEFReadingEvent) => {
|
||||||
this.removeAttribute("scan");
|
this.removeAttribute("scan");
|
||||||
this.node.value = event.serialNumber.replace(/:/g, "").toUpperCase();
|
this.node.value = event.serialNumber.replace(/:/g, "").toUpperCase();
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export class Tab extends HTMLElement {
|
|||||||
return html`
|
return html`
|
||||||
<button
|
<button
|
||||||
role="tab"
|
role="tab"
|
||||||
?aria-selected="${this.active}"
|
?aria-selected=${this.active}
|
||||||
class="tab-header clickable ${this.active ? "active" : ""}"
|
class="tab-header clickable ${this.active ? "active" : ""}"
|
||||||
@click="${() => this.setActive(true)}"
|
@click="${() => this.setActive(true)}"
|
||||||
>
|
>
|
||||||
@@ -40,7 +40,7 @@ export class Tab extends HTMLElement {
|
|||||||
return html`
|
return html`
|
||||||
<section
|
<section
|
||||||
class="tab-section"
|
class="tab-section"
|
||||||
?hidden="${!this.active}"
|
?hidden=${!this.active}
|
||||||
>
|
>
|
||||||
${unsafeHTML(this.getContentHtml())}
|
${unsafeHTML(this.getContentHtml())}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,77 +0,0 @@
|
|||||||
interface Config {
|
|
||||||
/**
|
|
||||||
* The prefix of the formset, in case it has been changed.
|
|
||||||
* See https://docs.djangoproject.com/fr/stable/topics/forms/formsets/#customizing-a-formset-s-prefix
|
|
||||||
*/
|
|
||||||
prefix?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// biome-ignore lint/style/useNamingConvention: It's the DOM API naming
|
|
||||||
type HTMLFormInputElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
|
|
||||||
|
|
||||||
document.addEventListener("alpine:init", () => {
|
|
||||||
/**
|
|
||||||
* Alpine data element to allow the dynamic addition of forms to a formset.
|
|
||||||
*
|
|
||||||
* To use this, you need :
|
|
||||||
* - an HTML element containing the existing forms, noted by `x-ref="formContainer"`
|
|
||||||
* - a template containing the empty form
|
|
||||||
* (that you can obtain jinja-side with `{{ formset.empty_form }}`),
|
|
||||||
* noted by `x-ref="formTemplate"`
|
|
||||||
* - a button with `@click="addForm"`
|
|
||||||
* - you may also have one or more buttons with `@click="removeForm(element)"`,
|
|
||||||
* where `element` is the HTML element containing the form.
|
|
||||||
*
|
|
||||||
* For an example of how this is used, you can have a look to
|
|
||||||
* `counter/templates/counter/product_form.jinja`
|
|
||||||
*/
|
|
||||||
Alpine.data("dynamicFormSet", (config?: Config) => ({
|
|
||||||
init() {
|
|
||||||
this.formContainer = this.$refs.formContainer as HTMLElement;
|
|
||||||
this.nbForms = this.formContainer.children.length as number;
|
|
||||||
this.template = this.$refs.formTemplate as HTMLTemplateElement;
|
|
||||||
const prefix = config?.prefix ?? "form";
|
|
||||||
this.$root
|
|
||||||
.querySelector(`#id_${prefix}-TOTAL_FORMS`)
|
|
||||||
.setAttribute(":value", "nbForms");
|
|
||||||
},
|
|
||||||
|
|
||||||
addForm() {
|
|
||||||
this.formContainer.appendChild(document.importNode(this.template.content, true));
|
|
||||||
const newForm = this.formContainer.lastElementChild;
|
|
||||||
const inputs: NodeListOf<HTMLFormInputElement> = newForm.querySelectorAll(
|
|
||||||
"input, select, textarea",
|
|
||||||
);
|
|
||||||
for (const el of inputs) {
|
|
||||||
el.name = el.name.replace("__prefix__", this.nbForms.toString());
|
|
||||||
el.id = el.id.replace("__prefix__", this.nbForms.toString());
|
|
||||||
}
|
|
||||||
const labels: NodeListOf<HTMLLabelElement> = newForm.querySelectorAll("label");
|
|
||||||
for (const el of labels) {
|
|
||||||
el.htmlFor = el.htmlFor.replace("__prefix__", this.nbForms.toString());
|
|
||||||
}
|
|
||||||
inputs[0].focus();
|
|
||||||
this.nbForms += 1;
|
|
||||||
},
|
|
||||||
|
|
||||||
removeForm(container: HTMLDivElement) {
|
|
||||||
container.remove();
|
|
||||||
this.nbForms -= 1;
|
|
||||||
// adjust the id of remaining forms
|
|
||||||
for (let i = 0; i < this.nbForms; i++) {
|
|
||||||
const form: HTMLDivElement = this.formContainer.children[i];
|
|
||||||
const inputs: NodeListOf<HTMLFormInputElement> = form.querySelectorAll(
|
|
||||||
"input, select, textarea",
|
|
||||||
);
|
|
||||||
for (const el of inputs) {
|
|
||||||
el.name = el.name.replace(/\d+/, i.toString());
|
|
||||||
el.id = el.id.replace(/\d+/, i.toString());
|
|
||||||
}
|
|
||||||
const labels: NodeListOf<HTMLLabelElement> = form.querySelectorAll("label");
|
|
||||||
for (const el of labels) {
|
|
||||||
el.htmlFor = el.htmlFor.replace(/\d+/, i.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
@@ -23,17 +23,10 @@ export function registerComponent(name: string, options?: ElementDefinitionOptio
|
|||||||
* The technique is to:
|
* The technique is to:
|
||||||
* create a new web component
|
* create a new web component
|
||||||
* create the desired type inside
|
* create the desired type inside
|
||||||
* move all attributes to the child component
|
* pass all attributes to the child component
|
||||||
* store is at as `node` inside the parent
|
* store is at as `node` inside the parent
|
||||||
**/
|
*
|
||||||
export interface InheritedHtmlElement<K extends keyof HTMLElementTagNameMap>
|
* Since we can't use the generic type to instantiate the node, we create a generator function
|
||||||
extends HTMLElement {
|
|
||||||
readonly inheritedTagName: K;
|
|
||||||
node: HTMLElementTagNameMap[K];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generator function that creates an InheritedHtmlElement compatible class
|
|
||||||
*
|
*
|
||||||
* ```js
|
* ```js
|
||||||
* class MyClass extends inheritHtmlElement("select") {
|
* class MyClass extends inheritHtmlElement("select") {
|
||||||
@@ -42,24 +35,11 @@ export interface InheritedHtmlElement<K extends keyof HTMLElementTagNameMap>
|
|||||||
* ```
|
* ```
|
||||||
**/
|
**/
|
||||||
export function inheritHtmlElement<K extends keyof HTMLElementTagNameMap>(tagName: K) {
|
export function inheritHtmlElement<K extends keyof HTMLElementTagNameMap>(tagName: K) {
|
||||||
return class InheritedHtmlElementImpl
|
return class Inherited extends HTMLElement {
|
||||||
extends HTMLElement
|
protected node: HTMLElementTagNameMap[K];
|
||||||
implements InheritedHtmlElement<K>
|
|
||||||
{
|
|
||||||
readonly inheritedTagName = tagName;
|
|
||||||
private readonly initializedAttribute = "component-initialized";
|
|
||||||
node: HTMLElementTagNameMap[K];
|
|
||||||
|
|
||||||
connectedCallback(autoAddNode?: boolean) {
|
connectedCallback(autoAddNode?: boolean) {
|
||||||
// When nesting inherited elements, we might trigger the wrapping twice
|
this.node = document.createElement(tagName);
|
||||||
// To avoid this, we tag a created element as initialized
|
|
||||||
// We then skip the initialization step and grab the inner content as the node
|
|
||||||
if (this.hasAttribute(this.initializedAttribute)) {
|
|
||||||
this.node = this.firstChild as HTMLElementTagNameMap[K];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.node = document.createElement(this.inheritedTagName);
|
|
||||||
const attributes: Attr[] = []; // We need to make a copy to delete while iterating
|
const attributes: Attr[] = []; // We need to make a copy to delete while iterating
|
||||||
for (const attr of this.attributes) {
|
for (const attr of this.attributes) {
|
||||||
if (attr.name in this.node) {
|
if (attr.name in this.node) {
|
||||||
@@ -67,12 +47,6 @@ export function inheritHtmlElement<K extends keyof HTMLElementTagNameMap>(tagNam
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.setAttribute(this.initializedAttribute, "");
|
|
||||||
|
|
||||||
// We move compatible attributes to the child element
|
|
||||||
// This avoids weird inconsistencies between attributes
|
|
||||||
// when we manipulate the dom in the future
|
|
||||||
// This is especially important when using attribute based reactivity
|
|
||||||
for (const attr of attributes) {
|
for (const attr of attributes) {
|
||||||
this.removeAttributeNode(attr);
|
this.removeAttributeNode(attr);
|
||||||
this.node.setAttributeNode(attr);
|
this.node.setAttributeNode(attr);
|
||||||
|
|||||||
@@ -115,6 +115,7 @@ blockquote:before,
|
|||||||
blockquote:after,
|
blockquote:after,
|
||||||
q:before,
|
q:before,
|
||||||
q:after {
|
q:after {
|
||||||
|
content: "";
|
||||||
content: none;
|
content: none;
|
||||||
}
|
}
|
||||||
table {
|
table {
|
||||||
|
|||||||
@@ -157,7 +157,6 @@ form {
|
|||||||
margin-bottom: .25rem;
|
margin-bottom: .25rem;
|
||||||
font-size: 80%;
|
font-size: 80%;
|
||||||
display: block;
|
display: block;
|
||||||
max-width: calc(100% - calc(var(--nf-input-size) * 2))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fieldset {
|
fieldset {
|
||||||
|
|||||||
@@ -271,7 +271,7 @@ body {
|
|||||||
|
|
||||||
/*--------------------------------CONTENT------------------------------*/
|
/*--------------------------------CONTENT------------------------------*/
|
||||||
#content {
|
#content {
|
||||||
padding: 1.5em 3%;
|
padding: 1em 1%;
|
||||||
box-shadow: $shadow-color 0 5px 10px;
|
box-shadow: $shadow-color 0 5px 10px;
|
||||||
background: $white-color;
|
background: $white-color;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
|
|||||||
@@ -5,6 +5,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.profile {
|
.profile {
|
||||||
|
&-visible {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
padding-top: 10px;
|
||||||
|
input[type="checkbox"]+label {
|
||||||
|
max-width: unset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
&-pictures {
|
&-pictures {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -19,6 +19,28 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&-cards,
|
||||||
|
&-trombi {
|
||||||
|
>p {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
text-align: justify;
|
||||||
|
gap: 5px;
|
||||||
|
margin: 0;
|
||||||
|
|
||||||
|
>input,
|
||||||
|
>select {
|
||||||
|
min-width: 300px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&-submit-btn {
|
||||||
|
margin-top: 10px !important;
|
||||||
|
max-width: 100px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.justify {
|
.justify {
|
||||||
|
|||||||
@@ -35,8 +35,8 @@
|
|||||||
<noscript><link rel="stylesheet" href="{{ static('bundled/fontawesome-index.css') }}"></noscript>
|
<noscript><link rel="stylesheet" href="{{ static('bundled/fontawesome-index.css') }}"></noscript>
|
||||||
|
|
||||||
<script src="{{ url('javascript-catalog') }}"></script>
|
<script src="{{ url('javascript-catalog') }}"></script>
|
||||||
<script type="module" src="{{ static("bundled/core/navbar-index.ts") }}"></script>
|
<script type="module" src={{ static("bundled/core/navbar-index.ts") }}></script>
|
||||||
<script type="module" src="{{ static("bundled/core/components/include-index.ts") }}"></script>
|
<script type="module" src={{ static("bundled/core/components/include-index.ts") }}></script>
|
||||||
<script type="module" src="{{ static('bundled/alpine-index.js') }}"></script>
|
<script type="module" src="{{ static('bundled/alpine-index.js') }}"></script>
|
||||||
<script type="module" src="{{ static('bundled/htmx-index.js') }}"></script>
|
<script type="module" src="{{ static('bundled/htmx-index.js') }}"></script>
|
||||||
<script type="module" src="{{ static('bundled/country-flags-index.ts') }}"></script>
|
<script type="module" src="{{ static('bundled/country-flags-index.ts') }}"></script>
|
||||||
|
|||||||
@@ -5,8 +5,9 @@
|
|||||||
<details name="navbar" class="menu">
|
<details name="navbar" class="menu">
|
||||||
<summary class="head">{% trans %}Associations & Clubs{% endtrans %}</summary>
|
<summary class="head">{% trans %}Associations & Clubs{% endtrans %}</summary>
|
||||||
<ul class="content">
|
<ul class="content">
|
||||||
<li><a href="{{ url("core:page", page_name="ae") }}">{% trans %}AE{% endtrans %}</a></li>
|
<li><a href="{{ url('core:page', page_name='ae') }}">{% trans %}AE{% endtrans %}</a></li>
|
||||||
<li><a href="{{ url("club:club_list") }}">{% trans %}AE's clubs{% endtrans %}</a></li>
|
<li><a href="{{ url('core:page', page_name='clubs') }}">{% trans %}AE's clubs{% endtrans %}</a></li>
|
||||||
|
<li><a href="{{ url('core:page', page_name='utbm-associations') }}">{% trans %}Others UTBM's Associations{% endtrans %}</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</details>
|
</details>
|
||||||
<details name="navbar" class="menu">
|
<details name="navbar" class="menu">
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
<div id="quick-notifications"
|
<div id="quick-notifications"
|
||||||
x-data='{
|
x-data="{
|
||||||
messages: [
|
messages: [
|
||||||
{%- for message in messages -%}
|
{% if messages %}
|
||||||
{%- if not message.extra_tags -%}
|
{% for message in messages %}
|
||||||
{ tag: {{ message.tags|string|tojson }}, text: {{ message|string|tojson }} },
|
{
|
||||||
{%- endif -%}
|
tag: '{{ message.tags }}',
|
||||||
{%- endfor -%}
|
text: '{{ message }}',
|
||||||
|
},
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
]
|
]
|
||||||
}'
|
}"
|
||||||
@quick-notification-add="(e) => messages.push(e?.detail)"
|
@quick-notification-add="(e) => messages.push(e?.detail)"
|
||||||
@quick-notification-delete="messages = []">
|
@quick-notification-delete="messages = []">
|
||||||
<template x-for="(message, index) in messages">
|
<template x-for="(message, index) in messages">
|
||||||
|
|||||||
@@ -33,8 +33,7 @@
|
|||||||
<a href="{{ url("core:file_detail", file_id=f.id) }}">{{ f.name }}</a><br/>
|
<a href="{{ url("core:file_detail", file_id=f.id) }}">{{ f.name }}</a><br/>
|
||||||
{% trans %}Full name: {% endtrans %}{{ f.get_parent_path()+'/'+f.name }}<br/>
|
{% trans %}Full name: {% endtrans %}{{ f.get_parent_path()+'/'+f.name }}<br/>
|
||||||
{% trans %}Owner: {% endtrans %}{{ f.owner.get_display_name() }}<br/>
|
{% trans %}Owner: {% endtrans %}{{ f.owner.get_display_name() }}<br/>
|
||||||
{% trans %}Date: {% endtrans %}
|
{% trans %}Date: {% endtrans %}{{ f.date|date(DATE_FORMAT) }} {{ f.date|time(TIME_FORMAT) }}<br/>
|
||||||
{{ f.date|date(DATE_FORMAT) }} {{ f.date|time(TIME_FORMAT) }}<br/>
|
|
||||||
</p>
|
</p>
|
||||||
<p><button
|
<p><button
|
||||||
hx-get="{{ url('core:file_moderate', file_id=f.id) }}"
|
hx-get="{{ url('core:file_moderate', file_id=f.id) }}"
|
||||||
@@ -49,6 +48,6 @@
|
|||||||
>{% trans %}Delete{% endtrans %}</button></p>
|
>{% trans %}Delete{% endtrans %}</button></p>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{{ paginate_htmx(request, page_obj, paginator) }}
|
{{ paginate_htmx(page_obj, paginator) }}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
<form
|
|
||||||
hx-post="{{ url("core:user_visibility_fragment", user_id=form.instance.id) }}"
|
|
||||||
hx-disabled-elt="find input[type='submit']"
|
|
||||||
hx-swap="outerHTML" x-data="{ isViewable: {{ form.is_viewable.value()|tojson }} }"
|
|
||||||
>
|
|
||||||
{% for message in messages %}
|
|
||||||
{% if message.extra_tags=="visibility" %}
|
|
||||||
<div class="alert alert-success">
|
|
||||||
{{ message }}
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
{% endfor %}
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.non_field_errors() }}
|
|
||||||
<fieldset class="form-group">
|
|
||||||
{{ form.is_viewable|add_attr("x-model=isViewable") }}
|
|
||||||
{{ form.is_viewable.label_tag() }}
|
|
||||||
<span class="helptext">{{ form.is_viewable.help_text }}</span>
|
|
||||||
{{ form.is_viewable.errors }}
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="form-group" x-show="!isViewable" x-transition x-cloak>
|
|
||||||
{{ form.whitelisted_users.as_field_group() }}
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="form-group">
|
|
||||||
{{ form.show_my_stats }}
|
|
||||||
{{ form.show_my_stats.label_tag() }}
|
|
||||||
<span class="helptext">
|
|
||||||
{{ form.show_my_stats.help_text }}
|
|
||||||
</span>
|
|
||||||
{{ form.show_my_stats.errors }}
|
|
||||||
</fieldset>
|
|
||||||
<input type="submit" class="btn btn-blue" value="{% trans %}Save{% endtrans %}">
|
|
||||||
</form>
|
|
||||||
@@ -118,21 +118,20 @@
|
|||||||
</nav>
|
</nav>
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
{% macro paginate_jinja(request, current_page, paginator) %}
|
{% macro paginate_jinja(current_page, paginator) %}
|
||||||
{# Add pagination buttons for pages without Alpine.
|
{# Add pagination buttons for pages without Alpine.
|
||||||
|
|
||||||
This must be coupled with a view that handles pagination
|
This must be coupled with a view that handles pagination
|
||||||
with the Django Paginator object.
|
with the Django Paginator object.
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
request (django.http.request.HttpRequest): the current django request
|
|
||||||
current_page (django.core.paginator.Page): the current page object
|
current_page (django.core.paginator.Page): the current page object
|
||||||
paginator (django.core.paginator.Paginator): the paginator object
|
paginator (django.core.paginator.Paginator): the paginator object
|
||||||
#}
|
#}
|
||||||
{{ paginate_server_side(request, current_page, paginator, "") }}
|
{{ paginate_server_side(current_page, paginator, False) }}
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
{% macro paginate_htmx(request, current_page, paginator, htmx_target="#content") %}
|
{% macro paginate_htmx(current_page, paginator) %}
|
||||||
{# Add pagination buttons for pages without Alpine but supporting fragments.
|
{# Add pagination buttons for pages without Alpine but supporting fragments.
|
||||||
|
|
||||||
This must be coupled with a view that handles pagination
|
This must be coupled with a view that handles pagination
|
||||||
@@ -141,26 +140,24 @@
|
|||||||
The replaced fragment will be #content so make sure you are calling this macro inside your content block.
|
The replaced fragment will be #content so make sure you are calling this macro inside your content block.
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
request (django.http.request.HttpRequest): the current django request
|
|
||||||
current_page (django.core.paginator.Page): the current page object
|
current_page (django.core.paginator.Page): the current page object
|
||||||
paginator (django.core.paginator.Paginator): the paginator object
|
paginator (django.core.paginator.Paginator): the paginator object
|
||||||
htmx_target (string): htmx target selector (default '#content')
|
|
||||||
#}
|
#}
|
||||||
{{ paginate_server_side(request, current_page, paginator, htmx_target) }}
|
{{ paginate_server_side(current_page, paginator, True) }}
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
{% macro paginate_server_side(request, current_page, paginator, htmx_target) %}
|
{% macro paginate_server_side(current_page, paginator, use_htmx) %}
|
||||||
<nav class="pagination">
|
<nav class="pagination">
|
||||||
{% if current_page.has_previous() %}
|
{% if current_page.has_previous() %}
|
||||||
<a
|
<a
|
||||||
{% if htmx_target -%}
|
{% if use_htmx -%}
|
||||||
hx-get="?{{ querystring(request, page=current_page.previous_page_number()) }}"
|
hx-get="?{{ querystring(page=current_page.previous_page_number()) }}"
|
||||||
hx-swap="innerHTML"
|
hx-swap="innerHTML"
|
||||||
hx-target="{{ htmx_target }}"
|
hx-target="#content"
|
||||||
hx-push-url="true"
|
hx-push-url="true"
|
||||||
hx-trigger="click, keyup[key=='ArrowLeft'] from:body"
|
hx-trigger="click, keyup[key=='ArrowLeft'] from:body"
|
||||||
{%- else -%}
|
{%- else -%}
|
||||||
href="?{{ querystring(request, page=current_page.previous_page_number()) }}"
|
href="?{{ querystring(page=current_page.previous_page_number()) }}"
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
>
|
>
|
||||||
<button>
|
<button>
|
||||||
@@ -177,13 +174,13 @@
|
|||||||
<strong>{{ paginator.ELLIPSIS }}</strong>
|
<strong>{{ paginator.ELLIPSIS }}</strong>
|
||||||
{% else %}
|
{% else %}
|
||||||
<a
|
<a
|
||||||
{% if htmx_target -%}
|
{% if use_htmx -%}
|
||||||
hx-get="?{{ querystring(request, page=i) }}"
|
hx-get="?{{ querystring(page=i) }}"
|
||||||
hx-swap="innerHTML"
|
hx-swap="innerHTML"
|
||||||
hx-target="{{ htmx_target }}"
|
hx-target="#content"
|
||||||
hx-push-url="true"
|
hx-push-url="true"
|
||||||
{%- else -%}
|
{%- else -%}
|
||||||
href="?{{ querystring(request, page=i) }}"
|
href="?{{ querystring(page=i) }}"
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
>
|
>
|
||||||
<button>{{ i }}</button>
|
<button>{{ i }}</button>
|
||||||
@@ -192,14 +189,14 @@
|
|||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if current_page.has_next() %}
|
{% if current_page.has_next() %}
|
||||||
<a
|
<a
|
||||||
{% if htmx_target -%}
|
{% if use_htmx -%}
|
||||||
hx-get="?{{querystring(request, page=current_page.next_page_number())}}"
|
hx-get="?{{querystring(page=current_page.next_page_number())}}"
|
||||||
hx-swap="innerHTML"
|
hx-swap="innerHTML"
|
||||||
hx-target="{{ htmx_target }}"
|
hx-target="#content"
|
||||||
hx-push-url="true"
|
hx-push-url="true"
|
||||||
hx-trigger="click, keyup[key=='ArrowRight'] from:body"
|
hx-trigger="click, keyup[key=='ArrowRight'] from:body"
|
||||||
{%- else -%}
|
{%- else -%}
|
||||||
href="?{{querystring(request, page=current_page.next_page_number())}}"
|
href="?{{querystring(page=current_page.next_page_number())}}"
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
><button>
|
><button>
|
||||||
<i class="fa fa-caret-right"></i>
|
<i class="fa fa-caret-right"></i>
|
||||||
@@ -250,8 +247,15 @@
|
|||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
|
|
||||||
{% macro querystring(request) %}
|
{% macro querystring() %}
|
||||||
{%- set qs = request.GET.copy() -%}
|
{%- for key, values in request.GET.lists() -%}
|
||||||
{%- do qs.update(kwargs) -%}
|
{%- if key not in kwargs -%}
|
||||||
{{- qs | urlencode -}}
|
{%- for value in values -%}
|
||||||
|
{{ key }}={{ value }}&
|
||||||
|
{%- endfor -%}
|
||||||
|
{%- endif -%}
|
||||||
|
{%- endfor -%}
|
||||||
|
{%- for key, value in kwargs.items() -%}
|
||||||
|
{{ key }}={{ value }}&
|
||||||
|
{%- endfor -%}
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
@@ -23,10 +23,10 @@
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for m in profile.memberships.ongoing().select_related("role") %}
|
{% for m in profile.memberships.filter(end_date=None).all() %}
|
||||||
<tr>
|
<tr>
|
||||||
<td><a href="{{ url('club:club_members', club_id=m.club.id) }}">{{ m.club }}</a></td>
|
<td><a href="{{ url('club:club_members', club_id=m.club.id) }}">{{ m.club }}</a></td>
|
||||||
<td>{{ m.role.name }}</td>
|
<td>{{ settings.SITH_CLUB_ROLES[m.role] }}</td>
|
||||||
<td>{{ m.description }}</td>
|
<td>{{ m.description }}</td>
|
||||||
<td>{{ m.start_date }}</td>
|
<td>{{ m.start_date }}</td>
|
||||||
{% if m.can_be_edited_by(user) %}
|
{% if m.can_be_edited_by(user) %}
|
||||||
@@ -65,10 +65,10 @@
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for m in profile.memberships.exclude(end_date=None).select_related("role") %}
|
{% for m in profile.memberships.exclude(end_date=None).all() %}
|
||||||
<tr>
|
<tr>
|
||||||
<td><a href="{{ url('club:club_members', club_id=m.club.id) }}">{{ m.club }}</a></td>
|
<td><a href="{{ url('club:club_members', club_id=m.club.id) }}">{{ m.club }}</a></td>
|
||||||
<td>{{ m.role.name }}</td>
|
<td>{{ settings.SITH_CLUB_ROLES[m.role] }}</td>
|
||||||
<td>{{ m.description }}</td>
|
<td>{{ m.description }}</td>
|
||||||
<td>{{ m.start_date }}</td>
|
<td>{{ m.start_date }}</td>
|
||||||
<td>{{ m.end_date }}</td>
|
<td>{{ m.end_date }}</td>
|
||||||
|
|||||||
@@ -147,7 +147,18 @@
|
|||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{# Checkboxes #}
|
||||||
|
<div class="profile-visible">
|
||||||
|
<div class="row">
|
||||||
|
{{ form.is_viewable }}
|
||||||
|
{{ form.is_viewable.label_tag() }}
|
||||||
|
</div>
|
||||||
|
<span class="helptext">
|
||||||
|
{{ form.is_viewable.help_text }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<div class="final-actions">
|
<div class="final-actions">
|
||||||
|
|
||||||
{%- if form.instance == user -%}
|
{%- if form.instance == user -%}
|
||||||
<p>
|
<p>
|
||||||
<a href="{{ url('core:password_change') }}">{%- trans -%}Change my password{%- endtrans -%}</a>
|
<a href="{{ url('core:password_change') }}">{%- trans -%}Change my password{%- endtrans -%}</a>
|
||||||
@@ -159,6 +170,7 @@
|
|||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
<input type="submit" value="{%- trans -%}Update{%- endtrans -%}" />
|
<input type="submit" value="{%- trans -%}Update{%- endtrans -%}" />
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -11,22 +11,30 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="main">
|
<div class="main">
|
||||||
<h2>{% trans %}Preferences{% endtrans %}</h2>
|
<h2>{% trans %}Preferences{% endtrans %}</h2>
|
||||||
<br />
|
<h3>{% trans %}General{% endtrans %}</h3>
|
||||||
<h3>{% trans %}Notifications{% endtrans %}</h3>
|
<form class="form form-general" action="" method="post" enctype="multipart/form-data">
|
||||||
<form action="" method="post" enctype="multipart/form-data">
|
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div class="form form-general">
|
{{ form.as_p() }}
|
||||||
{{ form.as_p() }}
|
<input class="form-submit-btn" type="submit" value="{% trans %}Save{% endtrans %}" />
|
||||||
</div>
|
|
||||||
<input class="btn btn-blue" type="submit" value="{% trans %}Save{% endtrans %}" />
|
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<br />
|
<h3>{% trans %}Trombi{% endtrans %}</h3>
|
||||||
<h3>{% trans %}Visibility{% endtrans %}</h3>
|
|
||||||
|
{% if trombi_form %}
|
||||||
|
<form class="form form-trombi" action="{{ url('trombi:user_tools') }}" method="post" enctype="multipart/form-data">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ trombi_form.as_p() }}
|
||||||
|
<input class="form-submit-btn" type="submit" value="{% trans %}Save{% endtrans %}" />
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% else %}
|
||||||
|
<p>{% trans trombi=profile.trombi_user.trombi %}You already choose to be in that Trombi: {{ trombi }}.{% endtrans %}
|
||||||
|
<br />
|
||||||
|
<a href="{{ url('trombi:user_tools') }}">{% trans %}Go to my Trombi tools{% endtrans %}</a>
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{{ user_visibility_fragment }}
|
|
||||||
|
|
||||||
<br />
|
|
||||||
{% if student_card_fragment %}
|
{% if student_card_fragment %}
|
||||||
<h3>{% trans %}Student card{% endtrans %}</h3>
|
<h3>{% trans %}Student card{% endtrans %}</h3>
|
||||||
{{ student_card_fragment }}
|
{{ student_card_fragment }}
|
||||||
@@ -35,21 +43,5 @@
|
|||||||
add a student card yourself, you'll need a NFC reader. We store the UID of the card which is 14 characters long.{% endtrans %}
|
add a student card yourself, you'll need a NFC reader. We store the UID of the card which is 14 characters long.{% endtrans %}
|
||||||
</p>
|
</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<br />
|
|
||||||
<h3>{% trans %}Trombi{% endtrans %}</h3>
|
|
||||||
|
|
||||||
{% if trombi_form %}
|
|
||||||
<form action="{{ url('trombi:user_tools') }}" method="post" enctype="multipart/form-data">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ trombi_form.as_p() }}
|
|
||||||
<input class="btn btn-blue" type="submit" value="{% trans %}Save{% endtrans %}" />
|
|
||||||
</form>
|
|
||||||
{% else %}
|
|
||||||
<p>{% trans trombi=profile.trombi_user.trombi %}You already choose to be in that Trombi: {{ trombi }}.{% endtrans %}
|
|
||||||
<br />
|
|
||||||
<a href="{{ url('trombi:user_tools') }}">{% trans %}Go to my Trombi tools{% endtrans %}</a>
|
|
||||||
</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
<script-once type="module" src="{{ js }}"></script-once>
|
<script-once type="module" src="{{ js }}"></script-once>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% for css in statics.css %}
|
{% for css in statics.css %}
|
||||||
<link-once rel="stylesheet" type="text/css" href="{{ css }}"></link-once>
|
<link-once rel="stylesheet" type="text/css" href="{{ css }}" defer></link-once>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|
||||||
<{{ component }} name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %}>
|
<{{ component }} name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %}>
|
||||||
|
|||||||
@@ -418,16 +418,16 @@ class TestUserIsInGroup(TestCase):
|
|||||||
group_in = baker.make(Group)
|
group_in = baker.make(Group)
|
||||||
self.public_user.groups.add(group_in)
|
self.public_user.groups.add(group_in)
|
||||||
|
|
||||||
# clear the cached property `User.all_groups`
|
# clear the cached property `User.cached_groups`
|
||||||
self.public_user.__dict__.pop("all_groups", None)
|
self.public_user.__dict__.pop("cached_groups", None)
|
||||||
# Test when the user is in the group
|
# Test when the user is in the group
|
||||||
with self.assertNumQueries(2):
|
with self.assertNumQueries(1):
|
||||||
self.public_user.is_in_group(pk=group_in.id)
|
self.public_user.is_in_group(pk=group_in.id)
|
||||||
with self.assertNumQueries(0):
|
with self.assertNumQueries(0):
|
||||||
self.public_user.is_in_group(pk=group_in.id)
|
self.public_user.is_in_group(pk=group_in.id)
|
||||||
|
|
||||||
group_not_in = baker.make(Group)
|
group_not_in = baker.make(Group)
|
||||||
self.public_user.__dict__.pop("all_groups", None)
|
self.public_user.__dict__.pop("cached_groups", None)
|
||||||
# Test when the user is not in the group
|
# Test when the user is not in the group
|
||||||
with self.assertNumQueries(1):
|
with self.assertNumQueries(1):
|
||||||
self.public_user.is_in_group(pk=group_not_in.id)
|
self.public_user.is_in_group(pk=group_not_in.id)
|
||||||
|
|||||||
+41
-22
@@ -5,6 +5,7 @@ from typing import Callable
|
|||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from django.conf import settings
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
|
from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
|
||||||
from django.test import Client, TestCase
|
from django.test import Client, TestCase
|
||||||
@@ -17,8 +18,8 @@ from pytest_django.asserts import assertNumQueries
|
|||||||
from core.baker_recipes import board_user, old_subscriber_user, subscriber_user
|
from core.baker_recipes import board_user, old_subscriber_user, subscriber_user
|
||||||
from core.models import Group, QuickUploadImage, SithFile, User
|
from core.models import Group, QuickUploadImage, SithFile, User
|
||||||
from core.utils import RED_PIXEL_PNG
|
from core.utils import RED_PIXEL_PNG
|
||||||
|
from sas.baker_recipes import picture_recipe
|
||||||
from sas.models import Picture
|
from sas.models import Picture
|
||||||
from sith import settings
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -30,24 +31,19 @@ class TestImageAccess:
|
|||||||
lambda: baker.make(
|
lambda: baker.make(
|
||||||
User, groups=[Group.objects.get(pk=settings.SITH_GROUP_SAS_ADMIN_ID)]
|
User, groups=[Group.objects.get(pk=settings.SITH_GROUP_SAS_ADMIN_ID)]
|
||||||
),
|
),
|
||||||
lambda: baker.make(
|
|
||||||
User, groups=[Group.objects.get(pk=settings.SITH_GROUP_COM_ADMIN_ID)]
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_sas_image_access(self, user_factory: Callable[[], User]):
|
def test_sas_image_access(self, user_factory: Callable[[], User]):
|
||||||
"""Test that only authorized users can access the sas image."""
|
"""Test that only authorized users can access the sas image."""
|
||||||
user = user_factory()
|
user = user_factory()
|
||||||
picture: SithFile = baker.make(
|
picture = picture_recipe.make()
|
||||||
Picture, parent=SithFile.objects.get(pk=settings.SITH_SAS_ROOT_DIR_ID)
|
assert user.can_edit(picture)
|
||||||
)
|
|
||||||
assert picture.is_owned_by(user)
|
|
||||||
|
|
||||||
def test_sas_image_access_owner(self):
|
def test_sas_image_access_owner(self):
|
||||||
"""Test that the owner of the image can access it."""
|
"""Test that the owner of the image can access it."""
|
||||||
user = baker.make(User)
|
user = baker.make(User)
|
||||||
picture: Picture = baker.make(Picture, owner=user)
|
picture = picture_recipe.make(owner=user)
|
||||||
assert picture.is_owned_by(user)
|
assert user.can_edit(picture)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"user_factory",
|
"user_factory",
|
||||||
@@ -63,7 +59,41 @@ class TestImageAccess:
|
|||||||
user = user_factory()
|
user = user_factory()
|
||||||
owner = baker.make(User)
|
owner = baker.make(User)
|
||||||
picture: Picture = baker.make(Picture, owner=owner)
|
picture: Picture = baker.make(Picture, owner=owner)
|
||||||
assert not picture.is_owned_by(user)
|
assert not user.can_edit(picture)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestUserPicture:
|
||||||
|
def test_anonymous_user_unauthorized(self, client):
|
||||||
|
"""An anonymous user shouldn't have access to an user's photo page."""
|
||||||
|
response = client.get(
|
||||||
|
reverse(
|
||||||
|
"sas:user_pictures",
|
||||||
|
kwargs={"user_id": User.objects.get(username="sli").pk},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("username", "status"),
|
||||||
|
[
|
||||||
|
("guy", 403),
|
||||||
|
("root", 200),
|
||||||
|
("skia", 200),
|
||||||
|
("sli", 200),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_page_is_working(self, client, username, status):
|
||||||
|
"""Only user that subscribed (or admins) should be able to see the page."""
|
||||||
|
# Test for simple user
|
||||||
|
client.force_login(User.objects.get(username=username))
|
||||||
|
response = client.get(
|
||||||
|
reverse(
|
||||||
|
"sas:user_pictures",
|
||||||
|
kwargs={"user_id": User.objects.get(username="sli").pk},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert response.status_code == status
|
||||||
|
|
||||||
|
|
||||||
# TODO: many tests on the pages:
|
# TODO: many tests on the pages:
|
||||||
@@ -344,14 +374,3 @@ def test_quick_upload_image(
|
|||||||
assert (
|
assert (
|
||||||
parsed["name"] == Path(file.name).stem[: QuickUploadImage.IMAGE_NAME_SIZE - 1]
|
parsed["name"] == Path(file.name).stem[: QuickUploadImage.IMAGE_NAME_SIZE - 1]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_populated_sas_is_in_sas():
|
|
||||||
"""Test that, in the data generated by the populate command,
|
|
||||||
the SAS has value is_in_sas=True.
|
|
||||||
|
|
||||||
If it's not the case, it has no incidence in prod, but it's annoying
|
|
||||||
in dev and may cause misunderstandings.
|
|
||||||
"""
|
|
||||||
assert SithFile.objects.get(id=settings.SITH_SAS_ROOT_DIR_ID).is_in_sas
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from django.utils.timezone import now
|
|||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
||||||
|
|
||||||
from club.models import Club, Membership
|
from club.models import Club
|
||||||
from core.baker_recipes import board_user, subscriber_user
|
from core.baker_recipes import board_user, subscriber_user
|
||||||
from core.markdown import markdown
|
from core.markdown import markdown
|
||||||
from core.models import AnonymousUser, Page, PageRev, User
|
from core.models import AnonymousUser, Page, PageRev, User
|
||||||
@@ -122,9 +122,6 @@ def test_page_revision_club_redirection(client: Client):
|
|||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_viewable_by():
|
def test_viewable_by():
|
||||||
# remove existing pages to prevent side effect
|
# remove existing pages to prevent side effect
|
||||||
# club pages are protected, so we must delete clubs first
|
|
||||||
Membership.objects.all().delete()
|
|
||||||
Club.objects.all().delete()
|
|
||||||
Page.objects.all().delete()
|
Page.objects.all().delete()
|
||||||
view_groups = [
|
view_groups = [
|
||||||
[settings.SITH_GROUP_PUBLIC_ID],
|
[settings.SITH_GROUP_PUBLIC_ID],
|
||||||
|
|||||||
+12
-24
@@ -21,12 +21,13 @@ from core.baker_recipes import (
|
|||||||
subscriber_user,
|
subscriber_user,
|
||||||
very_old_subscriber_user,
|
very_old_subscriber_user,
|
||||||
)
|
)
|
||||||
from core.models import AnonymousUser, Group, SithFile, User
|
from core.models import AnonymousUser, Group, User
|
||||||
from core.views import UserTabsMixin
|
from core.views import UserTabsMixin
|
||||||
from counter.baker_recipes import sale_recipe
|
from counter.baker_recipes import sale_recipe
|
||||||
from counter.models import Counter, Customer, Permanency, Refilling, Selling
|
from counter.models import Counter, Customer, Permanency, Refilling, Selling
|
||||||
from counter.utils import is_logged_in_counter
|
from counter.utils import is_logged_in_counter
|
||||||
from eboutic.models import Invoice, InvoiceItem
|
from eboutic.models import Invoice, InvoiceItem
|
||||||
|
from sas.models import Picture
|
||||||
|
|
||||||
|
|
||||||
class TestSearchUsers(TestCase):
|
class TestSearchUsers(TestCase):
|
||||||
@@ -34,7 +35,7 @@ class TestSearchUsers(TestCase):
|
|||||||
def setUpTestData(cls):
|
def setUpTestData(cls):
|
||||||
# News.author has on_delete=PROTECT, so news must be deleted beforehand
|
# News.author has on_delete=PROTECT, so news must be deleted beforehand
|
||||||
News.objects.all().delete()
|
News.objects.all().delete()
|
||||||
SithFile.objects.all().delete()
|
Picture.objects.all().delete() # same for pictures
|
||||||
User.objects.all().delete()
|
User.objects.all().delete()
|
||||||
user_recipe = Recipe(
|
user_recipe = Recipe(
|
||||||
User,
|
User,
|
||||||
@@ -214,9 +215,9 @@ def test_user_invoice_with_multiple_items():
|
|||||||
"""Test that annotate_total() works when invoices contain multiple items."""
|
"""Test that annotate_total() works when invoices contain multiple items."""
|
||||||
user: User = subscriber_user.make()
|
user: User = subscriber_user.make()
|
||||||
item_recipe = Recipe(InvoiceItem, invoice=foreign_key(Recipe(Invoice, user=user)))
|
item_recipe = Recipe(InvoiceItem, invoice=foreign_key(Recipe(Invoice, user=user)))
|
||||||
item_recipe.make(_quantity=3, quantity=1, unit_price=5)
|
item_recipe.make(_quantity=3, quantity=1, product_unit_price=5)
|
||||||
item_recipe.make(_quantity=1, quantity=1, unit_price=5)
|
item_recipe.make(_quantity=1, quantity=1, product_unit_price=5)
|
||||||
item_recipe.make(_quantity=2, quantity=1, unit_price=iter([5, 8]))
|
item_recipe.make(_quantity=2, quantity=1, product_unit_price=iter([5, 8]))
|
||||||
res = list(
|
res = list(
|
||||||
Invoice.objects.filter(user=user)
|
Invoice.objects.filter(user=user)
|
||||||
.annotate_total()
|
.annotate_total()
|
||||||
@@ -400,37 +401,24 @@ class TestUserQuerySetViewableBy:
|
|||||||
return [
|
return [
|
||||||
baker.make(User),
|
baker.make(User),
|
||||||
subscriber_user.make(),
|
subscriber_user.make(),
|
||||||
*subscriber_user.make(is_viewable=False, _quantity=2),
|
subscriber_user.make(is_viewable=False),
|
||||||
]
|
]
|
||||||
|
|
||||||
def test_admin_user(self, users: list[User]):
|
def test_admin_user(self, users: list[User]):
|
||||||
user = baker.make(
|
user = baker.make(
|
||||||
User, user_permissions=[Permission.objects.get(codename="view_hidden_user")]
|
User,
|
||||||
|
user_permissions=[Permission.objects.get(codename="view_hidden_user")],
|
||||||
)
|
)
|
||||||
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
||||||
assert set(viewable) == set(users)
|
assert set(viewable) == set(users)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"user_factory",
|
"user_factory", [old_subscriber_user.make, subscriber_user.make]
|
||||||
[
|
|
||||||
old_subscriber_user.make,
|
|
||||||
lambda: old_subscriber_user.make(is_viewable=False),
|
|
||||||
subscriber_user.make,
|
|
||||||
lambda: subscriber_user.make(is_viewable=False),
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
def test_can_search(self, users: list[User], user_factory):
|
def test_subscriber(self, users: list[User], user_factory):
|
||||||
user = user_factory()
|
user = user_factory()
|
||||||
viewable = User.objects.filter(
|
|
||||||
id__in=[u.id for u in [*users, user]]
|
|
||||||
).viewable_by(user)
|
|
||||||
assert set(viewable) == {user, users[0], users[1]}
|
|
||||||
|
|
||||||
def test_whitelist(self, users: list[User]):
|
|
||||||
user = subscriber_user.make()
|
|
||||||
users[3].whitelisted_users.add(user)
|
|
||||||
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
||||||
assert set(viewable) == {users[0], users[1], users[3]}
|
assert set(viewable) == {users[0], users[1]}
|
||||||
|
|
||||||
@pytest.mark.parametrize("user_factory", [lambda: baker.make(User), AnonymousUser])
|
@pytest.mark.parametrize("user_factory", [lambda: baker.make(User), AnonymousUser])
|
||||||
def test_not_subscriber(self, users: list[User], user_factory):
|
def test_not_subscriber(self, users: list[User], user_factory):
|
||||||
|
|||||||
+2
-6
@@ -69,6 +69,7 @@ from core.views import (
|
|||||||
UserCreationView,
|
UserCreationView,
|
||||||
UserGodfathersTreeView,
|
UserGodfathersTreeView,
|
||||||
UserGodfathersView,
|
UserGodfathersView,
|
||||||
|
UserListView,
|
||||||
UserMeRedirect,
|
UserMeRedirect,
|
||||||
UserMiniView,
|
UserMiniView,
|
||||||
UserPreferencesView,
|
UserPreferencesView,
|
||||||
@@ -77,7 +78,6 @@ from core.views import (
|
|||||||
UserUpdateGroupView,
|
UserUpdateGroupView,
|
||||||
UserUpdateProfileView,
|
UserUpdateProfileView,
|
||||||
UserView,
|
UserView,
|
||||||
UserVisibilityFormFragment,
|
|
||||||
delete_user_godfather,
|
delete_user_godfather,
|
||||||
logout,
|
logout,
|
||||||
notification,
|
notification,
|
||||||
@@ -136,11 +136,7 @@ urlpatterns = [
|
|||||||
"group/<int:group_id>/detail/", GroupTemplateView.as_view(), name="group_detail"
|
"group/<int:group_id>/detail/", GroupTemplateView.as_view(), name="group_detail"
|
||||||
),
|
),
|
||||||
# User views
|
# User views
|
||||||
path(
|
path("user/", UserListView.as_view(), name="user_list"),
|
||||||
"fragment/user/<int:user_id>/",
|
|
||||||
UserVisibilityFormFragment.as_view(),
|
|
||||||
name="user_visibility_fragment",
|
|
||||||
),
|
|
||||||
path(
|
path(
|
||||||
"user/me/<path:remaining_path>/",
|
"user/me/<path:remaining_path>/",
|
||||||
UserMeRedirect.as_view(),
|
UserMeRedirect.as_view(),
|
||||||
|
|||||||
+93
-3
@@ -12,19 +12,25 @@
|
|||||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
|
from dataclasses import dataclass
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
|
|
||||||
# Image utils
|
# Image utils
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from typing import Final
|
from typing import Any, Final, Unpack
|
||||||
|
|
||||||
import PIL
|
import PIL
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.files.base import ContentFile
|
from django.core.files.base import ContentFile
|
||||||
from django.core.files.uploadedfile import UploadedFile
|
from django.core.files.uploadedfile import UploadedFile
|
||||||
from django.http import HttpRequest
|
from django.db import models
|
||||||
|
from django.forms import BaseForm
|
||||||
|
from django.http import Http404, HttpRequest
|
||||||
|
from django.shortcuts import get_list_or_404
|
||||||
|
from django.template.loader import render_to_string
|
||||||
|
from django.utils.safestring import SafeString
|
||||||
from django.utils.timezone import localdate
|
from django.utils.timezone import localdate
|
||||||
|
from PIL import ExifTags
|
||||||
from PIL.Image import Image, Resampling
|
from PIL.Image import Image, Resampling
|
||||||
|
|
||||||
RED_PIXEL_PNG: Final[bytes] = (
|
RED_PIXEL_PNG: Final[bytes] = (
|
||||||
@@ -41,6 +47,21 @@ to generate a dummy image that is considered valid nonetheless
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FormFragmentTemplateData[T: BaseForm]:
|
||||||
|
"""Dataclass used to pre-render form fragments"""
|
||||||
|
|
||||||
|
form: T
|
||||||
|
template: str
|
||||||
|
context: dict[str, Any]
|
||||||
|
|
||||||
|
def render(self, request: HttpRequest) -> SafeString:
|
||||||
|
# Request is needed for csrf_tokens
|
||||||
|
return render_to_string(
|
||||||
|
self.template, context={"form": self.form, **self.context}, request=request
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_start_of_semester(today: date | None = None) -> date:
|
def get_start_of_semester(today: date | None = None) -> date:
|
||||||
"""Return the date of the start of the semester of the given 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.
|
If no date is given, return the start date of the current semester.
|
||||||
@@ -177,6 +198,22 @@ def resize_image_explicit(
|
|||||||
return ContentFile(content.getvalue())
|
return ContentFile(content.getvalue())
|
||||||
|
|
||||||
|
|
||||||
|
def exif_auto_rotate(image):
|
||||||
|
for orientation in ExifTags.TAGS:
|
||||||
|
if ExifTags.TAGS[orientation] == "Orientation":
|
||||||
|
break
|
||||||
|
exif = dict(image._getexif().items())
|
||||||
|
|
||||||
|
if exif[orientation] == 3:
|
||||||
|
image = image.rotate(180, expand=True)
|
||||||
|
elif exif[orientation] == 6:
|
||||||
|
image = image.rotate(270, expand=True)
|
||||||
|
elif exif[orientation] == 8:
|
||||||
|
image = image.rotate(90, expand=True)
|
||||||
|
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
def get_client_ip(request: HttpRequest) -> str | None:
|
def get_client_ip(request: HttpRequest) -> str | None:
|
||||||
headers = (
|
headers = (
|
||||||
"X_FORWARDED_FOR", # Common header for proxies
|
"X_FORWARDED_FOR", # Common header for proxies
|
||||||
@@ -188,3 +225,56 @@ def get_client_ip(request: HttpRequest) -> str | None:
|
|||||||
return ip
|
return ip
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
Filterable = type[models.Model] | models.QuerySet | models.Manager
|
||||||
|
ListFilter = dict[str, list | tuple | set]
|
||||||
|
|
||||||
|
|
||||||
|
def get_list_exact_or_404(klass: Filterable, **kwargs: Unpack[ListFilter]) -> list:
|
||||||
|
"""Use filter() to return a list of objects from a list of unique keys (like ids)
|
||||||
|
or raises Http404 if the list has not the same length as the given one.
|
||||||
|
|
||||||
|
Work like `get_object_or_404()` but for lists of objects, with some caveats :
|
||||||
|
|
||||||
|
- The filter must be a list, a tuple or a set.
|
||||||
|
- There can't be more than exactly one filter.
|
||||||
|
- There must be no duplicate in the filter.
|
||||||
|
- The filter should consist in unique keys (like ids), or it could fail randomly.
|
||||||
|
|
||||||
|
klass may be a Model, Manager, or QuerySet object. All other passed
|
||||||
|
arguments and keyword arguments are used in the filter() query.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
Http404: If the list is empty or doesn't have as many elements as the keys list.
|
||||||
|
ValueError: If the first argument is not a Model, Manager, or QuerySet object.
|
||||||
|
ValueError: If more than one filter is passed.
|
||||||
|
TypeError: If the given filter is not a list, a tuple or a set.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
Get all the products with ids 1, 2, 3: ::
|
||||||
|
|
||||||
|
products = get_list_exact_or_404(Product, id__in=[1, 2, 3])
|
||||||
|
|
||||||
|
Don't work with duplicate ids: ::
|
||||||
|
|
||||||
|
products = get_list_exact_or_404(Product, id__in=[1, 2, 3, 3])
|
||||||
|
# Raises Http404: "The list of keys must contain no duplicates."
|
||||||
|
"""
|
||||||
|
if len(kwargs) > 1:
|
||||||
|
raise ValueError("get_list_exact_or_404() only accepts one filter.")
|
||||||
|
key, list_filter = next(iter(kwargs.items()))
|
||||||
|
if not isinstance(list_filter, (list, tuple, set)):
|
||||||
|
raise TypeError(
|
||||||
|
f"The given filter must be a list, a tuple or a set, not {type(list_filter)}"
|
||||||
|
)
|
||||||
|
if len(list_filter) != len(set(list_filter)):
|
||||||
|
raise ValueError("The list of keys must contain no duplicates.")
|
||||||
|
kwargs = {key: list_filter}
|
||||||
|
obj_list = get_list_or_404(klass, **kwargs)
|
||||||
|
if len(obj_list) != len(list_filter):
|
||||||
|
raise Http404(
|
||||||
|
"The given list of keys doesn't match the number of objects found."
|
||||||
|
f"Expected {len(list_filter)} items, got {len(obj_list)}."
|
||||||
|
)
|
||||||
|
return obj_list
|
||||||
|
|||||||
+1
-1
@@ -374,7 +374,7 @@ class FileDeleteView(AllowFragment, CanEditPropMixin, DeleteView):
|
|||||||
class FileModerationView(AllowFragment, ListView):
|
class FileModerationView(AllowFragment, ListView):
|
||||||
model = SithFile
|
model = SithFile
|
||||||
template_name = "core/file_moderation.jinja"
|
template_name = "core/file_moderation.jinja"
|
||||||
queryset = SithFile.objects.filter(is_moderated=False, is_in_sas=False)
|
queryset = SithFile.objects.filter(is_moderated=False)
|
||||||
ordering = "id"
|
ordering = "id"
|
||||||
paginate_by = 100
|
paginate_by = 100
|
||||||
|
|
||||||
|
|||||||
+2
-34
@@ -48,13 +48,12 @@ from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
|||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
from antispam.forms import AntiSpamEmailField
|
from antispam.forms import AntiSpamEmailField
|
||||||
from core.models import Gift, Group, Page, PageRev, Preferences, SithFile, User
|
from core.models import Gift, Group, Page, PageRev, SithFile, User
|
||||||
from core.utils import resize_image
|
from core.utils import resize_image
|
||||||
from core.views.widgets.ajax_select import (
|
from core.views.widgets.ajax_select import (
|
||||||
AutoCompleteSelect,
|
AutoCompleteSelect,
|
||||||
AutoCompleteSelectGroup,
|
AutoCompleteSelectGroup,
|
||||||
AutoCompleteSelectMultipleGroup,
|
AutoCompleteSelectMultipleGroup,
|
||||||
AutoCompleteSelectMultipleUser,
|
|
||||||
AutoCompleteSelectUser,
|
AutoCompleteSelectUser,
|
||||||
)
|
)
|
||||||
from core.views.widgets.markdown import MarkdownInput
|
from core.views.widgets.markdown import MarkdownInput
|
||||||
@@ -180,6 +179,7 @@ class UserProfileForm(forms.ModelForm):
|
|||||||
"school",
|
"school",
|
||||||
"promo",
|
"promo",
|
||||||
"forum_signature",
|
"forum_signature",
|
||||||
|
"is_viewable",
|
||||||
]
|
]
|
||||||
widgets = {
|
widgets = {
|
||||||
"date_of_birth": SelectDate,
|
"date_of_birth": SelectDate,
|
||||||
@@ -264,38 +264,6 @@ class UserProfileForm(forms.ModelForm):
|
|||||||
self._post_clean()
|
self._post_clean()
|
||||||
|
|
||||||
|
|
||||||
class UserVisibilityForm(forms.ModelForm):
|
|
||||||
class Meta:
|
|
||||||
model = User
|
|
||||||
fields = ["is_viewable", "whitelisted_users"]
|
|
||||||
widgets = {
|
|
||||||
"is_viewable": forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
"whitelisted_users": AutoCompleteSelectMultipleUser,
|
|
||||||
}
|
|
||||||
|
|
||||||
__preferences_fields = forms.fields_for_model(
|
|
||||||
Preferences,
|
|
||||||
["show_my_stats"],
|
|
||||||
widgets={"show_my_stats": forms.CheckboxInput(attrs={"class": "switch"})},
|
|
||||||
)
|
|
||||||
show_my_stats = __preferences_fields["show_my_stats"]
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self, *args, initial: dict | None = None, instance: User | None = None, **kwargs
|
|
||||||
):
|
|
||||||
if instance:
|
|
||||||
initial = initial or {}
|
|
||||||
initial["show_my_stats"] = instance.preferences.show_my_stats
|
|
||||||
super().__init__(*args, initial=initial, instance=instance, **kwargs)
|
|
||||||
|
|
||||||
def save(self, commit=True) -> User: # noqa: FBT002
|
|
||||||
instance = super().save(commit=commit)
|
|
||||||
if commit:
|
|
||||||
instance.preferences.show_my_stats = self.cleaned_data["show_my_stats"]
|
|
||||||
instance.preferences.save()
|
|
||||||
return instance
|
|
||||||
|
|
||||||
|
|
||||||
class UserGroupsForm(forms.ModelForm):
|
class UserGroupsForm(forms.ModelForm):
|
||||||
error_css_class = "error"
|
error_css_class = "error"
|
||||||
required_css_class = "required"
|
required_css_class = "required"
|
||||||
|
|||||||
+21
-53
@@ -28,12 +28,10 @@ from datetime import timedelta
|
|||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
from smtplib import SMTPException
|
from smtplib import SMTPException
|
||||||
|
|
||||||
from django.contrib import messages
|
|
||||||
from django.contrib.auth import login, views
|
from django.contrib.auth import login, views
|
||||||
from django.contrib.auth.decorators import login_required
|
from django.contrib.auth.decorators import login_required
|
||||||
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
|
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
||||||
from django.contrib.messages.views import SuccessMessageMixin
|
|
||||||
from django.core.exceptions import PermissionDenied
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db.models import DateField, F, QuerySet, Sum
|
from django.db.models import DateField, F, QuerySet, Sum
|
||||||
from django.db.models.functions import Trunc
|
from django.db.models.functions import Trunc
|
||||||
@@ -50,6 +48,7 @@ from django.views.generic import (
|
|||||||
CreateView,
|
CreateView,
|
||||||
DeleteView,
|
DeleteView,
|
||||||
DetailView,
|
DetailView,
|
||||||
|
ListView,
|
||||||
RedirectView,
|
RedirectView,
|
||||||
TemplateView,
|
TemplateView,
|
||||||
)
|
)
|
||||||
@@ -66,9 +65,8 @@ from core.views.forms import (
|
|||||||
UserGodfathersForm,
|
UserGodfathersForm,
|
||||||
UserGroupsForm,
|
UserGroupsForm,
|
||||||
UserProfileForm,
|
UserProfileForm,
|
||||||
UserVisibilityForm,
|
|
||||||
)
|
)
|
||||||
from core.views.mixins import FragmentMixin, TabedViewMixin, UseFragmentsMixin
|
from core.views.mixins import TabedViewMixin, UseFragmentsMixin
|
||||||
from counter.models import Refilling, Selling
|
from counter.models import Refilling, Selling
|
||||||
from eboutic.models import Invoice
|
from eboutic.models import Invoice
|
||||||
from trombi.views import UserTrombiForm
|
from trombi.views import UserTrombiForm
|
||||||
@@ -250,15 +248,14 @@ class UserTabsMixin(TabedViewMixin):
|
|||||||
"name": _("Groups"),
|
"name": _("Groups"),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
can_view_account = (
|
if (
|
||||||
hasattr(user, "customer")
|
hasattr(user, "customer")
|
||||||
and user.customer
|
and user.customer
|
||||||
and (
|
and (
|
||||||
user == self.request.user
|
user == self.request.user
|
||||||
or self.request.user.has_perm("counter.view_customer")
|
or self.request.user.has_perm("counter.view_customer")
|
||||||
)
|
)
|
||||||
)
|
):
|
||||||
if can_view_account or user.preferences.show_my_stats:
|
|
||||||
tab_list.append(
|
tab_list.append(
|
||||||
{
|
{
|
||||||
"url": reverse("core:user_stats", kwargs={"user_id": user.id}),
|
"url": reverse("core:user_stats", kwargs={"user_id": user.id}),
|
||||||
@@ -266,7 +263,6 @@ class UserTabsMixin(TabedViewMixin):
|
|||||||
"name": _("Stats"),
|
"name": _("Stats"),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
if can_view_account:
|
|
||||||
tab_list.append(
|
tab_list.append(
|
||||||
{
|
{
|
||||||
"url": reverse("core:user_account", kwargs={"user_id": user.id}),
|
"url": reverse("core:user_account", kwargs={"user_id": user.id}),
|
||||||
@@ -353,7 +349,7 @@ class UserGodfathersTreeView(UserTabsMixin, CanViewMixin, DetailView):
|
|||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
|
|
||||||
class UserStatsView(UserTabsMixin, UserPassesTestMixin, DetailView):
|
class UserStatsView(UserTabsMixin, CanViewMixin, DetailView):
|
||||||
"""Display a user's stats."""
|
"""Display a user's stats."""
|
||||||
|
|
||||||
model = User
|
model = User
|
||||||
@@ -361,20 +357,15 @@ class UserStatsView(UserTabsMixin, UserPassesTestMixin, DetailView):
|
|||||||
context_object_name = "profile"
|
context_object_name = "profile"
|
||||||
template_name = "core/user_stats.jinja"
|
template_name = "core/user_stats.jinja"
|
||||||
current_tab = "stats"
|
current_tab = "stats"
|
||||||
queryset = User.objects.exclude(customer=None).select_related(
|
queryset = User.objects.exclude(customer=None).select_related("customer")
|
||||||
"customer", "_preferences"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_func(self):
|
def dispatch(self, request, *arg, **kwargs):
|
||||||
profile: User = self.get_object()
|
profile = self.get_object()
|
||||||
return (
|
if not (
|
||||||
profile == self.request.user
|
profile == request.user or request.user.has_perm("counter.view_customer")
|
||||||
or self.request.user.has_perm("counter.view_customer")
|
):
|
||||||
or (
|
raise PermissionDenied
|
||||||
self.request.user.can_view(profile)
|
return super().dispatch(request, *arg, **kwargs)
|
||||||
and profile.preferences.show_my_stats
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
@@ -413,6 +404,13 @@ class UserMiniView(CanViewMixin, DetailView):
|
|||||||
template_name = "core/user_mini.jinja"
|
template_name = "core/user_mini.jinja"
|
||||||
|
|
||||||
|
|
||||||
|
class UserListView(ListView, CanEditPropMixin):
|
||||||
|
"""Displays the user list."""
|
||||||
|
|
||||||
|
model = User
|
||||||
|
template_name = "core/user_list.jinja"
|
||||||
|
|
||||||
|
|
||||||
# FIXME: the edit_once fields aren't displayed to the user (as expected).
|
# FIXME: the edit_once fields aren't displayed to the user (as expected).
|
||||||
# However, if the user re-add them manually in the form, they are saved.
|
# However, if the user re-add them manually in the form, they are saved.
|
||||||
class UserUpdateProfileView(UserTabsMixin, CanEditMixin, UpdateView):
|
class UserUpdateProfileView(UserTabsMixin, CanEditMixin, UpdateView):
|
||||||
@@ -470,30 +468,6 @@ class UserClubView(UserTabsMixin, CanViewMixin, DetailView):
|
|||||||
current_tab = "clubs"
|
current_tab = "clubs"
|
||||||
|
|
||||||
|
|
||||||
class UserVisibilityFormFragment(FragmentMixin, SuccessMessageMixin, UpdateView):
|
|
||||||
model = User
|
|
||||||
form_class = UserVisibilityForm
|
|
||||||
template_name = "core/fragment/user_visibility.jinja"
|
|
||||||
pk_url_kwarg = "user_id"
|
|
||||||
|
|
||||||
def get_form_kwargs(self):
|
|
||||||
return super().get_form_kwargs() | {"label_suffix": ""}
|
|
||||||
|
|
||||||
def form_valid(self, form):
|
|
||||||
response = super().form_valid(form)
|
|
||||||
messages.success(
|
|
||||||
self.request, _("Visibility parameters updated."), extra_tags="visibility"
|
|
||||||
)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def render_fragment(self, request, **kwargs) -> SafeString:
|
|
||||||
self.object = kwargs.get("user")
|
|
||||||
return super().render_fragment(request, **kwargs)
|
|
||||||
|
|
||||||
def get_success_url(self, **kwargs):
|
|
||||||
return self.request.path
|
|
||||||
|
|
||||||
|
|
||||||
class UserPreferencesView(UserTabsMixin, UseFragmentsMixin, CanEditMixin, UpdateView):
|
class UserPreferencesView(UserTabsMixin, UseFragmentsMixin, CanEditMixin, UpdateView):
|
||||||
"""Edit a user's preferences."""
|
"""Edit a user's preferences."""
|
||||||
|
|
||||||
@@ -507,10 +481,7 @@ class UserPreferencesView(UserTabsMixin, UseFragmentsMixin, CanEditMixin, Update
|
|||||||
current_tab = "prefs"
|
current_tab = "prefs"
|
||||||
|
|
||||||
def get_form_kwargs(self):
|
def get_form_kwargs(self):
|
||||||
return super().get_form_kwargs() | {
|
return super().get_form_kwargs() | {"instance": self.object.preferences}
|
||||||
"instance": self.object.preferences,
|
|
||||||
"label_suffix": "",
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_success_url(self):
|
def get_success_url(self):
|
||||||
return self.request.path
|
return self.request.path
|
||||||
@@ -520,9 +491,6 @@ class UserPreferencesView(UserTabsMixin, UseFragmentsMixin, CanEditMixin, Update
|
|||||||
from counter.views.student_card import StudentCardFormFragment
|
from counter.views.student_card import StudentCardFormFragment
|
||||||
|
|
||||||
res = super().get_fragment_context_data()
|
res = super().get_fragment_context_data()
|
||||||
res["user_visibility_fragment"] = UserVisibilityFormFragment.as_fragment()(
|
|
||||||
self.request, user=self.object
|
|
||||||
)
|
|
||||||
if hasattr(self.object, "customer"):
|
if hasattr(self.object, "customer"):
|
||||||
res["student_card_fragment"] = StudentCardFormFragment.as_fragment()(
|
res["student_card_fragment"] = StudentCardFormFragment.as_fragment()(
|
||||||
self.request, customer=self.object.customer
|
self.request, customer=self.object.customer
|
||||||
|
|||||||
+1
-7
@@ -24,7 +24,6 @@ from counter.models import (
|
|||||||
Eticket,
|
Eticket,
|
||||||
InvoiceCall,
|
InvoiceCall,
|
||||||
Permanency,
|
Permanency,
|
||||||
Price,
|
|
||||||
Product,
|
Product,
|
||||||
ProductType,
|
ProductType,
|
||||||
Refilling,
|
Refilling,
|
||||||
@@ -33,24 +32,19 @@ from counter.models import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class PriceInline(admin.TabularInline):
|
|
||||||
model = Price
|
|
||||||
autocomplete_fields = ("groups",)
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Product)
|
@admin.register(Product)
|
||||||
class ProductAdmin(SearchModelAdmin):
|
class ProductAdmin(SearchModelAdmin):
|
||||||
list_display = (
|
list_display = (
|
||||||
"name",
|
"name",
|
||||||
"code",
|
"code",
|
||||||
"product_type",
|
"product_type",
|
||||||
|
"selling_price",
|
||||||
"archived",
|
"archived",
|
||||||
"created_at",
|
"created_at",
|
||||||
"updated_at",
|
"updated_at",
|
||||||
)
|
)
|
||||||
list_select_related = ("product_type",)
|
list_select_related = ("product_type",)
|
||||||
search_fields = ("name", "code")
|
search_fields = ("name", "code")
|
||||||
inlines = [PriceInline]
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(ReturnableProduct)
|
@admin.register(ReturnableProduct)
|
||||||
|
|||||||
+6
-2
@@ -101,9 +101,13 @@ class ProductController(ControllerBase):
|
|||||||
"""Get the detailed information about the products."""
|
"""Get the detailed information about the products."""
|
||||||
return filters.filter(
|
return filters.filter(
|
||||||
Product.objects.select_related("club")
|
Product.objects.select_related("club")
|
||||||
.prefetch_related("prices", "prices__groups")
|
.prefetch_related("buying_groups")
|
||||||
.select_related("product_type")
|
.select_related("product_type")
|
||||||
.order_by(F("product_type__order").asc(nulls_last=True), "name")
|
.order_by(
|
||||||
|
F("product_type__order").asc(nulls_last=True),
|
||||||
|
"product_type",
|
||||||
|
"name",
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,10 @@ from model_bakery.recipe import Recipe, foreign_key
|
|||||||
|
|
||||||
from club.models import Club
|
from club.models import Club
|
||||||
from core.models import User
|
from core.models import User
|
||||||
from counter.models import Counter, Price, Product, Refilling, Selling
|
from counter.models import Counter, Product, Refilling, Selling
|
||||||
|
|
||||||
counter_recipe = Recipe(Counter)
|
counter_recipe = Recipe(Counter)
|
||||||
product_recipe = Recipe(Product, club=foreign_key(Recipe(Club)))
|
product_recipe = Recipe(Product, club=foreign_key(Recipe(Club)))
|
||||||
price_recipe = Recipe(Price, product=foreign_key(product_recipe))
|
|
||||||
sale_recipe = Recipe(
|
sale_recipe = Recipe(
|
||||||
Selling,
|
Selling,
|
||||||
product=foreign_key(product_recipe),
|
product=foreign_key(product_recipe),
|
||||||
|
|||||||
+70
-141
@@ -1,12 +1,11 @@
|
|||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import uuid
|
import uuid
|
||||||
from collections import defaultdict
|
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date, datetime, timezone
|
||||||
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.validators import MaxValueValidator
|
||||||
from django.db.models import Exists, OuterRef, Q
|
from django.db.models import Exists, OuterRef, Q
|
||||||
from django.forms import BaseModelFormSet
|
from django.forms import BaseModelFormSet
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
@@ -16,7 +15,7 @@ from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
|||||||
|
|
||||||
from club.models import Club
|
from club.models import Club
|
||||||
from club.widgets.ajax_select import AutoCompleteSelectClub
|
from club.widgets.ajax_select import AutoCompleteSelectClub
|
||||||
from core.models import User, UserQuerySet
|
from core.models import User
|
||||||
from core.views.forms import (
|
from core.views.forms import (
|
||||||
FutureDateTimeField,
|
FutureDateTimeField,
|
||||||
NFCTextInput,
|
NFCTextInput,
|
||||||
@@ -33,11 +32,9 @@ from core.views.widgets.ajax_select import (
|
|||||||
from counter.models import (
|
from counter.models import (
|
||||||
BillingInfo,
|
BillingInfo,
|
||||||
Counter,
|
Counter,
|
||||||
CounterSellers,
|
|
||||||
Customer,
|
Customer,
|
||||||
Eticket,
|
Eticket,
|
||||||
InvoiceCall,
|
InvoiceCall,
|
||||||
Price,
|
|
||||||
Product,
|
Product,
|
||||||
ProductFormula,
|
ProductFormula,
|
||||||
Refilling,
|
Refilling,
|
||||||
@@ -173,39 +170,14 @@ class RefillForm(forms.ModelForm):
|
|||||||
class CounterEditForm(forms.ModelForm):
|
class CounterEditForm(forms.ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Counter
|
model = Counter
|
||||||
fields = ["products"]
|
fields = ["sellers", "products"]
|
||||||
|
widgets = {"sellers": AutoCompleteSelectMultipleUser}
|
||||||
sellers_regular = forms.ModelMultipleChoiceField(
|
|
||||||
label=_("Regular barmen"),
|
|
||||||
help_text=_(
|
|
||||||
"Barmen having regular permanences "
|
|
||||||
"or frequently giving a hand throughout the semester."
|
|
||||||
),
|
|
||||||
queryset=User.objects.all(),
|
|
||||||
widget=AutoCompleteSelectMultipleUser,
|
|
||||||
required=False,
|
|
||||||
)
|
|
||||||
sellers_temporary = forms.ModelMultipleChoiceField(
|
|
||||||
label=_("Temporary barmen"),
|
|
||||||
help_text=_(
|
|
||||||
"Barmen who will be there only for a limited period (e.g. for one evening)"
|
|
||||||
),
|
|
||||||
queryset=User.objects.all(),
|
|
||||||
widget=AutoCompleteSelectMultipleUser,
|
|
||||||
required=False,
|
|
||||||
)
|
|
||||||
field_order = ["sellers_regular", "sellers_temporary", "products"]
|
|
||||||
|
|
||||||
def __init__(self, *args, user: User, instance: Counter, **kwargs):
|
def __init__(self, *args, user: User, instance: Counter, **kwargs):
|
||||||
super().__init__(*args, instance=instance, **kwargs)
|
super().__init__(*args, instance=instance, **kwargs)
|
||||||
# if the user is an admin, he will have access to all products,
|
|
||||||
# else only to active products owned by the counter's club
|
|
||||||
# or already on the counter
|
|
||||||
if user.has_perm("counter.change_counter"):
|
if user.has_perm("counter.change_counter"):
|
||||||
self.fields["products"].widget = AutoCompleteSelectMultipleProduct()
|
self.fields["products"].widget = AutoCompleteSelectMultipleProduct()
|
||||||
else:
|
else:
|
||||||
# updating the queryset of the field also updates the choices of
|
|
||||||
# the widget, so it's important to set the queryset after the widget
|
|
||||||
self.fields["products"].widget = AutoCompleteSelectMultiple()
|
self.fields["products"].widget = AutoCompleteSelectMultiple()
|
||||||
self.fields["products"].queryset = Product.objects.filter(
|
self.fields["products"].queryset = Product.objects.filter(
|
||||||
Q(club_id=instance.club_id) | Q(counters=instance), archived=False
|
Q(club_id=instance.club_id) | Q(counters=instance), archived=False
|
||||||
@@ -214,61 +186,6 @@ class CounterEditForm(forms.ModelForm):
|
|||||||
"If you want to add a product that is not owned by "
|
"If you want to add a product that is not owned by "
|
||||||
"your club to this counter, you should ask an admin."
|
"your club to this counter, you should ask an admin."
|
||||||
)
|
)
|
||||||
self.fields["sellers_regular"].initial = self.instance.sellers.filter(
|
|
||||||
countersellers__is_regular=True
|
|
||||||
).all()
|
|
||||||
self.fields["sellers_temporary"].initial = self.instance.sellers.filter(
|
|
||||||
countersellers__is_regular=False
|
|
||||||
).all()
|
|
||||||
|
|
||||||
def clean(self):
|
|
||||||
regular: UserQuerySet = self.cleaned_data["sellers_regular"]
|
|
||||||
temporary: UserQuerySet = self.cleaned_data["sellers_temporary"]
|
|
||||||
duplicates = list(regular.intersection(temporary))
|
|
||||||
if duplicates:
|
|
||||||
raise ValidationError(
|
|
||||||
_(
|
|
||||||
"A user cannot be a regular and a temporary barman "
|
|
||||||
"at the same time, "
|
|
||||||
"but the following users have been defined as both : %(users)s"
|
|
||||||
)
|
|
||||||
% {"users": ", ".join([u.get_display_name() for u in duplicates])}
|
|
||||||
)
|
|
||||||
return self.cleaned_data
|
|
||||||
|
|
||||||
def save_sellers(self):
|
|
||||||
sellers = []
|
|
||||||
for users, is_regular in (
|
|
||||||
(self.cleaned_data["sellers_regular"], True),
|
|
||||||
(self.cleaned_data["sellers_temporary"], False),
|
|
||||||
):
|
|
||||||
sellers.extend(
|
|
||||||
[
|
|
||||||
CounterSellers(counter=self.instance, user=u, is_regular=is_regular)
|
|
||||||
for u in users
|
|
||||||
]
|
|
||||||
)
|
|
||||||
# start by deleting removed CounterSellers objects
|
|
||||||
user_ids = [seller.user.id for seller in sellers]
|
|
||||||
CounterSellers.objects.filter(
|
|
||||||
~Q(user_id__in=user_ids), counter=self.instance
|
|
||||||
).delete()
|
|
||||||
|
|
||||||
# then create or update the new barmen
|
|
||||||
CounterSellers.objects.bulk_create(
|
|
||||||
sellers,
|
|
||||||
update_conflicts=True,
|
|
||||||
update_fields=["is_regular"],
|
|
||||||
unique_fields=["user", "counter"],
|
|
||||||
)
|
|
||||||
|
|
||||||
def save(self, commit=True): # noqa: FBT002
|
|
||||||
self.instance = super().save(commit=commit)
|
|
||||||
if commit and any(
|
|
||||||
key in self.changed_data for key in ("sellers_regular", "sellers_temporary")
|
|
||||||
):
|
|
||||||
self.save_sellers()
|
|
||||||
return self.instance
|
|
||||||
|
|
||||||
|
|
||||||
class ScheduledProductActionForm(forms.ModelForm):
|
class ScheduledProductActionForm(forms.ModelForm):
|
||||||
@@ -374,22 +291,7 @@ ScheduledProductActionFormSet = forms.modelformset_factory(
|
|||||||
absolute_max=None,
|
absolute_max=None,
|
||||||
can_delete=True,
|
can_delete=True,
|
||||||
can_delete_extra=False,
|
can_delete_extra=False,
|
||||||
extra=0,
|
extra=2,
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
ProductPriceFormSet = forms.inlineformset_factory(
|
|
||||||
parent_model=Product,
|
|
||||||
model=Price,
|
|
||||||
fields=["amount", "label", "groups", "is_always_shown"],
|
|
||||||
widgets={
|
|
||||||
"groups": AutoCompleteSelectMultipleGroup,
|
|
||||||
"is_always_shown": forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
},
|
|
||||||
absolute_max=None,
|
|
||||||
can_delete_extra=False,
|
|
||||||
min_num=1,
|
|
||||||
extra=0,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -404,7 +306,10 @@ class ProductForm(forms.ModelForm):
|
|||||||
"description",
|
"description",
|
||||||
"product_type",
|
"product_type",
|
||||||
"code",
|
"code",
|
||||||
|
"buying_groups",
|
||||||
"purchase_price",
|
"purchase_price",
|
||||||
|
"selling_price",
|
||||||
|
"special_selling_price",
|
||||||
"icon",
|
"icon",
|
||||||
"club",
|
"club",
|
||||||
"limit_age",
|
"limit_age",
|
||||||
@@ -419,8 +324,8 @@ class ProductForm(forms.ModelForm):
|
|||||||
}
|
}
|
||||||
widgets = {
|
widgets = {
|
||||||
"product_type": AutoCompleteSelect,
|
"product_type": AutoCompleteSelect,
|
||||||
|
"buying_groups": AutoCompleteSelectMultipleGroup,
|
||||||
"club": AutoCompleteSelectClub,
|
"club": AutoCompleteSelectClub,
|
||||||
"tray": forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
counters = forms.ModelMultipleChoiceField(
|
counters = forms.ModelMultipleChoiceField(
|
||||||
@@ -430,40 +335,50 @@ class ProductForm(forms.ModelForm):
|
|||||||
queryset=Counter.objects.all(),
|
queryset=Counter.objects.all(),
|
||||||
)
|
)
|
||||||
|
|
||||||
def __init__(self, *args, prefix: str | None = None, instance=None, **kwargs):
|
def __init__(self, *args, instance=None, **kwargs):
|
||||||
super().__init__(*args, prefix=prefix, instance=instance, **kwargs)
|
super().__init__(*args, instance=instance, **kwargs)
|
||||||
self.fields["name"].widget.attrs["autofocus"] = "autofocus"
|
|
||||||
if self.instance.id:
|
if self.instance.id:
|
||||||
self.fields["counters"].initial = self.instance.counters.all()
|
self.fields["counters"].initial = self.instance.counters.all()
|
||||||
if hasattr(self.instance, "formula"):
|
if hasattr(self.instance, "formula"):
|
||||||
self.formula_init(self.instance.formula)
|
self.formula_init(self.instance.formula)
|
||||||
self.price_formset = ProductPriceFormSet(
|
|
||||||
*args, instance=self.instance, prefix="price", **kwargs
|
|
||||||
)
|
|
||||||
self.action_formset = ScheduledProductActionFormSet(
|
self.action_formset = ScheduledProductActionFormSet(
|
||||||
*args, product=self.instance, prefix="action", **kwargs
|
*args, product=self.instance, **kwargs
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def formula_init(self, formula: ProductFormula):
|
||||||
|
"""Part of the form initialisation specific to formula products."""
|
||||||
|
self.fields["selling_price"].help_text = _(
|
||||||
|
"This product is a formula. "
|
||||||
|
"Its price cannot be greater than the price "
|
||||||
|
"of the products constituting it, which is %(price)s €"
|
||||||
|
) % {"price": formula.max_selling_price}
|
||||||
|
self.fields["special_selling_price"].help_text = _(
|
||||||
|
"This product is a formula. "
|
||||||
|
"Its special price cannot be greater than the price "
|
||||||
|
"of the products constituting it, which is %(price)s €"
|
||||||
|
) % {"price": formula.max_special_selling_price}
|
||||||
|
for key, price in (
|
||||||
|
("selling_price", formula.max_selling_price),
|
||||||
|
("special_selling_price", formula.max_special_selling_price),
|
||||||
|
):
|
||||||
|
self.fields[key].widget.attrs["max"] = price
|
||||||
|
self.fields[key].validators.append(MaxValueValidator(price))
|
||||||
|
|
||||||
def is_valid(self):
|
def is_valid(self):
|
||||||
return (
|
return super().is_valid() and self.action_formset.is_valid()
|
||||||
super().is_valid()
|
|
||||||
and self.price_formset.is_valid()
|
|
||||||
and self.action_formset.is_valid()
|
|
||||||
)
|
|
||||||
|
|
||||||
def save(self, *args, **kwargs) -> Product:
|
def save(self, *args, **kwargs) -> Product:
|
||||||
product = super().save(*args, **kwargs)
|
product = super().save(*args, **kwargs)
|
||||||
product.counters.set(self.cleaned_data["counters"])
|
product.counters.set(self.cleaned_data["counters"])
|
||||||
# if it's a creation, the product given in the formset
|
|
||||||
# wasn't a persisted instance.
|
|
||||||
# So if we tried to persist the related objects in the current state,
|
|
||||||
# they would be linked to no product, thus be completely useless
|
|
||||||
# To make it work, we have to replace
|
|
||||||
# the initial product with a persisted one
|
|
||||||
for form in self.action_formset:
|
for form in self.action_formset:
|
||||||
|
# if it's a creation, the product given in the formset
|
||||||
|
# wasn't a persisted instance.
|
||||||
|
# So if we tried to persist the scheduled actions in the current state,
|
||||||
|
# they would be linked to no product, thus be completely useless
|
||||||
|
# To make it work, we have to replace
|
||||||
|
# the initial product with a persisted one
|
||||||
form.set_product(product)
|
form.set_product(product)
|
||||||
self.action_formset.save()
|
self.action_formset.save()
|
||||||
self.price_formset.save()
|
|
||||||
return product
|
return product
|
||||||
|
|
||||||
|
|
||||||
@@ -486,6 +401,18 @@ class ProductFormulaForm(forms.ModelForm):
|
|||||||
"the result and a part of the formula."
|
"the result and a part of the formula."
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
prices = [p.selling_price for p in cleaned_data["products"]]
|
||||||
|
special_prices = [p.special_selling_price for p in cleaned_data["products"]]
|
||||||
|
selling_price = cleaned_data["result"].selling_price
|
||||||
|
special_selling_price = cleaned_data["result"].special_selling_price
|
||||||
|
if selling_price > sum(prices) or special_selling_price > sum(special_prices):
|
||||||
|
self.add_error(
|
||||||
|
"result",
|
||||||
|
_(
|
||||||
|
"The result cannot be more expensive "
|
||||||
|
"than the total of the other products."
|
||||||
|
),
|
||||||
|
)
|
||||||
return cleaned_data
|
return cleaned_data
|
||||||
|
|
||||||
|
|
||||||
@@ -536,47 +463,48 @@ class CloseCustomerAccountForm(forms.Form):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class BasketItemForm(forms.Form):
|
class BasketProductForm(forms.Form):
|
||||||
quantity = forms.IntegerField(min_value=1, required=True)
|
quantity = forms.IntegerField(min_value=1, required=True)
|
||||||
price_id = forms.IntegerField(min_value=0, required=True)
|
id = forms.IntegerField(min_value=0, required=True)
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
customer: Customer,
|
customer: Customer,
|
||||||
counter: Counter,
|
counter: Counter,
|
||||||
allowed_prices: dict[int, Price],
|
allowed_products: dict[int, Product],
|
||||||
*args,
|
*args,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
self.customer = customer # Used by formset
|
self.customer = customer # Used by formset
|
||||||
self.counter = counter # Used by formset
|
self.counter = counter # Used by formset
|
||||||
self.allowed_prices = allowed_prices
|
self.allowed_products = allowed_products
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
def clean_price_id(self):
|
def clean_id(self):
|
||||||
data = self.cleaned_data["price_id"]
|
data = self.cleaned_data["id"]
|
||||||
|
|
||||||
# We store self.price so we can use it later on the formset validation
|
# We store self.product so we can use it later on the formset validation
|
||||||
# And also in the global clean
|
# And also in the global clean
|
||||||
self.price = self.allowed_prices.get(data, None)
|
self.product = self.allowed_products.get(data, None)
|
||||||
if self.price is None:
|
if self.product is None:
|
||||||
raise forms.ValidationError(
|
raise forms.ValidationError(
|
||||||
_("The selected product isn't available for this user")
|
_("The selected product isn't available for this user")
|
||||||
)
|
)
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
cleaned_data = super().clean()
|
cleaned_data = super().clean()
|
||||||
if len(self.errors) > 0:
|
if len(self.errors) > 0:
|
||||||
return cleaned_data
|
return
|
||||||
|
|
||||||
# Compute prices
|
# Compute prices
|
||||||
cleaned_data["bonus_quantity"] = 0
|
cleaned_data["bonus_quantity"] = 0
|
||||||
if self.price.product.tray:
|
if self.product.tray:
|
||||||
cleaned_data["bonus_quantity"] = math.floor(
|
cleaned_data["bonus_quantity"] = math.floor(
|
||||||
cleaned_data["quantity"] / Product.QUANTITY_FOR_TRAY_PRICE
|
cleaned_data["quantity"] / Product.QUANTITY_FOR_TRAY_PRICE
|
||||||
)
|
)
|
||||||
cleaned_data["total_price"] = self.price.amount * (
|
cleaned_data["total_price"] = self.product.price * (
|
||||||
cleaned_data["quantity"] - cleaned_data["bonus_quantity"]
|
cleaned_data["quantity"] - cleaned_data["bonus_quantity"]
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -600,8 +528,8 @@ class BaseBasketForm(forms.BaseFormSet):
|
|||||||
raise forms.ValidationError(_("Submitted basket is invalid"))
|
raise forms.ValidationError(_("Submitted basket is invalid"))
|
||||||
|
|
||||||
def _check_product_are_unique(self):
|
def _check_product_are_unique(self):
|
||||||
price_ids = {form.cleaned_data["price_id"] for form in self.forms}
|
product_ids = {form.cleaned_data["id"] for form in self.forms}
|
||||||
if len(price_ids) != len(self.forms):
|
if len(product_ids) != len(self.forms):
|
||||||
raise forms.ValidationError(_("Duplicated product entries."))
|
raise forms.ValidationError(_("Duplicated product entries."))
|
||||||
|
|
||||||
def _check_enough_money(self, counter: Counter, customer: Customer):
|
def _check_enough_money(self, counter: Counter, customer: Customer):
|
||||||
@@ -611,9 +539,10 @@ class BaseBasketForm(forms.BaseFormSet):
|
|||||||
|
|
||||||
def _check_recorded_products(self, customer: Customer):
|
def _check_recorded_products(self, customer: Customer):
|
||||||
"""Check for, among other things, ecocups and pitchers"""
|
"""Check for, among other things, ecocups and pitchers"""
|
||||||
items = defaultdict(int)
|
items = {
|
||||||
for form in self.forms:
|
form.cleaned_data["id"]: form.cleaned_data["quantity"]
|
||||||
items[form.price.product_id] += form.cleaned_data["quantity"]
|
for form in self.forms
|
||||||
|
}
|
||||||
ids = list(items.keys())
|
ids = list(items.keys())
|
||||||
returnables = list(
|
returnables = list(
|
||||||
ReturnableProduct.objects.filter(
|
ReturnableProduct.objects.filter(
|
||||||
@@ -639,7 +568,7 @@ class BaseBasketForm(forms.BaseFormSet):
|
|||||||
|
|
||||||
|
|
||||||
BasketForm = forms.formset_factory(
|
BasketForm = forms.formset_factory(
|
||||||
BasketItemForm, formset=BaseBasketForm, absolute_max=None, min_num=1
|
BasketProductForm, formset=BaseBasketForm, absolute_max=None, min_num=1
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
# Generated by Django 5.2.11 on 2026-03-04 15:26
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("counter", "0037_productformula"),
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
# cf. https://docs.djangoproject.com/fr/stable/howto/writing-migrations/#changing-a-manytomanyfield-to-use-a-through-model
|
|
||||||
migrations.SeparateDatabaseAndState(
|
|
||||||
database_operations=[
|
|
||||||
migrations.RunSQL(
|
|
||||||
sql="ALTER TABLE counter_counter_sellers RENAME TO counter_countersellers",
|
|
||||||
reverse_sql="ALTER TABLE counter_countersellers RENAME TO counter_counter_sellers",
|
|
||||||
),
|
|
||||||
],
|
|
||||||
state_operations=[
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="CounterSellers",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.AutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"counter",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
to="counter.counter",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"user",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
to=settings.AUTH_USER_MODEL,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
"constraints": [
|
|
||||||
models.UniqueConstraint(
|
|
||||||
fields=("counter", "user"),
|
|
||||||
name="counter_counter_sellers_counter_id_subscriber_id_key",
|
|
||||||
)
|
|
||||||
],
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="counter",
|
|
||||||
name="sellers",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True,
|
|
||||||
related_name="counters",
|
|
||||||
through="counter.CounterSellers",
|
|
||||||
to=settings.AUTH_USER_MODEL,
|
|
||||||
verbose_name="sellers",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="countersellers",
|
|
||||||
name="created_at",
|
|
||||||
field=models.DateTimeField(
|
|
||||||
auto_now_add=True,
|
|
||||||
default=django.utils.timezone.now,
|
|
||||||
verbose_name="created at",
|
|
||||||
),
|
|
||||||
preserve_default=False,
|
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="countersellers",
|
|
||||||
name="is_regular",
|
|
||||||
field=models.BooleanField(default=False, verbose_name="regular barman"),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
# Generated by Django 5.2.11 on 2026-02-18 13:30
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
from django.db.migrations.state import StateApps
|
|
||||||
|
|
||||||
import counter.fields
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_prices(apps: StateApps, schema_editor):
|
|
||||||
Product = apps.get_model("counter", "Product")
|
|
||||||
Price = apps.get_model("counter", "Price")
|
|
||||||
prices = [
|
|
||||||
Price(
|
|
||||||
amount=p.selling_price,
|
|
||||||
product=p,
|
|
||||||
created_at=p.created_at,
|
|
||||||
updated_at=p.updated_at,
|
|
||||||
)
|
|
||||||
for p in Product.objects.all()
|
|
||||||
]
|
|
||||||
Price.objects.bulk_create(prices)
|
|
||||||
groups = [
|
|
||||||
Price.groups.through(price=price, group=group)
|
|
||||||
for price in Price.objects.select_related("product").prefetch_related(
|
|
||||||
"product__buying_groups"
|
|
||||||
)
|
|
||||||
for group in price.product.buying_groups.all()
|
|
||||||
]
|
|
||||||
Price.groups.through.objects.bulk_create(groups)
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("core", "0048_alter_user_options"),
|
|
||||||
("counter", "0038_countersellers"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="Price",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.AutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"amount",
|
|
||||||
counter.fields.CurrencyField(
|
|
||||||
decimal_places=2, max_digits=12, verbose_name="amount"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"is_always_shown",
|
|
||||||
models.BooleanField(
|
|
||||||
default=False,
|
|
||||||
help_text=(
|
|
||||||
"If this option is enabled, "
|
|
||||||
"people will see this price and be able to pay it, "
|
|
||||||
"even if another cheaper price exists. "
|
|
||||||
"Else it will visible only if it is the cheapest available price."
|
|
||||||
),
|
|
||||||
verbose_name="always show",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"label",
|
|
||||||
models.CharField(
|
|
||||||
default="",
|
|
||||||
help_text=(
|
|
||||||
"A short label for easier differentiation "
|
|
||||||
"if a user can see multiple prices."
|
|
||||||
),
|
|
||||||
max_length=32,
|
|
||||||
verbose_name="label",
|
|
||||||
blank=True,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"created_at",
|
|
||||||
models.DateTimeField(auto_now_add=True, verbose_name="created at"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"updated_at",
|
|
||||||
models.DateTimeField(auto_now=True, verbose_name="updated at"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"groups",
|
|
||||||
models.ManyToManyField(
|
|
||||||
related_name="prices", to="core.group", verbose_name="groups"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"product",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
related_name="prices",
|
|
||||||
to="counter.product",
|
|
||||||
verbose_name="product",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
options={"verbose_name": "price"},
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="product",
|
|
||||||
name="tray",
|
|
||||||
field=models.BooleanField(
|
|
||||||
default=False,
|
|
||||||
help_text="Buy five, get the sixth free",
|
|
||||||
verbose_name="tray price",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.RunPython(migrate_prices, reverse_code=migrations.RunPython.noop),
|
|
||||||
migrations.RemoveField(model_name="product", name="selling_price"),
|
|
||||||
migrations.RemoveField(model_name="product", name="special_selling_price"),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="product",
|
|
||||||
name="description",
|
|
||||||
field=models.TextField(blank=True, default="", verbose_name="description"),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="product",
|
|
||||||
name="product_type",
|
|
||||||
field=models.ForeignKey(
|
|
||||||
null=True,
|
|
||||||
on_delete=django.db.models.deletion.SET_NULL,
|
|
||||||
related_name="products",
|
|
||||||
to="counter.producttype",
|
|
||||||
verbose_name="product type",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="productformula",
|
|
||||||
name="result",
|
|
||||||
field=models.OneToOneField(
|
|
||||||
help_text="The product got with the formula.",
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
related_name="formula",
|
|
||||||
to="counter.product",
|
|
||||||
verbose_name="result product",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
+85
-113
@@ -22,7 +22,7 @@ import string
|
|||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
from datetime import timezone as tz
|
from datetime import timezone as tz
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import TYPE_CHECKING, Literal, Self
|
from typing import Literal, Self
|
||||||
|
|
||||||
from dict2xml import dict2xml
|
from dict2xml import dict2xml
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@@ -47,9 +47,6 @@ from core.utils import get_start_of_semester
|
|||||||
from counter.fields import CurrencyField
|
from counter.fields import CurrencyField
|
||||||
from subscription.models import Subscription
|
from subscription.models import Subscription
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from collections.abc import Sequence
|
|
||||||
|
|
||||||
|
|
||||||
def get_eboutic() -> Counter:
|
def get_eboutic() -> Counter:
|
||||||
return Counter.objects.filter(type="EBOUTIC").order_by("id").first()
|
return Counter.objects.filter(type="EBOUTIC").order_by("id").first()
|
||||||
@@ -160,7 +157,14 @@ class Customer(models.Model):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def can_buy(self) -> bool:
|
def can_buy(self) -> bool:
|
||||||
"""Check if whether this customer has the right to purchase any item."""
|
"""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.
|
||||||
|
"""
|
||||||
subscription = self.user.subscriptions.order_by("subscription_end").last()
|
subscription = self.user.subscriptions.order_by("subscription_end").last()
|
||||||
if subscription is None:
|
if subscription is None:
|
||||||
return False
|
return False
|
||||||
@@ -359,13 +363,13 @@ class Product(models.Model):
|
|||||||
QUANTITY_FOR_TRAY_PRICE = 6
|
QUANTITY_FOR_TRAY_PRICE = 6
|
||||||
|
|
||||||
name = models.CharField(_("name"), max_length=64)
|
name = models.CharField(_("name"), max_length=64)
|
||||||
description = models.TextField(_("description"), blank=True, default="")
|
description = models.TextField(_("description"), default="")
|
||||||
product_type = models.ForeignKey(
|
product_type = models.ForeignKey(
|
||||||
ProductType,
|
ProductType,
|
||||||
related_name="products",
|
related_name="products",
|
||||||
verbose_name=_("product type"),
|
verbose_name=_("product type"),
|
||||||
null=True,
|
null=True,
|
||||||
blank=False,
|
blank=True,
|
||||||
on_delete=models.SET_NULL,
|
on_delete=models.SET_NULL,
|
||||||
)
|
)
|
||||||
code = models.CharField(_("code"), max_length=16, blank=True)
|
code = models.CharField(_("code"), max_length=16, blank=True)
|
||||||
@@ -373,6 +377,11 @@ class Product(models.Model):
|
|||||||
_("purchase price"),
|
_("purchase price"),
|
||||||
help_text=_("Initial cost of purchasing the product"),
|
help_text=_("Initial cost of purchasing the product"),
|
||||||
)
|
)
|
||||||
|
selling_price = CurrencyField(_("selling price"))
|
||||||
|
special_selling_price = CurrencyField(
|
||||||
|
_("special selling price"),
|
||||||
|
help_text=_("Price for barmen during their permanence"),
|
||||||
|
)
|
||||||
icon = ResizedImageField(
|
icon = ResizedImageField(
|
||||||
height=70,
|
height=70,
|
||||||
force_format="WEBP",
|
force_format="WEBP",
|
||||||
@@ -385,9 +394,7 @@ class Product(models.Model):
|
|||||||
Club, related_name="products", verbose_name=_("club"), on_delete=models.CASCADE
|
Club, related_name="products", verbose_name=_("club"), on_delete=models.CASCADE
|
||||||
)
|
)
|
||||||
limit_age = models.IntegerField(_("limit age"), default=0)
|
limit_age = models.IntegerField(_("limit age"), default=0)
|
||||||
tray = models.BooleanField(
|
tray = models.BooleanField(_("tray price"), default=False)
|
||||||
_("tray price"), help_text=_("Buy five, get the sixth free"), default=False
|
|
||||||
)
|
|
||||||
buying_groups = models.ManyToManyField(
|
buying_groups = models.ManyToManyField(
|
||||||
Group, related_name="products", verbose_name=_("buying groups"), blank=True
|
Group, related_name="products", verbose_name=_("buying groups"), blank=True
|
||||||
)
|
)
|
||||||
@@ -412,77 +419,41 @@ class Product(models.Model):
|
|||||||
pk=settings.SITH_GROUP_ACCOUNTING_ADMIN_ID
|
pk=settings.SITH_GROUP_ACCOUNTING_ADMIN_ID
|
||||||
) or user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)
|
) or user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)
|
||||||
|
|
||||||
|
def can_be_sold_to(self, user: User) -> bool:
|
||||||
|
"""Check if whether the user given in parameter has the right to buy
|
||||||
|
this product or not.
|
||||||
|
|
||||||
class PriceQuerySet(models.QuerySet):
|
This must be not confused with the Customer.can_buy()
|
||||||
def for_user(self, user: User) -> Self:
|
method as the present method returns an information
|
||||||
age = user.age
|
about the relation between a User and a Product,
|
||||||
if user.is_banned_alcohol:
|
whereas the other tells something about a Customer
|
||||||
age = min(age, 17)
|
(and not a user, they are not the same model).
|
||||||
return self.filter(
|
|
||||||
Q(is_always_shown=True, groups__in=user.all_groups)
|
|
||||||
| Q(
|
|
||||||
id=Subquery(
|
|
||||||
Price.objects.filter(
|
|
||||||
product_id=OuterRef("product_id"), groups__in=user.all_groups
|
|
||||||
)
|
|
||||||
.order_by("amount")
|
|
||||||
.values("id")[:1]
|
|
||||||
)
|
|
||||||
),
|
|
||||||
product__archived=False,
|
|
||||||
product__limit_age__lte=age,
|
|
||||||
).distinct()
|
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if the user can buy this product else False
|
||||||
|
|
||||||
class Price(models.Model):
|
Warning:
|
||||||
amount = CurrencyField(_("amount"))
|
This performs a db query, thus you can quickly have
|
||||||
product = models.ForeignKey(
|
a N+1 queries problem if you call it in a loop.
|
||||||
Product,
|
Hopefully, you can avoid that if you prefetch the buying_groups :
|
||||||
verbose_name=_("product"),
|
|
||||||
related_name="prices",
|
|
||||||
on_delete=models.CASCADE,
|
|
||||||
)
|
|
||||||
groups = models.ManyToManyField(
|
|
||||||
Group, verbose_name=_("groups"), related_name="prices"
|
|
||||||
)
|
|
||||||
is_always_shown = models.BooleanField(
|
|
||||||
_("always show"),
|
|
||||||
help_text=_(
|
|
||||||
"If this option is enabled, "
|
|
||||||
"people will see this price and be able to pay it, "
|
|
||||||
"even if another cheaper price exists. "
|
|
||||||
"Else it will visible only if it is the cheapest available price."
|
|
||||||
),
|
|
||||||
default=False,
|
|
||||||
)
|
|
||||||
label = models.CharField(
|
|
||||||
_("label"),
|
|
||||||
help_text=_(
|
|
||||||
"A short label for easier differentiation "
|
|
||||||
"if a user can see multiple prices."
|
|
||||||
),
|
|
||||||
max_length=32,
|
|
||||||
default="",
|
|
||||||
blank=True,
|
|
||||||
)
|
|
||||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(_("updated at"), auto_now=True)
|
|
||||||
|
|
||||||
objects = PriceQuerySet.as_manager()
|
```python
|
||||||
|
user = User.objects.get(username="foobar")
|
||||||
class Meta:
|
products = [
|
||||||
verbose_name = _("price")
|
p
|
||||||
|
for p in Product.objects.prefetch_related("buying_groups")
|
||||||
def __str__(self):
|
if p.can_be_sold_to(user)
|
||||||
if not self.label:
|
]
|
||||||
return f"{self.product.name} ({self.amount}€)"
|
```
|
||||||
return f"{self.product.name} {self.label} ({self.amount}€)"
|
"""
|
||||||
|
buying_groups = list(self.buying_groups.all())
|
||||||
|
if not buying_groups:
|
||||||
|
return True
|
||||||
|
return any(user.is_in_group(pk=group.id) for group in buying_groups)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def full_label(self):
|
def profit(self):
|
||||||
if not self.label:
|
return self.selling_price - self.purchase_price
|
||||||
return self.product.name
|
|
||||||
return f"{self.product.name} \u2013 {self.label}"
|
|
||||||
|
|
||||||
|
|
||||||
class ProductFormula(models.Model):
|
class ProductFormula(models.Model):
|
||||||
@@ -503,6 +474,18 @@ class ProductFormula(models.Model):
|
|||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.result.name
|
return self.result.name
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def max_selling_price(self) -> float:
|
||||||
|
# iterating over all products is less efficient than doing
|
||||||
|
# a simple aggregation, but this method is likely to be used in
|
||||||
|
# coordination with `max_special_selling_price`,
|
||||||
|
# and Django caches the result of the `all` queryset.
|
||||||
|
return sum(p.selling_price for p in self.products.all())
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def max_special_selling_price(self) -> float:
|
||||||
|
return sum(p.special_selling_price for p in self.products.all())
|
||||||
|
|
||||||
|
|
||||||
class CounterQuerySet(models.QuerySet):
|
class CounterQuerySet(models.QuerySet):
|
||||||
def annotate_has_barman(self, user: User) -> Self:
|
def annotate_has_barman(self, user: User) -> Self:
|
||||||
@@ -568,11 +551,7 @@ class Counter(models.Model):
|
|||||||
choices=[("BAR", _("Bar")), ("OFFICE", _("Office")), ("EBOUTIC", _("Eboutic"))],
|
choices=[("BAR", _("Bar")), ("OFFICE", _("Office")), ("EBOUTIC", _("Eboutic"))],
|
||||||
)
|
)
|
||||||
sellers = models.ManyToManyField(
|
sellers = models.ManyToManyField(
|
||||||
User,
|
User, verbose_name=_("sellers"), related_name="counters", blank=True
|
||||||
verbose_name=_("sellers"),
|
|
||||||
related_name="counters",
|
|
||||||
blank=True,
|
|
||||||
through="CounterSellers",
|
|
||||||
)
|
)
|
||||||
edit_groups = models.ManyToManyField(
|
edit_groups = models.ManyToManyField(
|
||||||
Group, related_name="editable_counters", blank=True
|
Group, related_name="editable_counters", blank=True
|
||||||
@@ -600,7 +579,7 @@ class Counter(models.Model):
|
|||||||
if user.is_anonymous:
|
if user.is_anonymous:
|
||||||
return False
|
return False
|
||||||
mem = self.club.get_membership_for(user)
|
mem = self.club.get_membership_for(user)
|
||||||
if mem and mem.role.is_presidency:
|
if mem and mem.role >= settings.SITH_CLUB_ROLES_ID["Treasurer"]:
|
||||||
return True
|
return True
|
||||||
return user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)
|
return user.is_in_group(pk=settings.SITH_GROUP_COUNTER_ADMIN_ID)
|
||||||
|
|
||||||
@@ -733,41 +712,36 @@ class Counter(models.Model):
|
|||||||
# but they share the same primary key
|
# but they share the same primary key
|
||||||
return self.type == "BAR" and any(b.pk == customer.pk for b in self.barmen_list)
|
return self.type == "BAR" and any(b.pk == customer.pk for b in self.barmen_list)
|
||||||
|
|
||||||
def get_prices_for(
|
def get_products_for(self, customer: Customer) -> list[Product]:
|
||||||
self, customer: Customer, *, order_by: Sequence[str] | None = None
|
"""
|
||||||
) -> list[Price]:
|
Get all allowed products for the provided customer on this counter
|
||||||
qs = (
|
Prices will be annotated
|
||||||
Price.objects.filter(
|
"""
|
||||||
product__counters=self, product__product_type__isnull=False
|
|
||||||
)
|
products = (
|
||||||
.for_user(customer.user)
|
self.products.filter(archived=False)
|
||||||
.select_related("product", "product__product_type")
|
.select_related("product_type")
|
||||||
.prefetch_related("groups")
|
.prefetch_related("buying_groups")
|
||||||
)
|
)
|
||||||
if order_by:
|
|
||||||
qs = qs.order_by(*order_by)
|
|
||||||
return list(qs)
|
|
||||||
|
|
||||||
|
# Only include age appropriate products
|
||||||
|
age = customer.user.age
|
||||||
|
if customer.user.is_banned_alcohol:
|
||||||
|
age = min(age, 17)
|
||||||
|
products = products.filter(limit_age__lte=age)
|
||||||
|
|
||||||
class CounterSellers(models.Model):
|
# Compute special price for customer if he is a barmen on that bar
|
||||||
"""Custom through model for the counter-sellers M2M relationship."""
|
if self.customer_is_barman(customer):
|
||||||
|
products = products.annotate(price=F("special_selling_price"))
|
||||||
|
else:
|
||||||
|
products = products.annotate(price=F("selling_price"))
|
||||||
|
|
||||||
counter = models.ForeignKey(Counter, on_delete=models.CASCADE)
|
return [
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
product
|
||||||
is_regular = models.BooleanField(_("regular barman"), default=False)
|
for product in products.all()
|
||||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
if product.can_be_sold_to(customer.user)
|
||||||
|
|
||||||
class Meta:
|
|
||||||
constraints = [
|
|
||||||
models.UniqueConstraint(
|
|
||||||
fields=["counter", "user"],
|
|
||||||
name="counter_counter_sellers_counter_id_subscriber_id_key",
|
|
||||||
)
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return f"counter {self.counter_id} - user {self.user_id}"
|
|
||||||
|
|
||||||
|
|
||||||
class RefillingQuerySet(models.QuerySet):
|
class RefillingQuerySet(models.QuerySet):
|
||||||
def annotate_total(self) -> Self:
|
def annotate_total(self) -> Self:
|
||||||
@@ -1027,9 +1001,7 @@ class Selling(models.Model):
|
|||||||
event = self.product.eticket.event_title or _("Unknown event")
|
event = self.product.eticket.event_title or _("Unknown event")
|
||||||
subject = _("Eticket bought for the event %(event)s") % {"event": event}
|
subject = _("Eticket bought for the event %(event)s") % {"event": event}
|
||||||
message_html = _(
|
message_html = _(
|
||||||
"You bought an eticket for the event %(event)s.\n"
|
"You bought an eticket for the event %(event)s.\nYou can download it directly from this link %(eticket)s.\nYou can also retrieve all your e-tickets on your account page %(url)s."
|
||||||
"You can download it directly from this link %(eticket)s.\n"
|
|
||||||
"You can also retrieve all your e-tickets on your account page %(url)s."
|
|
||||||
) % {
|
) % {
|
||||||
"event": event,
|
"event": event,
|
||||||
"url": (
|
"url": (
|
||||||
|
|||||||
+4
-9
@@ -6,8 +6,8 @@ from ninja import FilterLookup, FilterSchema, ModelSchema, Schema
|
|||||||
from pydantic import model_validator
|
from pydantic import model_validator
|
||||||
|
|
||||||
from club.schemas import SimpleClubSchema
|
from club.schemas import SimpleClubSchema
|
||||||
from core.schemas import NonEmptyStr, SimpleUserSchema
|
from core.schemas import GroupSchema, NonEmptyStr, SimpleUserSchema
|
||||||
from counter.models import Counter, Price, Product, ProductType
|
from counter.models import Counter, Product, ProductType
|
||||||
|
|
||||||
|
|
||||||
class CounterSchema(ModelSchema):
|
class CounterSchema(ModelSchema):
|
||||||
@@ -66,12 +66,6 @@ class SimpleProductSchema(ModelSchema):
|
|||||||
fields = ["id", "name", "code"]
|
fields = ["id", "name", "code"]
|
||||||
|
|
||||||
|
|
||||||
class ProductPriceSchema(ModelSchema):
|
|
||||||
class Meta:
|
|
||||||
model = Price
|
|
||||||
fields = ["amount", "groups"]
|
|
||||||
|
|
||||||
|
|
||||||
class ProductSchema(ModelSchema):
|
class ProductSchema(ModelSchema):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Product
|
model = Product
|
||||||
@@ -81,12 +75,13 @@ class ProductSchema(ModelSchema):
|
|||||||
"code",
|
"code",
|
||||||
"description",
|
"description",
|
||||||
"purchase_price",
|
"purchase_price",
|
||||||
|
"selling_price",
|
||||||
"icon",
|
"icon",
|
||||||
"limit_age",
|
"limit_age",
|
||||||
"archived",
|
"archived",
|
||||||
]
|
]
|
||||||
|
|
||||||
prices: list[ProductPriceSchema]
|
buying_groups: list[GroupSchema]
|
||||||
club: SimpleClubSchema
|
club: SimpleClubSchema
|
||||||
product_type: SimpleProductTypeSchema | None
|
product_type: SimpleProductTypeSchema | None
|
||||||
url: str
|
url: str
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import type { CounterItem } from "#counter:counter/types";
|
import type { Product } from "#counter:counter/types.ts";
|
||||||
|
|
||||||
export class BasketItem {
|
export class BasketItem {
|
||||||
quantity: number;
|
quantity: number;
|
||||||
product: CounterItem;
|
product: Product;
|
||||||
|
quantityForTrayPrice: number;
|
||||||
errors: string[];
|
errors: string[];
|
||||||
|
|
||||||
constructor(product: CounterItem, quantity: number) {
|
constructor(product: Product, quantity: number) {
|
||||||
this.quantity = quantity;
|
this.quantity = quantity;
|
||||||
this.product = product;
|
this.product = product;
|
||||||
this.errors = [];
|
this.errors = [];
|
||||||
@@ -19,6 +20,6 @@ export class BasketItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sum(): number {
|
sum(): number {
|
||||||
return (this.quantity - this.getBonusQuantity()) * this.product.price.amount;
|
return (this.quantity - this.getBonusQuantity()) * this.product.price;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { AlertMessage } from "#core:utils/alert-message";
|
import { AlertMessage } from "#core:utils/alert-message.ts";
|
||||||
import { BasketItem } from "#counter:counter/basket";
|
import { BasketItem } from "#counter:counter/basket.ts";
|
||||||
import type {
|
import type {
|
||||||
CounterConfig,
|
CounterConfig,
|
||||||
CounterItem,
|
|
||||||
ErrorMessage,
|
ErrorMessage,
|
||||||
ProductFormula,
|
ProductFormula,
|
||||||
} from "#counter:counter/types";
|
} from "#counter:counter/types.ts";
|
||||||
import type { CounterProductSelect } from "./components/counter-product-select-index";
|
import type { CounterProductSelect } from "./components/counter-product-select-index.ts";
|
||||||
|
|
||||||
document.addEventListener("alpine:init", () => {
|
document.addEventListener("alpine:init", () => {
|
||||||
Alpine.data("counter", (config: CounterConfig) => ({
|
Alpine.data("counter", (config: CounterConfig) => ({
|
||||||
@@ -64,10 +63,8 @@ document.addEventListener("alpine:init", () => {
|
|||||||
},
|
},
|
||||||
|
|
||||||
checkFormulas() {
|
checkFormulas() {
|
||||||
// Try to find a formula.
|
|
||||||
// A formula is found if all its elements are already in the basket
|
|
||||||
const products = new Set(
|
const products = new Set(
|
||||||
Object.values(this.basket).map((item: BasketItem) => item.product.productId),
|
Object.keys(this.basket).map((i: string) => Number.parseInt(i)),
|
||||||
);
|
);
|
||||||
const formula: ProductFormula = config.formulas.find((f: ProductFormula) => {
|
const formula: ProductFormula = config.formulas.find((f: ProductFormula) => {
|
||||||
return f.products.every((p: number) => products.has(p));
|
return f.products.every((p: number) => products.has(p));
|
||||||
@@ -75,29 +72,22 @@ document.addEventListener("alpine:init", () => {
|
|||||||
if (formula === undefined) {
|
if (formula === undefined) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Now that the formula is found, remove the items composing it from the basket
|
|
||||||
for (const product of formula.products) {
|
for (const product of formula.products) {
|
||||||
const key = Object.entries(this.basket).find(
|
const key = product.toString();
|
||||||
([_, i]: [string, BasketItem]) => i.product.productId === product,
|
|
||||||
)[0];
|
|
||||||
this.basket[key].quantity -= 1;
|
this.basket[key].quantity -= 1;
|
||||||
if (this.basket[key].quantity <= 0) {
|
if (this.basket[key].quantity <= 0) {
|
||||||
this.removeFromBasket(key);
|
this.removeFromBasket(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Then add the result product of the formula to the basket
|
|
||||||
const result = Object.values(config.products)
|
|
||||||
.filter((item: CounterItem) => item.productId === formula.result)
|
|
||||||
.reduce((acc, curr) => (acc.price.amount < curr.price.amount ? acc : curr));
|
|
||||||
this.addToBasket(result.price.id, 1);
|
|
||||||
this.alertMessage.display(
|
this.alertMessage.display(
|
||||||
interpolate(
|
interpolate(
|
||||||
gettext("Formula %(formula)s applied"),
|
gettext("Formula %(formula)s applied"),
|
||||||
{ formula: result.name },
|
{ formula: config.products[formula.result.toString()].name },
|
||||||
true,
|
true,
|
||||||
),
|
),
|
||||||
{ success: true },
|
{ success: true },
|
||||||
);
|
);
|
||||||
|
this.addToBasket(formula.result.toString(), 1);
|
||||||
},
|
},
|
||||||
|
|
||||||
getBasketSize() {
|
getBasketSize() {
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
import { showSaveFilePicker } from "native-file-system-adapter";
|
import { showSaveFilePicker } from "native-file-system-adapter";
|
||||||
import type TomSelect from "tom-select";
|
import type TomSelect from "tom-select";
|
||||||
import { paginated } from "#core:utils/api";
|
import { paginated } from "#core:utils/api.ts";
|
||||||
import { csv } from "#core:utils/csv";
|
import { csv } from "#core:utils/csv.ts";
|
||||||
import { getCurrentUrlParams, History, updateQueryString } from "#core:utils/history";
|
import {
|
||||||
import type { NestedKeyOf } from "#core:utils/types";
|
getCurrentUrlParams,
|
||||||
|
History,
|
||||||
|
updateQueryString,
|
||||||
|
} from "#core:utils/history.ts";
|
||||||
|
import type { NestedKeyOf } from "#core:utils/types.ts";
|
||||||
import {
|
import {
|
||||||
type ProductSchema,
|
type ProductSchema,
|
||||||
type ProductSearchProductsDetailedData,
|
type ProductSearchProductsDetailedData,
|
||||||
@@ -16,9 +20,6 @@ type GroupedProducts = Record<ProductType, ProductSchema[]>;
|
|||||||
const defaultPageSize = 100;
|
const defaultPageSize = 100;
|
||||||
const defaultPage = 1;
|
const defaultPage = 1;
|
||||||
|
|
||||||
// biome-ignore lint/style/useNamingConvention: api is snake case
|
|
||||||
type ProductWithPriceSchema = ProductSchema & { selling_price: string };
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Keys of the properties to include in the CSV.
|
* Keys of the properties to include in the CSV.
|
||||||
*/
|
*/
|
||||||
@@ -33,7 +34,7 @@ const csvColumns = [
|
|||||||
"purchase_price",
|
"purchase_price",
|
||||||
"selling_price",
|
"selling_price",
|
||||||
"archived",
|
"archived",
|
||||||
] as NestedKeyOf<ProductWithPriceSchema>[];
|
] as NestedKeyOf<ProductSchema>[];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Title of the csv columns.
|
* Title of the csv columns.
|
||||||
@@ -174,16 +175,7 @@ document.addEventListener("alpine:init", () => {
|
|||||||
this.nbPages > 1
|
this.nbPages > 1
|
||||||
? await paginated(productSearchProductsDetailed, this.getQueryParams())
|
? await paginated(productSearchProductsDetailed, this.getQueryParams())
|
||||||
: Object.values<ProductSchema[]>(this.products).flat();
|
: Object.values<ProductSchema[]>(this.products).flat();
|
||||||
// CSV cannot represent nested data
|
const content = csv.stringify(products, {
|
||||||
// so we create a row for each price of each product.
|
|
||||||
const productsWithPrice: ProductWithPriceSchema[] = products.flatMap(
|
|
||||||
(product: ProductSchema) =>
|
|
||||||
product.prices.map((price) =>
|
|
||||||
// biome-ignore lint/style/useNamingConvention: API is snake_case
|
|
||||||
Object.assign(product, { selling_price: price.amount }),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const content = csv.stringify(productsWithPrice, {
|
|
||||||
columns: csvColumns,
|
columns: csvColumns,
|
||||||
titleRow: csvColumnTitles,
|
titleRow: csvColumnTitles,
|
||||||
});
|
});
|
||||||
|
|||||||
+5
-10
@@ -2,7 +2,7 @@ export type ErrorMessage = string;
|
|||||||
|
|
||||||
export interface InitialFormData {
|
export interface InitialFormData {
|
||||||
/* Used to refill the form when the backend raises an error */
|
/* Used to refill the form when the backend raises an error */
|
||||||
id?: keyof Record<string, CounterItem>;
|
id?: keyof Record<string, Product>;
|
||||||
quantity?: number;
|
quantity?: number;
|
||||||
errors?: string[];
|
errors?: string[];
|
||||||
}
|
}
|
||||||
@@ -15,22 +15,17 @@ export interface ProductFormula {
|
|||||||
export interface CounterConfig {
|
export interface CounterConfig {
|
||||||
customerBalance: number;
|
customerBalance: number;
|
||||||
customerId: number;
|
customerId: number;
|
||||||
products: Record<string, CounterItem>;
|
products: Record<string, Product>;
|
||||||
formulas: ProductFormula[];
|
formulas: ProductFormula[];
|
||||||
formInitial: InitialFormData[];
|
formInitial: InitialFormData[];
|
||||||
cancelUrl: string;
|
cancelUrl: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Price {
|
export interface Product {
|
||||||
id: number;
|
id: string;
|
||||||
amount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CounterItem {
|
|
||||||
productId: number;
|
|
||||||
price: Price;
|
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
price: number;
|
||||||
hasTrayPrice: boolean;
|
hasTrayPrice: boolean;
|
||||||
quantityForTrayPrice: number;
|
quantityForTrayPrice: number;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,7 +57,7 @@
|
|||||||
</table>
|
</table>
|
||||||
<br>
|
<br>
|
||||||
{% if is_paginated %}
|
{% if is_paginated %}
|
||||||
{{ paginate_jinja(request, page_obj, paginator) }}
|
{{ paginate_jinja(page_obj, paginator) }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% else %}
|
{% else %}
|
||||||
{% trans %}There is no cash register summary in this website.{% endtrans %}
|
{% trans %}There is no cash register summary in this website.{% endtrans %}
|
||||||
|
|||||||
@@ -6,10 +6,10 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block additional_css %}
|
{% block additional_css %}
|
||||||
<link rel="stylesheet" href="{{ static('counter/css/counter-click.scss') }}">
|
<link rel="stylesheet" type="text/css" href="{{ static('counter/css/counter-click.scss') }}" defer></link>
|
||||||
<link rel="stylesheet" href="{{ static('bundled/core/components/ajax-select-index.css') }}">
|
<link rel="stylesheet" type="text/css" href="{{ static('bundled/core/components/ajax-select-index.css') }}" defer></link>
|
||||||
<link rel="stylesheet" href="{{ static('core/components/ajax-select.scss') }}">
|
<link rel="stylesheet" type="text/css" href="{{ static('core/components/ajax-select.scss') }}" defer></link>
|
||||||
<link rel="stylesheet" href="{{ static('core/components/tabs.scss') }}">
|
<link rel="stylesheet" type="text/css" href="{{ static('core/components/tabs.scss') }}" defer></link>
|
||||||
<link rel="stylesheet" href="{{ static("core/components/card.scss") }}">
|
<link rel="stylesheet" href="{{ static("core/components/card.scss") }}">
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -65,10 +65,10 @@
|
|||||||
<option value="FIN">{% trans %}Confirm (FIN){% endtrans %}</option>
|
<option value="FIN">{% trans %}Confirm (FIN){% endtrans %}</option>
|
||||||
<option value="ANN">{% trans %}Cancel (ANN){% endtrans %}</option>
|
<option value="ANN">{% trans %}Cancel (ANN){% endtrans %}</option>
|
||||||
</optgroup>
|
</optgroup>
|
||||||
{%- for category, prices in categories.items() -%}
|
{%- for category in categories.keys() -%}
|
||||||
<optgroup label="{{ category }}">
|
<optgroup label="{{ category }}">
|
||||||
{%- for price in prices -%}
|
{%- for product in categories[category] -%}
|
||||||
<option value="{{ price.id }}">{{ price.full_label }}</option>
|
<option value="{{ product.id }}">{{ product }}</option>
|
||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
</optgroup>
|
</optgroup>
|
||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
@@ -103,25 +103,24 @@
|
|||||||
</div>
|
</div>
|
||||||
<ul>
|
<ul>
|
||||||
<li x-show="getBasketSize() === 0">{% trans %}This basket is empty{% endtrans %}</li>
|
<li x-show="getBasketSize() === 0">{% trans %}This basket is empty{% endtrans %}</li>
|
||||||
<template x-for="(item, index) in Object.values(basket)" :key="item.product.price.id">
|
<template x-for="(item, index) in Object.values(basket)" :key="item.product.id">
|
||||||
<li>
|
<li>
|
||||||
<template x-for="error in item.errors">
|
<template x-for="error in item.errors">
|
||||||
<div class="alert alert-red" x-text="error">
|
<div class="alert alert-red" x-text="error">
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<button @click.prevent="addToBasket(item.product.price.id, -1)">-</button>
|
<button @click.prevent="addToBasket(item.product.id, -1)">-</button>
|
||||||
<span class="quantity" x-text="item.quantity"></span>
|
<span class="quantity" x-text="item.quantity"></span>
|
||||||
<button @click.prevent="addToBasket(item.product.price.id, 1)">+</button>
|
<button @click.prevent="addToBasket(item.product.id, 1)">+</button>
|
||||||
|
|
||||||
<span x-text="item.product.name"></span> :
|
<span x-text="item.product.name"></span> :
|
||||||
<span x-text="item.sum().toLocaleString(undefined, { minimumFractionDigits: 2 })">€</span>
|
<span x-text="item.sum().toLocaleString(undefined, { minimumFractionDigits: 2 })">€</span>
|
||||||
<span x-show="item.getBonusQuantity() > 0"
|
<span x-show="item.getBonusQuantity() > 0" x-text="`${item.getBonusQuantity()} x P`"></span>
|
||||||
x-text="`${item.getBonusQuantity()} x P`"></span>
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
class="remove-item"
|
class="remove-item"
|
||||||
@click.prevent="removeFromBasket(item.product.price.id)"
|
@click.prevent="removeFromBasket(item.product.id)"
|
||||||
><i class="fa fa-trash-can delete-action"></i></button>
|
><i class="fa fa-trash-can delete-action"></i></button>
|
||||||
|
|
||||||
<input
|
<input
|
||||||
@@ -134,9 +133,9 @@
|
|||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
type="hidden"
|
type="hidden"
|
||||||
:value="item.product.price.id"
|
:value="item.product.id"
|
||||||
:id="`id_form-${index}-price_id`"
|
:id="`id_form-${index}-id`"
|
||||||
:name="`form-${index}-price_id`"
|
:name="`form-${index}-id`"
|
||||||
required
|
required
|
||||||
readonly
|
readonly
|
||||||
>
|
>
|
||||||
@@ -202,30 +201,30 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="products">
|
<div id="products">
|
||||||
{% if not prices %}
|
{% if not products %}
|
||||||
<div class="alert alert-red">
|
<div class="alert alert-red">
|
||||||
{% trans %}No products available on this counter for this user{% endtrans %}
|
{% trans %}No products available on this counter for this user{% endtrans %}
|
||||||
</div>
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<ui-tab-group>
|
<ui-tab-group>
|
||||||
{% for category, prices in categories.items() -%}
|
{% for category in categories.keys() -%}
|
||||||
<ui-tab title="{{ category }}" {% if loop.index == 1 -%}active{%- endif -%}>
|
<ui-tab title="{{ category }}" {% if loop.index == 1 -%}active{%- endif -%}>
|
||||||
<h5 class="margin-bottom">{{ category }}</h5>
|
<h5 class="margin-bottom">{{ category }}</h5>
|
||||||
<div class="row gap-2x">
|
<div class="row gap-2x">
|
||||||
{% for price in prices -%}
|
{% for product in categories[category] -%}
|
||||||
<button class="card shadow" @click="addToBasket('{{ price.id }}', 1)">
|
<button class="card shadow" @click="addToBasket('{{ product.id }}', 1)">
|
||||||
<img
|
<img
|
||||||
class="card-image"
|
class="card-image"
|
||||||
alt="image de {{ price.full_label }}"
|
alt="image de {{ product.name }}"
|
||||||
{% if price.product.icon %}
|
{% if product.icon %}
|
||||||
src="{{ price.product.icon.url }}"
|
src="{{ product.icon.url }}"
|
||||||
{% else %}
|
{% else %}
|
||||||
src="{{ static('core/img/na.gif') }}"
|
src="{{ static('core/img/na.gif') }}"
|
||||||
{% endif %}
|
{% endif %}
|
||||||
/>
|
/>
|
||||||
<span class="card-content">
|
<span class="card-content">
|
||||||
<strong class="card-title">{{ price.full_label }}</strong>
|
<strong class="card-title">{{ product.name }}</strong>
|
||||||
<p>{{ price.amount }} €<br>{{ price.product.code }}</p>
|
<p>{{ product.price }} €<br>{{ product.code }}</p>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
{%- endfor %}
|
{%- endfor %}
|
||||||
@@ -242,14 +241,13 @@
|
|||||||
{{ super() }}
|
{{ super() }}
|
||||||
<script>
|
<script>
|
||||||
const products = {
|
const products = {
|
||||||
{%- for price in prices -%}
|
{%- for product in products -%}
|
||||||
{{ price.id }}: {
|
{{ product.id }}: {
|
||||||
productId: {{ price.product_id }},
|
id: "{{ product.id }}",
|
||||||
price: { id: "{{ price.id }}", amount: {{ price.amount }} },
|
name: "{{ product.name }}",
|
||||||
code: "{{ price.product.code }}",
|
price: {{ product.price }},
|
||||||
name: "{{ price.full_label }}",
|
hasTrayPrice: {{ product.tray | tojson }},
|
||||||
hasTrayPrice: {{ price.product.tray | tojson }},
|
quantityForTrayPrice: {{ product.QUANTITY_FOR_TRAY_PRICE }},
|
||||||
quantityForTrayPrice: {{ price.product.QUANTITY_FOR_TRAY_PRICE }},
|
|
||||||
},
|
},
|
||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -49,10 +49,14 @@
|
|||||||
<strong class="card-title">{{ formula.result.name }}</strong>
|
<strong class="card-title">{{ formula.result.name }}</strong>
|
||||||
<p>
|
<p>
|
||||||
{% for p in formula.products.all() %}
|
{% for p in formula.products.all() %}
|
||||||
<i>{{ p.name }} ({{ p.code }})</i>
|
<i>{{ p.code }} ({{ p.selling_price }} €)</i>
|
||||||
{% if not loop.last %}+{% endif %}
|
{% if not loop.last %}+{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</p>
|
</p>
|
||||||
|
<p>
|
||||||
|
{{ formula.result.selling_price }} €
|
||||||
|
({% trans %}instead of{% endtrans %} {{ formula.max_selling_price}} €)
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{% if user.has_perm("counter.delete_productformula") %}
|
{% if user.has_perm("counter.delete_productformula") %}
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -1,87 +1,5 @@
|
|||||||
{% extends "core/base.jinja" %}
|
{% extends "core/base.jinja" %}
|
||||||
|
|
||||||
{% block additional_js %}
|
|
||||||
<script type="module" src="{{ static("bundled/core/dynamic-formset-index.ts") }}"></script>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
||||||
{% macro action_form(form) %}
|
|
||||||
<fieldset x-data="{action: '{{ form.task.initial }}'}">
|
|
||||||
{{ form.non_field_errors() }}
|
|
||||||
<div class="row gap-2x margin-bottom">
|
|
||||||
<div>
|
|
||||||
{{ form.task.errors }}
|
|
||||||
{{ form.task.label_tag() }}
|
|
||||||
{{ form.task|add_attr("x-model=action") }}
|
|
||||||
</div>
|
|
||||||
<div>{{ form.trigger_at.as_field_group() }}</div>
|
|
||||||
</div>
|
|
||||||
<div x-show="action==='counter.tasks.change_counters'" class="margin-bottom">
|
|
||||||
{{ form.counters.as_field_group() }}
|
|
||||||
</div>
|
|
||||||
{%- if form.DELETE -%}
|
|
||||||
<div class="row gap">
|
|
||||||
{{ form.DELETE.as_field_group() }}
|
|
||||||
</div>
|
|
||||||
{%- else -%}
|
|
||||||
<button
|
|
||||||
class="btn btn-grey"
|
|
||||||
@click.prevent="removeForm($event.target.closest('fieldset'))"
|
|
||||||
>
|
|
||||||
<i class="fa fa-minus"></i>{% trans %}Remove this action{% endtrans %}
|
|
||||||
</button>
|
|
||||||
{%- endif -%}
|
|
||||||
{%- for field in form.hidden_fields() -%}
|
|
||||||
{{ field }}
|
|
||||||
{%- endfor -%}
|
|
||||||
<hr />
|
|
||||||
</fieldset>
|
|
||||||
{% endmacro %}
|
|
||||||
|
|
||||||
|
|
||||||
{% macro price_form(form) %}
|
|
||||||
<fieldset>
|
|
||||||
{{ form.non_field_errors() }}
|
|
||||||
<div class="form-group row gap-2x">
|
|
||||||
<div>{{ form.amount.as_field_group() }}</div>
|
|
||||||
<div>
|
|
||||||
{{ form.label.errors }}
|
|
||||||
<label for="{{ form.label.id_for_label }}">{{ form.label.label }}</label>
|
|
||||||
{{ form.label }}
|
|
||||||
<span class="helptext">{{ form.label.help_text }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="grow">{{ form.groups.as_field_group() }}</div>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<div>
|
|
||||||
{{ form.is_always_shown.errors }}
|
|
||||||
<div class="row gap">
|
|
||||||
{{ form.is_always_shown }}
|
|
||||||
<label for="{{ form.is_always_shown.id_for_label }}">{{ form.is_always_shown.label }}</label>
|
|
||||||
</div>
|
|
||||||
<span class="helptext">{{ form.is_always_shown.help_text }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{%- if form.DELETE -%}
|
|
||||||
<div class="form-group row gap">
|
|
||||||
{{ form.DELETE.as_field_group() }}
|
|
||||||
</div>
|
|
||||||
{%- else -%}
|
|
||||||
<br>
|
|
||||||
<button
|
|
||||||
class="btn btn-grey"
|
|
||||||
@click.prevent="removeForm($event.target.closest('fieldset').parentElement)"
|
|
||||||
>
|
|
||||||
<i class="fa fa-minus"></i> {% trans %}Remove price{% endtrans %}
|
|
||||||
</button>
|
|
||||||
{%- endif -%}
|
|
||||||
{%- for field in form.hidden_fields() -%}
|
|
||||||
{{ field }}
|
|
||||||
{%- endfor -%}
|
|
||||||
</fieldset>
|
|
||||||
<hr class="margin-bottom">
|
|
||||||
{% endmacro %}
|
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{% if object %}
|
{% if object %}
|
||||||
<h2>{% trans name=object %}Edit product {{ name }}{% endtrans %}</h2>
|
<h2>{% trans name=object %}Edit product {{ name }}{% endtrans %}</h2>
|
||||||
@@ -92,54 +10,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
<form method="post" enctype="multipart/form-data">
|
<form method="post" enctype="multipart/form-data">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{{ form.non_field_errors() }}
|
{{ form.as_p() }}
|
||||||
<fieldset class="row gap">
|
|
||||||
<div>{{ form.name.as_field_group() }}</div>
|
|
||||||
<div>{{ form.code.as_field_group() }}</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset>
|
|
||||||
<div class="form-group">{{ form.description.as_field_group() }}</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="row gap">
|
|
||||||
<div>{{ form.club.as_field_group() }}</div>
|
|
||||||
<div>{{ form.product_type.as_field_group() }}</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset><div>{{ form.icon.as_field_group() }}</div></fieldset>
|
|
||||||
<fieldset><div>{{ form.purchase_price.as_field_group() }}</div></fieldset>
|
|
||||||
<fieldset>
|
|
||||||
<div>{{ form.limit_age.as_field_group() }}</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset>
|
|
||||||
<div class="row gap">
|
|
||||||
{{ form.tray }}
|
|
||||||
<div>
|
|
||||||
{{ form.tray.label_tag() }}
|
|
||||||
<span class="helptext">{{ form.tray.help_text }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset><div>{{ form.counters.as_field_group() }}</div></fieldset>
|
|
||||||
|
|
||||||
<h3 class="margin-bottom">{% trans %}Prices{% endtrans %}</h3>
|
|
||||||
|
|
||||||
<div x-data="dynamicFormSet({ prefix: '{{ form.price_formset.prefix }}' })">
|
|
||||||
{{ form.price_formset.management_form }}
|
|
||||||
<div x-ref="formContainer">
|
|
||||||
{%- for form in form.price_formset.forms -%}
|
|
||||||
<div>
|
|
||||||
{{ price_form(form) }}
|
|
||||||
</div>
|
|
||||||
{%- endfor -%}
|
|
||||||
</div>
|
|
||||||
<template x-ref="formTemplate">
|
|
||||||
<div>
|
|
||||||
{{ price_form(form.price_formset.empty_form) }}
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<button class="btn btn-grey" @click.prevent="addForm()">
|
|
||||||
<i class="fa fa-plus"></i> {% trans %}Add a price{% endtrans %}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<br />
|
<br />
|
||||||
|
|
||||||
@@ -154,21 +25,34 @@
|
|||||||
</em>
|
</em>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div x-data="dynamicFormSet({ prefix: '{{ form.action_formset.prefix }}' })" class="margin-bottom">
|
{{ form.action_formset.management_form }}
|
||||||
{{ form.action_formset.management_form }}
|
{%- for action_form in form.action_formset.forms -%}
|
||||||
<div x-ref="formContainer">
|
<fieldset x-data="{action: '{{ action_form.task.initial }}'}">
|
||||||
{%- for f in form.action_formset.forms -%}
|
{{ action_form.non_field_errors() }}
|
||||||
{{ action_form(f) }}
|
<div class="row gap-2x margin-bottom">
|
||||||
|
<div>
|
||||||
|
{{ action_form.task.errors }}
|
||||||
|
{{ action_form.task.label_tag() }}
|
||||||
|
{{ action_form.task|add_attr("x-model=action") }}
|
||||||
|
</div>
|
||||||
|
<div>{{ action_form.trigger_at.as_field_group() }}</div>
|
||||||
|
</div>
|
||||||
|
<div x-show="action==='counter.tasks.change_counters'" class="margin-bottom">
|
||||||
|
{{ action_form.counters.as_field_group() }}
|
||||||
|
</div>
|
||||||
|
{%- if action_form.DELETE -%}
|
||||||
|
<div class="row gap">
|
||||||
|
{{ action_form.DELETE.as_field_group() }}
|
||||||
|
</div>
|
||||||
|
{%- endif -%}
|
||||||
|
{%- for field in action_form.hidden_fields() -%}
|
||||||
|
{{ field }}
|
||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
</div>
|
</fieldset>
|
||||||
<template x-ref="formTemplate">
|
{%- if not loop.last -%}
|
||||||
{{ action_form(form.action_formset.empty_form) }}
|
<hr class="margin-bottom">
|
||||||
</template>
|
{%- endif -%}
|
||||||
<button @click.prevent="addForm()" class="btn btn-grey">
|
{%- endfor -%}
|
||||||
<i class="fa fa-plus"></i>{% trans %}Add action{% endtrans %}
|
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="row gap margin-bottom">{{ form.archived.as_field_group() }}</div>
|
|
||||||
<p><input class="btn btn-blue" type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -108,7 +108,7 @@
|
|||||||
</template>
|
</template>
|
||||||
<span class="card-content">
|
<span class="card-content">
|
||||||
<strong class="card-title" x-text="`${p.name} (${p.code})`"></strong>
|
<strong class="card-title" x-text="`${p.name} (${p.code})`"></strong>
|
||||||
<p x-text="`${p.prices.map((p) => p.amount).join(' – ')} €`"></p>
|
<p x-text="`${p.selling_price} €`"></p>
|
||||||
</span>
|
</span>
|
||||||
</a>
|
</a>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
{%- endfor %}
|
{%- endfor %}
|
||||||
</table>
|
</table>
|
||||||
{% if is_paginated %}
|
{% if is_paginated %}
|
||||||
{{ paginate_jinja(request, page_obj, paginator) }}
|
{{ paginate_jinja(page_obj, paginator) }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{%- endblock %}
|
{%- endblock %}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from counter.forms import (
|
|||||||
ScheduledProductActionForm,
|
ScheduledProductActionForm,
|
||||||
ScheduledProductActionFormSet,
|
ScheduledProductActionFormSet,
|
||||||
)
|
)
|
||||||
from counter.models import Product, ProductType, ScheduledProductAction
|
from counter.models import Product, ScheduledProductAction
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -47,19 +47,18 @@ def test_create_actions_alongside_product():
|
|||||||
form = ProductForm(
|
form = ProductForm(
|
||||||
data={
|
data={
|
||||||
"name": "foo",
|
"name": "foo",
|
||||||
"product_type": ProductType.objects.first(),
|
"description": "bar",
|
||||||
|
"product_type": product.product_type_id,
|
||||||
"club": product.club_id,
|
"club": product.club_id,
|
||||||
"code": "FOO",
|
"code": "FOO",
|
||||||
"purchase_price": 1.0,
|
"purchase_price": 1.0,
|
||||||
"selling_price": 1.0,
|
"selling_price": 1.0,
|
||||||
"special_selling_price": 1.0,
|
"special_selling_price": 1.0,
|
||||||
"limit_age": 0,
|
"limit_age": 0,
|
||||||
"price-TOTAL_FORMS": "0",
|
"form-TOTAL_FORMS": "2",
|
||||||
"price-INITIAL_FORMS": "0",
|
"form-INITIAL_FORMS": "0",
|
||||||
"action-TOTAL_FORMS": "1",
|
"form-0-task": "counter.tasks.archive_product",
|
||||||
"action-INITIAL_FORMS": "0",
|
"form-0-trigger_at": trigger_at,
|
||||||
"action-0-task": "counter.tasks.archive_product",
|
|
||||||
"action-0-trigger_at": trigger_at,
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
assert form.is_valid()
|
assert form.is_valid()
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import pytest
|
|||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.models import Permission, make_password
|
from django.contrib.auth.models import Permission, make_password
|
||||||
|
from django.core.cache import cache
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.shortcuts import resolve_url
|
from django.shortcuts import resolve_url
|
||||||
from django.test import Client, TestCase
|
from django.test import Client, TestCase
|
||||||
@@ -31,15 +32,15 @@ from model_bakery import baker
|
|||||||
from model_bakery.recipe import Recipe
|
from model_bakery.recipe import Recipe
|
||||||
from pytest_django.asserts import assertRedirects
|
from pytest_django.asserts import assertRedirects
|
||||||
|
|
||||||
from club.models import ClubRole, Membership
|
from club.models import Membership
|
||||||
from core.baker_recipes import board_user, subscriber_user, very_old_subscriber_user
|
from core.baker_recipes import board_user, subscriber_user, very_old_subscriber_user
|
||||||
from core.models import BanGroup, Group, User
|
from core.models import BanGroup, User
|
||||||
from counter.baker_recipes import price_recipe, product_recipe, sale_recipe
|
from counter.baker_recipes import product_recipe, sale_recipe
|
||||||
from counter.models import (
|
from counter.models import (
|
||||||
Counter,
|
Counter,
|
||||||
Customer,
|
Customer,
|
||||||
Permanency,
|
Permanency,
|
||||||
ProductType,
|
Product,
|
||||||
Refilling,
|
Refilling,
|
||||||
ReturnableProduct,
|
ReturnableProduct,
|
||||||
Selling,
|
Selling,
|
||||||
@@ -87,7 +88,7 @@ class TestFullClickBase(TestCase):
|
|||||||
Membership,
|
Membership,
|
||||||
start_date=now() - timedelta(days=30),
|
start_date=now() - timedelta(days=30),
|
||||||
club=cls.club_counter.club,
|
club=cls.club_counter.club,
|
||||||
role=baker.make(ClubRole, club=cls.club_counter.club, is_board=True),
|
role=settings.SITH_CLUB_ROLES_ID["Board member"],
|
||||||
user=cls.club_admin,
|
user=cls.club_admin,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -203,7 +204,7 @@ class TestRefilling(TestFullClickBase):
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class BasketItem:
|
class BasketItem:
|
||||||
price_id: int | None = None
|
id: int | None = None
|
||||||
quantity: int | None = None
|
quantity: int | None = None
|
||||||
|
|
||||||
def to_form(self, index: int) -> dict[str, str]:
|
def to_form(self, index: int) -> dict[str, str]:
|
||||||
@@ -235,59 +236,38 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
cls.banned_counter_customer.ban_groups.add(
|
cls.banned_counter_customer.ban_groups.add(
|
||||||
BanGroup.objects.get(pk=settings.SITH_GROUP_BANNED_COUNTER_ID)
|
BanGroup.objects.get(pk=settings.SITH_GROUP_BANNED_COUNTER_ID)
|
||||||
)
|
)
|
||||||
subscriber_group = Group.objects.get(id=settings.SITH_GROUP_SUBSCRIBERS_ID)
|
|
||||||
old_subscriber_group = Group.objects.get(
|
|
||||||
id=settings.SITH_GROUP_OLD_SUBSCRIBERS_ID
|
|
||||||
)
|
|
||||||
_product_recipe = product_recipe.extend(product_type=baker.make(ProductType))
|
|
||||||
|
|
||||||
cls.gift = price_recipe.make(
|
cls.gift = product_recipe.make(
|
||||||
amount=-1.5, groups=[subscriber_group], product=_product_recipe.make()
|
selling_price="-1.5",
|
||||||
|
special_selling_price="-1.5",
|
||||||
)
|
)
|
||||||
cls.beer = price_recipe.make(
|
cls.beer = product_recipe.make(
|
||||||
groups=[subscriber_group],
|
limit_age=18, selling_price=1.5, special_selling_price=1
|
||||||
amount=1.5,
|
|
||||||
product=_product_recipe.make(limit_age=18),
|
|
||||||
)
|
)
|
||||||
cls.beer_tap = price_recipe.make(
|
cls.beer_tap = product_recipe.make(
|
||||||
groups=[subscriber_group],
|
limit_age=18, tray=True, selling_price=1.5, special_selling_price=1
|
||||||
amount=1.5,
|
|
||||||
product=_product_recipe.make(limit_age=18, tray=True),
|
|
||||||
)
|
)
|
||||||
cls.snack = price_recipe.make(
|
cls.snack = product_recipe.make(
|
||||||
groups=[subscriber_group, old_subscriber_group],
|
limit_age=0, selling_price=1.5, special_selling_price=1
|
||||||
amount=1.5,
|
|
||||||
product=_product_recipe.make(limit_age=0),
|
|
||||||
)
|
)
|
||||||
cls.stamps = price_recipe.make(
|
cls.stamps = product_recipe.make(
|
||||||
groups=[subscriber_group],
|
limit_age=0, selling_price=1.5, special_selling_price=1
|
||||||
amount=1.5,
|
|
||||||
product=_product_recipe.make(limit_age=0),
|
|
||||||
)
|
)
|
||||||
ReturnableProduct.objects.all().delete()
|
ReturnableProduct.objects.all().delete()
|
||||||
cls.cons = price_recipe.make(
|
cls.cons = baker.make(Product, selling_price=1)
|
||||||
amount=1, groups=[subscriber_group], product=_product_recipe.make()
|
cls.dcons = baker.make(Product, selling_price=-1)
|
||||||
)
|
|
||||||
cls.dcons = price_recipe.make(
|
|
||||||
amount=-1, groups=[subscriber_group], product=_product_recipe.make()
|
|
||||||
)
|
|
||||||
baker.make(
|
baker.make(
|
||||||
ReturnableProduct,
|
ReturnableProduct,
|
||||||
product=cls.cons.product,
|
product=cls.cons,
|
||||||
returned_product=cls.dcons.product,
|
returned_product=cls.dcons,
|
||||||
max_return=3,
|
max_return=3,
|
||||||
)
|
)
|
||||||
|
|
||||||
cls.counter.products.add(
|
cls.counter.products.add(
|
||||||
cls.gift.product,
|
cls.gift, cls.beer, cls.beer_tap, cls.snack, cls.cons, cls.dcons
|
||||||
cls.beer.product,
|
|
||||||
cls.beer_tap.product,
|
|
||||||
cls.snack.product,
|
|
||||||
cls.cons.product,
|
|
||||||
cls.dcons.product,
|
|
||||||
)
|
)
|
||||||
cls.other_counter.products.add(cls.snack.product)
|
cls.other_counter.products.add(cls.snack)
|
||||||
cls.club_counter.products.add(cls.stamps.product)
|
cls.club_counter.products.add(cls.stamps)
|
||||||
|
|
||||||
def login_in_bar(self, barmen: User | None = None):
|
def login_in_bar(self, barmen: User | None = None):
|
||||||
used_barman = barmen if barmen is not None else self.barmen
|
used_barman = barmen if barmen is not None else self.barmen
|
||||||
@@ -305,7 +285,10 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
) -> HttpResponse:
|
) -> HttpResponse:
|
||||||
used_counter = counter if counter is not None else self.counter
|
used_counter = counter if counter is not None else self.counter
|
||||||
used_client = client if client is not None else self.client
|
used_client = client if client is not None else self.client
|
||||||
data = {"form-TOTAL_FORMS": str(len(basket)), "form-INITIAL_FORMS": "0"}
|
data = {
|
||||||
|
"form-TOTAL_FORMS": str(len(basket)),
|
||||||
|
"form-INITIAL_FORMS": "0",
|
||||||
|
}
|
||||||
for index, item in enumerate(basket):
|
for index, item in enumerate(basket):
|
||||||
data.update(item.to_form(index))
|
data.update(item.to_form(index))
|
||||||
return used_client.post(
|
return used_client.post(
|
||||||
@@ -348,22 +331,32 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
res = self.submit_basket(
|
res = self.submit_basket(
|
||||||
self.customer, [BasketItem(self.beer.id, 2), BasketItem(self.snack.id, 1)]
|
self.customer, [BasketItem(self.beer.id, 2), BasketItem(self.snack.id, 1)]
|
||||||
)
|
)
|
||||||
self.assertRedirects(res, self.counter.get_absolute_url())
|
assert res.status_code == 302
|
||||||
|
|
||||||
assert self.updated_amount(self.customer) == Decimal("5.5")
|
assert self.updated_amount(self.customer) == Decimal("5.5")
|
||||||
|
|
||||||
|
# Test barmen special price
|
||||||
|
|
||||||
|
force_refill_user(self.barmen, 10)
|
||||||
|
|
||||||
|
assert (
|
||||||
|
self.submit_basket(self.barmen, [BasketItem(self.beer.id, 1)])
|
||||||
|
).status_code == 302
|
||||||
|
|
||||||
|
assert self.updated_amount(self.barmen) == Decimal(9)
|
||||||
|
|
||||||
def test_click_tray_price(self):
|
def test_click_tray_price(self):
|
||||||
force_refill_user(self.customer, 20)
|
force_refill_user(self.customer, 20)
|
||||||
self.login_in_bar(self.barmen)
|
self.login_in_bar(self.barmen)
|
||||||
|
|
||||||
# Not applying tray price
|
# Not applying tray price
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.beer_tap.id, 2)])
|
res = self.submit_basket(self.customer, [BasketItem(self.beer_tap.id, 2)])
|
||||||
self.assertRedirects(res, self.counter.get_absolute_url())
|
assert res.status_code == 302
|
||||||
assert self.updated_amount(self.customer) == Decimal(17)
|
assert self.updated_amount(self.customer) == Decimal(17)
|
||||||
|
|
||||||
# Applying tray price
|
# Applying tray price
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.beer_tap.id, 7)])
|
res = self.submit_basket(self.customer, [BasketItem(self.beer_tap.id, 7)])
|
||||||
self.assertRedirects(res, self.counter.get_absolute_url())
|
assert res.status_code == 302
|
||||||
assert self.updated_amount(self.customer) == Decimal(8)
|
assert self.updated_amount(self.customer) == Decimal(8)
|
||||||
|
|
||||||
def test_click_alcool_unauthorized(self):
|
def test_click_alcool_unauthorized(self):
|
||||||
@@ -484,8 +477,7 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
BasketItem(None, 1),
|
BasketItem(None, 1),
|
||||||
BasketItem(self.beer.id, None),
|
BasketItem(self.beer.id, None),
|
||||||
]:
|
]:
|
||||||
res = self.submit_basket(self.customer, [item])
|
assert self.submit_basket(self.customer, [item]).status_code == 200
|
||||||
assert res.status_code == 200
|
|
||||||
assert self.updated_amount(self.customer) == Decimal(10)
|
assert self.updated_amount(self.customer) == Decimal(10)
|
||||||
|
|
||||||
def test_click_not_enough_money(self):
|
def test_click_not_enough_money(self):
|
||||||
@@ -514,30 +506,29 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
res = self.submit_basket(
|
res = self.submit_basket(
|
||||||
self.customer, [BasketItem(self.beer.id, 1), BasketItem(self.gift.id, 1)]
|
self.customer, [BasketItem(self.beer.id, 1), BasketItem(self.gift.id, 1)]
|
||||||
)
|
)
|
||||||
self.assertRedirects(res, self.counter.get_absolute_url())
|
assert res.status_code == 302
|
||||||
|
|
||||||
assert self.updated_amount(self.customer) == 0
|
assert self.updated_amount(self.customer) == 0
|
||||||
|
|
||||||
def test_recordings(self):
|
def test_recordings(self):
|
||||||
force_refill_user(self.customer, self.cons.amount * 3)
|
force_refill_user(self.customer, self.cons.selling_price * 3)
|
||||||
self.login_in_bar(self.barmen)
|
self.login_in_bar(self.barmen)
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.cons.id, 3)])
|
res = self.submit_basket(self.customer, [BasketItem(self.cons.id, 3)])
|
||||||
assert res.status_code == 302
|
assert res.status_code == 302
|
||||||
assert self.updated_amount(self.customer) == 0
|
assert self.updated_amount(self.customer) == 0
|
||||||
assert list(
|
assert list(
|
||||||
self.customer.customer.return_balances.values("returnable", "balance")
|
self.customer.customer.return_balances.values("returnable", "balance")
|
||||||
) == [{"returnable": self.cons.product.cons.id, "balance": 3}]
|
) == [{"returnable": self.cons.cons.id, "balance": 3}]
|
||||||
|
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.dcons.id, 3)])
|
res = self.submit_basket(self.customer, [BasketItem(self.dcons.id, 3)])
|
||||||
assert res.status_code == 302
|
assert res.status_code == 302
|
||||||
assert self.updated_amount(self.customer) == self.dcons.amount * -3
|
assert self.updated_amount(self.customer) == self.dcons.selling_price * -3
|
||||||
|
|
||||||
res = self.submit_basket(
|
res = self.submit_basket(
|
||||||
self.customer,
|
self.customer, [BasketItem(self.dcons.id, self.dcons.dcons.max_return)]
|
||||||
[BasketItem(self.dcons.id, self.dcons.product.dcons.max_return)],
|
|
||||||
)
|
)
|
||||||
# from now on, the user amount should not change
|
# from now on, the user amount should not change
|
||||||
expected_amount = self.dcons.amount * (-3 - self.dcons.product.dcons.max_return)
|
expected_amount = self.dcons.selling_price * (-3 - self.dcons.dcons.max_return)
|
||||||
assert res.status_code == 302
|
assert res.status_code == 302
|
||||||
assert self.updated_amount(self.customer) == expected_amount
|
assert self.updated_amount(self.customer) == expected_amount
|
||||||
|
|
||||||
@@ -554,57 +545,48 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
def test_recordings_when_negative(self):
|
def test_recordings_when_negative(self):
|
||||||
sale_recipe.make(
|
sale_recipe.make(
|
||||||
customer=self.customer.customer,
|
customer=self.customer.customer,
|
||||||
product=self.dcons.product,
|
product=self.dcons,
|
||||||
unit_price=self.dcons.amount,
|
unit_price=self.dcons.selling_price,
|
||||||
quantity=10,
|
quantity=10,
|
||||||
)
|
)
|
||||||
self.customer.customer.update_returnable_balance()
|
self.customer.customer.update_returnable_balance()
|
||||||
self.login_in_bar(self.barmen)
|
self.login_in_bar(self.barmen)
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.dcons.id, 1)])
|
res = self.submit_basket(self.customer, [BasketItem(self.dcons.id, 1)])
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
assert self.updated_amount(self.customer) == self.dcons.amount * -10
|
assert self.updated_amount(self.customer) == self.dcons.selling_price * -10
|
||||||
|
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.cons.id, 3)])
|
res = self.submit_basket(self.customer, [BasketItem(self.cons.id, 3)])
|
||||||
assert res.status_code == 302
|
assert res.status_code == 302
|
||||||
assert (
|
assert (
|
||||||
self.updated_amount(self.customer)
|
self.updated_amount(self.customer)
|
||||||
== self.dcons.amount * -10 - self.cons.amount * 3
|
== self.dcons.selling_price * -10 - self.cons.selling_price * 3
|
||||||
)
|
)
|
||||||
|
|
||||||
res = self.submit_basket(self.customer, [BasketItem(self.beer.id, 1)])
|
res = self.submit_basket(self.customer, [BasketItem(self.beer.id, 1)])
|
||||||
assert res.status_code == 302
|
assert res.status_code == 302
|
||||||
assert (
|
assert (
|
||||||
self.updated_amount(self.customer)
|
self.updated_amount(self.customer)
|
||||||
== self.dcons.amount * -10 - self.cons.amount * 3 - self.beer.amount
|
== self.dcons.selling_price * -10
|
||||||
|
- self.cons.selling_price * 3
|
||||||
|
- self.beer.selling_price
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_no_fetch_archived_product(self):
|
def test_no_fetch_archived_product(self):
|
||||||
counter = baker.make(Counter)
|
counter = baker.make(Counter)
|
||||||
group = baker.make(Group)
|
|
||||||
customer = baker.make(Customer)
|
customer = baker.make(Customer)
|
||||||
group.users.add(customer.user)
|
product_recipe.make(archived=True, counters=[counter])
|
||||||
_product_recipe = product_recipe.extend(
|
unarchived_products = product_recipe.make(
|
||||||
counters=[counter], product_type=baker.make(ProductType)
|
archived=False, counters=[counter], _quantity=3
|
||||||
)
|
)
|
||||||
price_recipe.make(
|
customer_products = counter.get_products_for(customer)
|
||||||
_quantity=2,
|
assert unarchived_products == customer_products
|
||||||
product=iter(_product_recipe.make(archived=True, _quantity=2)),
|
|
||||||
groups=[group],
|
|
||||||
)
|
|
||||||
unarchived_prices = price_recipe.make(
|
|
||||||
_quantity=2,
|
|
||||||
product=iter(_product_recipe.make(archived=False, _quantity=2)),
|
|
||||||
groups=[group],
|
|
||||||
)
|
|
||||||
customer_prices = counter.get_prices_for(customer)
|
|
||||||
assert unarchived_prices == customer_prices
|
|
||||||
|
|
||||||
|
|
||||||
class TestCounterStats(TestCase):
|
class TestCounterStats(TestCase):
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpTestData(cls):
|
def setUpTestData(cls):
|
||||||
cls.users = subscriber_user.make(_quantity=4)
|
cls.users = subscriber_user.make(_quantity=4)
|
||||||
product = price_recipe.make(amount=1).product
|
product = product_recipe.make(selling_price=1)
|
||||||
cls.counter = baker.make(
|
cls.counter = baker.make(
|
||||||
Counter, type=["BAR"], sellers=cls.users[:4], products=[product]
|
Counter, type=["BAR"], sellers=cls.users[:4], products=[product]
|
||||||
)
|
)
|
||||||
@@ -800,15 +782,12 @@ class TestClubCounterClickAccess(TestCase):
|
|||||||
"counter:click",
|
"counter:click",
|
||||||
kwargs={"counter_id": cls.counter.id, "user_id": cls.customer.id},
|
kwargs={"counter_id": cls.counter.id, "user_id": cls.customer.id},
|
||||||
)
|
)
|
||||||
cls.board_role, cls.member_role = baker.make(
|
|
||||||
ClubRole,
|
|
||||||
club=cls.counter.club,
|
|
||||||
is_board=iter([True, False]),
|
|
||||||
_quantity=2,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
cls.user = subscriber_user.make()
|
cls.user = subscriber_user.make()
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
cache.clear()
|
||||||
|
|
||||||
def test_anonymous(self):
|
def test_anonymous(self):
|
||||||
res = self.client.get(self.click_url)
|
res = self.client.get(self.click_url)
|
||||||
assert res.status_code == 403
|
assert res.status_code == 403
|
||||||
@@ -818,17 +797,13 @@ class TestClubCounterClickAccess(TestCase):
|
|||||||
res = self.client.get(self.click_url)
|
res = self.client.get(self.click_url)
|
||||||
assert res.status_code == 403
|
assert res.status_code == 403
|
||||||
# being a member of the club, without being in the board, isn't enough
|
# being a member of the club, without being in the board, isn't enough
|
||||||
baker.make(
|
baker.make(Membership, club=self.counter.club, user=self.user, role=1)
|
||||||
Membership, club=self.counter.club, user=self.user, role=self.member_role
|
|
||||||
)
|
|
||||||
res = self.client.get(self.click_url)
|
res = self.client.get(self.click_url)
|
||||||
assert res.status_code == 403
|
assert res.status_code == 403
|
||||||
|
|
||||||
def test_board_member(self):
|
def test_board_member(self):
|
||||||
"""By default, board members should be able to click on office counters"""
|
"""By default, board members should be able to click on office counters"""
|
||||||
baker.make(
|
baker.make(Membership, club=self.counter.club, user=self.user, role=3)
|
||||||
Membership, club=self.counter.club, user=self.user, role=self.board_role
|
|
||||||
)
|
|
||||||
self.client.force_login(self.user)
|
self.client.force_login(self.user)
|
||||||
res = self.client.get(self.click_url)
|
res = self.client.get(self.click_url)
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
@@ -843,9 +818,7 @@ class TestClubCounterClickAccess(TestCase):
|
|||||||
def test_both_barman_and_board_member(self):
|
def test_both_barman_and_board_member(self):
|
||||||
"""If the user is barman and board member, he should be authorized as well."""
|
"""If the user is barman and board member, he should be authorized as well."""
|
||||||
self.counter.sellers.add(self.user)
|
self.counter.sellers.add(self.user)
|
||||||
baker.make(
|
baker.make(Membership, club=self.counter.club, user=self.user, role=3)
|
||||||
Membership, club=self.counter.club, user=self.user, role=self.board_role
|
|
||||||
)
|
|
||||||
self.client.force_login(self.user)
|
self.client.force_login(self.user)
|
||||||
res = self.client.get(self.click_url)
|
res = self.client.get(self.click_url)
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
|
|||||||
@@ -1,132 +1,13 @@
|
|||||||
from django.conf import settings
|
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from django.urls import reverse
|
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
|
|
||||||
from club.models import Membership
|
from club.models import Membership
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import Group, User
|
from core.models import User
|
||||||
from counter.baker_recipes import product_recipe
|
from counter.baker_recipes import product_recipe
|
||||||
from counter.forms import CounterEditForm
|
from counter.forms import CounterEditForm
|
||||||
from counter.models import Counter, CounterSellers
|
from counter.models import Counter
|
||||||
|
|
||||||
|
|
||||||
class TestEditCounterSellers(TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpTestData(cls):
|
|
||||||
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)
|
|
||||||
cls.regular_barmen = users[:2]
|
|
||||||
cls.tmp_barmen = users[2:4]
|
|
||||||
cls.not_barmen = users[4:]
|
|
||||||
CounterSellers.objects.bulk_create(
|
|
||||||
[
|
|
||||||
*baker.prepare(
|
|
||||||
CounterSellers,
|
|
||||||
counter=cls.counter,
|
|
||||||
user=iter(cls.regular_barmen),
|
|
||||||
is_regular=True,
|
|
||||||
_quantity=len(cls.regular_barmen),
|
|
||||||
),
|
|
||||||
*baker.prepare(
|
|
||||||
CounterSellers,
|
|
||||||
counter=cls.counter,
|
|
||||||
user=iter(cls.tmp_barmen),
|
|
||||||
is_regular=False,
|
|
||||||
_quantity=len(cls.tmp_barmen),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
cls.operator = baker.make(
|
|
||||||
User, groups=[Group.objects.get(id=settings.SITH_GROUP_COUNTER_ADMIN_ID)]
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_view_ok(self):
|
|
||||||
url = reverse("counter:admin", kwargs={"counter_id": self.counter.id})
|
|
||||||
self.client.force_login(self.operator)
|
|
||||||
res = self.client.get(url)
|
|
||||||
assert res.status_code == 200
|
|
||||||
res = self.client.post(
|
|
||||||
url,
|
|
||||||
data={
|
|
||||||
"sellers_regular": [u.id for u in self.regular_barmen],
|
|
||||||
"sellers_temporary": [u.id for u in self.tmp_barmen],
|
|
||||||
"products": [p.id for p in self.products],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
self.assertRedirects(res, url)
|
|
||||||
|
|
||||||
def test_add_barmen(self):
|
|
||||||
form = CounterEditForm(
|
|
||||||
data={
|
|
||||||
"sellers_regular": [*self.regular_barmen, self.not_barmen[0]],
|
|
||||||
"sellers_temporary": [*self.tmp_barmen, self.not_barmen[1]],
|
|
||||||
"products": self.products,
|
|
||||||
},
|
|
||||||
instance=self.counter,
|
|
||||||
user=self.operator,
|
|
||||||
)
|
|
||||||
assert form.is_valid()
|
|
||||||
form.save()
|
|
||||||
assert set(self.counter.sellers.filter(countersellers__is_regular=True)) == {
|
|
||||||
*self.regular_barmen,
|
|
||||||
self.not_barmen[0],
|
|
||||||
}
|
|
||||||
assert set(self.counter.sellers.filter(countersellers__is_regular=False)) == {
|
|
||||||
*self.tmp_barmen,
|
|
||||||
self.not_barmen[1],
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_barman_change_status(self):
|
|
||||||
"""Test when a barman goes from temporary to regular"""
|
|
||||||
form = CounterEditForm(
|
|
||||||
data={
|
|
||||||
"sellers_regular": [*self.regular_barmen, self.tmp_barmen[0]],
|
|
||||||
"sellers_temporary": [*self.tmp_barmen[1:]],
|
|
||||||
"products": self.products,
|
|
||||||
},
|
|
||||||
instance=self.counter,
|
|
||||||
user=self.operator,
|
|
||||||
)
|
|
||||||
assert form.is_valid()
|
|
||||||
form.save()
|
|
||||||
assert set(self.counter.sellers.filter(countersellers__is_regular=True)) == {
|
|
||||||
*self.regular_barmen,
|
|
||||||
self.tmp_barmen[0],
|
|
||||||
}
|
|
||||||
assert set(
|
|
||||||
self.counter.sellers.filter(countersellers__is_regular=False)
|
|
||||||
) == set(self.tmp_barmen[1:])
|
|
||||||
|
|
||||||
def test_barman_duplicate(self):
|
|
||||||
"""Test that a barman cannot be regular and temporary at the same time."""
|
|
||||||
form = CounterEditForm(
|
|
||||||
data={
|
|
||||||
"sellers_regular": [*self.regular_barmen, self.not_barmen[0]],
|
|
||||||
"sellers_temporary": [*self.tmp_barmen, self.not_barmen[0]],
|
|
||||||
"products": self.products,
|
|
||||||
},
|
|
||||||
instance=self.counter,
|
|
||||||
user=self.operator,
|
|
||||||
)
|
|
||||||
assert not form.is_valid()
|
|
||||||
assert form.errors == {
|
|
||||||
"__all__": [
|
|
||||||
"Un utilisateur ne peut pas être un barman "
|
|
||||||
"régulier et temporaire en même temps, "
|
|
||||||
"mais les utilisateurs suivants ont été définis "
|
|
||||||
f"comme les deux : {self.not_barmen[0].get_display_name()}"
|
|
||||||
],
|
|
||||||
}
|
|
||||||
assert set(self.counter.sellers.filter(countersellers__is_regular=True)) == set(
|
|
||||||
self.regular_barmen
|
|
||||||
)
|
|
||||||
assert set(
|
|
||||||
self.counter.sellers.filter(countersellers__is_regular=False)
|
|
||||||
) == set(self.tmp_barmen)
|
|
||||||
|
|
||||||
|
|
||||||
class TestEditCounterProducts(TestCase):
|
class TestEditCounterProducts(TestCase):
|
||||||
|
|||||||
@@ -3,13 +3,14 @@ import string
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from django.conf import settings
|
||||||
from django.contrib.auth.base_user import make_password
|
from django.contrib.auth.base_user import make_password
|
||||||
from django.test import Client, TestCase
|
from django.test import Client, TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
|
|
||||||
from club.models import ClubRole, Membership
|
from club.models import Membership
|
||||||
from core.baker_recipes import board_user, subscriber_user
|
from core.baker_recipes import board_user, subscriber_user
|
||||||
from core.models import User
|
from core.models import User
|
||||||
from counter.baker_recipes import product_recipe, refill_recipe, sale_recipe
|
from counter.baker_recipes import product_recipe, refill_recipe, sale_recipe
|
||||||
@@ -41,12 +42,11 @@ class TestStudentCard(TestCase):
|
|||||||
cls.counter.sellers.add(cls.barmen)
|
cls.counter.sellers.add(cls.barmen)
|
||||||
|
|
||||||
cls.club_counter = baker.make(Counter)
|
cls.club_counter = baker.make(Counter)
|
||||||
role = baker.make(ClubRole, club=cls.club_counter.club, is_board=True)
|
|
||||||
baker.make(
|
baker.make(
|
||||||
Membership,
|
Membership,
|
||||||
start_date=now() - timedelta(days=30),
|
start_date=now() - timedelta(days=30),
|
||||||
club=cls.club_counter.club,
|
club=cls.club_counter.club,
|
||||||
role=role,
|
role=settings.SITH_CLUB_ROLES_ID["Board member"],
|
||||||
user=cls.club_admin,
|
user=cls.club_admin,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -341,7 +341,7 @@ def test_update_balance():
|
|||||||
def test_update_returnable_balance():
|
def test_update_returnable_balance():
|
||||||
ReturnableProduct.objects.all().delete()
|
ReturnableProduct.objects.all().delete()
|
||||||
customer = baker.make(Customer)
|
customer = baker.make(Customer)
|
||||||
products = product_recipe.make(_quantity=4, _bulk_create=True)
|
products = product_recipe.make(selling_price=0, _quantity=4, _bulk_create=True)
|
||||||
returnables = [
|
returnables = [
|
||||||
baker.make(
|
baker.make(
|
||||||
ReturnableProduct, product=products[0], returned_product=products[1]
|
ReturnableProduct, product=products[0], returned_product=products[1]
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user