Compare commits

...
Author SHA1 Message Date
imperosol d7e1cdafde add translations 2026-10-25 12:17:55 +01:00
imperosol 93b6238c75 Test ClubNewsView 2026-10-25 12:17:54 +01:00
imperosol 91865fe7a1 add club news view to ClubTabsMixin 2026-10-25 12:17:54 +01:00
imperosol 1e189f7b2b display club past news 2026-10-25 12:17:54 +01:00
thomas girod 32c30da0fc Merge pull request #1507 from ae-utbm/edt-save
Add user timetable saving
2026-10-24 01:09:43 +02:00
thomas girod d3f3b18660 Merge pull request #1519 from ae-utbm/page-edit-link
Move the club page edit link to the club main page
2026-10-23 20:53:47 +02:00
thomas girod e50b1fd71e Merge pull request #1525 from ae-utbm/show-all-counters-in-stats
Show all counters in user stats view
2026-10-23 16:27:33 +02:00
imperosol 78376eaca4 don't restict user counter stats to bar counters 2026-10-23 16:08:40 +02:00
thomas girod 8d56c72054 Merge pull request #1524 from ae-utbm/remove-gentoken
remove unused Counter methods
2026-10-22 19:10:47 +02:00
imperosol a794f02a8d remove unused Counter methods
`Counter.gen_token` et `Counter.get_random_barman` étaient utilisés avant la refonte du système de connexion des barmen (PR #1413), mais on a oublié de les retirer.
2026-10-22 11:56:04 +02:00
imperosol cb0a2f866d TimetableTabMixin 2026-10-22 11:39:52 +02:00
imperosol 4b4c5a73b6 add tests 2026-10-22 11:39:52 +02:00
imperosol b37b98b932 view to see a user's timetables 2026-10-22 11:39:52 +02:00
imperosol ed888834d6 split timetable parsing and display 2026-10-22 11:39:52 +02:00
imperosol 0657888076 User timetable save 2026-10-22 11:39:52 +02:00
imperosol 3f135777cd add show_my_timetable to VisibilityForm 2026-10-22 11:39:51 +02:00
imperosol 73ebe9c674 add timetable visibility to UserVisibilityForm 2026-10-22 11:39:51 +02:00
imperosol 816cbe3a2c api to save timetable 2026-10-22 11:39:51 +02:00
imperosol a33a4da143 add models 2026-10-22 11:39:51 +02:00
imperosol 2c77ed3c54 add tests 2026-10-22 11:25:40 +02:00
imperosol 3312a6214e move the club page edit link to the club main page 2026-10-22 10:07:26 +02:00
thomas girod 87533a7327 Merge pull request #1521 from ae-utbm/account-dump-msg
Add success message when refunding AE account
2026-10-21 16:35:05 +02:00
imperosol 2db46e3958 add success message when refunding AE account 2026-10-21 16:34:12 +02:00
thomas girod f2469873fd Merge pull request #1522 from ae-utbm/md-smallfix
fix: add back `.markdown` on EasyMde preview editor
2026-10-20 18:38:19 +02:00
imperosol 68c05b5b1d fix: add back .markdown on EasyMde preview editor
A l'origine, l'API retournait le markdown encapsulé dans une div avec la class `.markdown`. Quand on est passé sur notre propre lib WASM pour faire la preview entièrement côté front, on a oublié ce détail.

En même temps, on résout ici un petit glitch d'affichage qui fait qu'on avait le background des blocs de codes qui se mettait en dessous de notre propre style.
2026-10-20 12:52:20 +02:00
thomas girod 2d492e0157 Merge pull request #1511 from ae-utbm/counter-admin-mixin
remove `CounterAdminMixin`
2026-10-14 20:13:43 +02:00
thomas girod 67cfcb66b6 Merge pull request #1512 from ae-utbm/docs-populate
Small documentation fixes
2026-10-13 11:32:02 +02:00
thomas girod b560c6860b Merge pull request #1510 from ae-utbm/forum-message-403
short-circuit `ForumMessageView` redirection on 403
2026-10-13 00:12:07 +02:00
imperosol 15c5a37c99 docs: fix nushell scripts 2026-10-12 14:08:12 +02:00
imperosol 07648f596e docs: describe populated user accounts 2026-10-12 13:51:18 +02:00
imperosol 0c6594b3cd remove CounterAdminMixin 2026-10-09 21:59:37 +02:00
imperosol 22b510e25b short-circuit ForumMessageView redirection on 403
Quand on accède à cette vue, on est immédiatement redirigé vers le topic correspondant (quitte à se faire 403 une fois arrivé là). Comme la redirection est une opération qui a un cout, on peut gagner du temps en mettant un PermissionDenied directement (d'autant plus que les bots aiment beaucoup rechercher les messages du forum, et qu'ils se font systématiquement 403)
2026-10-09 16:09:54 +02:00
thomas girod c9137a2a67 Merge pull request #1508 from ae-utbm/update-deps
Update deps
2026-10-02 18:42:38 +02:00
imperosol 9f4b76dc1a update JS deps 2026-10-02 17:07:01 +02:00
imperosol ffc509c1a1 update python deps 2026-10-02 17:06:56 +02:00
thomas girod c2d76d025e Merge pull request #1485 from ae-utbm/ue-style
Ue style
2026-10-02 16:47:40 +02:00
imperosol 80f0517bf8 hide regular comment delete button when the ue comment is reported 2026-10-02 15:09:14 +02:00
imperosol 9924dc05d0 apply review comments 2026-10-02 15:09:14 +02:00
imperosol 614b870133 add translations 2026-10-02 15:09:14 +02:00
imperosol 8437728251 style: improve ue comments appearance 2026-10-02 15:09:14 +02:00
imperosol 8d3d5630c8 style: improve ue comment form appearance 2026-10-02 15:09:14 +02:00
imperosol 45cca918f1 style: improve ue detail infos appearance 2026-10-02 15:09:14 +02:00
thomas girod f211d0ff85 Merge pull request #1220 from ae-utbm/discord-auth
Third-party authentication
2026-10-02 14:55:47 +02:00
thomas girod 0bd557ae73 Merge pull request #1495 from ae-utbm/cotis-stat-quick-fix
Small improvements on subscription stats view
2026-10-02 13:49:01 +02:00
imperosol 3deefbe847 apply docs review comments 2026-10-02 09:48:23 +02:00
imperosol b2707b7862 fix: don't send callback request if data has been modified 2026-10-02 09:48:23 +02:00
imperosol 7a0f4217cc apply review comments 2026-10-02 09:48:23 +02:00
imperosol f067c60a8c tweak documentation 2026-10-02 09:48:23 +02:00
imperosol 5bea3f14e8 doc: third-party auth 2026-10-02 09:48:21 +02:00
imperosol 1efbf93f62 translation: third-party authentication 2026-10-02 09:48:09 +02:00
imperosol a84224c6ff write tests 2026-10-02 09:48:07 +02:00
imperosol 6ef0166540 third-party authentication views 2026-10-02 09:46:52 +02:00
imperosol e3a9e23d6a hmac_hexdigest util function 2026-10-01 10:17:06 +02:00
imperosol d6ab0e17f8 add hmac_key to ApiClient 2026-10-01 10:17:06 +02:00
imperosol 225b8cced9 move ResultConverter to core app 2026-10-01 10:17:06 +02:00
imperosol f271b9d1df feat: api route to get api client infos 2026-10-01 10:17:06 +02:00
thomas girod e39a73ae32 Merge pull request #1488 from ae-utbm/cgu-approve
Force CGU/ToS approval on account creation
2026-10-01 09:43:02 +02:00
thomas girod ad02026d63 Merge pull request #1506 from ae-utbm/news-next-date
display the date of next happening in NewsDetailView
2026-09-30 14:34:04 +02:00
imperosol a5440e3166 display the date of next happening in NewsDetailView 2026-09-28 19:32:40 +02:00
thomas girod 796ef72fa1 Merge pull request #1499 from ae-utbm/sas-replacestate
don't push state on sas image change
2026-09-28 17:33:46 +02:00
imperosol 44f9965557 show tooltips on subscription chart hover 2026-09-28 17:30:20 +02:00
imperosol 37871b386a optimize subscriptions stats 2026-09-28 17:30:20 +02:00
imperosol c8f4d12fc4 remove date selection from subscription stats view
Ca n'a jamais marché depuis 2017
2026-09-28 17:30:20 +02:00
imperosol 63764f54ba better subscription generation in populate_more 2026-09-28 17:30:20 +02:00
thomas girod 2d8f56f1f7 Merge pull request #1500 from ae-utbm/test-populate-more
test populate_more command
2026-09-28 16:22:02 +02:00
imperosol 809df909fd test populate_more command 2026-09-27 21:49:47 +02:00
imperosol ef1ff862a8 don't push state on sas image change 2026-09-27 19:26:02 +02:00
imperosol 19f0f23a05 use DatetimeField to store cgu approval
Au lieu de dire si l'utilisateur a approuvé les CGUs ou non, on dit quand est-ce qu'il les a approuvées. Si la date de la dernière approbation est antérieure à la date de la dernière révision des CGUs, alors on demande à nouveau de les approuver.
2026-09-25 15:43:36 +02:00
imperosol 6f701a9579 default cgu_approved=True for populated users 2026-09-25 13:21:19 +02:00
imperosol b607c86ab7 make CGU a Page instead of a File 2026-09-25 12:11:04 +02:00
imperosol 0c6a96a7ab add tests 2026-09-24 23:10:40 +02:00
imperosol c8813f708a make existing users approve CGU after login 2026-09-24 23:10:40 +02:00
imperosol 03514e4d97 refactor login.jinja 2026-09-24 23:10:40 +02:00
imperosol 4e3ed3212e force CGU/EULA approval on account creation 2026-09-24 23:10:40 +02:00
imperosol 5b02bc2e3b add CGU/EULA to populate command 2026-09-24 23:10:40 +02:00
102 changed files with 4131 additions and 1927 deletions

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.16.0
rev: v0.16.10
hooks:
- id: ruff-check # just check the code, and print the errors
- id: ruff-check # actually fix the fixable errors, but print nothing
@@ -12,7 +12,7 @@ repos:
rev: v0.6.1
hooks:
- id: biome-check
additional_dependencies: ["@biomejs/biome@2.5.1"]
additional_dependencies: ["@biomejs/biome@2.5.15"]
- repo: https://github.com/rtts/djhtml
rev: 3.0.11
hooks:
+9
View File
@@ -21,6 +21,15 @@ class ApiClientAdmin(admin.ModelAdmin):
"owner__nick_name",
)
autocomplete_fields = ("owner", "groups", "client_permissions")
readonly_fields = ("hmac_key",)
actions = ("reset_hmac_key",)
@admin.action(permissions=["change"], description=_("Reset HMAC key"))
def reset_hmac_key(self, _request: HttpRequest, queryset: QuerySet[ApiClient]):
objs = list(queryset)
for obj in objs:
obj.reset_hmac(commit=False)
ApiClient.objects.bulk_update(objs, fields=["hmac_key"])
@admin.register(ApiKey)
+16
View File
@@ -0,0 +1,16 @@
from ninja_extra import ControllerBase, api_controller, route
from api.auth import ApiKeyAuth
from api.schemas import ApiClientSchema
@api_controller("/client")
class ApiClientController(ControllerBase):
@route.get(
"/me",
auth=[ApiKeyAuth()],
response=ApiClientSchema,
url_name="api-client-infos",
)
def get_client_info(self):
return self.context.request.auth
+35
View File
@@ -0,0 +1,35 @@
from django import forms
from django.forms import HiddenInput
from django.utils.translation import gettext_lazy as _
class ThirdPartyAuthForm(forms.Form):
"""Form to complete to authenticate on the sith from a third-party app.
For the form to be valid, the user approve the EULA (french: CGU)
and give its username from the third-party app.
"""
cgu_accepted = forms.BooleanField(
required=True,
label=_("I have read and I accept the terms and conditions of use"),
error_messages={
"required": _("You must approve the terms and conditions of use.")
},
)
is_username_valid = forms.BooleanField(
required=True,
error_messages={"required": _("You must confirm that this is your username.")},
)
client_id = forms.IntegerField(widget=HiddenInput())
third_party_app = forms.CharField(widget=HiddenInput())
privacy_link = forms.URLField(widget=HiddenInput())
username = forms.CharField(widget=HiddenInput())
callback_url = forms.URLField(widget=HiddenInput())
signature = forms.CharField(widget=HiddenInput())
def __init__(self, *args, label_suffix: str = "", initial, **kwargs):
super().__init__(*args, label_suffix=label_suffix, initial=initial, **kwargs)
self.fields["is_username_valid"].label = _(
"I confirm that %(username)s is my username on %(app)s"
) % {"username": initial.get("username"), "app": initial.get("third_party_app")}
+19
View File
@@ -0,0 +1,19 @@
# Generated by Django 5.2.3 on 2025-10-26 10:15
from django.db import migrations, models
import api.models
class Migration(migrations.Migration):
dependencies = [("api", "0001_initial")]
operations = [
migrations.AddField(
model_name="apiclient",
name="hmac_key",
field=models.CharField(
default=api.models.get_hmac_key, max_length=128, verbose_name="HMAC Key"
),
),
]
+32 -21
View File
@@ -1,13 +1,20 @@
import secrets
from typing import Iterable
from django.contrib.auth.models import Permission
from django.db import models
from django.db.models import Q
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django.utils.translation import pgettext_lazy
from core.models import Group, User
def get_hmac_key():
return secrets.token_hex(64)
class ApiClient(models.Model):
name = models.CharField(_("name"), max_length=64)
owner = models.ForeignKey(
@@ -26,11 +33,10 @@ class ApiClient(models.Model):
help_text=_("Specific permissions for this api client."),
related_name="clients",
)
hmac_key = models.CharField(_("HMAC Key"), max_length=128, default=get_hmac_key)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
_perm_cache: set[str] | None = None
class Meta:
verbose_name = _("api client")
verbose_name_plural = _("api clients")
@@ -38,33 +44,38 @@ class ApiClient(models.Model):
def __str__(self):
return self.name
def has_perm(self, perm: str):
"""Return True if the client has the specified permission."""
if self._perm_cache is None:
group_permissions = (
Permission.objects.filter(group__group__in=self.groups.all())
@cached_property
def all_permissions(self) -> set[str]:
permissions = (
Permission.objects.filter(
Q(group__group__in=self.groups.all()) | Q(clients=self)
)
.values_list("content_type__app_label", "codename")
.order_by()
)
client_permissions = self.client_permissions.values_list(
"content_type__app_label", "codename"
).order_by()
self._perm_cache = {
f"{content_type}.{name}"
for content_type, name in (*group_permissions, *client_permissions)
}
return perm in self._perm_cache
return {f"{content_type}.{name}" for content_type, name in permissions}
def has_perms(self, perm_list):
"""
Return True if the client has each of the specified permissions. If
object is passed, check if the client has all required perms for it.
"""
def has_perm(self, perm: str):
"""Return True if the client has the specified permission."""
return perm in self.all_permissions
def has_perms(self, perm_list: Iterable[str]) -> bool:
"""Return True if the client has each of the specified permissions."""
if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
raise ValueError("perm_list must be an iterable of permissions.")
return all(self.has_perm(perm) for perm in perm_list)
def reset_hmac(self, *, commit: bool = True) -> str:
"""Reset and return the HMAC key for this client.
Args:
commit: if True (the default), persist the new hmac in db.
"""
self.hmac_key = get_hmac_key()
if commit:
self.save()
return self.hmac_key
class ApiKey(models.Model):
PREFIX_LENGTH = 5
+23
View File
@@ -0,0 +1,23 @@
from ninja import ModelSchema, Schema
from pydantic import Field, HttpUrl
from api.models import ApiClient
from core.schemas import SimpleUserSchema
class ApiClientSchema(ModelSchema):
class Meta:
model = ApiClient
fields = ["id", "name"]
owner: SimpleUserSchema
permissions: list[str] = Field(alias="all_permissions")
class ThirdPartyAuthParamsSchema(Schema):
client_id: int
third_party_app: str
privacy_link: HttpUrl
username: str
callback_url: HttpUrl
signature: str
+32
View File
@@ -0,0 +1,32 @@
{% extends "core/base.jinja" %}
{% block content %}
<form method="post">
{% csrf_token %}
<h3>{% trans %}Confidentiality{% endtrans %}</h3>
<p>
{% trans trimmed app=third_party_app %}
By ticking this box and clicking on the send button, you
acknowledge and agree to provide {{ app }} with your
first name, last name, nickname and any other information
that was the third party app was explicitly authorized to fetch
and that it must have acknowledged to you, in a complete and accurate manner.
{% endtrans %}
</p>
<p class="margin-bottom">
{% trans trimmed app=third_party_app, privacy_link=third_party_cgu, sith_cgu_link=sith_cgu %}
The privacy policies of <a href="{{ privacy_link }}">{{ app }}</a>
and of <a href="{{ sith_cgu_link }}">the Students' Association</a>
applies as soon as the form is submitted.
{% endtrans %}
</p>
<div class="row">{{ form.cgu_accepted }} {{ form.cgu_accepted.label_tag() }}</div>
<br>
<h3 class="margin-bottom">{% trans %}Confirmation of identity{% endtrans %}</h3>
<div class="row margin-bottom">
{{ form.is_username_valid }} {{ form.is_username_valid.label_tag() }}
</div>
{% for field in form.hidden_fields() %}{{ field }}{% endfor %}
<input type="submit" class="btn btn-blue">
</form>
{% endblock %}
+24
View File
@@ -0,0 +1,24 @@
import pytest
from django.contrib.admin import AdminSite
from django.http import HttpRequest
from model_bakery import baker
from pytest_django.asserts import assertNumQueries
from api.admin import ApiClientAdmin
from api.models import ApiClient
@pytest.mark.django_db
def test_reset_hmac_action():
client_admin = ApiClientAdmin(ApiClient, AdminSite())
api_clients = baker.make(ApiClient, _quantity=4, _bulk_create=True)
old_hmac_keys = [c.hmac_key for c in api_clients]
with assertNumQueries(2):
qs = ApiClient.objects.filter(id__in=[c.id for c in api_clients[2:4]])
client_admin.reset_hmac_key(HttpRequest(), qs)
for c in api_clients:
c.refresh_from_db()
assert api_clients[0].hmac_key == old_hmac_keys[0]
assert api_clients[1].hmac_key == old_hmac_keys[1]
assert api_clients[2].hmac_key != old_hmac_keys[2]
assert api_clients[3].hmac_key != old_hmac_keys[3]
+22
View File
@@ -0,0 +1,22 @@
from typing import TYPE_CHECKING
import pytest
from django.urls import reverse
from model_bakery import baker
from api.hashers import generate_key
from api.models import ApiClient, ApiKey
from api.schemas import ApiClientSchema
if TYPE_CHECKING:
from django.test import Client
@pytest.mark.django_db
def test_api_client_controller(client: Client):
key, hashed = generate_key()
api_client = baker.make(ApiClient)
baker.make(ApiKey, client=api_client, hashed_key=hashed)
res = client.get(reverse("api:api-client-infos"), headers={"X-APIKey": key})
assert res.status_code == 200
assert res.json() == ApiClientSchema.from_orm(api_client).model_dump()
+59
View File
@@ -0,0 +1,59 @@
import pytest
from django.contrib.auth.models import Permission
from django.test import TestCase
from model_bakery import baker
from api.models import ApiClient
from core.models import Group
class TestClientPermissions(TestCase):
@classmethod
def setUpTestData(cls):
cls.api_client = baker.make(ApiClient)
cls.perms = baker.make(Permission, _quantity=10, _bulk_create=True)
cls.api_client.groups.set(
[
baker.make(Group, permissions=cls.perms[0:3]),
baker.make(Group, permissions=cls.perms[3:5]),
]
)
cls.api_client.client_permissions.set(
[cls.perms[3], cls.perms[5], cls.perms[6], cls.perms[7]]
)
def test_all_permissions(self):
assert self.api_client.all_permissions == {
f"{p.content_type.app_label}.{p.codename}" for p in self.perms[0:8]
}
def test_has_perm(self):
assert self.api_client.has_perm(
f"{self.perms[1].content_type.app_label}.{self.perms[1].codename}"
)
assert not self.api_client.has_perm(
f"{self.perms[9].content_type.app_label}.{self.perms[9].codename}"
)
def test_has_perms(self):
assert self.api_client.has_perms(
[
f"{self.perms[1].content_type.app_label}.{self.perms[1].codename}",
f"{self.perms[2].content_type.app_label}.{self.perms[2].codename}",
]
)
assert not self.api_client.has_perms(
[
f"{self.perms[1].content_type.app_label}.{self.perms[1].codename}",
f"{self.perms[9].content_type.app_label}.{self.perms[9].codename}",
],
)
@pytest.mark.django_db
def test_reset_hmac_key():
client = baker.make(ApiClient)
original_key = client.hmac_key
client.reset_hmac(commit=True)
assert len(client.hmac_key) == len(original_key)
assert client.hmac_key != original_key
+140
View File
@@ -0,0 +1,140 @@
from unittest import mock
from unittest.mock import Mock
from django.contrib.messages import Message, get_messages
from django.db.models import Max
from django.test import TestCase
from django.urls import reverse
from model_bakery import baker
from pytest_django.asserts import assertRedirects
from api.models import ApiClient, get_hmac_key
from core.baker_recipes import subscriber_user
from core.schemas import UserProfileSchema
from core.utils import hmac_hexdigest
def mocked_post(*, ok: bool):
class MockedResponse(Mock):
@property
def ok(self):
return ok
def mocked():
return MockedResponse()
return mocked
class TestThirdPartyAuth(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = subscriber_user.make()
cls.api_client = baker.make(ApiClient)
def setUp(self):
self.query = {
"client_id": self.api_client.id,
"third_party_app": "app",
"privacy_link": "https://foobar.fr/",
"username": "bibou",
"callback_url": "https://callback.fr/",
}
self.query["signature"] = hmac_hexdigest(self.api_client.hmac_key, self.query)
self.callback_data = {
"user": UserProfileSchema.from_orm(self.user).model_dump()
}
self.callback_data["signature"] = hmac_hexdigest(
self.api_client.hmac_key, self.callback_data["user"]
)
self.url = reverse("api-link:third-party-auth", query=self.query)
def test_auth_ok(self):
self.client.force_login(self.user)
res = self.client.get(self.url)
assert res.status_code == 200
with mock.patch("requests.post", new_callable=mocked_post(ok=True)) as mocked:
res = self.client.post(
self.url,
data={"cgu_accepted": True, "is_username_valid": True, **self.query},
)
mocked.assert_called_once_with(
self.query["callback_url"], json=self.callback_data
)
assertRedirects(
res,
reverse("api-link:third-party-auth-result", kwargs={"result": "success"}),
)
def test_callback_error(self):
"""Test that the user see the failure page if the callback request failed."""
self.client.force_login(self.user)
with mock.patch("requests.post", new_callable=mocked_post(ok=False)) as mocked:
res = self.client.post(
self.url,
data={"cgu_accepted": True, "is_username_valid": True, **self.query},
)
mocked.assert_called_once_with(
self.query["callback_url"], json=self.callback_data
)
assertRedirects(
res,
reverse("api-link:third-party-auth-result", kwargs={"result": "failure"}),
)
def test_wrong_signature(self):
"""Test that a 403 is raised if the signature of the query is wrong."""
self.client.force_login(subscriber_user.make())
new_key = get_hmac_key()
del self.query["signature"]
self.query["signature"] = hmac_hexdigest(new_key, self.query)
res = self.client.get(reverse("api-link:third-party-auth", query=self.query))
assert list(get_messages(res.wsgi_request)) == [
Message(
level=40,
message=(
"La signature est incorrecte. "
"Nous ne pouvons pas garantir l'authenticité de la requête."
),
)
]
res = self.client.post(self.url, data=self.query)
assert res.status_code == 200
def test_cgu_not_accepted(self):
self.client.force_login(self.user)
res = self.client.get(self.url)
assert res.status_code == 200
res = self.client.post(self.url, data=self.query)
assert res.status_code == 200 # no redirect means invalid form
res = self.client.post(
self.url,
data={"cgu_accepted": False, "is_username_valid": False, **self.query},
)
assert res.status_code == 200
def test_invalid_client(self):
self.client.force_login(self.user)
self.query["client_id"] = ApiClient.objects.aggregate(res=Max("id"))["res"] + 1
res = self.client.get(reverse("api-link:third-party-auth", query=self.query))
assert list(get_messages(res.wsgi_request)) == [
Message(
level=40,
message="Les données fournies pour l'authentification sont incorrectes.",
)
]
def test_missing_parameter(self):
self.client.force_login(self.user)
del self.query["username"]
self.query["signature"] = hmac_hexdigest(self.api_client.hmac_key, self.query)
res = self.client.get(reverse("api-link:third-party-auth", query=self.query))
assert list(get_messages(res.wsgi_request)) == [
Message(
level=40,
message="Les données fournies pour l'authentification sont incorrectes.",
)
]
res = self.client.post(self.url, data=self.query)
assert res.status_code == 200
+15
View File
@@ -1,6 +1,10 @@
from django.urls import path, register_converter
from ninja.security import SessionAuth
from ninja_extra import NinjaExtraAPI
from api.views import ThirdPartyAuthResultView, ThirdPartyAuthView
from core.converters import ResultConverter
api = NinjaExtraAPI(
title="PICON",
description="Portail Interactif de Communication avec les Outils Numériques",
@@ -9,3 +13,14 @@ api = NinjaExtraAPI(
auth=[SessionAuth()],
)
api.auto_discover_controllers()
register_converter(ResultConverter, "res")
urlpatterns = [
path("auth/", ThirdPartyAuthView.as_view(), name="third-party-auth"),
path(
"auth/<res:result>/",
ThirdPartyAuthResultView.as_view(),
name="third-party-auth-result",
),
]
+146
View File
@@ -0,0 +1,146 @@
import hmac
from urllib.parse import unquote
import pydantic
import requests
import sentry_sdk
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import AccessMixin, LoginRequiredMixin
from django.shortcuts import render
from django.urls import reverse, reverse_lazy
from django.utils.translation import gettext as _
from django.views.generic import FormView, TemplateView
from ninja_extra.shortcuts import get_object_or_none
from api.forms import ThirdPartyAuthForm
from api.models import ApiClient
from api.schemas import ThirdPartyAuthParamsSchema
from core.models import Page
from core.schemas import UserProfileSchema
from core.utils import hmac_hexdigest
class ThirdPartyAuthView(AccessMixin, FormView):
form_class = ThirdPartyAuthForm
template_name = "api/third_party/auth.jinja"
success_url = reverse_lazy("core:index")
def parse_params(self) -> ThirdPartyAuthParamsSchema | None:
"""Parse and check the authentication parameters.
If parsing fails, messages will be created using the django message
infrastructure.
Returns:
The parses parameters, or None if the parsing failed.
"""
# This is here rather than in ThirdPartyAuthForm because
# the given parameters and their signature are checked during both
# POST (for obvious reasons) and GET (in order not to make
# the user fill a form just to get an error he won't understand)
params = self.request.GET if self.request.method == "GET" else self.request.POST
params = {key: unquote(val) for key, val in params.dict().items()}
try:
params = ThirdPartyAuthParamsSchema(**params)
except pydantic.ValidationError:
messages.error(
self.request, _("The data provided for authentication is incorrect")
)
return None
client: ApiClient | None = get_object_or_none(ApiClient, id=params.client_id)
if not client:
messages.error(
self.request, _("The data provided for authentication is incorrect")
)
return None
if not hmac.compare_digest(
hmac_hexdigest(client.hmac_key, params.model_dump(exclude={"signature"})),
params.signature,
):
messages.error(
self.request,
_(
"The signature is incorrect. "
"We cannot ensure the provenance of the request."
),
)
return None
return params
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if (params := self.parse_params()) is None:
# if parameters parsing failed, shortcut the operation and display
# an empty page with just the error messages.
return render(request, "core/base.jinja")
self.params = params
return super().dispatch(request, *args, **kwargs)
def get(self, *args, **kwargs):
messages.warning(
self.request,
_(
"You are going to link your AE account and your %(app)s account. "
"Continue only if this page was opened from %(app)s."
)
% {"app": self.params.third_party_app},
)
return super().get(*args, **kwargs)
def get_initial(self):
return self.params.model_dump()
def form_valid(self, form):
client = ApiClient.objects.get(id=form.cleaned_data["client_id"])
user = UserProfileSchema.from_orm(self.request.user).model_dump()
data = {"user": user, "signature": hmac_hexdigest(client.hmac_key, user)}
try:
ok = requests.post(form.cleaned_data["callback_url"], json=data).ok
except requests.RequestException as e:
sentry_sdk.capture_exception(e)
ok = False
self.success_url = reverse(
"api-link:third-party-auth-result",
kwargs={"result": "success" if ok else "failure"},
)
return super().form_valid(form)
def get_context_data(self, **kwargs):
return super().get_context_data(**kwargs) | {
"third_party_app": self.params.third_party_app,
"third_party_cgu": self.params.privacy_link,
"sith_cgu": Page.objects.get(_full_name=settings.SITH_CGU_PAGE),
}
class ThirdPartyAuthResultView(LoginRequiredMixin, TemplateView):
"""View that the user will see if its authentication on sith was successful.
This can show either a success or a failure message :
- success : everything is good, the user is successfully authenticated
and can close the page
- failure : the authentication has been processed on the sith side,
but the request to the callback url received an error.
In such a case, there is nothing much we can do but to advice
the user to contact the developers of the third-party app.
"""
template_name = "core/base.jinja"
success_message = _(
"You have been successfully authenticated. You can now close this page."
)
error_message = _(
"Your authentication on the AE website was successful, "
"but an error happened during the interaction "
"with the third-party application. "
"Please contact the managers of the latter."
)
def get(self, request, *args, **kwargs):
if self.kwargs.get("result") == "success":
messages.success(request, self.success_message)
else:
messages.error(request, self.error_message)
return super().get(request, *args, **kwargs)
+1 -1
View File
@@ -238,7 +238,7 @@ class Club(models.Model):
def can_be_edited_by(self, user: User) -> bool:
"""Method to see if that object can be edited by the given user."""
return self.has_rights_in_club(user)
return user.has_perm("club.change_club") or self.has_rights_in_club(user)
def can_roles_be_edited_by(self, user: User) -> bool:
"""Return True if the given user can edit the roles of this club"""
+9
View File
@@ -26,6 +26,15 @@
{% endblock %}
{% block content %}
{% if user.is_authenticated and user.can_edit(club) %}
<a
href="{{ url("core:page_edit", page_name=club.page.get_full_name()) }}"
class="btn btn-blue margin-bottom"
>
<i class="fa fa-pen-to-square"></i> {% trans %}Edit{% endtrans %}
</a>
{% endif %}
<h3>{{ club.name }}</h3>
<div id="club-detail" {% if links %}class="has-links"{% endif %}>
<div id="club-attributes">
+79
View File
@@ -0,0 +1,79 @@
{% extends "core/base.jinja" %}
{% block content %}
{% if club.has_rights_in_club(user) %}
<a class="btn btn-blue" href="{{ url("com:news_new") }}">
<i class="fa fa-plus"></i> {% trans %}Create news{% endtrans %}
</a>
{% endif %}
{% for semester_code, semester_events in events %}
<h3>{{ semester_code }}</h3>
{% for event in semester_events %}
<details class="accordion">
<summary>{{ event.title }}</summary>
<div class="accordion-content">
{# Events that occur weekly from the start to the end of the semester
would take a lot of space if shown by default.
Thus, if the event has more than one date, those are
hidden by a details element.
If there is only one date, it is directly displayed. #}
{% set dates = event.dates.all()|list %}
{% if dates|length == 1 %}
<em>
<time datetime="{{ dates[0].start_date.isoformat(timespec="seconds") }}">
{{ dates[0].start_date|localtime|date(DATETIME_FORMAT) }},
{{ dates[0].start_date|localtime|time(DATETIME_FORMAT) }}
</time> -
<time datetime="{{ dates[0].end_date.isoformat(timespec="seconds") }}">
{{ dates[0].end_date|localtime|date(DATETIME_FORMAT) }},
{{ dates[0].end_date|localtime|time(DATETIME_FORMAT) }}
</time>
</em>
{% else %}
<details>
<summary>
{% trans trimmed nb_occurrences=dates|length %}
Dates ({{ nb_occurrences }} occurrences)
{% endtrans %}
</summary>
<ul>
{% for d in dates %}
<li>
<time datetime="{{ d.start_date.isoformat(timespec="seconds") }}">
{{ d.start_date|localtime|date(DATETIME_FORMAT) }},
{{ d.start_date|localtime|time(DATETIME_FORMAT) }}
</time> -
<time datetime="{{ d.end_date.isoformat(timespec="seconds") }}">
{{ d.end_date|localtime|date(DATETIME_FORMAT) }},
{{ d.end_date|localtime|time(DATETIME_FORMAT) }}
</time>
</li>
{% endfor %}
</ul>
</details>
{% endif %}
<h4>{% trans %}Permalink{% endtrans %}</h4>
<p>{{ request.build_absolute_uri(event.get_absolute_url())|urlize }}</p>
<h4>{% trans %}Summary{% endtrans %}</h4>
{% if event.summary %}
{{ event.summary|markdown }}
{% else %}
<p><em>{% trans %}No summary{% endtrans %}</em></p>
{% endif %}
<h4>{% trans %}Description{% endtrans %}</h4>
{% if event.content %}
{{ event.content|markdown }}
{% else %}
<p><em>{% trans %}No detailed description{% endtrans %}</em></p>
{% endif %}
</div>
</details>
{% endfor %}
<br />
{% endfor %}
{% endblock %}
+60
View File
@@ -0,0 +1,60 @@
from datetime import datetime
from django.test import RequestFactory, TestCase
from django.urls import reverse
from django.utils.timezone import get_current_timezone
from model_bakery import baker
from club.models import Club
from club.views import ClubNewsView
from com.models import News, NewsDate
from core.baker_recipes import subscriber_user
from core.models import User
class TestClubNews(TestCase):
@classmethod
def setUpTestData(cls):
cls.club = baker.make(Club)
cls.news = baker.make(
News, club=cls.club, is_published=True, author=baker.make(User), _quantity=5
)
d = datetime(year=2025, month=10, day=1, tzinfo=get_current_timezone())
dates = [
baker.prepare(NewsDate, news=cls.news[0], start_date=d),
baker.prepare(NewsDate, news=cls.news[0], start_date=d.replace(day=8)),
baker.prepare(NewsDate, news=cls.news[0], start_date=d.replace(day=15)),
baker.prepare(NewsDate, news=cls.news[1], start_date=d.replace(month=5)),
baker.prepare(NewsDate, news=cls.news[2], start_date=d.replace(month=4)),
baker.prepare(NewsDate, news=cls.news[3], start_date=d.replace(year=2024)),
baker.prepare(NewsDate, news=cls.news[4], start_date=d.replace(year=2020)),
]
NewsDate.objects.bulk_create(dates)
cls.url = reverse("club:news_list", kwargs={"club_id": cls.club.id})
def test_load_page(self):
"""Just test that the page loads."""
self.client.force_login(subscriber_user.make())
res = self.client.get(self.url)
assert res.status_code == 200
def test_page_data(self):
"""Test that we display the good events."""
# For this test, the object we want to test
# is built with `itertools.groupby`.
# However, it is consumed when rendering the template,
# making it unusable for later testing purposes,
# so we must use lower level django APIs in this test.
request = RequestFactory().get(self.url)
request.user = subscriber_user.make()
response = ClubNewsView.as_view()(request, club_id=self.club.id)
events = [
(semester_code, list(dates))
for semester_code, dates in response.context_data["events"]
]
assert events == [
("A25", [self.news[0]]),
("P25", [self.news[1], self.news[2]]),
("A24", [self.news[3]]),
("A20", [self.news[4]]),
]
+57 -9
View File
@@ -1,8 +1,9 @@
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Callable
import pytest
from aemark import markdown
from bs4 import BeautifulSoup
from django.contrib.auth.models import Permission
from django.urls import reverse
from model_bakery import baker
from pytest_django.asserts import assertHTMLEqual, assertRedirects
@@ -16,13 +17,20 @@ if TYPE_CHECKING:
@pytest.mark.django_db
def test_page_display_on_club_main_page(client: Client):
@pytest.mark.parametrize("user_factory", [lambda: None, subscriber_user.make])
def test_page_display_on_club_main_page(
client: Client, user_factory: Callable[[], User | None]
):
"""Test the club Page is properly displayed on the club main view"""
club = baker.make(Club)
# create another previous revision, to test that we display the most recent one
baker.make(PageRev, page=club.page, revision=1)
content = "# foo\nLorem ipsum dolor sit amet"
baker.make(PageRev, page=club.page, revision=1, content=content)
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
baker.make(PageRev, page=club.page, revision=2, content=content)
if user := user_factory():
client.force_login(user)
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
assert res.status_code == 200
soup = BeautifulSoup(res.text, "lxml")
detail_html = soup.find(id="club-page").find(class_="markdown")
@@ -30,20 +38,60 @@ def test_page_display_on_club_main_page(client: Client):
@pytest.mark.django_db
def test_club_main_page_without_content(client: Client):
"""Test the club view works, even if the club page is empty"""
@pytest.mark.parametrize(
("user_factory", "can_view_tabs", "can_view_edit_button"),
[
(lambda _: None, False, False),
(lambda _: baker.make(User), False, False),
(lambda _: subscriber_user.make(), True, False),
(
# admin user
lambda _: subscriber_user.make(
user_permissions=[Permission.objects.get(codename="change_club")]
),
True,
True,
),
(
# club board member
lambda club: (
baker.make(
Membership,
club=club,
role=baker.make(ClubRole, is_board=True),
user=subscriber_user.make(),
).user
),
True,
True,
),
],
ids=["anonymous", "public", "subscriber", "admin", "club board"],
)
@pytest.mark.django_db
def test_club_main_page_displayed_elements(
client: Client, user_factory, can_view_tabs, can_view_edit_button
):
"""Test that the appropriate elements are displayed depending on user status."""
club = baker.make(Club)
club.page.revisions.all().delete()
if user := user_factory(club):
client.force_login(user)
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
assert res.status_code == 200
soup = BeautifulSoup(res.text, "lxml")
detail_html = soup.find(id="club-page")
assert detail_html.find_all("markdown") == []
tabs = soup.find(class_="tool_bar")
assert tabs is not None if can_view_tabs else tabs is None
edit_btn = soup.find(
"a",
href=reverse("core:page_edit", kwargs={"page_name": club.page.get_full_name()}),
)
assert edit_btn is not None if can_view_edit_button else edit_btn is None
@pytest.mark.django_db
def test_page_revision(client: Client):
"""Test that accessing a previous revision of the club page works."""
club = baker.make(Club)
revisions = baker.make(
PageRev, page=club.page, _quantity=3, content=iter(["foo", "bar", "baz"])
+2
View File
@@ -31,6 +31,7 @@ from club.views import (
ClubListView,
ClubMailingView,
ClubMembersView,
ClubNewsView,
ClubOldMembersView,
ClubPageEditView,
ClubPageHistView,
@@ -136,4 +137,5 @@ urlpatterns = [
PosterDeleteView.as_view(),
name="poster_delete",
),
path("<int:club_id>/news/", ClubNewsView.as_view(), name="news_list"),
]
+45 -33
View File
@@ -37,6 +37,7 @@ from django.contrib.messages.views import SuccessMessageMixin
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
from django.core.paginator import InvalidPage, Paginator
from django.db.models import F, Prefetch, Q, Sum
from django.db.models.expressions import OuterRef, Subquery
from django.db.models.functions import Length
from django.http import Http404, StreamingHttpResponse
from django.shortcuts import get_object_or_404, redirect
@@ -71,7 +72,7 @@ from club.models import (
MailingSubscription,
Membership,
)
from com.models import Poster
from com.models import NewsDate, Poster
from com.views import (
PosterCreateBaseView,
PosterDeleteBaseView,
@@ -80,6 +81,7 @@ from com.views import (
)
from core.auth.mixins import CanEditMixin, PermissionOrClubBoardRequiredMixin
from core.models import Page, PageRev
from core.utils import get_semester_code
from core.views import BasePageEditView, DetailFormView, UseFragmentsMixin
from core.views.mixins import (
AllowFragment,
@@ -106,20 +108,19 @@ class ClubTabsMixin(TabedViewMixin):
return self.object.get_display_name()
def get_list_of_tabs(self):
if not self.request.user.has_perm("club.view_club"):
# The user will still be able to see the club main page,
# but nothing else.
# It's useless to display a tab with only one item, so return nothing.
return []
tab_list = [
{
"url": reverse("club:club_view", kwargs={"club_id": self.object.id}),
"slug": "infos",
"name": _("Infos"),
}
]
if self.request.user.has_perm("club.view_club"):
tab_list.extend(
[
},
{
"url": reverse(
"club:club_members", kwargs={"club_id": self.object.id}
),
"url": reverse("club:club_members", kwargs={"club_id": self.object.id}),
"slug": "members",
"name": _("Members"),
},
@@ -130,18 +131,17 @@ class ClubTabsMixin(TabedViewMixin):
"slug": "elderlies",
"name": _("Old members"),
},
]
)
if self.object.page:
tab_list.append(
{
"url": reverse(
"club:club_hist", kwargs={"club_id": self.object.id}
),
"url": reverse("club:club_hist", kwargs={"club_id": self.object.id}),
"slug": "history",
"name": _("History"),
}
)
},
{
"url": reverse("club:news_list", kwargs={"club_id": self.object.id}),
"slug": "events",
"name": _("Events"),
},
]
if self.request.user.can_edit(self.object):
tab_list.extend(
[
@@ -159,21 +159,6 @@ class ClubTabsMixin(TabedViewMixin):
"slug": "edit",
"name": _("Edit"),
},
]
)
if self.object.page and self.request.user.can_edit(self.object.page):
tab_list.append(
{
"url": reverse(
"core:page_edit",
kwargs={"page_name": self.object.page.get_full_name()},
),
"slug": "page_edit",
"name": _("Edit club page"),
}
)
tab_list.extend(
[
{
"url": reverse(
"club:club_sellings", kwargs={"club_id": self.object.id}
@@ -957,3 +942,30 @@ class PosterDeleteView(ClubTabsMixin, PosterDeleteBaseView):
def get_success_url(self):
return reverse_lazy("club:poster_list", kwargs={"club_id": self.club.id})
class ClubNewsView(PermissionRequiredMixin, ClubTabsMixin, DetailView):
pk_url_kwarg = "club_id"
model = Club
permission_required = "club.view_club"
template_name = "club/club_news_list.jinja"
current_tab = "events"
def get_context_data(self, **kwargs: Any):
events = list(
self.object.news.viewable_by(self.request.user)
.annotate(
first_date=Subquery(
NewsDate.objects.filter(news_id=OuterRef("pk"))
.order_by("start_date")
.values("start_date")[:1]
),
)
.prefetch_related("dates")
.order_by("-first_date")
)
return super().get_context_data(**kwargs) | {
"events": itertools.groupby(
events, key=lambda event: get_semester_code(event.first_date.date())
),
}
+10 -4
View File
@@ -39,12 +39,18 @@
<a href="{{ news.club.get_absolute_url() }}">{{ news.club }}</a>
</div>
<h4>{{ news.title }}</h4>
{% if date %}
<p class="date">
<time datetime="{{ date.start_date.isoformat(timespec="seconds") }}">{{ date.start_date|localtime|date(DATETIME_FORMAT) }}
{{ date.start_date|localtime|time(DATETIME_FORMAT) }}</time> -
<time datetime="{{ date.end_date.isoformat(timespec="seconds") }}">{{ date.end_date|localtime|date(DATETIME_FORMAT) }}
{{ date.end_date|localtime|time(DATETIME_FORMAT) }}</time>
<time datetime="{{ date.start_date.isoformat(timespec="seconds") }}">
{{ date.start_date|localtime|date(DATETIME_FORMAT) }}
{{ date.start_date|localtime|time(DATETIME_FORMAT) }}
</time> -
<time datetime="{{ date.end_date.isoformat(timespec="seconds") }}">
{{ date.end_date|localtime|date(DATETIME_FORMAT) }}
{{ date.end_date|localtime|time(DATETIME_FORMAT) }}
</time>
</p>
{% endif %}
<div class="news_content">
<div><em>{{ news.summary|markdown }}</em></div>
<br/>
+35
View File
@@ -26,6 +26,7 @@ from django.utils import html
from django.utils.timezone import now
from django.utils.translation import gettext as _
from model_bakery import baker
from model_bakery.recipe import Recipe
from pytest_django.asserts import assertNumQueries, assertRedirects
from club.models import Club, ClubRole, Membership
@@ -362,3 +363,37 @@ def test_moderate_poster(client: Client, referer: str | None):
poster.refresh_from_db()
assert poster.is_moderated
assert poster.moderator == user
class TestNewsDetail(TestCase):
@classmethod
def setUpTestData(cls) -> None:
cls.news = baker.make(News, is_published=True)
cls.user = subscriber_user.make()
cls.url = reverse("com:news_detail", kwargs={"news_id": cls.news.id})
def test_page_ok(self):
self.client.force_login(self.user)
res = self.client.get(self.url)
assert res.status_code == 200
def test_displayed_date(self):
self.client.force_login(self.user)
n = now()
date_recipe = Recipe(NewsDate, news=self.news)
date_recipe.make(
start_date=n - timedelta(days=1, hours=6), end_date=n - timedelta(days=1)
)
date_recipe.make(
start_date=n - timedelta(hours=6), end_date=n + timedelta(hours=1)
)
expected = date_recipe.make( # we expect the next happening date.
start_date=n + timedelta(days=1), end_date=n + timedelta(days=1, hours=1)
)
date_recipe.make(
start_date=n + timedelta(days=2), end_date=n + timedelta(days=2, hours=1)
)
self.client.force_login(self.user)
res = self.client.get(self.url)
assert res.status_code == 200
assert res.context_data["date"] == expected
+3 -1
View File
@@ -301,7 +301,9 @@ class NewsDetailView(CanViewMixin, DetailView):
queryset = News.objects.select_related("club", "author", "moderator")
def get_context_data(self, **kwargs):
return super().get_context_data(**kwargs) | {"date": self.object.dates.first()}
return super().get_context_data(**kwargs) | {
"date": self.object.dates.filter(start_date__gt=now()).first()
}
class NewsFeed(Feed):
+11 -8
View File
@@ -1,19 +1,16 @@
class FourDigitYearConverter:
regex = "[0-9]{4}"
from django.urls.converters import IntConverter, StringConverter
def to_python(self, value):
return int(value)
class FourDigitYearConverter(IntConverter):
regex = "[0-9]{4}"
def to_url(self, value):
return str(value).zfill(4)
class TwoDigitMonthConverter:
class TwoDigitMonthConverter(IntConverter):
regex = "[0-9]{2}"
def to_python(self, value):
return int(value)
def to_url(self, value):
return str(value).zfill(2)
@@ -28,3 +25,9 @@ class BooleanStringConverter:
def to_url(self, value):
return str(value)
class ResultConverter(StringConverter):
"""Converter whose regex match either "success" or "failure"."""
regex = "(success|failure)"
+49 -33
View File
@@ -20,6 +20,7 @@
# Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
import itertools
from datetime import date, datetime, timedelta
from io import StringIO
from pathlib import Path
@@ -120,11 +121,6 @@ class Command(BaseCommand):
)
self.profiles_root = SithFile.objects.create(name="profiles", owner=root)
home_root = SithFile.objects.create(name="users", owner=root)
# Page needed for club creation
p = Page(name=settings.SITH_CLUB_ROOT_PAGE)
p.save(force_lock=True)
club_root = SithFile.objects.create(name="clubs", owner=root)
sas = SithFile.objects.create(
name="SAS", owner=root, id=settings.SITH_SAS_ROOT_DIR_ID
@@ -256,6 +252,7 @@ class Command(BaseCommand):
date_of_birth="1942-06-12",
password="plop",
)
User.objects.all().update(cgu_approved_at=now())
User.groups.through.objects.bulk_create(
[
User.groups.through(group=groups.counter_admin, user=counter),
@@ -279,34 +276,7 @@ class Command(BaseCommand):
]
)
# Adding syntax help page
syntax_page = Page(name="Aide_sur_la_syntaxe")
syntax_page.save(force_lock=True)
PageRev.objects.create(
page=syntax_page,
title="Aide sur la syntaxe",
author=skia,
content=(self.ROOT_PATH / "core" / "fixtures" / "SYNTAX.md").read_text(),
)
services_page = Page(name="Services")
services_page.save(force_lock=True)
PageRev.objects.create(
page=services_page,
title="Services",
author=skia,
content="- [Eboutic](/eboutic)\n- Matmat\n- SAS\n- Weekmail\n- Forum",
)
index_page = Page(name="Index")
index_page.save(force_lock=True)
PageRev.objects.create(
page=index_page,
title="Wiki index",
author=root,
content="Welcome to the wiki page!",
)
groups.public.viewable_page.set([syntax_page, services_page, index_page])
self._create_pages(groups)
self._create_subscription(root)
self._create_subscription(skia)
@@ -577,6 +547,48 @@ class Command(BaseCommand):
]
)
def _create_pages(self, groups: PopulatedGroups):
pages = Page.objects.bulk_create(
[Page(name=s, _full_name=s) for s in settings.SITH_CGU_PAGE.split("/")]
)
for parent, son in itertools.pairwise(pages):
son.parent = parent
son.save(force_lock=True)
cgu_page = pages[-1]
syntax_page = Page(name="Aide_sur_la_syntaxe")
syntax_page.save(force_lock=True)
services_page = Page(name="Services")
services_page.save(force_lock=True)
index_page = Page(name="Index")
index_page.save(force_lock=True)
page_revs = [
PageRev(page=cgu_page, title="Règlement informatique", content=""),
PageRev(
page=syntax_page,
title="Aide sur la syntaxe",
content=(
self.ROOT_PATH / "core" / "fixtures" / "SYNTAX.md"
).read_text(),
),
PageRev(
page=services_page,
title="Services",
content="- [Eboutic](/eboutic)\n- Matmat\n- SAS\n- Weekmail\n- Forum",
),
PageRev(
page=index_page, title="Wiki index", content="Welcome to the wiki page!"
),
]
for rev in page_revs:
rev.author_id = settings.SITH_ROOT_USER_ID
rev.revision = 1
PageRev.objects.bulk_create(page_revs)
groups.public.viewable_page.set(
[syntax_page, services_page, index_page, cgu_page]
)
def _create_products(self, groups: PopulatedGroups, clubs: PopulatedClubs):
beers_type, cotis_type, refill_type, verre_type = (
ProductType.objects.bulk_create(
@@ -737,6 +749,10 @@ class Command(BaseCommand):
s.save()
def _create_clubs(self) -> PopulatedClubs:
# Page needed for club creation
p = Page(name=settings.SITH_CLUB_ROOT_PAGE)
p.save(force_lock=True)
ae = Club.objects.create(
id=1, name="AE", address="6 Boulevard Anatole France, 90000 Belfort"
)
+27 -8
View File
@@ -1,3 +1,4 @@
import math
import random
from datetime import date, timedelta
from datetime import timezone as tz
@@ -35,12 +36,17 @@ class Command(BaseCommand):
super().__init__(*args, **kwargs)
self.faker = Faker("fr_FR")
def add_arguments(self, parser):
parser.add_argument(
"-n", "--nb-users", help="Number of users to create", type=int, default=600
)
def handle(self, *args, **options):
if not settings.DEBUG:
raise Exception("Never call this command in prod. Never.")
self.stdout.write("Creating users...")
users = self.create_users()
users = self.create_users(options["nb_users"])
self.create_bans(random.sample(users, k=len(users) // 200)) # 0.5% of users
subscribers = random.sample(users, k=int(0.8 * len(users)))
self.stdout.write("Creating subscriptions...")
@@ -80,7 +86,7 @@ class Command(BaseCommand):
self.stdout.write("Creating products...")
self.create_products()
self.stdout.write("Creating sales and refills...")
sellers = random.sample(list(User.objects.all()), 100)
sellers = random.sample(users, len(users) // 10)
self.create_sales(sellers)
self.stdout.write("Creating permanences...")
self.create_permanences(sellers)
@@ -89,7 +95,7 @@ class Command(BaseCommand):
self.stdout.write("Done")
def create_users(self) -> list[User]:
def create_users(self, nb_users: int = 600) -> list[User]:
# Create a single password hash for all users to make it faster.
# It's insecure as hell, but it's ok since it's only for dev purposes.
password = make_password("plop")
@@ -108,7 +114,7 @@ class Command(BaseCommand):
address=self.faker.address(),
password=password,
)
for _ in range(600)
for _ in range(nb_users)
]
# there may a duplicate or two
# Not a problem, we will just have 599 users instead of 600
@@ -138,10 +144,22 @@ class Command(BaseCommand):
)
def create_subscriptions(self, users: list[User]):
subscription_types = [
"un-semestre",
"deux-semestres",
"cursus-tronc-commun",
"cursus-branche",
]
def prepare_subscription(_user: User, start_date: date) -> Subscription:
payment_method = random.choice(settings.SITH_SUBSCRIPTION_PAYMENT_METHOD)[0]
duration = random.randint(1, 4)
s = Subscription(member=_user, payment_method=payment_method)
subscription_type = random.choice(subscription_types)
s = Subscription(
member=_user,
payment_method=payment_method,
subscription_type=subscription_type,
)
duration = settings.SITH_SUBSCRIPTIONS[subscription_type]["duration"]
s.subscription_start = s.compute_start(d=start_date, duration=duration)
s.subscription_end = s.compute_end(duration)
return s
@@ -415,8 +433,9 @@ class Command(BaseCommand):
Permanency.objects.bulk_create(perms)
def create_forums(self):
forumers = random.sample(list(User.objects.all()), 100)
most_actives = random.sample(forumers, 10)
users = list(User.objects.all())
forumers = random.sample(users, math.ceil(len(users) / 10))
most_actives = random.sample(forumers, math.ceil(len(forumers) / 6))
categories = list(Forum.objects.filter(is_category=True))
new_forums = [
Forum(name=self.faker.text(20), parent=random.choice(categories))
@@ -0,0 +1,15 @@
# Generated by Django 5.2.17 on 2026-09-25 12:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("core", "0050_alter_sithfile_moderator")]
operations = [
migrations.AddField(
model_name="user",
name="cgu_approved_at",
field=models.DateTimeField(null=True, verbose_name="ToS approved at"),
),
]
@@ -0,0 +1,22 @@
# Generated by Django 5.2.17 on 2026-09-24 14:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("core", "0051_user_cgu_approved_at")]
operations = [
migrations.AddField(
model_name="preferences",
name="show_my_timetable",
field=models.BooleanField(
default=True,
help_text=(
"Allow subscribers to see your timetable and "
"to compare it to theirs (if you have filled it)"
),
verbose_name="show your timetable to others",
),
),
]
+20 -4
View File
@@ -44,6 +44,7 @@ from django.core.files.base import ContentFile
from django.core.mail import send_mail
from django.db import models, transaction
from django.db.models import Exists, F, OuterRef, Q
from django.db.models.aggregates import Max
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
@@ -291,6 +292,7 @@ class User(AbstractUser):
),
blank=True,
)
cgu_approved_at = models.DateTimeField(_("ToS approved at"), null=True, blank=False)
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
objects = CustomUserManager()
@@ -418,6 +420,14 @@ class User(AbstractUser):
)
return age
@cached_property
def approved_current_cgu(self) -> bool:
qs = PageRev.objects.filter(page___full_name=settings.SITH_CGU_PAGE)
return (
self.cgu_approved_at is not None
and self.cgu_approved_at > qs.aggregate(date=Max("date"))["date"]
)
def make_home(self):
if self.home is None:
home_root = SithFile.objects.filter(parent=None, name="users").first()
@@ -789,6 +799,14 @@ class Preferences(models.Model):
),
default=False,
)
show_my_timetable = models.BooleanField(
_("show your timetable to others"),
help_text=_(
"Allow subscribers to see your timetable and "
"to compare it to theirs (if you have filled it)"
),
default=True,
)
notify_on_click = models.BooleanField(
_("get a notification for every click"), default=False
)
@@ -1233,9 +1251,8 @@ class Page(models.Model):
raise NotLocked("The page is not locked and thus can not be saved")
self.full_clean()
if not self.id:
super().save(
*args, **kwargs
) # Save a first time to correctly set _full_name
# Save a first time to correctly set _full_name
super().save(*args, **kwargs)
# This reset the _full_name just before saving to maintain a coherent field quicker for queries than the
# recursive method
# It also update all the children to maintain correct names
@@ -1254,7 +1271,6 @@ class Page(models.Model):
return Page.objects.filter(_full_name=name).first()
def clean(self):
"""Cleans up only the name for the moment, but this can be used to make any treatment before saving the object."""
if "/" in self.name:
self.name = self.name.split("/")[-1]
if (
@@ -60,6 +60,7 @@ const loadEasyMde = (textarea: HTMLTextAreaElement) => {
});
easymde.codemirror.replaceSelection("\n");
},
previewClass: ["editor-preview", "markdown"], // default class + our own markdown class
previewRender: (plainText) => markdown(plainText),
forceSync: true, // Avoid validation error on generic create view
imageTexts: {
+1
View File
@@ -42,6 +42,7 @@ details.accordion>.accordion-content {
background: #ffffff;
color: #333333;
padding: 1em 2.2em;
margin-top: 0;
border: 1px solid #dddddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
+9
View File
@@ -33,6 +33,15 @@
padding: 1px 2px;
}
/**
* Some restyling rules for the cases where our own md css
* conflicts with the easymde editor preview css
*/
&.editor-preview {
pre {
background: unset;
}
}
pre code {
// code that is not inlined
margin: 15px;
+10 -45
View File
@@ -37,8 +37,7 @@ body {
margin: 0;
}
>div,
>form {
form {
box-sizing: border-box;
display: flex;
flex-direction: column;
@@ -49,67 +48,33 @@ body {
max-width: 500px;
margin-top: 20px;
>p,
>div {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
input[type="submit"] {
width: 100%;
margin: 0;
>label {
width: 100%;
@media (min-width: 500px) {
width: 300px;
}
}
}
>input,
>p>input,
>div>input {
box-sizing: border-box;
width: 100%;
max-width: 500px;
@media (min-width: 500px) {
max-width: 300px;
}
margin-top: 1em;
}
>.errorlist {
.errorlist {
color: red;
text-align: center;
margin: 10px 0 0 0;
list-style-type: none;
}
>.required>.helptext {
text-align: center;
font-style: italic;
}
>.required:last-of-type {
box-sizing: border-box;
div, fieldset {
max-width: 300px;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
}
.captcha {
box-sizing: border-box;
>label {
width: 100%;
fieldset {
margin-bottom: unset
}
>img {
width: 70px;
object-fit: contain;
}
>input {
width: 200px;
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
{% extends "core/base.jinja" %}
{%- block additional_css -%}
<link rel="stylesheet" href="{{ static('user/login.scss') }}">
{%- endblock -%}
{% block title %}
{% trans %}Login{% endtrans %}
{% endblock %}
{% block info_boxes %}
{% endblock %}
{% block nav %}
{% endblock %}
{% block content %}
<h1 class="title">{% trans %}Terms of Service{% endtrans %}</h1>
<form method="post" id="login-form">
{% csrf_token %}
<div class="alert alert-yellow">
{% trans trimmed %}
To continue using our services,
please read and approve the AE website's terms of service
{% endtrans %}
</div>
<div class="form-group">
{{ form.cgu_approved_at.errors }}
{{ form.cgu_approved_at }}
{{ form.cgu_approved_at.label_tag() }}
</div>
<input type="hidden" name="next" value="{{ next }}">
<input type="submit" class="btn btn-blue">
</form>
{% endblock %}
@@ -29,5 +29,13 @@
</span>
{{ form.show_my_stats.errors }}
</fieldset>
<fieldset class="form-group">
{{ form.show_my_timetable }}
{{ form.show_my_timetable.label_tag() }}
<span class="helptext">
{{ form.show_my_timetable.help_text }}
</span>
{{ form.show_my_timetable.errors }}
</fieldset>
<input type="submit" class="btn btn-blue" value="{% trans %}Save{% endtrans %}">
</form>
+8 -19
View File
@@ -35,28 +35,17 @@
{% csrf_token %}
<div>
<label for="{{ form.username.name }}">{{ form.username.label }}</label>
{{ form.username }}
{{ form.username.errors }}
</div>
<div>
<label for="{{ form.password.name }}">{{ form.password.label }}</label>
{{ form.password }}
{{ form.password.errors }}
</div>
{{ form }}
<input type="hidden" name="next" value="{{ next }}">
<input type="submit" value="{% trans %}Login{% endtrans %}">
<input type="submit" class="btn btn-blue" value="{% trans %}Login{% endtrans %}">
{# Assumes you setup the password_reset view in your URLconf #}
<p>
<a href="{{ url('core:password_reset') }}">{% trans %}Lost password?{% endtrans %}</a>
&nbsp;&nbsp;
<a href="{{ url('core:register') }}">{% trans %}Create account{% endtrans %}</a>
</p>
<div>
<a href="{{ url("core:password_reset") }}">{% trans %}Lost password?{% endtrans %}</a>
</div>
<div>
<a href="{{ url("core:register") }}">{% trans %}Create account{% endtrans %}</a>
</div>
</form>
{% endblock %}
+12 -2
View File
@@ -18,7 +18,17 @@
<form action="{{ url('core:register') }}" method="post">
{% csrf_token %}
{% render_honeypot_field %}
{{ form.as_p() }}
<input type="submit" value="{% trans %}Register{% endtrans %}" />
{% for field in form %}
{% if field.name not in ["cgu_approved_at", "captcha"] %}
<div>{{ field.as_field_group() }}</div>
{% endif %}
{% endfor %}
<div class="captcha">{{ form.captcha.as_field_group() }}</div>
<div class="form-group">
{{ form.cgu_approved_at.errors }}
{{ form.cgu_approved_at }}
{{ form.cgu_approved_at.label_tag() }}
</div>
<input type="submit" class="btn btn-blue" value="{% trans %}Register{% endtrans %}" />
</form>
{% endblock %}
+2 -2
View File
@@ -31,10 +31,10 @@
{% for sum in purchase_sums %}
<div>
<span>{{ sum["counter__name"] }}</span>
<span>{{ sum["total"] }} €</span>
<span>{{ "%.2f"|format(sum["total"]) }} €</span>
</div>
{% endfor %}
<div><b>Total : </b><b>{{ total_purchases }} €</b></div>
<div><b>Total : </b><b>{{ "%.2f"|format(total_purchases) }} €</b></div>
</div>
</div>
</div>
+13
View File
@@ -0,0 +1,13 @@
import contextlib
import os
import pytest
from django.core.management import call_command
@pytest.mark.django_db
def test_populate_more(settings):
"""Just check that populate more doesn't crash"""
settings.DEBUG = True
with open(os.devnull, "w") as devnull, contextlib.redirect_stdout(devnull):
call_command("populate_more", "--nb-users", "50")
+38 -2
View File
@@ -27,6 +27,7 @@ from django.core.exceptions import ValidationError
from django.core.mail import EmailMessage
from django.test import Client, RequestFactory, TestCase
from django.urls import reverse
from django.utils.timezone import now
from django.views.generic import View
from django.views.generic.base import ContextMixin
from model_bakery import baker
@@ -55,6 +56,7 @@ class TestUserRegistration:
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
"cgu_approved_at": now(),
}
@pytest.fixture()
@@ -92,6 +94,10 @@ class TestUserRegistration:
({"first_name": ""}, "Ce champ est obligatoire."),
({"last_name": ""}, "Ce champ est obligatoire."),
({"captcha_1": "WRONG_CAPTCHA"}, "CAPTCHA invalide"),
(
{"cgu_approved_at": False},
"Vous devez approuver les conditions générales d'utilisation",
),
],
)
def test_register_user_form_fail(
@@ -150,7 +156,7 @@ class TestUserRegistration:
class TestUserLogin:
@pytest.fixture()
def user(self) -> User:
return baker.make(User, password=make_password("plop"))
return baker.make(User, password=make_password("plop"), cgu_approved_at=now())
@pytest.mark.parametrize(
"identifier_getter",
@@ -191,10 +197,40 @@ class TestUserLogin:
reverse("core:login"),
{"username": identifier_getter(user), "password": "plop"},
)
assertRedirects(response, reverse("core:index"))
assertRedirects(response, settings.LOGIN_REDIRECT_URL)
assert response.wsgi_request.user == user
@pytest.mark.django_db
class TestCGU:
def test_cgu_approval(self, client: Client):
user = baker.make(User, password=make_password("plop"), cgu_approved_at=None)
user_url = user.get_absolute_url()
res = client.post(
reverse("core:login"),
{"username": user.username, "password": "plop", "next": user_url},
)
assertRedirects(res, reverse("core:approve_cgu", query={"next": user_url}))
res = client.post(
reverse("core:approve_cgu"), {"cgu_approved_at": now(), "next": user_url}
)
assertRedirects(res, user_url)
user.refresh_from_db()
assert user.cgu_approved_at is not None
def test_access_cgu_when_already_approved(self, client: Client):
url = reverse("core:approve_cgu")
res = client.get(url)
assertRedirects(res, reverse("core:login"))
client.force_login(baker.make(User, cgu_approved_at=now()))
res = client.get(url)
assertRedirects(res, settings.LOGIN_REDIRECT_URL)
res = client.post(url, {"cgu_approved_at": now()})
assertRedirects(res, settings.LOGIN_REDIRECT_URL)
@pytest.mark.parametrize(
("md", "html"),
[
+8
View File
@@ -31,6 +31,7 @@ from core.converters import (
TwoDigitMonthConverter,
)
from core.views import (
CGUApprovalView,
FileDeleteView,
FileEditPropView,
FileEditView,
@@ -83,6 +84,7 @@ from core.views import (
notification,
send_file,
)
from timetable.views import UserTimetableView
register_converter(FourDigitYearConverter, "yyyy")
register_converter(TwoDigitMonthConverter, "mm")
@@ -125,6 +127,7 @@ urlpatterns = [
name="password_reset_complete",
),
path("register/", UserCreationView.as_view(), name="register"),
path("cgu/", CGUApprovalView.as_view(), name="approve_cgu"),
# Group handling
path("group/", GroupListView.as_view(), name="group_list"),
path("group/new/", GroupCreateView.as_view(), name="group_new"),
@@ -182,6 +185,11 @@ urlpatterns = [
name="user_account_detail",
),
path("user/<int:user_id>/stats/", UserStatsView.as_view(), name="user_stats"),
path(
"user/<int:user_id>/edt/",
UserTimetableView.as_view(),
name="user_timetable",
),
path(
"user/<int:user_id>/gift/create/",
GiftCreateView.as_view(),
+39
View File
@@ -12,12 +12,15 @@
# OR WITHIN THE LOCAL FILE "LICENSE"
#
#
from __future__ import annotations
import hmac
from datetime import date, timedelta
# Image utils
from io import BytesIO
from typing import TYPE_CHECKING, Final
from urllib.parse import urlencode
import PIL
from django.conf import settings
@@ -25,6 +28,15 @@ from django.core.files.base import ContentFile
from django.utils.timezone import localdate
from PIL.Image import Image, Resampling
if TYPE_CHECKING:
from _hashlib import HASH
from collections.abc import Buffer, Mapping, Sequence
from typing import Any, Callable, Final
from django.core.files.uploadedfile import UploadedFile
from django.http import HttpRequest
if TYPE_CHECKING:
from django.core.files.uploadedfile import UploadedFile
from django.http import HttpRequest
@@ -190,3 +202,30 @@ def get_client_ip(request: HttpRequest) -> str | None:
return ip
return None
def hmac_hexdigest(
key: str | bytes,
data: Mapping[str, Any] | Sequence[tuple[str, Any]],
digest: str | Callable[[Buffer], HASH] = "sha512",
) -> str:
"""Return the hexdigest of the signature of the given data.
Args:
key: the HMAC key used for the signature
data: the data to sign
digest: a PEP247 hashing algorithm (by default, sha512)
Examples:
```python
data = {
"foo": 5,
"bar": "somevalue",
}
hmac_key = secrets.token_hex(64)
signature = hmac_hexdigest(hmac_key, data, "sha256")
```
"""
if isinstance(key, str):
key = key.encode()
return hmac.digest(key, urlencode(data).encode(), digest).hex()
+73 -7
View File
@@ -30,9 +30,7 @@ from django import forms
from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import Permission
from django.contrib.staticfiles.management.commands.collectstatic import (
staticfiles_storage,
)
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.exceptions import ValidationError
from django.db import transaction
from django.forms import (
@@ -42,6 +40,9 @@ from django.forms import (
TextInput,
Widget,
)
from django.urls import reverse
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from phonenumber_field.widgets import RegionalPhoneNumberWidget
@@ -108,6 +109,43 @@ class FutureDateTimeField(forms.DateTimeField):
return {"min": widget.format_value(now())}
class CGUApprovalField(forms.BooleanField):
"""Form field with a checkbox to approve the CGUs.
The checkbox must be checked to be valid.
If valid, then the value of the field is the current timestamp.
"""
default_error_messages = {"required": _("You must approve the terms of service.")}
__label = None
def __init__(self, *, label_suffix: str | None = "", **kwargs):
# Because the core app of the sith is so huge,
# and because we require a url from the latter,
# putting the reverse into the __init__ will result in it
# being evaluated at server startup time (even with reverse_lazy).
# This will result in a circular import.
# Thus, we must keep the label in its own property and force it to be lazy.
kwargs["label"] = lazy(self.get_label, str)
kwargs["required"] = True
super().__init__(label_suffix=label_suffix, **kwargs)
def to_python(self, value):
return now() if super().to_python(value) else None
def get_label(self):
if not self.__label:
url = reverse("core:page", kwargs={"page_name": settings.SITH_CGU_PAGE})
self.__label = mark_safe(
_(
"I have read and I approve the "
'<a href="%(url)s" target="_blank">Terms of Service</a>'
)
% {"url": url}
)
return self.__label
# Forms
@@ -146,8 +184,28 @@ class RegisteringForm(UserCreationForm):
class Meta:
model = User
fields = ("first_name", "last_name", "email")
field_classes = {"email": AntiSpamEmailField}
fields = ("first_name", "last_name", "email", "cgu_approved_at")
field_classes = {
"email": AntiSpamEmailField,
"cgu_approved_at": CGUApprovalField,
}
class CGUApprovalForm(forms.ModelForm):
class Meta:
model = User
fields = ["cgu_approved_at"]
field_classes = {"cgu_approved_at": CGUApprovalField}
def __init__(self, *args, instance: User | None = None, **kwargs):
if instance:
# If this form is displayed,
# then we want the user to explicitly check the button.
# So we pretend cgu were never approved (even if they were).
# If we didn't do that, the button would be initially checked,
# even if the approval was done before the last CGU version.
instance.cgu_approved_at = False
super().__init__(*args, instance=instance, **kwargs)
class UserProfileForm(forms.ModelForm):
@@ -278,10 +336,14 @@ class UserVisibilityForm(forms.ModelForm):
__preferences_fields = forms.fields_for_model(
Preferences,
["show_my_stats"],
widgets={"show_my_stats": forms.CheckboxInput(attrs={"class": "switch"})},
["show_my_stats", "show_my_timetable"],
widgets={
"show_my_stats": forms.CheckboxInput(attrs={"class": "switch"}),
"show_my_timetable": forms.CheckboxInput(attrs={"class": "switch"}),
},
)
show_my_stats = __preferences_fields["show_my_stats"]
show_my_timetable = __preferences_fields["show_my_timetable"]
def __init__(
self, *args, initial: dict | None = None, instance: User | None = None, **kwargs
@@ -289,12 +351,16 @@ class UserVisibilityForm(forms.ModelForm):
if instance:
initial = initial or {}
initial["show_my_stats"] = instance.preferences.show_my_stats
initial["show_my_timetable"] = instance.preferences.show_my_timetable
super().__init__(*args, initial=initial, instance=instance, **kwargs)
def save(self, commit=True) -> User: # noqa: FBT002
instance = super().save(commit=commit)
if commit:
instance.preferences.show_my_stats = self.cleaned_data["show_my_stats"]
instance.preferences.show_my_timetable = self.cleaned_data[
"show_my_timetable"
]
instance.preferences.save()
return instance
+16 -2
View File
@@ -1,6 +1,14 @@
import copy
import inspect
from typing import TYPE_CHECKING, Any, ClassVar, LiteralString, Protocol, Unpack
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
LiteralString,
Protocol,
TypedDict,
Unpack,
)
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
@@ -12,11 +20,17 @@ if TYPE_CHECKING:
from django.utils.safestring import SafeString
class TabItem(TypedDict):
url: str
slug: str
name: str
class TabedViewMixin(View):
"""Basic functions for displaying tabs in the template."""
current_tab: ClassVar[str | None] = None
list_of_tabs: ClassVar[list | None] = None
list_of_tabs: ClassVar[list[TabItem] | None] = None
tabs_title: ClassVar[str | None] = None
def get_tabs_title(self):
+35 -6
View File
@@ -27,12 +27,12 @@ from datetime import timedelta
# This file contains all the views that concern the user model
from operator import itemgetter
from smtplib import SMTPException
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from django.contrib import messages
from django.contrib.auth import login, views
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.core.exceptions import PermissionDenied
@@ -60,6 +60,7 @@ from honeypot.decorators import check_honeypot
from core.auth.mixins import CanEditMixin, CanEditPropMixin, CanViewMixin
from core.models import Gift, Preferences, User
from core.views.forms import (
CGUApprovalForm,
GiftForm,
LoginForm,
RegisteringForm,
@@ -71,6 +72,7 @@ from core.views.forms import (
from core.views.mixins import FragmentMixin, TabedViewMixin, UseFragmentsMixin
from counter.models import Refilling, Selling
from eboutic.models import Invoice
from sith import settings
from trombi.views import UserTrombiForm
if TYPE_CHECKING:
@@ -82,9 +84,16 @@ class SithLoginView(views.LoginView):
template_name = "core/login.jinja"
authentication_form = LoginForm
form_class = PasswordChangeForm
redirect_authenticated_user = True
def get_success_url(self) -> str:
redirect_to = self.get_redirect_url()
default_url = self.get_default_redirect_url()
if not self.request.user.approved_current_cgu:
query = {"next": redirect_to} if redirect_to else {}
return reverse("core:approve_cgu", query=query)
return redirect_to or default_url
class SithPasswordChangeView(views.PasswordChangeView):
"""Allows a user to change its password."""
@@ -188,6 +197,27 @@ class UserCreationView(FormView):
return super().form_valid(form)
class CGUApprovalView(views.RedirectURLMixin, UpdateView):
form_class = CGUApprovalForm
next_page = settings.LOGIN_REDIRECT_URL
template_name = "core/cgu_approve.jinja"
def dispatch(self, request, *args, **kwargs):
if self.request.user.is_anonymous:
return redirect("core:login")
if self.request.user.approved_current_cgu:
return redirect(self.get_success_url())
return super().dispatch(request, *args, **kwargs)
def get_object(self, *args, **kwargs):
return self.request.user
def get_context_data(self, **kwargs) -> dict[str, Any]:
return super().get_context_data(**kwargs) | {
self.redirect_field_name: self.get_redirect_url()
}
class UserMeRedirect(LoginRequiredMixin, RedirectView):
def get_redirect_url(self, *args, **kwargs):
if remaining := kwargs.get("remaining_path"):
@@ -383,7 +413,7 @@ class UserStatsView(UserTabsMixin, UserPassesTestMixin, DetailView):
kwargs = super().get_context_data(**kwargs)
kwargs["perm_time"] = list(
self.object.permanencies.filter(end__isnull=False, counter__type="BAR")
self.object.permanencies.filter(end__isnull=False)
.values("counter", "counter__name")
.annotate(total=Sum(F("end") - F("start"), default=timedelta(seconds=0)))
.order_by("-total")
@@ -392,8 +422,7 @@ class UserStatsView(UserTabsMixin, UserPassesTestMixin, DetailView):
[perm["total"] for perm in kwargs["perm_time"]], start=timedelta(seconds=0)
)
kwargs["purchase_sums"] = list(
self.object.customer.buyings.filter(counter__type="BAR")
.values("counter", "counter__name")
self.object.customer.buyings.values("counter", "counter__name")
.annotate(total=Sum(F("unit_price") * F("quantity")))
.order_by("-total")
)
-11
View File
@@ -647,13 +647,6 @@ class Counter(models.Model):
or user in self.sellers.all()
)
def gen_token(self) -> None:
"""Generate a new token for this counter."""
self.token = "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(30)
)
self.save()
@cached_property
def barmen_list(self) -> list[User]:
"""Returns the barman list as list of User."""
@@ -661,10 +654,6 @@ class Counter(models.Model):
p.user for p in self.permanencies.filter(end=None).select_related("user")
]
def get_random_barman(self) -> User:
"""Return a random user being currently a barman."""
return random.choice(self.barmen_list)
def update_activity(self) -> None:
"""Update the barman activity to prevent timeout."""
self.permanencies.filter(end=None).update(activity=timezone.now())
+19 -7
View File
@@ -83,8 +83,17 @@
{% endmacro %}
{% block content %}
<div class="alert alert-yellow">
<div class="alert-main">
{%- trans trimmed -%}
You can see product details.
However, you cannot edit it, thus you won't be able
to submit this form.
{%- endtrans -%}
</div>
</div>
{% if object %}
<h2>{% trans name=object %}Edit product {{ name }}{% endtrans %}</h2>
<h2>{{ object }}</h2>
<p><i>{% trans %}Creation date{% endtrans %} : {{ object.created_at|date }}</i></p>
<p><i>{% trans %}Last update{% endtrans %} : {{ object.updated_at|date }}</i></p>
{% else %}
@@ -127,19 +136,17 @@
{{ form.price_formset.management_form }}
<div x-ref="formContainer">
{%- for form in form.price_formset.forms -%}
<div>
{{ price_form(form) }}
</div>
<div>{{ price_form(form) }}</div>
{%- endfor -%}
</div>
<template x-ref="formTemplate">
<div>
{{ price_form(form.price_formset.empty_form) }}
</div>
<div>{{ price_form(form.price_formset.empty_form) }}</div>
</template>
{% if user.has_perm("counter.change_product") %}
<button class="btn btn-grey" @click.prevent="addForm()">
<i class="fa fa-plus"></i> {% trans %}Add a price{% endtrans %}
</button>
{% endif %}
</div>
<br />
@@ -165,11 +172,16 @@
<template x-ref="formTemplate">
{{ action_form(form.action_formset.empty_form) }}
</template>
{% if user.has_perm("counter.change_product") %}
<button @click.prevent="addForm()" class="btn btn-grey">
<i class="fa fa-plus"></i>{% trans %}Add action{% endtrans %}
</button>
{% endif %}
</div>
<div class="row gap margin-bottom">{{ form.archived.as_field_group() }}</div>
{% if user.has_perm("counter.change_product") %}
<p><input class="btn btn-blue" type="submit" value="{% trans %}Save{% endtrans %}" /></p>
{% endif %}
</form>
{% endblock %}
@@ -80,9 +80,11 @@
<h3 class="margin-bottom">{% trans %}Product list{% endtrans %}</h3>
<div class="row margin-bottom">
{% if user.has_perm("counter.add_product") %}
<a href="{{ url('counter:new_product') }}" class="btn btn-blue">
{% trans %}New product{% endtrans %} <i class="fa fa-plus"></i>
</a>
{% endif %}
<button
class="btn btn-blue"
@click="downloadCsv()"
@@ -13,12 +13,12 @@
{% endblock %}
{% block content %}
<p>
<a href="{{ url('counter:new_product_type') }}" class="btn btn-blue">
{% if user.has_perm("counter.add_producttype") %}
<a href="{{ url('counter:new_product_type') }}" class="btn btn-blue margin-bottom">
{% trans %}New product type{% endtrans %}
<i class="fa fa-plus"></i>
</a>
</p>
{% endif %}
{% if product_types %}
<aside>
<p>
+36 -22
View File
@@ -48,7 +48,7 @@ from counter.models import (
Selling,
)
from counter.utils import is_logged_in_counter
from counter.views.mixins import CounterAdminMixin, CounterAdminTabsMixin
from counter.views.mixins import CounterAdminTabsMixin
class CounterListView(CounterAdminTabsMixin, CanViewMixin, ListView):
@@ -84,17 +84,18 @@ class CounterEditView(
return reverse_lazy("counter:admin", kwargs={"counter_id": self.object.id})
class CounterEditPropView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
"""Edit a counter's main informations (for the counter's admin)."""
class CounterEditPropView(CounterAdminTabsMixin, PermissionRequiredMixin, UpdateView):
"""Edit a counter's main infos."""
model = Counter
form_class = modelform_factory(Counter, fields=["name", "club", "type"])
pk_url_kwarg = "counter_id"
template_name = "core/edit.jinja"
current_tab = "counters"
permission_required = "counter.change_counter"
class CounterCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
class CounterCreateView(CounterAdminTabsMixin, PermissionRequiredMixin, CreateView):
"""Create a counter (for the admins)."""
model = Counter
@@ -105,9 +106,10 @@ class CounterCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
)
template_name = "core/create.jinja"
current_tab = "counters"
permission_required = "counter.add_counter"
class CounterDeleteView(CounterAdminTabsMixin, CounterAdminMixin, DeleteView):
class CounterDeleteView(CounterAdminTabsMixin, PermissionRequiredMixin, DeleteView):
"""Delete a counter (for the admins)."""
model = Counter
@@ -115,30 +117,33 @@ class CounterDeleteView(CounterAdminTabsMixin, CounterAdminMixin, DeleteView):
template_name = "core/delete_confirm.jinja"
success_url = reverse_lazy("counter:admin_list")
current_tab = "counters"
permission_required = "counter.delete_counter"
# Product management
class ProductTypeListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
class ProductTypeListView(CounterAdminTabsMixin, PermissionRequiredMixin, ListView):
"""A list view for the admins."""
model = ProductType
template_name = "counter/product_type_list.jinja"
current_tab = "product_types"
context_object_name = "product_types"
permission_required = "counter.view_producttype"
class ProductTypeCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
class ProductTypeCreateView(CounterAdminTabsMixin, PermissionRequiredMixin, CreateView):
"""A create view for the admins."""
model = ProductType
fields = ["name", "description", "comment", "icon"]
template_name = "core/create.jinja"
current_tab = "products"
permission_required = "counter.add_producttype"
class ProductTypeEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
class ProductTypeEditView(CounterAdminTabsMixin, PermissionRequiredMixin, UpdateView):
"""An edit view for the admins."""
model = ProductType
@@ -146,23 +151,26 @@ class ProductTypeEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
fields = ["name", "description", "comment", "icon"]
pk_url_kwarg = "type_id"
current_tab = "products"
permission_required = "counter.change_producttype"
class ProductListView(CounterAdminTabsMixin, CounterAdminMixin, TemplateView):
class ProductListView(CounterAdminTabsMixin, PermissionRequiredMixin, TemplateView):
current_tab = "products"
template_name = "counter/product_list.jinja"
permission_required = "counter.view_product"
class ProductCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
class ProductCreateView(CounterAdminTabsMixin, PermissionRequiredMixin, CreateView):
"""A create view for the admins."""
model = Product
form_class = ProductForm
template_name = "counter/product_form.jinja"
current_tab = "products"
permission_required = "counter.add_product"
class ProductEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
class ProductEditView(CounterAdminTabsMixin, PermissionRequiredMixin, UpdateView):
"""An edit view for the admins."""
model = Product
@@ -170,6 +178,13 @@ class ProductEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
pk_url_kwarg = "product_id"
template_name = "counter/product_form.jinja"
current_tab = "products"
permission_required = "counter.change_product"
def has_permission(self):
return self.request.user.has_perm("counter.change_product") or (
self.request.method == "GET"
and self.request.user.has_perm("counter.view_product")
)
class ProductFormulaListView(CounterAdminTabsMixin, PermissionRequiredMixin, ListView):
@@ -299,7 +314,6 @@ class RefillingDeleteView(DeleteView):
template_name = "core/delete_confirm.jinja"
def dispatch(self, request, *args, **kwargs):
"""We have here a very particular right handling, we can't inherit from CanEditPropMixin."""
self.object = self.get_object()
if timezone.now() - self.object.date <= timedelta(
minutes=settings.SITH_LAST_OPERATIONS_LIMIT
@@ -324,7 +338,6 @@ class SellingDeleteView(DeleteView):
template_name = "core/delete_confirm.jinja"
def dispatch(self, request, *args, **kwargs):
"""We have here a very particular right handling, we can't inherit from CanEditPropMixin."""
self.object = self.get_object()
if timezone.now() - self.object.date <= timedelta(
minutes=settings.SITH_LAST_OPERATIONS_LIMIT
@@ -376,30 +389,31 @@ class CounterStatView(PermissionRequiredMixin, DetailView):
return kwargs
class CounterRefillingListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
class CounterRefillingListView(
CounterAdminTabsMixin, PermissionRequiredMixin, ListView
):
"""List of refillings on a counter."""
model = Refilling
template_name = "counter/refilling_list.jinja"
current_tab = "counters"
paginate_by = 30
permission_required = "counter.view_refilling"
def dispatch(self, request, *args, **kwargs):
self.counter = get_object_or_404(Counter, pk=kwargs["counter_id"])
self.queryset = Refilling.objects.filter(counter__id=self.counter.id)
return super().dispatch(request, *args, **kwargs)
def get_queryset(self):
self.counter = get_object_or_404(Counter, pk=self.kwargs["counter_id"])
return Refilling.objects.filter(counter=self.counter).order_by("-date")
def get_context_data(self, **kwargs):
kwargs = super().get_context_data(**kwargs)
kwargs["counter"] = self.counter
return kwargs
return super().get_context_data(**kwargs) | {"counter": self.counter}
class RefoundAccountView(UserPassesTestMixin, FormView):
class RefoundAccountView(UserPassesTestMixin, SuccessMessageMixin, FormView):
"""Create a selling with the same amount as the current user money."""
template_name = "counter/refound_account.jinja"
form_class = CloseCustomerAccountForm
success_message = _("%(user)s's AE account has been emptied")
def test_func(self):
return self.request.user.is_root or self.request.user.is_in_group(
+8 -5
View File
@@ -12,7 +12,7 @@
# OR WITHIN THE LOCAL FILE "LICENSE"
#
#
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import Http404, HttpResponse
from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView, ListView
@@ -21,28 +21,30 @@ from django.views.generic.edit import CreateView, UpdateView
from core.auth.mixins import CanViewMixin
from counter.forms import EticketForm
from counter.models import Eticket, Selling
from counter.views.mixins import CounterAdminMixin, CounterAdminTabsMixin
from counter.views.mixins import CounterAdminTabsMixin
class EticketListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
class EticketListView(CounterAdminTabsMixin, PermissionRequiredMixin, ListView):
"""A list view for the admins."""
model = Eticket
template_name = "counter/eticket_list.jinja"
ordering = ["id"]
current_tab = "etickets"
permission_required = "counter.view_eticket"
class EticketCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
class EticketCreateView(CounterAdminTabsMixin, PermissionRequiredMixin, CreateView):
"""Create an eticket."""
model = Eticket
template_name = "core/create.jinja"
form_class = EticketForm
current_tab = "etickets"
permission_required = "counter.add_eticket"
class EticketEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
class EticketEditView(CounterAdminTabsMixin, PermissionRequiredMixin, UpdateView):
"""Edit an eticket."""
model = Eticket
@@ -50,6 +52,7 @@ class EticketEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
form_class = EticketForm
pk_url_kwarg = "eticket_id"
current_tab = "etickets"
permission_required = "counter.change_eticket"
class EticketPDFView(CanViewMixin, DetailView):
+35 -35
View File
@@ -13,38 +13,13 @@
#
#
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.urls import reverse, reverse_lazy
from django.utils.translation import gettext_lazy as _
from django.views.generic.base import View
from core.views.mixins import TabedViewMixin
from counter.utils import is_logged_in_counter
class CounterAdminMixin(View):
"""Protect counter admin section."""
edit_group = [settings.SITH_GROUP_COUNTER_ADMIN_ID]
edit_club = []
def _test_group(self, user):
return any(user.is_in_group(pk=grp_id) for grp_id in self.edit_group)
def _test_club(self, user):
return any(c.can_be_edited_by(user) for c in self.edit_club)
def dispatch(self, request, *args, **kwargs):
if not (
request.user.is_root
or self._test_group(request.user)
or self._test_club(request.user)
):
raise PermissionDenied
return super().dispatch(request, *args, **kwargs)
class CounterTabsMixin(TabedViewMixin):
def get_tabs_title(self):
return self.object
@@ -89,45 +64,70 @@ class CounterTabsMixin(TabedViewMixin):
class CounterAdminTabsMixin(TabedViewMixin):
tabs_title = _("Counter administration")
list_of_tabs = [
def get_list_of_tabs(self):
user = self.request.user
res = [
{
"url": reverse_lazy("counter:admin_list"),
"slug": "counters",
"name": _("Counters"),
},
}
]
if user.has_perm("counter.view_product"):
res.append(
{
"url": reverse_lazy("counter:product_list"),
"slug": "products",
"name": _("Products"),
},
}
)
if user.has_perm("counter.view_productformula"):
res.append(
{
"url": reverse_lazy("counter:product_formula_list"),
"slug": "formulas",
"name": _("Formulas"),
},
}
)
if user.has_perm("counter.view_producttype"):
res.append(
{
"url": reverse_lazy("counter:product_type_list"),
"slug": "product_types",
"name": _("Product types"),
},
}
)
if user.has_perm("counter.view_returnableproduct"):
res.append(
{
"url": reverse_lazy("counter:returnable_list"),
"slug": "returnable_products",
"name": _("Returnable products"),
},
}
)
if user.has_perm("counter.view_cashregistersummary"):
res.append(
{
"url": reverse_lazy("counter:cash_summary_list"),
"slug": "cash_summary",
"name": _("Cash register summaries"),
},
}
)
if user.has_perm("counter.view_invoicecall"):
res.append(
{
"url": reverse_lazy("counter:invoices_call"),
"slug": "invoices_call",
"name": _("Invoices call"),
},
}
)
if user.has_perm("counter.view_eticket"):
res.append(
{
"url": reverse_lazy("counter:eticket_list"),
"slug": "etickets",
"name": _("Etickets"),
},
]
}
)
return res
+5 -7
View File
@@ -48,7 +48,7 @@ des scripts complets mais qui restent lisibles,
```
Ok, c'est de la triche, on installe un package externe.
Mais bon, ça marche, et l'équivalent pur bash
serait carrément plus moche.
serait un pur enfer.
=== "nu"
@@ -59,20 +59,18 @@ des scripts complets mais qui restent lisibles,
Nombre de lignes total :
```nu
ls **/*.py | insert linecount { get name | open | lines | length } | math sum
ls **/*.py | par-each { open $in.name | lines | length } | math sum
```
Vous pouvez aussi exlure les lignes vides
et les les lignes de commentaire :
```nu
ls **/*.py |
insert linecount {
get name |
open |
par-each {
open $in.name |
lines |
each { str trim } |
filter { |l| not ($l | str starts-with "#") } | # commentaires
filter { |l| ($l | str length) > 0 } | # lignes vides
where { |l| ($l | str length) > 0 and not ($l | str starts-with "#") } |
length
} |
math sum
+1
View File
@@ -0,0 +1 @@
::: api.schemas
+1
View File
@@ -0,0 +1 @@
::: api.views
+378
View File
@@ -0,0 +1,378 @@
Le site AE offre des mécanismes permettant aux applications tierces
de récupérer les informations sur un utilisateur du site AE.
De cette manière, il devient possible de synchroniser les informations
qu possède l'application tierce sur l'utilisateur, directement depuis
le site AE.
## Fonctionnement général
Pour authentifier vos utilisateurs, vous aurez besoin d'un serveur web
et d'un client d'API (celui auquel est liée votre
[clef d'API](./connect.md#obtenir-une-clef-dapi)).
Deux informations vous sont nécessaires, en plus de votre clef d'API :
- l'id du client : vous pouvez l'obtenir soit en le demandant à l'équipe info,
soit en appelant la route `GET /api/client/me` avec votre clef d'API
renseignée dans le header [X-APIKey](./connect.md#x-apikey)
- la clef HMAC du client : vous devez la demander à l'équipe info.
Ces deux éléments ont une fonction différente : l'id du client permet
de dire au serveur quelle est l'application qui s'adresse à lui,
tandis que la [clef HMAC](https://fr.wikipedia.org/wiki/HMAC)
servira à créer une signature unique permettant de s'assurer
que les données transmises n'ont pas été falsifiées.
Grâce à ces informations, vous allez pouvoir fournir le contexte nécessaire
au site AE pour qu'il authentifie vos utilisateurs.
En effet, la démarche d'authentification s'effectue presque entièrement
sur le site : le travail de l'application tierce consiste uniquement
à fournir à l'utilisateur une url avec les bons paramètres, puis
à recevoir la réponse du serveur si tout s'est bien passé.
Comme un dessin vaut parfois mieux que mille mots,
voici les diagrammes décrivant le processus.
L'un montre l'entièreté de la démarche ;
l'autre dans un souci de simplicité, ne montre que ce qui est visible
directement par l'application tierce.
=== "Intégralité du processus"
```mermaid
sequenceDiagram
actor User
participant App
User->>+App: Authentifie-moi, stp
App-->>-User: url de connexion<br/>avec signature
User->>+Sith: GET url
opt Utilisateur non-connecté
Sith->>+User: Formulaire de connexion
User-->>-Sith: Connexion
end
Sith->>Sith: vérification de la signature
Sith->>+User: Formulaire<br/>des conditions<br/>d'utilisation
User-->>-Sith: Validation
Sith->>+App: URL de retour<br/>avec données utilisateur
App->>App: Traitement des <br/>données utilisateur
App-->>-Sith: 204 OK, No content
Sith-->>-User: Message de succès
App--)User: Message de succès
```
=== "Point de vue de l'application tierce"
```mermaid
sequenceDiagram
actor User
participant App
User->>+App: Authentifie-moi, stp
App-->>-User: url de connexion<br/>avec signature
opt
Sith->>+App: URL de retour<br/>avec données utilisateur
App->>App: Traitement des <br/>données utilisateur
App-->>-Sith: 204 OK, No content
App--)User: Message de succès
end
```
## Données attendues
### URL de connexion
L'URL de connexion que vous allez fournir à l'utilisateur doit
être `https://ae.utbm.fr/api-link/auth/`
et doit contenir les données décrites dans
[`ThirdPartyAuthParamsSchema`][api.schemas.ThirdPartyAuthParamsSchema] :
- `client_id` (integer) : l'id de votre client, que vous pouvez obtenir
de la manière décrite plus haut
- `third_party_app`(string) : le nom de la plateforme pour laquelle
l'authentification va être réalisée (si votre application est un bot
discord, mettez la valeur "discord")
- `privacy_link`(URL) : l'URL vers la page de politique de confidentialité
qui s'appliquera dans le cadre de l'application
(s'il s'agit d'un bot discord, donnez le lien vers celles de Discord)
- `username`(string) : le pseudonyme que l'utilisateur possède sur
votre application
- `callback_url`(URL) : l'URL que le site AE appellera si l'authentification
réussit
- `signature`(string) : la signature des données de la requête.
Il s'agit d'une signature par clef HMAC dont le fonctionnement
est détaillé plus bas.
Ces données doivent être url-encodées et passées dans les paramètres GET.
!!!warning "URL de retour"
Les URLs fournies doivent être des URLs HTTP valides.
En outre, elles doivent obligatoirement inclure la barre oblique finale.
=== "URL correcte ✔️"
`https://exemple.ae.utbm.fr/foo/`
=== "URL incorrecte ❌"
`https://exemple.ae.utbm.fr/foo`
!!!tip
Inclure l'id de votre utilisateur dans l'URL de retour
peut être un bon moyen de l'identifier lors du callback.
Par exemple : `GET /callback/{int:user_id}/`.
???Example
Supposons que votre client d'API soit utilisé dans le cadre d'un bot Discord,
avec les données suivantes :
- l'id du client est 15
- sa clef HMAC est "beb99dd53"
(c'est pour l'exemple, une vraie clef sera beaucoup plus longue)
- le pseudonyme discord de votre utilisateur est Brian
- son id sur discord est 123456789
- votre route de callback est `GET /callback/{int:user_id}/`,
accessible au domaine `https://bot.ae.utbm.fr`
Alors les paramètres de votre URL seront :
| Paramètre | valeur |
|-----------------|-----------------------------------------------------------------------|
| client_id | 15 |
| third_party_app | discord |
| privacy_link | `https://discord.com/privacy` |
| username | Brian |
| callback_url | `https://bot.ae.utbm.fr/callback/123456789/` |
| signature | 1a383c51060be64f07772aa42e07<br/>18ae096b8f21f2cdb4061c0834a416d12101 |
Et l'url fournie à l'utilisateur sera :
`https://ae.utbm.fr/api-link/auth/?client_id=15&third_party_app=discord
&privacy_link=https%3A%2F%2Fdiscord.com%2Fprivacy&username=Brian
&callback_url=https%3A%2F%2Fbot.ae.utbm.fr%2Fcallback%2F123456789%2F
&signature=1a383c51060be64f07772aa42e0718ae096b8f21f2cdb4061c0834a416d12101`
### Données de retour
Si l'authentification réussit, le site AE enverra une requête HTTP POST
à l'URL de retour fournie dans l'URL de connexion.
Le corps de la requête de callback et au format JSON
et contient deux paires clef-valeur :
- `user` : les données utilisateur, telles que décrites
par [UserProfileSchema][core.schemas.UserProfileSchema]
- `signature` : la signature des données utilisateur
???Example
En reprenant les mêmes paramètres que dans l'exemple précédent,
le site AE pourra renvoyer à l'application la requête suivante :
```http
POST https://bot.ae.utbm.fr/callback/123456789/
content-type: application/json
body: {
"user": {
"id": 144131,
"nick_name": "inzekitchen",
"first_name": "Brian",
...
},
"signature": "f16955bab6b805f6e1abbb98a86dfee53fed0bf812aa6513ca46cfd461b70020"
}
```
L'application doit répondre avec un des codes HTTP suivants :
| Code | Raison |
|------|--------------------------------------------------------------------------------|
| 204 | Tout s'est bien passé |
| 403 | Les données de retour ne sont <br>pas signées ou sont mal signées |
| 404 | L'URL de retour ne permet pas <br>d'identifier un utilisateur de l'application |
!!!note "Code d'erreur par défaut"
Si l'appel de la route fait face à plusieurs problèmes en même temps
(par exemple, l'URL ne permet pas de retrouver votre utilisateur,
et en plus les données sont mal signées),
le 403 prime et doit être retourné par défaut.
## Signature des données
Les données de l'URL de connexion doivent être signées,
et la signature de l'URL de retour doit être vérifiée.
Dans le deux cas, la signature est le digest HMAC-SHA512
des données url-encodées, en utilisant la clef HMAC du client d'API.
L'ordre dans lequel ces données sont placées dans l'encodage URL
doit être strictement le même que celui donné plus haut.
???Example "Signature de l'URL de connexion"
En reprenant le même exemple que les fois précédentes,
l'url-encodage des données est :
`client_id=15&third_party_app=discord
&privacy_link=https%3A%2F%2Fdiscord.com%2Fprivacy%2F&username=Brian
&callback_url=https%3A%2F%2Fbot.ae.utbm.fr%2Fcallback%2F123456789%2F`
Notez que la signature n'est pas (encore) dedans.
Cette dernière peut-être obtenue avec le code suivant :
=== ":simple-python: Python"
Dépendances :
- `environs` (>=14.1)
```python
import hmac
from urllib.parse import urlencode
from environs import Env
env = Env()
env.read_env()
key = env.str("HMAC_KEY").encode()
data = {
"client_id": 15,
"third_party_app": "discord",
"privacy_link": "https://discord.com/privacy/",
"username": "Brian",
"callback_url": "https://bot.ae.utbm.fr/callback/123456789/",
}
urlencoded = urlencode(data)
data["signature"] = hmac.digest(key, urlencoded.encode(), "sha512").hex()
# URL a fournir à l'utilisateur pour son authentification
user_url = f"https://ae.ubtm.fr/api-link/auth/?{urlencode(data)}"
```
=== ":simple-rust: Rust"
Dépendances :
- `hmac` (>=0.12.1)
- `url` (>=2.5.7, features `serde`)
- `serde` (>=1.0.228, features `derive`)
- `serde_urlencoded` (>=0.7.1)
- `sha2` (>=0.10.9)
- `dotenvy` (>= 0.15)
```rust
use hmac::{Mac, SimpleHmac};
use serde::Serialize;
use sha2::Sha512;
use url::Url;
#[derive(Serialize, Debug)]
struct UrlData<'a> {
client_id: u32,
third_party_app: &'a str,
privacy_link: Url,
username: &'a str,
callback_url: Url,
}
impl<'a> UrlData<'a> {
pub fn signature(&self, key: &[u8]) -> CtOutput<SimpleHmac<Sha512>> {
let urlencoded = serde_urlencoded::to_string(self).unwrap();
SimpleHmac::<Sha512>::new_from_slice(key)
.unwrap()
.chain_update(urlencoded.as_bytes())
.finalize()
}
}
impl Into<Url> for UrlData<'_> {
fn into(self) -> Url {
let key = std::env::var("HMAC_KEY").unwrap();
let mut url = Url::parse("http://ae.utbm.fr/api-link/auth/").unwrap();
url.set_query(Some(
format!(
"{}&signature={:x}",
serde_urlencoded::to_string(&self).unwrap(),
self.signature(key.as_bytes()).into_bytes()
)
.as_str(),
));
url
}
}
fn main() {
dotenvy::dotenv().expect("Couldn't load env");
let data = UrlData {
client_id: 1,
third_party_app: "discord",
privacy_link: "https://discord.com/privacy/".parse().unwrap(),
username: "Brian",
callback_url: "https://bot.ae.utbm.fr/callback/123456789/"
.parse()
.unwrap(),
};
let url: Url = data.into();
println!("{:?}", url);
}
```
???Example "Vérification de la signature de la réponse"
Les données utilisateur peuvent ressembler à :
```json
{
"user": {
"display_name": "Matthieu Vincent",
"profile_url": "/user/380/",
"profile_pict": "/static/core/img/unknown.jpg",
"id": 380,
"nick_name": None,
"first_name": "Matthieu",
"last_name": "Vincent",
},
"signature": "3802a280fbb01bd9fetc."
}
```
Vous pouvez vérifier la signature ainsi :
```python
import hmac
from urllib.parse import urlencode
from environs import Env
env = Env()
env.read_env()
def is_signature_valid(user_data: dict, signature: str) -> bool:
key = env.str("HMAC_KEY").encode()
urlencoded = urlencode(user_data)
return hmac.compare_digest(
hmac.digest(key, urlencoded.encode(), "sha512").hex(),
signature,
)
post_data = <récupération des données POST>
print(
"signature valide :",
is_signature_valid(post_data["user"], post_data["signature"])
)
```
!!!Warning
Vous devez impérativement vérifier la signature
des données de la requête de callback !
Ne pas vérifier la signature permet à n'importe quel acteur
tierce malveillant de vous appeler sur votre callback.
Ce serait une faille de sécurité majeure de votre côté.
Si l'équipe informatique se rend compte que vous ne le faites pas,
elle se réserve le droit de suspendre votre application,
immédiatement et sans préavis.
+4 -4
View File
@@ -112,7 +112,7 @@ cf. [HTTP persistant connection (wikipedia)](https://en.wikipedia.org/wiki/HTTP_
Voici quelques exemples :
=== "Python (requests)"
=== ":simple-python: Python (requests)"
Dépendances :
@@ -132,7 +132,7 @@ Voici quelques exemples :
print(response.json())
```
=== "Python (aiohttp)"
=== ":simple-python: Python (aiohttp)"
Dépendances :
@@ -159,7 +159,7 @@ Voici quelques exemples :
asyncio.run(main())
```
=== "Javascript (axios)"
=== ":simple-javascript: Javascript (axios)"
Dépendances :
@@ -179,7 +179,7 @@ Voici quelques exemples :
console.log(await instance.get("club/1").json());
```
=== "Rust (reqwest)"
=== ":simple-rust: Rust (reqwest)"
Dépendances :
+33 -9
View File
@@ -18,7 +18,8 @@ il n'est pas possible de développer le site sur ce système d'exploitation.
Heureusement, il existe une alternative qui ne requiert pas de désinstaller votre
OS ni de mettre un dual boot sur votre ordinateur : `WSL`.
- **Prérequis:** vous devez être sur Windows 10 version 2004 ou ultérieure (build 19041 & versions ultérieures) ou Windows 11.
- **Prérequis:** vous devez être sur Windows 10 version 2004 ou ultérieure (build 19041 & versions ultérieures) ou
Windows 11.
- **Plus d'info:** [docs.microsoft.com](https://docs.microsoft.com/fr-fr/windows/wsl/install)
```shell
@@ -43,7 +44,7 @@ il suffit d'utiliser la commande suivante :
cd /mnt/<la_lettre_du_disque>/vos/fichiers/comme/dhab
```
!!!note
!!!success
À ce stade, si vous avez réussi votre installation de `WSL` ou bien qu'il
était déjà installé, vous pouvez effectuer la mise en place du projet en suivant
@@ -101,10 +102,10 @@ cd /mnt/<la_lettre_du_disque>/vos/fichiers/comme/dhab
ln -s /usr/bin/valkey-server /usr/bin/redis-server
```
=== "macOS"
Pour installer les dépendances, il est fortement recommandé d'installer le gestionnaire de paquets `homebrew <https://brew.sh/index_fr>`_.
Pour installer les dépendances, il est fortement recommandé
d'installer le gestionnaire de paquets `homebrew <https://brew.sh/index_fr>`_.
Il est également nécessaire d'avoir installé xcode
```bash
@@ -116,12 +117,15 @@ cd /mnt/<la_lettre_du_disque>/vos/fichiers/comme/dhab
!!!note
Si vous rencontrez des erreurs lors de votre configuration, n'hésitez pas à vérifier l'état de votre installation homebrew avec :code:`brew doctor`
Si vous rencontrez des erreurs lors de votre configuration,
n'hésitez pas à vérifier l'état de votre installation homebrew
avec :code:`brew doctor`
!!!note
Python ne fait pas parti des dépendances puisqu'il est automatiquement
installé par uv. Il est cependant parfois nécessaire d'installer les headers Python nécessaire à la compilation de certains paquets.
installé par uv. Il est cependant parfois nécessaire d'installer
les headers Python nécessaire à la compilation de certains paquets.
## Finaliser l'installation
@@ -145,7 +149,6 @@ uv run ./manage.py install_xapian
de texte à l'écran.
C'est normal, il ne faut pas avoir peur.
La modification de la configuration passe par la modification de variables
d'environnement.
Ces variables sont stockées dans un fichier `.env`.
@@ -183,12 +186,33 @@ Il suffit ensuite d'utiliser cette commande :
uv run ./manage.py runserver
```
!!!note
Le serveur est alors accessible à l'adresse
[http://localhost:8000](http://localhost:8000)
ou bien [http://127.0.0.1:8000/](http://127.0.0.1:8000/).
Pour vous connecter, vous pouvez utiliser un des comptes utilisateur
créés durant l'installation :
| username | description |
|------------------|----------------------------------------------------------------------------|
| `root` | super-utilisateur<br/>il peut tout faire et tout voir |
| `subscriber` | simple cotisant |
| `old_subscriber` | ancien cotisant |
| `public` | non-cotisant |
| `krophil` | cotisant<br/>barman Foyer<br/>président du Troll Penché |
| `sli` | cotisant<br/>VP Troll |
| `skia` | cotisant<br/>barman MDE<br/>membre du bureau AE<br/>ancien membre du Troll |
| `comunity` | cotisant<br/>membre du bureau PdF<br/>admin communication |
| `counter` | cotisant<br/>admin comptoirs |
| `comptable` | cotisant<br/>admin comptabilité |
| `rbatsbak` | cotisant<br/>membre du Troll |
En plus de ces dernier, quelques centaines d'utilisateurs
supplémentaires sont générés procéduralement,
afin de rajouter un peu de volume de données.
Tous les utilisateurs ont le mot de passe `plop`.
!!!note
Le serveur de développement se charge de lancer redis
-37
View File
@@ -1,37 +0,0 @@
#
# Copyright 2022
# - Maréchal <thgirod@hotmail.com
#
# Ce fichier fait partie du site de l'Association des Étudiants de l'UTBM,
# http://ae.utbm.fr.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License a published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.
class PaymentResultConverter:
"""Converter used for url mapping of the `eboutic.views.payment_result` view.
It's meant to build an url that can match
either `/eboutic/pay/success/` or `/eboutic/pay/failure/`
but nothing else.
"""
regex = "(success|failure)"
def to_python(self, value):
return str(value)
def to_url(self, value):
return str(value)
+2 -2
View File
@@ -24,7 +24,7 @@
from django.urls import path, register_converter
from eboutic.converters import PaymentResultConverter
from core.converters import ResultConverter
from eboutic.views import (
BillingInfoFormFragment,
EbouticCheckout,
@@ -34,7 +34,7 @@ from eboutic.views import (
payment_result,
)
register_converter(PaymentResultConverter, "res")
register_converter(ResultConverter, "res")
urlpatterns = [
# Subscription views
+5 -2
View File
@@ -346,13 +346,16 @@ class ForumTopicDetailView(CanViewMixin, DetailView):
return kwargs
class ForumMessageView(SingleObjectMixin, RedirectView):
class ForumMessageView(SingleObjectMixin, UserPassesTestMixin, RedirectView):
model = ForumMessage
pk_url_kwarg = "message_id"
permanent = False
def get_redirect_url(self, *args, **kwargs):
def test_func(self) -> bool:
self.object = self.get_object()
return self.request.user.can_view(self.object)
def get_redirect_url(self, *args, **kwargs):
return self.object.get_url()
+372 -116
View File
@@ -6,7 +6,7 @@
msgid ""
msgstr ""
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-09 07:21+0200\n"
"POT-Creation-Date: 2026-10-25 12:04+0100\n"
"PO-Revision-Date: 2016-07-18\n"
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
"Language-Team: AE info <ae.info@utbm.fr>\n"
@@ -35,6 +35,10 @@ msgstr ""
"True si gardé à jour par le biais d'un fournisseur externe de domains "
"toxics, False sinon"
#: api/admin.py
msgid "Reset HMAC key"
msgstr "Réinitialiser la clef HMAC"
#: api/admin.py
#, python-format
msgid ""
@@ -48,6 +52,23 @@ msgstr ""
msgid "Revoke selected API keys"
msgstr "Révoquer les clefs d'API sélectionnées"
#: api/forms.py
msgid "I have read and I accept the terms and conditions of use"
msgstr "J'ai lu et j'accepte les conditions générales d'utilisation."
#: api/forms.py
msgid "You must approve the terms and conditions of use."
msgstr "Vous devez approuver les conditions générales d'utilisation."
#: api/forms.py
msgid "You must confirm that this is your username."
msgstr "Vous devez confirmer que c'est bien votre nom d'utilisateur."
#: api/forms.py
#, python-format
msgid "I confirm that %(username)s is my username on %(app)s"
msgstr "Je confirme que %(username)s est mon nom d'utilisateur sur %(app)s"
#: api/models.py club/models.py com/models.py counter/models.py forum/models.py
msgid "name"
msgstr "nom"
@@ -68,6 +89,10 @@ msgstr "permissions du client"
msgid "Specific permissions for this api client."
msgstr "Permissions spécifiques pour ce client d'API"
#: api/models.py
msgid "HMAC Key"
msgstr "Clef HMAC"
#: api/models.py
msgid "api client"
msgstr "client d'api"
@@ -97,6 +122,76 @@ msgstr "clef d'api"
msgid "api keys"
msgstr "clefs d'api"
#: api/templates/api/third_party/auth.jinja
msgid "Confidentiality"
msgstr "Confidentialité"
#: api/templates/api/third_party/auth.jinja
#, python-format
msgid ""
"By ticking this box and clicking on the send button, you acknowledge and "
"agree to provide %(app)s with your first name, last name, nickname and any "
"other information that was the third party app was explicitly authorized to "
"fetch and that it must have acknowledged to you, in a complete and accurate "
"manner."
msgstr ""
"En cochant cette case et en cliquant sur le bouton « Envoyer », vous "
"reconnaissez et acceptez de fournir à %(app)s votre prénom, nom, pseudonyme "
"et toute autre information que l'application tierce a été explicitement "
"autorisée à récupérer et qu'elle doit vous avoir communiqué de manière "
"complète et exacte."
#: api/templates/api/third_party/auth.jinja
#, python-format
msgid ""
"The privacy policies of <a href=\"%(privacy_link)s\">%(app)s</a> and of <a "
"href=\"%(sith_cgu_link)s\">the Students' Association</a> applies as soon as "
"the form is submitted."
msgstr ""
"Les politiques de confidentialité de <a href=\"%(privacy_link)s\">%(app)s</"
"a> et de <a href=\"%(sith_cgu_link)s\">l'Association des Etudiants</a> "
"s'appliquent dès la soumission du formulaire."
#: api/templates/api/third_party/auth.jinja
msgid "Confirmation of identity"
msgstr "Confirmation d'identité"
#: api/views.py
msgid "The data provided for authentication is incorrect"
msgstr "Les données fournies pour l'authentification sont incorrectes."
#: api/views.py
msgid ""
"The signature is incorrect. We cannot ensure the provenance of the request."
msgstr ""
"La signature est incorrecte. Nous ne pouvons pas garantir l'authenticité de "
"la requête."
#: api/views.py
#, python-format
msgid ""
"You are going to link your AE account and your %(app)s account. Continue "
"only if this page was opened from %(app)s."
msgstr ""
"Vous allez lier votre compte AE et votre compte %(app)s. Poursuivez "
"uniquement si cette page a été ouverte depuis %(app)s."
#: api/views.py
msgid "You have been successfully authenticated. You can now close this page."
msgstr ""
"Vous avez été authentifié avec succès. Vous pouvez maintenant fermer cette "
"page."
#: api/views.py
msgid ""
"Your authentication on the AE website was successful, but an error happened "
"during the interaction with the third-party application. Please contact the "
"managers of the latter."
msgstr ""
"Votre authentification sur le site AE a fonctionné, mais une erreur est "
"arrivée durant l'interaction avec l'application tierce. Veuillez contacter "
"les responsables de cette dernière."
#: club/forms.py
msgid "Users to add"
msgstr "Utilisateurs à ajouter"
@@ -141,7 +236,7 @@ msgstr "vous devez spécifier au moins un utilisateur ou une adresse email"
msgid "Begin date"
msgstr "Date de début"
#: club/forms.py com/forms.py counter/forms.py subscription/forms.py
#: club/forms.py com/forms.py counter/forms.py
msgid "End date"
msgstr "Date de fin"
@@ -299,7 +394,8 @@ msgstr ""
"de la présidence."
#: club/models.py core/models.py counter/models.py eboutic/models.py
#: election/models.py pedagogy/models.py sas/models.py trombi/models.py
#: election/models.py pedagogy/models.py sas/models.py timetable/models.py
#: trombi/models.py
msgid "user"
msgstr "utilisateur"
@@ -422,6 +518,22 @@ msgstr "Url dupliquée"
msgid "This link doesn't match with the url base of its type."
msgstr "Ce lien ne correspond pas à l'url de base de son type."
#: club/templates/club/club_detail.jinja club/views.py
#: com/templates/com/news_admin_list.jinja com/templates/com/poster_list.jinja
#: com/templates/com/screen_list.jinja com/templates/com/weekmail.jinja
#: core/templates/core/file.jinja core/templates/core/group_list.jinja
#: core/templates/core/page/base.jinja core/templates/core/user_tools.jinja
#: core/views/user.py counter/templates/counter/cash_summary_list.jinja
#: counter/templates/counter/counter_list.jinja
#: election/templates/election/election_detail.jinja
#: forum/templates/forum/macros.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/guide.jinja sas/templates/sas/album.jinja
#: trombi/templates/trombi/detail.jinja
#: trombi/templates/trombi/edit_profile.jinja
msgid "Edit"
msgstr "Éditer"
#: club/templates/club/club_detail.jinja com/templates/com/news_list.jinja
msgid "Links"
msgstr "Liens"
@@ -469,6 +581,7 @@ msgid "Role"
msgstr "Rôle"
#: club/templates/club/club_members.jinja
#: club/templates/club/club_news_list.jinja
#: club/templates/club/club_old_members.jinja
#: core/templates/core/group_list.jinja core/templates/core/user_clubs.jinja
msgid "Description"
@@ -483,6 +596,34 @@ msgstr "Depuis"
msgid "There are no members in this club."
msgstr "Il n'y a pas de membres dans ce club."
#: club/templates/club/club_news_list.jinja
#: com/templates/com/news_admin_list.jinja com/templates/com/news_edit.jinja
#: com/templates/com/news_list.jinja core/templates/core/user_tools.jinja
msgid "Create news"
msgstr "Créer une nouvelle"
#: club/templates/club/club_news_list.jinja
#, python-format
msgid "Dates (%(nb_occurrences)s occurrences)"
msgstr "Dates (%(nb_occurrences)s occurrences)"
#: club/templates/club/club_news_list.jinja
msgid "Permalink"
msgstr "Permalien"
#: club/templates/club/club_news_list.jinja
#: com/templates/com/news_admin_list.jinja
msgid "Summary"
msgstr "Résumé"
#: club/templates/club/club_news_list.jinja
msgid "No summary"
msgstr "Pas de Résumé"
#: club/templates/club/club_news_list.jinja
msgid "No detailed description"
msgstr "Pas de description détaillée"
#: club/templates/club/club_old_members.jinja
msgid "Club old members"
msgstr "Anciens membres du club"
@@ -736,8 +877,9 @@ msgstr "Méthode de paiement"
#: counter/templates/counter/fragments/create_student_card.jinja
#: counter/templates/counter/last_ops.jinja
#: election/templates/election/election_detail.jinja
#: forum/templates/forum/macros.jinja pedagogy/templates/pedagogy/guide.jinja
#: pedagogy/templates/pedagogy/ue_detail.jinja sas/templates/sas/album.jinja
#: forum/templates/forum/macros.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/guide.jinja sas/templates/sas/album.jinja
#: sas/templates/sas/moderation.jinja sas/templates/sas/picture.jinja
#: trombi/templates/trombi/detail.jinja
#: trombi/templates/trombi/edit_profile.jinja
@@ -918,30 +1060,16 @@ msgstr "Anciens membres"
msgid "History"
msgstr "Historique"
#: club/views.py com/templates/com/news_admin_list.jinja
#: core/templates/core/base/navbar.jinja
msgid "Events"
msgstr "Événements"
#: club/views.py core/templates/core/base/header.jinja core/views/user.py
#: sas/templates/sas/picture.jinja trombi/views.py
msgid "Tools"
msgstr "Outils"
#: club/views.py com/templates/com/news_admin_list.jinja
#: com/templates/com/poster_list.jinja com/templates/com/screen_list.jinja
#: com/templates/com/weekmail.jinja core/templates/core/file.jinja
#: core/templates/core/group_list.jinja core/templates/core/page/base.jinja
#: core/templates/core/user_tools.jinja core/views/user.py
#: counter/templates/counter/cash_summary_list.jinja
#: counter/templates/counter/counter_list.jinja
#: election/templates/election/election_detail.jinja
#: forum/templates/forum/macros.jinja pedagogy/templates/pedagogy/guide.jinja
#: pedagogy/templates/pedagogy/ue_detail.jinja sas/templates/sas/album.jinja
#: trombi/templates/trombi/detail.jinja
#: trombi/templates/trombi/edit_profile.jinja
msgid "Edit"
msgstr "Éditer"
#: club/views.py
msgid "Edit club page"
msgstr "Éditer la page de club"
#: club/views.py
msgid "Sellings"
msgstr "Vente"
@@ -996,7 +1124,7 @@ msgstr "Prix d'achat"
msgid "Format: 16:9 | Resolution: 1920x1080"
msgstr "Format : 16:9 | Résolution : 1920x1080"
#: com/forms.py subscription/forms.py
#: com/forms.py
msgid "Start date"
msgstr "Date de début"
@@ -1188,8 +1316,9 @@ msgstr "Actions"
#: com/templates/com/mailing_admin.jinja com/templates/com/poster_list.jinja
#: core/templates/core/file_detail.jinja
#: core/templates/core/file_moderation.jinja sas/templates/sas/moderation.jinja
#: sas/templates/sas/picture.jinja
#: core/templates/core/file_moderation.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: sas/templates/sas/moderation.jinja sas/templates/sas/picture.jinja
msgid "Moderate"
msgstr "Modérer"
@@ -1223,11 +1352,6 @@ msgstr "Administration des nouvelles"
msgid "News"
msgstr "Nouvelles"
#: com/templates/com/news_admin_list.jinja com/templates/com/news_edit.jinja
#: com/templates/com/news_list.jinja core/templates/core/user_tools.jinja
msgid "Create news"
msgstr "Créer une nouvelle"
#: com/templates/com/news_admin_list.jinja
msgid "Weeklies"
msgstr "Événements hebdomadaires"
@@ -1242,10 +1366,6 @@ msgstr "Événements hebdomadaires affichées"
msgid "Title"
msgstr "Titre"
#: com/templates/com/news_admin_list.jinja
msgid "Summary"
msgstr "Résumé"
#: com/templates/com/news_admin_list.jinja com/templates/com/weekmail.jinja
#: forum/templates/forum/forum.jinja sas/models.py
msgid "Author"
@@ -1273,11 +1393,6 @@ msgstr "Dépublier"
msgid "Weeklies to moderate"
msgstr "Nouvelles hebdomadaires à modérer"
#: com/templates/com/news_admin_list.jinja
#: core/templates/core/base/navbar.jinja
msgid "Events"
msgstr "Événements"
#: com/templates/com/news_admin_list.jinja
msgid "Displayed events"
msgstr "Événements affichés"
@@ -1491,7 +1606,6 @@ msgstr "Descendre"
#: com/templates/com/weekmail_preview.jinja
#: core/templates/core/user_account_detail.jinja
#: pedagogy/templates/pedagogy/ue_detail.jinja
#: trombi/templates/trombi/comment_moderation.jinja
#: trombi/templates/trombi/export.jinja
msgid "Back"
@@ -1776,7 +1890,7 @@ msgstr "département"
msgid "dpt option"
msgstr "Filière"
#: core/models.py pedagogy/models.py
#: core/models.py pedagogy/models.py timetable/models.py
msgid "semester"
msgstr "semestre"
@@ -1835,6 +1949,10 @@ msgstr ""
"Même si ce profil est caché, les utilisateurs sur cette liste pourront "
"toujours le voir."
#: core/models.py
msgid "ToS approved at"
msgstr "CGU approuvées le"
#: core/models.py
msgid "A user with that username already exists"
msgstr "Un utilisateur de ce nom d'utilisateur existe déjà"
@@ -1842,7 +1960,9 @@ msgstr "Un utilisateur de ce nom d'utilisateur existe déjà"
#: core/models.py core/templates/core/macros.jinja
#: core/templates/core/user_detail.jinja core/templates/core/user_edit.jinja
#: election/templates/election/election_detail.jinja
#: forum/templates/forum/macros.jinja trombi/templates/trombi/user_tools.jinja
#: forum/templates/forum/macros.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: trombi/templates/trombi/user_tools.jinja
msgid "Profile"
msgstr "Profil"
@@ -1895,6 +2015,18 @@ msgstr ""
"Autorise les cotisants (ou les personnes whitelistées, si votre profil est "
"caché) à accéder aux statistiques de votre compte AE"
#: core/models.py
msgid "show your timetable to others"
msgstr "montrez votre emploi du temps aux autres"
#: core/models.py
msgid ""
"Allow subscribers to see your timetable and to compare it to theirs (if you "
"have filled it)"
msgstr ""
"Permet aux cotisants de voir votre emploi du temps et de le comparer au leur "
"(si vous l'avez enregistré)"
#: core/models.py
msgid "get a notification for every click"
msgstr "avoir une notification pour chaque click"
@@ -2109,7 +2241,8 @@ msgstr "R&D"
msgid "Site created by the IT Department of the AE"
msgstr "Site réalisé par le Pôle Informatique de l'AE"
#: core/templates/core/base/header.jinja core/templates/core/login.jinja
#: core/templates/core/base/header.jinja core/templates/core/cgu_approve.jinja
#: core/templates/core/login.jinja
#: core/templates/core/password_reset_complete.jinja
msgid "Login"
msgstr "Connexion"
@@ -2207,6 +2340,18 @@ msgstr "FAQ"
msgid "Wiki"
msgstr "Wiki"
#: core/templates/core/cgu_approve.jinja
msgid "Terms of Service"
msgstr "Conditions générales d'utilisation"
#: core/templates/core/cgu_approve.jinja
msgid ""
"To continue using our services, please read and approve the AE website's "
"terms of service"
msgstr ""
"Pour continuer à utiliser nos services, veuillez lire et approuver les "
"conditions générales d'utilisation du site AE."
#: core/templates/core/create.jinja
#, python-format
msgid "Create %(name)s"
@@ -2233,6 +2378,7 @@ msgstr "Confirmation"
#: core/templates/core/file_delete_confirm.jinja
#: counter/templates/counter/counter_click.jinja
#: counter/templates/counter/fragments/delete_student_card.jinja
#: pedagogy/templates/pedagogy/fragments/comment_report.jinja
#: sas/templates/sas/ask_picture_removal.jinja
msgid "Cancel"
msgstr "Annuler"
@@ -3133,6 +3279,19 @@ msgstr "Appliquer les droits récursivement"
msgid "Ensure this timestamp is set in the future"
msgstr "Assurez-vous que cet horodatage est dans le futur"
#: core/views/forms.py
msgid "You must approve the terms of service."
msgstr "Vous devez approuver les conditions générales d'utilisation"
#: core/views/forms.py
#, python-format
msgid ""
"I have read and I approve the <a href=\"%(url)s\" target=\"_blank\">Terms of "
"Service</a>"
msgstr ""
"J'ai lu et j'approuve les <a href=\"%(url)s\" target=\"_blank\">Conditions "
"Générales d'utilisation</a>"
#: core/views/forms.py
msgid "Username, email, or account number"
msgstr "Nom d'utilisateur, email, ou numéro de compte AE"
@@ -3779,7 +3938,6 @@ msgstr "Coffre vidé"
#: counter/templates/counter/cash_summary_list.jinja counter/views/cash.py
#: pedagogy/templates/pedagogy/moderation.jinja
#: pedagogy/templates/pedagogy/ue_detail.jinja
#: trombi/templates/trombi/comment.jinja
#: trombi/templates/trombi/user_tools.jinja
msgid "Comment"
@@ -3973,7 +4131,6 @@ msgstr "Nouvelle formule"
#: counter/templates/counter/fragments/create_student_card.jinja
#: counter/templates/counter/invoices_call.jinja
#: sas/templates/sas/picture.jinja
#: subscription/templates/subscription/stats.jinja
msgid "Go"
msgstr "Valider"
@@ -4108,9 +4265,12 @@ msgid "Remove price"
msgstr "Retirer le prix"
#: counter/templates/counter/product_form.jinja
#, python-format
msgid "Edit product %(name)s"
msgstr "Édition du produit %(name)s"
msgid ""
"You can see product details. However, you cannot edit it, thus you won't be "
"able to submit this form."
msgstr ""
"Vous pouvez voir ce produit. Cependant, vous ne pouvez pas l'éditer ; vous "
"ne serez donc pas en mesure de soumettre le formulaire."
#: counter/templates/counter/product_form.jinja
msgid "Creation date"
@@ -4282,6 +4442,11 @@ msgstr ""
msgid "returnable product : %(returnable)s -> %(returned)s"
msgstr "produit consigné : %(returnable)s -> %(returned)s"
#: counter/views/admin.py
#, python-format
msgid "%(user)s's AE account has been emptied"
msgstr "Le compte de %(user)s a été vidé"
#: counter/views/cash.py
msgid "10 cents"
msgstr "10 centimes"
@@ -5069,7 +5234,7 @@ msgstr "heures THE"
msgid "hours TE"
msgstr "heures TE"
#: pedagogy/models.py
#: pedagogy/models.py timetable/models.py
msgid "ue"
msgstr "UE"
@@ -5109,6 +5274,62 @@ msgstr "signaler"
msgid "reporter"
msgstr "signalant"
#: pedagogy/templates/pedagogy/fragments/comment_report.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
msgid "Report"
msgstr "Signaler"
#: pedagogy/templates/pedagogy/fragments/ue_comment_form.jinja
msgid "Leave comment"
msgstr "Laisser un commentaire"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: trombi/templates/trombi/export.jinja
msgid "Comments"
msgstr "Commentaires"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
msgid "This comment has been reported"
msgstr "Ce commentaire a été signalé"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
msgid "It will be hidden until moderated."
msgstr "Il sera caché tant qu'il ne sera pas modéré."
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/grade.jinja
msgid "Global grade"
msgstr "Note globale"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/grade.jinja
msgid "Utility"
msgstr "Utilité"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/grade.jinja
msgid "Interest"
msgstr "Intérêt"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/grade.jinja
msgid "Teaching"
msgstr "Enseignement"
#: pedagogy/templates/pedagogy/fragments/ue_detail/comments.jinja
#: pedagogy/templates/pedagogy/fragments/ue_detail/grade.jinja
msgid "Workload"
msgstr "Charge de travail"
#: pedagogy/templates/pedagogy/fragments/ue_detail/ue_detail.jinja
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid ""
"You already posted a comment on this UE. If you want to comment again, "
"please modify or delete your previous comment."
msgstr ""
"Vous avez déjà commenté cette UE. Si vous voulez de nouveau commenter, "
"veuillez modifier ou supprimer votre commentaire précédent."
#: pedagogy/templates/pedagogy/guide.jinja
msgid "A guide of courses available at UTBM."
msgstr "Un guide de tous les cours disponibles à l'UTBM."
@@ -5117,6 +5338,10 @@ msgstr "Un guide de tous les cours disponibles à l'UTBM."
msgid "Search UE"
msgstr "Recherche d'UE"
#: pedagogy/templates/pedagogy/guide.jinja
msgid "Hide closed UEs"
msgstr "Cacher les UEs fermées"
#: pedagogy/templates/pedagogy/guide.jinja
#, python-format
msgid "%(display_name)s"
@@ -5170,44 +5395,36 @@ msgid "UE Details"
msgstr "Détails d'UE"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "CM: "
msgstr "CM : "
msgid "Category"
msgstr "Catégorie"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "TD: "
msgstr "TD : "
msgid "Credits"
msgstr "Crédits"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "TP: "
msgstr "TP : "
msgid "Lectures"
msgstr "Cours magistraux"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "TE: "
msgstr "TE : "
msgid "Tutorials"
msgstr "Travaux dirigés"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "THE: "
msgstr "THE : "
msgid "Practicals"
msgstr "Travaux pratiques"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Global grade"
msgstr "Note globale"
msgid "Work without supervision"
msgstr "Travail hors encadrement"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Utility"
msgstr "Utilité"
msgid "Availability"
msgstr "Disponibilité"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Interest"
msgstr "Intérêt"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Teaching"
msgstr "Enseignement"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Work load"
msgstr "Charge de travail"
msgid "Manager"
msgstr "Responsable"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Objectives"
@@ -5225,35 +5442,6 @@ msgstr "Compétences acquises"
msgid "Key concepts"
msgstr "Concepts clefs"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "UE manager: "
msgstr "Gestionnaire d'UE : "
#: pedagogy/templates/pedagogy/ue_detail.jinja pedagogy/tests/tests.py
msgid ""
"You already posted a comment on this UE. If you want to comment again, "
"please modify or delete your previous comment."
msgstr ""
"Vous avez déjà commenté cette UE. Si vous voulez de nouveau commenter, "
"veuillez modifier ou supprimer votre commentaire précédent."
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Leave comment"
msgstr "Laisser un commentaire"
#: pedagogy/templates/pedagogy/ue_detail.jinja
#: trombi/templates/trombi/export.jinja
msgid "Comments"
msgstr "Commentaires"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "This comment has been reported"
msgstr "Ce commentaire a été signalé"
#: pedagogy/templates/pedagogy/ue_detail.jinja
msgid "Report this comment"
msgstr "Signaler ce commentaire"
#: pedagogy/templates/pedagogy/ue_edit.jinja
msgid "Edit UE"
msgstr "Éditer l'UE"
@@ -5833,12 +6021,8 @@ msgid "Create another subscription"
msgstr "Créer une nouvelle cotisation"
#: subscription/templates/subscription/stats.jinja
msgid "Total subscriptions"
msgstr "Cotisations totales"
#: subscription/templates/subscription/stats.jinja
msgid "Subscriptions by type"
msgstr "Cotisations par type"
msgid "All subscriptions"
msgstr "Toutes les cotisations"
#: subscription/templates/subscription/subscription.jinja
msgid "Existing member"
@@ -5848,6 +6032,46 @@ msgstr "Membre existant"
msgid "the groups that can create subscriptions"
msgstr "les groupes pouvant créer des cotisations"
#: timetable/models.py
msgid "timetable"
msgstr "emploi du temps"
#: timetable/models.py
msgid "timetables"
msgstr "emplois du temps"
#: timetable/models.py
msgid "weekday"
msgstr "jour de la semaine"
#: timetable/models.py
msgid "start at"
msgstr "début"
#: timetable/models.py
msgid "end at"
msgstr "fin"
#: timetable/models.py
msgid "course type"
msgstr "type de cours"
#: timetable/models.py
msgid "room"
msgstr "salle"
#: timetable/models.py
msgid "week group"
msgstr "groupe de semaine"
#: timetable/models.py
msgid "timetable slot"
msgstr "créneau d'emploi du temps"
#: timetable/models.py
msgid "timetable slots"
msgstr "créneaux d'emploi du temps"
#: timetable/templates/timetable/generator.jinja
msgid "Timetable generator"
msgstr "Générateur d'emploi du temps"
@@ -5878,8 +6102,44 @@ msgid "Generate"
msgstr "Générer"
#: timetable/templates/timetable/generator.jinja
msgid "Save to PNG"
msgstr "Sauver en PNG"
msgid "Save on your profile"
msgstr "Enregistrer sur votre profil"
#: timetable/templates/timetable/generator.jinja
msgid "Make this timetable public"
msgstr "Rendre cet emploi du temps publique"
#: timetable/templates/timetable/generator.jinja
#, python-format
msgid ""
"You can change this at any time in <a href=\"%(url)s\">your preferences</a>"
msgstr ""
"Vous pouvez changer ceci n'importe quand dans <a href=\"%(url)s\">vos préférences</a>"
#: timetable/templates/timetable/generator.jinja
msgid "Save timetable"
msgstr "Enregistrer l'emploi du temps"
#: timetable/templates/timetable/generator.jinja
#: trombi/templates/trombi/detail.jinja
msgid "Export"
msgstr "Export"
#: timetable/templates/timetable/generator.jinja
msgid "Export to PNG"
msgstr "Exporter en PNG"
#: timetable/views.py
msgid "Timetables"
msgstr "Emplois du temps"
#: timetable/views.py
msgid "Generator"
msgstr "Générateur"
#: timetable/views.py
msgid "My timetables"
msgstr "Mes emplois du temps"
#: trombi/models.py
msgid "subscription deadline"
@@ -5994,10 +6254,6 @@ msgstr "Fin des inscriptions : "
msgid "Comment deadline: "
msgstr "Fin des commentaires : "
#: trombi/templates/trombi/detail.jinja
msgid "Export"
msgstr "Exporter"
#: trombi/templates/trombi/detail.jinja
msgid "Add user"
msgstr "Ajouter une personne"
+3
View File
@@ -71,6 +71,7 @@ nav:
- API:
- Développement: tutorial/api/dev.md
- Connexion à l'API: tutorial/api/connect.md
- Liaison avec le compte AE: tutorial/api/account-link.md
- Markdown AE: tutorial/markdown.md
- Etransactions: tutorial/etransaction.md
- How-to:
@@ -95,6 +96,8 @@ nav:
- reference/api/hashers.md
- reference/api/models.md
- reference/api/perms.md
- reference/api/schemas.md
- reference/api/views.md
- club:
- reference/club/models.md
- reference/club/views.md
+385 -355
View File
File diff suppressed because it is too large. Load diff
+14 -14
View File
@@ -24,24 +24,24 @@
"#com:*": "./com/static/bundled/*"
},
"devDependencies": {
"@babel/core": "^8.0.1",
"@babel/preset-env": "^8.0.2",
"@biomejs/biome": "^2.5.1",
"@babel/core": "^8.0.6",
"@babel/preset-env": "^8.0.6",
"@biomejs/biome": "^2.5.15",
"@hey-api/openapi-ts": "^0.99.0",
"@types/alpinejs": "^3.13.11",
"@types/alpinejs": "^3.17.0",
"@types/alpinejs__sort": "^3.13.0",
"@types/cytoscape-cxtmenu": "^3.4.5",
"@types/cytoscape-klay": "^3.1.5",
"@types/js-cookie": "^3.0.6",
"@types/node": "^26.2.0",
"@types/node": "^26.6.4",
"@typescript/native": "npm:typescript@^7.0.2",
"rollup-plugin-visualizer": "^7.1.1",
"typescript": "npm:@typescript/typescript6@^6.0.2",
"vite": "^8.2.2"
"vite": "^8.3.2"
},
"dependencies": {
"@ae_utbm/aemark": "^0.1.3",
"@alpinejs/sort": "^3.16.2",
"@alpinejs/sort": "^3.17.4",
"@arendjr/text-clipper": "npm:@jsr/arendjr__text-clipper@^3.0.0",
"@floating-ui/dom": "^1.8.0",
"@fortawesome/fontawesome-free": "^7.3.1",
@@ -49,13 +49,13 @@
"@fullcalendar/daygrid": "^6.1.21",
"@fullcalendar/icalendar": "^6.1.21",
"@fullcalendar/list": "^6.1.21",
"@sentry/browser": "^10.70.0",
"@zip.js/zip.js": "^2.8.57",
"3d-force-graph": "^1.80.0",
"alpinejs": "^3.16.2",
"@sentry/browser": "^11.3.0",
"@zip.js/zip.js": "^2.22.0",
"3d-force-graph": "^1.80.1",
"alpinejs": "^3.17.4",
"chart.js": "^4.5.1",
"country-flag-emoji-polyfill": "^0.1.10",
"cytoscape": "^3.34.1",
"cytoscape": "^3.34.3",
"cytoscape-cxtmenu": "^3.5.0",
"cytoscape-klay": "^3.1.4",
"d3-force-3d": "^3.0.6",
@@ -66,8 +66,8 @@
"js-cookie": "^3.0.8",
"lit-html": "^3.3.3",
"native-file-system-adapter": "^3.0.1",
"temporal-polyfill": "^1.0.4",
"three": "^0.185.1",
"temporal-polyfill": "^1.0.5",
"three": "^0.186.1",
"three-spritetext": "^1.10.0",
"tom-select": "^2.6.2"
}
+110 -346
View File
@@ -1,52 +1,22 @@
@import "core/static/core/devices";
@import "core/static/core/colors";
$pedagogy-blue: #1bb9ea;
$pedagogy-orange: #ea7900;
$pedagogy-hover-blue: #0e97ce;
$pedagogy-light-blue: #caf0ff;
$pedagogy-white-text: #f0f0f0;
.pedagogy {
&.star-not-checked {
color: #f7f7f7;
.star-not-checked {
color: lightgray;
margin-bottom: 0;
margin-top: 0;
}
&.star-checked {
.star-checked {
color: $pedagogy-orange;
margin-bottom: 0;
margin-top: 0;
}
&.grade-without-star {
display: none;
}
@media screen and (max-width: $large-devices) {
&.star-not-checked {
margin-left: 5px;
margin-right: 5px;
}
&.star-checked {
margin-left: 5px;
margin-right: 5px;
}
}
@media screen and (max-width: $small-devices) {
&.grade-without-star {
display: block;
}
&.grade-with-star {
display: none;
}
}
#ue-list {
font-size: 1.1em;
@@ -64,12 +34,10 @@ $pedagogy-white-text: #f0f0f0;
}
#search_form {
.radio-guide fieldset {
input[type="checkbox"] {
display: none;
}
margin-top: 10px;
margin-bottom: 0;
color: white;
@@ -85,80 +53,79 @@ $pedagogy-white-text: #f0f0f0;
}
}
#ue_detail {
color: #062f38;
.ue-quick-info-container {
&#ue_detail {
.ue-infos {
display: flex;
gap: 2em;
flex-direction: row;
@media screen and (max-width: 700px) {
flex-direction: column;
}
}
.infos-column {
display: flex;
flex-direction: column;
gap: 1em;
min-width: 300px;
}
.info-container {
// Darken the background color just enough to make this part
// stand out a little, while not being too perceptible
background: darken($white-color, 1%);
display: grid;
grid-template-columns: 20% 20% 20% 20% auto;
grid-template-rows: auto auto;
grid-template-areas:
"hours-cm hours-td hours-tp hours-te hours-the"
"department credit-type semester . .";
grid-template-columns: 1fr 1fr;
border-radius: 5px;
padding: .75rem 1rem ;
grid-gap: .5rem;
@include shadow;
.info-container-item {
display: grid;
grid-column: span 2;
grid-template-rows: subgrid;
grid-template-columns: subgrid;
grid-column-gap: 1rem;
div {
display: flex;
align-items: center;
}
.department {
grid-area: department;
:first-child {
justify-content: right;
text-align: right;
}
}
.credit-type {
grid-area: credit-type;
}
.semester {
grid-area: semester;
}
.hours-cm {
grid-area: hours-cm;
}
.hours-td {
grid-area: hours-td;
}
.hours-tp {
grid-area: hours-tp;
}
.hours-te {
grid-area: hours-te;
}
.hours-the {
grid-area: hours-the;
}
.leave-comment-not-allowed {
p {
text-align: center;
color: red;
hr {
grid-column: span 2;
width: 50%;
margin: auto;
}
}
.leave-comment {
.leave-comment-grid-container {
display: grid;
grid-template-columns: 270px auto;
grid-template-rows: 100%;
grid-template-areas: "stars comment";
.comment-form-content {
display: flex;
gap: 2em;
@media screen and (max-width: $large-devices) {
grid-template-columns: 100%;
grid-template-rows: auto auto;
grid-template-areas:
"stars"
"comment";
gap: 1em;
flex-direction: column;
}
}
.form-stars {
grid-area: stars;
flex: 0;
min-width: 250px;
display: flex;
align-content: flex-start;
justify-content: center;
flex-wrap: wrap;
gap: 1rem 2em;
height: unset;
}
.form-comment {
grid-area: comment;
flex: 2;
}
.ui-accordion-header-icon {
@@ -166,45 +133,18 @@ $pedagogy-white-text: #f0f0f0;
margin-right: 10px;
}
.input-stars {
margin-top: 20px;
}
input[type="submit"] {
display: block;
margin-left: auto;
}
.ue-details-container {
display: grid;
grid-template-columns: 150px 130px auto;
grid-template-rows: 156px 1fr;
grid-template-areas:
"grade grade-stars ue-infos"
". . ue-infos";
@media screen and (max-width: $large-devices) {
grid-template-columns: 50% 50%;
grid-template-rows: auto auto;
grid-template-areas:
"grade grade-stars"
"ue-infos ue-infos";
}
}
.grade {
grid-area: grade;
summary {
background: $pedagogy-orange;
color: $pedagogy-white-text;
background-color: $pedagogy-blue;
padding-right: 10px;
>p {
text-align: right;
font-weight: bold;
@media screen and (min-width: $large-devices) {
clip-path: polygon(0 0%, 0 100%, 30% 100%, 33% 0);
}
}
.grade-stars {
grid-area: grade-stars;
color: $pedagogy-white-text;
background-color: $pedagogy-blue;
font-weight: bold;
}
.ue-infos {
@@ -212,237 +152,61 @@ $pedagogy-white-text: #f0f0f0;
padding-left: 10px;
}
.comment-container {
display: grid;
grid-template-columns: 300px auto;
grid-template-rows: auto auto auto;
grid-template-areas:
"grade-block comment"
"grade-block info"
"comment-end-bar comment-end-bar";
margin-bottom: 30px;
margin-top: 10px;
@media screen and (max-width: $large-devices) {
grid-template-columns: auto;
grid-template-rows: auto auto auto auto;
grid-template-areas:
"grade-block"
"comment"
"info"
"comment-end-bar";
}
.grade-block {
grid-area: grade-block;
width: 300px;
display: grid;
grid-template-columns: 150px 150px;
grid-template-rows: 156px auto;
grid-template-areas:
"grade-type grade-stars"
"grade-extension grade-extension";
grid-gap: 15px;
clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 30px, 270px 0);
align-items: start;
background-color: $pedagogy-blue;
@media screen and (max-width: $large-devices) {
grid-template-columns: 50% auto;
grid-template-rows: auto;
grid-template-areas: "grade-type grade-stars";
width: auto;
clip-path: none;
align-content: space-evenly;
align-items: end;
}
.grade-extension {
grid-area: grade-extension;
background-color: $pedagogy-blue;
}
.grade-type {
grid-area: grade-type;
>p {
color: $pedagogy-white-text;
font-weight: bold;
text-align: right;
}
}
.grade-stars {
grid-area: grade-stars;
}
}
.comment {
grid-area: comment;
padding: 15px;
margin: 20px;
display: flex;
flex-direction: column;
gap: 10px;
background: $primary-neutral-light-color;
border-radius: 5px;
border: 1px darken($secondary-neutral-light-color, 10%) solid;
display: grid;
grid-template-columns: auto;
grid-template-rows: auto auto;
grid-template-areas:
"anchor"
"markdown";
@media screen and (max-width: $large-devices) {
border-left: solid;
border-right: solid;
border-color: $pedagogy-blue;
&.reported {
border: #fc8181 1px solid;
}
.anchor {
grid-area: anchor;
text-align: right;
margin-right: 15px;
.comment-header {
display: flex;
gap: 20px;
img {
width: 50px;
height: 50px;
border-radius: 50%;
}
.markdown {
grid-area: markdown;
.comment-metadata {
display: flex;
flex-direction: column;
justify-content: center;
}
min-height: 139px;
margin-top: 0;
margin-right: 0;
padding: 10px;
.comment-options {
flex: 2;
display: flex;
justify-content: right;
gap: 15px;
}
}
.comment-stars {
display: flex;
justify-content: space-evenly;
flex-wrap: wrap;
gap: 1em 2em;
padding: 1.5em;
border-top: 0.0625rem grey dotted;
border-bottom: 0.0625rem grey dotted;
}
.comment-content {
text-align: justify;
overflow: auto;
}
}
.info {
grid-area: info;
padding-bottom: 10px;
@media screen and (max-width: $large-devices) {
border-left: solid;
border-right: solid;
border-color: $pedagogy-blue;
}
.status-reported {
color: red;
float: left;
padding-left: 10px;
}
.action {
float: right;
margin-top: 0;
}
}
.comment-end-bar {
grid-area: comment-end-bar;
display: grid;
grid-template-columns: 33% auto auto;
grid-template-rows: 2.5em;
grid-template-areas: "author date report";
background-color: $pedagogy-blue;
margin-top: -1px;
@media screen and (max-width: $large-devices) {
grid-template-columns: auto;
grid-template-rows: auto auto auto;
grid-template-areas:
"report"
"date"
"author";
margin-top: 0;
text-align: center;
}
.author {
grid-area: author;
padding-top: 6px;
padding-left: 20px;
background-color: $pedagogy-orange;
clip-path: polygon(0 10px, 0 100%, 350px 200%, 300px 10px);
@media screen and (max-width: $large-devices) {
clip-path: none;
padding: 0;
padding-bottom: 7px;
}
a {
color: $pedagogy-white-text;
font-weight: bold;
}
a:hover {
color: $pedagogy-hover-blue;
}
}
.date {
grid-area: date;
color: $pedagogy-white-text;
@media screen and (max-width: $large-devices) {
padding-bottom: 7px;
}
}
.report {
grid-area: report;
justify-self: right;
padding-right: 30px;
padding-left: 30px;
a {
color: $pedagogy-white-text;
cursor: pointer;
}
a:hover {
color: $pedagogy-hover-blue;
}
@media screen and (max-width: $large-devices) {
text-align: center;
justify-self: inherit;
padding-bottom: 7px;
background-color: $white-color;
border-left: solid;
border-right: solid;
border-color: $pedagogy-blue;
a {
color: $black-color;
padding: .5em 20px 1em;
}
}
}
}
}
}
}
details.accordion summary {
background: $pedagogy-orange !important;
color: $pedagogy-white-text !important;
clip-path: polygon(0 0%, 0 100%, 30% 100%, 33% 0);
@media screen and (max-width: $large-devices) {
clip-path: none;
}
}
details.accordion>.accordion-content {
background-color: $white-color;
border-color: $pedagogy-orange;
border-right: none;
}
.buttons {
display: flex;
@@ -11,44 +11,39 @@
hx-disabled-elt="find input[type='submit']"
>
{% csrf_token %}
<div class="leave-comment-grid-container">
<div class="form-stars">
{{ form.non_field_errors() }}
{{ form.author.errors }}
{{ form.ue.errors }}
{{ form.author }}
{{ form.ue }}
<div class="input-stars">
<label for="{{ form.grade_global.id_for_label }}">{{ form.grade_global.label }} :</label>
<div class="comment-form-content">
<div class="form-stars">
<fieldset>
<legend>{{ form.grade_global.label }} :</legend>
{{ form.grade_global.errors }}
{{ form.grade_global }}
</div>
<div class="input-stars">
<label for="{{ form.grade_utility.id_for_label }}">{{ form.grade_utility.label }} :</label>
</fieldset>
<fieldset>
<legend>{{ form.grade_utility.label }} :</legend>
{{ form.grade_utility.errors }}
{{ form.grade_utility }}
</div>
<div class="input-stars">
<label for="{{ form.grade_interest.id_for_label }}">{{ form.grade_interest.label }} :</label>
</fieldset>
<fieldset>
<legend>{{ form.grade_interest.label }} :</legend>
{{ form.grade_interest.errors }}
{{ form.grade_interest }}
</div>
<div class="input-stars">
<label for="{{ form.grade_teaching.id_for_label }}">{{ form.grade_teaching.label }} :</label>
</fieldset>
<fieldset>
<legend>{{ form.grade_teaching.label }} :</legend>
{{ form.grade_teaching.errors }}
{{ form.grade_teaching }}
</div>
<div class="input-stars">
<label for="{{ form.grade_work_load.id_for_label }}">{{ form.grade_work_load.label }} :</label>
</fieldset>
<fieldset>
<legend>{{ form.grade_work_load.label }} :</legend>
{{ form.grade_work_load.errors }}
{{ form.grade_work_load }}
</div>
</fieldset>
</div>
<div class="form-comment">
<label for="{{ form.comment.id_for_label }}">{{ form.comment.label }} :</label>
@@ -56,9 +51,7 @@
{{ form.comment }}
</div>
</div>
<div class="buttons">
<input type="submit" value="{% trans %}Comment{% endtrans %}" />
</div>
<p><input type="submit" class="btn btn-blue"/></p>
</form>
{% if form.is_creation %}
@@ -0,0 +1,129 @@
{% from "pedagogy/macros.jinja" import display_star %}
{% from "core/macros.jinja" import user_profile_link %}
{% if comments %}
<h2>{% trans %}Comments{% endtrans %}</h2>
<br>
{% endif %}
<section>
{%- for comment in comments -%}
<article
id="comment-{{ comment.id }}"
class="comment {% if comment.is_reported %}reported{% endif %}"
>
{% if comment.is_reported %}
<div class="alert alert-red">
<div class="alert-main">
<h5 class="alert-title margin-bottom">
{% trans %}This comment has been reported{% endtrans %}
</h5>
<p>{% trans %}It will be hidden until moderated.{% endtrans %}</p>
{% if user.has_perm("pedagogy.view_uecommentreport") %}
{% for report in comment.reports.all() %}
<div class="markdown margin-bottom">
<blockquote>
<em>{{ report.reporter.get_display_name() }}</em>
{{ report.reason|markdown }}
</blockquote>
</div>
{% endfor %}
{% endif %}
</div>
{% if comment.author_id == user.id or user.has_perm("pedagogy.delete_uecomment") %}
<div class="alert-aside">
<a
href="{{ url("pedagogy:comment_delete", comment_id=comment.id) }}"
class="btn btn-red"
>
<i class="fa fa-trash"></i>{% trans %}Delete{% endtrans %}
</a>
<a href="{{ url("pedagogy:moderation") }}" class="btn btn-green">
<i class="fa fa-check"></i>{% trans %}Moderate{% endtrans %}
</a>
</div>
{% endif %}
</div>
{% endif %}
<div class="comment-header">
<img
{% if comment.author.avatar_pict %}
src="{{ comment.author.avatar_pict.get_download_url() }}"
{% elif comment.author.profile_pict %}
src="{{ comment.author.profile_pict.get_download_url() }}"
{% else %}
src="{{ static("core/img/unknown.jpg") }}"
{% endif %}
alt="{% trans %}Profile{% endtrans %}"
/>
<div class="comment-metadata">
<a href="{{ comment.author.get_absolute_url() }}">
<strong>{{ comment.author.get_display_name() }}</strong>
</a>
<time datetime="{{ comment.publish_date.isoformat(timespec="seconds") }}">
{{ comment.publish_date|localtime|date(DATETIME_FORMAT) }}
{{ comment.publish_date|localtime|time(DATETIME_FORMAT) }}
</time>
</div>
<div class="comment-options">
{% if comment.author_id == user.id or user.has_perm("pedagogy.change_uecomment") %}
<a
class="clickable"
hx-get="{{ url('pedagogy:comment_update', comment_id=comment.id) }}"
hx-swap="outerHTML"
hx-target="#comment-{{ comment.id }}"
tooltip="{% trans %}Edit{% endtrans %}"
>
<i class="fa fa-pencil edit-action"></i>
</a>
{% endif %}
{% if not comment.is_reported %}
<a
class="clickable"
hx-get="{{ url('pedagogy:comment_report', comment_id=comment.id) }}"
hx-swap="outerHTML"
hx-target="#comment-{{ comment.id }}"
tooltip="{% trans %}Report{% endtrans %}"
>
<i class="fa fa-exclamation delete-action"></i>
</a>
{% if comment.author_id == user.id or user.has_perm("pedagogy.delete_uecomment") %}
<a
href="{{ url("pedagogy:comment_delete", comment_id=comment.id) }}"
tooltip="{% trans %}Delete{% endtrans %}"
>
<i class="fa fa-trash-can delete-action"></i>
</a>
{% endif %}
{% endif %}
</div>
</div>
<div class="comment-stars">
<div>
<span>{% trans %}Global grade{% endtrans %}</span>
<span>{{ display_star(comment.grade_global) }}</span>
</div>
<div>
<span>{% trans %}Utility{% endtrans %}</span>
<span>{{ display_star(comment.grade_utility) }}</span>
</div>
<div>
<span>{% trans %}Interest{% endtrans %}</span>
<span>{{ display_star(comment.grade_interest) }}</span>
</div>
<div>
<span>{% trans %}Teaching{% endtrans %}</span>
<span>{{ display_star(comment.grade_teaching) }}</span>
</div>
<div>
<span>{% trans %}Workload{% endtrans %}</span>
<span>{{ display_star(comment.grade_work_load) }}</span>
</div>
</div>
<div class="comment-content">
{{ comment.comment|markdown }}
</div>
</article>
{%- endfor -%}
</section>
@@ -0,0 +1,20 @@
<div class="info-container-item">
<span>{% trans %}Global grade{% endtrans %}</span>
<span>{{ display_star(object.grade_global_average) }}</span>
</div>
<div class="info-container-item">
<span>{% trans %}Utility{% endtrans %}</span>
<span>{{ display_star(object.grade_utility_average) }}</span>
</div>
<div class="info-container-item">
<span>{% trans %}Interest{% endtrans %}</span>
<span>{{ display_star(object.grade_interest_average) }}</span>
</div>
<div class="info-container-item">
<span>{% trans %}Teaching{% endtrans %}</span>
<span>{{ display_star(object.grade_teaching_average) }}</span>
</div>
<div class="info-container-item">
<span>{% trans %}Workload{% endtrans %}</span>
<span>{{ display_star(object.grade_work_load_average) }}</span>
</div>
@@ -0,0 +1,25 @@
{# A few hx-partials for swapping a few parts of the main ue_detail.jinja #}
{% from "pedagogy/macros.jinja" import display_star %}
<hx-partial id="ue-grade">
{% include "pedagogy/fragments/ue_detail/grade.jinja" %}
</hx-partial>
<hx-partial id="comment-form">
{% if object.has_user_already_commented(user) %}
<em>
{% trans trimmed %}
You already posted a comment on this UE.
If you want to comment again, please modify or delete your previous comment.
{% endtrans %}
</em>
<br>
{% elif user.has_perm("pedagogy.add_uecomment") %}
{{ add_comment_form }}
{% endif %}
</hx-partial>
<hx-partial id="comments" hx-swap="innerMorph">
{% include "pedagogy/fragments/ue_detail/comments.jinja" %}
</hx-partial>
@@ -1,91 +0,0 @@
{% from "pedagogy/macros.jinja" import display_star %}
{% from "core/macros.jinja" import user_profile_link %}
{% if comments %}
<h2>{% trans %}Comments{% endtrans %}</h2>
<br>
{% endif %}
<section>
{% for comment in comments %}
<div id="comment-{{ comment.id }}" class="comment-container">
<div class="grade-block">
<div class="grade-type">
<p>{% trans %}Global grade{% endtrans %}</p>
<p>{% trans %}Utility{% endtrans %}</p>
<p>{% trans %}Interest{% endtrans %}</p>
<p>{% trans %}Teaching{% endtrans %}</p>
<p>{% trans %}Work load{% endtrans %}</p>
</div>
<div class="grade-stars">
<p>{{ display_star(comment.grade_global) }}</p>
<p>{{ display_star(comment.grade_utility) }}</p>
<p>{{ display_star(comment.grade_interest) }}</p>
<p>{{ display_star(comment.grade_teaching) }}</p>
<p>{{ display_star(comment.grade_work_load) }}</p>
</div>
<div class="grade-extension"></div>
</div>
<div class="comment">
<div class="anchor">
<a href="{{ url('pedagogy:ue_detail', ue_id=ue.id) }}#comment-{{ comment.id }}"><i class="fa fa-paragraph"></i></a>
</div>
{{ comment.comment|markdown }}
</div>
<div class="info">
{% if comment.is_reported %}
<p class="status-reported">
{% trans %}This comment has been reported{% endtrans %}
</p>
{% endif %}
{% if comment.author_id == user.id or user.has_perm("pedagogy.change_comment") %}
<button
class="btn btn-orange action"
hx-get="{{ url('pedagogy:comment_update', comment_id=comment.id) }}"
hx-swap="outerHTML"
hx-target="#comment-{{ comment.id }}"
>
<i class="fa fa-pencil"></i> {% trans %}Edit{% endtrans %}
</button>
{% endif %}
{% if comment.author_id == user.id or user.has_perm("pedagogy.delete_comment") %}
<form class="action"
hx-post="{{ url('pedagogy:comment_delete', comment_id=comment.id) }}"
hx-confirm='{% trans obj=object %}Are you sure you want to delete "{{ obj }}"?{% endtrans %}'
hx-swap="outerHTML"
hx-target="#comment-{{ comment.id }}"
>
{% csrf_token %}
<button class="btn btn-red action">
<i class="fa fa-trash-can"></i> {% trans %}Delete{% endtrans %}
</button>
</form>
{% endif %}
</div>
<div class="comment-end-bar">
<div class="report">
<p>
<a
hx-get="{{ url('pedagogy:comment_report', comment_id=comment.id) }}"
hx-swap="outerHTML"
hx-target="#comment-{{ comment.id }}"
>
{% trans %}Report this comment{% endtrans %}
</a>
</p>
</div>
<div class="date"><p>{{ comment.publish_date.strftime('%d/%m/%Y') }}</p></div>
<div class="author"><p>{{ user_profile_link(comment.author) }}</p></div>
</div>
</div>
{% endfor %}
</section>
@@ -1,10 +0,0 @@
{% if object.has_user_already_commented(user) %}
<div class="leave-comment-not-allowed">
<p>{% trans %}You already posted a comment on this UE. If you want to comment again, please modify or delete your previous comment.{% endtrans %}</p>
</div>
<br>
{% endif %}
{% if not object.has_user_already_commented(user) and user.has_perm("pedagogy.add_uecomment") %}
{{ add_comment_form }}
{% endif %}
@@ -1,27 +0,0 @@
<div class="ue-details-container">
<div class="grade">
<p>{% trans %}Global grade{% endtrans %}</p>
<p>{% trans %}Utility{% endtrans %}</p>
<p>{% trans %}Interest{% endtrans %}</p>
<p>{% trans %}Teaching{% endtrans %}</p>
<p>{% trans %}Work load{% endtrans %}</p>
</div>
<div class="grade-stars">
<p>{{ display_star(object.grade_global_average) }}</p>
<p>{{ display_star(object.grade_utility_average) }}</p>
<p>{{ display_star(object.grade_interest_average) }}</p>
<p>{{ display_star(object.grade_teaching_average) }}</p>
<p>{{ display_star(object.grade_work_load_average) }}</p>
</div>
<div class="ue-infos">
<p><b>{% trans %}Objectives{% endtrans %}</b></p>
<p>{{ object.objectives|markdown }}</p>
<p><b>{% trans %}Program{% endtrans %}</b></p>
<p>{{ object.program|markdown }}</p>
<p><b>{% trans %}Earned skills{% endtrans %}</b></p>
<p>{{ object.skills|markdown }}</p>
<p><b>{% trans %}Key concepts{% endtrans %}</b></p>
<p>{{ object.key_concepts|markdown }}</p>
<p><b>{% trans %}UE manager: {% endtrans %}</b>{{ object.manager }}</p>
</div>
</div>
-3
View File
@@ -1,5 +1,4 @@
{% macro display_star(grade) -%}
{% if grade >= 0 %}
{% for i in range(5) %}
{% if i <= grade %}
@@ -8,9 +7,7 @@
<span class="fa-solid fa-star pedagogy star-not-checked grade-with-star"></span>
{% endif %}
{% endfor %}
<span class="pedagogy grade-without-star">{{ grade }}/5</span>
{% else %}
<span class="grade-text"> {% trans %} not rated {% endtrans %} </span>
{% endif %}
{%- endmacro %}
+60 -59
View File
@@ -1,21 +1,6 @@
{% extends "core/base.jinja" %}
{% from "pedagogy/macros.jinja" import display_star %}
{% if is_fragment %}
<hx-partial id="ue-grade">
{% include "pedagogy/fragments/ue_details/grade.jinja" %}
</hx-partial>
<hx-partial id="comment-form">
{% include "pedagogy/fragments/ue_details/form.jinja" %}
</hx-partial>
<hx-partial id="comments" hx-swap="innerMorph">
{% include "pedagogy/fragments/ue_details/comments.jinja" %}
</hx-partial>
{% else %}
{% extends "core/base.jinja" %}
{% block additional_css %}
<link rel="stylesheet" href="{{ static('pedagogy/css/pedagogy.scss') }}">
@@ -26,66 +11,82 @@
{% endblock %}
{% block content %}
<div class="pedagogy">
<div id="ue_detail">
<button onclick='(function(){
// If comes from the guide page, go back with history
if (document.referrer.replace(/\?(.+)/gm,"").endsWith(`{{ url("pedagogy:guide") }}`)){
window.history.back();
return;
}
// Simply goes to the guide page
window.location.href = `{{ url("pedagogy:guide") }}`;
})()' hidden>{% trans %}Back{% endtrans %}</button>
<h1>{{ object.code }} - {{ object.title }}</h1>
<br>
<div class="ue-quick-info-container">
<div class="hours-cm">
<b>{% trans %}CM: {% endtrans %}</b>{{ object.hours_CM }}
<h1>{{ object.code }}</h1>
<h2 class="margin-bottom">{{ object.title }}</h2>
<div class="pedagogy" id="ue_detail">
<div class="ue-infos">
<div class="infos-column">
<aside class="info-container">
<div class="info-container-item">
<div>{% trans %}Category{% endtrans %}</div>
<div>{{ object.credit_type }}</div>
</div>
<div class="hours-td">
<b>{% trans %}TD: {% endtrans %}</b>{{ object.hours_TD }}
<div class="info-container-item">
<div>{% trans %}Credits{% endtrans %}</div>
<div>{{ object.credits }}</div>
</div>
<div class="hours-tp">
<b>{% trans %}TP: {% endtrans %}</b>{{ object.hours_TP }}
<hr>
<div class="info-container-item">
<div>{% trans %}Lectures{% endtrans %}</div>
<div>{{ object.hours_CM }}h</div>
</div>
<div class="hours-te">
<b>{% trans %}TE: {% endtrans %}</b>{{ object.hours_TE }}
<div class="info-container-item">
<div>{% trans %}Tutorials{% endtrans %}</div>
<div>{{ object.hours_TD }}h</div>
</div>
<div class="hours-the">
<b>{% trans %}THE: {% endtrans %}</b>{{ object.hours_THE }}
<div class="info-container-item">
<div>{% trans %}Practicals{% endtrans %}</div>
<div>{{ object.hours_TP }}h</div>
</div>
<div class="department">
{{ object.department }}
<div class="info-container-item">
<div>{% trans %}Work without supervision{% endtrans %}</div>
<div>{{ object.hours_THE }}h</div>
</div>
<div class="credit-type">
{{ object.credit_type }}
<hr>
<div class="info-container-item">
<div>{% trans %}Availability{% endtrans %}</div>
<div>{{ object.get_semester_display() }}</div>
</div>
<div class="semester">
{{ object.get_semester_display() }}
<hr>
<div class="info-container-item">
<div>{% trans %}Manager{% endtrans %}</div>
<div>{{ object.manager }}</div>
</div>
</aside>
<aside class="info-container" id="ue-grade">
{% include "pedagogy/fragments/ue_detail/grade.jinja" %}
</aside>
</div>
<br>
<div id="ue-grade">
{% include "pedagogy/fragments/ue_details/grade.jinja" %}
<section class="ue-main-infos">
<h3>{% trans %}Objectives{% endtrans %}</h3>
<p>{{ object.objectives|markdown }}</p>
<h3>{% trans %}Program{% endtrans %}</h3>
<p>{{ object.program|markdown }}</p>
<h3>{% trans %}Earned skills{% endtrans %}</h3>
<p>{{ object.skills|markdown }}</p>
<h3>{% trans %}Key concepts{% endtrans %}</h3>
<p>{{ object.key_concepts|markdown }}</p>
</section>
</div>
<br>
<div id="comment-form">
{% include "pedagogy/fragments/ue_details/form.jinja" %}
{% if object.has_user_already_commented(user) %}
<em>
{% trans trimmed %}
You already posted a comment on this UE.
If you want to comment again, please modify or delete your previous comment.
{% endtrans %}
</em>
<br>
{% elif user.has_perm("pedagogy.add_uecomment") %}
{{ add_comment_form }}
{% endif %}
</div>
<div id="comments">
{% include "pedagogy/fragments/ue_details/comments.jinja" %}
</div>
{% include "pedagogy/fragments/ue_detail/comments.jinja" %}
</div>
</div>
{% endblock %}
{% endif %}
+10 -7
View File
@@ -88,16 +88,19 @@ class UEDetailView(
model = UE
pk_url_kwarg = "ue_id"
template_name = "pedagogy/ue_detail.jinja"
permission_required = "pedagogy.view_ue"
fragments = {
"add_comment_form": UECommentCreateView,
}
fragments = {"add_comment_form": UECommentCreateView}
def get_template_names(self) -> list[str]:
is_fragment = self.request.headers.get("HX-Request", False)
return (
["pedagogy/fragments/ue_detail/ue_detail.jinja"]
if is_fragment
else ["pedagogy/ue_detail.jinja"]
)
def get_fragment_data(self):
return {
"add_comment_form": {"ue_id": self.object.id},
}
return {"add_comment_form": {"ue_id": self.object.id}}
def get_context_data(self, **kwargs):
return super().get_context_data(**kwargs) | {
+14 -14
View File
@@ -20,14 +20,14 @@ license = { text = "GPL-3.0-only" }
requires-python = "<4.0,>=3.14"
dependencies = [
"django>=5.2.17,<6.0.0",
"django-ninja>=1.7.0,<2.0.0",
"django-ninja>=1.7.1,<2.0.0",
"django-ninja-extra>=0.31.7",
"Pillow>=12.3.0,<13.0.0",
"aemark>=0.1.1",
"django-jinja<3.0.0,>=2.11.0",
"cryptography>=50.0.1,<51.0.0",
"cryptography>=50.0.2,<51.0.0",
"django-phonenumber-field>=8.5.0,<9.0.0",
"phonenumbers>=9.0.38,<10.0.0",
"phonenumbers>=9.0.40,<10.0.0",
"reportlab>=5.0.1,<6.0.0",
"django-haystack>=3.4.0,<4.0.0",
"xapian-haystack>=4.0.0,<5.0.0",
@@ -35,21 +35,21 @@ dependencies = [
"django-ordered-model>=3.7.4,<4.0.0",
"django-simple-captcha>=0.7.0,<1.0.0",
"python-dateutil>=2.9.0.post0,<3.0.0",
"sentry-sdk>=2.68.1,<3.0.0",
"sentry-sdk>=2.71.0,<3.0.0",
"jinja2>=3.1.6,<4.0.0",
"django-countries>=9.0.0,<10.0.0",
"django-countries>=9.1.0,<10.0.0",
"dict2xml>=1.7.8,<2.0.0",
"Sphinx>=9.1.0,<10", # Used by xapian during installation
"tomli>=2.4.1,<3.0.0",
"django-honeypot>=1.3.0,<2",
"pydantic-extra-types>=2.11.1,<3.0.0",
"ical>=14.1.1",
"redis[hiredis]>=6.4.0,<9.0.0",
"environs[django]>=15.1.0,<16",
"ical>=14.2.0",
"redis[hiredis]>=8.1.0,<9",
"environs[django]>=15.2.0,<16",
"requests>=2.34.2,<3.0.0",
"honcho>=2.0.0",
"psutil>=7.2.2,<8.0.0",
"celery[redis]>=5.6.2,<7",
"celery[redis]>=5.6.3,<7",
"django-celery-results>=2.6.0",
"django-celery-beat>=2.9.0",
]
@@ -65,10 +65,10 @@ prod = [
dev = [
"django-debug-toolbar>=8.0.0,<9",
"ipython>=9.17.1,<10.0.0",
"pre-commit>=4.6.1,<5.0.0",
"ruff>=0.16.6,<1.0.0",
"pre-commit>=4.6.2,<5.0.0",
"ruff>=0.16.10,<1.0.0",
"djhtml>=3.0.11,<4.0.0",
"faker>=40.38.0,<41.0.0",
"faker>=40.40.0,<41.0.0",
"rjsmin>=1.2.5,<2.0.0",
]
tests = [
@@ -76,7 +76,7 @@ tests = [
"pytest>=9.1.1,<10.0.0",
"pytest-cov>=7.1.0,<8.0.0",
"pytest-django>=4.14.0,<5.0.0",
"model-bakery>=1.24.0,<2.0.0",
"model-bakery>=1.24.1,<2.0.0",
"beautifulsoup4>=4.15.0,<5",
"lxml>=6.1.3,<7",
]
@@ -84,7 +84,7 @@ docs = [
"mkdocs>=1.6.1,<2.0.0",
"mkdocs-material>=9.7.7,<10.0.0",
"mkdocstrings>=1.0.6,<2.0.0",
"mkdocstrings-python>=2.0.7,<3.0.0",
"mkdocstrings-python>=2.0.9,<3.0.0",
"mkdocs-include-markdown-plugin>=7.3.0,<8.0.0",
]
+5 -19
View File
@@ -2,7 +2,6 @@ import type TomSelect from "tom-select";
import type { TomOption } from "tom-select/src/types";
import type { UserAjaxSelect } from "#core:core/components/ajax-select-index";
import { paginated } from "#core:utils/api";
import { History } from "#core:utils/history";
import {
type IdentifiedUserSchema,
type ModerationRequestSchema,
@@ -228,11 +227,6 @@ document.addEventListener("alpine:init", () => {
* Error message when a moderation operation fails
**/
moderationError: "",
/**
* Method of pushing new url to the browser history
* Used by popstate event and always reset to it's default value when used
**/
pushstate: History.Push,
async init() {
this.pictures = (
@@ -267,12 +261,10 @@ document.addEventListener("alpine:init", () => {
if (!event.state || event.state.sasPictureId === undefined) {
return;
}
this.pushstate = History.Replace;
this.currentPicture = this.pictures.find(
(i: PictureSchema) => i.id === Number.parseInt(event.state.sasPictureId, 10),
) as PictureWithIdentifications;
});
this.pushstate = History.Replace; /* Avoid first url push */
await this.updatePicture();
},
@@ -285,17 +277,11 @@ document.addEventListener("alpine:init", () => {
* the list of identified users are updated.
*/
async updatePicture(): Promise<void> {
const updateArgs = {
data: { sasPictureId: this.currentPicture.id },
unused: "",
url: this.currentPicture.sas_url,
};
if (this.pushstate === History.Replace) {
window.history.replaceState(updateArgs.data, updateArgs.unused, updateArgs.url);
this.pushstate = History.Push;
} else {
window.history.pushState(updateArgs.data, updateArgs.unused, updateArgs.url);
}
window.history.replaceState(
{ sasPictureId: this.currentPicture.id },
"",
this.currentPicture.sas_url,
);
this.moderationError = "";
const index: number = this.pictures.indexOf(this.currentPicture);
+3
View File
@@ -372,6 +372,9 @@ SITH_PDF_CLUB_ID = env.int("SITH_PDF_CLUB_ID", default=2)
# Main root for club pages
SITH_CLUB_ROOT_PAGE = "clubs"
SITH_CGU_PAGE = env.str("SITH_CGU_PAGE", default="legals/ri")
# Define the date in the year serving as
# reference for the subscriptions calendar (month, day)
SITH_SEMESTER_START_AUTUMN = (8, 15) # 15 August
+1
View File
@@ -34,6 +34,7 @@ urlpatterns = [
path("", include(("core.urls", "core"), namespace="core")),
path("sitemap.xml", cache_page(86400)(sitemap), {"sitemaps": sitemaps}),
path("api/", api.urls),
path("api-link/", include(("api.urls", "api-link"), namespace="api-link")),
path("rootplace/", include(("rootplace.urls", "rootplace"), namespace="rootplace")),
path(
"subscription/",
+1 -12
View File
@@ -8,22 +8,11 @@ from django.utils.translation import gettext_lazy as _
from core.models import User
from core.utils import get_last_promo
from core.views.forms import SelectDate, SelectDateTime
from core.views.forms import SelectDate
from core.views.widgets.ajax_select import AutoCompleteSelectUser
from subscription.models import Subscription
class SelectionDateForm(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["start_date"] = forms.DateTimeField(
label=_("Start date"), widget=SelectDateTime, required=True
)
self.fields["end_date"] = forms.DateTimeField(
label=_("End date"), widget=SelectDateTime, required=True
)
class SubscriptionForm(forms.ModelForm):
allowed_payment_methods = ["CARD", "CASH", "AE_ACCOUNT"]
@@ -1,6 +1,13 @@
import { BarController, BarElement, CategoryScale, Chart, LinearScale } from "chart.js";
import {
BarController,
BarElement,
CategoryScale,
Chart,
LinearScale,
Tooltip,
} from "chart.js";
Chart.register(BarController, BarElement, CategoryScale, LinearScale);
Chart.register(BarController, BarElement, CategoryScale, LinearScale, Tooltip);
function getRandomColor() {
const letters = "0123456789ABCDEF";
+14 -26
View File
@@ -11,51 +11,39 @@
{% block content %}
<p>
<form>
{{ form.start_date.label }}<br>
{{ form.start_date }}<br><br>
{{ form.end_date.label }}<br>
{{ form.end_date }}<br>
<p><input type="submit" value="{% trans %}Go{% endtrans %}" /></p>
</form>
</p>
<canvas id="statsChart" width="400" height="200"></canvas>
<p>
{% trans %}Total subscriptions{% endtrans %} : {{ subscriptions_total.count() }}<br><br>
{% trans %}Subscriptions by type{% endtrans %}<br><br>
{% for location in locations %}
{{ location[1] }} : <i class="nb">{{ subscriptions_total.filter(location=location[0]).count() }}</i><br>
{% endfor %}
<p>
<br>
<table>
<tr>
<thead>
<th>{% trans %}Subscription type{% endtrans %}</th>
{% for location in locations %}
<th>{{ location[1] }}</th>
{% endfor %}
<th id="graphLabel">{% trans %}Total{% endtrans %}</th>
</thead>
<tr>
<td>{% trans %}All subscriptions{% endtrans %}</td>
{% for location in locations %}
<td><i class="nb">{{ total_location[location[0]] }}</i><br></td>
{% endfor %}
<td><i class="nb">{{ total_location.values()|sum }}</i></td>
</tr>
{% for type in subscriptions_types %}
<tr>
<td><i class="types">{{ subscriptions_types[type]['name'] }}</i></td>
{% set subscriptions_total_type = subscriptions_total.filter(subscription_type=type) %}
{% for location in locations %}
<td>
{% set subscriptions_total_type_location = subscriptions_total_type.filter(location=location[0]) %}
{% trans %}Total{% endtrans %} : {{ subscriptions_total_type_location.count()}}<br>
{% for p_type in payment_types %}
{{ p_type[1] }} : <i class="nb">{{ subscriptions_total_type_location.filter(payment_method=p_type[0]).count()}}</i><br>
{% set subtotal = subscriptions[type][location[0]][p_type[0]] %}
{% if subtotal > 0 %}
{{ p_type[1] }} : <i class="nb">{{ subtotal }}</i><br>
{% endif %}
{% endfor %}
</td>
{% endfor %}
<td class="total"><i class="nb">{{subscriptions_total_type.count()}}</i>
<td class="total"><i class="nb">{{ total_type[type] }}</i></td>
</tr>
{% endfor %}
</table>
{% endblock %}
+26 -22
View File
@@ -12,21 +12,21 @@
# OR WITHIN THE LOCAL FILE "LICENSE"
#
#
from collections import defaultdict
from django.conf import settings
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import PermissionDenied
from django.urls import reverse, reverse_lazy
from django.db.models import Count
from django.urls import reverse
from django.utils.timezone import localdate
from django.utils.translation import gettext_lazy as _
from django.views.generic import CreateView, DetailView, TemplateView
from django.views.generic.edit import FormView
from core.views import FragmentMixin, UseFragmentsMixin
from core.views.group import PermissionGroupsUpdateView
from subscription.forms import (
SelectionDateForm,
SubscriptionExistingUserForm,
SubscriptionNewUserForm,
)
@@ -93,35 +93,39 @@ class SubscriptionPermissionView(PermissionGroupsUpdateView):
extra_context = {"object_name": _("the groups that can create subscriptions")}
class SubscriptionsStatsView(FormView):
class SubscriptionsStatsView(TemplateView):
template_name = "subscription/stats.jinja"
form_class = SelectionDateForm
success_url = reverse_lazy("subscriptions:stats")
def dispatch(self, request, *arg, **kwargs):
self.start_date = localdate()
self.end_date = self.start_date
if request.user.is_root or request.user.is_board_member:
return super().dispatch(request, *arg, **kwargs)
raise PermissionDenied
def post(self, request, *args, **kwargs):
self.form = self.get_form()
self.start_date = self.form["start_date"]
self.end_date = self.form["end_date"]
return super().post(request, *args, **kwargs)
def get_initial(self):
return {
"start_date": self.start_date.strftime("%Y-%m-%d %H:%M:%S"),
"end_date": self.end_date.strftime("%Y-%m-%d %H:%M:%S"),
}
def get_context_data(self, **kwargs):
kwargs = super().get_context_data(**kwargs)
kwargs["subscriptions_total"] = Subscription.objects.filter(
subscription_end__gte=self.end_date, subscription_start__lte=self.start_date
today = localdate()
qs = Subscription.objects.filter(
subscription_end__gte=today, subscription_start__lte=today
)
grouped = qs.values("subscription_type", "location", "payment_method").annotate(
count=Count("*")
)
by_location = qs.values("location").annotate(count=Count("*"))
by_type = qs.values("subscription_type").annotate(count=Count("*"))
kwargs["subscriptions"] = defaultdict(
lambda: defaultdict(lambda: defaultdict(int))
)
for sub in grouped:
kwargs["subscriptions"][sub["subscription_type"]][sub["location"]][
sub["payment_method"]
] = sub["count"]
kwargs["total_location"] = defaultdict(
int, {i["location"]: i["count"] for i in by_location}
)
kwargs["total_type"] = defaultdict(
int, {i["subscription_type"]: i["count"] for i in by_type}
)
kwargs["subscriptions_types"] = settings.SITH_SUBSCRIPTIONS
kwargs["payment_types"] = settings.SITH_SUBSCRIPTION_PAYMENT_METHOD
kwargs["locations"] = settings.SITH_SUBSCRIPTION_LOCATIONS
+16
View File
@@ -1 +1,17 @@
# Register your models here.
from django.contrib import admin
from timetable.models import Timetable, TimetableSlot
class TimetableSlotInline(admin.TabularInline):
model = TimetableSlot
@admin.register(Timetable)
class TimetableAdmin(admin.ModelAdmin):
list_display = ("user", "semester")
search_fields = ("user__nick_name", "user__first_name", "user__last_name")
autocomplete_fields = ("user",)
inlines = (TimetableSlotInline,)
list_select_related = ("user",)
+37
View File
@@ -0,0 +1,37 @@
from ninja.security import SessionAuth
from ninja_extra import ControllerBase, api_controller, route
from ninja_extra.exceptions import PermissionDenied
from core.utils import get_semester_code
from timetable.models import Timetable, TimetableSlot
from timetable.schemas import CreateTimetableSchema, TimetableSchema
@api_controller("/edt", urls_namespace="timetable")
class TimetableController(ControllerBase):
@route.put(
"/{int:user_id}",
auth=SessionAuth(),
response={200: TimetableSchema},
url_name="save",
)
def save_timetable(self, user_id: int, data: CreateTimetableSchema):
user = self.context.request.user
if not user.has_perm("pedagogy.add_timetable") and not (
user.has_perm("timetable.add_self_timetable") and user.id == user_id
):
raise PermissionDenied
timetable, created = Timetable.objects.get_or_create(
semester=get_semester_code(), user_id=user_id
)
if not created:
timetable.slots.all().delete()
if user.preferences.show_my_timetable != data.is_viewable:
user.preferences.show_my_timetable = data.is_viewable
user.preferences.save()
slots = TimetableSlot.objects.bulk_create(
[TimetableSlot(timetable=timetable, **s.model_dump()) for s in data.slots]
)
return TimetableSchema(
id=timetable.id, semester=timetable.semester, slots=slots
)
+141
View File
@@ -0,0 +1,141 @@
# Generated by Django 5.2.17 on 2026-10-03 21:43
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import core.utils
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
operations = [
migrations.CreateModel(
name="Timetable",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"semester",
models.CharField(
blank=True,
default=core.utils.get_semester_code,
validators=[
django.core.validators.RegexValidator("(A|P)\\d{2}")
],
verbose_name="semester",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="timetables",
to=settings.AUTH_USER_MODEL,
verbose_name="user",
),
),
],
options={
"verbose_name": "timetable",
"verbose_name_plural": "timetables",
"permissions": [("add_self_timetable", "Can add its own timetable")],
},
),
migrations.CreateModel(
name="TimetableSlot",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"weekday",
models.SmallIntegerField(
choices=[
(1, "Monday"),
(2, "Tuesday"),
(3, "Wednesday"),
(4, "Thursday"),
(5, "Friday"),
(6, "Saturday"),
(7, "Sunday"),
],
verbose_name="weekday",
),
),
(
"start_at",
models.PositiveSmallIntegerField(
validators=[django.core.validators.MaxValueValidator(95)],
verbose_name="start at",
),
),
(
"end_at",
models.PositiveSmallIntegerField(
validators=[django.core.validators.MaxValueValidator(95)],
verbose_name="end at",
),
),
(
"course_type",
models.CharField(max_length=12, verbose_name="course type"),
),
("room", models.CharField(max_length=32, verbose_name="room")),
("ue", models.CharField(max_length=32, verbose_name="ue")),
(
"week_group",
models.CharField(
blank=True,
choices=[("A", "A"), ("B", "B")],
default="",
max_length=1,
verbose_name="week group",
),
),
(
"timetable",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="slots",
to="timetable.timetable",
verbose_name="timetable",
),
),
],
options={
"verbose_name": "timetable slot",
"verbose_name_plural": "timetable slots",
},
),
migrations.AddConstraint(
model_name="timetable",
constraint=models.UniqueConstraint(
fields=("user", "semester"), name="timetable_unique_user_semester"
),
),
migrations.AddConstraint(
model_name="timetableslot",
constraint=models.CheckConstraint(
condition=models.Q(("end_at__gt", models.F("start_at"))),
name="timetable_slot_end_after_start",
),
),
]
+101
View File
@@ -1 +1,102 @@
# Create your models here.
from datetime import timedelta
from django.core.validators import MaxValueValidator, RegexValidator
from django.db import models
from django.db.models import F, Q
from django.utils.translation import gettext_lazy as _
from core.models import User
from core.utils import get_semester_code
class Timetable(models.Model):
user = models.ForeignKey(
User,
verbose_name=_("user"),
related_name="timetables",
on_delete=models.CASCADE,
)
semester = models.CharField(
_("semester"),
default=get_semester_code,
validators=[RegexValidator(r"(A|P)\d{2}")],
blank=True,
)
class Meta:
verbose_name = _("timetable")
verbose_name_plural = _("timetables")
constraints = [
models.UniqueConstraint(
fields=("user", "semester"), name="timetable_unique_user_semester"
)
]
permissions = [("add_self_timetable", "Can add its own timetable")]
def __str__(self) -> str:
return f"{self.user} {self.semester}"
class TimetableSlot(models.Model):
MINUTES_PER_SLOT = 15
class WeekDay(models.IntegerChoices):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
class WeekGroup(models.TextChoices):
A = "A"
B = "B"
BOTH = ""
timetable = models.ForeignKey(
Timetable,
verbose_name=_("timetable"),
related_name="slots",
on_delete=models.CASCADE,
)
weekday = models.SmallIntegerField(_("weekday"), choices=WeekDay)
# there are 4 * 24 = 96 quarters in a day, and we start counting at 0
start_at = models.PositiveSmallIntegerField(
_("start at"), validators=[MaxValueValidator(95)]
)
end_at = models.PositiveSmallIntegerField(
_("end at"), validators=[MaxValueValidator(95)]
)
course_type = models.CharField(_("course type"), max_length=12)
room = models.CharField(_("room"), max_length=32)
ue = models.CharField(_("ue"), max_length=32)
week_group = models.CharField(
_("week group"),
max_length=1,
choices=WeekGroup,
default=WeekGroup.BOTH,
blank=True,
)
class Meta:
verbose_name = _("timetable slot")
verbose_name_plural = _("timetable slots")
constraints = [
models.CheckConstraint(
condition=Q(end_at__gt=F("start_at")),
name="timetable_slot_end_after_start",
)
]
def __str__(self) -> str:
return f"{self.start_hour} - {self.end_hour} - {self.get_weekday_display()}"
@property
def start_hour(self):
return timedelta(minutes=self.start_at * self.MINUTES_PER_SLOT)
@property
def end_hour(self):
return timedelta(minutes=self.end_at * self.MINUTES_PER_SLOT)
+35
View File
@@ -0,0 +1,35 @@
from typing import Annotated
from annotated_types import Ge, Le
from ninja import ModelSchema, Schema
from pydantic import Field
from timetable.models import Timetable, TimetableSlot
class TimetableSlotSchema(ModelSchema):
weekday: TimetableSlot.WeekDay = Field(
description=(
f"{TimetableSlot.WeekDay.MONDAY} is monday, "
f"{TimetableSlot.WeekDay.TUESDAY} is tuesday, etc."
)
)
start_at: Annotated[int, Ge(0), Le(96)]
end_at: Annotated[int, Ge(0), Le(96)]
class Meta:
model = TimetableSlot
fields = ["start_at", "end_at", "week_group", "ue", "course_type", "room"]
class CreateTimetableSchema(Schema):
is_viewable: bool
slots: list[TimetableSlotSchema]
class TimetableSchema(ModelSchema):
slots: list[TimetableSlotSchema]
class Meta:
model = Timetable
fields = ["id", "semester"]
@@ -1,4 +1,6 @@
import html2canvas from "html2canvas";
import { AlertMessage } from "#core:utils/alert-message";
import { type WeekDay as ApiWeekDay, timetableSaveTimetable } from "#openapi";
// see https://regex101.com/r/QHSaPM/3
const TIMETABLE_ROW_RE: RegExp =
@@ -76,17 +78,88 @@ function parseSlots(s: string): TimetableSlot[] {
}
document.addEventListener("alpine:init", () => {
Alpine.data("timetableGenerator", () => ({
/**
* Alpine data that can parse a timetable, save it and export it to png.
*/
Alpine.data("timetableGenerator", (userId: number) => ({
content: DEFAULT_TIMETABLE,
error: null as { incorrectRow?: string },
displayedWeekdays: [] as WeekDay[],
error: null as { incorrectRow?: string } | null,
courses: [] as TimetableSlot[],
edtPublic: false,
saving: false,
timetableSavedMessage: new AlertMessage(),
generate() {
try {
this.courses = parseSlots(this.content);
this.error = null;
} catch (err) {
type ParseRowError = { cause: { row: string } };
this.error = { incorrectRow: (err as ParseRowError)?.cause?.row };
return;
}
},
async savePng() {
const elem = document.getElementById("timetable");
const img = (await html2canvas(elem as HTMLElement)).toDataURL();
const downloadLink = document.createElement("a");
downloadLink.href = img;
downloadLink.download = "edt.png";
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
},
async saveSith() {
this.saving = true;
const res = await timetableSaveTimetable({
// biome-ignore lint/style/useNamingConvention: api is snake case
path: { user_id: userId },
body: {
// biome-ignore lint/style/useNamingConvention: api is snake case
is_viewable: this.edtPublic,
slots: this.courses.map((c) => ({
// biome-ignore lint/style/useNamingConvention: api is snake case
start_at: c.startSlot,
// biome-ignore lint/style/useNamingConvention: api is snake case
end_at: c.endSlot,
weekday: (WEEKDAYS.indexOf(c.weekday) + 1) as ApiWeekDay,
// biome-ignore lint/style/useNamingConvention: api is snake case
week_group: c.weekGroup,
// biome-ignore lint/style/useNamingConvention: api is snake case
course_type: c.courseType,
room: c.room,
ue: c.ueCode,
})),
},
});
if (res.response?.ok) {
this.timetableSavedMessage.display(
gettext("This timetable has been saved in your profile"),
{ success: true },
);
} else {
this.timetableSavedMessage.display(
interpolate(gettext("Error %d: timetable save failed"), res.response?.status),
{ success: false },
);
}
this.saving = false;
},
}));
/**
* Alpine data dedicated to timetable display only.
* It can interact with the `timetableGenerator` data with x-model and x-modelable
* (for example of this, see timetable/generator.jinja)
*/
Alpine.data("timetableDisplay", (slots: TimetableSlot[]) => ({
displayedWeekdays: [] as WeekDay[],
startSlot: 0,
endSlot: 0,
table: {
height: 0,
width: 0,
},
table: { height: 0, width: 0 },
slots: slots,
colors: {} as Record<string, string>,
colorPalette: [
@@ -103,18 +176,14 @@ document.addEventListener("alpine:init", () => {
"#1b5e20",
],
generate() {
try {
this.courses = parseSlots(this.content);
this.error = null;
} catch (err) {
this.error = { incorrectRow: err?.cause?.row };
return;
}
init() {
this.$watch("slots", () => this.display());
},
display() {
// color each UE
let colorIndex = 0;
for (const slot of this.courses) {
for (const slot of this.slots) {
if (!this.colors[slot.ueCode]) {
this.colors[slot.ueCode] =
this.colorPalette[colorIndex % this.colorPalette.length];
@@ -123,13 +192,13 @@ document.addEventListener("alpine:init", () => {
}
this.displayedWeekdays = WEEKDAYS.filter((day) =>
this.courses.some((slot: TimetableSlot) => slot.weekday === day),
this.slots.some((slot: TimetableSlot) => slot.weekday === day),
);
this.startSlot = this.courses.reduce(
this.startSlot = this.slots.reduce(
(acc: number, curr: TimetableSlot) => Math.min(acc, curr.startSlot),
25 * 4,
);
this.endSlot = this.courses.reduce(
this.endSlot = this.slots.reduce(
(acc: number, curr: TimetableSlot) => Math.max(acc, curr.endSlot),
1,
);
@@ -138,7 +207,7 @@ document.addEventListener("alpine:init", () => {
},
getStyle(slot: TimetableSlot) {
const hasWeekGroup = slot.weekGroup !== undefined;
const hasWeekGroup = !!slot.weekGroup;
const width = hasWeekGroup ? SLOT_WIDTH / 2 : SLOT_WIDTH;
const leftOffset = slot.weekGroup === "B" ? SLOT_WIDTH / 2 : 0;
return {
@@ -150,15 +219,19 @@ document.addEventListener("alpine:init", () => {
};
},
getHours(): [string, object][] {
/**
* Return the hours that should be displayed on this timetable,
* with their `top` placing
*/
getHours(): [string, { top: `${number}px` }][] {
let hour: number = Number.parseInt(
this.courses
this.slots
.map((c: TimetableSlot) => c.startHour)
.reduce((res: string, hour: string) => (hour < res ? hour : res), "24:00")
.split(":")[0],
10,
);
const res: [string, object][] = [];
const res: [string, { top: `${number}px` }][] = [];
for (let i = 0; i <= this.endSlot - this.startSlot; i += 60 / MINUTES_PER_SLOT) {
res.push([`${hour}:00`, { top: `${i * SLOT_HEIGHT}px` }]);
hour += 1;
@@ -169,16 +242,5 @@ document.addEventListener("alpine:init", () => {
getWidth() {
return this.displayedWeekdays.length * SLOT_WIDTH + 20;
},
async savePng() {
const elem = document.getElementById("timetable");
const img = (await html2canvas(elem as HTMLElement)).toDataURL();
const downloadLink = document.createElement("a");
downloadLink.href = img;
downloadLink.download = "edt.png";
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
},
}));
});
@@ -1,6 +1,6 @@
@import "core/static/core/colors";
#timetable {
.timetable {
--hour-side-width: 60px;
display: block;
+39 -41
View File
@@ -1,11 +1,13 @@
{% extends 'core/base.jinja' %}
{% extends "core/base.jinja" %}
{% from "timetable/macros.jinja" import display_timetable %}
{%- block additional_css -%}
<link rel="stylesheet" href="{{ static('timetable/css/generator.scss') }}">
{%- endblock -%}
{%- block additional_js -%}
<script type="module" src="{{ static('bundled/timetable/generator-index.ts') }}"></script>
<script type="module" src="{{ static('bundled/timetable/timetable-index.ts') }}"></script>
{%- endblock -%}
{% block title %}
@@ -32,7 +34,7 @@
{% endblock %}
{% block content %}
<div x-data="timetableGenerator">
<div x-data="timetableGenerator({{ user.id }})">
<form @submit.prevent="generate()">
<h1>{% trans %}Timetable generator{% endtrans %}</h1>
<template x-if="error !== null" x-cloak>
@@ -60,44 +62,40 @@
</div>
<input type="submit" class="btn btn-blue" value="{% trans %}Generate{% endtrans %}">
</form>
<div
id="timetable"
x-show="table.height > 0 && table.width > 0"
:style="{width: `${table.width+80}px`, height: `${table.height+40}px`}"
>
<div class="header">
<template x-for="weekday in displayedWeekdays">
<span x-text="weekday"></span>
</template>
</div>
<div class="content">
<div class="hours" :height="(endSlot - endSlot%4) - (startSlot - startSlot%4)">
<template x-for="[hour, style] in getHours()">
<div class="hour" :style="style">
<div x-text="hour"></div>
<div class="hour-bar" :style="{width: `${getWidth()}px`}"></div>
</div>
</template>
</div>
<div class="courses">
<template x-for="course in courses">
<div class="slot" :style="getStyle(course)">
<span class="course-type" x-text="course.courseType"></span>
<span x-text="course.ueCode"></span>
<span x-text="`${course.startHour} - ${course.endHour}`"></span>
<span x-text="(course.weekGroup ? `\nGroupe ${course.weekGroup}` : '')"></span>
<span x-text="course.room"></span>
</div>
</template>
</div>
</div>
</div>
<button
class="margin-bottom btn btn-blue"
@click="savePng"
x-show="table.height > 0 && table.width > 0"
>
{% trans %}Save to PNG{% endtrans %}
{{ display_timetable("courses") }}
<template x-if="courses.length > 0">
<section>
{% if user.has_perm("timetable.add_self_timetable") %}
<div id="timetable-save" class="margin-bottom">
<h3>{% trans %}Save on your profile{% endtrans %}</h3>
<form>
<fieldset>
<input type="checkbox" class="switch" id="edt-public-switch-id" x-model="edtPublic">
<label for="edt-public-switch-id">{% trans %}Make this timetable public{% endtrans %}</label>
<span class="helptext">
{% trans trimmed url=url("core:user_prefs", user_id=user.id) %}
You can change this at any time in <a href="{{ url }}">your preferences</a>
{% endtrans %}
</span>
</fieldset>
<button class="btn btn-blue" :disabled="saving" @click.prevent="saveSith">
{% trans %}Save timetable{% endtrans %}
</button>
<p
class="alert"
:class="timetableSavedMessage.success ? 'alert-green' : 'alert-red'"
x-show="timetableSavedMessage.open"
x-transition.duration.500ms
x-text="timetableSavedMessage.content"
></p>
</form>
</div>
{% endif %}
<h3 class="margin-bottom">{% trans %}Export{% endtrans %}</h3>
<button class="margin-bottom btn btn-blue" @click="savePng">
{% trans %}Export to PNG{% endtrans %}
</button>
</section>
</template>
</div>
{% endblock content %}
@@ -0,0 +1,46 @@
{# HTML+AlpineJS to display a timetable
Args:
ues: either a JS variable name or an array of object
satisfying the TimetableSlot interface
reactive: if True and `ues` is a variable used in an Alpine context,
then this timetable will react to modifications and
change its own display
#}
{% macro display_timetable(ues) %}
<div
x-data="timetableDisplay({{ ues }})"
x-model="{{ ues }}"
x-modelable="slots"
class="timetable"
x-show="slots.length > 0"
:style="{width: `${table.width+80}px`, height: `${table.height+40}px`}"
>
<div class="header">
<template x-for="weekday in displayedWeekdays">
<span x-text="weekday"></span>
</template>
</div>
<div class="content">
<div class="hours" :height="(endSlot - endSlot%4) - (startSlot - startSlot%4)">
<template x-for="[hour, style] in getHours()">
<div class="hour" :style="style">
<div x-text="hour"></div>
<div class="hour-bar" :style="{width: `${getWidth()}px`}"></div>
</div>
</template>
</div>
<div class="courses">
<template x-for="course in slots">
<div class="slot" :style="getStyle(course)">
<span class="course-type" x-text="course.courseType"></span>
<span x-text="course.ueCode"></span>
<span x-text="`${course.startHour} - ${course.endHour}`"></span>
<span x-text="(course.weekGroup ? `\nGroupe ${course.weekGroup}` : '')"></span>
<span x-text="course.room"></span>
</div>
</template>
</div>
</div>
</div>
{% endmacro %}
@@ -0,0 +1,52 @@
{% extends "core/base.jinja" %}
{% from "timetable/macros.jinja" import display_timetable %}
{%- block additional_css -%}
<link rel="stylesheet" href="{{ static('timetable/css/generator.scss') }}">
{%- endblock -%}
{%- block additional_js -%}
<script type="module" src="{{ static('bundled/timetable/timetable-index.ts') }}"></script>
{%- endblock -%}
{% block content %}
{% for timetable in timetables %}
<details
class="accordion"
name="{{ timetable.semester }}"
{% if loop.first %}open{% endif %}
>
<summary>{{ timetable.semester }}</summary>
<div class="accordion-content">
{{ display_timetable(timetable.semester) }}
</div>
</details>
{% endfor %}
{% endblock %}
{%- block script -%}
{% set weekdays = ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"] %}
<script>
{%- for timetable in timetables -%}
const {{ timetable.semester }} = [
{%- for slot in timetable.slots.all() -%}
{
courseType: "{{ slot.course_type }}",
room: "{{ slot.room }}",
startHour: "{{ "%02d:%02d" % (slot.start_hour.seconds // 3600, (slot.start_hour.seconds % 3600 ) // 60) }}",
endHour: "{{ "%02d:%02d" % (slot.end_hour.seconds // 3600, (slot.end_hour.seconds % 3600 ) // 60) }}",
startSlot: {{ slot.start_at }},
endSlot: {{ slot.end_at }},
ueCode: "{{ slot.ue }}",
{%- if slot.week_group -%}
weekGroup: "{{ slot.week_group }}",
{%- endif -%}
weekday: "{{ weekdays[slot.weekday] }}"
},
{%- endfor -%}
];
{%- endfor -%}
</script>
{%- endblock -%}
-1
View File
@@ -1 +0,0 @@
# Create your tests here.
View File
Whitespace-only changes.
+20
View File
@@ -0,0 +1,20 @@
from django.test import TestCase
from django.urls import reverse
from core.baker_recipes import subscriber_user
from timetable.models import TimetableSlot
class TestSaveTimetable(TestCase):
@classmethod
def setUpTestData(cls) -> None:
cls.user = subscriber_user.make()
cls.payload = {
"is_viewable": True,
"slots": [
{"weekday": TimetableSlot.WeekDay.MONDAY, "start_at": 32, "end_at": 40},
{"weekday": TimetableSlot.WeekDay.MONDAY, "start_at": 41, "end_at": 49},
{"weekday": TimetableSlot.WeekDay.FRIDAY, "start_at": 52, "end_at": 64},
],
}
cls.url = reverse("api:timetable:save", kwargs={"user_id": cls.user.id})
+31
View File
@@ -0,0 +1,31 @@
from typing import TYPE_CHECKING
import pytest
from bs4 import BeautifulSoup
from django.contrib.auth.models import Permission
from django.urls import reverse
from model_bakery import baker
from core.models import User
if TYPE_CHECKING:
from django.test import Client
@pytest.mark.django_db
@pytest.mark.parametrize("can_save", [True, False])
def test_generator_ok(client: Client, can_save):
user = baker.make(User)
if can_save:
user.user_permissions.add(Permission.objects.get(codename="add_self_timetable"))
client.force_login(user)
res = client.get(reverse("timetable:generator"))
assert res.status_code == 200
soup = BeautifulSoup(res.text, "lxml")
elem = soup.find(id="timetable-save")
if can_save:
assert elem is not None
else:
assert elem is None
+5 -2
View File
@@ -1,5 +1,8 @@
from django.urls import path
from timetable.views import GeneratorView
from timetable.views import GeneratorView, UserTimetableView
urlpatterns = [path("", GeneratorView.as_view(), name="generator")]
urlpatterns = [
path("", GeneratorView.as_view(), name="generator"),
path("user/<int:user_id>", UserTimetableView.as_view(), name="user_timetable"),
]
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more