mirror of
https://github.com/ae-utbm/sith.git
synced 2026-03-14 15:45:02 +00:00
Compare commits
13 Commits
user-white
...
room-reser
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
753b219c53 | ||
|
|
bb36707c29 | ||
|
|
5d78529702 | ||
|
|
ed51f75601 | ||
|
|
08d19fed59 | ||
|
|
a97fc7a29a | ||
|
|
9645c7fead | ||
|
|
0f71e220c4 | ||
|
|
d6639f4ff5 | ||
|
|
d07aeb5e63 | ||
|
|
056afbebda | ||
|
|
e7eb3562ad | ||
| 77995dcc0f |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -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:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
},
|
},
|
||||||
"files": {
|
"files": {
|
||||||
"ignoreUnknown": false,
|
"ignoreUnknown": false,
|
||||||
"includes": ["**/static/**", "vite.config.mts"]
|
"includes": ["**/static/**"]
|
||||||
},
|
},
|
||||||
"formatter": {
|
"formatter": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
|
|||||||
29
club/api.py
29
club/api.py
@@ -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 CanAccessLookup, 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")
|
||||||
@@ -44,22 +38,3 @@ class ClubController(ControllerBase):
|
|||||||
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")
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -40,8 +40,6 @@ class ClubProfileSchema(ModelSchema):
|
|||||||
|
|
||||||
|
|
||||||
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", "role", "description"]
|
fields = ["start_date", "end_date", "role", "description"]
|
||||||
@@ -55,13 +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", "role", "description"]
|
|
||||||
|
|
||||||
club: SimpleClubSchema
|
|
||||||
|
|||||||
@@ -1,25 +1,63 @@
|
|||||||
{% extends "core/base.jinja" %}
|
{% extends "core/base.jinja" %}
|
||||||
|
{% from "reservation/macros.jinja" import room_detail %}
|
||||||
|
|
||||||
|
{% block additional_css %}
|
||||||
|
<link rel="stylesheet" href="{{ static("core/components/card.scss") }}">
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h3>{% trans %}Club tools{% endtrans %}</h3>
|
<h3>{% trans %}Club tools{% endtrans %} ({{ club.name }})</h3>
|
||||||
<div>
|
<div>
|
||||||
<h4>{% trans %}Communication:{% endtrans %}</h4>
|
<h4>{% trans %}Communication:{% endtrans %}</h4>
|
||||||
<ul>
|
<ul>
|
||||||
<li> <a href="{{ url('com:news_new') }}?club={{ object.id }}">{% trans %}Create a news{% endtrans %}</a></li>
|
<li>
|
||||||
<li> <a href="{{ url('com:weekmail_article') }}?club={{ object.id }}">{% trans %}Post in the Weekmail{% endtrans %}</a></li>
|
<a href="{{ url('com:news_new') }}?club={{ object.id }}">
|
||||||
|
{% trans %}Create a news{% endtrans %}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="{{ url('com:weekmail_article') }}?club={{ object.id }}">
|
||||||
|
{% trans %}Post in the Weekmail{% endtrans %}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
{% if object.trombi %}
|
{% if object.trombi %}
|
||||||
<li> <a href="{{ url('trombi:detail', trombi_id=object.trombi.id) }}">{% trans %}Edit Trombi{% endtrans %}</a></li>
|
<li>
|
||||||
|
<a href="{{ url('trombi:detail', trombi_id=object.trombi.id) }}">
|
||||||
|
{% trans %}Edit Trombi{% endtrans %}</a>
|
||||||
|
</li>
|
||||||
{% else %}
|
{% else %}
|
||||||
<li><a href="{{ url('trombi:create', club_id=object.id) }}">{% trans %}New Trombi{% endtrans %}</a></li>
|
<li><a href="{{ url('trombi:create', club_id=object.id) }}">{% trans %}New Trombi{% endtrans %}</a></li>
|
||||||
<li><a href="{{ url('club:poster_list', club_id=object.id) }}">{% trans %}Posters{% endtrans %}</a></li>
|
<li><a href="{{ url('club:poster_list', club_id=object.id) }}">{% trans %}Posters{% endtrans %}</a></li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</ul>
|
</ul>
|
||||||
|
<h4>{% trans %}Reservable rooms{% endtrans %}</h4>
|
||||||
|
<a
|
||||||
|
href="{{ url("reservation:room_create") }}?club={{ object.id }}"
|
||||||
|
class="btn btn-blue"
|
||||||
|
>
|
||||||
|
{% trans %}Add a room{% endtrans %}
|
||||||
|
</a>
|
||||||
|
{%- if reservable_rooms|length > 0 -%}
|
||||||
|
<ul class="card-group">
|
||||||
|
{%- for room in reservable_rooms -%}
|
||||||
|
{{ room_detail(
|
||||||
|
room,
|
||||||
|
can_edit=user.can_edit(room),
|
||||||
|
can_delete=request.user.has_perm("reservation.delete_room")
|
||||||
|
) }}
|
||||||
|
{%- endfor -%}
|
||||||
|
</ul>
|
||||||
|
{%- else -%}
|
||||||
|
<p>
|
||||||
|
{% trans %}This club manages no reservable room{% endtrans %}
|
||||||
|
</p>
|
||||||
|
{%- endif -%}
|
||||||
<h4>{% trans %}Counters:{% endtrans %}</h4>
|
<h4>{% trans %}Counters:{% endtrans %}</h4>
|
||||||
<ul>
|
<ul>
|
||||||
{% for c in object.counters.filter(type="OFFICE") %}
|
{% for counter in counters %}
|
||||||
<li>{{ c }}:
|
<li>{{ counter }}:
|
||||||
<a href="{{ url('counter:details', counter_id=c.id) }}">View</a>
|
<a href="{{ url('counter:details', counter_id=counter.id) }}">View</a>
|
||||||
<a href="{{ url('counter:admin', counter_id=c.id) }}">Edit</a>
|
<a href="{{ url('counter:admin', counter_id=counter.id) }}">Edit</a>
|
||||||
</li>
|
</li>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -1,50 +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, 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)
|
|
||||||
)
|
|
||||||
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
|
|
||||||
@@ -260,6 +260,12 @@ class ClubToolsView(ClubTabsMixin, CanEditMixin, DetailView):
|
|||||||
template_name = "club/club_tools.jinja"
|
template_name = "club/club_tools.jinja"
|
||||||
current_tab = "tools"
|
current_tab = "tools"
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
return super().get_context_data(**kwargs) | {
|
||||||
|
"reservable_rooms": list(self.object.reservable_rooms.all()),
|
||||||
|
"counters": list(self.object.counters.filter(type="OFFICE")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class ClubAddMembersFragment(
|
class ClubAddMembersFragment(
|
||||||
FragmentMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView
|
FragmentMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView
|
||||||
|
|||||||
@@ -81,7 +81,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
#links_content {
|
#links_content {
|
||||||
overflow: auto;
|
|
||||||
box-shadow: $shadow-color 1px 1px 1px;
|
box-shadow: $shadow-color 1px 1px 1px;
|
||||||
min-height: 20em;
|
min-height: 20em;
|
||||||
padding-bottom: 1em;
|
padding-bottom: 1em;
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
{% extends "core/base.jinja" %}
|
{% extends "core/base.jinja" %}
|
||||||
{% from "com/macros.jinja" import news_moderation_alert %}
|
{% from "com/macros.jinja" import news_moderation_alert %}
|
||||||
|
|
||||||
|
{% block title %}AE UTBM{% endblock %}
|
||||||
|
|
||||||
{% block additional_css %}
|
{% block additional_css %}
|
||||||
<link rel="stylesheet" href="{{ static('com/css/news-list.scss') }}">
|
<link rel="stylesheet" href="{{ static('com/css/news-list.scss') }}">
|
||||||
<link rel="stylesheet" href="{{ static('com/components/ics-calendar.scss') }}">
|
<link rel="stylesheet" href="{{ static('core/components/calendar.scss') }}">
|
||||||
|
|
||||||
{# Atom feed discovery, not really css but also goes there #}
|
{# Atom feed discovery, not really css but also goes there #}
|
||||||
<link rel="alternate" type="application/rss+xml" title="{% trans %}News feed{% endtrans %}" href="{{ url("com:news_feed") }}">
|
<link rel="alternate" type="application/rss+xml" title="{% trans %}News feed{% endtrans %}" href="{{ url("com:news_feed") }}">
|
||||||
@@ -213,6 +215,12 @@
|
|||||||
<i class="fa-solid fa-magnifying-glass fa-xl"></i>
|
<i class="fa-solid fa-magnifying-glass fa-xl"></i>
|
||||||
<a href="{{ url("matmat:search") }}">{% trans %}Matmatronch{% endtrans %}</a>
|
<a href="{{ url("matmat:search") }}">{% trans %}Matmatronch{% endtrans %}</a>
|
||||||
</li>
|
</li>
|
||||||
|
{% if user.has_perm("reservation.view_reservationslot") %}
|
||||||
|
<li>
|
||||||
|
<i class="fa-solid fa-thumbtack fa-xl"></i>
|
||||||
|
<a href="{{ url("reservation:main") }}">{% trans %}Room reservation{% endtrans %}</a>
|
||||||
|
</li>
|
||||||
|
{% endif %}
|
||||||
<li>
|
<li>
|
||||||
<i class="fa-solid fa-check-to-slot fa-xl"></i>
|
<i class="fa-solid fa-check-to-slot fa-xl"></i>
|
||||||
<a href="{{ url("election:list") }}">{% trans %}Elections{% endtrans %}</a>
|
<a href="{{ url("election:list") }}">{% trans %}Elections{% endtrans %}</a>
|
||||||
|
|||||||
@@ -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,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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"]
|
||||||
|
|||||||
@@ -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
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -790,7 +790,11 @@ class Command(BaseCommand):
|
|||||||
|
|
||||||
subscribers = Group.objects.create(name="Cotisants")
|
subscribers = Group.objects.create(name="Cotisants")
|
||||||
subscribers.permissions.add(
|
subscribers.permissions.add(
|
||||||
*list(perms.filter(codename__in=["add_news", "add_uecomment"]))
|
*list(
|
||||||
|
perms.filter(
|
||||||
|
codename__in=["add_news", "add_uecomment", "view_reservationslot"]
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
old_subscribers = Group.objects.create(name="Anciens cotisants")
|
old_subscribers = Group.objects.create(name="Anciens cotisants")
|
||||||
old_subscribers.permissions.add(
|
old_subscribers.permissions.add(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import random
|
import random
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
from datetime import timezone as tz
|
from datetime import timezone as tz
|
||||||
|
from math import ceil
|
||||||
from typing import Iterator
|
from typing import Iterator
|
||||||
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
@@ -24,6 +25,7 @@ from counter.models import (
|
|||||||
)
|
)
|
||||||
from forum.models import Forum, ForumMessage, ForumTopic
|
from forum.models import Forum, ForumMessage, ForumTopic
|
||||||
from pedagogy.models import UE
|
from pedagogy.models import UE
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
from subscription.models import Subscription
|
from subscription.models import Subscription
|
||||||
|
|
||||||
|
|
||||||
@@ -41,45 +43,20 @@ class Command(BaseCommand):
|
|||||||
self.stdout.write("Creating users...")
|
self.stdout.write("Creating users...")
|
||||||
users = self.create_users()
|
users = self.create_users()
|
||||||
self.create_bans(random.sample(users, k=len(users) // 200)) # 0.5% of users
|
self.create_bans(random.sample(users, k=len(users) // 200)) # 0.5% of users
|
||||||
|
# len(subscribers) is approximately 480
|
||||||
subscribers = random.sample(users, k=int(0.8 * len(users)))
|
subscribers = random.sample(users, k=int(0.8 * len(users)))
|
||||||
self.stdout.write("Creating subscriptions...")
|
self.stdout.write("Creating subscriptions...")
|
||||||
self.create_subscriptions(subscribers)
|
self.create_subscriptions(subscribers)
|
||||||
self.stdout.write("Creating club memberships...")
|
self.stdout.write("Creating club memberships...")
|
||||||
users_qs = User.objects.filter(id__in=[s.id for s in subscribers])
|
self.create_club_memberships(subscribers)
|
||||||
subscribers_now = list(
|
self.stdout.write("Creating rooms and reservation...")
|
||||||
users_qs.annotate(
|
self.create_resources_and_reservations(random.sample(subscribers, k=40))
|
||||||
filter=Exists(
|
|
||||||
Subscription.objects.filter(
|
|
||||||
member_id=OuterRef("pk"), subscription_end__gte=now()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
old_subscribers = list(
|
|
||||||
users_qs.annotate(
|
|
||||||
filter=Exists(
|
|
||||||
Subscription.objects.filter(
|
|
||||||
member_id=OuterRef("pk"), subscription_end__lt=now()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.make_club(
|
|
||||||
Club.objects.get(id=settings.SITH_MAIN_CLUB_ID),
|
|
||||||
random.sample(subscribers_now, k=min(30, len(subscribers_now))),
|
|
||||||
random.sample(old_subscribers, k=min(60, len(old_subscribers))),
|
|
||||||
)
|
|
||||||
self.make_club(
|
|
||||||
Club.objects.get(name="Troll Penché"),
|
|
||||||
random.sample(subscribers_now, k=min(20, len(subscribers_now))),
|
|
||||||
random.sample(old_subscribers, k=min(80, len(old_subscribers))),
|
|
||||||
)
|
|
||||||
self.stdout.write("Creating uvs...")
|
self.stdout.write("Creating uvs...")
|
||||||
self.create_ues()
|
self.create_ues()
|
||||||
self.stdout.write("Creating products...")
|
self.stdout.write("Creating products...")
|
||||||
self.create_products()
|
self.create_products()
|
||||||
self.stdout.write("Creating sales and refills...")
|
self.stdout.write("Creating sales and refills...")
|
||||||
sellers = random.sample(list(User.objects.all()), 100)
|
sellers = list(User.objects.order_by("?")[:100])
|
||||||
self.create_sales(sellers)
|
self.create_sales(sellers)
|
||||||
self.stdout.write("Creating permanences...")
|
self.stdout.write("Creating permanences...")
|
||||||
self.create_permanences(sellers)
|
self.create_permanences(sellers)
|
||||||
@@ -214,6 +191,97 @@ class Command(BaseCommand):
|
|||||||
memberships = Membership.objects.bulk_create(memberships)
|
memberships = Membership.objects.bulk_create(memberships)
|
||||||
Membership._add_club_groups(memberships)
|
Membership._add_club_groups(memberships)
|
||||||
|
|
||||||
|
def create_club_memberships(self, users: list[User]):
|
||||||
|
users_qs = User.objects.filter(id__in=[s.id for s in users])
|
||||||
|
subscribers_now = list(
|
||||||
|
users_qs.annotate(
|
||||||
|
filter=Exists(
|
||||||
|
Subscription.objects.filter(
|
||||||
|
member_id=OuterRef("pk"), subscription_end__gte=now()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
old_subscribers = list(
|
||||||
|
users_qs.annotate(
|
||||||
|
filter=Exists(
|
||||||
|
Subscription.objects.filter(
|
||||||
|
member_id=OuterRef("pk"), subscription_end__lt=now()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.make_club(
|
||||||
|
Club.objects.get(id=settings.SITH_MAIN_CLUB_ID),
|
||||||
|
random.sample(subscribers_now, k=min(30, len(subscribers_now))),
|
||||||
|
random.sample(old_subscribers, k=min(60, len(old_subscribers))),
|
||||||
|
)
|
||||||
|
self.make_club(
|
||||||
|
Club.objects.get(name="Troll Penché"),
|
||||||
|
random.sample(subscribers_now, k=min(20, len(subscribers_now))),
|
||||||
|
random.sample(old_subscribers, k=min(80, len(old_subscribers))),
|
||||||
|
)
|
||||||
|
|
||||||
|
def create_resources_and_reservations(self, users: list[User]):
|
||||||
|
"""Generate reservable rooms and reservations slots for those rooms.
|
||||||
|
|
||||||
|
Contrary to the other data generator,
|
||||||
|
this one generates more data than what is expected on the real db.
|
||||||
|
"""
|
||||||
|
ae = Club.objects.get(id=settings.SITH_MAIN_CLUB_ID)
|
||||||
|
pdf = Club.objects.get(id=settings.SITH_PDF_CLUB_ID)
|
||||||
|
troll = Club.objects.get(name="Troll Penché")
|
||||||
|
rooms = [
|
||||||
|
Room(
|
||||||
|
name=name,
|
||||||
|
club=club,
|
||||||
|
location=location,
|
||||||
|
description=self.faker.text(100),
|
||||||
|
)
|
||||||
|
for name, club, location in [
|
||||||
|
("Champi", ae, "BELFORT"),
|
||||||
|
("Muzik", ae, "BELFORT"),
|
||||||
|
("Pôle Tech", ae, "BELFORT"),
|
||||||
|
("Jolly", troll, "BELFORT"),
|
||||||
|
("Cookut", pdf, "BELFORT"),
|
||||||
|
("Lucky", pdf, "BELFORT"),
|
||||||
|
("Potards", pdf, "SEVENANS"),
|
||||||
|
("Bureau AE", ae, "SEVENANS"),
|
||||||
|
]
|
||||||
|
]
|
||||||
|
rooms = Room.objects.bulk_create(rooms)
|
||||||
|
reservations = []
|
||||||
|
for room in rooms:
|
||||||
|
# how much people use this room.
|
||||||
|
# The higher the number, the more reservations exist,
|
||||||
|
# the smaller the interval between two slot is,
|
||||||
|
# and the more future reservations have already been made ahead of time
|
||||||
|
affluence = random.randint(2, 6)
|
||||||
|
slot_start = make_aware(self.faker.past_datetime("-5y").replace(minute=0))
|
||||||
|
generate_until = make_aware(
|
||||||
|
self.faker.future_datetime(timedelta(days=1) * affluence**2)
|
||||||
|
)
|
||||||
|
while slot_start < generate_until:
|
||||||
|
if slot_start.hour < 8:
|
||||||
|
# if a reservation would start in the middle of the night
|
||||||
|
# make it start the next morning instead
|
||||||
|
slot_start += timedelta(hours=10 - slot_start.hour)
|
||||||
|
duration = timedelta(minutes=15) * (1 + int(random.gammavariate(3, 2)))
|
||||||
|
reservations.append(
|
||||||
|
ReservationSlot(
|
||||||
|
room=room,
|
||||||
|
author=random.choice(users),
|
||||||
|
start_at=slot_start,
|
||||||
|
end_at=slot_start + duration,
|
||||||
|
created_at=slot_start - self.faker.time_delta("+7d"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
slot_start += duration + (
|
||||||
|
timedelta(minutes=15) * ceil(random.expovariate(affluence / 192))
|
||||||
|
)
|
||||||
|
reservations.sort(key=lambda slot: slot.created_at)
|
||||||
|
ReservationSlot.objects.bulk_create(reservations)
|
||||||
|
|
||||||
def create_ues(self):
|
def create_ues(self):
|
||||||
root = User.objects.get(username="root")
|
root = User.objects.get(username="root")
|
||||||
categories = ["CS", "TM", "OM", "QC", "EC"]
|
categories = ["CS", "TM", "OM", "QC", "EC"]
|
||||||
@@ -410,7 +478,7 @@ class Command(BaseCommand):
|
|||||||
Permanency.objects.bulk_create(perms)
|
Permanency.objects.bulk_create(perms)
|
||||||
|
|
||||||
def create_forums(self):
|
def create_forums(self):
|
||||||
forumers = random.sample(list(User.objects.all()), 100)
|
forumers = list(User.objects.order_by("?")[:100])
|
||||||
most_actives = random.sample(forumers, 10)
|
most_actives = random.sample(forumers, 10)
|
||||||
categories = list(Forum.objects.filter(is_category=True))
|
categories = list(Forum.objects.filter(is_category=True))
|
||||||
new_forums = [
|
new_forums = [
|
||||||
@@ -428,7 +496,7 @@ class Command(BaseCommand):
|
|||||||
for _ in range(100)
|
for _ in range(100)
|
||||||
]
|
]
|
||||||
ForumTopic.objects.bulk_create(new_topics)
|
ForumTopic.objects.bulk_create(new_topics)
|
||||||
topics = list(ForumTopic.objects.all())
|
topics = list(ForumTopic.objects.values_list("id", flat=True))
|
||||||
|
|
||||||
def get_author():
|
def get_author():
|
||||||
if random.random() > 0.5:
|
if random.random() > 0.5:
|
||||||
@@ -436,7 +504,7 @@ class Command(BaseCommand):
|
|||||||
return random.choice(forumers)
|
return random.choice(forumers)
|
||||||
|
|
||||||
messages = []
|
messages = []
|
||||||
for t in topics:
|
for topic_id in topics:
|
||||||
nb_messages = max(1, int(random.normalvariate(mu=90, sigma=50)))
|
nb_messages = max(1, int(random.normalvariate(mu=90, sigma=50)))
|
||||||
dates = sorted(
|
dates = sorted(
|
||||||
[
|
[
|
||||||
@@ -448,7 +516,7 @@ class Command(BaseCommand):
|
|||||||
messages.extend(
|
messages.extend(
|
||||||
[
|
[
|
||||||
ForumMessage(
|
ForumMessage(
|
||||||
topic=t,
|
topic_id=topic_id,
|
||||||
author=get_author(),
|
author=get_author(),
|
||||||
date=d,
|
date=d,
|
||||||
message="\n\n".join(
|
message="\n\n".join(
|
||||||
|
|||||||
@@ -1,24 +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(
|
|
||||||
help_text=(
|
|
||||||
"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",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -131,7 +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(Q(is_viewable=True) | Q(whitelisted_users=user))
|
return self.filter(is_viewable=True)
|
||||||
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)
|
||||||
@@ -279,15 +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=_(
|
|
||||||
"If this profile is hidden, "
|
|
||||||
"the users in this list will still be able to see it."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
||||||
|
|
||||||
objects = CustomUserManager()
|
objects = CustomUserManager()
|
||||||
@@ -365,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:
|
||||||
@@ -576,31 +563,10 @@ class User(AbstractUser):
|
|||||||
return 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):
|
||||||
@@ -1133,7 +1099,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
|
||||||
@@ -1407,7 +1376,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,9 +1,10 @@
|
|||||||
|
import { morph } from "@alpinejs/morph";
|
||||||
import sort from "@alpinejs/sort";
|
import sort from "@alpinejs/sort";
|
||||||
import Alpine from "alpinejs";
|
import Alpine from "alpinejs";
|
||||||
import { limitedChoices } from "#core:alpine/limited-choices.ts";
|
import { limitedChoices } from "#core:alpine/limited-choices.ts";
|
||||||
import { alpinePlugin as notificationPlugin } from "#core:utils/notifications.ts";
|
import { alpinePlugin as notificationPlugin } from "#core:utils/notifications.ts";
|
||||||
|
|
||||||
Alpine.plugin([sort, limitedChoices]);
|
Alpine.plugin([sort, morph, limitedChoices]);
|
||||||
Alpine.magic("notifications", notificationPlugin);
|
Alpine.magic("notifications", notificationPlugin);
|
||||||
window.Alpine = Alpine;
|
window.Alpine = Alpine;
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
|
|||||||
@@ -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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import htmx from "htmx.org";
|
import htmx from "htmx.org";
|
||||||
|
import "htmx-ext-alpine-morph";
|
||||||
|
|
||||||
document.body.addEventListener("htmx:beforeRequest", (event) => {
|
document.body.addEventListener("htmx:beforeRequest", (event) => {
|
||||||
event.detail.target.ariaBusy = true;
|
event.detail.target.ariaBusy = true;
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -16,16 +16,76 @@
|
|||||||
--event-details-padding: 20px;
|
--event-details-padding: 20px;
|
||||||
--event-details-border: 1px solid #EEEEEE;
|
--event-details-border: 1px solid #EEEEEE;
|
||||||
--event-details-border-radius: 4px;
|
--event-details-border-radius: 4px;
|
||||||
--event-details-box-shadow: 0px 6px 20px 4px rgb(0 0 0 / 16%);
|
--event-details-box-shadow: 0 6px 20px 4px rgb(0 0 0 / 16%);
|
||||||
--event-details-max-width: 600px;
|
--event-details-max-width: 600px;
|
||||||
--event-recurring-internal-color: #6f69cd;
|
--event-recurring-internal-color: #6f69cd;
|
||||||
--event-recurring-unpublished-color: orange;
|
--event-recurring-unpublished-color: orange;
|
||||||
}
|
}
|
||||||
|
|
||||||
ics-calendar {
|
ics-calendar,
|
||||||
|
room-scheduler {
|
||||||
border: none;
|
border: none;
|
||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
|
|
||||||
|
a.fc-col-header-cell-cushion,
|
||||||
|
a.fc-col-header-cell-cushion:hover {
|
||||||
|
color: black;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.fc-daygrid-day-number,
|
||||||
|
a.fc-daygrid-day-number:hover {
|
||||||
|
color: rgb(34, 34, 34);
|
||||||
|
}
|
||||||
|
|
||||||
|
td {
|
||||||
|
overflow: visible; // Show events on multiple days
|
||||||
|
}
|
||||||
|
|
||||||
|
td, th {
|
||||||
|
text-align: unset;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Reset from style.scss
|
||||||
|
table {
|
||||||
|
box-shadow: none;
|
||||||
|
border-radius: 0;
|
||||||
|
-moz-border-radius: 0;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset from style.scss
|
||||||
|
thead {
|
||||||
|
background-color: white;
|
||||||
|
color: black;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset from style.scss
|
||||||
|
tbody > tr {
|
||||||
|
&:nth-child(even):not(.highlight) {
|
||||||
|
background: white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.fc .fc-toolbar.fc-footer-toolbar {
|
||||||
|
margin-bottom: 0.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.text-copy,
|
||||||
|
button.text-copy:focus,
|
||||||
|
button.text-copy:hover {
|
||||||
|
background-color: #67AE6E !important;
|
||||||
|
transition: 500ms ease-in;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.text-copied,
|
||||||
|
button.text-copied:focus,
|
||||||
|
button.text-copied:hover {
|
||||||
|
transition: 500ms ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
ics-calendar {
|
||||||
#event-details {
|
#event-details {
|
||||||
z-index: 10;
|
z-index: 10;
|
||||||
max-width: 1151px;
|
max-width: 1151px;
|
||||||
@@ -62,31 +122,10 @@ ics-calendar {
|
|||||||
align-items: start;
|
align-items: start;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
background-color: var(--event-details-background-color);
|
background-color: var(--event-details-background-color);
|
||||||
margin-top: 0px;
|
margin-top: 0;
|
||||||
margin-bottom: 4px;
|
margin-bottom: 4px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
a.fc-col-header-cell-cushion,
|
|
||||||
a.fc-col-header-cell-cushion:hover {
|
|
||||||
color: black;
|
|
||||||
}
|
|
||||||
|
|
||||||
a.fc-daygrid-day-number,
|
|
||||||
a.fc-daygrid-day-number:hover {
|
|
||||||
color: rgb(34, 34, 34);
|
|
||||||
}
|
|
||||||
|
|
||||||
td {
|
|
||||||
overflow: visible; // Show events on multiple days
|
|
||||||
}
|
|
||||||
|
|
||||||
//Reset from style.scss
|
|
||||||
table {
|
|
||||||
box-shadow: none;
|
|
||||||
border-radius: 0px;
|
|
||||||
-moz-border-radius: 0px;
|
|
||||||
margin: 0px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset from style.scss
|
// Reset from style.scss
|
||||||
@@ -138,7 +177,6 @@ ics-calendar {
|
|||||||
.fc .fc-helpButton-button:hover {
|
.fc .fc-helpButton-button:hover {
|
||||||
background-color: rgba(20, 20, 20, 0.6);
|
background-color: rgba(20, 20, 20, 0.6);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
.tooltip.calendar-copy-tooltip {
|
.tooltip.calendar-copy-tooltip {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
@@ -16,6 +16,13 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.card-group {
|
||||||
|
display: flex;
|
||||||
|
gap: 15px;
|
||||||
|
margin-bottom: 30px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
.card {
|
.card {
|
||||||
background-color: $primary-neutral-light-color;
|
background-color: $primary-neutral-light-color;
|
||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
@@ -92,13 +99,23 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media screen and (max-width: 765px) {
|
@media screen and (max-width: 765px) {
|
||||||
@include row-layout
|
@include row-layout;
|
||||||
}
|
}
|
||||||
|
|
||||||
// When combined with card, card-row display the card in a row layout,
|
// When combined with card, card-row display the card in a row layout,
|
||||||
// whatever the size of the screen.
|
// whatever the size of the screen.
|
||||||
&.card-row {
|
&.card-row {
|
||||||
@include row-layout
|
@include row-layout;
|
||||||
|
|
||||||
|
&.card-row-m {
|
||||||
|
//width: 50%;
|
||||||
|
max-width: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.card-row-s {
|
||||||
|
//width: 33%;
|
||||||
|
max-width: 33%;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,9 @@
|
|||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
padding: 5px 10px;
|
padding: 5px 10px;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
white-space: nowrap;
|
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transition: opacity 500ms ease-out;
|
transition: opacity 500ms ease-out;
|
||||||
|
width: max-content;
|
||||||
white-space: normal;
|
white-space: normal;
|
||||||
|
|
||||||
left: 0;
|
left: 0;
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -399,12 +399,13 @@ 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)
|
||||||
@@ -417,12 +418,6 @@ class TestUserQuerySetViewableBy:
|
|||||||
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]}
|
assert set(viewable) == {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)
|
|
||||||
assert set(viewable) == {users[0], users[1], users[3]}
|
|
||||||
|
|
||||||
@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):
|
||||||
user = user_factory()
|
user = user_factory()
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ from core.views import (
|
|||||||
UserCreationView,
|
UserCreationView,
|
||||||
UserGodfathersTreeView,
|
UserGodfathersTreeView,
|
||||||
UserGodfathersView,
|
UserGodfathersView,
|
||||||
|
UserListView,
|
||||||
UserMeRedirect,
|
UserMeRedirect,
|
||||||
UserMiniView,
|
UserMiniView,
|
||||||
UserPreferencesView,
|
UserPreferencesView,
|
||||||
@@ -135,6 +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("user/", UserListView.as_view(), name="user_list"),
|
||||||
path(
|
path(
|
||||||
"user/me/<path:remaining_path>/",
|
"user/me/<path:remaining_path>/",
|
||||||
UserMeRedirect.as_view(),
|
UserMeRedirect.as_view(),
|
||||||
|
|||||||
@@ -40,9 +40,8 @@ from django.forms import (
|
|||||||
DateInput,
|
DateInput,
|
||||||
DateTimeInput,
|
DateTimeInput,
|
||||||
TextInput,
|
TextInput,
|
||||||
Widget,
|
|
||||||
)
|
)
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import localtime, now
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
@@ -100,8 +99,8 @@ class FutureDateTimeField(forms.DateTimeField):
|
|||||||
|
|
||||||
default_validators = [validate_future_timestamp]
|
default_validators = [validate_future_timestamp]
|
||||||
|
|
||||||
def widget_attrs(self, widget: Widget) -> dict[str, str]:
|
def widget_attrs(self, widget: forms.Widget) -> dict[str, str]:
|
||||||
return {"min": widget.format_value(now())}
|
return {"min": widget.format_value(localtime())}
|
||||||
|
|
||||||
|
|
||||||
# Forms
|
# Forms
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ class FragmentMixin(TemplateResponseMixin, ContextMixin):
|
|||||||
return render(
|
return render(
|
||||||
request,
|
request,
|
||||||
"app/template.jinja",
|
"app/template.jinja",
|
||||||
context={"fragment": fragment(request)
|
context={"fragment": fragment(request)}
|
||||||
}
|
}
|
||||||
|
|
||||||
# in urls.py
|
# in urls.py
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ from django.views.generic import (
|
|||||||
CreateView,
|
CreateView,
|
||||||
DeleteView,
|
DeleteView,
|
||||||
DetailView,
|
DetailView,
|
||||||
|
ListView,
|
||||||
RedirectView,
|
RedirectView,
|
||||||
TemplateView,
|
TemplateView,
|
||||||
)
|
)
|
||||||
@@ -403,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):
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ 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.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
|
||||||
@@ -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,7 +32,6 @@ 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,
|
||||||
@@ -172,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
|
||||||
@@ -213,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):
|
||||||
@@ -373,8 +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,
|
||||||
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"),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -551,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
|
||||||
@@ -747,26 +743,6 @@ class Counter(models.Model):
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class CounterSellers(models.Model):
|
|
||||||
"""Custom through model for the counter-sellers M2M relationship."""
|
|
||||||
|
|
||||||
counter = models.ForeignKey(Counter, on_delete=models.CASCADE)
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
|
||||||
is_regular = models.BooleanField(_("regular barman"), default=False)
|
|
||||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
|
||||||
|
|
||||||
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:
|
||||||
"""Annotate the Queryset with the total amount.
|
"""Annotate the Queryset with the total amount.
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ document.addEventListener("alpine:init", () => {
|
|||||||
|
|
||||||
checkFormulas() {
|
checkFormulas() {
|
||||||
const products = new Set(
|
const products = new Set(
|
||||||
Object.keys(this.basket).map((i: string) => Number.parseInt(i, 10)),
|
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));
|
||||||
|
|||||||
@@ -1,44 +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 %}
|
|
||||||
|
|
||||||
|
|
||||||
{% 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>
|
||||||
@@ -64,20 +25,34 @@
|
|||||||
</em>
|
</em>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div x-data="dynamicFormSet" class="margin-bottom">
|
|
||||||
{{ form.action_formset.management_form }}
|
{{ form.action_formset.management_form }}
|
||||||
<div x-ref="formContainer">
|
{%- for action_form in form.action_formset.forms -%}
|
||||||
{%- for f in form.action_formset.forms -%}
|
<fieldset x-data="{action: '{{ action_form.task.initial }}'}">
|
||||||
{{ action_form(f) }}
|
{{ action_form.non_field_errors() }}
|
||||||
|
<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>
|
|
||||||
<p><input class="btn btn-blue" type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -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):
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ from datetime import datetime, timedelta
|
|||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
|
||||||
from django.contrib.messages.views import SuccessMessageMixin
|
|
||||||
from django.core.exceptions import PermissionDenied
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.forms import CheckboxSelectMultiple
|
from django.forms import CheckboxSelectMultiple
|
||||||
@@ -59,9 +58,7 @@ class CounterListView(CounterAdminTabsMixin, CanViewMixin, ListView):
|
|||||||
current_tab = "counters"
|
current_tab = "counters"
|
||||||
|
|
||||||
|
|
||||||
class CounterEditView(
|
class CounterEditView(CounterAdminTabsMixin, UserPassesTestMixin, UpdateView):
|
||||||
CounterAdminTabsMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView
|
|
||||||
):
|
|
||||||
"""Edit a counter's main informations (for the counter's manager)."""
|
"""Edit a counter's main informations (for the counter's manager)."""
|
||||||
|
|
||||||
model = Counter
|
model = Counter
|
||||||
@@ -69,7 +66,6 @@ class CounterEditView(
|
|||||||
pk_url_kwarg = "counter_id"
|
pk_url_kwarg = "counter_id"
|
||||||
template_name = "core/edit.jinja"
|
template_name = "core/edit.jinja"
|
||||||
current_tab = "counters"
|
current_tab = "counters"
|
||||||
success_message = _("Counter update done")
|
|
||||||
|
|
||||||
def test_func(self):
|
def test_func(self):
|
||||||
if self.request.user.has_perm("counter.change_counter"):
|
if self.request.user.has_perm("counter.change_counter"):
|
||||||
|
|||||||
@@ -146,7 +146,7 @@
|
|||||||
<label for="{{ input_id }}">
|
<label for="{{ input_id }}">
|
||||||
{%- endif %}
|
{%- endif %}
|
||||||
<figure>
|
<figure>
|
||||||
{%- if user.can_view(candidature.user) %}
|
{%- if user.is_viewable %}
|
||||||
{% if candidature.user.profile_pict %}
|
{% if candidature.user.profile_pict %}
|
||||||
<img class="candidate__picture" src="{{ candidature.user.profile_pict.get_download_url() }}" alt="{% trans %}Profile{% endtrans %}">
|
<img class="candidate__picture" src="{{ candidature.user.profile_pict.get_download_url() }}" alt="{% trans %}Profile{% endtrans %}">
|
||||||
{% else %}
|
{% else %}
|
||||||
|
|||||||
@@ -6,8 +6,6 @@ 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 model_bakery.recipe import Recipe
|
|
||||||
from pytest_django.asserts import assertRedirects
|
|
||||||
|
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import Group, User
|
from core.models import Group, User
|
||||||
@@ -54,102 +52,6 @@ class TestElectionUpdateView(TestElection):
|
|||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
class TestElectionForm(TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpTestData(cls):
|
|
||||||
cls.election = baker.make(Election, end_date=now() + timedelta(days=1))
|
|
||||||
cls.group = baker.make(Group)
|
|
||||||
cls.election.vote_groups.add(cls.group)
|
|
||||||
cls.election.edit_groups.add(cls.group)
|
|
||||||
lists = baker.make(
|
|
||||||
ElectionList, election=cls.election, _quantity=2, _bulk_create=True
|
|
||||||
)
|
|
||||||
cls.roles = baker.make(
|
|
||||||
Role, election=cls.election, _quantity=2, _bulk_create=True
|
|
||||||
)
|
|
||||||
users = baker.make(User, _quantity=4, _bulk_create=True)
|
|
||||||
recipe = Recipe(Candidature)
|
|
||||||
cls.cand = [
|
|
||||||
recipe.prepare(role=cls.roles[0], user=users[0], election_list=lists[0]),
|
|
||||||
recipe.prepare(role=cls.roles[0], user=users[1], election_list=lists[1]),
|
|
||||||
recipe.prepare(role=cls.roles[1], user=users[2], election_list=lists[0]),
|
|
||||||
recipe.prepare(role=cls.roles[1], user=users[3], election_list=lists[1]),
|
|
||||||
]
|
|
||||||
Candidature.objects.bulk_create(cls.cand)
|
|
||||||
cls.vote_url = reverse("election:vote", kwargs={"election_id": cls.election.id})
|
|
||||||
cls.detail_url = reverse(
|
|
||||||
"election:detail", kwargs={"election_id": cls.election.id}
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_election_good_form(self):
|
|
||||||
postes = (self.roles[0].title, self.roles[1].title)
|
|
||||||
votes = [
|
|
||||||
{postes[0]: "", postes[1]: str(self.cand[2].id)},
|
|
||||||
{postes[0]: "", postes[1]: ""},
|
|
||||||
{postes[0]: str(self.cand[0].id), postes[1]: str(self.cand[2].id)},
|
|
||||||
{postes[0]: str(self.cand[0].id), postes[1]: str(self.cand[3].id)},
|
|
||||||
]
|
|
||||||
voters = subscriber_user.make(_quantity=len(votes), _bulk_create=True)
|
|
||||||
self.group.users.set(voters)
|
|
||||||
|
|
||||||
for voter, vote in zip(voters, votes, strict=True):
|
|
||||||
assert self.election.can_vote(voter)
|
|
||||||
self.client.force_login(voter)
|
|
||||||
response = self.client.post(self.vote_url, data=vote)
|
|
||||||
assertRedirects(response, self.detail_url)
|
|
||||||
|
|
||||||
assert set(self.election.voters.all()) == set(voters)
|
|
||||||
assert self.election.results == {
|
|
||||||
postes[0]: {
|
|
||||||
self.cand[0].user.username: {"percent": 50.0, "vote": 2},
|
|
||||||
self.cand[1].user.username: {"percent": 0.0, "vote": 0},
|
|
||||||
"blank vote": {"percent": 50.0, "vote": 2},
|
|
||||||
"total vote": 4,
|
|
||||||
},
|
|
||||||
postes[1]: {
|
|
||||||
self.cand[2].user.username: {"percent": 50.0, "vote": 2},
|
|
||||||
self.cand[3].user.username: {"percent": 25.0, "vote": 1},
|
|
||||||
"blank vote": {"percent": 25.0, "vote": 1},
|
|
||||||
"total vote": 4,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_election_bad_form(self):
|
|
||||||
postes = (self.roles[0].title, self.roles[1].title)
|
|
||||||
|
|
||||||
votes = [
|
|
||||||
{postes[0]: "", postes[1]: str(self.cand[0].id)}, # wrong candidate
|
|
||||||
{postes[0]: ""},
|
|
||||||
{
|
|
||||||
postes[0]: "0123456789", # unknow users
|
|
||||||
postes[1]: str(subscriber_user.make().id), # not a candidate
|
|
||||||
},
|
|
||||||
{},
|
|
||||||
]
|
|
||||||
voters = subscriber_user.make(_quantity=len(votes), _bulk_create=True)
|
|
||||||
self.group.users.set(voters)
|
|
||||||
|
|
||||||
for voter, vote in zip(voters, votes, strict=True):
|
|
||||||
self.client.force_login(voter)
|
|
||||||
response = self.client.post(self.vote_url, data=vote)
|
|
||||||
assertRedirects(response, self.detail_url)
|
|
||||||
|
|
||||||
assert self.election.results == {
|
|
||||||
postes[0]: {
|
|
||||||
self.cand[0].user.username: {"percent": 0.0, "vote": 0},
|
|
||||||
self.cand[1].user.username: {"percent": 0.0, "vote": 0},
|
|
||||||
"blank vote": {"percent": 100.0, "vote": 2},
|
|
||||||
"total vote": 2,
|
|
||||||
},
|
|
||||||
postes[1]: {
|
|
||||||
self.cand[2].user.username: {"percent": 0.0, "vote": 0},
|
|
||||||
self.cand[3].user.username: {"percent": 0.0, "vote": 0},
|
|
||||||
"blank vote": {"percent": 100.0, "vote": 2},
|
|
||||||
"total vote": 2,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_election_create_list_permission(client: Client):
|
def test_election_create_list_permission(client: Client):
|
||||||
election = baker.make(Election, end_candidature=now() + timedelta(hours=1))
|
election = baker.make(Election, end_candidature=now() + timedelta(hours=1))
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from cryptography.utils import cached_property
|
from cryptography.utils import cached_property
|
||||||
|
from django.conf import settings
|
||||||
from django.contrib import messages
|
from django.contrib import messages
|
||||||
from django.contrib.auth.mixins import (
|
from django.contrib.auth.mixins import (
|
||||||
LoginRequiredMixin,
|
LoginRequiredMixin,
|
||||||
@@ -114,9 +115,16 @@ class VoteFormView(LoginRequiredMixin, UserPassesTestMixin, FormView):
|
|||||||
def test_func(self):
|
def test_func(self):
|
||||||
if not self.election.can_vote(self.request.user):
|
if not self.election.can_vote(self.request.user):
|
||||||
return False
|
return False
|
||||||
return self.election.vote_groups.filter(
|
|
||||||
id__in=self.request.user.all_groups
|
groups = set(self.election.vote_groups.values_list("id", flat=True))
|
||||||
).exists()
|
if (
|
||||||
|
settings.SITH_GROUP_SUBSCRIBERS_ID in groups
|
||||||
|
and self.request.user.is_subscribed
|
||||||
|
):
|
||||||
|
# the subscriber group isn't truly attached to users,
|
||||||
|
# so it must be dealt with separately
|
||||||
|
return True
|
||||||
|
return self.request.user.groups.filter(id__in=groups).exists()
|
||||||
|
|
||||||
def vote(self, election_data):
|
def vote(self, election_data):
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
@@ -230,9 +238,15 @@ class RoleCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView):
|
|||||||
return False
|
return False
|
||||||
if self.request.user.has_perm("election.add_role"):
|
if self.request.user.has_perm("election.add_role"):
|
||||||
return True
|
return True
|
||||||
return self.election.edit_groups.filter(
|
groups = set(self.election.edit_groups.values_list("id", flat=True))
|
||||||
id__in=self.request.user.all_groups
|
if (
|
||||||
).exists()
|
settings.SITH_GROUP_SUBSCRIBERS_ID in groups
|
||||||
|
and self.request.user.is_subscribed
|
||||||
|
):
|
||||||
|
# the subscriber group isn't truly attached to users,
|
||||||
|
# so it must be dealt with separately
|
||||||
|
return True
|
||||||
|
return self.request.user.groups.filter(id__in=groups).exists()
|
||||||
|
|
||||||
def get_initial(self):
|
def get_initial(self):
|
||||||
return {"election": self.election}
|
return {"election": self.election}
|
||||||
@@ -265,7 +279,14 @@ class ElectionListCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView
|
|||||||
.union(self.election.edit_groups.values("id"))
|
.union(self.election.edit_groups.values("id"))
|
||||||
.values_list("id", flat=True)
|
.values_list("id", flat=True)
|
||||||
)
|
)
|
||||||
return not groups.isdisjoint(self.request.user.all_groups.keys())
|
if (
|
||||||
|
settings.SITH_GROUP_SUBSCRIBERS_ID in groups
|
||||||
|
and self.request.user.is_subscribed
|
||||||
|
):
|
||||||
|
# the subscriber group isn't truly attached to users,
|
||||||
|
# so it must be dealt with separately
|
||||||
|
return True
|
||||||
|
return self.request.user.groups.filter(id__in=groups).exists()
|
||||||
|
|
||||||
def get_initial(self):
|
def get_initial(self):
|
||||||
return {"election": self.election}
|
return {"election": self.election}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
msgid ""
|
msgid ""
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Report-Msgid-Bugs-To: \n"
|
"Report-Msgid-Bugs-To: \n"
|
||||||
"POT-Creation-Date: 2026-03-10 10:28+0100\n"
|
"POT-Creation-Date: 2026-03-07 15:47+0100\n"
|
||||||
"PO-Revision-Date: 2016-07-18\n"
|
"PO-Revision-Date: 2016-07-18\n"
|
||||||
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
||||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||||
@@ -239,7 +239,7 @@ msgid "role"
|
|||||||
msgstr "rôle"
|
msgstr "rôle"
|
||||||
|
|
||||||
#: club/models.py core/models.py counter/models.py election/models.py
|
#: club/models.py core/models.py counter/models.py election/models.py
|
||||||
#: forum/models.py
|
#: forum/models.py reservation/models.py
|
||||||
msgid "description"
|
msgid "description"
|
||||||
msgstr "description"
|
msgstr "description"
|
||||||
|
|
||||||
@@ -514,6 +514,18 @@ msgstr "Nouveau Trombi"
|
|||||||
msgid "Posters"
|
msgid "Posters"
|
||||||
msgstr "Affiches"
|
msgstr "Affiches"
|
||||||
|
|
||||||
|
#: club/templates/club/club_tools.jinja
|
||||||
|
msgid "Reservable rooms"
|
||||||
|
msgstr "Salles réservables"
|
||||||
|
|
||||||
|
#: club/templates/club/club_tools.jinja
|
||||||
|
msgid "Add a room"
|
||||||
|
msgstr "Ajouter une salle"
|
||||||
|
|
||||||
|
#: club/templates/club/club_tools.jinja
|
||||||
|
msgid "This club manages no reservable room"
|
||||||
|
msgstr "Ce club ne gère pas de salle réservable"
|
||||||
|
|
||||||
#: club/templates/club/club_tools.jinja
|
#: club/templates/club/club_tools.jinja
|
||||||
msgid "Counters:"
|
msgid "Counters:"
|
||||||
msgstr "Comptoirs : "
|
msgstr "Comptoirs : "
|
||||||
@@ -792,7 +804,7 @@ msgstr "Une description plus détaillée et exhaustive de l'évènement."
|
|||||||
msgid "The club which organizes the event."
|
msgid "The club which organizes the event."
|
||||||
msgstr "Le club qui organise l'évènement."
|
msgstr "Le club qui organise l'évènement."
|
||||||
|
|
||||||
#: com/models.py pedagogy/models.py trombi/models.py
|
#: com/models.py pedagogy/models.py reservation/models.py trombi/models.py
|
||||||
msgid "author"
|
msgid "author"
|
||||||
msgstr "auteur"
|
msgstr "auteur"
|
||||||
|
|
||||||
@@ -1089,6 +1101,11 @@ msgstr "Emploi du temps"
|
|||||||
msgid "Matmatronch"
|
msgid "Matmatronch"
|
||||||
msgstr "Matmatronch"
|
msgstr "Matmatronch"
|
||||||
|
|
||||||
|
#: com/templates/com/news_list.jinja
|
||||||
|
#: reservation/templates/reservation/schedule.jinja
|
||||||
|
msgid "Room reservation"
|
||||||
|
msgstr "Réservation de salle"
|
||||||
|
|
||||||
#: com/templates/com/news_list.jinja core/templates/core/base/navbar.jinja
|
#: com/templates/com/news_list.jinja core/templates/core/base/navbar.jinja
|
||||||
#: core/templates/core/user_tools.jinja
|
#: core/templates/core/user_tools.jinja
|
||||||
msgid "Elections"
|
msgid "Elections"
|
||||||
@@ -1949,6 +1966,7 @@ msgstr "Confirmation"
|
|||||||
#: core/templates/core/file_delete_confirm.jinja
|
#: core/templates/core/file_delete_confirm.jinja
|
||||||
#: counter/templates/counter/counter_click.jinja
|
#: counter/templates/counter/counter_click.jinja
|
||||||
#: counter/templates/counter/fragments/delete_student_card.jinja
|
#: counter/templates/counter/fragments/delete_student_card.jinja
|
||||||
|
#: reservation/templates/reservation/fragments/create_reservation.jinja
|
||||||
#: sas/templates/sas/ask_picture_removal.jinja
|
#: sas/templates/sas/ask_picture_removal.jinja
|
||||||
msgid "Cancel"
|
msgid "Cancel"
|
||||||
msgstr "Annuler"
|
msgstr "Annuler"
|
||||||
@@ -2937,29 +2955,6 @@ msgstr "Cet UID est invalide"
|
|||||||
msgid "User not found"
|
msgid "User not found"
|
||||||
msgstr "Utilisateur non trouvé"
|
msgstr "Utilisateur non trouvé"
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
msgid "Regular barmen"
|
|
||||||
msgstr "Barmen réguliers"
|
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
msgid ""
|
|
||||||
"Barmen having regular permanences or frequently giving a hand throughout the "
|
|
||||||
"semester."
|
|
||||||
msgstr ""
|
|
||||||
"Les barmen assurant des permanences régulières ou donnant régulièrement un "
|
|
||||||
"coup de main au cours du semestre."
|
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
msgid "Temporary barmen"
|
|
||||||
msgstr "Barmen temporaires"
|
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
msgid ""
|
|
||||||
"Barmen who will be there only for a limited period (e.g. for one evening)"
|
|
||||||
msgstr ""
|
|
||||||
"Les barmen qui seront là uniquement pour une durée limitée (par exemple, le "
|
|
||||||
"temps d'une soirée)"
|
|
||||||
|
|
||||||
#: counter/forms.py
|
#: counter/forms.py
|
||||||
msgid ""
|
msgid ""
|
||||||
"If you want to add a product that is not owned by your club to this counter, "
|
"If you want to add a product that is not owned by your club to this counter, "
|
||||||
@@ -2968,16 +2963,6 @@ msgstr ""
|
|||||||
"Si vous souhaitez ajouter sur ce comptoir un produit qui n'appartient pas à "
|
"Si vous souhaitez ajouter sur ce comptoir un produit qui n'appartient pas à "
|
||||||
"votre club, vous devriez demander à un admin."
|
"votre club, vous devriez demander à un admin."
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
#, python-format
|
|
||||||
msgid ""
|
|
||||||
"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"
|
|
||||||
msgstr ""
|
|
||||||
"Un utilisateur ne peut pas être un barman régulier et temporaire en même "
|
|
||||||
"temps, mais les utilisateurs suivants ont été définis comme les deux : "
|
|
||||||
"%(users)s"
|
|
||||||
|
|
||||||
#: counter/forms.py
|
#: counter/forms.py
|
||||||
msgid "Date and time of action"
|
msgid "Date and time of action"
|
||||||
msgstr "Date et heure de l'action"
|
msgstr "Date et heure de l'action"
|
||||||
@@ -3126,7 +3111,7 @@ msgstr "Mettre à True si le mail a reçu une erreur"
|
|||||||
msgid "The operation that emptied the account."
|
msgid "The operation that emptied the account."
|
||||||
msgstr "L'opération qui a vidé le compte."
|
msgstr "L'opération qui a vidé le compte."
|
||||||
|
|
||||||
#: counter/models.py pedagogy/models.py
|
#: counter/models.py pedagogy/models.py reservation/models.py
|
||||||
msgid "comment"
|
msgid "comment"
|
||||||
msgstr "commentaire"
|
msgstr "commentaire"
|
||||||
|
|
||||||
@@ -3226,10 +3211,6 @@ msgstr "vendeurs"
|
|||||||
msgid "token"
|
msgid "token"
|
||||||
msgstr "jeton"
|
msgstr "jeton"
|
||||||
|
|
||||||
#: counter/models.py
|
|
||||||
msgid "regular barman"
|
|
||||||
msgstr "barman régulier"
|
|
||||||
|
|
||||||
#: counter/models.py sith/settings.py
|
#: counter/models.py sith/settings.py
|
||||||
msgid "Credit card"
|
msgid "Credit card"
|
||||||
msgstr "Carte bancaire"
|
msgstr "Carte bancaire"
|
||||||
@@ -3794,10 +3775,6 @@ msgstr ""
|
|||||||
"votre cotisation. Si vous ne renouvelez pas votre cotisation, il n'y aura "
|
"votre cotisation. Si vous ne renouvelez pas votre cotisation, il n'y aura "
|
||||||
"aucune conséquence autre que le retrait de l'argent de votre compte."
|
"aucune conséquence autre que le retrait de l'argent de votre compte."
|
||||||
|
|
||||||
#: counter/templates/counter/product_form.jinja
|
|
||||||
msgid "Remove this action"
|
|
||||||
msgstr "Retirer cette action"
|
|
||||||
|
|
||||||
#: counter/templates/counter/product_form.jinja
|
#: counter/templates/counter/product_form.jinja
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid "Edit product %(name)s"
|
msgid "Edit product %(name)s"
|
||||||
@@ -3825,10 +3802,6 @@ msgstr ""
|
|||||||
"Les actions automatiques vous permettent de planifier des modifications du "
|
"Les actions automatiques vous permettent de planifier des modifications du "
|
||||||
"produit à l'avance."
|
"produit à l'avance."
|
||||||
|
|
||||||
#: counter/templates/counter/product_form.jinja
|
|
||||||
msgid "Add action"
|
|
||||||
msgstr "Ajouter une action"
|
|
||||||
|
|
||||||
#: counter/templates/counter/product_list.jinja
|
#: counter/templates/counter/product_list.jinja
|
||||||
msgid "Product list"
|
msgid "Product list"
|
||||||
msgstr "Liste des produits"
|
msgstr "Liste des produits"
|
||||||
@@ -3942,10 +3915,6 @@ msgstr "Temps"
|
|||||||
msgid "Top 100 barman %(counter_name)s (all semesters)"
|
msgid "Top 100 barman %(counter_name)s (all semesters)"
|
||||||
msgstr "Top 100 barman %(counter_name)s (tous les semestres)"
|
msgstr "Top 100 barman %(counter_name)s (tous les semestres)"
|
||||||
|
|
||||||
#: counter/views/admin.py
|
|
||||||
msgid "Counter update done"
|
|
||||||
msgstr "Mise à jour du comptoir effectuée"
|
|
||||||
|
|
||||||
#: counter/views/admin.py
|
#: counter/views/admin.py
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid "%(formula)s (formula)"
|
msgid "%(formula)s (formula)"
|
||||||
@@ -4855,6 +4824,73 @@ msgstr "Signaler ce commentaire"
|
|||||||
msgid "Edit UE"
|
msgid "Edit UE"
|
||||||
msgstr "Éditer l'UE"
|
msgstr "Éditer l'UE"
|
||||||
|
|
||||||
|
#: reservation/forms.py
|
||||||
|
msgid "The start must be set before the end"
|
||||||
|
msgstr "Le début doit être placé avant la fin"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "room name"
|
||||||
|
msgstr "Nom de la salle"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "room owner"
|
||||||
|
msgstr "propriétaire de la salle"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "The club which manages this room"
|
||||||
|
msgstr "Le club qui gère cette salle"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "site"
|
||||||
|
msgstr "site"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "reservable room"
|
||||||
|
msgstr "salle réservable"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "reservable rooms"
|
||||||
|
msgstr "salles réservables"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "reserved room"
|
||||||
|
msgstr "salle réservée"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "slot start"
|
||||||
|
msgstr "début du créneau"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "slot end"
|
||||||
|
msgstr "fin du créneau"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "reservation slot"
|
||||||
|
msgstr "créneau de réservation"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "reservation slots"
|
||||||
|
msgstr "créneaux de réservation"
|
||||||
|
|
||||||
|
#: reservation/models.py
|
||||||
|
msgid "There is already a reservation on this slot."
|
||||||
|
msgstr "Il y a déjà une réservation sur ce créneau."
|
||||||
|
|
||||||
|
#: reservation/templates/reservation/fragments/create_reservation.jinja
|
||||||
|
msgid "Book a room"
|
||||||
|
msgstr "Réserver une salle"
|
||||||
|
|
||||||
|
#: reservation/templates/reservation/schedule.jinja
|
||||||
|
msgid "You can book a room by selecting a free slot in the calendar."
|
||||||
|
msgstr ""
|
||||||
|
"Vous pouvez réserver une salle en sélectionnant un emplacement libre dans le "
|
||||||
|
"calendrier."
|
||||||
|
|
||||||
|
#: reservation/views.py
|
||||||
|
#, python-format
|
||||||
|
msgid "%(name)s was updated successfully"
|
||||||
|
msgstr "%(name)s a été mis à jour avec succès"
|
||||||
|
|
||||||
#: rootplace/forms.py
|
#: rootplace/forms.py
|
||||||
msgid "User that will be kept"
|
msgid "User that will be kept"
|
||||||
msgstr "Utilisateur qui sera conservé"
|
msgstr "Utilisateur qui sera conservé"
|
||||||
@@ -5294,6 +5330,8 @@ msgid "One day"
|
|||||||
msgstr "Un jour"
|
msgstr "Un jour"
|
||||||
|
|
||||||
#: sith/settings.py
|
#: sith/settings.py
|
||||||
|
#, fuzzy
|
||||||
|
#| msgid "GA staff member"
|
||||||
msgid "GA staff member"
|
msgid "GA staff member"
|
||||||
msgstr "Membre staff GA"
|
msgstr "Membre staff GA"
|
||||||
|
|
||||||
|
|||||||
@@ -255,6 +255,14 @@ msgstr "Types de produits réordonnés !"
|
|||||||
msgid "Product type reorganisation failed with status code : %d"
|
msgid "Product type reorganisation failed with status code : %d"
|
||||||
msgstr "La réorganisation des types de produit a échoué avec le code : %d"
|
msgstr "La réorganisation des types de produit a échoué avec le code : %d"
|
||||||
|
|
||||||
|
#: reservation/static/bundled/reservation/components/room-scheduler-index.ts
|
||||||
|
msgid "Rooms"
|
||||||
|
msgstr "Salles"
|
||||||
|
|
||||||
|
#: reservation/static/bundled/reservation/slot-reservation-index.ts
|
||||||
|
msgid "This slot has been successfully moved"
|
||||||
|
msgstr "Ce créneau a été bougé avec succès"
|
||||||
|
|
||||||
#: sas/static/bundled/sas/pictures-download-index.ts
|
#: sas/static/bundled/sas/pictures-download-index.ts
|
||||||
msgid "pictures.%(extension)s"
|
msgid "pictures.%(extension)s"
|
||||||
msgstr "photos.%(extension)s"
|
msgstr "photos.%(extension)s"
|
||||||
|
|||||||
2460
package-lock.json
generated
2460
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
31
package.json
31
package.json
@@ -8,6 +8,8 @@
|
|||||||
"compile-dev": "vite build --mode development",
|
"compile-dev": "vite build --mode development",
|
||||||
"serve": "vite build --mode development --watch --minify false",
|
"serve": "vite build --mode development --watch --minify false",
|
||||||
"openapi": "openapi-ts",
|
"openapi": "openapi-ts",
|
||||||
|
"analyse-dev": "vite-bundle-visualizer --mode development",
|
||||||
|
"analyse-prod": "vite-bundle-visualizer --mode production",
|
||||||
"check": "tsc && biome check --write"
|
"check": "tsc && biome check --write"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
@@ -21,33 +23,39 @@
|
|||||||
"#core:*": "./core/static/bundled/*",
|
"#core:*": "./core/static/bundled/*",
|
||||||
"#pedagogy:*": "./pedagogy/static/bundled/*",
|
"#pedagogy:*": "./pedagogy/static/bundled/*",
|
||||||
"#counter:*": "./counter/static/bundled/*",
|
"#counter:*": "./counter/static/bundled/*",
|
||||||
"#com:*": "./com/static/bundled/*"
|
"#com:*": "./com/static/bundled/*",
|
||||||
|
"#reservation:*": "./reservation/static/bundled/*"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.29.0",
|
"@babel/core": "^7.29.0",
|
||||||
"@babel/preset-env": "^7.29.0",
|
"@babel/preset-env": "^7.29.0",
|
||||||
"@biomejs/biome": "^2.4.6",
|
"@biomejs/biome": "^2.3.14",
|
||||||
"@hey-api/openapi-ts": "^0.94.0",
|
"@hey-api/openapi-ts": "^0.92.4",
|
||||||
"@rollup/plugin-inject": "^5.0.5",
|
"@rollup/plugin-inject": "^5.0.5",
|
||||||
"@types/alpinejs": "^3.13.11",
|
"@types/alpinejs": "^3.13.11",
|
||||||
"@types/cytoscape-cxtmenu": "^3.4.5",
|
"@types/cytoscape-cxtmenu": "^3.4.5",
|
||||||
"@types/cytoscape-klay": "^3.1.5",
|
"@types/cytoscape-klay": "^3.1.5",
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
"rollup-plugin-visualizer": "^7.0.1",
|
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^8.0.0"
|
"vite": "^7.3.1",
|
||||||
|
"vite-bundle-visualizer": "^1.2.1",
|
||||||
|
"vite-plugin-static-copy": "^3.2.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@alpinejs/morph": "^3.14.9",
|
||||||
"@alpinejs/sort": "^3.15.8",
|
"@alpinejs/sort": "^3.15.8",
|
||||||
"@arendjr/text-clipper": "npm:@jsr/arendjr__text-clipper@^3.0.0",
|
"@arendjr/text-clipper": "npm:@jsr/arendjr__text-clipper@^3.0.0",
|
||||||
"@floating-ui/dom": "^1.7.6",
|
"@floating-ui/dom": "^1.7.5",
|
||||||
"@fortawesome/fontawesome-free": "^7.2.0",
|
"@fortawesome/fontawesome-free": "^7.2.0",
|
||||||
"@fullcalendar/core": "^6.1.20",
|
"@fullcalendar/core": "^6.1.20",
|
||||||
"@fullcalendar/daygrid": "^6.1.20",
|
"@fullcalendar/daygrid": "^6.1.20",
|
||||||
"@fullcalendar/icalendar": "^6.1.20",
|
"@fullcalendar/icalendar": "^6.1.20",
|
||||||
|
"@fullcalendar/interaction": "^6.1.19",
|
||||||
"@fullcalendar/list": "^6.1.20",
|
"@fullcalendar/list": "^6.1.20",
|
||||||
"@sentry/browser": "^10.43.0",
|
"@fullcalendar/resource": "^6.1.19",
|
||||||
"@zip.js/zip.js": "^2.8.23",
|
"@fullcalendar/resource-timeline": "^6.1.19",
|
||||||
|
"@sentry/browser": "^10.38.0",
|
||||||
|
"@zip.js/zip.js": "^2.8.20",
|
||||||
"3d-force-graph": "^1.79.1",
|
"3d-force-graph": "^1.79.1",
|
||||||
"alpinejs": "^3.15.8",
|
"alpinejs": "^3.15.8",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
@@ -57,14 +65,15 @@
|
|||||||
"cytoscape-klay": "^3.1.4",
|
"cytoscape-klay": "^3.1.4",
|
||||||
"d3-force-3d": "^3.0.6",
|
"d3-force-3d": "^3.0.6",
|
||||||
"easymde": "^2.20.0",
|
"easymde": "^2.20.0",
|
||||||
"glob": "^13.0.6",
|
"glob": "^13.0.2",
|
||||||
"html2canvas": "^1.4.1",
|
"html2canvas": "^1.4.1",
|
||||||
|
"htmx-ext-alpine-morph": "^2.0.1",
|
||||||
"htmx.org": "^2.0.8",
|
"htmx.org": "^2.0.8",
|
||||||
"js-cookie": "^3.0.5",
|
"js-cookie": "^3.0.5",
|
||||||
"lit-html": "^3.3.2",
|
"lit-html": "^3.3.2",
|
||||||
"native-file-system-adapter": "^3.0.1",
|
"native-file-system-adapter": "^3.0.1",
|
||||||
"three": "^0.183.2",
|
"three": "^0.182.0",
|
||||||
"three-spritetext": "^1.10.0",
|
"three-spritetext": "^1.10.0",
|
||||||
"tom-select": "^2.5.2"
|
"tom-select": "^2.5.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ authors = [
|
|||||||
license = { text = "GPL-3.0-only" }
|
license = { text = "GPL-3.0-only" }
|
||||||
requires-python = "<4.0,>=3.12"
|
requires-python = "<4.0,>=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"django>=5.2.12,<6.0.0",
|
"django>=5.2.11,<6.0.0",
|
||||||
"django-ninja>=1.5.3,<6.0.0",
|
"django-ninja>=1.5.3,<6.0.0",
|
||||||
"django-ninja-extra>=0.31.0",
|
"django-ninja-extra>=0.31.0",
|
||||||
"Pillow>=12.1.1,<13.0.0",
|
"Pillow>=12.1.1,<13.0.0",
|
||||||
@@ -27,15 +27,15 @@ dependencies = [
|
|||||||
"django-jinja<3.0.0,>=2.11.0",
|
"django-jinja<3.0.0,>=2.11.0",
|
||||||
"cryptography>=46.0.5,<47.0.0",
|
"cryptography>=46.0.5,<47.0.0",
|
||||||
"django-phonenumber-field>=8.4.0,<9.0.0",
|
"django-phonenumber-field>=8.4.0,<9.0.0",
|
||||||
"phonenumbers>=9.0.25,<10.0.0",
|
"phonenumbers>=9.0.23,<10.0.0",
|
||||||
"reportlab>=4.4.10,<5.0.0",
|
"reportlab>=4.4.9,<5.0.0",
|
||||||
"django-haystack<4.0.0,>=3.3.0",
|
"django-haystack<4.0.0,>=3.3.0",
|
||||||
"xapian-haystack<4.0.0,>=3.1.0",
|
"xapian-haystack<4.0.0,>=3.1.0",
|
||||||
"libsass<1.0.0,>=0.23.0",
|
"libsass<1.0.0,>=0.23.0",
|
||||||
"django-ordered-model<4.0.0,>=3.7.4",
|
"django-ordered-model<4.0.0,>=3.7.4",
|
||||||
"django-simple-captcha<1.0.0,>=0.6.3",
|
"django-simple-captcha<1.0.0,>=0.6.3",
|
||||||
"python-dateutil<3.0.0.0,>=2.9.0.post0",
|
"python-dateutil<3.0.0.0,>=2.9.0.post0",
|
||||||
"sentry-sdk>=2.54.0,<3.0.0",
|
"sentry-sdk>=2.52.0,<3.0.0",
|
||||||
"jinja2<4.0.0,>=3.1.6",
|
"jinja2<4.0.0,>=3.1.6",
|
||||||
"django-countries>=8.2.0,<9.0.0",
|
"django-countries>=8.2.0,<9.0.0",
|
||||||
"dict2xml>=1.7.8,<2.0.0",
|
"dict2xml>=1.7.8,<2.0.0",
|
||||||
@@ -51,7 +51,7 @@ dependencies = [
|
|||||||
"psutil>=7.2.2,<8.0.0",
|
"psutil>=7.2.2,<8.0.0",
|
||||||
"celery[redis]>=5.6.2,<7",
|
"celery[redis]>=5.6.2,<7",
|
||||||
"django-celery-results>=2.5.1",
|
"django-celery-results>=2.5.1",
|
||||||
"django-celery-beat>=2.9.0",
|
"django-celery-beat>=2.7.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
@@ -60,31 +60,31 @@ documentation = "https://sith-ae.readthedocs.io/"
|
|||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
prod = [
|
prod = [
|
||||||
"psycopg[c]>=3.3.3,<4.0.0",
|
"psycopg[c]>=3.3.2,<4.0.0",
|
||||||
]
|
]
|
||||||
dev = [
|
dev = [
|
||||||
"django-debug-toolbar>=6.2.0,<7",
|
"django-debug-toolbar>=6.2.0,<7",
|
||||||
"ipython>=9.11.0,<10.0.0",
|
"ipython>=9.10.0,<10.0.0",
|
||||||
"pre-commit>=4.5.1,<5.0.0",
|
"pre-commit>=4.5.1,<5.0.0",
|
||||||
"ruff>=0.15.5,<1.0.0",
|
"ruff>=0.15.0,<1.0.0",
|
||||||
"djhtml>=3.0.10,<4.0.0",
|
"djhtml>=3.0.10,<4.0.0",
|
||||||
"faker>=40.8.0,<41.0.0",
|
"faker>=40.4.0,<41.0.0",
|
||||||
"rjsmin>=1.2.5,<2.0.0",
|
"rjsmin>=1.2.5,<2.0.0",
|
||||||
]
|
]
|
||||||
tests = [
|
tests = [
|
||||||
"freezegun>=1.5.5,<2.0.0",
|
"freezegun>=1.5.5,<2.0.0",
|
||||||
"pytest>=9.0.2,<10.0.0",
|
"pytest>=9.0.2,<10.0.0",
|
||||||
"pytest-cov>=7.0.0,<8.0.0",
|
"pytest-cov>=7.0.0,<8.0.0",
|
||||||
"pytest-django<5.0.0,>=4.12.0",
|
"pytest-django<5.0.0,>=4.10.0",
|
||||||
"model-bakery<2.0.0,>=1.23.3",
|
"model-bakery<2.0.0,>=1.23.2",
|
||||||
"beautifulsoup4>=4.14.3,<5",
|
"beautifulsoup4>=4.14.3,<5",
|
||||||
"lxml>=6.0.2,<7",
|
"lxml>=6.0.2,<7",
|
||||||
]
|
]
|
||||||
docs = [
|
docs = [
|
||||||
"mkdocs<2.0.0,>=1.6.1",
|
"mkdocs<2.0.0,>=1.6.1",
|
||||||
"mkdocs-material>=9.7.5,<10.0.0",
|
"mkdocs-material>=9.7.1,<10.0.0",
|
||||||
"mkdocstrings>=1.0.3,<2.0.0",
|
"mkdocstrings>=1.0.3,<2.0.0",
|
||||||
"mkdocstrings-python>=2.0.3,<3.0.0",
|
"mkdocstrings-python>=2.0.2,<3.0.0",
|
||||||
"mkdocs-include-markdown-plugin>=7.2.1,<8.0.0",
|
"mkdocs-include-markdown-plugin>=7.2.1,<8.0.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
0
reservation/__init__.py
Normal file
0
reservation/__init__.py
Normal file
19
reservation/admin.py
Normal file
19
reservation/admin.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(Room)
|
||||||
|
class RoomAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ("name", "club")
|
||||||
|
list_filter = (("club", admin.RelatedOnlyFieldListFilter), "location")
|
||||||
|
autocomplete_fields = ("club",)
|
||||||
|
search_fields = ("name",)
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(ReservationSlot)
|
||||||
|
class ReservationSlotAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ("room", "start_at", "end_at", "author")
|
||||||
|
autocomplete_fields = ("author",)
|
||||||
|
list_filter = ("room",)
|
||||||
|
date_hierarchy = "start_at"
|
||||||
64
reservation/api.py
Normal file
64
reservation/api.py
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from ninja import Query
|
||||||
|
from ninja_extra import ControllerBase, api_controller, paginate, route
|
||||||
|
from ninja_extra.pagination import PageNumberPaginationExtra
|
||||||
|
from ninja_extra.schemas import PaginatedResponseSchema
|
||||||
|
|
||||||
|
from api.permissions import HasPerm
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
|
from reservation.schemas import (
|
||||||
|
RoomFilterSchema,
|
||||||
|
RoomSchema,
|
||||||
|
SlotFilterSchema,
|
||||||
|
SlotSchema,
|
||||||
|
UpdateReservationSlotSchema,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@api_controller("/reservation/room")
|
||||||
|
class ReservableRoomController(ControllerBase):
|
||||||
|
@route.get(
|
||||||
|
"",
|
||||||
|
response=list[RoomSchema],
|
||||||
|
permissions=[HasPerm("reservation.view_room")],
|
||||||
|
url_name="fetch_reservable_rooms",
|
||||||
|
)
|
||||||
|
def fetch_rooms(self, filters: Query[RoomFilterSchema]):
|
||||||
|
return filters.filter(Room.objects.select_related("club"))
|
||||||
|
|
||||||
|
|
||||||
|
@api_controller("/reservation/slot")
|
||||||
|
class ReservationSlotController(ControllerBase):
|
||||||
|
@route.get(
|
||||||
|
"",
|
||||||
|
response=PaginatedResponseSchema[SlotSchema],
|
||||||
|
permissions=[HasPerm("reservation.view_reservationslot")],
|
||||||
|
url_name="fetch_reservation_slots",
|
||||||
|
)
|
||||||
|
@paginate(PageNumberPaginationExtra)
|
||||||
|
def fetch_slots(self, filters: Query[SlotFilterSchema]):
|
||||||
|
return filters.filter(
|
||||||
|
ReservationSlot.objects.select_related("author").order_by("start_at")
|
||||||
|
)
|
||||||
|
|
||||||
|
@route.patch(
|
||||||
|
"/reservation/slot/{int:slot_id}",
|
||||||
|
permissions=[HasPerm("reservation.change_reservationslot")],
|
||||||
|
response={
|
||||||
|
200: None,
|
||||||
|
409: dict[Literal["detail"], dict[str, list[str]]],
|
||||||
|
422: dict[Literal["detail"], list[dict[str, Any]]],
|
||||||
|
},
|
||||||
|
url_name="change_reservation_slot",
|
||||||
|
)
|
||||||
|
def update_slot(self, slot_id: int, params: UpdateReservationSlotSchema):
|
||||||
|
slot = self.get_object_or_exception(ReservationSlot, id=slot_id)
|
||||||
|
slot.start_at = params.start_at
|
||||||
|
slot.end_at = params.end_at
|
||||||
|
try:
|
||||||
|
slot.full_clean()
|
||||||
|
slot.save()
|
||||||
|
except ValidationError as e:
|
||||||
|
return self.create_response({"detail": dict(e)}, status_code=409)
|
||||||
6
reservation/apps.py
Normal file
6
reservation/apps.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationConfig(AppConfig):
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
|
name = "reservation"
|
||||||
60
reservation/forms.py
Normal file
60
reservation/forms.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
from django import forms
|
||||||
|
from django.core.exceptions import NON_FIELD_ERRORS
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
from club.widgets.ajax_select import AutoCompleteSelectClub
|
||||||
|
from core.models import User
|
||||||
|
from core.views.forms import FutureDateTimeField, SelectDateTime
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
|
|
||||||
|
|
||||||
|
class RoomCreateForm(forms.ModelForm):
|
||||||
|
required_css_class = "required"
|
||||||
|
error_css_class = "error"
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Room
|
||||||
|
fields = ["name", "club", "location", "description"]
|
||||||
|
widgets = {"club": AutoCompleteSelectClub}
|
||||||
|
|
||||||
|
|
||||||
|
class RoomUpdateForm(forms.ModelForm):
|
||||||
|
required_css_class = "required"
|
||||||
|
error_css_class = "error"
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Room
|
||||||
|
fields = ["name", "club", "location", "description"]
|
||||||
|
widgets = {"club": AutoCompleteSelectClub}
|
||||||
|
|
||||||
|
def __init__(self, *args, request_user: User, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
if not request_user.has_perm("reservation.change_room"):
|
||||||
|
# if the user doesn't have the global edition permission
|
||||||
|
# (i.e. it's a club board member, but not a sith admin)
|
||||||
|
# some fields aren't editable
|
||||||
|
del self.fields["club"]
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationForm(forms.ModelForm):
|
||||||
|
required_css_class = "required"
|
||||||
|
error_css_class = "error"
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ReservationSlot
|
||||||
|
fields = ["room", "start_at", "end_at", "comment"]
|
||||||
|
field_classes = {"start_at": FutureDateTimeField, "end_at": FutureDateTimeField}
|
||||||
|
widgets = {"start_at": SelectDateTime(), "end_at": SelectDateTime()}
|
||||||
|
error_messages = {
|
||||||
|
NON_FIELD_ERRORS: {
|
||||||
|
"start_after_end": _("The start must be set before the end")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def __init__(self, *args, author: User, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.author = author
|
||||||
|
|
||||||
|
def save(self, commit: bool = True): # noqa FBT001
|
||||||
|
self.instance.author = self.author
|
||||||
|
return super().save(commit)
|
||||||
117
reservation/migrations/0001_initial.py
Normal file
117
reservation/migrations/0001_initial.py
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
# Generated by Django 5.2.1 on 2025-06-05 10:44
|
||||||
|
|
||||||
|
import django.core.validators
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("club", "0014_alter_club_options_rename_unix_name_club_slug_name_and_more"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="Room",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("name", models.CharField(max_length=100, verbose_name="room name")),
|
||||||
|
(
|
||||||
|
"description",
|
||||||
|
models.TextField(
|
||||||
|
blank=True, default="", verbose_name="description"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"location",
|
||||||
|
models.CharField(
|
||||||
|
blank=True,
|
||||||
|
choices=[
|
||||||
|
("BELFORT", "Belfort"),
|
||||||
|
("SEVENANS", "Sévenans"),
|
||||||
|
("MONTBELIARD", "Montbéliard"),
|
||||||
|
],
|
||||||
|
verbose_name="site",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"club",
|
||||||
|
models.ForeignKey(
|
||||||
|
help_text="The club which manages this room",
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="reservable_rooms",
|
||||||
|
to="club.club",
|
||||||
|
verbose_name="room owner",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "reservable room",
|
||||||
|
"verbose_name_plural": "reservable rooms",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="ReservationSlot",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"comment",
|
||||||
|
models.TextField(blank=True, default="", verbose_name="comment"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"start_at",
|
||||||
|
models.DateTimeField(db_index=True, verbose_name="slot start"),
|
||||||
|
),
|
||||||
|
("end_at", models.DateTimeField(verbose_name="slot end")),
|
||||||
|
("created_at", models.DateTimeField(auto_now_add=True)),
|
||||||
|
(
|
||||||
|
"author",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
verbose_name="author",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"room",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="slots",
|
||||||
|
to="reservation.room",
|
||||||
|
verbose_name="reserved room",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "reservation slot",
|
||||||
|
"verbose_name_plural": "reservation slots",
|
||||||
|
"constraints": [
|
||||||
|
models.CheckConstraint(
|
||||||
|
condition=models.Q(("end_at__gt", models.F("start_at"))),
|
||||||
|
name="reservation_slot_end_after_start",
|
||||||
|
violation_error_code="start_after_end",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
0
reservation/migrations/__init__.py
Normal file
0
reservation/migrations/__init__.py
Normal file
100
reservation/models.py
Normal file
100
reservation/models.py
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Self
|
||||||
|
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.db import models
|
||||||
|
from django.db.models import F, Q
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
from club.models import Club
|
||||||
|
from core.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class Room(models.Model):
|
||||||
|
name = models.CharField(_("room name"), max_length=100)
|
||||||
|
description = models.TextField(_("description"), blank=True, default="")
|
||||||
|
club = models.ForeignKey(
|
||||||
|
Club,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="reservable_rooms",
|
||||||
|
verbose_name=_("room owner"),
|
||||||
|
help_text=_("The club which manages this room"),
|
||||||
|
)
|
||||||
|
location = models.CharField(
|
||||||
|
_("site"),
|
||||||
|
blank=True,
|
||||||
|
choices=[
|
||||||
|
("BELFORT", "Belfort"),
|
||||||
|
("SEVENANS", "Sévenans"),
|
||||||
|
("MONTBELIARD", "Montbéliard"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = _("reservable room")
|
||||||
|
verbose_name_plural = _("reservable rooms")
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.name
|
||||||
|
|
||||||
|
def can_be_edited_by(self, user: User) -> bool:
|
||||||
|
# a user may edit a room if it has the global perm
|
||||||
|
# or is in the owner club board
|
||||||
|
return user.has_perm("reservation.change_room") or self.club.board_group_id in [
|
||||||
|
g.id for g in user.cached_groups
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationSlotQuerySet(models.QuerySet):
|
||||||
|
def overlapping_with(self, slot: ReservationSlot) -> Self:
|
||||||
|
return self.filter(
|
||||||
|
Q(start_at__lt=slot.start_at, end_at__gt=slot.start_at)
|
||||||
|
| Q(start_at__lt=slot.end_at, end_at__gt=slot.end_at)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationSlot(models.Model):
|
||||||
|
room = models.ForeignKey(
|
||||||
|
Room,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="slots",
|
||||||
|
verbose_name=_("reserved room"),
|
||||||
|
)
|
||||||
|
author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("author"))
|
||||||
|
comment = models.TextField(_("comment"), blank=True, default="")
|
||||||
|
start_at = models.DateTimeField(_("slot start"), db_index=True)
|
||||||
|
end_at = models.DateTimeField(_("slot end"))
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
objects = ReservationSlotQuerySet.as_manager()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = _("reservation slot")
|
||||||
|
verbose_name_plural = _("reservation slots")
|
||||||
|
constraints = [
|
||||||
|
models.CheckConstraint(
|
||||||
|
condition=Q(end_at__gt=F("start_at")),
|
||||||
|
name="reservation_slot_end_after_start",
|
||||||
|
violation_error_code="start_after_end",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"{self.room.name} : {self.start_at} - {self.end_at}"
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
super().clean()
|
||||||
|
if self.end_at is None or self.start_at is None:
|
||||||
|
# if there is no start or no end, then there is no
|
||||||
|
# point to check if this perm overlap with another,
|
||||||
|
# so in this case, don't do the overlap check and let
|
||||||
|
# Django manage the non-null constraint error.
|
||||||
|
return
|
||||||
|
overlapping = ReservationSlot.objects.overlapping_with(self).filter(
|
||||||
|
room_id=self.room_id
|
||||||
|
)
|
||||||
|
if self.id is not None:
|
||||||
|
overlapping = overlapping.exclude(id=self.id)
|
||||||
|
if overlapping.exists():
|
||||||
|
raise ValidationError(_("There is already a reservation on this slot."))
|
||||||
46
reservation/schemas.py
Normal file
46
reservation/schemas.py
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from ninja import FilterSchema, ModelSchema, Schema
|
||||||
|
from pydantic import Field, FutureDatetime
|
||||||
|
|
||||||
|
from club.schemas import SimpleClubSchema
|
||||||
|
from core.schemas import SimpleUserSchema
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
|
|
||||||
|
|
||||||
|
class RoomFilterSchema(FilterSchema):
|
||||||
|
club: set[int] | None = Field(None, q="club_id__in")
|
||||||
|
|
||||||
|
|
||||||
|
class RoomSchema(ModelSchema):
|
||||||
|
class Meta:
|
||||||
|
model = Room
|
||||||
|
fields = ["id", "name", "description", "location"]
|
||||||
|
|
||||||
|
club: SimpleClubSchema
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def resolve_location(obj: Room):
|
||||||
|
return obj.get_location_display()
|
||||||
|
|
||||||
|
|
||||||
|
class SlotFilterSchema(FilterSchema):
|
||||||
|
after: datetime = Field(default=None, q="end_at__gt")
|
||||||
|
before: datetime = Field(default=None, q="start_at__lt")
|
||||||
|
room: set[int] | None = None
|
||||||
|
club: set[int] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SlotSchema(ModelSchema):
|
||||||
|
class Meta:
|
||||||
|
model = ReservationSlot
|
||||||
|
fields = ["id", "room", "comment"]
|
||||||
|
|
||||||
|
start: datetime = Field(alias="start_at")
|
||||||
|
end: datetime = Field(alias="end_at")
|
||||||
|
author: SimpleUserSchema
|
||||||
|
|
||||||
|
|
||||||
|
class UpdateReservationSlotSchema(Schema):
|
||||||
|
start_at: FutureDatetime
|
||||||
|
end_at: FutureDatetime
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import {
|
||||||
|
Calendar,
|
||||||
|
type DateSelectArg,
|
||||||
|
type EventDropArg,
|
||||||
|
type EventSourceFuncArg,
|
||||||
|
} from "@fullcalendar/core";
|
||||||
|
import enLocale from "@fullcalendar/core/locales/en-gb";
|
||||||
|
import frLocale from "@fullcalendar/core/locales/fr";
|
||||||
|
import interactionPlugin, { type EventResizeDoneArg } from "@fullcalendar/interaction";
|
||||||
|
import resourceTimelinePlugin from "@fullcalendar/resource-timeline";
|
||||||
|
import { paginated } from "#core:utils/api";
|
||||||
|
import { inheritHtmlElement, registerComponent } from "#core:utils/web-components";
|
||||||
|
import {
|
||||||
|
type ReservationslotFetchSlotsData,
|
||||||
|
reservableroomFetchRooms,
|
||||||
|
reservationslotFetchSlots,
|
||||||
|
reservationslotUpdateSlot,
|
||||||
|
type SlotSchema,
|
||||||
|
} from "#openapi";
|
||||||
|
import type { SlotSelectedEventArg } from "#reservation:reservation/types";
|
||||||
|
|
||||||
|
@registerComponent("room-scheduler")
|
||||||
|
export class RoomScheduler extends inheritHtmlElement("div") {
|
||||||
|
static observedAttributes = ["locale", "can_edit_slot", "can_create_slot"];
|
||||||
|
private scheduler: Calendar;
|
||||||
|
private locale = "en";
|
||||||
|
private canEditSlot = false;
|
||||||
|
private canBookSlot = false;
|
||||||
|
private canDeleteSlot = false;
|
||||||
|
|
||||||
|
attributeChangedCallback(name: string, _oldValue?: string, newValue?: string) {
|
||||||
|
if (name === "locale") {
|
||||||
|
this.locale = newValue;
|
||||||
|
}
|
||||||
|
if (name === "can_edit_slot") {
|
||||||
|
this.canEditSlot = newValue.toLowerCase() === "true";
|
||||||
|
}
|
||||||
|
if (name === "can_create_slot") {
|
||||||
|
this.canBookSlot = newValue.toLowerCase() === "true";
|
||||||
|
}
|
||||||
|
if (name === "can_delete_slot") {
|
||||||
|
this.canDeleteSlot = newValue.toLowerCase() === "true";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the events displayed in the timeline.
|
||||||
|
* cf https://fullcalendar.io/docs/events-function
|
||||||
|
*/
|
||||||
|
async fetchEvents(fetchInfo: EventSourceFuncArg) {
|
||||||
|
const res: SlotSchema[] = await paginated(reservationslotFetchSlots, {
|
||||||
|
query: { after: fetchInfo.startStr, before: fetchInfo.endStr },
|
||||||
|
} as ReservationslotFetchSlotsData);
|
||||||
|
return res.map((i) =>
|
||||||
|
Object.assign(i, {
|
||||||
|
title: `${i.author.first_name} ${i.author.last_name}`,
|
||||||
|
resourceId: i.room,
|
||||||
|
editable: new Date(i.start) > new Date(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the resources which events are associated with.
|
||||||
|
* cf https://fullcalendar.io/docs/resources-function
|
||||||
|
*/
|
||||||
|
async fetchResources() {
|
||||||
|
const res = await reservableroomFetchRooms();
|
||||||
|
return res.data.map((i) => Object.assign(i, { title: i.name, group: i.location }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a request to the API to change
|
||||||
|
* the start and the duration of a reservation slot
|
||||||
|
*/
|
||||||
|
async changeReservation(args: EventDropArg | EventResizeDoneArg) {
|
||||||
|
const response = await reservationslotUpdateSlot({
|
||||||
|
// biome-ignore lint/style/useNamingConvention: api is snake_case
|
||||||
|
path: { slot_id: Number.parseInt(args.event.id) },
|
||||||
|
// biome-ignore lint/style/useNamingConvention: api is snake_case
|
||||||
|
body: { start_at: args.event.startStr, end_at: args.event.endStr },
|
||||||
|
});
|
||||||
|
if (response.response.ok) {
|
||||||
|
document.dispatchEvent(new CustomEvent("reservationSlotChanged"));
|
||||||
|
this.scheduler.refetchEvents();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
selectFreeSlot(infos: DateSelectArg) {
|
||||||
|
document.dispatchEvent(
|
||||||
|
new CustomEvent<SlotSelectedEventArg>("timeSlotSelected", {
|
||||||
|
detail: {
|
||||||
|
ressource: Number.parseInt(infos.resource.id),
|
||||||
|
start: infos.startStr,
|
||||||
|
end: infos.endStr,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
connectedCallback() {
|
||||||
|
super.connectedCallback();
|
||||||
|
this.scheduler = new Calendar(this.node, {
|
||||||
|
schedulerLicenseKey: "GPL-My-Project-Is-Open-Source",
|
||||||
|
initialView: "resourceTimelineDay",
|
||||||
|
headerToolbar: {
|
||||||
|
left: "prev,next today",
|
||||||
|
center: "title",
|
||||||
|
right: "resourceTimelineDay,resourceTimelineWeek",
|
||||||
|
},
|
||||||
|
plugins: [resourceTimelinePlugin, interactionPlugin],
|
||||||
|
locales: [frLocale, enLocale],
|
||||||
|
height: "auto",
|
||||||
|
locale: this.locale,
|
||||||
|
resourceGroupField: "group",
|
||||||
|
resourceAreaHeaderContent: gettext("Rooms"),
|
||||||
|
editable: this.canEditSlot,
|
||||||
|
snapDuration: "00:15",
|
||||||
|
eventConstraint: { start: new Date() }, // forbid edition of past events
|
||||||
|
eventOverlap: false,
|
||||||
|
eventResourceEditable: false,
|
||||||
|
refetchResourcesOnNavigate: true,
|
||||||
|
resourceAreaWidth: "20%",
|
||||||
|
resources: this.fetchResources,
|
||||||
|
events: this.fetchEvents,
|
||||||
|
select: this.selectFreeSlot,
|
||||||
|
selectOverlap: false,
|
||||||
|
selectable: this.canBookSlot,
|
||||||
|
selectConstraint: { start: new Date() },
|
||||||
|
nowIndicator: true,
|
||||||
|
eventDrop: this.changeReservation,
|
||||||
|
eventResize: this.changeReservation,
|
||||||
|
});
|
||||||
|
this.scheduler.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { AlertMessage } from "#core:utils/alert-message";
|
||||||
|
import type { SlotSelectedEventArg } from "#reservation:reservation/types";
|
||||||
|
|
||||||
|
document.addEventListener("alpine:init", () => {
|
||||||
|
Alpine.data("slotReservation", () => ({
|
||||||
|
start: null as string,
|
||||||
|
end: null as string,
|
||||||
|
room: null as number,
|
||||||
|
showForm: false,
|
||||||
|
|
||||||
|
init() {
|
||||||
|
document.addEventListener(
|
||||||
|
"timeSlotSelected",
|
||||||
|
(event: CustomEvent<SlotSelectedEventArg>) => {
|
||||||
|
this.start = event.detail.start.split("+")[0];
|
||||||
|
this.end = event.detail.end.split("+")[0];
|
||||||
|
this.room = event.detail.ressource;
|
||||||
|
this.showForm = true;
|
||||||
|
this.$nextTick(() => this.$el.scrollIntoView({ behavior: "smooth" })).then();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Component that will catch events sent from the scheduler
|
||||||
|
* to display success messages accordingly.
|
||||||
|
*/
|
||||||
|
Alpine.data("scheduleMessages", () => ({
|
||||||
|
alertMessage: new AlertMessage({ defaultDuration: 2000 }),
|
||||||
|
init() {
|
||||||
|
document.addEventListener("reservationSlotChanged", (_event: CustomEvent) => {
|
||||||
|
this.alertMessage.display(gettext("This slot has been successfully moved"), {
|
||||||
|
success: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
});
|
||||||
5
reservation/static/bundled/reservation/types.d.ts
vendored
Normal file
5
reservation/static/bundled/reservation/types.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export interface SlotSelectedEventArg {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
ressource: number;
|
||||||
|
}
|
||||||
39
reservation/static/reservation/reservation.scss
Normal file
39
reservation/static/reservation/reservation.scss
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
#slot-reservation {
|
||||||
|
margin-top: 3em;
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
display: block;
|
||||||
|
margin: auto;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert, .error {
|
||||||
|
display: block;
|
||||||
|
margin: 1em auto auto;
|
||||||
|
max-width: 400px;
|
||||||
|
word-wrap: break-word;
|
||||||
|
text-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: .5em;
|
||||||
|
justify-content: center;
|
||||||
|
|
||||||
|
.buttons-row {
|
||||||
|
input[type="submit"], button {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
textarea {
|
||||||
|
max-width: unset;
|
||||||
|
width: 100%;
|
||||||
|
margin-top: unset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<section
|
||||||
|
id="slot-reservation"
|
||||||
|
x-data="slotReservation"
|
||||||
|
x-show="showForm"
|
||||||
|
hx-target="this"
|
||||||
|
hx-ext="alpine-morph"
|
||||||
|
hx-swap="morph"
|
||||||
|
>
|
||||||
|
<h3>{% trans %}Book a room{% endtrans %}</h3>
|
||||||
|
{% set non_field_errors = form.non_field_errors() %}
|
||||||
|
{% if non_field_errors %}
|
||||||
|
<div class="alert alert-red">
|
||||||
|
{% for error in non_field_errors %}
|
||||||
|
<span>{{ error }}</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<form
|
||||||
|
id="slot-reservation-form"
|
||||||
|
hx-post="{{ url("reservation:make_reservation") }}"
|
||||||
|
hx-disabled-elt="find input[type='submit']"
|
||||||
|
>
|
||||||
|
{% csrf_token %}
|
||||||
|
<div class="form-group">
|
||||||
|
{{ form.room.errors }}
|
||||||
|
{{ form.room.label_tag() }}
|
||||||
|
{{ form.room|add_attr("x-model=room") }}
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
{{ form.start_at.errors }}
|
||||||
|
{{ form.start_at.label_tag() }}
|
||||||
|
{{ form.start_at|add_attr("x-model=start") }}
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
{{ form.end_at.errors }}
|
||||||
|
{{ form.end_at.label_tag() }}
|
||||||
|
{{ form.end_at|add_attr("x-model=end") }}
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
{{ form.comment.errors }}
|
||||||
|
{{ form.comment.label_tag() }}
|
||||||
|
{{ form.comment }}
|
||||||
|
</div>
|
||||||
|
<div class="row gap buttons-row">
|
||||||
|
<button class="btn btn-grey grow" @click.prevent="showForm = false">
|
||||||
|
{% trans %}Cancel{% endtrans %}
|
||||||
|
</button>
|
||||||
|
<input class="btn btn-blue grow" type="submit">
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
27
reservation/templates/reservation/macros.jinja
Normal file
27
reservation/templates/reservation/macros.jinja
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
{% macro room_detail(room, can_edit, can_delete) %}
|
||||||
|
<div class="card card-row card-row-m">
|
||||||
|
<div class="card-content">
|
||||||
|
<strong class="card-title">{{ room.name }}</strong>
|
||||||
|
<em>{{ room.get_location_display() }}</em>
|
||||||
|
<p>{{ room.description|truncate(250) }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="card-top-left">
|
||||||
|
{% if can_edit %}
|
||||||
|
<a
|
||||||
|
class="btn btn-grey btn-no-text"
|
||||||
|
href="{{ url("reservation:room_edit", room_id=room.id) }}"
|
||||||
|
>
|
||||||
|
<i class="fa fa-edit"></i>
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if can_delete %}
|
||||||
|
<a
|
||||||
|
class="btn btn-red btn-no-text"
|
||||||
|
href="{{ url("reservation:room_delete", room_id=room.id) }}"
|
||||||
|
>
|
||||||
|
<i class="fa fa-trash"></i>
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endmacro %}
|
||||||
33
reservation/templates/reservation/schedule.jinja
Normal file
33
reservation/templates/reservation/schedule.jinja
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
{% extends "core/base.jinja" %}
|
||||||
|
|
||||||
|
{% block additional_js %}
|
||||||
|
<script type="module" src="{{ static("bundled/reservation/components/room-scheduler-index.ts") }}"></script>
|
||||||
|
<script type="module" src="{{ static("bundled/reservation/slot-reservation-index.ts") }}"></script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block additional_css %}
|
||||||
|
<link rel="stylesheet" href="{{ static('core/components/calendar.scss') }}">
|
||||||
|
<link rel="stylesheet" href="{{ static('reservation/reservation.scss') }}">
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h2 class="margin-bottom">{% trans %}Room reservation{% endtrans %}</h2>
|
||||||
|
<p
|
||||||
|
x-data="scheduleMessages"
|
||||||
|
class="alert snackbar"
|
||||||
|
:class="alertMessage.success ? 'alert-green' : 'alert-red'"
|
||||||
|
x-show="alertMessage.open"
|
||||||
|
x-transition.duration.500ms
|
||||||
|
x-text="alertMessage.content"
|
||||||
|
></p>
|
||||||
|
<room-scheduler
|
||||||
|
locale="{{ LANGUAGE_CODE }}"
|
||||||
|
can_edit_slot="{{ user.has_perm("reservation.change_reservationslot") }}"
|
||||||
|
can_create_slot="{{ user.has_perm("reservation.add_reservationslot") }}"
|
||||||
|
></room-scheduler>
|
||||||
|
{% if user.has_perm("reservation.add_reservationslot") %}
|
||||||
|
<p><em>{% trans %}You can book a room by selecting a free slot in the calendar.{% endtrans %}</em></p>
|
||||||
|
{{ add_slot_fragment }}
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
0
reservation/tests/__init__.py
Normal file
0
reservation/tests/__init__.py
Normal file
113
reservation/tests/test_room.py
Normal file
113
reservation/tests/test_room.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import pytest
|
||||||
|
from django.contrib.auth.models import Permission
|
||||||
|
from django.test import Client
|
||||||
|
from django.urls import reverse
|
||||||
|
from model_bakery import baker
|
||||||
|
from pytest_django.asserts import assertNumQueries, assertRedirects
|
||||||
|
|
||||||
|
from club.models import Club
|
||||||
|
from core.models import User
|
||||||
|
from reservation.forms import RoomUpdateForm
|
||||||
|
from reservation.models import Room
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestFetchRoom:
|
||||||
|
@pytest.fixture
|
||||||
|
def user(self):
|
||||||
|
return baker.make(
|
||||||
|
User,
|
||||||
|
user_permissions=[Permission.objects.get(codename="view_room")],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_fetch_simple(self, client: Client, user: User):
|
||||||
|
rooms = baker.make(Room, _quantity=3, _bulk_create=True)
|
||||||
|
client.force_login(user)
|
||||||
|
response = client.get(reverse("api:fetch_reservable_rooms"))
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == [
|
||||||
|
{
|
||||||
|
"id": room.id,
|
||||||
|
"name": room.name,
|
||||||
|
"description": room.description,
|
||||||
|
"location": room.location,
|
||||||
|
"club": {"id": room.club.id, "name": room.club.name},
|
||||||
|
}
|
||||||
|
for room in rooms
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_nb_queries(self, client: Client, user: User):
|
||||||
|
client.force_login(user)
|
||||||
|
with assertNumQueries(5):
|
||||||
|
# 4 for authentication
|
||||||
|
# 1 to fetch the actual data
|
||||||
|
client.get(reverse("api:fetch_reservable_rooms"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestCreateRoom:
|
||||||
|
def test_ok(self, client: Client):
|
||||||
|
perm = Permission.objects.get(codename="add_room")
|
||||||
|
club = baker.make(Club)
|
||||||
|
client.force_login(
|
||||||
|
baker.make(User, user_permissions=[perm], groups=[club.board_group])
|
||||||
|
)
|
||||||
|
response = client.post(
|
||||||
|
reverse("reservation:room_create"),
|
||||||
|
data={"club": club.id, "name": "test", "location": "BELFORT"},
|
||||||
|
)
|
||||||
|
assertRedirects(response, reverse("club:tools", kwargs={"club_id": club.id}))
|
||||||
|
room = Room.objects.last()
|
||||||
|
assert room is not None
|
||||||
|
assert room.club == club
|
||||||
|
assert room.name == "test"
|
||||||
|
assert room.location == "BELFORT"
|
||||||
|
|
||||||
|
def test_permission_denied(self, client: Client):
|
||||||
|
club = baker.make(Club)
|
||||||
|
client.force_login(baker.make(User))
|
||||||
|
response = client.get(reverse("reservation:room_create"))
|
||||||
|
assert response.status_code == 403
|
||||||
|
response = client.post(
|
||||||
|
reverse("reservation:room_create"),
|
||||||
|
data={"club": club.id, "name": "test", "location": "BELFORT"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestUpdateRoom:
|
||||||
|
def test_ok(self, client: Client):
|
||||||
|
club = baker.make(Club)
|
||||||
|
room = baker.make(Room, club=club)
|
||||||
|
client.force_login(baker.make(User, groups=[club.board_group]))
|
||||||
|
url = reverse("reservation:room_edit", kwargs={"room_id": room.id})
|
||||||
|
response = client.post(url, data={"name": "test", "location": "BELFORT"})
|
||||||
|
assertRedirects(response, url)
|
||||||
|
room.refresh_from_db()
|
||||||
|
assert room.club == club
|
||||||
|
assert room.name == "test"
|
||||||
|
assert room.location == "BELFORT"
|
||||||
|
|
||||||
|
def test_permission_denied(self, client: Client):
|
||||||
|
club = baker.make(Club)
|
||||||
|
room = baker.make(Room, club=club)
|
||||||
|
client.force_login(baker.make(User))
|
||||||
|
url = reverse("reservation:room_edit", kwargs={"room_id": room.id})
|
||||||
|
response = client.get(url)
|
||||||
|
assert response.status_code == 403
|
||||||
|
response = client.post(url, data={"name": "test", "location": "BELFORT"})
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestUpdateRoomForm:
|
||||||
|
def test_form_club_edition_rights(self):
|
||||||
|
"""The club field should appear only if the request user can edit it."""
|
||||||
|
room = baker.make(Room)
|
||||||
|
perm = Permission.objects.get(codename="change_room")
|
||||||
|
user_authorized = baker.make(User, user_permissions=[perm])
|
||||||
|
assert "club" in RoomUpdateForm(request_user=user_authorized).fields
|
||||||
|
|
||||||
|
user_forbidden = baker.make(User, groups=[room.club.board_group])
|
||||||
|
assert "club" not in RoomUpdateForm(request_user=user_forbidden).fields
|
||||||
207
reservation/tests/test_slot.py
Normal file
207
reservation/tests/test_slot.py
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.contrib.auth.models import Permission
|
||||||
|
from django.test import Client
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils.timezone import now
|
||||||
|
from model_bakery import baker
|
||||||
|
from pytest_django.asserts import assertNumQueries
|
||||||
|
|
||||||
|
from core.models import User
|
||||||
|
from reservation.forms import ReservationForm
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestFetchReservationSlotsApi:
|
||||||
|
@pytest.fixture
|
||||||
|
def user(self):
|
||||||
|
perm = Permission.objects.get(codename="view_reservationslot")
|
||||||
|
return baker.make(User, user_permissions=[perm])
|
||||||
|
|
||||||
|
def test_fetch_simple(self, client: Client, user: User):
|
||||||
|
slots = baker.make(ReservationSlot, _quantity=5, _bulk_create=True)
|
||||||
|
client.force_login(user)
|
||||||
|
response = client.get(reverse("api:fetch_reservation_slots"))
|
||||||
|
assert response.json()["results"] == [
|
||||||
|
{
|
||||||
|
"id": slot.id,
|
||||||
|
"room": slot.room_id,
|
||||||
|
"comment": slot.comment,
|
||||||
|
"start": slot.start_at.isoformat(timespec="milliseconds").replace(
|
||||||
|
"+00:00", "Z"
|
||||||
|
),
|
||||||
|
"end": slot.end_at.isoformat(timespec="milliseconds").replace(
|
||||||
|
"+00:00", "Z"
|
||||||
|
),
|
||||||
|
"author": {
|
||||||
|
"id": slot.author.id,
|
||||||
|
"first_name": slot.author.first_name,
|
||||||
|
"last_name": slot.author.last_name,
|
||||||
|
"nick_name": slot.author.nick_name,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for slot in slots
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_nb_queries(self, client: Client, user: User):
|
||||||
|
client.force_login(user)
|
||||||
|
with assertNumQueries(5):
|
||||||
|
# 4 for authentication
|
||||||
|
# 1 to fetch the actual data
|
||||||
|
client.get(reverse("api:fetch_reservation_slots"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestUpdateReservationSlotApi:
|
||||||
|
@pytest.fixture
|
||||||
|
def user(self):
|
||||||
|
perm = Permission.objects.get(codename="change_reservationslot")
|
||||||
|
return baker.make(User, user_permissions=[perm])
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def slot(self):
|
||||||
|
return baker.make(
|
||||||
|
ReservationSlot,
|
||||||
|
start_at=now() + timedelta(hours=2),
|
||||||
|
end_at=now() + timedelta(hours=4),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_ok(self, client: Client, user: User, slot: ReservationSlot):
|
||||||
|
client.force_login(user)
|
||||||
|
new_start = (slot.start_at + timedelta(hours=1)).replace(microsecond=0)
|
||||||
|
response = client.patch(
|
||||||
|
reverse("api:change_reservation_slot", kwargs={"slot_id": slot.id}),
|
||||||
|
{"start_at": new_start, "end_at": new_start + timedelta(hours=2)},
|
||||||
|
content_type="application/json",
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
slot.refresh_from_db()
|
||||||
|
assert slot.start_at.replace(microsecond=0) == new_start
|
||||||
|
assert slot.end_at.replace(microsecond=0) == new_start + timedelta(hours=2)
|
||||||
|
|
||||||
|
def test_change_past_event(self, client, user: User, slot: ReservationSlot):
|
||||||
|
"""Test that moving a slot that already began is impossible."""
|
||||||
|
client.force_login(user)
|
||||||
|
new_start = now() - timedelta(hours=1)
|
||||||
|
response = client.patch(
|
||||||
|
reverse("api:change_reservation_slot", kwargs={"slot_id": slot.id}),
|
||||||
|
{"start_at": new_start, "end_at": new_start + timedelta(hours=2)},
|
||||||
|
content_type="application/json",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
|
||||||
|
def test_move_event_to_occupied_slot(
|
||||||
|
self, client: Client, user: User, slot: ReservationSlot
|
||||||
|
):
|
||||||
|
client.force_login(user)
|
||||||
|
other_slot = baker.make(
|
||||||
|
ReservationSlot,
|
||||||
|
room=slot.room,
|
||||||
|
start_at=slot.end_at + timedelta(hours=1),
|
||||||
|
end_at=slot.end_at + timedelta(hours=3),
|
||||||
|
)
|
||||||
|
response = client.patch(
|
||||||
|
reverse("api:change_reservation_slot", kwargs={"slot_id": slot.id}),
|
||||||
|
{
|
||||||
|
"start_at": other_slot.start_at - timedelta(hours=1),
|
||||||
|
"end_at": other_slot.start_at + timedelta(hours=1),
|
||||||
|
},
|
||||||
|
content_type="application/json",
|
||||||
|
)
|
||||||
|
assert response.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestReservationForm:
|
||||||
|
def test_ok(self):
|
||||||
|
start = now() + timedelta(hours=2)
|
||||||
|
end = start + timedelta(hours=1)
|
||||||
|
form = ReservationForm(
|
||||||
|
author=baker.make(User),
|
||||||
|
data={"room": baker.make(Room), "start_at": start, "end_at": end},
|
||||||
|
)
|
||||||
|
assert form.is_valid()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("start_date", "end_date", "errors"),
|
||||||
|
[
|
||||||
|
(
|
||||||
|
now() - timedelta(hours=2),
|
||||||
|
now() + timedelta(hours=2),
|
||||||
|
{"start_at": ["Assurez-vous que cet horodatage est dans le futur"]},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
now() + timedelta(hours=3),
|
||||||
|
now() + timedelta(hours=2),
|
||||||
|
{"__all__": ["Le début doit être placé avant la fin"]},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_timedates(self, start_date, end_date, errors):
|
||||||
|
form = ReservationForm(
|
||||||
|
author=baker.make(User),
|
||||||
|
data={"room": baker.make(Room), "start_at": start_date, "end_at": end_date},
|
||||||
|
)
|
||||||
|
assert not form.is_valid()
|
||||||
|
assert form.errors == errors
|
||||||
|
|
||||||
|
def test_unavailable_room(self):
|
||||||
|
room = baker.make(Room)
|
||||||
|
baker.make(
|
||||||
|
ReservationSlot,
|
||||||
|
room=room,
|
||||||
|
start_at=now() + timedelta(hours=2),
|
||||||
|
end_at=now() + timedelta(hours=4),
|
||||||
|
)
|
||||||
|
form = ReservationForm(
|
||||||
|
author=baker.make(User),
|
||||||
|
data={
|
||||||
|
"room": room,
|
||||||
|
"start_at": now() + timedelta(hours=1),
|
||||||
|
"end_at": now() + timedelta(hours=3),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert not form.is_valid()
|
||||||
|
assert form.errors == {
|
||||||
|
"__all__": ["Il y a déjà une réservation sur ce créneau."]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestCreateReservationSlot:
|
||||||
|
@pytest.fixture
|
||||||
|
def user(self):
|
||||||
|
perms = Permission.objects.filter(
|
||||||
|
codename__in=["add_reservationslot", "view_reservationslot"]
|
||||||
|
)
|
||||||
|
return baker.make(User, user_permissions=list(perms))
|
||||||
|
|
||||||
|
def test_ok(self, client: Client, user: User):
|
||||||
|
client.force_login(user)
|
||||||
|
start = now() + timedelta(hours=2)
|
||||||
|
end = start + timedelta(hours=1)
|
||||||
|
room = baker.make(Room)
|
||||||
|
response = client.post(
|
||||||
|
reverse("reservation:make_reservation"),
|
||||||
|
{"room": room.id, "start_at": start, "end_at": end},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.headers.get("HX-Redirect", "") == reverse("reservation:main")
|
||||||
|
slot = ReservationSlot.objects.filter(room=room).last()
|
||||||
|
assert slot is not None
|
||||||
|
assert slot.start_at == start
|
||||||
|
assert slot.end_at == end
|
||||||
|
assert slot.author == user
|
||||||
|
|
||||||
|
def test_permissions_denied(self, client: Client):
|
||||||
|
client.force_login(baker.make(User))
|
||||||
|
start = now() + timedelta(hours=2)
|
||||||
|
end = start + timedelta(hours=1)
|
||||||
|
response = client.post(
|
||||||
|
reverse("reservation:make_reservation"),
|
||||||
|
{"room": baker.make(Room), "start_at": start, "end_at": end},
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
19
reservation/urls.py
Normal file
19
reservation/urls.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from reservation.views import (
|
||||||
|
ReservationFragment,
|
||||||
|
ReservationScheduleView,
|
||||||
|
RoomCreateView,
|
||||||
|
RoomDeleteView,
|
||||||
|
RoomUpdateView,
|
||||||
|
)
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("", ReservationScheduleView.as_view(), name="main"),
|
||||||
|
path("room/create/", RoomCreateView.as_view(), name="room_create"),
|
||||||
|
path("room/<int:room_id>/edit", RoomUpdateView.as_view(), name="room_edit"),
|
||||||
|
path("room/<int:room_id>/delete", RoomDeleteView.as_view(), name="room_delete"),
|
||||||
|
path(
|
||||||
|
"fragment/reservation", ReservationFragment.as_view(), name="make_reservation"
|
||||||
|
),
|
||||||
|
]
|
||||||
72
reservation/views.py
Normal file
72
reservation/views.py
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
# Create your views here.
|
||||||
|
|
||||||
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
|
from django.contrib.messages.views import SuccessMessageMixin
|
||||||
|
from django.urls import reverse, reverse_lazy
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
from django.views.generic import CreateView, DeleteView, TemplateView, UpdateView
|
||||||
|
|
||||||
|
from club.models import Club
|
||||||
|
from core.auth.mixins import CanEditMixin
|
||||||
|
from core.views import UseFragmentsMixin
|
||||||
|
from core.views.mixins import FragmentMixin
|
||||||
|
from reservation.forms import ReservationForm, RoomCreateForm, RoomUpdateForm
|
||||||
|
from reservation.models import ReservationSlot, Room
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationFragment(PermissionRequiredMixin, FragmentMixin, CreateView):
|
||||||
|
model = ReservationSlot
|
||||||
|
form_class = ReservationForm
|
||||||
|
permission_required = "reservation.add_reservationslot"
|
||||||
|
template_name = "reservation/fragments/create_reservation.jinja"
|
||||||
|
success_url = reverse_lazy("reservation:main")
|
||||||
|
reload_on_redirect = True
|
||||||
|
object = None
|
||||||
|
|
||||||
|
def get_form_kwargs(self):
|
||||||
|
return super().get_form_kwargs() | {"author": self.request.user}
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationScheduleView(PermissionRequiredMixin, UseFragmentsMixin, TemplateView):
|
||||||
|
template_name = "reservation/schedule.jinja"
|
||||||
|
permission_required = "reservation.view_reservationslot"
|
||||||
|
fragments = {"add_slot_fragment": ReservationFragment}
|
||||||
|
|
||||||
|
|
||||||
|
class RoomCreateView(PermissionRequiredMixin, CreateView):
|
||||||
|
form_class = RoomCreateForm
|
||||||
|
template_name = "core/create.jinja"
|
||||||
|
permission_required = "reservation.add_room"
|
||||||
|
|
||||||
|
def get_initial(self):
|
||||||
|
init = super().get_initial()
|
||||||
|
if "club" in self.request.GET:
|
||||||
|
club_id = self.request.GET["club"]
|
||||||
|
if club_id.isdigit() and int(club_id) > 0:
|
||||||
|
init["club"] = Club.objects.filter(id=int(club_id)).first()
|
||||||
|
return init
|
||||||
|
|
||||||
|
def get_success_url(self):
|
||||||
|
return reverse("club:tools", kwargs={"club_id": self.object.club_id})
|
||||||
|
|
||||||
|
|
||||||
|
class RoomUpdateView(SuccessMessageMixin, CanEditMixin, UpdateView):
|
||||||
|
model = Room
|
||||||
|
pk_url_kwarg = "room_id"
|
||||||
|
form_class = RoomUpdateForm
|
||||||
|
template_name = "core/edit.jinja"
|
||||||
|
success_message = _("%(name)s was updated successfully")
|
||||||
|
|
||||||
|
def get_form_kwargs(self):
|
||||||
|
return super().get_form_kwargs() | {"request_user": self.request.user}
|
||||||
|
|
||||||
|
def get_success_url(self):
|
||||||
|
return self.request.path
|
||||||
|
|
||||||
|
|
||||||
|
class RoomDeleteView(PermissionRequiredMixin, DeleteView):
|
||||||
|
model = Room
|
||||||
|
pk_url_kwarg = "room_id"
|
||||||
|
template_name = "core/delete_confirm.jinja"
|
||||||
|
success_url = reverse_lazy("reservation:room_list")
|
||||||
|
permission_required = "reservation.delete_room"
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import type TomSelect from "tom-select";
|
import type TomSelect from "tom-select";
|
||||||
import type { UserAjaxSelect } from "#core:core/components/ajax-select-index.ts";
|
import type { UserAjaxSelect } from "#core:core/components/ajax-select-index.ts";
|
||||||
import { paginated } from "#core:utils/api.ts";
|
import { paginated } from "#core:utils/api.ts";
|
||||||
|
import { exportToHtml } from "#core:utils/globals.ts";
|
||||||
import { History } from "#core:utils/history.ts";
|
import { History } from "#core:utils/history.ts";
|
||||||
import {
|
import {
|
||||||
type IdentifiedUserSchema,
|
type IdentifiedUserSchema,
|
||||||
@@ -108,14 +109,15 @@ interface ViewerConfig {
|
|||||||
/** id of the first picture to load on the page */
|
/** id of the first picture to load on the page */
|
||||||
firstPictureId: number;
|
firstPictureId: number;
|
||||||
/** if the user is sas admin */
|
/** if the user is sas admin */
|
||||||
userCanModerate: boolean;
|
userIsSasAdmin: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load user picture page with a nice download bar
|
* Load user picture page with a nice download bar
|
||||||
**/
|
**/
|
||||||
|
exportToHtml("loadViewer", (config: ViewerConfig) => {
|
||||||
document.addEventListener("alpine:init", () => {
|
document.addEventListener("alpine:init", () => {
|
||||||
Alpine.data("picture_viewer", (config: ViewerConfig) => ({
|
Alpine.data("picture_viewer", () => ({
|
||||||
/**
|
/**
|
||||||
* All the pictures that can be displayed on this picture viewer
|
* All the pictures that can be displayed on this picture viewer
|
||||||
**/
|
**/
|
||||||
@@ -206,7 +208,8 @@ document.addEventListener("alpine:init", () => {
|
|||||||
}
|
}
|
||||||
this.pushstate = History.Replace;
|
this.pushstate = History.Replace;
|
||||||
this.currentPicture = this.pictures.find(
|
this.currentPicture = this.pictures.find(
|
||||||
(i: PictureSchema) => i.id === Number.parseInt(event.state.sasPictureId, 10),
|
(i: PictureSchema) =>
|
||||||
|
i.id === Number.parseInt(event.state.sasPictureId, 10),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
this.pushstate = History.Replace; /* Avoid first url push */
|
this.pushstate = History.Replace; /* Avoid first url push */
|
||||||
@@ -228,7 +231,11 @@ document.addEventListener("alpine:init", () => {
|
|||||||
url: this.currentPicture.sas_url,
|
url: this.currentPicture.sas_url,
|
||||||
};
|
};
|
||||||
if (this.pushstate === History.Replace) {
|
if (this.pushstate === History.Replace) {
|
||||||
window.history.replaceState(updateArgs.data, updateArgs.unused, updateArgs.url);
|
window.history.replaceState(
|
||||||
|
updateArgs.data,
|
||||||
|
updateArgs.unused,
|
||||||
|
updateArgs.url,
|
||||||
|
);
|
||||||
this.pushstate = History.Push;
|
this.pushstate = History.Push;
|
||||||
} else {
|
} else {
|
||||||
window.history.pushState(updateArgs.data, updateArgs.unused, updateArgs.url);
|
window.history.pushState(updateArgs.data, updateArgs.unused, updateArgs.url);
|
||||||
@@ -244,7 +251,7 @@ document.addEventListener("alpine:init", () => {
|
|||||||
this.nextPicture?.preload();
|
this.nextPicture?.preload();
|
||||||
this.previousPicture?.preload();
|
this.previousPicture?.preload();
|
||||||
});
|
});
|
||||||
if (this.currentPicture.asked_for_removal && config.userCanModerate) {
|
if (this.currentPicture.asked_for_removal && config.userIsSasAdmin) {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.currentPicture.loadIdentifications(),
|
this.currentPicture.loadIdentifications(),
|
||||||
this.currentPicture.loadModeration(),
|
this.currentPicture.loadModeration(),
|
||||||
@@ -310,7 +317,7 @@ document.addEventListener("alpine:init", () => {
|
|||||||
* Check if an identification can be removed by the currently logged user
|
* Check if an identification can be removed by the currently logged user
|
||||||
*/
|
*/
|
||||||
canBeRemoved(identification: IdentifiedUserSchema): boolean {
|
canBeRemoved(identification: IdentifiedUserSchema): boolean {
|
||||||
return config.userCanModerate || identification.user.id === config.userId;
|
return config.userIsSasAdmin || identification.user.id === config.userId;
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -330,3 +337,4 @@ document.addEventListener("alpine:init", () => {
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -17,8 +17,10 @@
|
|||||||
|
|
||||||
{% from "sas/macros.jinja" import print_path %}
|
{% from "sas/macros.jinja" import print_path %}
|
||||||
|
|
||||||
|
{% set user_is_sas_admin = user.is_root or user.is_in_group(pk = settings.SITH_GROUP_SAS_ADMIN_ID) %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<main x-data="picture_viewer(config)">
|
<main x-data="picture_viewer">
|
||||||
<code>
|
<code>
|
||||||
<a href="{{ url('sas:main') }}">SAS</a> / {{ print_path(album) }} <span x-text="currentPicture.name"></span>
|
<a href="{{ url('sas:main') }}">SAS</a> / {{ print_path(album) }} <span x-text="currentPicture.name"></span>
|
||||||
</code>
|
</code>
|
||||||
@@ -48,13 +50,15 @@
|
|||||||
It will be hidden to other users until it has been moderated.
|
It will be hidden to other users until it has been moderated.
|
||||||
{% endtrans %}
|
{% endtrans %}
|
||||||
</p>
|
</p>
|
||||||
{% if user.has_perm("sas.moderate_sasfile") %}
|
{% if user_is_sas_admin %}
|
||||||
<template x-if="currentPicture.asked_for_removal">
|
<template x-if="currentPicture.asked_for_removal">
|
||||||
<div>
|
<div>
|
||||||
<h5>{% trans %}The following issues have been raised:{% endtrans %}</h5>
|
<h5>{% trans %}The following issues have been raised:{% endtrans %}</h5>
|
||||||
<template x-for="req in (currentPicture.moderationRequests ?? [])" :key="req.id">
|
<template x-for="req in (currentPicture.moderationRequests ?? [])" :key="req.id">
|
||||||
<div>
|
<div>
|
||||||
<h6 x-text="`${req.author.first_name} ${req.author.last_name}`"></h6>
|
<h6
|
||||||
|
x-text="`${req.author.first_name} ${req.author.last_name}`"
|
||||||
|
></h6>
|
||||||
<i x-text="Intl.DateTimeFormat(
|
<i x-text="Intl.DateTimeFormat(
|
||||||
'{{ LANGUAGE_CODE }}',
|
'{{ LANGUAGE_CODE }}',
|
||||||
{dateStyle: 'long', timeStyle: 'short'}
|
{dateStyle: 'long', timeStyle: 'short'}
|
||||||
@@ -66,7 +70,7 @@
|
|||||||
</template>
|
</template>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% if user.has_perm("sas.moderate_sasfile") %}
|
{% if user_is_sas_admin %}
|
||||||
<div class="alert-aside">
|
<div class="alert-aside">
|
||||||
<button class="btn btn-blue" @click="moderatePicture()">
|
<button class="btn btn-blue" @click="moderatePicture()">
|
||||||
{% trans %}Moderate{% endtrans %}
|
{% trans %}Moderate{% endtrans %}
|
||||||
@@ -200,13 +204,16 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block script %}
|
{% block script %}
|
||||||
|
{{ super() }}
|
||||||
<script>
|
<script>
|
||||||
const config = {
|
window.addEventListener("DOMContentLoaded", () => {
|
||||||
|
loadViewer({
|
||||||
albumId: {{ album.id }} ,
|
albumId: {{ album.id }} ,
|
||||||
albumUrl: "{{ album.get_absolute_url() }}",
|
albumUrl: "{{ album.get_absolute_url() }}",
|
||||||
firstPictureId: {{ picture.id }}, {# id of the first picture to show after page load #}
|
firstPictureId: {{ picture.id }}, {# id of the first picture to show after page load #}
|
||||||
userId: {{ user.id }},
|
userId: {{ user.id }},
|
||||||
userCanModerate: {{ user.has_perm("sas.moderate_sasfile")|tojson }}
|
userIsSasAdmin: {{ user_is_sas_admin|tojson }}
|
||||||
}
|
});
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -161,22 +161,16 @@ class TestSasModeration(TestCase):
|
|||||||
assert len(res.context_data["pictures"]) == 1
|
assert len(res.context_data["pictures"]) == 1
|
||||||
assert res.context_data["pictures"][0] == self.to_moderate
|
assert res.context_data["pictures"][0] == self.to_moderate
|
||||||
|
|
||||||
|
res = self.client.post(
|
||||||
|
reverse("sas:moderation"),
|
||||||
|
data={"album_id": self.to_moderate.id, "picture_id": self.to_moderate.id},
|
||||||
|
)
|
||||||
|
|
||||||
def test_moderation_page_forbidden(self):
|
def test_moderation_page_forbidden(self):
|
||||||
self.client.force_login(self.simple_user)
|
self.client.force_login(self.simple_user)
|
||||||
res = self.client.get(reverse("sas:moderation"))
|
res = self.client.get(reverse("sas:moderation"))
|
||||||
assert res.status_code == 403
|
assert res.status_code == 403
|
||||||
|
|
||||||
def test_moderate_album(self):
|
|
||||||
self.client.force_login(self.moderator)
|
|
||||||
url = reverse("sas:moderation")
|
|
||||||
album = baker.make(
|
|
||||||
Album, is_moderated=False, parent_id=settings.SITH_SAS_ROOT_DIR_ID
|
|
||||||
)
|
|
||||||
res = self.client.post(url, data={"album_id": album.id, "moderate": ""})
|
|
||||||
assertRedirects(res, url)
|
|
||||||
album.refresh_from_db()
|
|
||||||
assert album.is_moderated
|
|
||||||
|
|
||||||
def test_moderate_picture(self):
|
def test_moderate_picture(self):
|
||||||
self.client.force_login(self.moderator)
|
self.client.force_login(self.moderator)
|
||||||
res = self.client.get(
|
res = self.client.get(
|
||||||
|
|||||||
15
sas/views.py
15
sas/views.py
@@ -15,10 +15,10 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db.models import Count, OuterRef, Subquery
|
from django.db.models import Count, OuterRef, Subquery
|
||||||
from django.http import Http404, HttpResponseRedirect
|
from django.http import Http404, HttpResponseRedirect
|
||||||
from django.shortcuts import get_object_or_404, redirect
|
from django.shortcuts import get_object_or_404
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.safestring import SafeString
|
from django.utils.safestring import SafeString
|
||||||
from django.views.generic import CreateView, DetailView, TemplateView
|
from django.views.generic import CreateView, DetailView, TemplateView
|
||||||
@@ -191,13 +191,18 @@ class UserPicturesView(UserTabsMixin, CanViewMixin, DetailView):
|
|||||||
# Admin views
|
# Admin views
|
||||||
|
|
||||||
|
|
||||||
class ModerationView(PermissionRequiredMixin, TemplateView):
|
class ModerationView(TemplateView):
|
||||||
template_name = "sas/moderation.jinja"
|
template_name = "sas/moderation.jinja"
|
||||||
permission_required = "sas.moderate_sasfile"
|
|
||||||
|
def get(self, request, *args, **kwargs):
|
||||||
|
if request.user.is_in_group(pk=settings.SITH_GROUP_SAS_ADMIN_ID):
|
||||||
|
return super().get(request, *args, **kwargs)
|
||||||
|
raise PermissionDenied
|
||||||
|
|
||||||
def post(self, request, *args, **kwargs):
|
def post(self, request, *args, **kwargs):
|
||||||
if "album_id" not in request.POST:
|
if "album_id" not in request.POST:
|
||||||
raise Http404
|
raise Http404
|
||||||
|
if request.user.is_in_group(pk=settings.SITH_GROUP_SAS_ADMIN_ID):
|
||||||
album = get_object_or_404(Album, pk=request.POST["album_id"])
|
album = get_object_or_404(Album, pk=request.POST["album_id"])
|
||||||
if "moderate" in request.POST:
|
if "moderate" in request.POST:
|
||||||
album.moderator = request.user
|
album.moderator = request.user
|
||||||
@@ -205,7 +210,7 @@ class ModerationView(PermissionRequiredMixin, TemplateView):
|
|||||||
album.save()
|
album.save()
|
||||||
elif "delete" in request.POST:
|
elif "delete" in request.POST:
|
||||||
album.delete()
|
album.delete()
|
||||||
return redirect(self.request.path)
|
return super().get(request, *args, **kwargs)
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
|
|||||||
@@ -123,6 +123,7 @@ INSTALLED_APPS = (
|
|||||||
"trombi",
|
"trombi",
|
||||||
"matmat",
|
"matmat",
|
||||||
"pedagogy",
|
"pedagogy",
|
||||||
|
"reservation",
|
||||||
"galaxy",
|
"galaxy",
|
||||||
"antispam",
|
"antispam",
|
||||||
"timetable",
|
"timetable",
|
||||||
@@ -274,7 +275,7 @@ LOGGING = {
|
|||||||
# Internationalization
|
# Internationalization
|
||||||
# https://docs.djangoproject.com/en/1.8/topics/i18n/
|
# https://docs.djangoproject.com/en/1.8/topics/i18n/
|
||||||
|
|
||||||
LANGUAGE_CODE = "fr-FR"
|
LANGUAGE_CODE = "fr"
|
||||||
|
|
||||||
LANGUAGES = [("en", _("English")), ("fr", _("French"))]
|
LANGUAGES = [("en", _("English")), ("fr", _("French"))]
|
||||||
|
|
||||||
@@ -551,27 +552,27 @@ SITH_SUBSCRIPTIONS = {
|
|||||||
# Discount subscriptions
|
# Discount subscriptions
|
||||||
"un-semestre-reduction": {
|
"un-semestre-reduction": {
|
||||||
"name": _("One semester (-20%)"),
|
"name": _("One semester (-20%)"),
|
||||||
"price": 16,
|
"price": 12,
|
||||||
"duration": 1,
|
"duration": 1,
|
||||||
},
|
},
|
||||||
"deux-semestres-reduction": {
|
"deux-semestres-reduction": {
|
||||||
"name": _("Two semesters (-20%)"),
|
"name": _("Two semesters (-20%)"),
|
||||||
"price": 28,
|
"price": 22,
|
||||||
"duration": 2,
|
"duration": 2,
|
||||||
},
|
},
|
||||||
"cursus-tronc-commun-reduction": {
|
"cursus-tronc-commun-reduction": {
|
||||||
"name": _("Common core cursus (-20%)"),
|
"name": _("Common core cursus (-20%)"),
|
||||||
"price": 48,
|
"price": 36,
|
||||||
"duration": 4,
|
"duration": 4,
|
||||||
},
|
},
|
||||||
"cursus-branche-reduction": {
|
"cursus-branche-reduction": {
|
||||||
"name": _("Branch cursus (-20%)"),
|
"name": _("Branch cursus (-20%)"),
|
||||||
"price": 48,
|
"price": 36,
|
||||||
"duration": 6,
|
"duration": 6,
|
||||||
},
|
},
|
||||||
"cursus-alternant-reduction": {
|
"cursus-alternant-reduction": {
|
||||||
"name": _("Alternating cursus (-20%)"),
|
"name": _("Alternating cursus (-20%)"),
|
||||||
"price": 28,
|
"price": 24,
|
||||||
"duration": 6,
|
"duration": 6,
|
||||||
},
|
},
|
||||||
# CA special offer
|
# CA special offer
|
||||||
|
|||||||
@@ -49,6 +49,10 @@ urlpatterns = [
|
|||||||
path("trombi/", include(("trombi.urls", "trombi"), namespace="trombi")),
|
path("trombi/", include(("trombi.urls", "trombi"), namespace="trombi")),
|
||||||
path("matmatronch/", include(("matmat.urls", "matmat"), namespace="matmat")),
|
path("matmatronch/", include(("matmat.urls", "matmat"), namespace="matmat")),
|
||||||
path("pedagogy/", include(("pedagogy.urls", "pedagogy"), namespace="pedagogy")),
|
path("pedagogy/", include(("pedagogy.urls", "pedagogy"), namespace="pedagogy")),
|
||||||
|
path(
|
||||||
|
"reservation/",
|
||||||
|
include(("reservation.urls", "reservation"), namespace="reservation"),
|
||||||
|
),
|
||||||
path("admin/", admin.site.urls),
|
path("admin/", admin.site.urls),
|
||||||
path("i18n/", include("django.conf.urls.i18n")),
|
path("i18n/", include("django.conf.urls.i18n")),
|
||||||
path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
|
path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
|
||||||
|
|||||||
@@ -18,7 +18,8 @@
|
|||||||
"#core:*": ["./core/static/bundled/*"],
|
"#core:*": ["./core/static/bundled/*"],
|
||||||
"#pedagogy:*": ["./pedagogy/static/bundled/*"],
|
"#pedagogy:*": ["./pedagogy/static/bundled/*"],
|
||||||
"#counter:*": ["./counter/static/bundled/*"],
|
"#counter:*": ["./counter/static/bundled/*"],
|
||||||
"#com:*": ["./com/static/bundled/*"]
|
"#com:*": ["./com/static/bundled/*"],
|
||||||
|
"#reservation:*": ["./reservation/static/bundled/*"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
|
// biome-ignore lint/correctness/noNodejsModules: this is backend side
|
||||||
import { parse, resolve } from "node:path";
|
import { parse, resolve } from "node:path";
|
||||||
import inject from "@rollup/plugin-inject";
|
import inject from "@rollup/plugin-inject";
|
||||||
import { glob } from "glob";
|
import { glob } from "glob";
|
||||||
import { visualizer } from "rollup-plugin-visualizer";
|
import type { Rollup } from "vite";
|
||||||
import {
|
import { type AliasOptions, defineConfig, type UserConfig } from "vite";
|
||||||
type AliasOptions,
|
|
||||||
defineConfig,
|
|
||||||
type PluginOption,
|
|
||||||
type Rollup,
|
|
||||||
type UserConfig,
|
|
||||||
} from "vite";
|
|
||||||
import tsconfig from "./tsconfig.json";
|
import tsconfig from "./tsconfig.json";
|
||||||
|
|
||||||
const outDir = resolve(__dirname, "./staticfiles/generated/bundled");
|
const outDir = resolve(__dirname, "./staticfiles/generated/bundled");
|
||||||
|
const vendored = resolve(outDir, "vendored");
|
||||||
|
const nodeModules = resolve(__dirname, "node_modules");
|
||||||
const collectedFiles = glob.sync(
|
const collectedFiles = glob.sync(
|
||||||
"./!(static)/static/bundled/**/*?(-)index.?(m)[j|t]s?(x)",
|
"./!(static)/static/bundled/**/*?(-)index.?(m)[j|t]s?(x)",
|
||||||
);
|
);
|
||||||
@@ -45,6 +42,7 @@ function getRelativeAssetPath(path: string): string {
|
|||||||
return relativePath.join("/");
|
return relativePath.join("/");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// biome-ignore lint/style/noDefaultExport: this is recommended by documentation
|
||||||
export default defineConfig((config: UserConfig) => {
|
export default defineConfig((config: UserConfig) => {
|
||||||
return {
|
return {
|
||||||
base: "/static/bundled/",
|
base: "/static/bundled/",
|
||||||
@@ -88,7 +86,6 @@ export default defineConfig((config: UserConfig) => {
|
|||||||
Alpine: "alpinejs",
|
Alpine: "alpinejs",
|
||||||
htmx: "htmx.org",
|
htmx: "htmx.org",
|
||||||
}),
|
}),
|
||||||
visualizer({ filename: ".bundle-size-report.html" }) as PluginOption,
|
|
||||||
],
|
],
|
||||||
} satisfies UserConfig;
|
} satisfies UserConfig;
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user