mirror of
https://github.com/ae-utbm/sith.git
synced 2025-12-13 02:41:20 +00:00
Compare commits
3 Commits
product-fo
...
galaxy
| Author | SHA1 | Date | |
|---|---|---|---|
| d539b7f906 | |||
| 67bdbfdcfc | |||
| 95e1246d2b |
@@ -8,7 +8,7 @@ from django.utils.crypto import constant_time_compare
|
|||||||
|
|
||||||
class Sha512ApiKeyHasher(BasePasswordHasher):
|
class Sha512ApiKeyHasher(BasePasswordHasher):
|
||||||
"""
|
"""
|
||||||
An API key hasher using the sha512 algorithm.
|
An API key hasher using the sha256 algorithm.
|
||||||
|
|
||||||
This hasher shouldn't be used in Django's `PASSWORD_HASHERS` setting.
|
This hasher shouldn't be used in Django's `PASSWORD_HASHERS` setting.
|
||||||
It is insecure for use in hashing passwords, but is safe for hashing
|
It is insecure for use in hashing passwords, but is safe for hashing
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ from core.views.widgets.ajax_select import (
|
|||||||
AutoCompleteSelectUser,
|
AutoCompleteSelectUser,
|
||||||
)
|
)
|
||||||
from counter.models import Counter, Selling
|
from counter.models import Counter, Selling
|
||||||
from counter.schemas import SaleFilterSchema
|
|
||||||
|
|
||||||
|
|
||||||
class ClubEditForm(forms.ModelForm):
|
class ClubEditForm(forms.ModelForm):
|
||||||
@@ -192,18 +191,6 @@ class SellingsForm(forms.Form):
|
|||||||
required=False,
|
required=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
def to_filter_schema(self) -> SaleFilterSchema:
|
|
||||||
products = (
|
|
||||||
*self.cleaned_data["products"],
|
|
||||||
*self.cleaned_data["archived_products"],
|
|
||||||
)
|
|
||||||
return SaleFilterSchema(
|
|
||||||
after=self.cleaned_data["begin_date"],
|
|
||||||
before=self.cleaned_data["end_date"],
|
|
||||||
counters={c.id for c in self.cleaned_data["counters"]} or None,
|
|
||||||
products={p.id for p in products} or None,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ClubOldMemberForm(forms.Form):
|
class ClubOldMemberForm(forms.Form):
|
||||||
members_old = forms.ModelMultipleChoiceField(
|
members_old = forms.ModelMultipleChoiceField(
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
|
from annotated_types import MinLen
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from ninja import FilterLookup, FilterSchema, ModelSchema
|
from ninja import Field, FilterSchema, ModelSchema
|
||||||
|
|
||||||
from club.models import Club, Membership
|
from club.models import Club, Membership
|
||||||
from core.schemas import NonEmptyStr, SimpleUserSchema
|
from core.schemas import SimpleUserSchema
|
||||||
|
|
||||||
|
|
||||||
class ClubSearchFilterSchema(FilterSchema):
|
class ClubSearchFilterSchema(FilterSchema):
|
||||||
search: Annotated[NonEmptyStr | None, FilterLookup("name__icontains")] = None
|
search: Annotated[str, MinLen(1)] | None = Field(None, q="name__icontains")
|
||||||
is_active: bool | None = None
|
is_active: bool | None = None
|
||||||
parent_id: int | None = None
|
parent_id: int | None = None
|
||||||
|
parent_name: str | None = Field(None, q="parent__name__icontains")
|
||||||
exclude_ids: set[int] | None = None
|
exclude_ids: set[int] | None = None
|
||||||
|
|
||||||
def filter_exclude_ids(self, value: set[int] | None):
|
def filter_exclude_ids(self, value: set[int] | None):
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ TODO : rewrite the pagination used in this template an Alpine one
|
|||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{{ form }}
|
{{ form }}
|
||||||
<p><input type="submit" value="{% trans %}Show{% endtrans %}" /></p>
|
<p><input type="submit" value="{% trans %}Show{% endtrans %}" /></p>
|
||||||
<p><input type="submit" value="{% trans %}Download as csv{% endtrans %}" formaction="{{ url('club:sellings_csv', club_id=object.id) }}"/></p>
|
<p><input type="submit" value="{% trans %}Download as cvs{% endtrans %}" formaction="{{ url('club:sellings_csv', club_id=object.id) }}"/></p>
|
||||||
</form>
|
</form>
|
||||||
<p>
|
<p>
|
||||||
{% trans %}Quantity: {% endtrans %}{{ total_quantity }} {% trans %}units{% endtrans %}<br/>
|
{% trans %}Quantity: {% endtrans %}{{ total_quantity }} {% trans %}units{% endtrans %}<br/>
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
{% extends "core/base.jinja" %}
|
{% extends "core/base.jinja" %}
|
||||||
{% from 'core/page/macros.jinja' import page_history %}
|
{% from 'core/macros_pages.jinja' import page_history %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{{ page_history(club.page) }}
|
{% if club.page %}
|
||||||
|
{{ page_history(club.page) }}
|
||||||
|
{% else %}
|
||||||
|
{% trans %}No page existing for this club{% endtrans %}
|
||||||
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
{% extends "core/base.jinja" %}
|
{% extends "core/base.jinja" %}
|
||||||
|
{% from 'core/macros_pages.jinja' import page_edit_form %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h2>{% trans %}Edit page{% endtrans %}</h2>
|
{{ page_edit_form(page, form, url('club:club_edit_page', club_id=page.club.id), csrf_token) }}
|
||||||
<form action="{{ url('club:club_edit_page', club_id=page.club.id) }}" method="post">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.as_p() }}
|
|
||||||
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from django.conf import settings
|
|||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.db.models import Max
|
from django.db.models import Max
|
||||||
from django.test import Client, TestCase
|
from django.test import TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.timezone import localdate, localtime, now
|
from django.utils.timezone import localdate, localtime, now
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
@@ -532,35 +532,6 @@ class TestMembership(TestClub):
|
|||||||
assert new_board == initial_board
|
assert new_board == initial_board
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_membership_set_old(client: Client):
|
|
||||||
membership = baker.make(Membership, end_date=None, user=(subscriber_user.make()))
|
|
||||||
client.force_login(membership.user)
|
|
||||||
response = client.post(
|
|
||||||
reverse("club:membership_set_old", kwargs={"membership_id": membership.id})
|
|
||||||
)
|
|
||||||
assertRedirects(
|
|
||||||
response, reverse("core:user_clubs", kwargs={"user_id": membership.user_id})
|
|
||||||
)
|
|
||||||
membership.refresh_from_db()
|
|
||||||
assert membership.end_date == localdate()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_membership_delete(client: Client):
|
|
||||||
user = baker.make(User, is_superuser=True)
|
|
||||||
membership = baker.make(Membership)
|
|
||||||
client.force_login(user)
|
|
||||||
url = reverse("club:membership_delete", kwargs={"membership_id": membership.id})
|
|
||||||
response = client.get(url)
|
|
||||||
assert response.status_code == 200
|
|
||||||
response = client.post(url)
|
|
||||||
assertRedirects(
|
|
||||||
response, reverse("core:user_clubs", kwargs={"user_id": membership.user_id})
|
|
||||||
)
|
|
||||||
assert not Membership.objects.filter(id=membership.id).exists()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
class TestJoinClub:
|
class TestJoinClub:
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
|
|||||||
@@ -3,10 +3,9 @@ from bs4 import BeautifulSoup
|
|||||||
from django.test import Client
|
from django.test import Client
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
from pytest_django.asserts import assertHTMLEqual
|
||||||
|
|
||||||
from club.models import Club, Membership
|
from club.models import Club
|
||||||
from core.baker_recipes import subscriber_user
|
|
||||||
from core.markdown import markdown
|
from core.markdown import markdown
|
||||||
from core.models import PageRev, User
|
from core.models import PageRev, User
|
||||||
|
|
||||||
@@ -17,6 +16,7 @@ def test_page_display_on_club_main_page(client: Client):
|
|||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
content = "# foo\nLorem ipsum dolor sit amet"
|
content = "# foo\nLorem ipsum dolor sit amet"
|
||||||
baker.make(PageRev, page=club.page, revision=1, content=content)
|
baker.make(PageRev, page=club.page, revision=1, content=content)
|
||||||
|
client.force_login(baker.make(User))
|
||||||
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
|
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
|
||||||
|
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
@@ -30,42 +30,10 @@ def test_club_main_page_without_content(client: Client):
|
|||||||
"""Test the club view works, even if the club page is empty"""
|
"""Test the club view works, even if the club page is empty"""
|
||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
club.page.revisions.all().delete()
|
club.page.revisions.all().delete()
|
||||||
|
client.force_login(baker.make(User))
|
||||||
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
|
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
|
||||||
|
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
soup = BeautifulSoup(res.text, "lxml")
|
soup = BeautifulSoup(res.text, "lxml")
|
||||||
detail_html = soup.find(id="club_detail")
|
detail_html = soup.find(id="club_detail")
|
||||||
assert detail_html.find_all("markdown") == []
|
assert detail_html.find_all("markdown") == []
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_page_revision(client: Client):
|
|
||||||
club = baker.make(Club)
|
|
||||||
revisions = baker.make(
|
|
||||||
PageRev, page=club.page, _quantity=3, content=iter(["foo", "bar", "baz"])
|
|
||||||
)
|
|
||||||
client.force_login(baker.make(User))
|
|
||||||
url = reverse(
|
|
||||||
"club:club_view_rev", kwargs={"club_id": club.id, "rev_id": revisions[1].id}
|
|
||||||
)
|
|
||||||
res = client.get(url)
|
|
||||||
assert res.status_code == 200
|
|
||||||
soup = BeautifulSoup(res.text, "lxml")
|
|
||||||
detail_html = soup.find(class_="markdown")
|
|
||||||
assertHTMLEqual(detail_html.decode_contents(), markdown(revisions[1].content))
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_edit_page(client: Client):
|
|
||||||
club = baker.make(Club)
|
|
||||||
user = subscriber_user.make()
|
|
||||||
baker.make(Membership, user=user, club=club, role=3)
|
|
||||||
client.force_login(user)
|
|
||||||
url = reverse("club:club_edit_page", kwargs={"club_id": club.id})
|
|
||||||
content = "# foo\nLorem ipsum dolor sit amet"
|
|
||||||
|
|
||||||
res = client.get(url)
|
|
||||||
assert res.status_code == 200
|
|
||||||
res = client.post(url, data={"content": content})
|
|
||||||
assertRedirects(res, reverse("club:club_view", kwargs={"club_id": club.id}))
|
|
||||||
assert club.page.revisions.last().content == content
|
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
import csv
|
|
||||||
import itertools
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django.test import Client
|
from django.test import Client
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
@@ -10,20 +7,16 @@ from club.forms import SellingsForm
|
|||||||
from club.models import Club
|
from club.models import Club
|
||||||
from core.models import User
|
from core.models import User
|
||||||
from counter.baker_recipes import product_recipe, sale_recipe
|
from counter.baker_recipes import product_recipe, sale_recipe
|
||||||
from counter.models import Counter, Customer, Product, Selling
|
from counter.models import Counter, Customer
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_sales_page_doesnt_crash(client: Client):
|
def test_sales_page_doesnt_crash(client: Client):
|
||||||
"""Basic crashtest on club sales view."""
|
|
||||||
club = baker.make(Club)
|
club = baker.make(Club)
|
||||||
product = baker.make(Product, club=club)
|
|
||||||
admin = baker.make(User, is_superuser=True)
|
admin = baker.make(User, is_superuser=True)
|
||||||
client.force_login(admin)
|
client.force_login(admin)
|
||||||
url = reverse("club:club_sellings", kwargs={"club_id": club.id})
|
response = client.get(reverse("club:club_sellings", kwargs={"club_id": club.id}))
|
||||||
assert client.get(url).status_code == 200
|
assert response.status_code == 200
|
||||||
assert client.post(url).status_code == 200
|
|
||||||
assert client.post(url, data={"products": [product.id]}).status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -43,62 +36,3 @@ def test_sales_form_counter_filter():
|
|||||||
form = SellingsForm(club)
|
form = SellingsForm(club)
|
||||||
form_counters = list(form.fields["counters"].queryset)
|
form_counters = list(form.fields["counters"].queryset)
|
||||||
assert form_counters == [counters[1], counters[2], counters[0]]
|
assert form_counters == [counters[1], counters[2], counters[0]]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_club_sales_csv(client: Client):
|
|
||||||
client.force_login(baker.make(User, is_superuser=True))
|
|
||||||
club = baker.make(Club)
|
|
||||||
counter = baker.make(Counter, club=club)
|
|
||||||
product = product_recipe.make(club=club, counters=[counter], purchase_price=0.5)
|
|
||||||
customers = baker.make(Customer, amount=100, _quantity=2, _bulk_create=True)
|
|
||||||
sales: list[Selling] = sale_recipe.make(
|
|
||||||
club=club,
|
|
||||||
counter=counter,
|
|
||||||
quantity=2,
|
|
||||||
unit_price=1.5,
|
|
||||||
product=iter([product, product, None]),
|
|
||||||
customer=itertools.cycle(customers),
|
|
||||||
_quantity=3,
|
|
||||||
)
|
|
||||||
url = reverse("club:sellings_csv", kwargs={"club_id": club.id})
|
|
||||||
response = client.post(url, data={"counters": [counter.id]})
|
|
||||||
assert response.status_code == 200
|
|
||||||
reader = csv.reader(s.decode() for s in response.streaming_content)
|
|
||||||
data = list(reader)
|
|
||||||
sale_rows = [
|
|
||||||
[
|
|
||||||
str(s.date),
|
|
||||||
str(counter),
|
|
||||||
str(s.seller),
|
|
||||||
s.customer.user.get_display_name(),
|
|
||||||
s.label,
|
|
||||||
"2",
|
|
||||||
"1.50",
|
|
||||||
"3.00",
|
|
||||||
"Compte utilisateur",
|
|
||||||
]
|
|
||||||
for s in sales[::-1]
|
|
||||||
]
|
|
||||||
sale_rows[2].extend(["0.50", "1.00"])
|
|
||||||
sale_rows[1].extend(["0.50", "1.00"])
|
|
||||||
sale_rows[0].extend(["", ""])
|
|
||||||
assert data == [
|
|
||||||
["Quantité", "6"],
|
|
||||||
["Total", "9"],
|
|
||||||
["Bénéfice", "1"],
|
|
||||||
[
|
|
||||||
"Date",
|
|
||||||
"Comptoir",
|
|
||||||
"Barman",
|
|
||||||
"Client",
|
|
||||||
"Étiquette",
|
|
||||||
"Quantité",
|
|
||||||
"Prix unitaire",
|
|
||||||
"Total",
|
|
||||||
"Méthode de paiement",
|
|
||||||
"Prix d'achat",
|
|
||||||
"Bénéfice",
|
|
||||||
],
|
|
||||||
*sale_rows,
|
|
||||||
]
|
|
||||||
|
|||||||
103
club/views.py
103
club/views.py
@@ -22,28 +22,25 @@
|
|||||||
#
|
#
|
||||||
#
|
#
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import csv
|
import csv
|
||||||
import itertools
|
import itertools
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import Any
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.contrib.messages.views import SuccessMessageMixin
|
from django.contrib.messages.views import SuccessMessageMixin
|
||||||
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
|
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
|
||||||
from django.core.paginator import InvalidPage, Paginator
|
from django.core.paginator import InvalidPage, Paginator
|
||||||
from django.db.models import F, Q, Sum
|
from django.db.models import F, Q, Sum
|
||||||
from django.http import Http404, StreamingHttpResponse
|
from django.http import Http404, HttpResponseRedirect, StreamingHttpResponse
|
||||||
from django.shortcuts import get_object_or_404, redirect
|
from django.shortcuts import get_object_or_404, redirect
|
||||||
from django.urls import reverse, reverse_lazy
|
from django.urls import reverse, reverse_lazy
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.utils.functional import cached_property
|
from django.utils.safestring import SafeString
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from django.utils.translation import gettext
|
from django.utils.translation import gettext
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from django.views.generic import DetailView, ListView, View
|
from django.views.generic import DetailView, ListView, View
|
||||||
from django.views.generic.detail import SingleObjectMixin
|
|
||||||
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||||
|
|
||||||
from club.forms import (
|
from club.forms import (
|
||||||
@@ -64,14 +61,11 @@ from com.views import (
|
|||||||
PosterListBaseView,
|
PosterListBaseView,
|
||||||
)
|
)
|
||||||
from core.auth.mixins import CanEditMixin, PermissionOrClubBoardRequiredMixin
|
from core.auth.mixins import CanEditMixin, PermissionOrClubBoardRequiredMixin
|
||||||
from core.models import Page, PageRev
|
from core.models import PageRev
|
||||||
from core.views import BasePageEditView, DetailFormView, UseFragmentsMixin
|
from core.views import DetailFormView, PageEditViewBase, UseFragmentsMixin
|
||||||
from core.views.mixins import FragmentMixin, FragmentRenderer, TabedViewMixin
|
from core.views.mixins import FragmentMixin, FragmentRenderer, TabedViewMixin
|
||||||
from counter.models import Selling
|
from counter.models import Selling
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from django.utils.safestring import SafeString
|
|
||||||
|
|
||||||
|
|
||||||
class ClubTabsMixin(TabedViewMixin):
|
class ClubTabsMixin(TabedViewMixin):
|
||||||
def get_tabs_title(self):
|
def get_tabs_title(self):
|
||||||
@@ -81,8 +75,6 @@ class ClubTabsMixin(TabedViewMixin):
|
|||||||
self.object = self.object.page.club
|
self.object = self.object.page.club
|
||||||
elif isinstance(self.object, Poster):
|
elif isinstance(self.object, Poster):
|
||||||
self.object = self.object.club
|
self.object = self.object.club
|
||||||
elif hasattr(self, "club"):
|
|
||||||
self.object = self.club
|
|
||||||
return self.object.get_display_name()
|
return self.object.get_display_name()
|
||||||
|
|
||||||
def get_list_of_tabs(self):
|
def get_list_of_tabs(self):
|
||||||
@@ -210,7 +202,7 @@ class ClubView(ClubTabsMixin, DetailView):
|
|||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
|
|
||||||
class ClubRevView(LoginRequiredMixin, ClubView):
|
class ClubRevView(ClubView):
|
||||||
"""Display a specific page revision."""
|
"""Display a specific page revision."""
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
@@ -224,26 +216,26 @@ class ClubRevView(LoginRequiredMixin, ClubView):
|
|||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
|
|
||||||
class ClubPageEditView(ClubTabsMixin, BasePageEditView):
|
class ClubPageEditView(ClubTabsMixin, PageEditViewBase):
|
||||||
template_name = "club/pagerev_edit.jinja"
|
template_name = "club/pagerev_edit.jinja"
|
||||||
current_tab = "page_edit"
|
current_tab = "page_edit"
|
||||||
|
|
||||||
@cached_property
|
def dispatch(self, request, *args, **kwargs):
|
||||||
def club(self):
|
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
||||||
return get_object_or_404(Club, pk=self.kwargs["club_id"])
|
if not self.club.page:
|
||||||
|
raise Http404
|
||||||
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@cached_property
|
def get_object(self):
|
||||||
def page(self) -> Page:
|
self.page = self.club.page
|
||||||
page = self.club.page
|
return self._get_revision()
|
||||||
page.set_lock(self.request.user)
|
|
||||||
return page
|
|
||||||
|
|
||||||
def get_success_url(self, **kwargs):
|
def get_success_url(self, **kwargs):
|
||||||
return reverse_lazy("club:club_view", kwargs={"club_id": self.club.id})
|
return reverse_lazy("club:club_view", kwargs={"club_id": self.club.id})
|
||||||
|
|
||||||
|
|
||||||
class ClubPageHistView(ClubTabsMixin, PermissionRequiredMixin, DetailView):
|
class ClubPageHistView(ClubTabsMixin, PermissionRequiredMixin, DetailView):
|
||||||
"""Modification history of the page."""
|
"""Modification hostory of the page."""
|
||||||
|
|
||||||
model = Club
|
model = Club
|
||||||
pk_url_kwarg = "club_id"
|
pk_url_kwarg = "club_id"
|
||||||
@@ -407,14 +399,33 @@ class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView):
|
|||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
|
|
||||||
kwargs["result"] = Selling.objects.none()
|
kwargs["result"] = Selling.objects.none()
|
||||||
|
kwargs["paginated_result"] = kwargs["result"]
|
||||||
kwargs["total"] = 0
|
kwargs["total"] = 0
|
||||||
kwargs["total_quantity"] = 0
|
kwargs["total_quantity"] = 0
|
||||||
kwargs["benefit"] = 0
|
kwargs["benefit"] = 0
|
||||||
|
|
||||||
form: SellingsForm = self.get_form()
|
form = self.get_form()
|
||||||
if form.is_valid() and any(v for v in form.cleaned_data.values()):
|
if form.is_valid():
|
||||||
filters = form.to_filter_schema()
|
qs = Selling.objects.filter(club=self.object)
|
||||||
qs = filters.filter(Selling.objects.filter(club=self.object))
|
if not len([v for v in form.cleaned_data.values() if v is not None]):
|
||||||
|
qs = Selling.objects.none()
|
||||||
|
if form.cleaned_data["begin_date"]:
|
||||||
|
qs = qs.filter(date__gte=form.cleaned_data["begin_date"])
|
||||||
|
if form.cleaned_data["end_date"]:
|
||||||
|
qs = qs.filter(date__lte=form.cleaned_data["end_date"])
|
||||||
|
|
||||||
|
if form.cleaned_data["counters"]:
|
||||||
|
qs = qs.filter(counter__in=form.cleaned_data["counters"])
|
||||||
|
|
||||||
|
selected_products = []
|
||||||
|
if form.cleaned_data["products"]:
|
||||||
|
selected_products.extend(form.cleaned_data["products"])
|
||||||
|
if form.cleaned_data["archived_products"]:
|
||||||
|
selected_products.extend(form.cleaned_data["archived_products"])
|
||||||
|
|
||||||
|
if len(selected_products) > 0:
|
||||||
|
qs = qs.filter(product__in=selected_products)
|
||||||
|
|
||||||
kwargs["total"] = qs.annotate(
|
kwargs["total"] = qs.annotate(
|
||||||
price=F("quantity") * F("unit_price")
|
price=F("quantity") * F("unit_price")
|
||||||
).aggregate(total=Sum("price", default=0))["total"]
|
).aggregate(total=Sum("price", default=0))["total"]
|
||||||
@@ -461,15 +472,15 @@ class ClubSellingCSVView(ClubSellingView):
|
|||||||
*row,
|
*row,
|
||||||
selling.label,
|
selling.label,
|
||||||
selling.quantity,
|
selling.quantity,
|
||||||
selling.unit_price,
|
|
||||||
selling.quantity * selling.unit_price,
|
selling.quantity * selling.unit_price,
|
||||||
selling.get_payment_method_display(),
|
selling.get_payment_method_display(),
|
||||||
]
|
]
|
||||||
if selling.product:
|
if selling.product:
|
||||||
|
row.append(selling.product.selling_price)
|
||||||
row.append(selling.product.purchase_price)
|
row.append(selling.product.purchase_price)
|
||||||
row.append(selling.unit_price - selling.product.purchase_price)
|
row.append(selling.product.selling_price - selling.product.purchase_price)
|
||||||
else:
|
else:
|
||||||
row = [*row, "", ""]
|
row = [*row, "", "", ""]
|
||||||
return row
|
return row
|
||||||
|
|
||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
@@ -490,9 +501,9 @@ class ClubSellingCSVView(ClubSellingView):
|
|||||||
gettext("Customer"),
|
gettext("Customer"),
|
||||||
gettext("Label"),
|
gettext("Label"),
|
||||||
gettext("Quantity"),
|
gettext("Quantity"),
|
||||||
gettext("Unit price"),
|
|
||||||
gettext("Total"),
|
gettext("Total"),
|
||||||
gettext("Payment method"),
|
gettext("Payment method"),
|
||||||
|
gettext("Selling price"),
|
||||||
gettext("Purchase price"),
|
gettext("Purchase price"),
|
||||||
gettext("Benefit"),
|
gettext("Benefit"),
|
||||||
],
|
],
|
||||||
@@ -545,17 +556,33 @@ class ClubCreateView(PermissionRequiredMixin, CreateView):
|
|||||||
permission_required = "club.add_club"
|
permission_required = "club.add_club"
|
||||||
|
|
||||||
|
|
||||||
class MembershipSetOldView(CanEditMixin, SingleObjectMixin, View):
|
class MembershipSetOldView(CanEditMixin, DetailView):
|
||||||
"""Set a membership as being old."""
|
"""Set a membership as beeing old."""
|
||||||
|
|
||||||
model = Membership
|
model = Membership
|
||||||
pk_url_kwarg = "membership_id"
|
pk_url_kwarg = "membership_id"
|
||||||
|
|
||||||
def post(self, *_args, **_kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
self.object = self.get_object()
|
self.object = self.get_object()
|
||||||
self.object.end_date = timezone.now()
|
self.object.end_date = timezone.now()
|
||||||
self.object.save()
|
self.object.save()
|
||||||
return redirect("core:user_clubs", user_id=self.object.user_id)
|
return HttpResponseRedirect(
|
||||||
|
reverse(
|
||||||
|
"club:club_members",
|
||||||
|
args=self.args,
|
||||||
|
kwargs={"club_id": self.object.club.id},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
self.object = self.get_object()
|
||||||
|
return HttpResponseRedirect(
|
||||||
|
reverse(
|
||||||
|
"club:club_members",
|
||||||
|
args=self.args,
|
||||||
|
kwargs={"club_id": self.object.club.id},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class MembershipDeleteView(PermissionRequiredMixin, DeleteView):
|
class MembershipDeleteView(PermissionRequiredMixin, DeleteView):
|
||||||
@@ -567,7 +594,7 @@ class MembershipDeleteView(PermissionRequiredMixin, DeleteView):
|
|||||||
permission_required = "club.delete_membership"
|
permission_required = "club.delete_membership"
|
||||||
|
|
||||||
def get_success_url(self):
|
def get_success_url(self):
|
||||||
return reverse_lazy("core:user_clubs", kwargs={"user_id": self.object.user_id})
|
return reverse_lazy("core:user_clubs", kwargs={"user_id": self.object.user.id})
|
||||||
|
|
||||||
|
|
||||||
class ClubMailingView(ClubTabsMixin, CanEditMixin, DetailFormView):
|
class ClubMailingView(ClubTabsMixin, CanEditMixin, DetailFormView):
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from ninja import FilterLookup, FilterSchema, ModelSchema
|
from ninja import FilterSchema, ModelSchema
|
||||||
from ninja_extra import service_resolver
|
from ninja_extra import service_resolver
|
||||||
from ninja_extra.context import RouteContext
|
from ninja_extra.context import RouteContext
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
from club.schemas import ClubProfileSchema
|
from club.schemas import ClubProfileSchema
|
||||||
from com.models import News, NewsDate
|
from com.models import News, NewsDate
|
||||||
@@ -11,12 +11,12 @@ from core.markdown import markdown
|
|||||||
|
|
||||||
|
|
||||||
class NewsDateFilterSchema(FilterSchema):
|
class NewsDateFilterSchema(FilterSchema):
|
||||||
before: Annotated[datetime | None, FilterLookup("end_date__lt")] = None
|
before: datetime | None = Field(None, q="end_date__lt")
|
||||||
after: Annotated[datetime | None, FilterLookup("start_date__gt")] = None
|
after: datetime | None = Field(None, q="start_date__gt")
|
||||||
club_id: Annotated[int | None, FilterLookup("news__club_id")] = None
|
club_id: int | None = Field(None, q="news__club_id")
|
||||||
news_id: int | None = None
|
news_id: int | None = None
|
||||||
is_published: Annotated[bool | None, FilterLookup("news__is_published")] = None
|
is_published: bool | None = Field(None, q="news__is_published")
|
||||||
title: Annotated[str | None, FilterLookup("news__title__icontains")] = None
|
title: str | None = Field(None, q="news__title__icontains")
|
||||||
|
|
||||||
|
|
||||||
class NewsSchema(ModelSchema):
|
class NewsSchema(ModelSchema):
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -17,6 +18,16 @@ from core.markdown import markdown
|
|||||||
from core.models import User
|
from core.models import User
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MockResponse:
|
||||||
|
ok: bool
|
||||||
|
value: str
|
||||||
|
|
||||||
|
@property
|
||||||
|
def content(self):
|
||||||
|
return self.value.encode("utf8")
|
||||||
|
|
||||||
|
|
||||||
def accel_redirect_to_file(response: HttpResponse) -> Path | None:
|
def accel_redirect_to_file(response: HttpResponse) -> Path | None:
|
||||||
redirect = Path(response.headers.get("X-Accel-Redirect", ""))
|
redirect = Path(response.headers.get("X-Accel-Redirect", ""))
|
||||||
if not redirect.is_relative_to(Path("/") / settings.MEDIA_ROOT.stem):
|
if not redirect.is_relative_to(Path("/") / settings.MEDIA_ROOT.stem):
|
||||||
|
|||||||
@@ -240,11 +240,10 @@ class NewsListView(TemplateView):
|
|||||||
if not self.request.user.has_perm("core.view_user"):
|
if not self.request.user.has_perm("core.view_user"):
|
||||||
return []
|
return []
|
||||||
return itertools.groupby(
|
return itertools.groupby(
|
||||||
User.objects.viewable_by(self.request.user)
|
User.objects.filter(
|
||||||
.filter(
|
|
||||||
date_of_birth__month=localdate().month,
|
date_of_birth__month=localdate().month,
|
||||||
date_of_birth__day=localdate().day,
|
date_of_birth__day=localdate().day,
|
||||||
is_viewable=True,
|
is_subscriber_viewable=True,
|
||||||
)
|
)
|
||||||
.filter(role__in=["STUDENT", "FORMER STUDENT"])
|
.filter(role__in=["STUDENT", "FORMER STUDENT"])
|
||||||
.order_by("-date_of_birth"),
|
.order_by("-date_of_birth"),
|
||||||
|
|||||||
@@ -74,19 +74,9 @@ class UserBanAdmin(admin.ModelAdmin):
|
|||||||
autocomplete_fields = ("user", "ban_group")
|
autocomplete_fields = ("user", "ban_group")
|
||||||
|
|
||||||
|
|
||||||
class GroupInline(admin.TabularInline):
|
|
||||||
model = Group.permissions.through
|
|
||||||
readonly_fields = ("group",)
|
|
||||||
extra = 0
|
|
||||||
|
|
||||||
def has_add_permission(self, request, obj):
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Permission)
|
@admin.register(Permission)
|
||||||
class PermissionAdmin(admin.ModelAdmin):
|
class PermissionAdmin(admin.ModelAdmin):
|
||||||
search_fields = ("codename",)
|
search_fields = ("codename",)
|
||||||
inlines = (GroupInline,)
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Page)
|
@admin.register(Page)
|
||||||
|
|||||||
26
core/api.py
26
core/api.py
@@ -1,6 +1,6 @@
|
|||||||
from typing import Annotated, Any, Literal
|
from typing import Annotated, Any, Literal
|
||||||
|
|
||||||
from annotated_types import Ge, Le, MinLen
|
import annotated_types
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.db.models import F
|
from django.db.models import F
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
@@ -28,7 +28,6 @@ from core.schemas import (
|
|||||||
UserSchema,
|
UserSchema,
|
||||||
)
|
)
|
||||||
from core.templatetags.renderer import markdown
|
from core.templatetags.renderer import markdown
|
||||||
from counter.utils import is_logged_in_counter
|
|
||||||
|
|
||||||
|
|
||||||
@api_controller("/markdown")
|
@api_controller("/markdown")
|
||||||
@@ -73,9 +72,9 @@ class MailingListController(ControllerBase):
|
|||||||
|
|
||||||
@api_controller("/user")
|
@api_controller("/user")
|
||||||
class UserController(ControllerBase):
|
class UserController(ControllerBase):
|
||||||
@route.get("", response=list[UserProfileSchema])
|
@route.get("", response=list[UserProfileSchema], permissions=[CanAccessLookup])
|
||||||
def fetch_profiles(self, pks: Query[set[int]]):
|
def fetch_profiles(self, pks: Query[set[int]]):
|
||||||
return User.objects.viewable_by(self.context.request.user).filter(pk__in=pks)
|
return User.objects.filter(pk__in=pks)
|
||||||
|
|
||||||
@route.get("/{int:user_id}", response=UserSchema, permissions=[CanView])
|
@route.get("/{int:user_id}", response=UserSchema, permissions=[CanView])
|
||||||
def fetch_user(self, user_id: int):
|
def fetch_user(self, user_id: int):
|
||||||
@@ -86,18 +85,13 @@ class UserController(ControllerBase):
|
|||||||
"/search",
|
"/search",
|
||||||
response=PaginatedResponseSchema[UserProfileSchema],
|
response=PaginatedResponseSchema[UserProfileSchema],
|
||||||
url_name="search_users",
|
url_name="search_users",
|
||||||
# logged in barmen aren't authenticated stricto sensu, so no auth here
|
permissions=[CanAccessLookup],
|
||||||
auth=None,
|
|
||||||
)
|
)
|
||||||
@paginate(PageNumberPaginationExtra, page_size=20)
|
@paginate(PageNumberPaginationExtra, page_size=20)
|
||||||
def search_users(self, filters: Query[UserFilterSchema]):
|
def search_users(self, filters: Query[UserFilterSchema]):
|
||||||
qs = User.objects
|
return filters.filter(
|
||||||
# the logged in barmen can see all users (even the hidden one),
|
User.objects.order_by(F("last_login").desc(nulls_last=True))
|
||||||
# because they have a temporary administrative function during
|
)
|
||||||
# which they may have to deal with hidden users
|
|
||||||
if not is_logged_in_counter(self.context.request):
|
|
||||||
qs = qs.viewable_by(self.context.request.user)
|
|
||||||
return filters.filter(qs.order_by(F("last_login").desc(nulls_last=True)))
|
|
||||||
|
|
||||||
|
|
||||||
@api_controller("/file")
|
@api_controller("/file")
|
||||||
@@ -109,7 +103,7 @@ class SithFileController(ControllerBase):
|
|||||||
permissions=[CanAccessLookup],
|
permissions=[CanAccessLookup],
|
||||||
)
|
)
|
||||||
@paginate(PageNumberPaginationExtra, page_size=50)
|
@paginate(PageNumberPaginationExtra, page_size=50)
|
||||||
def search_files(self, search: Annotated[str, MinLen(1)]):
|
def search_files(self, search: Annotated[str, annotated_types.MinLen(1)]):
|
||||||
return SithFile.objects.filter(is_in_sas=False).filter(name__icontains=search)
|
return SithFile.objects.filter(is_in_sas=False).filter(name__icontains=search)
|
||||||
|
|
||||||
|
|
||||||
@@ -122,11 +116,11 @@ class GroupController(ControllerBase):
|
|||||||
permissions=[CanAccessLookup],
|
permissions=[CanAccessLookup],
|
||||||
)
|
)
|
||||||
@paginate(PageNumberPaginationExtra, page_size=50)
|
@paginate(PageNumberPaginationExtra, page_size=50)
|
||||||
def search_group(self, search: Annotated[str, MinLen(1)]):
|
def search_group(self, search: Annotated[str, annotated_types.MinLen(1)]):
|
||||||
return Group.objects.filter(name__icontains=search).values()
|
return Group.objects.filter(name__icontains=search).values()
|
||||||
|
|
||||||
|
|
||||||
DepthValue = Annotated[int, Ge(0), Le(10)]
|
DepthValue = Annotated[int, annotated_types.Ge(0), annotated_types.Le(10)]
|
||||||
DEFAULT_DEPTH = 4
|
DEFAULT_DEPTH = 4
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -150,8 +150,7 @@ class Command(BaseCommand):
|
|||||||
|
|
||||||
Weekmail().save()
|
Weekmail().save()
|
||||||
|
|
||||||
# Here we add a lot of test datas, that are not necessary for the Sith,
|
# Here we add a lot of test datas, that are not necessary for the Sith, but that provide a basic development environment
|
||||||
# but that provide a basic development environment
|
|
||||||
self.now = timezone.now().replace(hour=12, second=0)
|
self.now = timezone.now().replace(hour=12, second=0)
|
||||||
|
|
||||||
skia = User.objects.create_user(
|
skia = User.objects.create_user(
|
||||||
|
|||||||
@@ -350,6 +350,7 @@ class Command(BaseCommand):
|
|||||||
date=make_aware(
|
date=make_aware(
|
||||||
self.faker.date_time_between(customer.since, localdate())
|
self.faker.date_time_between(customer.since, localdate())
|
||||||
),
|
),
|
||||||
|
is_validated=True,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
sales.extend(this_customer_sales)
|
sales.extend(this_customer_sales)
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
# Generated by Django 5.2.8 on 2025-11-09 15:20
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [("core", "0047_alter_notification_date_alter_notification_type")]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterModelOptions(
|
|
||||||
name="user",
|
|
||||||
options={
|
|
||||||
"permissions": [("view_hidden_user", "Can view hidden users")],
|
|
||||||
"verbose_name": "user",
|
|
||||||
"verbose_name_plural": "users",
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.RenameField(
|
|
||||||
model_name="user", old_name="is_subscriber_viewable", new_name="is_viewable"
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="user",
|
|
||||||
name="is_viewable",
|
|
||||||
field=models.BooleanField(
|
|
||||||
default=True,
|
|
||||||
verbose_name="Profile visible by subscribers",
|
|
||||||
help_text=(
|
|
||||||
"If you disable this option, only admin users "
|
|
||||||
"will be able to see your profile."
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -23,13 +23,12 @@
|
|||||||
#
|
#
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import difflib
|
|
||||||
import string
|
import string
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING, Final, Self
|
from typing import TYPE_CHECKING, Self
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@@ -38,6 +37,7 @@ from django.contrib.auth.models import AnonymousUser as AuthAnonymousUser
|
|||||||
from django.contrib.auth.models import Group as AuthGroup
|
from django.contrib.auth.models import Group as AuthGroup
|
||||||
from django.contrib.staticfiles.storage import staticfiles_storage
|
from django.contrib.staticfiles.storage import staticfiles_storage
|
||||||
from django.core import validators
|
from django.core import validators
|
||||||
|
from django.core.cache import cache
|
||||||
from django.core.exceptions import PermissionDenied, ValidationError
|
from django.core.exceptions import PermissionDenied, ValidationError
|
||||||
from django.core.files import File
|
from django.core.files import File
|
||||||
from django.core.files.base import ContentFile
|
from django.core.files.base import ContentFile
|
||||||
@@ -54,8 +54,6 @@ from django.utils.translation import gettext_lazy as _
|
|||||||
from phonenumber_field.modelfields import PhoneNumberField
|
from phonenumber_field.modelfields import PhoneNumberField
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
from core.utils import get_last_promo
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from django.core.files.uploadedfile import UploadedFile
|
from django.core.files.uploadedfile import UploadedFile
|
||||||
from pydantic import NonNegativeInt
|
from pydantic import NonNegativeInt
|
||||||
@@ -76,13 +74,24 @@ class Group(AuthGroup):
|
|||||||
def get_absolute_url(self) -> str:
|
def get_absolute_url(self) -> str:
|
||||||
return reverse("core:group_list")
|
return reverse("core:group_list")
|
||||||
|
|
||||||
|
def save(self, *args, **kwargs) -> None:
|
||||||
|
super().save(*args, **kwargs)
|
||||||
|
cache.set(f"sith_group_{self.id}", self)
|
||||||
|
cache.set(f"sith_group_{self.name.replace(' ', '_')}", self)
|
||||||
|
|
||||||
|
def delete(self, *args, **kwargs) -> None:
|
||||||
|
super().delete(*args, **kwargs)
|
||||||
|
cache.delete(f"sith_group_{self.id}")
|
||||||
|
cache.delete(f"sith_group_{self.name.replace(' ', '_')}")
|
||||||
|
|
||||||
|
|
||||||
def validate_promo(value: int) -> None:
|
def validate_promo(value: int) -> None:
|
||||||
last_promo = get_last_promo()
|
start_year = settings.SITH_SCHOOL_START_YEAR
|
||||||
if not 0 < value <= last_promo:
|
delta = (localdate() + timedelta(days=180)).year - start_year
|
||||||
|
if value < 0 or delta < value:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
_("%(value)s is not a valid promo (between 0 and %(end)s)"),
|
_("%(value)s is not a valid promo (between 0 and %(end)s)"),
|
||||||
params={"value": value, "end": last_promo},
|
params={"value": value, "end": delta},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -127,15 +136,6 @@ class UserQuerySet(models.QuerySet):
|
|||||||
Q(Exists(subscriptions)) | Q(Exists(refills)) | Q(Exists(purchases))
|
Q(Exists(subscriptions)) | Q(Exists(refills)) | Q(Exists(purchases))
|
||||||
)
|
)
|
||||||
|
|
||||||
def viewable_by(self, user: User) -> Self:
|
|
||||||
if user.has_perm("core.view_hidden_user"):
|
|
||||||
return self
|
|
||||||
if user.has_perm("core.view_user"):
|
|
||||||
return self.filter(is_viewable=True)
|
|
||||||
if user.is_anonymous:
|
|
||||||
return self.none()
|
|
||||||
return self.filter(id=user.id)
|
|
||||||
|
|
||||||
|
|
||||||
class CustomUserManager(UserManager.from_queryset(UserQuerySet)):
|
class CustomUserManager(UserManager.from_queryset(UserQuerySet)):
|
||||||
# see https://docs.djangoproject.com/fr/stable/topics/migrations/#model-managers
|
# see https://docs.djangoproject.com/fr/stable/topics/migrations/#model-managers
|
||||||
@@ -271,24 +271,13 @@ class User(AbstractUser):
|
|||||||
parent_address = models.CharField(
|
parent_address = models.CharField(
|
||||||
_("parent address"), max_length=128, blank=True, default=""
|
_("parent address"), max_length=128, blank=True, default=""
|
||||||
)
|
)
|
||||||
is_viewable = models.BooleanField(
|
is_subscriber_viewable = models.BooleanField(
|
||||||
_("Profile visible by subscribers"),
|
_("is subscriber viewable"), default=True
|
||||||
help_text=_(
|
|
||||||
"If you disable this option, only admin users "
|
|
||||||
"will be able to see your profile."
|
|
||||||
),
|
|
||||||
default=True,
|
|
||||||
)
|
)
|
||||||
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
||||||
|
|
||||||
objects = CustomUserManager()
|
objects = CustomUserManager()
|
||||||
|
|
||||||
class Meta(AbstractUser.Meta):
|
|
||||||
abstract = False
|
|
||||||
permissions = [
|
|
||||||
("view_hidden_user", "Can view hidden users"),
|
|
||||||
]
|
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.get_display_name()
|
return self.get_display_name()
|
||||||
|
|
||||||
@@ -562,12 +551,8 @@ class User(AbstractUser):
|
|||||||
def can_be_edited_by(self, user):
|
def can_be_edited_by(self, user):
|
||||||
return user.is_root or user.is_board_member
|
return user.is_root or user.is_board_member
|
||||||
|
|
||||||
def can_be_viewed_by(self, user: User) -> bool:
|
def can_be_viewed_by(self, user):
|
||||||
return (
|
return (user.was_subscribed and self.is_subscriber_viewable) or user.is_root
|
||||||
user.id == self.id
|
|
||||||
or user.has_perm("core.view_hidden_user")
|
|
||||||
or (user.has_perm("core.view_user") and self.is_viewable)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_mini_item(self):
|
def get_mini_item(self):
|
||||||
return """
|
return """
|
||||||
@@ -1334,9 +1319,6 @@ class PageRev(models.Model):
|
|||||||
The content is in PageRev.title and PageRev.content .
|
The content is in PageRev.title and PageRev.content .
|
||||||
"""
|
"""
|
||||||
|
|
||||||
MERGE_TIME_THRESHOLD: Final[timedelta] = timedelta(minutes=20)
|
|
||||||
MERGE_DIFF_THRESHOLD: Final[float] = 0.2
|
|
||||||
|
|
||||||
revision = models.IntegerField(_("revision"))
|
revision = models.IntegerField(_("revision"))
|
||||||
title = models.CharField(_("page title"), max_length=255, blank=True)
|
title = models.CharField(_("page title"), max_length=255, blank=True)
|
||||||
content = models.TextField(_("page content"), blank=True)
|
content = models.TextField(_("page content"), blank=True)
|
||||||
@@ -1378,32 +1360,6 @@ class PageRev(models.Model):
|
|||||||
def is_owned_by(self, user: User) -> bool:
|
def is_owned_by(self, user: User) -> bool:
|
||||||
return any(g.id == self.page.owner_group_id for g in user.cached_groups)
|
return any(g.id == self.page.owner_group_id for g in user.cached_groups)
|
||||||
|
|
||||||
def similarity_ratio(self, text: str) -> float:
|
|
||||||
"""Similarity ratio between this revision's content and the given text.
|
|
||||||
|
|
||||||
The result is a float in [0; 1], 0 meaning the contents are entirely different,
|
|
||||||
and 1 they are strictly the same.
|
|
||||||
"""
|
|
||||||
# cf. https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio
|
|
||||||
return difflib.SequenceMatcher(None, self.content, text).quick_ratio()
|
|
||||||
|
|
||||||
def should_merge(self, other: Self) -> bool:
|
|
||||||
"""Return True if `other` should be merged into `self`, else False.
|
|
||||||
|
|
||||||
It's considered the other revision should be merged into this one if :
|
|
||||||
|
|
||||||
- it was made less than 20 minutes after
|
|
||||||
- by the same author
|
|
||||||
- with a similarity ratio higher than 80%
|
|
||||||
"""
|
|
||||||
return (
|
|
||||||
not self._state.adding # cannot merge if the original rev doesn't exist
|
|
||||||
and self.author == other.author
|
|
||||||
and (other.date - self.date) < self.MERGE_TIME_THRESHOLD
|
|
||||||
and (not other._state.adding or other.revision == self.revision + 1)
|
|
||||||
and self.similarity_ratio(other.content) >= (1 - other.MERGE_DIFF_THRESHOLD)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def get_notification_types():
|
def get_notification_types():
|
||||||
return settings.SITH_NOTIFICATIONS
|
return settings.SITH_NOTIFICATIONS
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ from pydantic_core.core_schema import ValidationInfo
|
|||||||
from core.models import Group, QuickUploadImage, SithFile, User
|
from core.models import Group, QuickUploadImage, SithFile, User
|
||||||
from core.utils import is_image
|
from core.utils import is_image
|
||||||
|
|
||||||
NonEmptyStr = Annotated[str, MinLen(1)]
|
|
||||||
|
|
||||||
|
|
||||||
class UploadedImage(UploadedFile):
|
class UploadedImage(UploadedFile):
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -21,8 +21,6 @@ $secondary-neutral-dark-color: hsl(40, 57.6%, 17%);
|
|||||||
|
|
||||||
$white-color: hsl(219.6, 20.8%, 98%);
|
$white-color: hsl(219.6, 20.8%, 98%);
|
||||||
$black-color: hsl(0, 0%, 17%);
|
$black-color: hsl(0, 0%, 17%);
|
||||||
$red-text-color: #eb2f06;
|
|
||||||
$hovered-red-text-color: #ff4d4d;
|
|
||||||
|
|
||||||
$faceblue: hsl(221, 44%, 41%);
|
$faceblue: hsl(221, 44%, 41%);
|
||||||
$twitblue: hsl(206, 82%, 63%);
|
$twitblue: hsl(206, 82%, 63%);
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ footer.bottom-links {
|
|||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
background-color: $primary-neutral-dark-color;
|
background-color: $primary-neutral-dark-color;
|
||||||
box-shadow: $shadow-color 0 0 15px;
|
box-shadow: black 0 8px 15px;
|
||||||
|
|
||||||
a {
|
a {
|
||||||
color: $white-color;
|
color: $white-color;
|
||||||
|
|||||||
@@ -745,32 +745,4 @@ form {
|
|||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
background-size: var(--nf-input-size);
|
background-size: var(--nf-input-size);
|
||||||
}
|
}
|
||||||
|
|
||||||
&.no-margin {
|
|
||||||
margin:0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// a submit input that should look like a regular <a>
|
|
||||||
input[type="submit"], button {
|
|
||||||
&.link-like {
|
|
||||||
color: $primary-dark-color;
|
|
||||||
&:hover {
|
|
||||||
color: $primary-light-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.link-red {
|
|
||||||
color: $red-text-color;
|
|
||||||
&:hover {
|
|
||||||
color: $hovered-red-text-color;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
font-weight: normal;
|
|
||||||
font-size: 100%;
|
|
||||||
margin: auto;
|
|
||||||
background: none;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,14 @@ $text-color: white;
|
|||||||
|
|
||||||
$background-color-hovered: #283747;
|
$background-color-hovered: #283747;
|
||||||
|
|
||||||
|
$red-text-color: #eb2f06;
|
||||||
|
$hovered-red-text-color: #ff4d4d;
|
||||||
|
|
||||||
.header {
|
.header {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
background-color: $deepblue;
|
background-color: $deepblue;
|
||||||
box-shadow: 3px 3px 3px 0 #dfdfdf;
|
box-shadow: black 0 1px 3px 0,
|
||||||
|
black 0 4px 8px 3px;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -96,7 +100,7 @@ $background-color-hovered: #283747;
|
|||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
background-color: $deepblue;
|
background-color: transparent;
|
||||||
width: 45px;
|
width: 45px;
|
||||||
height: 25px;
|
height: 25px;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
@@ -248,15 +252,12 @@ $background-color-hovered: #283747;
|
|||||||
justify-content: flex-start;
|
justify-content: flex-start;
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
|
||||||
color: $text-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
a,
|
a,
|
||||||
button {
|
button {
|
||||||
font-size: 100%;
|
font-size: 100%;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
|
color: $text-color;
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
@@ -268,6 +269,19 @@ $background-color-hovered: #283747;
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
display: inline;
|
display: inline;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#logout-form button {
|
||||||
|
color: $red-text-color;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: $hovered-red-text-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -318,7 +332,7 @@ $background-color-hovered: #283747;
|
|||||||
padding: 10px;
|
padding: 10px;
|
||||||
z-index: 100;
|
z-index: 100;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
box-shadow: 3px 3px 3px 0 #767676;
|
@include shadow;
|
||||||
|
|
||||||
>ul {
|
>ul {
|
||||||
list-style-type: none;
|
list-style-type: none;
|
||||||
|
|||||||
BIN
core/static/core/img/gala25_background.webp
Normal file
BIN
core/static/core/img/gala25_background.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 298 KiB |
BIN
core/static/core/img/gala25_logo.webp
Normal file
BIN
core/static/core/img/gala25_logo.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
@@ -271,8 +271,9 @@ body {
|
|||||||
|
|
||||||
/*--------------------------------CONTENT------------------------------*/
|
/*--------------------------------CONTENT------------------------------*/
|
||||||
#content {
|
#content {
|
||||||
padding: 1em 1%;
|
padding: 1.5em 2%;
|
||||||
box-shadow: $shadow-color 0 5px 10px;
|
border-radius: 5px;
|
||||||
|
box-shadow: black 0 8px 15px;
|
||||||
background: $white-color;
|
background: $white-color;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
}
|
}
|
||||||
@@ -519,6 +520,7 @@ th {
|
|||||||
td {
|
td {
|
||||||
margin: 5px;
|
margin: 5px;
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
|
vertical-align: top;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
|
|
||||||
|
|||||||
@@ -7,13 +7,10 @@
|
|||||||
.profile {
|
.profile {
|
||||||
&-visible {
|
&-visible {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
padding-top: 10px;
|
padding-top: 10px;
|
||||||
input[type="checkbox"]+label {
|
|
||||||
max-width: unset;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
&-pictures {
|
&-pictures {
|
||||||
@@ -119,19 +116,23 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: var(--nf-input-size) 10px;
|
gap: 10px;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
&-field {
|
&-field {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
gap: 10px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 330px;
|
max-width: 330px;
|
||||||
min-width: 300px;
|
min-width: 300px;
|
||||||
|
|
||||||
@media (max-width: 750px) {
|
@media (max-width: 750px) {
|
||||||
|
gap: 4px;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,6 +145,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&-label {
|
||||||
|
text-align: left !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
&-content {
|
||||||
|
> * {
|
||||||
|
box-sizing: border-box;
|
||||||
|
text-align: left !important;
|
||||||
|
margin: 0;
|
||||||
|
|
||||||
|
> * {
|
||||||
|
text-align: left !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
textarea {
|
textarea {
|
||||||
height: 7rem;
|
height: 7rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,18 @@
|
|||||||
|
|
||||||
{% block additional_css %}{% endblock %}
|
{% block additional_css %}{% endblock %}
|
||||||
{% block additional_js %}{% endblock %}
|
{% block additional_js %}{% endblock %}
|
||||||
|
<style>
|
||||||
|
{# background image must be declared here, because the static names are
|
||||||
|
changed during the static collection step,
|
||||||
|
which means we must gather them with the `static` template function #}
|
||||||
|
.header {
|
||||||
|
background-image: url("{{ static("core/img/gala25_background.webp") }}");
|
||||||
|
background-position-y: 80%; {# There are more stars in this part of the picture #}
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
background-image: url("{{ static("core/img/gala25_background.webp") }}");
|
||||||
|
}
|
||||||
|
</style>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<header class="header">
|
<header class="header">
|
||||||
<div class="header-logo">
|
<div class="header-logo">
|
||||||
<a class="header-logo-picture" href="{{ url('core:index') }}" style="background-image: url('{{ static('core/img/logo_no_text.png') }}')">
|
<a class="header-logo-picture" href="{{ url('core:index') }}" style="background-image: url('{{ static("core/img/gala25_logo.webp") }}')">
|
||||||
|
|
||||||
</a>
|
</a>
|
||||||
<a class="header-logo-text" href="{{ url('core:index') }}">
|
<a class="header-logo-text" href="{{ url('core:index') }}">
|
||||||
@@ -61,9 +61,7 @@
|
|||||||
<a href="{{ url('core:user_tools') }}">{% trans %}Tools{% endtrans %}</a>
|
<a href="{{ url('core:user_tools') }}">{% trans %}Tools{% endtrans %}</a>
|
||||||
<form id="logout-form" method="post" action="{{ url("core:logout") }}">
|
<form id="logout-form" method="post" action="{{ url("core:logout") }}">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<button type="submit" class="link-like link-red">
|
<button type="submit">{% trans %}Logout{% endtrans %}</button>
|
||||||
{% trans %}Logout{% endtrans %}
|
|
||||||
</button>
|
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -17,3 +17,12 @@
|
|||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
</ul>
|
</ul>
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
|
{% macro page_edit_form(page, form, url, token) %}
|
||||||
|
<h2>{% trans %}Edit page{% endtrans %}</h2>
|
||||||
|
<form action="{{ url }}" method="post">
|
||||||
|
<input type="hidden" name="csrfmiddlewaretoken" value="{{ token }}">
|
||||||
|
{{ form.as_p() }}
|
||||||
|
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
||||||
|
</form>
|
||||||
|
{% endmacro %}
|
||||||
64
core/templates/core/page.jinja
Normal file
64
core/templates/core/page.jinja
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
{% extends "core/base.jinja" %}
|
||||||
|
|
||||||
|
{% block title %}
|
||||||
|
{% if page %}
|
||||||
|
{{ page.get_display_name() }}
|
||||||
|
{% elif page_list %}
|
||||||
|
{% trans %}Page list{% endtrans %}
|
||||||
|
{% elif new_page %}
|
||||||
|
{% trans %}Create page{% endtrans %}
|
||||||
|
{% else %}
|
||||||
|
{% trans %}Not found{% endtrans %}
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block metatags %}
|
||||||
|
{% if page %}
|
||||||
|
<meta property="og:url" content="{{ request.build_absolute_uri(page.get_absolute_url()) }}" />
|
||||||
|
<meta property="og:type" content="article" />
|
||||||
|
<meta property="article:section" content="{% trans %}Page{% endtrans %}" />
|
||||||
|
<meta property="og:title" content="{{ page.get_display_name() }}" />
|
||||||
|
<meta property="og:image" content="{{ request.build_absolute_uri(static("core/img/logo_no_text.png")) }}" />
|
||||||
|
{% else %}
|
||||||
|
{{ super() }}
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{%- macro print_page_name(page) -%}
|
||||||
|
{%- if page -%}
|
||||||
|
{{ print_page_name(page.parent) }} >
|
||||||
|
<a href="{{ url('core:page', page_name=page.get_full_name()) }}">{{ page.get_display_name() }}</a>
|
||||||
|
{%- endif -%}
|
||||||
|
{%- endmacro -%}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{{ print_page_name(page) }}
|
||||||
|
<div class="tool_bar">
|
||||||
|
<div class="tools">
|
||||||
|
{% if page %}
|
||||||
|
{% if page.club %}
|
||||||
|
<a href="{{ url('club:club_view', club_id=page.club.id) }}">{% trans %}Return to club management{% endtrans %}</a>
|
||||||
|
{% else %}
|
||||||
|
<a href="{{ url('core:page', page.get_full_name()) }}">{% trans %}View{% endtrans %}</a>
|
||||||
|
{% endif %}
|
||||||
|
<a href="{{ url('core:page_hist', page_name=page.get_full_name()) }}">{% trans %}History{% endtrans %}</a>
|
||||||
|
{% if can_edit(page, user) %}
|
||||||
|
<a href="{{ url('core:page_edit', page_name=page.get_full_name()) }}">{% trans %}Edit{% endtrans %}</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if can_edit_prop(page, user) and not page.is_club_page %}
|
||||||
|
<a href="{{ url('core:page_prop', page_name=page.get_full_name()) }}">{% trans %}Prop{% endtrans %}</a>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
{% if page %}
|
||||||
|
{% block page %}
|
||||||
|
{% endblock %}
|
||||||
|
{% else %}
|
||||||
|
<h2>{% trans %}Page does not exist{% endtrans %}</h2>
|
||||||
|
<p><a href="{{ url('core:page_new') }}?page={{ request.resolver_match.kwargs['page_name'] }}">
|
||||||
|
{% trans %}Create it?{% endtrans %}</a></p>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{{ page.get_display_name() }}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block metatags %}
|
|
||||||
<meta property="og:url" content="{{ request.build_absolute_uri(page.get_absolute_url()) }}" />
|
|
||||||
<meta property="og:type" content="article" />
|
|
||||||
<meta property="article:section" content="{% trans %}Page{% endtrans %}" />
|
|
||||||
<meta property="og:title" content="{{ page.get_display_name() }}" />
|
|
||||||
<meta property="og:image" content="{{ request.build_absolute_uri(static("core/img/logo_no_text.png")) }}" />
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{%- macro print_page_name(page) -%}
|
|
||||||
{%- if page -%}
|
|
||||||
{{ print_page_name(page.parent) }} >
|
|
||||||
<a href="{{ url('core:page', page_name=page.get_full_name()) }}">{{ page.get_display_name() }}</a>
|
|
||||||
{%- endif -%}
|
|
||||||
{%- endmacro -%}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
{{ print_page_name(page) }}
|
|
||||||
<div class="tool_bar">
|
|
||||||
<div class="tools">
|
|
||||||
{% if page.club %}
|
|
||||||
<a href="{{ url('club:club_view', club_id=page.club.id) }}">{% trans %}Return to club management{% endtrans %}</a>
|
|
||||||
{% else %}
|
|
||||||
<a href="{{ url('core:page', page.get_full_name()) }}">{% trans %}View{% endtrans %}</a>
|
|
||||||
{% endif %}
|
|
||||||
<a href="{{ url('core:page_hist', page_name=page.get_full_name()) }}">{% trans %}History{% endtrans %}</a>
|
|
||||||
{% if can_edit(page, user) %}
|
|
||||||
<a href="{{ url('core:page_edit', page_name=page.get_full_name()) }}">{% trans %}Edit{% endtrans %}</a>
|
|
||||||
{% endif %}
|
|
||||||
{% if can_edit_prop(page, user) and not page.is_club_page %}
|
|
||||||
<a href="{{ url('core:page_prop', page_name=page.get_full_name()) }}">{% trans %}Prop{% endtrans %}</a>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
{% block page %}
|
|
||||||
{% endblock %}
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
{% extends "core/page/base.jinja" %}
|
|
||||||
|
|
||||||
{% block page %}
|
|
||||||
{% if revision and revision.id != last_revision.id %}
|
|
||||||
<h4>
|
|
||||||
{% trans trimmed rev_id=revision.revision %}
|
|
||||||
This may not be the last update, you are seeing revision {{ rev_id }}!
|
|
||||||
{% endtrans %}
|
|
||||||
</h4>
|
|
||||||
{% endif %}
|
|
||||||
{% set current_revision = revision or last_revision %}
|
|
||||||
<h3>{{ current_revision.title }}</h3>
|
|
||||||
<div class="page_content">{{ current_revision.content|markdown }}</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
{% extends "core/page/base.jinja" %}
|
|
||||||
|
|
||||||
{% block page %}
|
|
||||||
<h2>{% trans %}Edit page{% endtrans %}</h2>
|
|
||||||
<form action="{{ url('core:page_edit', page_name=page.get_full_name()) }}" method="post">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.as_p() }}
|
|
||||||
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2>{% trans %}Page does not exist{% endtrans %}</h2>
|
|
||||||
<p>
|
|
||||||
{# This template is rendered when a PageNotFound error is raised,
|
|
||||||
so the `exception` context variable should always have a page_name attribute #}
|
|
||||||
<a href="{{ url('core:page_new') }}?page={{ exception.page_name }}">
|
|
||||||
{% trans %}Create it?{% endtrans %}
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
{% endblock %}
|
|
||||||
17
core/templates/core/page_detail.jinja
Normal file
17
core/templates/core/page_detail.jinja
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
{% extends "core/page.jinja" %}
|
||||||
|
|
||||||
|
{% block page %}
|
||||||
|
{% if rev %}
|
||||||
|
<h4>{% trans rev_id=rev.revision %}This may not be the last update, you are seeing revision {{ rev_id }}!{% endtrans %}</h4>
|
||||||
|
<h3>{{ rev.title }}</h3>
|
||||||
|
<div class="page_content">{{ rev.content|markdown }}</div>
|
||||||
|
{% else %}
|
||||||
|
{% if page.revisions.last() %}
|
||||||
|
<h3>{{ page.revisions.last().title }}</h3>
|
||||||
|
<div class="page_content">{{ page.revisions.last().content|markdown }}</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "core/page/base.jinja" %}
|
{% extends "core/page.jinja" %}
|
||||||
|
|
||||||
{% from "core/page/macros.jinja" import page_history %}
|
{% from "core/macros_pages.jinja" import page_history %}
|
||||||
|
|
||||||
{% block page %}
|
{% block page %}
|
||||||
<h3>{% trans %}Page history{% endtrans %}</h3>
|
<h3>{% trans %}Page history{% endtrans %}</h3>
|
||||||
@@ -1,13 +1,18 @@
|
|||||||
{% extends "core/page/base.jinja" %}
|
{% extends "core/page.jinja" %}
|
||||||
|
|
||||||
{% block page %}
|
{% block content %}
|
||||||
|
{% if page %}
|
||||||
|
{{ super() }}
|
||||||
|
{% endif %}
|
||||||
<h2>{% trans %}Page properties{% endtrans %}</h2>
|
<h2>{% trans %}Page properties{% endtrans %}</h2>
|
||||||
<form action="" method="post">
|
<form action="" method="post">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{{ form.as_p() }}
|
{{ form.as_p() }}
|
||||||
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
||||||
</form>
|
</form>
|
||||||
<a href="{{ url('core:page_delete', page_id=page.id)}}">{% trans %}Delete{% endtrans %}</a>
|
{% if page %}
|
||||||
|
<a href="{{ url('core:page_delete', page_id=page.id)}}">{% trans %}Delete{% endtrans %}</a>
|
||||||
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
9
core/templates/core/pagerev_edit.jinja
Normal file
9
core/templates/core/pagerev_edit.jinja
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{% extends "core/page.jinja" %}
|
||||||
|
{% from 'core/macros_pages.jinja' import page_edit_form %}
|
||||||
|
|
||||||
|
{% block page %}
|
||||||
|
{{ page_edit_form(page, form, url('core:page_edit', page_name=page.get_full_name()), csrf_token) }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -9,17 +9,19 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
<h4>{% trans %}Users{% endtrans %}</h4>
|
<h4>{% trans %}Users{% endtrans %}</h4>
|
||||||
<ul>
|
<ul>
|
||||||
{% for user in users %}
|
{% for i in result.users %}
|
||||||
<li>
|
{% if user.can_view(i) %}
|
||||||
{{ user_link_with_pict(user) }}
|
<li>
|
||||||
</li>
|
{{ user_link_with_pict(i) }}
|
||||||
|
</li>
|
||||||
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</ul>
|
||||||
<h4>{% trans %}Clubs{% endtrans %}</h4>
|
<h4>{% trans %}Clubs{% endtrans %}</h4>
|
||||||
<ul>
|
<ul>
|
||||||
{% for club in clubs %}
|
{% for i in result.clubs %}
|
||||||
<li>
|
<li>
|
||||||
<a href="{{ url("club:club_view", club_id=club.id) }}">{{ club }}</a>
|
<a href="{{ url("club:club_view", club_id=i.id) }}">{{ i }}</a>
|
||||||
</li>
|
</li>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -17,9 +17,7 @@
|
|||||||
<td>{% trans %}Description{% endtrans %}</td>
|
<td>{% trans %}Description{% endtrans %}</td>
|
||||||
<td>{% trans %}Since{% endtrans %}</td>
|
<td>{% trans %}Since{% endtrans %}</td>
|
||||||
<td></td>
|
<td></td>
|
||||||
{% if user.has_perm("club.delete_membership") %}
|
<td></td>
|
||||||
<td></td>
|
|
||||||
{% endif %}
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -30,16 +28,7 @@
|
|||||||
<td>{{ m.description }}</td>
|
<td>{{ m.description }}</td>
|
||||||
<td>{{ m.start_date }}</td>
|
<td>{{ m.start_date }}</td>
|
||||||
{% if m.can_be_edited_by(user) %}
|
{% if m.can_be_edited_by(user) %}
|
||||||
<td>
|
<td><a href="{{ url('club:membership_set_old', membership_id=m.id) }}">{% trans %}Mark as old{% endtrans %}</a></td>
|
||||||
<form
|
|
||||||
method="post"
|
|
||||||
action="{{ url('club:membership_set_old', membership_id=m.id) }}"
|
|
||||||
class="no-margin"
|
|
||||||
>
|
|
||||||
{% csrf_token %}
|
|
||||||
<input type="submit" class="link-like" value="{% trans %}Mark as old{% endtrans %}" />
|
|
||||||
</form>
|
|
||||||
</td>
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if user.has_perm("club.delete_membership") %}
|
{% if user.has_perm("club.delete_membership") %}
|
||||||
<td><a href="{{ url('club:membership_delete', membership_id=m.id) }}">{% trans %}Delete{% endtrans %}</a></td>
|
<td><a href="{{ url('club:membership_delete', membership_id=m.id) }}">{% trans %}Delete{% endtrans %}</a></td>
|
||||||
@@ -59,9 +48,7 @@
|
|||||||
<td>{% trans %}Description{% endtrans %}</td>
|
<td>{% trans %}Description{% endtrans %}</td>
|
||||||
<td>{% trans %}From{% endtrans %}</td>
|
<td>{% trans %}From{% endtrans %}</td>
|
||||||
<td>{% trans %}To{% endtrans %}</td>
|
<td>{% trans %}To{% endtrans %}</td>
|
||||||
{% if user.has_perm("club.delete_membership") %}
|
|
||||||
<td></td>
|
|
||||||
{% endif %}
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
|
|||||||
@@ -116,12 +116,12 @@
|
|||||||
{# All fields #}
|
{# All fields #}
|
||||||
<div class="profile-fields">
|
<div class="profile-fields">
|
||||||
{%- for field in form -%}
|
{%- for field in form -%}
|
||||||
{%- if field.name in ["quote","profile_pict","avatar_pict","scrub_pict","is_viewable","forum_signature"] -%}
|
{%- if field.name in ["quote","profile_pict","avatar_pict","scrub_pict","is_subscriber_viewable","forum_signature"] -%}
|
||||||
{%- continue -%}
|
{%- continue -%}
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
|
|
||||||
<div class="profile-field">
|
<div class="profile-field">
|
||||||
{{ field.label_tag() }}
|
<div class="profile-field-label">{{ field.label }}</div>
|
||||||
<div class="profile-field-content">
|
<div class="profile-field-content">
|
||||||
{{ field }}
|
{{ field }}
|
||||||
{%- if field.errors -%}
|
{%- if field.errors -%}
|
||||||
@@ -136,7 +136,7 @@
|
|||||||
<div class="profile-fields">
|
<div class="profile-fields">
|
||||||
{%- for field in [form.quote, form.forum_signature] -%}
|
{%- for field in [form.quote, form.forum_signature] -%}
|
||||||
<div class="profile-field">
|
<div class="profile-field">
|
||||||
{{ field.label_tag() }}
|
<div class="profile-field-label">{{ field.label }}</div>
|
||||||
<div class="profile-field-content">
|
<div class="profile-field-content">
|
||||||
{{ field }}
|
{{ field }}
|
||||||
{%- if field.errors -%}
|
{%- if field.errors -%}
|
||||||
@@ -149,13 +149,8 @@
|
|||||||
|
|
||||||
{# Checkboxes #}
|
{# Checkboxes #}
|
||||||
<div class="profile-visible">
|
<div class="profile-visible">
|
||||||
<div class="row">
|
{{ form.is_subscriber_viewable }}
|
||||||
{{ form.is_viewable }}
|
{{ form.is_subscriber_viewable.label }}
|
||||||
{{ form.is_viewable.label_tag() }}
|
|
||||||
</div>
|
|
||||||
<span class="helptext">
|
|
||||||
{{ form.is_viewable.help_text }}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="final-actions">
|
<div class="final-actions">
|
||||||
|
|
||||||
|
|||||||
@@ -11,35 +11,32 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
{% if total_perm_time %}
|
{% if profile.permanencies %}
|
||||||
<div>
|
<div>
|
||||||
<h3>{% trans %}Permanencies{% endtrans %}</h3>
|
<h3>{% trans %}Permanencies{% endtrans %}</h3>
|
||||||
<div class="flexed">
|
<div class="flexed">
|
||||||
{% for perm in perm_time %}
|
<div><span>Foyer :</span><span>{{ total_foyer_time }}</span></div>
|
||||||
<div>
|
<div><span>Gommette :</span><span>{{ total_gommette_time }}</span></div>
|
||||||
<span>{{ perm["counter__name"] }} :</span>
|
<div><span>MDE :</span><span>{{ total_mde_time }}</span></div>
|
||||||
<span>{{ perm["total"]|format_timedelta }}</span>
|
<div><b>Total :</b><b>{{ total_perm_time }}</b></div>
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
<div><b>Total :</b><b>{{ total_perm_time|format_timedelta }}</b></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<h3>{% trans %}Buyings{% endtrans %}</h3>
|
<h3>{% trans %}Buyings{% endtrans %}</h3>
|
||||||
<div class="flexed">
|
<div class="flexed">
|
||||||
{% for sum in purchase_sums %}
|
<div><span>Foyer :</span><span>{{ total_foyer_buyings }} €</span></div>
|
||||||
<div>
|
<div><span>Gommette :</span><span>{{ total_gommette_buyings }} €</span></div>
|
||||||
<span>{{ sum["counter__name"] }}</span>
|
<div><span>MDE :</span><span>{{ total_mde_buyings }} €</span></div>
|
||||||
<span>{{ sum["total"] }} €</span>
|
<div><b>Total :</b><b>{{ total_foyer_buyings + total_gommette_buyings + total_mde_buyings }} €</b>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
|
||||||
<div><b>Total : </b><b>{{ total_purchases }} €</b></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<h3>{% trans %}Product top 15{% endtrans %}</h3>
|
<h3>{% trans %}Product top 10{% endtrans %}</h3>
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
|
|||||||
@@ -55,17 +55,31 @@ def phonenumber(
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
@register.filter(name="truncate_time")
|
||||||
|
def truncate_time(value, time_unit):
|
||||||
|
"""Remove everything in the time format lower than the specified unit.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
value: the value to truncate
|
||||||
|
time_unit: the lowest unit to display
|
||||||
|
"""
|
||||||
|
value = str(value)
|
||||||
|
return {
|
||||||
|
"millis": lambda: value.split(".")[0],
|
||||||
|
"seconds": lambda: value.rsplit(":", maxsplit=1)[0],
|
||||||
|
"minutes": lambda: value.split(":", maxsplit=1)[0],
|
||||||
|
"hours": lambda: value.rsplit(" ")[0],
|
||||||
|
}[time_unit]()
|
||||||
|
|
||||||
|
|
||||||
@register.filter(name="format_timedelta")
|
@register.filter(name="format_timedelta")
|
||||||
def format_timedelta(value: datetime.timedelta) -> str:
|
def format_timedelta(value: datetime.timedelta) -> str:
|
||||||
value = value - datetime.timedelta(microseconds=value.microseconds)
|
|
||||||
days = value.days
|
days = value.days
|
||||||
if days == 0:
|
if days == 0:
|
||||||
return str(value)
|
return str(value)
|
||||||
remainder = value - datetime.timedelta(days=days)
|
remainder = value - datetime.timedelta(days=days)
|
||||||
return ngettext(
|
return ngettext(
|
||||||
"%(nb_days)d day, %(remainder)s",
|
"%(nb_days)d day, %(remainder)s", "%(nb_days)d days, %(remainder)s", days
|
||||||
"%(nb_days)d days, %(remainder)s",
|
|
||||||
days,
|
|
||||||
) % {"nb_days": days, "remainder": str(remainder)}
|
) % {"nb_days": days, "remainder": str(remainder)}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ from django.contrib.auth.hashers import make_password
|
|||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.core import mail
|
from django.core import mail
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.core.exceptions import ValidationError
|
|
||||||
from django.core.mail import EmailMessage
|
from django.core.mail import EmailMessage
|
||||||
from django.test import Client, RequestFactory, TestCase
|
from django.test import Client, RequestFactory, TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
@@ -35,10 +34,9 @@ from pytest_django.asserts import assertInHTML, assertRedirects
|
|||||||
|
|
||||||
from antispam.models import ToxicDomain
|
from antispam.models import ToxicDomain
|
||||||
from club.models import Club, Membership
|
from club.models import Club, Membership
|
||||||
from core.baker_recipes import subscriber_user
|
|
||||||
from core.markdown import markdown
|
from core.markdown import markdown
|
||||||
from core.models import AnonymousUser, Group, Page, User, validate_promo
|
from core.models import AnonymousUser, Group, Page, User
|
||||||
from core.utils import get_last_promo, get_semester_code, get_start_of_semester
|
from core.utils import get_semester_code, get_start_of_semester
|
||||||
from core.views import AllowFragment
|
from core.views import AllowFragment
|
||||||
from counter.models import Customer
|
from counter.models import Customer
|
||||||
from sith import settings
|
from sith import settings
|
||||||
@@ -320,8 +318,9 @@ class TestPageHandling(TestCase):
|
|||||||
def test_access_page_not_found(self):
|
def test_access_page_not_found(self):
|
||||||
"""Should not display a page correctly."""
|
"""Should not display a page correctly."""
|
||||||
response = self.client.get(reverse("core:page", kwargs={"page_name": "swagg"}))
|
response = self.client.get(reverse("core:page", kwargs={"page_name": "swagg"}))
|
||||||
assert response.status_code == 404
|
assert response.status_code == 200
|
||||||
assert '<a href="/page/create/?page=swagg">' in response.text
|
html = response.text
|
||||||
|
self.assertIn('<a href="/page/create/?page=swagg">', html)
|
||||||
|
|
||||||
def test_create_page_markdown_safe(self):
|
def test_create_page_markdown_safe(self):
|
||||||
"""Should format the markdown and escape html correctly."""
|
"""Should format the markdown and escape html correctly."""
|
||||||
@@ -524,21 +523,6 @@ class TestDateUtils(TestCase):
|
|||||||
assert get_start_of_semester() == autumn_2023
|
assert get_start_of_semester() == autumn_2023
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
("current_date", "promo"),
|
|
||||||
[("2020-10-01", 22), ("2025-03-01", 26), ("2000-11-11", 2)],
|
|
||||||
)
|
|
||||||
def test_get_last_promo(current_date: str, promo: int):
|
|
||||||
with freezegun.freeze_time(current_date):
|
|
||||||
assert get_last_promo() == promo
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("promo", [0, 24])
|
|
||||||
def test_promo_validator(promo: int):
|
|
||||||
with freezegun.freeze_time("2021-10-01"), pytest.raises(ValidationError):
|
|
||||||
validate_promo(promo)
|
|
||||||
|
|
||||||
|
|
||||||
def test_allow_fragment_mixin():
|
def test_allow_fragment_mixin():
|
||||||
class TestAllowFragmentView(AllowFragment, ContextMixin, View):
|
class TestAllowFragmentView(AllowFragment, ContextMixin, View):
|
||||||
def get(self, *args, **kwargs):
|
def get(self, *args, **kwargs):
|
||||||
@@ -552,10 +536,3 @@ def test_allow_fragment_mixin():
|
|||||||
assert not TestAllowFragmentView.as_view()(request)
|
assert not TestAllowFragmentView.as_view()(request)
|
||||||
request.headers = {"HX-Request": True, **base_headers}
|
request.headers = {"HX-Request": True, **base_headers}
|
||||||
assert TestAllowFragmentView.as_view()(request)
|
assert TestAllowFragmentView.as_view()(request)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_search_view(client: Client):
|
|
||||||
client.force_login(subscriber_user.make())
|
|
||||||
response = client.get(reverse("core:search", query={"query": "foo"}))
|
|
||||||
assert response.status_code == 200
|
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ class TestFetchFamilyApi(TestCase):
|
|||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
|
|
||||||
def test_fetch_family_hidden_user(self):
|
def test_fetch_family_hidden_user(self):
|
||||||
self.main_user.is_viewable = False
|
self.main_user.is_subscriber_viewable = False
|
||||||
self.main_user.save()
|
self.main_user.save()
|
||||||
for user_to_login, error_code in [
|
for user_to_login, error_code in [
|
||||||
(self.main_user, 200),
|
(self.main_user, 200),
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
from datetime import timedelta
|
|
||||||
from operator import attrgetter
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from bs4 import BeautifulSoup
|
|
||||||
from django.test import Client, TestCase
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.utils.timezone import now
|
|
||||||
from model_bakery import baker, seq
|
|
||||||
from pytest_django.asserts import assertRedirects
|
|
||||||
|
|
||||||
from core.baker_recipes import subscriber_user
|
|
||||||
from core.models import Notification
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
class TestNotificationList(TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpTestData(cls):
|
|
||||||
cls.user = subscriber_user.make()
|
|
||||||
url = reverse("core:user_profile", kwargs={"user_id": cls.user.id})
|
|
||||||
cls.notifs = baker.make(
|
|
||||||
Notification,
|
|
||||||
user=cls.user,
|
|
||||||
url=url,
|
|
||||||
viewed=False,
|
|
||||||
date=seq(now() - timedelta(days=1), timedelta(hours=1)),
|
|
||||||
_quantity=10,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_list(self):
|
|
||||||
self.client.force_login(self.user)
|
|
||||||
response = self.client.get(reverse("core:notification_list"))
|
|
||||||
assert response.status_code == 200
|
|
||||||
soup = BeautifulSoup(response.text, "lxml")
|
|
||||||
ul = soup.find("ul", id="notifications")
|
|
||||||
elements = list(ul.find_all("li"))
|
|
||||||
assert len(elements) == len(self.notifs)
|
|
||||||
notifs = sorted(self.notifs, key=attrgetter("date"), reverse=True)
|
|
||||||
for element, notif in zip(elements, notifs, strict=True):
|
|
||||||
assert element.find("a")["href"] == reverse(
|
|
||||||
"core:notification", kwargs={"notif_id": notif.id}
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_read_all(self):
|
|
||||||
self.client.force_login(self.user)
|
|
||||||
response = self.client.get(
|
|
||||||
reverse("core:notification_list", query={"read_all": None})
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert not self.user.notifications.filter(viewed=True).exists()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_notification_redirect(client: Client):
|
|
||||||
user = subscriber_user.make()
|
|
||||||
url = reverse("core:user_profile", kwargs={"user_id": user.id})
|
|
||||||
notif = baker.make(Notification, user=user, url=url, viewed=False)
|
|
||||||
client.force_login(user)
|
|
||||||
response = client.get(reverse("core:notification", kwargs={"notif_id": notif.id}))
|
|
||||||
assertRedirects(response, url)
|
|
||||||
notif.refresh_from_db()
|
|
||||||
assert notif.viewed is True
|
|
||||||
@@ -1,122 +1,32 @@
|
|||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
import freezegun
|
|
||||||
import pytest
|
import pytest
|
||||||
from bs4 import BeautifulSoup
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.test import Client
|
from django.test import Client
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.timezone import now
|
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
from pytest_django.asserts import assertRedirects
|
||||||
|
|
||||||
from club.models import Club
|
|
||||||
from core.baker_recipes import board_user, subscriber_user
|
from core.baker_recipes import board_user, subscriber_user
|
||||||
from core.markdown import markdown
|
from core.models import AnonymousUser, Page, User
|
||||||
from core.models import AnonymousUser, Page, PageRev, User
|
from sith.settings import SITH_GROUP_OLD_SUBSCRIBERS_ID, SITH_GROUP_SUBSCRIBERS_ID
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
class TestEditPage:
|
def test_edit_page(client: Client):
|
||||||
def test_edit_page(self, client: Client):
|
user = board_user.make()
|
||||||
user = board_user.make()
|
|
||||||
page = baker.prepare(Page)
|
|
||||||
page.save(force_lock=True)
|
|
||||||
page.view_groups.add(user.groups.first())
|
|
||||||
page.edit_groups.add(user.groups.first())
|
|
||||||
client.force_login(user)
|
|
||||||
|
|
||||||
url = reverse("core:page_edit", kwargs={"page_name": page._full_name})
|
|
||||||
res = client.get(url)
|
|
||||||
assert res.status_code == 200
|
|
||||||
|
|
||||||
res = client.post(url, data={"content": "Hello World"})
|
|
||||||
assertRedirects(
|
|
||||||
res, reverse("core:page", kwargs={"page_name": page._full_name})
|
|
||||||
)
|
|
||||||
revision = page.revisions.last()
|
|
||||||
assert revision.content == "Hello World"
|
|
||||||
|
|
||||||
def test_pagerev_reused(self, client):
|
|
||||||
"""Test that the previous revision is edited, if same author and small time diff"""
|
|
||||||
user = baker.make(User, is_superuser=True)
|
|
||||||
page = baker.prepare(Page)
|
|
||||||
page.save(force_lock=True)
|
|
||||||
first_rev = baker.make(
|
|
||||||
PageRev, author=user, page=page, date=now(), content="Hello World"
|
|
||||||
)
|
|
||||||
client.force_login(user)
|
|
||||||
url = reverse("core:page_edit", kwargs={"page_name": page._full_name})
|
|
||||||
client.post(url, data={"content": "Hello World!"})
|
|
||||||
assert page.revisions.count() == 1
|
|
||||||
assert page.revisions.last() == first_rev
|
|
||||||
first_rev.refresh_from_db()
|
|
||||||
assert first_rev.author == user
|
|
||||||
assert first_rev.content == "Hello World!"
|
|
||||||
|
|
||||||
def test_pagerev_not_reused(self, client):
|
|
||||||
"""Test that a new revision is created if too much time
|
|
||||||
passed since the last one.
|
|
||||||
"""
|
|
||||||
user = baker.make(User, is_superuser=True)
|
|
||||||
page = baker.prepare(Page)
|
|
||||||
page.save(force_lock=True)
|
|
||||||
first_rev = baker.make(PageRev, author=user, page=page, date=now())
|
|
||||||
client.force_login(user)
|
|
||||||
url = reverse("core:page_edit", kwargs={"page_name": page._full_name})
|
|
||||||
with freezegun.freeze_time(now() + timedelta(minutes=30)):
|
|
||||||
client.post(url, data={"content": "Hello World"})
|
|
||||||
assert page.revisions.count() == 2
|
|
||||||
assert page.revisions.last() != first_rev
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_page_revision(client: Client):
|
|
||||||
"""Test the GET to request to a specific revision page."""
|
|
||||||
page = baker.prepare(Page)
|
page = baker.prepare(Page)
|
||||||
page.save(force_lock=True)
|
page.save(force_lock=True)
|
||||||
page.view_groups.add(settings.SITH_GROUP_SUBSCRIBERS_ID)
|
page.view_groups.add(user.groups.first())
|
||||||
revisions = baker.make(
|
client.force_login(user)
|
||||||
PageRev, page=page, _quantity=3, content=iter(["foo", "bar", "baz"])
|
|
||||||
)
|
url = reverse("core:page_edit", kwargs={"page_name": page._full_name})
|
||||||
client.force_login(subscriber_user.make())
|
|
||||||
url = reverse(
|
|
||||||
"core:page_rev",
|
|
||||||
kwargs={"page_name": page._full_name, "rev": revisions[1].id},
|
|
||||||
)
|
|
||||||
res = client.get(url)
|
res = client.get(url)
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
soup = BeautifulSoup(res.text, "lxml")
|
|
||||||
detail_html = soup.find(class_="markdown")
|
|
||||||
assertHTMLEqual(detail_html.decode_contents(), markdown(revisions[1].content))
|
|
||||||
|
|
||||||
|
res = client.post(url, data={"content": "Hello World"})
|
||||||
@pytest.mark.django_db
|
assertRedirects(res, reverse("core:page", kwargs={"page_name": page._full_name}))
|
||||||
def test_page_club_redirection(client: Client):
|
revision = page.revisions.last()
|
||||||
club = baker.make(Club)
|
assert revision.content == "Hello World"
|
||||||
url = reverse("core:page", kwargs={"page_name": club.page._full_name})
|
|
||||||
res = client.get(url)
|
|
||||||
redirection_url = reverse("club:club_view", kwargs={"club_id": club.id})
|
|
||||||
assertRedirects(res, redirection_url)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_page_revision_club_redirection(client: Client):
|
|
||||||
client.force_login(subscriber_user.make())
|
|
||||||
club = baker.make(Club)
|
|
||||||
revisions = baker.make(
|
|
||||||
PageRev, page=club.page, _quantity=3, content=iter(["foo", "bar", "baz"])
|
|
||||||
)
|
|
||||||
url = reverse(
|
|
||||||
"core:page_rev",
|
|
||||||
kwargs={"page_name": club.page._full_name, "rev": revisions[1].id},
|
|
||||||
)
|
|
||||||
res = client.get(url)
|
|
||||||
redirection_url = reverse(
|
|
||||||
"club:club_view_rev", kwargs={"club_id": club.id, "rev_id": revisions[1].id}
|
|
||||||
)
|
|
||||||
assertRedirects(res, redirection_url)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -125,9 +35,9 @@ def test_viewable_by():
|
|||||||
Page.objects.all().delete()
|
Page.objects.all().delete()
|
||||||
view_groups = [
|
view_groups = [
|
||||||
[settings.SITH_GROUP_PUBLIC_ID],
|
[settings.SITH_GROUP_PUBLIC_ID],
|
||||||
[settings.SITH_GROUP_PUBLIC_ID, settings.SITH_GROUP_SUBSCRIBERS_ID],
|
[settings.SITH_GROUP_PUBLIC_ID, SITH_GROUP_SUBSCRIBERS_ID],
|
||||||
[settings.SITH_GROUP_SUBSCRIBERS_ID],
|
[SITH_GROUP_SUBSCRIBERS_ID],
|
||||||
[settings.SITH_GROUP_SUBSCRIBERS_ID, settings.SITH_GROUP_OLD_SUBSCRIBERS_ID],
|
[SITH_GROUP_SUBSCRIBERS_ID, SITH_GROUP_OLD_SUBSCRIBERS_ID],
|
||||||
[],
|
[],
|
||||||
]
|
]
|
||||||
pages = baker.make(Page, _quantity=len(view_groups), _bulk_create=True)
|
pages = baker.make(Page, _quantity=len(view_groups), _bulk_create=True)
|
||||||
@@ -146,11 +56,3 @@ def test_viewable_by():
|
|||||||
)
|
)
|
||||||
viewable = Page.objects.viewable_by(root_user).values_list("id", flat=True)
|
viewable = Page.objects.viewable_by(root_user).values_list("id", flat=True)
|
||||||
assert set(viewable) == {p.id for p in pages}
|
assert set(viewable) == {p.id for p in pages}
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_page_list_view(client: Client):
|
|
||||||
baker.make(Page, _quantity=10, _bulk_create=True)
|
|
||||||
client.force_login(subscriber_user.make())
|
|
||||||
res = client.get(reverse("core:page_list"))
|
|
||||||
assert res.status_code == 200
|
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
import itertools
|
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from unittest import mock
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib import auth
|
from django.contrib import auth
|
||||||
from django.contrib.auth.models import Permission
|
|
||||||
from django.core.management import call_command
|
from django.core.management import call_command
|
||||||
from django.test import Client, RequestFactory, TestCase
|
from django.test import Client, RequestFactory, TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
@@ -21,11 +18,10 @@ from core.baker_recipes import (
|
|||||||
subscriber_user,
|
subscriber_user,
|
||||||
very_old_subscriber_user,
|
very_old_subscriber_user,
|
||||||
)
|
)
|
||||||
from core.models import AnonymousUser, Group, User
|
from core.models import Group, User
|
||||||
from core.views import UserTabsMixin
|
from core.views import UserTabsMixin
|
||||||
from counter.baker_recipes import sale_recipe
|
from counter.baker_recipes import sale_recipe
|
||||||
from counter.models import Counter, Customer, Permanency, Refilling, Selling
|
from counter.models import Counter, Customer, Refilling, Selling
|
||||||
from counter.utils import is_logged_in_counter
|
|
||||||
from eboutic.models import Invoice, InvoiceItem
|
from eboutic.models import Invoice, InvoiceItem
|
||||||
|
|
||||||
|
|
||||||
@@ -63,9 +59,7 @@ class TestSearchUsersAPI(TestSearchUsers):
|
|||||||
"""Test that users are ordered by last login date."""
|
"""Test that users are ordered by last login date."""
|
||||||
self.client.force_login(subscriber_user.make())
|
self.client.force_login(subscriber_user.make())
|
||||||
|
|
||||||
response = self.client.get(
|
response = self.client.get(reverse("api:search_users") + "?search=First")
|
||||||
reverse("api:search_users", query={"search": "First"})
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json()["count"] == 11
|
assert response.json()["count"] == 11
|
||||||
# The users are ordered by last login date, so we need to reverse the list
|
# The users are ordered by last login date, so we need to reverse the list
|
||||||
@@ -74,7 +68,7 @@ class TestSearchUsersAPI(TestSearchUsers):
|
|||||||
]
|
]
|
||||||
|
|
||||||
def test_search_case_insensitive(self):
|
def test_search_case_insensitive(self):
|
||||||
"""Test that the search is case-insensitive."""
|
"""Test that the search is case insensitive."""
|
||||||
self.client.force_login(subscriber_user.make())
|
self.client.force_login(subscriber_user.make())
|
||||||
|
|
||||||
expected = [u.id for u in self.users[::-1]]
|
expected = [u.id for u in self.users[::-1]]
|
||||||
@@ -87,19 +81,14 @@ class TestSearchUsersAPI(TestSearchUsers):
|
|||||||
assert [r["id"] for r in response.json()["results"]] == expected
|
assert [r["id"] for r in response.json()["results"]] == expected
|
||||||
|
|
||||||
def test_search_nick_name(self):
|
def test_search_nick_name(self):
|
||||||
"""Test that the search can be done on the nickname."""
|
"""Test that the search can be done on the nick name."""
|
||||||
# hidden users should not be in the final result,
|
|
||||||
# even when the nickname matches
|
|
||||||
self.users[10].is_viewable = False
|
|
||||||
self.users[10].save()
|
|
||||||
self.client.force_login(subscriber_user.make())
|
self.client.force_login(subscriber_user.make())
|
||||||
|
|
||||||
# this should return users with nicknames Nick11, Nick10 and Nick1
|
# this should return users with nicknames Nick11, Nick10 and Nick1
|
||||||
response = self.client.get(
|
response = self.client.get(reverse("api:search_users") + "?search=Nick1")
|
||||||
reverse("api:search_users", query={"search": "Nick1"})
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert [r["id"] for r in response.json()["results"]] == [
|
assert [r["id"] for r in response.json()["results"]] == [
|
||||||
|
self.users[10].id,
|
||||||
self.users[9].id,
|
self.users[9].id,
|
||||||
self.users[0].id,
|
self.users[0].id,
|
||||||
]
|
]
|
||||||
@@ -111,25 +100,10 @@ class TestSearchUsersAPI(TestSearchUsers):
|
|||||||
self.client.force_login(subscriber_user.make())
|
self.client.force_login(subscriber_user.make())
|
||||||
|
|
||||||
# this should return users with first names First1 and First10
|
# this should return users with first names First1 and First10
|
||||||
response = self.client.get(reverse("api:search_users", query={"search": "bél"}))
|
response = self.client.get(reverse("api:search_users") + "?search=bél")
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert [r["id"] for r in response.json()["results"]] == [belix.id]
|
assert [r["id"] for r in response.json()["results"]] == [belix.id]
|
||||||
|
|
||||||
@mock.create_autospec(is_logged_in_counter, return_value=True)
|
|
||||||
def test_search_as_barman(self):
|
|
||||||
# barmen should also see hidden users
|
|
||||||
self.users[10].is_viewable = False
|
|
||||||
self.users[10].save()
|
|
||||||
response = self.client.get(
|
|
||||||
reverse("api:search_users", query={"search": "Nick1"})
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert [r["id"] for r in response.json()["results"]] == [
|
|
||||||
self.users[10].id,
|
|
||||||
self.users[9].id,
|
|
||||||
self.users[0].id,
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
class TestSearchUsersView(TestSearchUsers):
|
class TestSearchUsersView(TestSearchUsers):
|
||||||
"""Test the search user view (`GET /search`)."""
|
"""Test the search user view (`GET /search`)."""
|
||||||
@@ -188,7 +162,11 @@ class TestFilterInactive(TestCase):
|
|||||||
time_inactive = time_active - timedelta(days=3)
|
time_inactive = time_active - timedelta(days=3)
|
||||||
counter, seller = baker.make(Counter), baker.make(User)
|
counter, seller = baker.make(Counter), baker.make(User)
|
||||||
sale_recipe = Recipe(
|
sale_recipe = Recipe(
|
||||||
Selling, counter=counter, club=counter.club, seller=seller, unit_price=0
|
Selling,
|
||||||
|
counter=counter,
|
||||||
|
club=counter.club,
|
||||||
|
seller=seller,
|
||||||
|
is_validated=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
cls.users = [
|
cls.users = [
|
||||||
@@ -390,63 +368,3 @@ class TestRedirectMe:
|
|||||||
def test_promo_has_logo(promo):
|
def test_promo_has_logo(promo):
|
||||||
user = baker.make(User, promo=promo)
|
user = baker.make(User, promo=promo)
|
||||||
assert user.promo_has_logo()
|
assert user.promo_has_logo()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
class TestUserQuerySetViewableBy:
|
|
||||||
@pytest.fixture
|
|
||||||
def users(self) -> list[User]:
|
|
||||||
return [
|
|
||||||
baker.make(User),
|
|
||||||
subscriber_user.make(),
|
|
||||||
subscriber_user.make(is_viewable=False),
|
|
||||||
]
|
|
||||||
|
|
||||||
def test_admin_user(self, users: list[User]):
|
|
||||||
user = baker.make(
|
|
||||||
User,
|
|
||||||
user_permissions=[Permission.objects.get(codename="view_hidden_user")],
|
|
||||||
)
|
|
||||||
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
|
||||||
assert set(viewable) == set(users)
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"user_factory", [old_subscriber_user.make, subscriber_user.make]
|
|
||||||
)
|
|
||||||
def test_subscriber(self, users: list[User], user_factory):
|
|
||||||
user = user_factory()
|
|
||||||
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
|
||||||
assert set(viewable) == {users[0], users[1]}
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"user_factory", [lambda: baker.make(User), lambda: AnonymousUser()]
|
|
||||||
)
|
|
||||||
def test_not_subscriber(self, users: list[User], user_factory):
|
|
||||||
user = user_factory()
|
|
||||||
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user)
|
|
||||||
assert not viewable.exists()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_user_stats(client: Client):
|
|
||||||
user = subscriber_user.make()
|
|
||||||
baker.make(Refilling, customer=user.customer, amount=99999)
|
|
||||||
bars = [b[0] for b in settings.SITH_COUNTER_BARS]
|
|
||||||
baker.make(
|
|
||||||
Permanency,
|
|
||||||
end=now() - timedelta(days=5),
|
|
||||||
start=now() - timedelta(days=5, hours=3),
|
|
||||||
counter_id=itertools.cycle(bars),
|
|
||||||
_quantity=5,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
sale_recipe.make(
|
|
||||||
counter_id=itertools.cycle(bars),
|
|
||||||
customer=user.customer,
|
|
||||||
unit_price=1,
|
|
||||||
quantity=1,
|
|
||||||
_quantity=5,
|
|
||||||
)
|
|
||||||
client.force_login(user)
|
|
||||||
response = client.get(reverse("core:user_stats", kwargs={"user_id": user.id}))
|
|
||||||
assert response.status_code == 200
|
|
||||||
|
|||||||
12
core/urls.py
12
core/urls.py
@@ -24,7 +24,6 @@
|
|||||||
from django.urls import path, re_path, register_converter
|
from django.urls import path, re_path, register_converter
|
||||||
from django.views.generic import RedirectView
|
from django.views.generic import RedirectView
|
||||||
|
|
||||||
from com.views import NewsListView
|
|
||||||
from core.converters import (
|
from core.converters import (
|
||||||
BooleanStringConverter,
|
BooleanStringConverter,
|
||||||
FourDigitYearConverter,
|
FourDigitYearConverter,
|
||||||
@@ -54,7 +53,6 @@ from core.views import (
|
|||||||
PagePropView,
|
PagePropView,
|
||||||
PageRevView,
|
PageRevView,
|
||||||
PageView,
|
PageView,
|
||||||
SearchView,
|
|
||||||
SithLoginView,
|
SithLoginView,
|
||||||
SithPasswordChangeDoneView,
|
SithPasswordChangeDoneView,
|
||||||
SithPasswordChangeView,
|
SithPasswordChangeView,
|
||||||
@@ -78,9 +76,13 @@ from core.views import (
|
|||||||
UserUpdateProfileView,
|
UserUpdateProfileView,
|
||||||
UserView,
|
UserView,
|
||||||
delete_user_godfather,
|
delete_user_godfather,
|
||||||
|
index,
|
||||||
logout,
|
logout,
|
||||||
notification,
|
notification,
|
||||||
password_root_change,
|
password_root_change,
|
||||||
|
search_json,
|
||||||
|
search_user_json,
|
||||||
|
search_view,
|
||||||
send_file,
|
send_file,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -89,11 +91,13 @@ register_converter(TwoDigitMonthConverter, "mm")
|
|||||||
register_converter(BooleanStringConverter, "bool")
|
register_converter(BooleanStringConverter, "bool")
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("", NewsListView.as_view(), name="index"),
|
path("", index, name="index"),
|
||||||
path("notifications/", NotificationList.as_view(), name="notification_list"),
|
path("notifications/", NotificationList.as_view(), name="notification_list"),
|
||||||
path("notification/<int:notif_id>/", notification, name="notification"),
|
path("notification/<int:notif_id>/", notification, name="notification"),
|
||||||
# Search
|
# Search
|
||||||
path("search/", SearchView.as_view(), name="search"),
|
path("search/", search_view, name="search"),
|
||||||
|
path("search_json/", search_json, name="search_json"),
|
||||||
|
path("search_user/", search_user_json, name="search_user"),
|
||||||
# Login and co
|
# Login and co
|
||||||
path("login/", SithLoginView.as_view(), name="login"),
|
path("login/", SithLoginView.as_view(), name="login"),
|
||||||
path("logout/", logout, name="logout"),
|
path("logout/", logout, name="logout"),
|
||||||
|
|||||||
@@ -112,16 +112,6 @@ def get_semester_code(d: date | None = None) -> str:
|
|||||||
return "P" + str(start.year)[-2:]
|
return "P" + str(start.year)[-2:]
|
||||||
|
|
||||||
|
|
||||||
def get_last_promo() -> int:
|
|
||||||
"""Get the latest promo at the time the function is called.
|
|
||||||
|
|
||||||
For example, if called in october 2022 return 24,
|
|
||||||
if called in march 2026 return 27, etc.
|
|
||||||
"""
|
|
||||||
start_year = settings.SITH_SCHOOL_START_YEAR
|
|
||||||
return (localdate() + timedelta(days=180)).year - start_year
|
|
||||||
|
|
||||||
|
|
||||||
def is_image(file: UploadedFile):
|
def is_image(file: UploadedFile):
|
||||||
try:
|
try:
|
||||||
im = PIL.Image.open(file.file)
|
im = PIL.Image.open(file.file)
|
||||||
@@ -196,7 +186,7 @@ def exif_auto_rotate(image):
|
|||||||
|
|
||||||
def get_client_ip(request: HttpRequest) -> str | None:
|
def get_client_ip(request: HttpRequest) -> str | None:
|
||||||
headers = (
|
headers = (
|
||||||
"X_FORWARDED_FOR", # Common header for proxies
|
"X_FORWARDED_FOR", # Common header for proixes
|
||||||
"FORWARDED", # Standard header defined by RFC 7239.
|
"FORWARDED", # Standard header defined by RFC 7239.
|
||||||
"REMOTE_ADDR", # Default IP Address (direct connection)
|
"REMOTE_ADDR", # Default IP Address (direct connection)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -21,10 +21,10 @@
|
|||||||
# Place - Suite 330, Boston, MA 02111-1307, USA.
|
# Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
|
|
||||||
from django.http import (
|
from django.http import (
|
||||||
Http404,
|
|
||||||
HttpRequest,
|
|
||||||
HttpResponseForbidden,
|
HttpResponseForbidden,
|
||||||
|
HttpResponseNotFound,
|
||||||
HttpResponseServerError,
|
HttpResponseServerError,
|
||||||
)
|
)
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
@@ -33,20 +33,17 @@ from django.views.generic.edit import FormView
|
|||||||
from sentry_sdk import last_event_id
|
from sentry_sdk import last_event_id
|
||||||
|
|
||||||
from core.views.forms import LoginForm
|
from core.views.forms import LoginForm
|
||||||
from core.views.page import PageNotFound
|
|
||||||
|
|
||||||
|
|
||||||
def forbidden(request: HttpRequest, exception):
|
def forbidden(request, exception):
|
||||||
context = {"next": request.path, "form": LoginForm()}
|
context = {"next": request.path, "form": LoginForm()}
|
||||||
return HttpResponseForbidden(render(request, "core/403.jinja", context=context))
|
return HttpResponseForbidden(render(request, "core/403.jinja", context=context))
|
||||||
|
|
||||||
|
|
||||||
def not_found(request: HttpRequest, exception: Http404):
|
def not_found(request, exception):
|
||||||
if isinstance(exception, PageNotFound):
|
return HttpResponseNotFound(
|
||||||
template_name = "core/page/not_found.jinja"
|
render(request, "core/404.jinja", context={"exception": exception})
|
||||||
else:
|
)
|
||||||
template_name = "core/404.jinja"
|
|
||||||
return render(request, template_name, context={"exception": exception}, status=404)
|
|
||||||
|
|
||||||
|
|
||||||
def internal_servor_error(request):
|
def internal_servor_error(request):
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
#
|
#
|
||||||
#
|
#
|
||||||
import re
|
import re
|
||||||
from copy import copy
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
@@ -43,12 +42,13 @@ from django.forms import (
|
|||||||
Widget,
|
Widget,
|
||||||
)
|
)
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
|
from django.utils.translation import gettext
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
from antispam.forms import AntiSpamEmailField
|
from antispam.forms import AntiSpamEmailField
|
||||||
from core.models import Gift, Group, Page, PageRev, SithFile, User
|
from core.models import Gift, Group, Page, SithFile, User
|
||||||
from core.utils import resize_image
|
from core.utils import resize_image
|
||||||
from core.views.widgets.ajax_select import (
|
from core.views.widgets.ajax_select import (
|
||||||
AutoCompleteSelect,
|
AutoCompleteSelect,
|
||||||
@@ -56,7 +56,6 @@ from core.views.widgets.ajax_select import (
|
|||||||
AutoCompleteSelectMultipleGroup,
|
AutoCompleteSelectMultipleGroup,
|
||||||
AutoCompleteSelectUser,
|
AutoCompleteSelectUser,
|
||||||
)
|
)
|
||||||
from core.views.widgets.markdown import MarkdownInput
|
|
||||||
|
|
||||||
# Widgets
|
# Widgets
|
||||||
|
|
||||||
@@ -87,6 +86,30 @@ class NFCTextInput(TextInput):
|
|||||||
return context
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
class SelectUser(TextInput):
|
||||||
|
def render(self, name, value, attrs=None, renderer=None):
|
||||||
|
if attrs:
|
||||||
|
attrs["class"] = "select_user"
|
||||||
|
else:
|
||||||
|
attrs = {"class": "select_user"}
|
||||||
|
output = (
|
||||||
|
'%(content)s<div name="%(name)s" class="choose_user_widget" title="%(title)s"></div>'
|
||||||
|
% {
|
||||||
|
"content": super().render(name, value, attrs, renderer),
|
||||||
|
"title": _("Choose user"),
|
||||||
|
"name": name,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
output += (
|
||||||
|
'<span name="'
|
||||||
|
+ name
|
||||||
|
+ '" class="choose_user_button">'
|
||||||
|
+ gettext("Choose user")
|
||||||
|
+ "</span>"
|
||||||
|
)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
# Fields
|
# Fields
|
||||||
|
|
||||||
|
|
||||||
@@ -179,7 +202,7 @@ class UserProfileForm(forms.ModelForm):
|
|||||||
"school",
|
"school",
|
||||||
"promo",
|
"promo",
|
||||||
"forum_signature",
|
"forum_signature",
|
||||||
"is_viewable",
|
"is_subscriber_viewable",
|
||||||
]
|
]
|
||||||
widgets = {
|
widgets = {
|
||||||
"date_of_birth": SelectDate,
|
"date_of_birth": SelectDate,
|
||||||
@@ -188,8 +211,8 @@ class UserProfileForm(forms.ModelForm):
|
|||||||
"quote": forms.Textarea,
|
"quote": forms.Textarea,
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, *args, label_suffix: str = "", **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, label_suffix=label_suffix, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
# Image fields are injected here to override the file field provided by the model
|
# Image fields are injected here to override the file field provided by the model
|
||||||
# This would be better if we could have a SithImage sort of model input instead of a generic SithFile
|
# This would be better if we could have a SithImage sort of model input instead of a generic SithFile
|
||||||
@@ -381,42 +404,6 @@ class PageForm(forms.ModelForm):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class PageRevisionForm(forms.ModelForm):
|
|
||||||
"""Form to add a new revision to a page.
|
|
||||||
|
|
||||||
Notes:
|
|
||||||
Saving this form won't always result in a new revision.
|
|
||||||
If the previous revision on the same page was made :
|
|
||||||
|
|
||||||
- less than 20 minutes ago
|
|
||||||
- by the same author
|
|
||||||
- with a similarity ratio higher than 80%
|
|
||||||
|
|
||||||
then the latter will be edited and the new revision won't be created.
|
|
||||||
"""
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = PageRev
|
|
||||||
fields = ["title", "content"]
|
|
||||||
widgets = {"content": MarkdownInput}
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self, *args, author: User, page: Page, instance: PageRev | None = None, **kwargs
|
|
||||||
):
|
|
||||||
super().__init__(*args, instance=instance, **kwargs)
|
|
||||||
self.author = author
|
|
||||||
self.page = page
|
|
||||||
self.initial_obj: PageRev = copy(self.instance)
|
|
||||||
|
|
||||||
def save(self, commit=True): # noqa FBT002
|
|
||||||
revision: PageRev = self.instance
|
|
||||||
if not self.initial_obj.should_merge(self.instance):
|
|
||||||
revision.author = self.author
|
|
||||||
revision.page = self.page
|
|
||||||
revision.id = None # if id is None, Django will create a new record
|
|
||||||
return super().save(commit=commit)
|
|
||||||
|
|
||||||
|
|
||||||
class GiftForm(forms.ModelForm):
|
class GiftForm(forms.ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Gift
|
model = Gift
|
||||||
|
|||||||
@@ -22,49 +22,106 @@
|
|||||||
#
|
#
|
||||||
#
|
#
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
from django.contrib.auth.decorators import login_required
|
||||||
from django.db.models import F
|
from django.core import serializers
|
||||||
from django.db.models.query import QuerySet
|
from django.db.models.query import QuerySet
|
||||||
from django.http import HttpRequest
|
from django.http import JsonResponse
|
||||||
from django.shortcuts import get_object_or_404, redirect
|
from django.shortcuts import redirect, render
|
||||||
from django.views.generic import ListView, TemplateView
|
from django.utils import html
|
||||||
|
from django.utils.text import slugify
|
||||||
|
from django.views.generic import ListView
|
||||||
|
from haystack.query import SearchQuerySet
|
||||||
|
|
||||||
from club.models import Club
|
from club.models import Club
|
||||||
from core.models import Notification, User
|
from core.models import Notification, User
|
||||||
from core.schemas import UserFilterSchema
|
|
||||||
|
|
||||||
|
|
||||||
class NotificationList(LoginRequiredMixin, ListView):
|
def index(request, context=None):
|
||||||
|
from com.views import NewsListView
|
||||||
|
|
||||||
|
return NewsListView.as_view()(request)
|
||||||
|
|
||||||
|
|
||||||
|
class NotificationList(ListView):
|
||||||
model = Notification
|
model = Notification
|
||||||
template_name = "core/notification_list.jinja"
|
template_name = "core/notification_list.jinja"
|
||||||
|
|
||||||
def get_queryset(self) -> QuerySet[Notification]:
|
def get_queryset(self) -> QuerySet[Notification]:
|
||||||
|
if self.request.user.is_anonymous:
|
||||||
|
return Notification.objects.none()
|
||||||
|
# TODO: Bulk update in django 2.2
|
||||||
if "see_all" in self.request.GET:
|
if "see_all" in self.request.GET:
|
||||||
self.request.user.notifications.filter(viewed=False).update(viewed=True)
|
self.request.user.notifications.filter(viewed=False).update(viewed=True)
|
||||||
return self.request.user.notifications.order_by("-date")[:20]
|
return self.request.user.notifications.order_by("-date")[:20]
|
||||||
|
|
||||||
|
|
||||||
def notification(request: HttpRequest, notif_id: int):
|
def notification(request, notif_id):
|
||||||
notif = get_object_or_404(Notification, id=notif_id)
|
notif = Notification.objects.filter(id=notif_id).first()
|
||||||
if notif.type not in settings.SITH_PERMANENT_NOTIFICATIONS:
|
if notif:
|
||||||
notif.viewed = True
|
if notif.type not in settings.SITH_PERMANENT_NOTIFICATIONS:
|
||||||
else:
|
notif.viewed = True
|
||||||
notif.callback()
|
else:
|
||||||
notif.save()
|
notif.callback()
|
||||||
return redirect(notif.url)
|
notif.save()
|
||||||
|
return redirect(notif.url)
|
||||||
|
return redirect("/")
|
||||||
|
|
||||||
|
|
||||||
class SearchView(LoginRequiredMixin, TemplateView):
|
def search_user(query):
|
||||||
template_name = "core/search.jinja"
|
try:
|
||||||
|
# slugify turns everything into ascii and every whitespace into -
|
||||||
|
# it ends by removing duplicate - (so ' - ' will turn into '-')
|
||||||
|
# replace('-', ' ') because search is whitespace based
|
||||||
|
query = slugify(query).replace("-", " ")
|
||||||
|
# TODO: is this necessary?
|
||||||
|
query = html.escape(query)
|
||||||
|
res = (
|
||||||
|
SearchQuerySet()
|
||||||
|
.models(User)
|
||||||
|
.autocomplete(auto=query)
|
||||||
|
.order_by("-last_login")
|
||||||
|
.load_all()[:20]
|
||||||
|
)
|
||||||
|
return [r.object for r in res]
|
||||||
|
except TypeError:
|
||||||
|
return []
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
|
||||||
users, clubs = [], []
|
def search_club(query, *, as_json=False):
|
||||||
if query := self.request.GET.get("query"):
|
clubs = []
|
||||||
users = list(
|
if query:
|
||||||
UserFilterSchema(search=query)
|
clubs = Club.objects.filter(name__icontains=query).all()
|
||||||
.filter(User.objects.viewable_by(self.request.user))
|
clubs = clubs[:5]
|
||||||
.order_by(F("last_login").desc(nulls_last=True))
|
if as_json:
|
||||||
)
|
# Re-loads json to avoid double encoding by JsonResponse, but still benefit from serializers
|
||||||
clubs = list(Club.objects.filter(name__icontains=query)[:5])
|
clubs = json.loads(serializers.serialize("json", clubs, fields=("name")))
|
||||||
return super().get_context_data(**kwargs) | {"users": users, "clubs": clubs}
|
else:
|
||||||
|
clubs = list(clubs)
|
||||||
|
return clubs
|
||||||
|
|
||||||
|
|
||||||
|
@login_required
|
||||||
|
def search_view(request):
|
||||||
|
result = {
|
||||||
|
"users": search_user(request.GET.get("query", "")),
|
||||||
|
"clubs": search_club(request.GET.get("query", "")),
|
||||||
|
}
|
||||||
|
return render(request, "core/search.jinja", context={"result": result})
|
||||||
|
|
||||||
|
|
||||||
|
@login_required
|
||||||
|
def search_user_json(request):
|
||||||
|
result = {"users": search_user(request.GET.get("query", ""))}
|
||||||
|
return JsonResponse(result)
|
||||||
|
|
||||||
|
|
||||||
|
@login_required
|
||||||
|
def search_json(request):
|
||||||
|
result = {
|
||||||
|
"users": search_user(request.GET.get("query", "")),
|
||||||
|
"clubs": search_club(request.GET.get("query", ""), as_json=True),
|
||||||
|
}
|
||||||
|
return JsonResponse(result)
|
||||||
|
|||||||
@@ -13,39 +13,39 @@
|
|||||||
#
|
#
|
||||||
#
|
#
|
||||||
|
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.db.models import F, OuterRef, Subquery
|
from django.db.models import F, OuterRef, Subquery
|
||||||
from django.db.models.functions import Coalesce
|
from django.db.models.functions import Coalesce
|
||||||
|
|
||||||
|
# This file contains all the views that concern the page model
|
||||||
|
from django.forms.models import modelform_factory
|
||||||
from django.http import Http404
|
from django.http import Http404
|
||||||
from django.shortcuts import get_object_or_404, redirect
|
from django.shortcuts import redirect
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
from django.utils.functional import cached_property
|
|
||||||
from django.views.generic import DetailView, ListView
|
from django.views.generic import DetailView, ListView
|
||||||
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||||
|
|
||||||
from core.auth.mixins import CanEditPropMixin, CanViewMixin
|
from core.auth.mixins import (
|
||||||
from core.models import Page, PageRev
|
CanEditMixin,
|
||||||
from core.views.forms import PageForm, PagePropForm, PageRevisionForm
|
CanEditPropMixin,
|
||||||
|
CanViewMixin,
|
||||||
|
)
|
||||||
|
from core.models import LockError, Page, PageRev
|
||||||
|
from core.views.forms import PageForm, PagePropForm
|
||||||
|
from core.views.widgets.markdown import MarkdownInput
|
||||||
|
|
||||||
|
|
||||||
class PageNotFound(Http404):
|
class CanEditPagePropMixin(CanEditPropMixin):
|
||||||
"""Http404 Exception, but specifically for when the not found object is a Page."""
|
def dispatch(self, request, *args, **kwargs):
|
||||||
|
res = super().dispatch(request, *args, **kwargs)
|
||||||
def __init__(self, page_name: str):
|
if self.object.is_club_page:
|
||||||
self.page_name = page_name
|
raise Http404
|
||||||
|
return res
|
||||||
|
|
||||||
def get_page_or_404(full_name: str) -> Page:
|
|
||||||
"""Like Django's get_object_or_404, but for Page, and with a custom 404 exception."""
|
|
||||||
page = Page.objects.filter(_full_name=full_name).first()
|
|
||||||
if not page:
|
|
||||||
raise PageNotFound(full_name)
|
|
||||||
return page
|
|
||||||
|
|
||||||
|
|
||||||
class PageListView(ListView):
|
class PageListView(ListView):
|
||||||
model = Page
|
model = Page
|
||||||
template_name = "core/page/list.jinja"
|
template_name = "core/page_list.jinja"
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
return (
|
return (
|
||||||
@@ -64,57 +64,80 @@ class PageListView(ListView):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class BasePageDetailView(CanViewMixin, DetailView):
|
class PageView(CanViewMixin, DetailView):
|
||||||
model = Page
|
model = Page
|
||||||
|
template_name = "core/page_detail.jinja"
|
||||||
|
|
||||||
|
def dispatch(self, request, *args, **kwargs):
|
||||||
|
res = super().dispatch(request, *args, **kwargs)
|
||||||
|
if self.object and self.object.need_club_redirection:
|
||||||
|
return redirect("club:club_view", club_id=self.object.club.id)
|
||||||
|
return res
|
||||||
|
|
||||||
|
def get_object(self):
|
||||||
|
self.page = Page.get_page_by_full_name(self.kwargs["page_name"])
|
||||||
|
return self.page
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
context = super().get_context_data(**kwargs)
|
||||||
|
if "page" not in context:
|
||||||
|
context["new_page"] = self.kwargs["page_name"]
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
class PageHistView(CanViewMixin, DetailView):
|
||||||
|
model = Page
|
||||||
|
template_name = "core/page_hist.jinja"
|
||||||
|
slug_field = "_full_name"
|
||||||
slug_url_kwarg = "page_name"
|
slug_url_kwarg = "page_name"
|
||||||
_cached_object: Page | None = None
|
_cached_object: Page | None = None
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
page = self.get_object()
|
page = self.get_object()
|
||||||
if page.need_club_redirection:
|
if page.need_club_redirection:
|
||||||
return redirect("club:club_view", club_id=page.club.id)
|
return redirect("club:club_hist", club_id=page.club.id)
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
def get_object(self, *args, **kwargs):
|
def get_object(self, *args, **kwargs):
|
||||||
if not self._cached_object:
|
if not self._cached_object:
|
||||||
full_name = self.kwargs.get(self.slug_url_kwarg)
|
self._cached_object = super().get_object()
|
||||||
self._cached_object = get_page_or_404(full_name)
|
|
||||||
return self._cached_object
|
return self._cached_object
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
|
||||||
return super().get_context_data(**kwargs) | {
|
|
||||||
"last_revision": self.object.revisions.last()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
class PageRevView(CanViewMixin, DetailView):
|
||||||
class PageView(BasePageDetailView):
|
model = Page
|
||||||
template_name = "core/page/detail.jinja"
|
template_name = "core/page_detail.jinja"
|
||||||
|
|
||||||
|
|
||||||
class PageHistView(BasePageDetailView):
|
|
||||||
template_name = "core/page/history.jinja"
|
|
||||||
|
|
||||||
|
|
||||||
class PageRevView(BasePageDetailView):
|
|
||||||
template_name = "core/page/detail.jinja"
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
page = self.get_object()
|
res = super().dispatch(request, *args, **kwargs)
|
||||||
if page.need_club_redirection:
|
self.object = self.get_object()
|
||||||
|
|
||||||
|
if self.object is None:
|
||||||
|
return redirect("core:page_create", page_name=self.kwargs["page_name"])
|
||||||
|
|
||||||
|
if self.object.need_club_redirection:
|
||||||
return redirect(
|
return redirect(
|
||||||
"club:club_view_rev", club_id=page.club.id, rev_id=kwargs["rev"]
|
"club:club_view_rev", club_id=self.object.club.id, rev_id=kwargs["rev"]
|
||||||
)
|
)
|
||||||
self.revision = get_object_or_404(page.revisions, id=self.kwargs["rev"])
|
return res
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
def get_object(self, *args, **kwargs):
|
||||||
|
self.page = Page.get_page_by_full_name(self.kwargs["page_name"])
|
||||||
|
return self.page
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
return super().get_context_data(**kwargs) | {"revision": self.revision}
|
context = super().get_context_data(**kwargs)
|
||||||
|
if not self.page:
|
||||||
|
return context | {"new_page": self.kwargs["page_name"]}
|
||||||
|
context["page"] = self.page
|
||||||
|
context["rev"] = self.page.revisions.filter(id=self.kwargs["rev"]).first()
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
class PageCreateView(PermissionRequiredMixin, CreateView):
|
class PageCreateView(PermissionRequiredMixin, CreateView):
|
||||||
model = Page
|
model = Page
|
||||||
form_class = PageForm
|
form_class = PageForm
|
||||||
template_name = "core/create.jinja"
|
template_name = "core/page_prop.jinja"
|
||||||
permission_required = "core.add_page"
|
permission_required = "core.add_page"
|
||||||
|
|
||||||
def get_initial(self):
|
def get_initial(self):
|
||||||
@@ -129,67 +152,88 @@ class PageCreateView(PermissionRequiredMixin, CreateView):
|
|||||||
init["name"] = page_name[-1]
|
init["name"] = page_name[-1]
|
||||||
return init
|
return init
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
context = super().get_context_data(**kwargs)
|
||||||
|
context["new_page"] = True
|
||||||
|
return context
|
||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
form.instance.set_lock(self.request.user)
|
form.instance.set_lock(self.request.user)
|
||||||
ret = super().form_valid(form)
|
ret = super().form_valid(form)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
class CanEditPagePropMixin(CanEditPropMixin):
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
res = super().dispatch(request, *args, **kwargs)
|
|
||||||
if self.object.is_club_page:
|
|
||||||
raise Http404
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
class PagePropView(CanEditPagePropMixin, UpdateView):
|
class PagePropView(CanEditPagePropMixin, UpdateView):
|
||||||
model = Page
|
model = Page
|
||||||
form_class = PagePropForm
|
form_class = PagePropForm
|
||||||
template_name = "core/page/prop.jinja"
|
template_name = "core/page_prop.jinja"
|
||||||
|
slug_field = "_full_name"
|
||||||
|
slug_url_kwarg = "page_name"
|
||||||
|
|
||||||
def get_object(self, queryset=None):
|
def get_object(self, queryset=None):
|
||||||
self.page = get_page_or_404(full_name=self.kwargs["page_name"])
|
self.page = super().get_object()
|
||||||
self.page.set_lock_recursive(self.request.user)
|
try:
|
||||||
|
self.page.set_lock_recursive(self.request.user)
|
||||||
|
except LockError as e:
|
||||||
|
raise e
|
||||||
return self.page
|
return self.page
|
||||||
|
|
||||||
|
|
||||||
class BasePageEditView(UserPassesTestMixin, UpdateView):
|
class PageEditViewBase(CanEditMixin, UpdateView):
|
||||||
model = PageRev
|
model = PageRev
|
||||||
form_class = PageRevisionForm
|
form_class = modelform_factory(
|
||||||
template_name = "core/page/edit.jinja"
|
model=PageRev, fields=["title", "content"], widgets={"content": MarkdownInput}
|
||||||
|
)
|
||||||
def test_func(self):
|
template_name = "core/pagerev_edit.jinja"
|
||||||
return self.request.user.can_edit(self.page)
|
|
||||||
|
|
||||||
@cached_property
|
|
||||||
def page(self) -> Page:
|
|
||||||
page = get_page_or_404(full_name=self.kwargs["page_name"])
|
|
||||||
page.set_lock(self.request.user)
|
|
||||||
return page
|
|
||||||
|
|
||||||
def get_object(self, *args, **kwargs):
|
def get_object(self, *args, **kwargs):
|
||||||
return self.page.revisions.last()
|
self.page = Page.get_page_by_full_name(self.kwargs["page_name"])
|
||||||
|
return self._get_revision()
|
||||||
|
|
||||||
|
def _get_revision(self):
|
||||||
|
if self.page is not None:
|
||||||
|
# First edit
|
||||||
|
if self.page.revisions.all() is None:
|
||||||
|
rev = PageRev(author=self.request.user)
|
||||||
|
rev.save()
|
||||||
|
self.page.revisions.add(rev)
|
||||||
|
try:
|
||||||
|
self.page.set_lock(self.request.user)
|
||||||
|
except LockError as e:
|
||||||
|
raise e
|
||||||
|
return self.page.revisions.last()
|
||||||
|
return None
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
return super().get_context_data(**kwargs) | {"page": self.page}
|
context = super().get_context_data(**kwargs)
|
||||||
|
if self.page is not None:
|
||||||
|
context["page"] = self.page
|
||||||
|
else:
|
||||||
|
context["new_page"] = self.kwargs["page_name"]
|
||||||
|
return context
|
||||||
|
|
||||||
def get_form_kwargs(self):
|
def form_valid(self, form):
|
||||||
return super().get_form_kwargs() | {
|
# TODO : factor that, but first make some tests
|
||||||
"author": self.request.user,
|
rev = form.instance
|
||||||
"page": self.page,
|
new_rev = PageRev(title=rev.title, content=rev.content)
|
||||||
}
|
new_rev.author = self.request.user
|
||||||
|
new_rev.page = self.page
|
||||||
|
form.instance = new_rev
|
||||||
|
return super().form_valid(form)
|
||||||
|
|
||||||
|
|
||||||
class PageEditView(BasePageEditView):
|
class PageEditView(PageEditViewBase):
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if self.page.need_club_redirection:
|
res = super().dispatch(request, *args, **kwargs)
|
||||||
return redirect("club:club_edit_page", club_id=self.page.club.id)
|
if self.object and self.object.page.need_club_redirection:
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return redirect("club:club_edit_page", club_id=self.object.page.club.id)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
class PageDeleteView(CanEditPagePropMixin, DeleteView):
|
class PageDeleteView(CanEditPagePropMixin, DeleteView):
|
||||||
model = Page
|
model = Page
|
||||||
template_name = "core/delete_confirm.jinja"
|
template_name = "core/delete_confirm.jinja"
|
||||||
pk_url_kwarg = "page_id"
|
pk_url_kwarg = "page_id"
|
||||||
success_url = reverse_lazy("core:page_list")
|
|
||||||
|
def get_success_url(self, **kwargs):
|
||||||
|
return reverse_lazy("core:page_list")
|
||||||
|
|||||||
@@ -22,9 +22,9 @@
|
|||||||
#
|
#
|
||||||
#
|
#
|
||||||
import itertools
|
import itertools
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
# This file contains all the views that concern the user model
|
# This file contains all the views that concern the user model
|
||||||
|
from datetime import date, timedelta
|
||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
from smtplib import SMTPException
|
from smtplib import SMTPException
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ from django.contrib.auth import login, views
|
|||||||
from django.contrib.auth.forms import PasswordChangeForm
|
from django.contrib.auth.forms import PasswordChangeForm
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||||
from django.core.exceptions import PermissionDenied
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db.models import DateField, F, QuerySet, Sum
|
from django.db.models import DateField, QuerySet
|
||||||
from django.db.models.functions import Trunc
|
from django.db.models.functions import Trunc
|
||||||
from django.forms.models import modelform_factory
|
from django.forms.models import modelform_factory
|
||||||
from django.http import Http404
|
from django.http import Http404
|
||||||
@@ -66,8 +66,9 @@ from core.views.forms import (
|
|||||||
UserProfileForm,
|
UserProfileForm,
|
||||||
)
|
)
|
||||||
from core.views.mixins import TabedViewMixin, UseFragmentsMixin
|
from core.views.mixins import TabedViewMixin, UseFragmentsMixin
|
||||||
from counter.models import Refilling, Selling
|
from counter.models import Counter, Refilling, Selling
|
||||||
from eboutic.models import Invoice
|
from eboutic.models import Invoice
|
||||||
|
from subscription.models import Subscription
|
||||||
from trombi.views import UserTrombiForm
|
from trombi.views import UserTrombiForm
|
||||||
|
|
||||||
|
|
||||||
@@ -102,7 +103,9 @@ def password_root_change(request, user_id):
|
|||||||
"""Allows a root user to change someone's password."""
|
"""Allows a root user to change someone's password."""
|
||||||
if not request.user.is_root:
|
if not request.user.is_root:
|
||||||
raise PermissionDenied
|
raise PermissionDenied
|
||||||
user = get_object_or_404(User, id=user_id)
|
user = User.objects.filter(id=user_id).first()
|
||||||
|
if not user:
|
||||||
|
raise Http404("User not found")
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
form = views.SetPasswordForm(user=user, data=request.POST)
|
form = views.SetPasswordForm(user=user, data=request.POST)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
@@ -352,40 +355,87 @@ class UserStatsView(UserTabsMixin, CanViewMixin, DetailView):
|
|||||||
context_object_name = "profile"
|
context_object_name = "profile"
|
||||||
template_name = "core/user_stats.jinja"
|
template_name = "core/user_stats.jinja"
|
||||||
current_tab = "stats"
|
current_tab = "stats"
|
||||||
queryset = User.objects.exclude(customer=None).select_related("customer")
|
|
||||||
|
|
||||||
def dispatch(self, request, *arg, **kwargs):
|
def dispatch(self, request, *arg, **kwargs):
|
||||||
profile = self.get_object()
|
profile = self.get_object()
|
||||||
|
|
||||||
|
if not hasattr(profile, "customer"):
|
||||||
|
raise Http404
|
||||||
|
|
||||||
if not (
|
if not (
|
||||||
profile == request.user or request.user.has_perm("counter.view_customer")
|
profile == request.user or request.user.has_perm("counter.view_customer")
|
||||||
):
|
):
|
||||||
raise PermissionDenied
|
raise PermissionDenied
|
||||||
|
|
||||||
return super().dispatch(request, *arg, **kwargs)
|
return super().dispatch(request, *arg, **kwargs)
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
|
from django.db.models import Sum
|
||||||
|
|
||||||
kwargs["perm_time"] = list(
|
foyer = Counter.objects.filter(name="Foyer").first()
|
||||||
self.object.permanencies.filter(end__isnull=False, counter__type="BAR")
|
mde = Counter.objects.filter(name="MDE").first()
|
||||||
.values("counter", "counter__name")
|
gommette = Counter.objects.filter(name="La Gommette").first()
|
||||||
.annotate(total=Sum(F("end") - F("start"), default=timedelta(seconds=0)))
|
semester_start = Subscription.compute_start(d=date.today(), duration=3)
|
||||||
.order_by("-total")
|
|
||||||
)
|
|
||||||
kwargs["total_perm_time"] = sum(
|
kwargs["total_perm_time"] = sum(
|
||||||
[perm["total"] for perm in kwargs["perm_time"]], start=timedelta(seconds=0)
|
[p.end - p.start for p in self.object.permanencies.exclude(end=None)],
|
||||||
|
timedelta(),
|
||||||
)
|
)
|
||||||
kwargs["purchase_sums"] = list(
|
kwargs["total_foyer_time"] = sum(
|
||||||
self.object.customer.buyings.filter(counter__type="BAR")
|
[
|
||||||
.values("counter", "counter__name")
|
p.end - p.start
|
||||||
.annotate(total=Sum(F("unit_price") * F("quantity")))
|
for p in self.object.permanencies.filter(counter=foyer).exclude(
|
||||||
.order_by("-total")
|
end=None
|
||||||
|
)
|
||||||
|
],
|
||||||
|
timedelta(),
|
||||||
|
)
|
||||||
|
kwargs["total_mde_time"] = sum(
|
||||||
|
[
|
||||||
|
p.end - p.start
|
||||||
|
for p in self.object.permanencies.filter(counter=mde).exclude(end=None)
|
||||||
|
],
|
||||||
|
timedelta(),
|
||||||
|
)
|
||||||
|
kwargs["total_gommette_time"] = sum(
|
||||||
|
[
|
||||||
|
p.end - p.start
|
||||||
|
for p in self.object.permanencies.filter(counter=gommette).exclude(
|
||||||
|
end=None
|
||||||
|
)
|
||||||
|
],
|
||||||
|
timedelta(),
|
||||||
|
)
|
||||||
|
kwargs["total_foyer_buyings"] = sum(
|
||||||
|
[
|
||||||
|
b.unit_price * b.quantity
|
||||||
|
for b in self.object.customer.buyings.filter(
|
||||||
|
counter=foyer, date__gte=semester_start
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
kwargs["total_mde_buyings"] = sum(
|
||||||
|
[
|
||||||
|
b.unit_price * b.quantity
|
||||||
|
for b in self.object.customer.buyings.filter(
|
||||||
|
counter=mde, date__gte=semester_start
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
kwargs["total_gommette_buyings"] = sum(
|
||||||
|
[
|
||||||
|
b.unit_price * b.quantity
|
||||||
|
for b in self.object.customer.buyings.filter(
|
||||||
|
counter=gommette, date__gte=semester_start
|
||||||
|
)
|
||||||
|
]
|
||||||
)
|
)
|
||||||
kwargs["total_purchases"] = sum(s["total"] for s in kwargs["purchase_sums"])
|
|
||||||
kwargs["top_product"] = (
|
kwargs["top_product"] = (
|
||||||
self.object.customer.buyings.values("product__name")
|
self.object.customer.buyings.values("product__name")
|
||||||
.annotate(product_sum=Sum("quantity"))
|
.annotate(product_sum=Sum("quantity"))
|
||||||
|
.exclude(product_sum=None)
|
||||||
.order_by("-product_sum")
|
.order_by("-product_sum")
|
||||||
.all()[:15]
|
.all()[:10]
|
||||||
)
|
)
|
||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,12 @@
|
|||||||
from django.apps import AppConfig
|
from django.apps import AppConfig
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
PAYMENT_METHOD = [
|
||||||
|
("CHECK", _("Check")),
|
||||||
|
("CASH", _("Cash")),
|
||||||
|
("CARD", _("Credit card")),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class CounterConfig(AppConfig):
|
class CounterConfig(AppConfig):
|
||||||
name = "counter"
|
name = "counter"
|
||||||
|
|||||||
109
counter/forms.py
109
counter/forms.py
@@ -1,11 +1,10 @@
|
|||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date
|
||||||
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.core.validators import MaxValueValidator
|
|
||||||
from django.db.models import Exists, OuterRef, Q
|
from django.db.models import Exists, OuterRef, Q
|
||||||
from django.forms import BaseModelFormSet
|
from django.forms import BaseModelFormSet
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
@@ -35,7 +34,6 @@ from counter.models import (
|
|||||||
Eticket,
|
Eticket,
|
||||||
InvoiceCall,
|
InvoiceCall,
|
||||||
Product,
|
Product,
|
||||||
ProductFormula,
|
|
||||||
Refilling,
|
Refilling,
|
||||||
ReturnableProduct,
|
ReturnableProduct,
|
||||||
ScheduledProductAction,
|
ScheduledProductAction,
|
||||||
@@ -138,10 +136,7 @@ class GetUserForm(forms.Form):
|
|||||||
|
|
||||||
|
|
||||||
class RefillForm(forms.ModelForm):
|
class RefillForm(forms.ModelForm):
|
||||||
allowed_refilling_methods = [
|
allowed_refilling_methods = ["CASH", "CARD"]
|
||||||
Refilling.PaymentMethod.CASH,
|
|
||||||
Refilling.PaymentMethod.CARD,
|
|
||||||
]
|
|
||||||
|
|
||||||
error_css_class = "error"
|
error_css_class = "error"
|
||||||
required_css_class = "required"
|
required_css_class = "required"
|
||||||
@@ -151,7 +146,7 @@ class RefillForm(forms.ModelForm):
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Refilling
|
model = Refilling
|
||||||
fields = ["amount", "payment_method"]
|
fields = ["amount", "payment_method", "bank"]
|
||||||
widgets = {"payment_method": forms.RadioSelect}
|
widgets = {"payment_method": forms.RadioSelect}
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
@@ -165,6 +160,9 @@ class RefillForm(forms.ModelForm):
|
|||||||
if self.fields["payment_method"].initial not in self.allowed_refilling_methods:
|
if self.fields["payment_method"].initial not in self.allowed_refilling_methods:
|
||||||
self.fields["payment_method"].initial = self.allowed_refilling_methods[0]
|
self.fields["payment_method"].initial = self.allowed_refilling_methods[0]
|
||||||
|
|
||||||
|
if "CHECK" not in self.allowed_refilling_methods:
|
||||||
|
del self.fields["bank"]
|
||||||
|
|
||||||
|
|
||||||
class CounterEditForm(forms.ModelForm):
|
class CounterEditForm(forms.ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
@@ -237,19 +235,6 @@ class ScheduledProductActionForm(forms.ModelForm):
|
|||||||
)
|
)
|
||||||
return super().clean()
|
return super().clean()
|
||||||
|
|
||||||
def set_product(self, product: Product):
|
|
||||||
"""Set the product to which this form's instance is linked.
|
|
||||||
|
|
||||||
When this form is linked to a ProductForm in the case of a product's creation,
|
|
||||||
the product doesn't exist yet, so saving this form as is will result
|
|
||||||
in having `{"product_id": null}` in the action kwargs.
|
|
||||||
For the creation to be useful, it may be needed to inject the newly created
|
|
||||||
product into this form, before saving the latter.
|
|
||||||
"""
|
|
||||||
self.product = product
|
|
||||||
kwargs = json.loads(self.instance.kwargs) | {"product_id": self.product.id}
|
|
||||||
self.instance.kwargs = json.dumps(kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
class BaseScheduledProductActionFormSet(BaseModelFormSet):
|
class BaseScheduledProductActionFormSet(BaseModelFormSet):
|
||||||
def __init__(self, *args, product: Product, **kwargs):
|
def __init__(self, *args, product: Product, **kwargs):
|
||||||
@@ -318,6 +303,7 @@ class ProductForm(forms.ModelForm):
|
|||||||
}
|
}
|
||||||
|
|
||||||
counters = forms.ModelMultipleChoiceField(
|
counters = forms.ModelMultipleChoiceField(
|
||||||
|
help_text=None,
|
||||||
label=_("Counters"),
|
label=_("Counters"),
|
||||||
required=False,
|
required=False,
|
||||||
widget=AutoCompleteSelectMultipleCounter,
|
widget=AutoCompleteSelectMultipleCounter,
|
||||||
@@ -328,81 +314,18 @@ class ProductForm(forms.ModelForm):
|
|||||||
super().__init__(*args, instance=instance, **kwargs)
|
super().__init__(*args, instance=instance, **kwargs)
|
||||||
if self.instance.id:
|
if self.instance.id:
|
||||||
self.fields["counters"].initial = self.instance.counters.all()
|
self.fields["counters"].initial = self.instance.counters.all()
|
||||||
if hasattr(self.instance, "formula"):
|
|
||||||
self.formula_init(self.instance.formula)
|
|
||||||
self.action_formset = ScheduledProductActionFormSet(
|
self.action_formset = ScheduledProductActionFormSet(
|
||||||
*args, product=self.instance, **kwargs
|
*args, product=self.instance, **kwargs
|
||||||
)
|
)
|
||||||
|
|
||||||
def formula_init(self, formula: ProductFormula):
|
|
||||||
"""Part of the form initialisation specific to formula products."""
|
|
||||||
self.fields["selling_price"].help_text = _(
|
|
||||||
"This product is a formula. "
|
|
||||||
"Its price cannot be greater than the price "
|
|
||||||
"of the products constituting it, which is %(price)s €"
|
|
||||||
) % {"price": formula.max_selling_price}
|
|
||||||
self.fields["special_selling_price"].help_text = _(
|
|
||||||
"This product is a formula. "
|
|
||||||
"Its special price cannot be greater than the price "
|
|
||||||
"of the products constituting it, which is %(price)s €"
|
|
||||||
) % {"price": formula.max_special_selling_price}
|
|
||||||
for key, price in (
|
|
||||||
("selling_price", formula.max_selling_price),
|
|
||||||
("special_selling_price", formula.max_special_selling_price),
|
|
||||||
):
|
|
||||||
self.fields[key].widget.attrs["max"] = price
|
|
||||||
self.fields[key].validators.append(MaxValueValidator(price))
|
|
||||||
|
|
||||||
def is_valid(self):
|
def is_valid(self):
|
||||||
return super().is_valid() and self.action_formset.is_valid()
|
return super().is_valid() and self.action_formset.is_valid()
|
||||||
|
|
||||||
def save(self, *args, **kwargs) -> Product:
|
def save(self, *args, **kwargs):
|
||||||
product = super().save(*args, **kwargs)
|
ret = super().save(*args, **kwargs)
|
||||||
product.counters.set(self.cleaned_data["counters"])
|
self.instance.counters.set(self.cleaned_data["counters"])
|
||||||
for form in self.action_formset:
|
|
||||||
# if it's a creation, the product given in the formset
|
|
||||||
# wasn't a persisted instance.
|
|
||||||
# So if we tried to persist the scheduled actions in the current state,
|
|
||||||
# they would be linked to no product, thus be completely useless
|
|
||||||
# To make it work, we have to replace
|
|
||||||
# the initial product with a persisted one
|
|
||||||
form.set_product(product)
|
|
||||||
self.action_formset.save()
|
self.action_formset.save()
|
||||||
return product
|
return ret
|
||||||
|
|
||||||
|
|
||||||
class ProductFormulaForm(forms.ModelForm):
|
|
||||||
class Meta:
|
|
||||||
model = ProductFormula
|
|
||||||
fields = ["products", "result"]
|
|
||||||
widgets = {
|
|
||||||
"products": AutoCompleteSelectMultipleProduct,
|
|
||||||
"result": AutoCompleteSelectProduct,
|
|
||||||
}
|
|
||||||
|
|
||||||
def clean(self):
|
|
||||||
cleaned_data = super().clean()
|
|
||||||
if cleaned_data["result"] in cleaned_data["products"]:
|
|
||||||
self.add_error(
|
|
||||||
None,
|
|
||||||
_(
|
|
||||||
"The same product cannot be at the same time "
|
|
||||||
"the result and a part of the formula."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
prices = [p.selling_price for p in cleaned_data["products"]]
|
|
||||||
special_prices = [p.special_selling_price for p in cleaned_data["products"]]
|
|
||||||
selling_price = cleaned_data["result"].selling_price
|
|
||||||
special_selling_price = cleaned_data["result"].special_selling_price
|
|
||||||
if selling_price > sum(prices) or special_selling_price > sum(special_prices):
|
|
||||||
self.add_error(
|
|
||||||
"result",
|
|
||||||
_(
|
|
||||||
"The result cannot be more expensive "
|
|
||||||
"than the total of the other products."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
return cleaned_data
|
|
||||||
|
|
||||||
|
|
||||||
class ReturnableProductForm(forms.ModelForm):
|
class ReturnableProductForm(forms.ModelForm):
|
||||||
@@ -410,8 +333,8 @@ class ReturnableProductForm(forms.ModelForm):
|
|||||||
model = ReturnableProduct
|
model = ReturnableProduct
|
||||||
fields = ["product", "returned_product", "max_return"]
|
fields = ["product", "returned_product", "max_return"]
|
||||||
widgets = {
|
widgets = {
|
||||||
"product": AutoCompleteSelectProduct,
|
"product": AutoCompleteSelectProduct(),
|
||||||
"returned_product": AutoCompleteSelectProduct,
|
"returned_product": AutoCompleteSelectProduct(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def save(self, commit: bool = True) -> ReturnableProduct: # noqa FBT
|
def save(self, commit: bool = True) -> ReturnableProduct: # noqa FBT
|
||||||
@@ -446,6 +369,7 @@ class EticketForm(forms.ModelForm):
|
|||||||
class CloseCustomerAccountForm(forms.Form):
|
class CloseCustomerAccountForm(forms.Form):
|
||||||
user = forms.ModelChoiceField(
|
user = forms.ModelChoiceField(
|
||||||
label=_("Refound this account"),
|
label=_("Refound this account"),
|
||||||
|
help_text=None,
|
||||||
required=True,
|
required=True,
|
||||||
widget=AutoCompleteSelectUser,
|
widget=AutoCompleteSelectUser,
|
||||||
queryset=User.objects.all(),
|
queryset=User.objects.all(),
|
||||||
@@ -565,14 +489,13 @@ class InvoiceCallForm(forms.Form):
|
|||||||
def __init__(self, *args, month: date, **kwargs):
|
def __init__(self, *args, month: date, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self.month = month
|
self.month = month
|
||||||
month_start = datetime(month.year, month.month, month.day, tzinfo=timezone.utc)
|
|
||||||
self.clubs = list(
|
self.clubs = list(
|
||||||
Club.objects.filter(
|
Club.objects.filter(
|
||||||
Exists(
|
Exists(
|
||||||
Selling.objects.filter(
|
Selling.objects.filter(
|
||||||
club=OuterRef("pk"),
|
club=OuterRef("pk"),
|
||||||
date__gte=month_start,
|
date__gte=month,
|
||||||
date__lte=month_start + relativedelta(months=1),
|
date__lte=month + relativedelta(months=1),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
).annotate(
|
).annotate(
|
||||||
|
|||||||
@@ -119,6 +119,7 @@ class Command(BaseCommand):
|
|||||||
quantity=1,
|
quantity=1,
|
||||||
unit_price=account.amount,
|
unit_price=account.amount,
|
||||||
date=now(),
|
date=now(),
|
||||||
|
is_validated=True,
|
||||||
)
|
)
|
||||||
for account in accounts
|
for account in accounts
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
# Generated by Django 5.2.8 on 2025-11-19 17:59
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
from django.db.migrations.state import StateApps
|
|
||||||
from django.db.models import Case, When
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_selling_payment_method(apps: StateApps, schema_editor):
|
|
||||||
# 0 <=> SITH_ACCOUNT is the default value, so no need to migrate it
|
|
||||||
Selling = apps.get_model("counter", "Selling")
|
|
||||||
Selling.objects.filter(payment_method_str="CARD").update(payment_method=1)
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_selling_payment_method_reverse(apps: StateApps, schema_editor):
|
|
||||||
Selling = apps.get_model("counter", "Selling")
|
|
||||||
Selling.objects.filter(payment_method=1).update(payment_method_str="CARD")
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_refilling_payment_method(apps: StateApps, schema_editor):
|
|
||||||
Refilling = apps.get_model("counter", "Refilling")
|
|
||||||
Refilling.objects.update(
|
|
||||||
payment_method=Case(
|
|
||||||
When(payment_method_str="CARD", then=0),
|
|
||||||
When(payment_method_str="CASH", then=1),
|
|
||||||
When(payment_method_str="CHECK", then=2),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_refilling_payment_method_reverse(apps: StateApps, schema_editor):
|
|
||||||
Refilling = apps.get_model("counter", "Refilling")
|
|
||||||
Refilling.objects.update(
|
|
||||||
payment_method_str=Case(
|
|
||||||
When(payment_method=0, then="CARD"),
|
|
||||||
When(payment_method=1, then="CASH"),
|
|
||||||
When(payment_method=2, then="CHECK"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [("counter", "0034_alter_selling_date_selling_date_month_idx")]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.RemoveField(model_name="selling", name="is_validated"),
|
|
||||||
migrations.RemoveField(model_name="refilling", name="is_validated"),
|
|
||||||
migrations.RemoveField(model_name="refilling", name="bank"),
|
|
||||||
migrations.RenameField(
|
|
||||||
model_name="selling",
|
|
||||||
old_name="payment_method",
|
|
||||||
new_name="payment_method_str",
|
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="selling",
|
|
||||||
name="payment_method",
|
|
||||||
field=models.PositiveSmallIntegerField(
|
|
||||||
choices=[(0, "Sith account"), (1, "Credit card")],
|
|
||||||
default=0,
|
|
||||||
verbose_name="payment method",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.RunPython(
|
|
||||||
migrate_selling_payment_method, migrate_selling_payment_method_reverse
|
|
||||||
),
|
|
||||||
migrations.RemoveField(model_name="selling", name="payment_method_str"),
|
|
||||||
migrations.RenameField(
|
|
||||||
model_name="refilling",
|
|
||||||
old_name="payment_method",
|
|
||||||
new_name="payment_method_str",
|
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="refilling",
|
|
||||||
name="payment_method",
|
|
||||||
field=models.PositiveSmallIntegerField(
|
|
||||||
choices=[(0, "Credit card"), (1, "Cash"), (2, "Check")],
|
|
||||||
default=0,
|
|
||||||
verbose_name="payment method",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.RunPython(
|
|
||||||
migrate_refilling_payment_method, migrate_refilling_payment_method_reverse
|
|
||||||
),
|
|
||||||
migrations.RemoveField(model_name="refilling", name="payment_method_str"),
|
|
||||||
]
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
# Generated by Django 5.2.8 on 2025-11-26 11:34
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [("counter", "0035_remove_selling_is_validated_and_more")]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="ProductFormula",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.AutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"products",
|
|
||||||
models.ManyToManyField(
|
|
||||||
help_text="The products that constitute this formula.",
|
|
||||||
related_name="formulas",
|
|
||||||
to="counter.product",
|
|
||||||
verbose_name="products",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"result",
|
|
||||||
models.OneToOneField(
|
|
||||||
help_text="The formula product.",
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
to="counter.product",
|
|
||||||
verbose_name="result product",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -44,6 +44,7 @@ from club.models import Club
|
|||||||
from core.fields import ResizedImageField
|
from core.fields import ResizedImageField
|
||||||
from core.models import Group, Notification, User
|
from core.models import Group, Notification, User
|
||||||
from core.utils import get_start_of_semester
|
from core.utils import get_start_of_semester
|
||||||
|
from counter.apps import PAYMENT_METHOD
|
||||||
from counter.fields import CurrencyField
|
from counter.fields import CurrencyField
|
||||||
from subscription.models import Subscription
|
from subscription.models import Subscription
|
||||||
|
|
||||||
@@ -79,8 +80,7 @@ class CustomerQuerySet(models.QuerySet):
|
|||||||
)
|
)
|
||||||
money_out = Subquery(
|
money_out = Subquery(
|
||||||
Selling.objects.filter(
|
Selling.objects.filter(
|
||||||
customer=OuterRef("pk"),
|
customer=OuterRef("pk"), payment_method="SITH_ACCOUNT"
|
||||||
payment_method=Selling.PaymentMethod.SITH_ACCOUNT,
|
|
||||||
)
|
)
|
||||||
.values("customer_id")
|
.values("customer_id")
|
||||||
.annotate(res=Sum(F("unit_price") * F("quantity"), default=0))
|
.annotate(res=Sum(F("unit_price") * F("quantity"), default=0))
|
||||||
@@ -455,37 +455,6 @@ class Product(models.Model):
|
|||||||
return self.selling_price - self.purchase_price
|
return self.selling_price - self.purchase_price
|
||||||
|
|
||||||
|
|
||||||
class ProductFormula(models.Model):
|
|
||||||
products = models.ManyToManyField(
|
|
||||||
Product,
|
|
||||||
related_name="formulas",
|
|
||||||
verbose_name=_("products"),
|
|
||||||
help_text=_("The products that constitute this formula."),
|
|
||||||
)
|
|
||||||
result = models.OneToOneField(
|
|
||||||
Product,
|
|
||||||
related_name="formula",
|
|
||||||
on_delete=models.CASCADE,
|
|
||||||
verbose_name=_("result product"),
|
|
||||||
help_text=_("The product got with the formula."),
|
|
||||||
)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.result.name
|
|
||||||
|
|
||||||
@cached_property
|
|
||||||
def max_selling_price(self) -> float:
|
|
||||||
# iterating over all products is less efficient than doing
|
|
||||||
# a simple aggregation, but this method is likely to be used in
|
|
||||||
# coordination with `max_special_selling_price`,
|
|
||||||
# and Django caches the result of the `all` queryset.
|
|
||||||
return sum(p.selling_price for p in self.products.all())
|
|
||||||
|
|
||||||
@cached_property
|
|
||||||
def max_special_selling_price(self) -> float:
|
|
||||||
return sum(p.special_selling_price for p in self.products.all())
|
|
||||||
|
|
||||||
|
|
||||||
class CounterQuerySet(models.QuerySet):
|
class CounterQuerySet(models.QuerySet):
|
||||||
def annotate_has_barman(self, user: User) -> Self:
|
def annotate_has_barman(self, user: User) -> Self:
|
||||||
"""Annotate the queryset with the `user_is_barman` field.
|
"""Annotate the queryset with the `user_is_barman` field.
|
||||||
@@ -762,11 +731,6 @@ class RefillingQuerySet(models.QuerySet):
|
|||||||
class Refilling(models.Model):
|
class Refilling(models.Model):
|
||||||
"""Handle the refilling."""
|
"""Handle the refilling."""
|
||||||
|
|
||||||
class PaymentMethod(models.IntegerChoices):
|
|
||||||
CARD = 0, _("Credit card")
|
|
||||||
CASH = 1, _("Cash")
|
|
||||||
CHECK = 2, _("Check")
|
|
||||||
|
|
||||||
counter = models.ForeignKey(
|
counter = models.ForeignKey(
|
||||||
Counter, related_name="refillings", blank=False, on_delete=models.CASCADE
|
Counter, related_name="refillings", blank=False, on_delete=models.CASCADE
|
||||||
)
|
)
|
||||||
@@ -781,9 +745,16 @@ class Refilling(models.Model):
|
|||||||
Customer, related_name="refillings", blank=False, on_delete=models.CASCADE
|
Customer, related_name="refillings", blank=False, on_delete=models.CASCADE
|
||||||
)
|
)
|
||||||
date = models.DateTimeField(_("date"))
|
date = models.DateTimeField(_("date"))
|
||||||
payment_method = models.PositiveSmallIntegerField(
|
payment_method = models.CharField(
|
||||||
_("payment method"), choices=PaymentMethod, default=PaymentMethod.CARD
|
_("payment method"),
|
||||||
|
max_length=255,
|
||||||
|
choices=PAYMENT_METHOD,
|
||||||
|
default="CARD",
|
||||||
)
|
)
|
||||||
|
bank = models.CharField(
|
||||||
|
_("bank"), max_length=255, choices=settings.SITH_COUNTER_BANK, default="OTHER"
|
||||||
|
)
|
||||||
|
is_validated = models.BooleanField(_("is validated"), default=False)
|
||||||
|
|
||||||
objects = RefillingQuerySet.as_manager()
|
objects = RefillingQuerySet.as_manager()
|
||||||
|
|
||||||
@@ -800,9 +771,10 @@ class Refilling(models.Model):
|
|||||||
if not self.date:
|
if not self.date:
|
||||||
self.date = timezone.now()
|
self.date = timezone.now()
|
||||||
self.full_clean()
|
self.full_clean()
|
||||||
if self._state.adding:
|
if not self.is_validated:
|
||||||
self.customer.amount += self.amount
|
self.customer.amount += self.amount
|
||||||
self.customer.save()
|
self.customer.save()
|
||||||
|
self.is_validated = True
|
||||||
if self.customer.user.preferences.notify_on_refill:
|
if self.customer.user.preferences.notify_on_refill:
|
||||||
Notification(
|
Notification(
|
||||||
user=self.customer.user,
|
user=self.customer.user,
|
||||||
@@ -842,10 +814,6 @@ class SellingQuerySet(models.QuerySet):
|
|||||||
class Selling(models.Model):
|
class Selling(models.Model):
|
||||||
"""Handle the sellings."""
|
"""Handle the sellings."""
|
||||||
|
|
||||||
class PaymentMethod(models.IntegerChoices):
|
|
||||||
SITH_ACCOUNT = 0, _("Sith account")
|
|
||||||
CARD = 1, _("Credit card")
|
|
||||||
|
|
||||||
# We make sure that sellings have a way begger label than any product name is allowed to
|
# We make sure that sellings have a way begger label than any product name is allowed to
|
||||||
label = models.CharField(_("label"), max_length=128)
|
label = models.CharField(_("label"), max_length=128)
|
||||||
product = models.ForeignKey(
|
product = models.ForeignKey(
|
||||||
@@ -882,9 +850,13 @@ class Selling(models.Model):
|
|||||||
on_delete=models.SET_NULL,
|
on_delete=models.SET_NULL,
|
||||||
)
|
)
|
||||||
date = models.DateTimeField(_("date"), db_index=True)
|
date = models.DateTimeField(_("date"), db_index=True)
|
||||||
payment_method = models.PositiveSmallIntegerField(
|
payment_method = models.CharField(
|
||||||
_("payment method"), choices=PaymentMethod, default=PaymentMethod.SITH_ACCOUNT
|
_("payment method"),
|
||||||
|
max_length=255,
|
||||||
|
choices=[("SITH_ACCOUNT", _("Sith account")), ("CARD", _("Credit card"))],
|
||||||
|
default="SITH_ACCOUNT",
|
||||||
)
|
)
|
||||||
|
is_validated = models.BooleanField(_("is validated"), default=False)
|
||||||
|
|
||||||
objects = SellingQuerySet.as_manager()
|
objects = SellingQuerySet.as_manager()
|
||||||
|
|
||||||
@@ -903,12 +875,10 @@ class Selling(models.Model):
|
|||||||
if not self.date:
|
if not self.date:
|
||||||
self.date = timezone.now()
|
self.date = timezone.now()
|
||||||
self.full_clean()
|
self.full_clean()
|
||||||
if (
|
if not self.is_validated:
|
||||||
self._state.adding
|
|
||||||
and self.payment_method == self.PaymentMethod.SITH_ACCOUNT
|
|
||||||
):
|
|
||||||
self.customer.amount -= self.quantity * self.unit_price
|
self.customer.amount -= self.quantity * self.unit_price
|
||||||
self.customer.save(allow_negative=allow_negative)
|
self.customer.save(allow_negative=allow_negative)
|
||||||
|
self.is_validated = True
|
||||||
user = self.customer.user
|
user = self.customer.user
|
||||||
if user.was_subscribed:
|
if user.was_subscribed:
|
||||||
if (
|
if (
|
||||||
@@ -978,9 +948,7 @@ class Selling(models.Model):
|
|||||||
def is_owned_by(self, user: User) -> bool:
|
def is_owned_by(self, user: User) -> bool:
|
||||||
if user.is_anonymous:
|
if user.is_anonymous:
|
||||||
return False
|
return False
|
||||||
return self.payment_method != self.PaymentMethod.CARD and user.is_owner(
|
return self.payment_method != "CARD" and user.is_owner(self.counter)
|
||||||
self.counter
|
|
||||||
)
|
|
||||||
|
|
||||||
def can_be_viewed_by(self, user: User) -> bool:
|
def can_be_viewed_by(self, user: User) -> bool:
|
||||||
if (
|
if (
|
||||||
@@ -990,7 +958,7 @@ class Selling(models.Model):
|
|||||||
return user == self.customer.user
|
return user == self.customer.user
|
||||||
|
|
||||||
def delete(self, *args, **kwargs):
|
def delete(self, *args, **kwargs):
|
||||||
if self.payment_method == Selling.PaymentMethod.SITH_ACCOUNT:
|
if self.payment_method == "SITH_ACCOUNT":
|
||||||
self.customer.amount += self.quantity * self.unit_price
|
self.customer.amount += self.quantity * self.unit_price
|
||||||
self.customer.save()
|
self.customer.save()
|
||||||
super().delete(*args, **kwargs)
|
super().delete(*args, **kwargs)
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
from datetime import datetime
|
|
||||||
from typing import Annotated, Self
|
from typing import Annotated, Self
|
||||||
|
|
||||||
|
from annotated_types import MinLen
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from ninja import FilterLookup, FilterSchema, ModelSchema, Schema
|
from ninja import Field, FilterSchema, ModelSchema, Schema
|
||||||
from pydantic import model_validator
|
from pydantic import model_validator
|
||||||
|
|
||||||
from club.schemas import SimpleClubSchema
|
from club.schemas import SimpleClubSchema
|
||||||
from core.schemas import GroupSchema, NonEmptyStr, SimpleUserSchema
|
from core.schemas import GroupSchema, SimpleUserSchema
|
||||||
from counter.models import Counter, Product, ProductType
|
from counter.models import Counter, Product, ProductType
|
||||||
|
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ class CounterSchema(ModelSchema):
|
|||||||
|
|
||||||
|
|
||||||
class CounterFilterSchema(FilterSchema):
|
class CounterFilterSchema(FilterSchema):
|
||||||
search: Annotated[NonEmptyStr | None, FilterLookup("name__icontains")] = None
|
search: Annotated[str, MinLen(1)] = Field(None, q="name__icontains")
|
||||||
|
|
||||||
|
|
||||||
class SimplifiedCounterSchema(ModelSchema):
|
class SimplifiedCounterSchema(ModelSchema):
|
||||||
@@ -92,18 +92,11 @@ class ProductSchema(ModelSchema):
|
|||||||
|
|
||||||
|
|
||||||
class ProductFilterSchema(FilterSchema):
|
class ProductFilterSchema(FilterSchema):
|
||||||
search: Annotated[
|
search: Annotated[str, MinLen(1)] | None = Field(
|
||||||
NonEmptyStr | None, FilterLookup(["name__icontains", "code__icontains"])
|
None, q=["name__icontains", "code__icontains"]
|
||||||
] = None
|
)
|
||||||
is_archived: Annotated[bool | None, FilterLookup("archived")] = None
|
is_archived: bool | None = Field(None, q="archived")
|
||||||
buying_groups: Annotated[set[int] | None, FilterLookup("buying_groups__in")] = None
|
buying_groups: set[int] | None = Field(None, q="buying_groups__in")
|
||||||
product_type: Annotated[set[int] | None, FilterLookup("product_type__in")] = None
|
product_type: set[int] | None = Field(None, q="product_type__in")
|
||||||
club: Annotated[set[int] | None, FilterLookup("club__in")] = None
|
club: set[int] | None = Field(None, q="club__in")
|
||||||
counter: Annotated[set[int] | None, FilterLookup("counters__in")] = None
|
counter: set[int] | None = Field(None, q="counters__in")
|
||||||
|
|
||||||
|
|
||||||
class SaleFilterSchema(FilterSchema):
|
|
||||||
before: Annotated[datetime | None, FilterLookup("date__lt")] = None
|
|
||||||
after: Annotated[datetime | None, FilterLookup("date__gt")] = None
|
|
||||||
counters: Annotated[set[int] | None, FilterLookup("counter__in")] = None
|
|
||||||
products: Annotated[set[int] | None, FilterLookup("product__in")] = None
|
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
import { AlertMessage } from "#core:utils/alert-message";
|
import { AlertMessage } from "#core:utils/alert-message";
|
||||||
import { BasketItem } from "#counter:counter/basket";
|
import { BasketItem } from "#counter:counter/basket";
|
||||||
import type {
|
import type { CounterConfig, ErrorMessage } from "#counter:counter/types";
|
||||||
CounterConfig,
|
|
||||||
ErrorMessage,
|
|
||||||
ProductFormula,
|
|
||||||
} from "#counter:counter/types";
|
|
||||||
import type { CounterProductSelect } from "./components/counter-product-select-index.ts";
|
import type { CounterProductSelect } from "./components/counter-product-select-index.ts";
|
||||||
|
|
||||||
document.addEventListener("alpine:init", () => {
|
document.addEventListener("alpine:init", () => {
|
||||||
@@ -51,43 +47,15 @@ document.addEventListener("alpine:init", () => {
|
|||||||
|
|
||||||
this.basket[id] = item;
|
this.basket[id] = item;
|
||||||
|
|
||||||
this.checkFormulas();
|
|
||||||
|
|
||||||
if (this.sumBasket() > this.customerBalance) {
|
if (this.sumBasket() > this.customerBalance) {
|
||||||
item.quantity = oldQty;
|
item.quantity = oldQty;
|
||||||
if (item.quantity === 0) {
|
if (item.quantity === 0) {
|
||||||
delete this.basket[id];
|
delete this.basket[id];
|
||||||
}
|
}
|
||||||
this.alertMessage.display(gettext("Not enough money"), { success: false });
|
return gettext("Not enough money");
|
||||||
}
|
}
|
||||||
},
|
|
||||||
|
|
||||||
checkFormulas() {
|
return "";
|
||||||
const products = new Set(
|
|
||||||
Object.keys(this.basket).map((i: string) => Number.parseInt(i)),
|
|
||||||
);
|
|
||||||
const formula: ProductFormula = config.formulas.find((f: ProductFormula) => {
|
|
||||||
return f.products.every((p: number) => products.has(p));
|
|
||||||
});
|
|
||||||
if (formula === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (const product of formula.products) {
|
|
||||||
const key = product.toString();
|
|
||||||
this.basket[key].quantity -= 1;
|
|
||||||
if (this.basket[key].quantity <= 0) {
|
|
||||||
this.removeFromBasket(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.alertMessage.display(
|
|
||||||
interpolate(
|
|
||||||
gettext("Formula %(formula)s applied"),
|
|
||||||
{ formula: config.products[formula.result.toString()].name },
|
|
||||||
true,
|
|
||||||
),
|
|
||||||
{ success: true },
|
|
||||||
);
|
|
||||||
this.addToBasket(formula.result.toString(), 1);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getBasketSize() {
|
getBasketSize() {
|
||||||
@@ -102,7 +70,14 @@ document.addEventListener("alpine:init", () => {
|
|||||||
(acc: number, cur: BasketItem) => acc + cur.sum(),
|
(acc: number, cur: BasketItem) => acc + cur.sum(),
|
||||||
0,
|
0,
|
||||||
) as number;
|
) as number;
|
||||||
return Math.round(total * 100) / 100;
|
return total;
|
||||||
|
},
|
||||||
|
|
||||||
|
addToBasketWithMessage(id: string, quantity: number) {
|
||||||
|
const message = this.addToBasket(id, quantity);
|
||||||
|
if (message.length > 0) {
|
||||||
|
this.alertMessage.display(message, { success: false });
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
onRefillingSuccess(event: CustomEvent) {
|
onRefillingSuccess(event: CustomEvent) {
|
||||||
@@ -141,7 +116,7 @@ document.addEventListener("alpine:init", () => {
|
|||||||
this.finish();
|
this.finish();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.addToBasket(code, quantity);
|
this.addToBasketWithMessage(code, quantity);
|
||||||
}
|
}
|
||||||
this.codeField.widget.clear();
|
this.codeField.widget.clear();
|
||||||
this.codeField.widget.focus();
|
this.codeField.widget.focus();
|
||||||
|
|||||||
6
counter/static/bundled/counter/types.d.ts
vendored
6
counter/static/bundled/counter/types.d.ts
vendored
@@ -7,16 +7,10 @@ export interface InitialFormData {
|
|||||||
errors?: string[];
|
errors?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProductFormula {
|
|
||||||
result: number;
|
|
||||||
products: number[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CounterConfig {
|
export interface CounterConfig {
|
||||||
customerBalance: number;
|
customerBalance: number;
|
||||||
customerId: number;
|
customerId: number;
|
||||||
products: Record<string, Product>;
|
products: Record<string, Product>;
|
||||||
formulas: ProductFormula[];
|
|
||||||
formInitial: InitialFormData[];
|
formInitial: InitialFormData[];
|
||||||
cancelUrl: string;
|
cancelUrl: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,12 @@
|
|||||||
float: right;
|
float: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
.basket-message-container {
|
.basket-error-container {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: block
|
display: block
|
||||||
}
|
}
|
||||||
|
|
||||||
.basket-message {
|
.basket-error {
|
||||||
z-index: 10; // to get on top of tomselect
|
z-index: 10; // to get on top of tomselect
|
||||||
text-align: center;
|
text-align: center;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|||||||
@@ -32,11 +32,13 @@
|
|||||||
<div id="bar-ui" x-data="counter({
|
<div id="bar-ui" x-data="counter({
|
||||||
customerBalance: {{ customer.amount }},
|
customerBalance: {{ customer.amount }},
|
||||||
products: products,
|
products: products,
|
||||||
formulas: formulas,
|
|
||||||
customerId: {{ customer.pk }},
|
customerId: {{ customer.pk }},
|
||||||
formInitial: formInitial,
|
formInitial: formInitial,
|
||||||
cancelUrl: '{{ cancel_url }}',
|
cancelUrl: '{{ cancel_url }}',
|
||||||
})">
|
})">
|
||||||
|
<noscript>
|
||||||
|
<p class="important">Javascript is required for the counter UI.</p>
|
||||||
|
</noscript>
|
||||||
|
|
||||||
<div id="user_info">
|
<div id="user_info">
|
||||||
<h5>{% trans %}Customer{% endtrans %}</h5>
|
<h5>{% trans %}Customer{% endtrans %}</h5>
|
||||||
@@ -86,12 +88,11 @@
|
|||||||
|
|
||||||
<form x-cloak method="post" action="" x-ref="basketForm">
|
<form x-cloak method="post" action="" x-ref="basketForm">
|
||||||
|
|
||||||
<div class="basket-message-container">
|
<div class="basket-error-container">
|
||||||
<div
|
<div
|
||||||
x-cloak
|
x-cloak
|
||||||
class="alert basket-message"
|
class="alert alert-red basket-error"
|
||||||
:class="alertMessage.success ? 'alert-green' : 'alert-red'"
|
x-show="alertMessage.show"
|
||||||
x-show="alertMessage.open"
|
|
||||||
x-transition.duration.500ms
|
x-transition.duration.500ms
|
||||||
x-text="alertMessage.content"
|
x-text="alertMessage.content"
|
||||||
></div>
|
></div>
|
||||||
@@ -110,9 +111,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<button @click.prevent="addToBasket(item.product.id, -1)">-</button>
|
<button @click.prevent="addToBasketWithMessage(item.product.id, -1)">-</button>
|
||||||
<span class="quantity" x-text="item.quantity"></span>
|
<span class="quantity" x-text="item.quantity"></span>
|
||||||
<button @click.prevent="addToBasket(item.product.id, 1)">+</button>
|
<button @click.prevent="addToBasketWithMessage(item.product.id, 1)">+</button>
|
||||||
|
|
||||||
<span x-text="item.product.name"></span> :
|
<span x-text="item.product.name"></span> :
|
||||||
<span x-text="item.sum().toLocaleString(undefined, { minimumFractionDigits: 2 })">€</span>
|
<span x-text="item.sum().toLocaleString(undefined, { minimumFractionDigits: 2 })">€</span>
|
||||||
@@ -212,7 +213,7 @@
|
|||||||
<h5 class="margin-bottom">{{ category }}</h5>
|
<h5 class="margin-bottom">{{ category }}</h5>
|
||||||
<div class="row gap-2x">
|
<div class="row gap-2x">
|
||||||
{% for product in categories[category] -%}
|
{% for product in categories[category] -%}
|
||||||
<button class="card shadow" @click="addToBasket('{{ product.id }}', 1)">
|
<button class="card shadow" @click="addToBasketWithMessage('{{ product.id }}', 1)">
|
||||||
<img
|
<img
|
||||||
class="card-image"
|
class="card-image"
|
||||||
alt="image de {{ product.name }}"
|
alt="image de {{ product.name }}"
|
||||||
@@ -251,18 +252,6 @@
|
|||||||
},
|
},
|
||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
};
|
};
|
||||||
const formulas = [
|
|
||||||
{%- for formula in formulas -%}
|
|
||||||
{
|
|
||||||
result: {{ formula.result_id }},
|
|
||||||
products: [
|
|
||||||
{%- for product in formula.products.all() -%}
|
|
||||||
{{ product.id }},
|
|
||||||
{%- endfor -%}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{%- endfor -%}
|
|
||||||
];
|
|
||||||
const formInitial = [
|
const formInitial = [
|
||||||
{%- for f in form -%}
|
{%- for f in form -%}
|
||||||
{%- if f.cleaned_data -%}
|
{%- if f.cleaned_data -%}
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{% trans %}Product formulas{% endtrans %}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("core/components/card.scss") }}">
|
|
||||||
<link rel="stylesheet" href="{{ static("counter/css/admin.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h3 class="margin-bottom">{% trans %}Product formulas{% endtrans %}</h3>
|
|
||||||
<p>
|
|
||||||
<a href="{{ url('counter:product_formula_create') }}" class="btn btn-blue">
|
|
||||||
{% trans %}New formula{% endtrans %}
|
|
||||||
<i class="fa fa-plus"></i>
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
<ul class="product-group">
|
|
||||||
{%- for formula in object_list -%}
|
|
||||||
<li>
|
|
||||||
<a href="{{ url('counter:product_formula_edit', formula_id=formula.id) }}">
|
|
||||||
{{ formula.result.name }}
|
|
||||||
</a>
|
|
||||||
<a href="{{ url('counter:product_formula_delete', formula_id=formula.id) }}">
|
|
||||||
<i class="fa fa-trash delete-action"></i>
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
{%- endfor -%}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -89,7 +89,7 @@
|
|||||||
:disabled="csvLoading"
|
:disabled="csvLoading"
|
||||||
:aria-busy="csvLoading"
|
:aria-busy="csvLoading"
|
||||||
>
|
>
|
||||||
{% trans %}Download as csv{% endtrans %} <i class="fa fa-file-arrow-down"></i>
|
{% trans %}Download as cvs{% endtrans %} <i class="fa fa-file-arrow-down"></i>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -51,7 +51,7 @@
|
|||||||
<td>{{ loop.index }}</td>
|
<td>{{ loop.index }}</td>
|
||||||
<td>{{ barman.name }} {% if barman.nickname %}({{ barman.nickname }}){% endif %}</td>
|
<td>{{ barman.name }} {% if barman.nickname %}({{ barman.nickname }}){% endif %}</td>
|
||||||
<td>{{ barman.promo or '' }}</td>
|
<td>{{ barman.promo or '' }}</td>
|
||||||
<td>{{ barman.perm_sum|format_timedelta }}</td>
|
<td>{{ barman.perm_sum|format_timedelta|truncate_time("millis") }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -73,7 +73,7 @@
|
|||||||
<td>{{ loop.index }}</td>
|
<td>{{ loop.index }}</td>
|
||||||
<td>{{ barman.name }} {% if barman.nickname %}({{ barman.nickname }}){% endif %}</td>
|
<td>{{ barman.name }} {% if barman.nickname %}({{ barman.nickname }}){% endif %}</td>
|
||||||
<td>{{ barman.promo or '' }}</td>
|
<td>{{ barman.promo or '' }}</td>
|
||||||
<td>{{ barman.perm_sum|format_timedelta }}</td>
|
<td>{{ barman.perm_sum|format_timedelta|truncate_time("millis") }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -116,6 +116,7 @@ class TestAccountDumpCommand(TestAccountDump):
|
|||||||
operation: Selling = customer.buyings.order_by("date").last()
|
operation: Selling = customer.buyings.order_by("date").last()
|
||||||
assert operation.unit_price == initial_amount
|
assert operation.unit_price == initial_amount
|
||||||
assert operation.counter_id == settings.SITH_COUNTER_ACCOUNT_DUMP_ID
|
assert operation.counter_id == settings.SITH_COUNTER_ACCOUNT_DUMP_ID
|
||||||
|
assert operation.is_validated is True
|
||||||
dump = customer.dumps.last()
|
dump = customer.dumps.last()
|
||||||
assert dump.dump_operation == operation
|
assert dump.dump_operation == operation
|
||||||
|
|
||||||
|
|||||||
@@ -11,12 +11,8 @@ from model_bakery import baker
|
|||||||
|
|
||||||
from core.models import Group, User
|
from core.models import Group, User
|
||||||
from counter.baker_recipes import counter_recipe, product_recipe
|
from counter.baker_recipes import counter_recipe, product_recipe
|
||||||
from counter.forms import (
|
from counter.forms import ScheduledProductActionForm, ScheduledProductActionFormSet
|
||||||
ProductForm,
|
from counter.models import ScheduledProductAction
|
||||||
ScheduledProductActionForm,
|
|
||||||
ScheduledProductActionFormSet,
|
|
||||||
)
|
|
||||||
from counter.models import Product, ScheduledProductAction
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -38,39 +34,6 @@ def test_edit_product(client: Client):
|
|||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
def test_create_actions_alongside_product():
|
|
||||||
"""The form should work when the product and the actions are created alongside."""
|
|
||||||
# non-persisted instance
|
|
||||||
product: Product = product_recipe.prepare(_save_related=True)
|
|
||||||
trigger_at = now() + timedelta(minutes=10)
|
|
||||||
form = ProductForm(
|
|
||||||
data={
|
|
||||||
"name": "foo",
|
|
||||||
"description": "bar",
|
|
||||||
"product_type": product.product_type_id,
|
|
||||||
"club": product.club_id,
|
|
||||||
"code": "FOO",
|
|
||||||
"purchase_price": 1.0,
|
|
||||||
"selling_price": 1.0,
|
|
||||||
"special_selling_price": 1.0,
|
|
||||||
"limit_age": 0,
|
|
||||||
"form-TOTAL_FORMS": "2",
|
|
||||||
"form-INITIAL_FORMS": "0",
|
|
||||||
"form-0-task": "counter.tasks.archive_product",
|
|
||||||
"form-0-trigger_at": trigger_at,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert form.is_valid()
|
|
||||||
product = form.save()
|
|
||||||
action = ScheduledProductAction.objects.last()
|
|
||||||
assert action.clocked.clocked_time == trigger_at
|
|
||||||
assert action.enabled is True
|
|
||||||
assert action.one_off is True
|
|
||||||
assert action.task == "counter.tasks.archive_product"
|
|
||||||
assert action.kwargs == json.dumps({"product_id": product.id})
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
class TestProductActionForm:
|
class TestProductActionForm:
|
||||||
def test_single_form_archive(self):
|
def test_single_form_archive(self):
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ def set_age(user: User, age: int):
|
|||||||
|
|
||||||
|
|
||||||
def force_refill_user(user: User, amount: Decimal | int):
|
def force_refill_user(user: User, amount: Decimal | int):
|
||||||
baker.make(Refilling, amount=amount, customer=user.customer)
|
baker.make(Refilling, amount=amount, customer=user.customer, is_validated=False)
|
||||||
|
|
||||||
|
|
||||||
class TestFullClickBase(TestCase):
|
class TestFullClickBase(TestCase):
|
||||||
@@ -115,10 +115,18 @@ class TestRefilling(TestFullClickBase):
|
|||||||
) -> HttpResponse:
|
) -> HttpResponse:
|
||||||
used_client = client if client is not None else self.client
|
used_client = client if client is not None else self.client
|
||||||
return used_client.post(
|
return used_client.post(
|
||||||
reverse("counter:refilling_create", kwargs={"customer_id": user.pk}),
|
reverse(
|
||||||
{"amount": str(amount), "payment_method": Refilling.PaymentMethod.CASH},
|
"counter:refilling_create",
|
||||||
|
kwargs={"customer_id": user.pk},
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"amount": str(amount),
|
||||||
|
"payment_method": "CASH",
|
||||||
|
"bank": "OTHER",
|
||||||
|
},
|
||||||
HTTP_REFERER=reverse(
|
HTTP_REFERER=reverse(
|
||||||
"counter:click", kwargs={"counter_id": counter.id, "user_id": user.pk}
|
"counter:click",
|
||||||
|
kwargs={"counter_id": counter.id, "user_id": user.pk},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -141,7 +149,11 @@ class TestRefilling(TestFullClickBase):
|
|||||||
"counter:refilling_create",
|
"counter:refilling_create",
|
||||||
kwargs={"customer_id": self.customer.pk},
|
kwargs={"customer_id": self.customer.pk},
|
||||||
),
|
),
|
||||||
{"amount": "10", "payment_method": "CASH"},
|
{
|
||||||
|
"amount": "10",
|
||||||
|
"payment_method": "CASH",
|
||||||
|
"bank": "OTHER",
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
self.client.force_login(self.club_admin)
|
self.client.force_login(self.club_admin)
|
||||||
|
|||||||
@@ -298,6 +298,7 @@ def test_update_balance():
|
|||||||
_quantity=len(customers),
|
_quantity=len(customers),
|
||||||
unit_price=10,
|
unit_price=10,
|
||||||
quantity=1,
|
quantity=1,
|
||||||
|
payment_method="SITH_ACCOUNT",
|
||||||
_save_related=True,
|
_save_related=True,
|
||||||
),
|
),
|
||||||
*sale_recipe.prepare(
|
*sale_recipe.prepare(
|
||||||
@@ -305,12 +306,14 @@ def test_update_balance():
|
|||||||
_quantity=3,
|
_quantity=3,
|
||||||
unit_price=5,
|
unit_price=5,
|
||||||
quantity=2,
|
quantity=2,
|
||||||
|
payment_method="SITH_ACCOUNT",
|
||||||
_save_related=True,
|
_save_related=True,
|
||||||
),
|
),
|
||||||
sale_recipe.prepare(
|
sale_recipe.prepare(
|
||||||
customer=customers[4],
|
customer=customers[4],
|
||||||
quantity=1,
|
quantity=1,
|
||||||
unit_price=50,
|
unit_price=50,
|
||||||
|
payment_method="SITH_ACCOUNT",
|
||||||
_save_related=True,
|
_save_related=True,
|
||||||
),
|
),
|
||||||
*sale_recipe.prepare(
|
*sale_recipe.prepare(
|
||||||
@@ -321,7 +324,7 @@ def test_update_balance():
|
|||||||
_quantity=len(customers),
|
_quantity=len(customers),
|
||||||
unit_price=50,
|
unit_price=50,
|
||||||
quantity=1,
|
quantity=1,
|
||||||
payment_method=Selling.PaymentMethod.CARD,
|
payment_method="CARD",
|
||||||
_save_related=True,
|
_save_related=True,
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
from counter.baker_recipes import product_recipe
|
|
||||||
from counter.forms import ProductFormulaForm
|
|
||||||
|
|
||||||
|
|
||||||
class TestFormulaForm(TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpTestData(cls):
|
|
||||||
cls.products = product_recipe.make(
|
|
||||||
selling_price=iter([1.5, 1, 1]),
|
|
||||||
special_selling_price=iter([1.4, 0.9, 0.9]),
|
|
||||||
_quantity=3,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_ok(self):
|
|
||||||
form = ProductFormulaForm(
|
|
||||||
data={
|
|
||||||
"result": self.products[0].id,
|
|
||||||
"products": [self.products[1].id, self.products[2].id],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
assert form.is_valid()
|
|
||||||
formula = form.save()
|
|
||||||
assert formula.result == self.products[0]
|
|
||||||
assert set(formula.products.all()) == set(self.products[1:])
|
|
||||||
|
|
||||||
def test_price_invalid(self):
|
|
||||||
self.products[0].selling_price = 2.1
|
|
||||||
self.products[0].save()
|
|
||||||
form = ProductFormulaForm(
|
|
||||||
data={
|
|
||||||
"result": self.products[0].id,
|
|
||||||
"products": [self.products[1].id, self.products[2].id],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
assert not form.is_valid()
|
|
||||||
assert form.errors == {
|
|
||||||
"result": [
|
|
||||||
"Le résultat ne peut pas être plus cher "
|
|
||||||
"que le total des autres produits."
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_product_both_in_result_and_products(self):
|
|
||||||
form = ProductFormulaForm(
|
|
||||||
data={
|
|
||||||
"result": self.products[0].id,
|
|
||||||
"products": [self.products[0].id, self.products[1].id],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
assert not form.is_valid()
|
|
||||||
assert form.errors == {
|
|
||||||
"__all__": [
|
|
||||||
"Un même produit ne peut pas être à la fois "
|
|
||||||
"le résultat et un élément de la formule."
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,7 @@ from django.contrib.auth.models import Permission
|
|||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.test import Client
|
from django.test import Client
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import localdate
|
||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertRedirects
|
from pytest_django.asserts import assertRedirects
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ def test_invoice_call_view(client: Client, query: dict | None):
|
|||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_invoice_call_form():
|
def test_invoice_call_form():
|
||||||
Selling.objects.all().delete()
|
Selling.objects.all().delete()
|
||||||
month = now() - relativedelta(months=1)
|
month = localdate() - relativedelta(months=1)
|
||||||
clubs = baker.make(Club, _quantity=2)
|
clubs = baker.make(Club, _quantity=2)
|
||||||
recipe = sale_recipe.extend(date=month, customer=baker.make(Customer, amount=10000))
|
recipe = sale_recipe.extend(date=month, customer=baker.make(Customer, amount=10000))
|
||||||
recipe.make(club=clubs[0], quantity=2, unit_price=200)
|
recipe.make(club=clubs[0], quantity=2, unit_price=200)
|
||||||
|
|||||||
@@ -15,9 +15,8 @@ from pytest_django.asserts import assertNumQueries, assertRedirects
|
|||||||
from club.models import Club
|
from club.models import Club
|
||||||
from core.baker_recipes import board_user, subscriber_user
|
from core.baker_recipes import board_user, subscriber_user
|
||||||
from core.models import Group, User
|
from core.models import Group, User
|
||||||
from counter.baker_recipes import product_recipe
|
|
||||||
from counter.forms import ProductForm
|
from counter.forms import ProductForm
|
||||||
from counter.models import Product, ProductFormula, ProductType
|
from counter.models import Product, ProductType
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
@@ -94,9 +93,6 @@ class TestCreateProduct(TestCase):
|
|||||||
def setUpTestData(cls):
|
def setUpTestData(cls):
|
||||||
cls.product_type = baker.make(ProductType)
|
cls.product_type = baker.make(ProductType)
|
||||||
cls.club = baker.make(Club)
|
cls.club = baker.make(Club)
|
||||||
cls.counter_admin = baker.make(
|
|
||||||
User, groups=[Group.objects.get(id=settings.SITH_GROUP_COUNTER_ADMIN_ID)]
|
|
||||||
)
|
|
||||||
cls.data = {
|
cls.data = {
|
||||||
"name": "foo",
|
"name": "foo",
|
||||||
"description": "bar",
|
"description": "bar",
|
||||||
@@ -120,36 +116,13 @@ class TestCreateProduct(TestCase):
|
|||||||
assert instance.name == "foo"
|
assert instance.name == "foo"
|
||||||
assert instance.selling_price == 1.0
|
assert instance.selling_price == 1.0
|
||||||
|
|
||||||
def test_form_with_product_from_formula(self):
|
|
||||||
"""Test when the edited product is a result of a formula."""
|
|
||||||
self.client.force_login(self.counter_admin)
|
|
||||||
products = product_recipe.make(
|
|
||||||
selling_price=iter([1.5, 1, 1]),
|
|
||||||
special_selling_price=iter([1.4, 0.9, 0.9]),
|
|
||||||
_quantity=3,
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
baker.make(ProductFormula, result=products[0], products=products[1:])
|
|
||||||
|
|
||||||
data = self.data | {"selling_price": 1.7, "special_selling_price": 1.5}
|
|
||||||
form = ProductForm(data=data, instance=products[0])
|
|
||||||
assert form.is_valid()
|
|
||||||
|
|
||||||
# it shouldn't be possible to give a price higher than the formula's products
|
|
||||||
data = self.data | {"selling_price": 2.1, "special_selling_price": 1.9}
|
|
||||||
form = ProductForm(data=data, instance=products[0])
|
|
||||||
assert not form.is_valid()
|
|
||||||
assert form.errors == {
|
|
||||||
"selling_price": [
|
|
||||||
"Assurez-vous que cette valeur est inférieure ou égale à 2.00."
|
|
||||||
],
|
|
||||||
"special_selling_price": [
|
|
||||||
"Assurez-vous que cette valeur est inférieure ou égale à 1.80."
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_view(self):
|
def test_view(self):
|
||||||
self.client.force_login(self.counter_admin)
|
self.client.force_login(
|
||||||
|
baker.make(
|
||||||
|
User,
|
||||||
|
groups=[Group.objects.get(id=settings.SITH_GROUP_COUNTER_ADMIN_ID)],
|
||||||
|
)
|
||||||
|
)
|
||||||
url = reverse("counter:new_product")
|
url = reverse("counter:new_product")
|
||||||
response = self.client.get(url)
|
response = self.client.get(url)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
|
|||||||
@@ -25,10 +25,6 @@ from counter.views.admin import (
|
|||||||
CounterStatView,
|
CounterStatView,
|
||||||
ProductCreateView,
|
ProductCreateView,
|
||||||
ProductEditView,
|
ProductEditView,
|
||||||
ProductFormulaCreateView,
|
|
||||||
ProductFormulaDeleteView,
|
|
||||||
ProductFormulaEditView,
|
|
||||||
ProductFormulaListView,
|
|
||||||
ProductListView,
|
ProductListView,
|
||||||
ProductTypeCreateView,
|
ProductTypeCreateView,
|
||||||
ProductTypeEditView,
|
ProductTypeEditView,
|
||||||
@@ -120,24 +116,6 @@ urlpatterns = [
|
|||||||
ProductEditView.as_view(),
|
ProductEditView.as_view(),
|
||||||
name="product_edit",
|
name="product_edit",
|
||||||
),
|
),
|
||||||
path(
|
|
||||||
"admin/formula/", ProductFormulaListView.as_view(), name="product_formula_list"
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"admin/formula/new/",
|
|
||||||
ProductFormulaCreateView.as_view(),
|
|
||||||
name="product_formula_create",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"admin/formula/<int:formula_id>/edit",
|
|
||||||
ProductFormulaEditView.as_view(),
|
|
||||||
name="product_formula_edit",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"admin/formula/<int:formula_id>/delete",
|
|
||||||
ProductFormulaDeleteView.as_view(),
|
|
||||||
name="product_formula_delete",
|
|
||||||
),
|
|
||||||
path(
|
path(
|
||||||
"admin/product-type/list/",
|
"admin/product-type/list/",
|
||||||
ProductTypeListView.as_view(),
|
ProductTypeListView.as_view(),
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
from datetime import datetime, timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
|
||||||
@@ -23,7 +23,6 @@ from django.forms.models import modelform_factory
|
|||||||
from django.shortcuts import get_object_or_404
|
from django.shortcuts import get_object_or_404
|
||||||
from django.urls import reverse, reverse_lazy
|
from django.urls import reverse, reverse_lazy
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.utils.timezone import get_current_timezone
|
|
||||||
from django.utils.translation import gettext as _
|
from django.utils.translation import gettext as _
|
||||||
from django.views.generic import DetailView, ListView, TemplateView
|
from django.views.generic import DetailView, ListView, TemplateView
|
||||||
from django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView
|
from django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView
|
||||||
@@ -34,13 +33,11 @@ from counter.forms import (
|
|||||||
CloseCustomerAccountForm,
|
CloseCustomerAccountForm,
|
||||||
CounterEditForm,
|
CounterEditForm,
|
||||||
ProductForm,
|
ProductForm,
|
||||||
ProductFormulaForm,
|
|
||||||
ReturnableProductForm,
|
ReturnableProductForm,
|
||||||
)
|
)
|
||||||
from counter.models import (
|
from counter.models import (
|
||||||
Counter,
|
Counter,
|
||||||
Product,
|
Product,
|
||||||
ProductFormula,
|
|
||||||
ProductType,
|
ProductType,
|
||||||
Refilling,
|
Refilling,
|
||||||
ReturnableProduct,
|
ReturnableProduct,
|
||||||
@@ -164,49 +161,6 @@ class ProductEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
|||||||
current_tab = "products"
|
current_tab = "products"
|
||||||
|
|
||||||
|
|
||||||
class ProductFormulaListView(CounterAdminTabsMixin, PermissionRequiredMixin, ListView):
|
|
||||||
model = ProductFormula
|
|
||||||
queryset = ProductFormula.objects.select_related("result")
|
|
||||||
template_name = "counter/formula_list.jinja"
|
|
||||||
current_tab = "formulas"
|
|
||||||
permission_required = "counter.view_productformula"
|
|
||||||
|
|
||||||
|
|
||||||
class ProductFormulaCreateView(
|
|
||||||
CounterAdminTabsMixin, PermissionRequiredMixin, CreateView
|
|
||||||
):
|
|
||||||
model = ProductFormula
|
|
||||||
form_class = ProductFormulaForm
|
|
||||||
pk_url_kwarg = "formula_id"
|
|
||||||
template_name = "core/create.jinja"
|
|
||||||
current_tab = "formulas"
|
|
||||||
success_url = reverse_lazy("counter:product_formula_list")
|
|
||||||
permission_required = "counter.add_productformula"
|
|
||||||
|
|
||||||
|
|
||||||
class ProductFormulaEditView(
|
|
||||||
CounterAdminTabsMixin, PermissionRequiredMixin, UpdateView
|
|
||||||
):
|
|
||||||
model = ProductFormula
|
|
||||||
form_class = ProductFormulaForm
|
|
||||||
pk_url_kwarg = "formula_id"
|
|
||||||
template_name = "core/edit.jinja"
|
|
||||||
current_tab = "formulas"
|
|
||||||
success_url = reverse_lazy("counter:product_formula_list")
|
|
||||||
permission_required = "counter.change_productformula"
|
|
||||||
|
|
||||||
|
|
||||||
class ProductFormulaDeleteView(
|
|
||||||
CounterAdminTabsMixin, PermissionRequiredMixin, DeleteView
|
|
||||||
):
|
|
||||||
model = ProductFormula
|
|
||||||
pk_url_kwarg = "formula_id"
|
|
||||||
template_name = "core/delete_confirm.jinja"
|
|
||||||
current_tab = "formulas"
|
|
||||||
success_url = reverse_lazy("counter:product_formula_list")
|
|
||||||
permission_required = "counter.delete_productformula"
|
|
||||||
|
|
||||||
|
|
||||||
class ReturnableProductListView(
|
class ReturnableProductListView(
|
||||||
CounterAdminTabsMixin, PermissionRequiredMixin, ListView
|
CounterAdminTabsMixin, PermissionRequiredMixin, ListView
|
||||||
):
|
):
|
||||||
@@ -331,13 +285,7 @@ class CounterStatView(PermissionRequiredMixin, DetailView):
|
|||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
"""Add stats to the context."""
|
"""Add stats to the context."""
|
||||||
counter: Counter = self.object
|
counter: Counter = self.object
|
||||||
start_date = get_start_of_semester()
|
semester_start = get_start_of_semester()
|
||||||
semester_start = datetime(
|
|
||||||
start_date.year,
|
|
||||||
start_date.month,
|
|
||||||
start_date.day,
|
|
||||||
tzinfo=get_current_timezone(),
|
|
||||||
)
|
|
||||||
office_hours = counter.get_top_barmen()
|
office_hours = counter.get_top_barmen()
|
||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
kwargs.update(
|
kwargs.update(
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
from collections import defaultdict
|
|
||||||
|
|
||||||
from django.core.exceptions import PermissionDenied
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
@@ -32,7 +31,6 @@ from counter.forms import BasketForm, RefillForm
|
|||||||
from counter.models import (
|
from counter.models import (
|
||||||
Counter,
|
Counter,
|
||||||
Customer,
|
Customer,
|
||||||
ProductFormula,
|
|
||||||
ReturnableProduct,
|
ReturnableProduct,
|
||||||
Selling,
|
Selling,
|
||||||
)
|
)
|
||||||
@@ -208,13 +206,12 @@ class CounterClick(
|
|||||||
"""Add customer to the context."""
|
"""Add customer to the context."""
|
||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
kwargs["products"] = self.products
|
kwargs["products"] = self.products
|
||||||
kwargs["formulas"] = ProductFormula.objects.filter(
|
kwargs["categories"] = {}
|
||||||
result__in=self.products
|
|
||||||
).prefetch_related("products")
|
|
||||||
kwargs["categories"] = defaultdict(list)
|
|
||||||
for product in kwargs["products"]:
|
for product in kwargs["products"]:
|
||||||
if product.product_type:
|
if product.product_type:
|
||||||
kwargs["categories"][product.product_type].append(product)
|
kwargs["categories"].setdefault(product.product_type, []).append(
|
||||||
|
product
|
||||||
|
)
|
||||||
kwargs["customer"] = self.customer
|
kwargs["customer"] = self.customer
|
||||||
kwargs["cancel_url"] = self.get_success_url()
|
kwargs["cancel_url"] = self.get_success_url()
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
@@ -63,18 +63,19 @@ class InvoiceCallView(
|
|||||||
"""Add sums to the context."""
|
"""Add sums to the context."""
|
||||||
kwargs = super().get_context_data(**kwargs)
|
kwargs = super().get_context_data(**kwargs)
|
||||||
kwargs["months"] = Selling.objects.datetimes("date", "month", order="DESC")
|
kwargs["months"] = Selling.objects.datetimes("date", "month", order="DESC")
|
||||||
month = self.get_month()
|
start_date = self.get_month()
|
||||||
start_date = datetime(month.year, month.month, month.day, tzinfo=timezone.utc)
|
|
||||||
end_date = start_date + relativedelta(months=1)
|
end_date = start_date + relativedelta(months=1)
|
||||||
|
|
||||||
kwargs["sum_cb"] = Refilling.objects.filter(
|
kwargs["sum_cb"] = Refilling.objects.filter(
|
||||||
payment_method=Refilling.PaymentMethod.CARD,
|
payment_method="CARD",
|
||||||
|
is_validated=True,
|
||||||
date__gte=start_date,
|
date__gte=start_date,
|
||||||
date__lte=end_date,
|
date__lte=end_date,
|
||||||
).aggregate(res=Sum("amount", default=0))["res"]
|
).aggregate(res=Sum("amount", default=0))["res"]
|
||||||
kwargs["sum_cb"] += (
|
kwargs["sum_cb"] += (
|
||||||
Selling.objects.filter(
|
Selling.objects.filter(
|
||||||
payment_method=Selling.PaymentMethod.CARD,
|
payment_method="CARD",
|
||||||
|
is_validated=True,
|
||||||
date__gte=start_date,
|
date__gte=start_date,
|
||||||
date__lte=end_date,
|
date__lte=end_date,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -100,11 +100,6 @@ class CounterAdminTabsMixin(TabedViewMixin):
|
|||||||
"slug": "products",
|
"slug": "products",
|
||||||
"name": _("Products"),
|
"name": _("Products"),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"url": reverse_lazy("counter:product_formula_list"),
|
|
||||||
"slug": "formulas",
|
|
||||||
"name": _("Formulas"),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"url": reverse_lazy("counter:product_type_list"),
|
"url": reverse_lazy("counter:product_type_list"),
|
||||||
"slug": "product_types",
|
"slug": "product_types",
|
||||||
|
|||||||
@@ -110,9 +110,7 @@ class Basket(models.Model):
|
|||||||
)["total"]
|
)["total"]
|
||||||
)
|
)
|
||||||
|
|
||||||
def generate_sales(
|
def generate_sales(self, counter, seller: User, payment_method: str):
|
||||||
self, counter, seller: User, payment_method: Selling.PaymentMethod
|
|
||||||
):
|
|
||||||
"""Generate a list of sold items corresponding to the items
|
"""Generate a list of sold items corresponding to the items
|
||||||
of this basket WITHOUT saving them NOR deleting the basket.
|
of this basket WITHOUT saving them NOR deleting the basket.
|
||||||
|
|
||||||
@@ -253,7 +251,8 @@ class Invoice(models.Model):
|
|||||||
customer=customer,
|
customer=customer,
|
||||||
operator=self.user,
|
operator=self.user,
|
||||||
amount=i.product_unit_price * i.quantity,
|
amount=i.product_unit_price * i.quantity,
|
||||||
payment_method=Refilling.PaymentMethod.CARD,
|
payment_method="CARD",
|
||||||
|
bank="OTHER",
|
||||||
date=self.date,
|
date=self.date,
|
||||||
)
|
)
|
||||||
new.save()
|
new.save()
|
||||||
@@ -268,7 +267,8 @@ class Invoice(models.Model):
|
|||||||
customer=customer,
|
customer=customer,
|
||||||
unit_price=i.product_unit_price,
|
unit_price=i.product_unit_price,
|
||||||
quantity=i.quantity,
|
quantity=i.quantity,
|
||||||
payment_method=Selling.PaymentMethod.CARD,
|
payment_method="CARD",
|
||||||
|
is_validated=True,
|
||||||
date=self.date,
|
date=self.date,
|
||||||
)
|
)
|
||||||
new.save()
|
new.save()
|
||||||
|
|||||||
@@ -108,22 +108,12 @@ def test_eboutic_basket_expiry(
|
|||||||
|
|
||||||
client.force_login(customer.user)
|
client.force_login(customer.user)
|
||||||
|
|
||||||
if sellings:
|
for date in sellings:
|
||||||
sale_recipe.make(
|
sale_recipe.make(
|
||||||
customer=customer,
|
customer=customer, counter=eboutic, date=date, is_validated=True
|
||||||
counter=eboutic,
|
|
||||||
date=iter(sellings),
|
|
||||||
_quantity=len(sellings),
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
|
||||||
if refillings:
|
|
||||||
refill_recipe.make(
|
|
||||||
customer=customer,
|
|
||||||
counter=eboutic,
|
|
||||||
date=iter(refillings),
|
|
||||||
_quantity=len(refillings),
|
|
||||||
_bulk_create=True,
|
|
||||||
)
|
)
|
||||||
|
for date in refillings:
|
||||||
|
refill_recipe.make(customer=customer, counter=eboutic, date=date)
|
||||||
|
|
||||||
assert (
|
assert (
|
||||||
f'x-data="basket({int(expected.timestamp() * 1000) if expected else "null"})"'
|
f'x-data="basket({int(expected.timestamp() * 1000) if expected else "null"})"'
|
||||||
|
|||||||
@@ -114,13 +114,13 @@ class TestPaymentSith(TestPaymentBase):
|
|||||||
"quantity"
|
"quantity"
|
||||||
)
|
)
|
||||||
assert len(sellings) == 2
|
assert len(sellings) == 2
|
||||||
assert sellings[0].payment_method == Selling.PaymentMethod.SITH_ACCOUNT
|
assert sellings[0].payment_method == "SITH_ACCOUNT"
|
||||||
assert sellings[0].quantity == 1
|
assert sellings[0].quantity == 1
|
||||||
assert sellings[0].unit_price == self.snack.selling_price
|
assert sellings[0].unit_price == self.snack.selling_price
|
||||||
assert sellings[0].counter.type == "EBOUTIC"
|
assert sellings[0].counter.type == "EBOUTIC"
|
||||||
assert sellings[0].product == self.snack
|
assert sellings[0].product == self.snack
|
||||||
|
|
||||||
assert sellings[1].payment_method == Selling.PaymentMethod.SITH_ACCOUNT
|
assert sellings[1].payment_method == "SITH_ACCOUNT"
|
||||||
assert sellings[1].quantity == 2
|
assert sellings[1].quantity == 2
|
||||||
assert sellings[1].unit_price == self.beer.selling_price
|
assert sellings[1].unit_price == self.beer.selling_price
|
||||||
assert sellings[1].counter.type == "EBOUTIC"
|
assert sellings[1].counter.type == "EBOUTIC"
|
||||||
@@ -198,13 +198,13 @@ class TestPaymentCard(TestPaymentBase):
|
|||||||
"quantity"
|
"quantity"
|
||||||
)
|
)
|
||||||
assert len(sellings) == 2
|
assert len(sellings) == 2
|
||||||
assert sellings[0].payment_method == Selling.PaymentMethod.CARD
|
assert sellings[0].payment_method == "CARD"
|
||||||
assert sellings[0].quantity == 1
|
assert sellings[0].quantity == 1
|
||||||
assert sellings[0].unit_price == self.snack.selling_price
|
assert sellings[0].unit_price == self.snack.selling_price
|
||||||
assert sellings[0].counter.type == "EBOUTIC"
|
assert sellings[0].counter.type == "EBOUTIC"
|
||||||
assert sellings[0].product == self.snack
|
assert sellings[0].product == self.snack
|
||||||
|
|
||||||
assert sellings[1].payment_method == Selling.PaymentMethod.CARD
|
assert sellings[1].payment_method == "CARD"
|
||||||
assert sellings[1].quantity == 2
|
assert sellings[1].quantity == 2
|
||||||
assert sellings[1].unit_price == self.beer.selling_price
|
assert sellings[1].unit_price == self.beer.selling_price
|
||||||
assert sellings[1].counter.type == "EBOUTIC"
|
assert sellings[1].counter.type == "EBOUTIC"
|
||||||
|
|||||||
@@ -275,9 +275,7 @@ class EbouticPayWithSith(CanViewMixin, SingleObjectMixin, View):
|
|||||||
return redirect("eboutic:payment_result", "failure")
|
return redirect("eboutic:payment_result", "failure")
|
||||||
|
|
||||||
eboutic = get_eboutic()
|
eboutic = get_eboutic()
|
||||||
sales = basket.generate_sales(
|
sales = basket.generate_sales(eboutic, basket.user, "SITH_ACCOUNT")
|
||||||
eboutic, basket.user, Selling.PaymentMethod.SITH_ACCOUNT
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
# Selling.save has some important business logic in it.
|
# Selling.save has some important business logic in it.
|
||||||
|
|||||||
@@ -141,7 +141,7 @@
|
|||||||
<label for="{{ input_id }}">
|
<label for="{{ input_id }}">
|
||||||
{%- endif %}
|
{%- endif %}
|
||||||
<figure>
|
<figure>
|
||||||
{%- if user.is_viewable %}
|
{%- if user.is_subscriber_viewable %}
|
||||||
{% if candidature.user.profile_pict %}
|
{% if candidature.user.profile_pict %}
|
||||||
<img class="candidate__picture" src="{{ candidature.user.profile_pict.get_download_url() }}" alt="{% trans %}Profile{% endtrans %}">
|
<img class="candidate__picture" src="{{ candidature.user.profile_pict.get_download_url() }}" alt="{% trans %}Profile{% endtrans %}">
|
||||||
{% else %}
|
{% else %}
|
||||||
|
|||||||
@@ -199,7 +199,7 @@ class Galaxy(models.Model):
|
|||||||
cls, picture_count_threshold: int = DEFAULT_PICTURE_COUNT_THRESHOLD
|
cls, picture_count_threshold: int = DEFAULT_PICTURE_COUNT_THRESHOLD
|
||||||
) -> QuerySet[User]:
|
) -> QuerySet[User]:
|
||||||
return (
|
return (
|
||||||
User.objects.filter(is_viewable=True)
|
User.objects.filter(is_subscriber_viewable=True)
|
||||||
.exclude(subscriptions=None)
|
.exclude(subscriptions=None)
|
||||||
.annotate(
|
.annotate(
|
||||||
pictures_count=Count("pictures"),
|
pictures_count=Count("pictures"),
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
import { default as ForceGraph3D } from "3d-force-graph";
|
|
||||||
import { forceX, forceY, forceZ } from "d3-force-3d";
|
|
||||||
// biome-ignore lint/style/noNamespaceImport: This is how it should be imported
|
|
||||||
import * as Three from "three";
|
|
||||||
import SpriteText from "three-spritetext";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @typedef GalaxyConfig
|
|
||||||
* @property {number} nodeId id of the current user node
|
|
||||||
* @property {string} dataUrl url to fetch the galaxy data from
|
|
||||||
**/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load the galaxy of an user
|
|
||||||
* @param {GalaxyConfig} config
|
|
||||||
**/
|
|
||||||
window.loadGalaxy = (config) => {
|
|
||||||
window.getNodeFromId = (id) => {
|
|
||||||
return Graph.graphData().nodes.find((n) => n.id === id);
|
|
||||||
};
|
|
||||||
|
|
||||||
window.getLinksFromNodeId = (id) => {
|
|
||||||
return Graph.graphData().links.filter(
|
|
||||||
(l) => l.source.id === id || l.target.id === id,
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
window.focusNode = (node) => {
|
|
||||||
highlightNodes.clear();
|
|
||||||
highlightLinks.clear();
|
|
||||||
|
|
||||||
hoverNode = node || null;
|
|
||||||
if (node) {
|
|
||||||
// collect neighbors and links for highlighting
|
|
||||||
for (const link of window.getLinksFromNodeId(node.id)) {
|
|
||||||
highlightLinks.add(link);
|
|
||||||
highlightNodes.add(link.source);
|
|
||||||
highlightNodes.add(link.target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// refresh node and link display
|
|
||||||
Graph.nodeThreeObject(Graph.nodeThreeObject())
|
|
||||||
.linkWidth(Graph.linkWidth())
|
|
||||||
.linkDirectionalParticles(Graph.linkDirectionalParticles());
|
|
||||||
|
|
||||||
// Aim at node from outside it
|
|
||||||
const distance = 42;
|
|
||||||
const distRatio = 1 + distance / Math.hypot(node.x, node.y, node.z);
|
|
||||||
|
|
||||||
const newPos =
|
|
||||||
node.x || node.y || node.z
|
|
||||||
? { x: node.x * distRatio, y: node.y * distRatio, z: node.z * distRatio }
|
|
||||||
: { x: 0, y: 0, z: distance }; // special case if node is in (0,0,0)
|
|
||||||
|
|
||||||
Graph.cameraPosition(
|
|
||||||
newPos, // new position
|
|
||||||
node, // lookAt ({ x, y, z })
|
|
||||||
3000, // ms transition duration
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const highlightNodes = new Set();
|
|
||||||
const highlightLinks = new Set();
|
|
||||||
let hoverNode = null;
|
|
||||||
|
|
||||||
const grpahDiv = document.getElementById("3d-graph");
|
|
||||||
const Graph = ForceGraph3D();
|
|
||||||
Graph(grpahDiv);
|
|
||||||
Graph.jsonUrl(config.dataUrl)
|
|
||||||
.width(
|
|
||||||
grpahDiv.parentElement.clientWidth > 1200
|
|
||||||
? 1200
|
|
||||||
: grpahDiv.parentElement.clientWidth,
|
|
||||||
) // Not perfect at all. JS-fu master from the future, please fix this :-)
|
|
||||||
.height(1000)
|
|
||||||
.enableNodeDrag(false) // allow easier navigation
|
|
||||||
.onNodeClick((node) => {
|
|
||||||
const camera = Graph.cameraPosition();
|
|
||||||
const distance = Math.sqrt(
|
|
||||||
(node.x - camera.x) ** 2 + (node.y - camera.y) ** 2 + (node.z - camera.z) ** 2,
|
|
||||||
);
|
|
||||||
if (distance < 120 || highlightNodes.has(node)) {
|
|
||||||
window.focusNode(node);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.linkWidth((link) => (highlightLinks.has(link) ? 0.4 : 0.0))
|
|
||||||
.linkColor((link) =>
|
|
||||||
highlightLinks.has(link) ? "rgba(255,160,0,1)" : "rgba(128,255,255,0.6)",
|
|
||||||
)
|
|
||||||
.linkVisibility((link) => highlightLinks.has(link))
|
|
||||||
.nodeVisibility((node) => highlightNodes.has(node) || node.mass > 4)
|
|
||||||
// .linkDirectionalParticles(link => highlightLinks.has(link) ? 3 : 1) // kinda buggy for now, and slows this a bit, but would be great to help visualize lanes
|
|
||||||
.linkDirectionalParticleWidth(0.2)
|
|
||||||
.linkDirectionalParticleSpeed(-0.006)
|
|
||||||
.nodeThreeObject((node) => {
|
|
||||||
const sprite = new SpriteText(node.name);
|
|
||||||
sprite.material.depthWrite = false; // make sprite background transparent
|
|
||||||
sprite.color = highlightNodes.has(node)
|
|
||||||
? node === hoverNode
|
|
||||||
? "rgba(200,0,0,1)"
|
|
||||||
: "rgba(255,160,0,0.8)"
|
|
||||||
: "rgba(0,255,255,0.2)";
|
|
||||||
sprite.textHeight = 2;
|
|
||||||
sprite.center = new Three.Vector2(1.2, 0.5);
|
|
||||||
return sprite;
|
|
||||||
})
|
|
||||||
.onEngineStop(() => {
|
|
||||||
window.focusNode(window.getNodeFromId(config.nodeId));
|
|
||||||
Graph.onEngineStop(() => {
|
|
||||||
/* nope */
|
|
||||||
}); // don't call ourselves in a loop while moving the focus
|
|
||||||
});
|
|
||||||
|
|
||||||
// Set distance between stars
|
|
||||||
Graph.d3Force("link").distance((link) => link.value);
|
|
||||||
|
|
||||||
// Set high masses nearer the center of the galaxy
|
|
||||||
// TODO: quick and dirty strength computation, this will need tuning.
|
|
||||||
Graph.d3Force(
|
|
||||||
"positionX",
|
|
||||||
forceX().strength((node) => {
|
|
||||||
return 1 - 1 / node.mass;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
Graph.d3Force(
|
|
||||||
"positionY",
|
|
||||||
forceY().strength((node) => {
|
|
||||||
return 1 - 1 / node.mass;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
Graph.d3Force(
|
|
||||||
"positionZ",
|
|
||||||
forceZ().strength((node) => {
|
|
||||||
return 1 - 1 / node.mass;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
137
galaxy/static/bundled/galaxy/galaxy-index.ts
Normal file
137
galaxy/static/bundled/galaxy/galaxy-index.ts
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
import { exportToHtml } from "#core:utils/globals";
|
||||||
|
|
||||||
|
import cytoscape from "cytoscape";
|
||||||
|
import d3Force, { type D3ForceLayoutOptions } from "cytoscape-d3-force";
|
||||||
|
|
||||||
|
cytoscape.use(d3Force);
|
||||||
|
|
||||||
|
interface GalaxyConfig {
|
||||||
|
nodeId: number;
|
||||||
|
dataUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getGraphData(dataUrl: string) {
|
||||||
|
const response = await fetch(dataUrl);
|
||||||
|
if (!response.ok) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = await response.json();
|
||||||
|
const nodes = content.nodes.map((node, i) => {
|
||||||
|
return {
|
||||||
|
group: "nodes",
|
||||||
|
data: {
|
||||||
|
id: node.id,
|
||||||
|
name: node.name,
|
||||||
|
mass: node.mass,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const edges = content.links.map((link) => {
|
||||||
|
return {
|
||||||
|
group: "edges",
|
||||||
|
data: {
|
||||||
|
id: `edge_${link.source}_${link.value}`,
|
||||||
|
source: link.source,
|
||||||
|
target: link.target,
|
||||||
|
value: link.value,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return { nodes: nodes, edges: edges };
|
||||||
|
}
|
||||||
|
|
||||||
|
exportToHtml("loadGalaxy", async (config: GalaxyConfig) => {
|
||||||
|
const graphDiv = document.getElementById("3d-graph");
|
||||||
|
const elements = await getGraphData(config.dataUrl);
|
||||||
|
const cy = cytoscape({
|
||||||
|
container: graphDiv,
|
||||||
|
elements: elements,
|
||||||
|
style: [
|
||||||
|
{
|
||||||
|
selector: "node",
|
||||||
|
style: {
|
||||||
|
label: "data(name)",
|
||||||
|
"background-color": "red",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
selector: ".focused",
|
||||||
|
style: {
|
||||||
|
"border-width": "5px",
|
||||||
|
"border-style": "solid",
|
||||||
|
"border-color": "black",
|
||||||
|
"target-arrow-color": "black",
|
||||||
|
"line-color": "black",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
selector: "edge",
|
||||||
|
style: {
|
||||||
|
width: 0.1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
selector: ".direct",
|
||||||
|
style: {
|
||||||
|
width: "5px",
|
||||||
|
"line-color": "red",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
layout: {
|
||||||
|
name: "d3-force",
|
||||||
|
animate: true,
|
||||||
|
fit: false,
|
||||||
|
ungrabifyWhileSimulating: true,
|
||||||
|
fixedAfterDragging: true,
|
||||||
|
|
||||||
|
linkId: (node) => {
|
||||||
|
return node.id;
|
||||||
|
},
|
||||||
|
|
||||||
|
linkDistance: (link) => {
|
||||||
|
return elements.nodes.length * 10;
|
||||||
|
},
|
||||||
|
|
||||||
|
linkStrength: (link) => {
|
||||||
|
return 1 / Math.max(1, link?.value);
|
||||||
|
},
|
||||||
|
|
||||||
|
linkIterations: 10,
|
||||||
|
|
||||||
|
manyBodyStrength: (node) => {
|
||||||
|
return node?.mass;
|
||||||
|
},
|
||||||
|
|
||||||
|
// manyBodyDistanceMin: 500,
|
||||||
|
collideRadius: () => {
|
||||||
|
return 50;
|
||||||
|
},
|
||||||
|
|
||||||
|
ready: (e) => {
|
||||||
|
// Center on current user node at the start of the simulation
|
||||||
|
// Color all direct paths from that citizen to it's neighbor
|
||||||
|
const citizen = e.cy.nodes(`#${config.nodeId}`)[0];
|
||||||
|
citizen.addClass("focused");
|
||||||
|
citizen.connectedEdges().addClass("direct");
|
||||||
|
e.cy.center(citizen);
|
||||||
|
},
|
||||||
|
|
||||||
|
tick: () => {
|
||||||
|
// Center on current user node during simulation
|
||||||
|
const citizen = cy.nodes(`#${config.nodeId}`)[0];
|
||||||
|
cy.center(citizen);
|
||||||
|
},
|
||||||
|
|
||||||
|
stop: (e) => {
|
||||||
|
// Disable user grabbing of nodes
|
||||||
|
// This has to be disabled after the simulation is done
|
||||||
|
// Otherwise the simulation can't move nodes
|
||||||
|
e.cy.autolock(true);
|
||||||
|
},
|
||||||
|
} as D3ForceLayoutOptions,
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,14 +5,14 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block additional_js %}
|
{% block additional_js %}
|
||||||
<script type="module" src="{{ static('bundled/galaxy/galaxy-index.js') }}"></script>
|
<script type="module" src="{{ static('bundled/galaxy/galaxy-index.ts') }}"></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{% if object.current_star %}
|
{% if object.current_star %}
|
||||||
<div style="display: flex; flex-wrap: wrap;">
|
<div style="display: flex; flex-wrap: wrap;">
|
||||||
<div id="3d-graph"></div>
|
<div style="width: 100%; height: 70vh; display: block" id="3d-graph"></div>
|
||||||
|
|
||||||
<div style="margin: 1em;">
|
<div style="margin: 1em;">
|
||||||
<p><a onclick="window.focusNode(window.getNodeFromId({{ object.id }}))">Reset on {{ object.get_display_name() }}</a></p>
|
<p><a onclick="window.focusNode(window.getNodeFromId({{ object.id }}))">Reset on {{ object.get_display_name() }}</a></p>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
msgid ""
|
msgid ""
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Report-Msgid-Bugs-To: \n"
|
"Report-Msgid-Bugs-To: \n"
|
||||||
"POT-Creation-Date: 2025-11-27 14:22+0100\n"
|
"POT-Creation-Date: 2025-11-07 14:50+0100\n"
|
||||||
"PO-Revision-Date: 2016-07-18\n"
|
"PO-Revision-Date: 2016-07-18\n"
|
||||||
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
||||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||||
@@ -247,7 +247,8 @@ msgstr "description"
|
|||||||
msgid "past member"
|
msgid "past member"
|
||||||
msgstr "ancien membre"
|
msgstr "ancien membre"
|
||||||
|
|
||||||
#: club/models.py com/templates/com/mailing_admin.jinja
|
#: club/models.py club/templates/club/club_detail.jinja
|
||||||
|
#: com/templates/com/mailing_admin.jinja
|
||||||
#: com/templates/com/news_admin_list.jinja com/templates/com/weekmail.jinja
|
#: com/templates/com/news_admin_list.jinja com/templates/com/weekmail.jinja
|
||||||
#: core/templates/core/user_clubs.jinja
|
#: core/templates/core/user_clubs.jinja
|
||||||
#: counter/templates/counter/invoices_call.jinja
|
#: counter/templates/counter/invoices_call.jinja
|
||||||
@@ -388,7 +389,7 @@ msgstr "Montrer"
|
|||||||
|
|
||||||
#: club/templates/club/club_sellings.jinja
|
#: club/templates/club/club_sellings.jinja
|
||||||
#: counter/templates/counter/product_list.jinja
|
#: counter/templates/counter/product_list.jinja
|
||||||
msgid "Download as csv"
|
msgid "Download as cvs"
|
||||||
msgstr "Télécharger en CSV"
|
msgstr "Télécharger en CSV"
|
||||||
|
|
||||||
#: club/templates/club/club_sellings.jinja
|
#: club/templates/club/club_sellings.jinja
|
||||||
@@ -470,7 +471,7 @@ msgstr "Méthode de paiement"
|
|||||||
#: core/templates/core/file_detail.jinja
|
#: core/templates/core/file_detail.jinja
|
||||||
#: core/templates/core/file_moderation.jinja
|
#: core/templates/core/file_moderation.jinja
|
||||||
#: core/templates/core/group_detail.jinja core/templates/core/group_list.jinja
|
#: core/templates/core/group_detail.jinja core/templates/core/group_list.jinja
|
||||||
#: core/templates/core/macros.jinja core/templates/core/page/prop.jinja
|
#: core/templates/core/macros.jinja core/templates/core/page_prop.jinja
|
||||||
#: core/templates/core/user_account_detail.jinja
|
#: core/templates/core/user_account_detail.jinja
|
||||||
#: core/templates/core/user_clubs.jinja core/templates/core/user_edit.jinja
|
#: core/templates/core/user_clubs.jinja core/templates/core/user_edit.jinja
|
||||||
#: counter/templates/counter/fragments/create_student_card.jinja
|
#: counter/templates/counter/fragments/create_student_card.jinja
|
||||||
@@ -546,12 +547,11 @@ msgstr ""
|
|||||||
"Les champs de formulaire suivants sont liées à la description basique d'un "
|
"Les champs de formulaire suivants sont liées à la description basique d'un "
|
||||||
"club. Tous les membres du bureau du club peuvent voir et modifier ceux-ci."
|
"club. Tous les membres du bureau du club peuvent voir et modifier ceux-ci."
|
||||||
|
|
||||||
#: club/templates/club/edit_club.jinja club/templates/club/pagerev_edit.jinja
|
#: club/templates/club/edit_club.jinja com/templates/com/news_edit.jinja
|
||||||
#: com/templates/com/news_edit.jinja com/templates/com/poster_edit.jinja
|
#: com/templates/com/poster_edit.jinja com/templates/com/screen_edit.jinja
|
||||||
#: com/templates/com/screen_edit.jinja com/templates/com/weekmail.jinja
|
#: com/templates/com/weekmail.jinja core/templates/core/create.jinja
|
||||||
#: core/templates/core/create.jinja core/templates/core/edit.jinja
|
#: core/templates/core/edit.jinja core/templates/core/file_edit.jinja
|
||||||
#: core/templates/core/file_edit.jinja core/templates/core/page/edit.jinja
|
#: core/templates/core/macros_pages.jinja core/templates/core/page_prop.jinja
|
||||||
#: core/templates/core/page/prop.jinja
|
|
||||||
#: core/templates/core/user_godfathers.jinja
|
#: core/templates/core/user_godfathers.jinja
|
||||||
#: core/templates/core/user_godfathers_tree.jinja
|
#: core/templates/core/user_godfathers_tree.jinja
|
||||||
#: core/templates/core/user_preferences.jinja
|
#: core/templates/core/user_preferences.jinja
|
||||||
@@ -638,9 +638,9 @@ msgstr "Nouvelle liste de diffusion"
|
|||||||
msgid "Create mailing list"
|
msgid "Create mailing list"
|
||||||
msgstr "Créer une liste de diffusion"
|
msgstr "Créer une liste de diffusion"
|
||||||
|
|
||||||
#: club/templates/club/pagerev_edit.jinja core/templates/core/page/edit.jinja
|
#: club/templates/club/page_history.jinja
|
||||||
msgid "Edit page"
|
msgid "No page existing for this club"
|
||||||
msgstr "Éditer la page"
|
msgstr "Aucune page n'existe pour ce club"
|
||||||
|
|
||||||
#: club/views.py core/views/user.py sas/templates/sas/picture.jinja
|
#: club/views.py core/views/user.py sas/templates/sas/picture.jinja
|
||||||
msgid "Infos"
|
msgid "Infos"
|
||||||
@@ -654,7 +654,7 @@ msgstr "Membres"
|
|||||||
msgid "Old members"
|
msgid "Old members"
|
||||||
msgstr "Anciens membres"
|
msgstr "Anciens membres"
|
||||||
|
|
||||||
#: club/views.py core/templates/core/page/base.jinja
|
#: club/views.py core/templates/core/page.jinja
|
||||||
msgid "History"
|
msgid "History"
|
||||||
msgstr "Historique"
|
msgstr "Historique"
|
||||||
|
|
||||||
@@ -666,7 +666,7 @@ msgstr "Outils"
|
|||||||
#: club/views.py com/templates/com/news_admin_list.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/poster_list.jinja com/templates/com/screen_list.jinja
|
||||||
#: com/templates/com/weekmail.jinja core/templates/core/file.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/group_list.jinja core/templates/core/page.jinja
|
||||||
#: core/templates/core/user_tools.jinja core/views/user.py
|
#: core/templates/core/user_tools.jinja core/views/user.py
|
||||||
#: counter/templates/counter/cash_summary_list.jinja
|
#: counter/templates/counter/cash_summary_list.jinja
|
||||||
#: counter/templates/counter/counter_list.jinja
|
#: counter/templates/counter/counter_list.jinja
|
||||||
@@ -704,8 +704,8 @@ msgid "Benefit"
|
|||||||
msgstr "Bénéfice"
|
msgstr "Bénéfice"
|
||||||
|
|
||||||
#: club/views.py
|
#: club/views.py
|
||||||
msgid "Unit price"
|
msgid "Selling price"
|
||||||
msgstr "Prix unitaire"
|
msgstr "Prix de vente"
|
||||||
|
|
||||||
#: club/views.py
|
#: club/views.py
|
||||||
msgid "Purchase price"
|
msgid "Purchase price"
|
||||||
@@ -980,7 +980,7 @@ msgid "Dates"
|
|||||||
msgstr "Dates"
|
msgstr "Dates"
|
||||||
|
|
||||||
#: com/templates/com/news_admin_list.jinja core/templates/core/file.jinja
|
#: com/templates/com/news_admin_list.jinja core/templates/core/file.jinja
|
||||||
#: core/templates/core/page/base.jinja
|
#: core/templates/core/page.jinja
|
||||||
msgid "View"
|
msgid "View"
|
||||||
msgstr "Voir"
|
msgstr "Voir"
|
||||||
|
|
||||||
@@ -1017,10 +1017,6 @@ msgstr "Événements à modérer"
|
|||||||
msgid "Back to news"
|
msgid "Back to news"
|
||||||
msgstr "Retour aux nouvelles"
|
msgstr "Retour aux nouvelles"
|
||||||
|
|
||||||
#: com/templates/com/news_detail.jinja
|
|
||||||
msgid "Share on Facebook"
|
|
||||||
msgstr "Partager sur Facebook"
|
|
||||||
|
|
||||||
#: com/templates/com/news_detail.jinja
|
#: com/templates/com/news_detail.jinja
|
||||||
msgid "Author: "
|
msgid "Author: "
|
||||||
msgstr "Auteur : "
|
msgstr "Auteur : "
|
||||||
@@ -1536,15 +1532,8 @@ msgid "parent address"
|
|||||||
msgstr "adresse des parents"
|
msgstr "adresse des parents"
|
||||||
|
|
||||||
#: core/models.py
|
#: core/models.py
|
||||||
msgid "Profile visible by subscribers"
|
msgid "is subscriber viewable"
|
||||||
msgstr "Profil visible par les cotisants"
|
msgstr "profil visible par les cotisants"
|
||||||
|
|
||||||
#: core/models.py
|
|
||||||
msgid ""
|
|
||||||
"If you disable this option, only admin users will be able to see your "
|
|
||||||
"profile."
|
|
||||||
msgstr ""
|
|
||||||
"Si vous désactivez cette option, seuls les admins pourront voir votre profil."
|
|
||||||
|
|
||||||
#: core/models.py
|
#: core/models.py
|
||||||
msgid "A user with that username already exists"
|
msgid "A user with that username already exists"
|
||||||
@@ -1960,7 +1949,7 @@ msgstr "Liste de fichiers"
|
|||||||
msgid "New file"
|
msgid "New file"
|
||||||
msgstr "Nouveau fichier"
|
msgstr "Nouveau fichier"
|
||||||
|
|
||||||
#: core/templates/core/file.jinja
|
#: core/templates/core/file.jinja core/templates/core/page.jinja
|
||||||
msgid "Not found"
|
msgid "Not found"
|
||||||
msgstr "Non trouvé"
|
msgstr "Non trouvé"
|
||||||
|
|
||||||
@@ -1968,7 +1957,7 @@ msgstr "Non trouvé"
|
|||||||
msgid "My files"
|
msgid "My files"
|
||||||
msgstr "Mes fichiers"
|
msgstr "Mes fichiers"
|
||||||
|
|
||||||
#: core/templates/core/file.jinja core/templates/core/page/base.jinja
|
#: core/templates/core/file.jinja core/templates/core/page.jinja
|
||||||
msgid "Prop"
|
msgid "Prop"
|
||||||
msgstr "Propriétés"
|
msgstr "Propriétés"
|
||||||
|
|
||||||
@@ -2106,6 +2095,14 @@ msgstr "Mot de passe perdu ?"
|
|||||||
msgid "Create account"
|
msgid "Create account"
|
||||||
msgstr "Créer un compte"
|
msgstr "Créer un compte"
|
||||||
|
|
||||||
|
#: core/templates/core/macros.jinja
|
||||||
|
msgid "Share on Facebook"
|
||||||
|
msgstr "Partager sur Facebook"
|
||||||
|
|
||||||
|
#: core/templates/core/macros.jinja
|
||||||
|
msgid "Tweet"
|
||||||
|
msgstr "Tweeter"
|
||||||
|
|
||||||
#: core/templates/core/macros.jinja
|
#: core/templates/core/macros.jinja
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid "Subscribed until %(subscription_end)s"
|
msgid "Subscribed until %(subscription_end)s"
|
||||||
@@ -2127,6 +2124,19 @@ msgstr "Tout sélectionner"
|
|||||||
msgid "Unselect All"
|
msgid "Unselect All"
|
||||||
msgstr "Tout désélectionner"
|
msgstr "Tout désélectionner"
|
||||||
|
|
||||||
|
#: core/templates/core/macros_pages.jinja
|
||||||
|
#, python-format
|
||||||
|
msgid "You're seeing the history of page \"%(page_name)s\""
|
||||||
|
msgstr "Vous consultez l'historique de la page \"%(page_name)s\""
|
||||||
|
|
||||||
|
#: core/templates/core/macros_pages.jinja
|
||||||
|
msgid "last"
|
||||||
|
msgstr "actuel"
|
||||||
|
|
||||||
|
#: core/templates/core/macros_pages.jinja
|
||||||
|
msgid "Edit page"
|
||||||
|
msgstr "Éditer la page"
|
||||||
|
|
||||||
#: core/templates/core/new_user_email.jinja
|
#: core/templates/core/new_user_email.jinja
|
||||||
msgid ""
|
msgid ""
|
||||||
"You're receiving this email because you subscribed to the UTBM student "
|
"You're receiving this email because you subscribed to the UTBM student "
|
||||||
@@ -2177,47 +2187,38 @@ msgstr "Nouvelle cotisation à l'Association des Étudiants de l'UTBM"
|
|||||||
msgid "Notification list"
|
msgid "Notification list"
|
||||||
msgstr "Liste des notifications"
|
msgstr "Liste des notifications"
|
||||||
|
|
||||||
#: core/templates/core/page/base.jinja
|
#: core/templates/core/page.jinja core/templates/core/page_list.jinja
|
||||||
msgid "Page"
|
msgid "Page list"
|
||||||
msgstr "Page"
|
msgstr "Liste des pages"
|
||||||
|
|
||||||
#: core/templates/core/page/base.jinja
|
#: core/templates/core/page.jinja
|
||||||
|
msgid "Create page"
|
||||||
|
msgstr "Créer une page"
|
||||||
|
|
||||||
|
#: core/templates/core/page.jinja
|
||||||
msgid "Return to club management"
|
msgid "Return to club management"
|
||||||
msgstr "Retourner à la gestion du club"
|
msgstr "Retourner à la gestion du club"
|
||||||
|
|
||||||
#: core/templates/core/page/detail.jinja
|
#: core/templates/core/page.jinja
|
||||||
|
msgid "Page does not exist"
|
||||||
|
msgstr "La page n'existe pas"
|
||||||
|
|
||||||
|
#: core/templates/core/page.jinja
|
||||||
|
msgid "Create it?"
|
||||||
|
msgstr "La créer ?"
|
||||||
|
|
||||||
|
#: core/templates/core/page_detail.jinja
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid "This may not be the last update, you are seeing revision %(rev_id)s!"
|
msgid "This may not be the last update, you are seeing revision %(rev_id)s!"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Ceci n'est peut-être pas la dernière version de la page. Vous consultez la "
|
"Ceci n'est peut-être pas la dernière version de la page. Vous consultez la "
|
||||||
"version %(rev_id)s."
|
"version %(rev_id)s."
|
||||||
|
|
||||||
#: core/templates/core/page/history.jinja
|
#: core/templates/core/page_hist.jinja
|
||||||
msgid "Page history"
|
msgid "Page history"
|
||||||
msgstr "Historique de la page"
|
msgstr "Historique de la page"
|
||||||
|
|
||||||
#: core/templates/core/page/list.jinja
|
#: core/templates/core/page_prop.jinja
|
||||||
msgid "Page list"
|
|
||||||
msgstr "Liste des pages"
|
|
||||||
|
|
||||||
#: core/templates/core/page/macros.jinja
|
|
||||||
#, python-format
|
|
||||||
msgid "You're seeing the history of page \"%(page_name)s\""
|
|
||||||
msgstr "Vous consultez l'historique de la page \"%(page_name)s\""
|
|
||||||
|
|
||||||
#: core/templates/core/page/macros.jinja
|
|
||||||
msgid "last"
|
|
||||||
msgstr "actuel"
|
|
||||||
|
|
||||||
#: core/templates/core/page/not_found.jinja
|
|
||||||
msgid "Page does not exist"
|
|
||||||
msgstr "La page n'existe pas"
|
|
||||||
|
|
||||||
#: core/templates/core/page/not_found.jinja
|
|
||||||
msgid "Create it?"
|
|
||||||
msgstr "La créer ?"
|
|
||||||
|
|
||||||
#: core/templates/core/page/prop.jinja
|
|
||||||
msgid "Page properties"
|
msgid "Page properties"
|
||||||
msgstr "Propriétés de la page"
|
msgstr "Propriétés de la page"
|
||||||
|
|
||||||
@@ -2658,8 +2659,8 @@ msgid "Buyings"
|
|||||||
msgstr "Achats"
|
msgstr "Achats"
|
||||||
|
|
||||||
#: core/templates/core/user_stats.jinja
|
#: core/templates/core/user_stats.jinja
|
||||||
msgid "Product top 15"
|
msgid "Product top 10"
|
||||||
msgstr "Top 15 produits"
|
msgstr "Top 10 produits"
|
||||||
|
|
||||||
#: core/templates/core/user_stats.jinja
|
#: core/templates/core/user_stats.jinja
|
||||||
msgid "Product"
|
msgid "Product"
|
||||||
@@ -2819,8 +2820,8 @@ msgstr "Outils Trombi"
|
|||||||
#, python-format
|
#, python-format
|
||||||
msgid "%(nb_days)d day, %(remainder)s"
|
msgid "%(nb_days)d day, %(remainder)s"
|
||||||
msgid_plural "%(nb_days)d days, %(remainder)s"
|
msgid_plural "%(nb_days)d days, %(remainder)s"
|
||||||
msgstr[0] "%(nb_days)d jour, %(remainder)s"
|
msgstr[0] ""
|
||||||
msgstr[1] "%(nb_days)d jours, %(remainder)s"
|
msgstr[1] ""
|
||||||
|
|
||||||
#: core/views/files.py
|
#: core/views/files.py
|
||||||
msgid "Add a new folder"
|
msgid "Add a new folder"
|
||||||
@@ -2840,6 +2841,10 @@ msgstr "Erreur d'envoi du fichier %(file_name)s : %(msg)s"
|
|||||||
msgid "Apply rights recursively"
|
msgid "Apply rights recursively"
|
||||||
msgstr "Appliquer les droits récursivement"
|
msgstr "Appliquer les droits récursivement"
|
||||||
|
|
||||||
|
#: core/views/forms.py
|
||||||
|
msgid "Choose user"
|
||||||
|
msgstr "Choisir un utilisateur"
|
||||||
|
|
||||||
#: core/views/forms.py
|
#: core/views/forms.py
|
||||||
msgid "Ensure this timestamp is set in the future"
|
msgid "Ensure this timestamp is set in the future"
|
||||||
msgstr "Assurez-vous que cet horodatage est dans le futur"
|
msgstr "Assurez-vous que cet horodatage est dans le futur"
|
||||||
@@ -2928,6 +2933,18 @@ msgstr "Photos"
|
|||||||
msgid "Account"
|
msgid "Account"
|
||||||
msgstr "Compte"
|
msgstr "Compte"
|
||||||
|
|
||||||
|
#: counter/apps.py sith/settings.py
|
||||||
|
msgid "Check"
|
||||||
|
msgstr "Chèque"
|
||||||
|
|
||||||
|
#: counter/apps.py sith/settings.py
|
||||||
|
msgid "Cash"
|
||||||
|
msgstr "Espèces"
|
||||||
|
|
||||||
|
#: counter/apps.py counter/models.py sith/settings.py
|
||||||
|
msgid "Credit card"
|
||||||
|
msgstr "Carte bancaire"
|
||||||
|
|
||||||
#: counter/apps.py counter/models.py
|
#: counter/apps.py counter/models.py
|
||||||
msgid "counter"
|
msgid "counter"
|
||||||
msgstr "comptoir"
|
msgstr "comptoir"
|
||||||
@@ -2960,38 +2977,6 @@ msgstr ""
|
|||||||
"Décrivez le produit. Si c'est un click pour un évènement, donnez quelques "
|
"Décrivez le produit. Si c'est un click pour un évènement, donnez quelques "
|
||||||
"détails dessus, comme la date (en incluant l'année)."
|
"détails dessus, comme la date (en incluant l'année)."
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
#, python-format
|
|
||||||
msgid ""
|
|
||||||
"This product is a formula. Its price cannot be greater than the price of the "
|
|
||||||
"products constituting it, which is %(price)s €"
|
|
||||||
msgstr ""
|
|
||||||
"Ce produit est une formule. Son prix ne peut pas être supérieur au prix des "
|
|
||||||
"produits qui la constituent, soit %(price)s €."
|
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
#, python-format
|
|
||||||
msgid ""
|
|
||||||
"This product is a formula. Its special price cannot be greater than the "
|
|
||||||
"price of the products constituting it, which is %(price)s €"
|
|
||||||
msgstr ""
|
|
||||||
"Ce produit est une formule. Son prix spécial ne peut pas être supérieur au "
|
|
||||||
"prix des produits qui la constituent, soit %(price)s €."
|
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
msgid ""
|
|
||||||
"The same product cannot be at the same time the result and a part of the "
|
|
||||||
"formula."
|
|
||||||
msgstr ""
|
|
||||||
"Un même produit ne peut pas être à la fois le résultat et un élément de la "
|
|
||||||
"formule."
|
|
||||||
|
|
||||||
#: counter/forms.py
|
|
||||||
msgid ""
|
|
||||||
"The result cannot be more expensive than the total of the other products."
|
|
||||||
msgstr ""
|
|
||||||
"Le résultat ne peut pas être plus cher que le total des autres produits."
|
|
||||||
|
|
||||||
#: counter/forms.py
|
#: counter/forms.py
|
||||||
msgid "Refound this account"
|
msgid "Refound this account"
|
||||||
msgstr "Rembourser ce compte"
|
msgstr "Rembourser ce compte"
|
||||||
@@ -3152,18 +3137,6 @@ msgstr "produit"
|
|||||||
msgid "products"
|
msgid "products"
|
||||||
msgstr "produits"
|
msgstr "produits"
|
||||||
|
|
||||||
#: counter/models.py
|
|
||||||
msgid "The products that constitute this formula."
|
|
||||||
msgstr "Les produits qui constituent cette formule."
|
|
||||||
|
|
||||||
#: counter/models.py
|
|
||||||
msgid "result product"
|
|
||||||
msgstr "produit résultat"
|
|
||||||
|
|
||||||
#: counter/models.py
|
|
||||||
msgid "The product got with the formula."
|
|
||||||
msgstr "Le produit obtenu par la formule."
|
|
||||||
|
|
||||||
#: counter/models.py
|
#: counter/models.py
|
||||||
msgid "counter type"
|
msgid "counter type"
|
||||||
msgstr "type de comptoir"
|
msgstr "type de comptoir"
|
||||||
@@ -3184,29 +3157,21 @@ msgstr "vendeurs"
|
|||||||
msgid "token"
|
msgid "token"
|
||||||
msgstr "jeton"
|
msgstr "jeton"
|
||||||
|
|
||||||
#: counter/models.py sith/settings.py
|
|
||||||
msgid "Credit card"
|
|
||||||
msgstr "Carte bancaire"
|
|
||||||
|
|
||||||
#: counter/models.py sith/settings.py
|
|
||||||
msgid "Cash"
|
|
||||||
msgstr "Espèces"
|
|
||||||
|
|
||||||
#: counter/models.py sith/settings.py
|
|
||||||
msgid "Check"
|
|
||||||
msgstr "Chèque"
|
|
||||||
|
|
||||||
#: counter/models.py subscription/models.py
|
#: counter/models.py subscription/models.py
|
||||||
msgid "payment method"
|
msgid "payment method"
|
||||||
msgstr "méthode de paiement"
|
msgstr "méthode de paiement"
|
||||||
|
|
||||||
#: counter/models.py
|
#: counter/models.py
|
||||||
msgid "refilling"
|
msgid "bank"
|
||||||
msgstr "rechargement"
|
msgstr "banque"
|
||||||
|
|
||||||
#: counter/models.py
|
#: counter/models.py
|
||||||
msgid "Sith account"
|
msgid "is validated"
|
||||||
msgstr "Compte utilisateur"
|
msgstr "est validé"
|
||||||
|
|
||||||
|
#: counter/models.py
|
||||||
|
msgid "refilling"
|
||||||
|
msgstr "rechargement"
|
||||||
|
|
||||||
#: counter/models.py eboutic/models.py
|
#: counter/models.py eboutic/models.py
|
||||||
msgid "unit price"
|
msgid "unit price"
|
||||||
@@ -3216,6 +3181,10 @@ msgstr "prix unitaire"
|
|||||||
msgid "quantity"
|
msgid "quantity"
|
||||||
msgstr "quantité"
|
msgstr "quantité"
|
||||||
|
|
||||||
|
#: counter/models.py
|
||||||
|
msgid "Sith account"
|
||||||
|
msgstr "Compte utilisateur"
|
||||||
|
|
||||||
#: counter/models.py
|
#: counter/models.py
|
||||||
msgid "selling"
|
msgid "selling"
|
||||||
msgstr "vente"
|
msgstr "vente"
|
||||||
@@ -3368,10 +3337,6 @@ msgid ""
|
|||||||
"“%(value)s” value has the correct format (YYYY-MM) but it is an invalid date."
|
"“%(value)s” value has the correct format (YYYY-MM) but it is an invalid date."
|
||||||
msgstr "La valeur « %(value)s » a le bon format, mais est une date invalide."
|
msgstr "La valeur « %(value)s » a le bon format, mais est une date invalide."
|
||||||
|
|
||||||
#: counter/models.py
|
|
||||||
msgid "is validated"
|
|
||||||
msgstr "est validé"
|
|
||||||
|
|
||||||
#: counter/models.py
|
#: counter/models.py
|
||||||
msgid "invoice date"
|
msgid "invoice date"
|
||||||
msgstr "date de la facture"
|
msgstr "date de la facture"
|
||||||
@@ -3584,14 +3549,6 @@ msgstr "Nouveau eticket"
|
|||||||
msgid "There is no eticket in this website."
|
msgid "There is no eticket in this website."
|
||||||
msgstr "Il n'y a pas de eticket sur ce site web."
|
msgstr "Il n'y a pas de eticket sur ce site web."
|
||||||
|
|
||||||
#: counter/templates/counter/formula_list.jinja
|
|
||||||
msgid "Product formulas"
|
|
||||||
msgstr "Formules de produits"
|
|
||||||
|
|
||||||
#: counter/templates/counter/formula_list.jinja
|
|
||||||
msgid "New formula"
|
|
||||||
msgstr "Nouvelle formule"
|
|
||||||
|
|
||||||
#: counter/templates/counter/fragments/create_student_card.jinja
|
#: counter/templates/counter/fragments/create_student_card.jinja
|
||||||
msgid "No student card registered."
|
msgid "No student card registered."
|
||||||
msgstr "Aucune carte étudiante enregistrée."
|
msgstr "Aucune carte étudiante enregistrée."
|
||||||
@@ -3931,10 +3888,6 @@ msgstr "Dernières opérations"
|
|||||||
msgid "Counter administration"
|
msgid "Counter administration"
|
||||||
msgstr "Administration des comptoirs"
|
msgstr "Administration des comptoirs"
|
||||||
|
|
||||||
#: counter/views/mixins.py
|
|
||||||
msgid "Formulas"
|
|
||||||
msgstr "Formules"
|
|
||||||
|
|
||||||
#: counter/views/mixins.py
|
#: counter/views/mixins.py
|
||||||
msgid "Product types"
|
msgid "Product types"
|
||||||
msgstr "Types de produit"
|
msgstr "Types de produit"
|
||||||
@@ -5159,6 +5112,14 @@ msgstr "Membre de Sbarro ou de l'ESTA"
|
|||||||
msgid "One semester Welcome Week"
|
msgid "One semester Welcome Week"
|
||||||
msgstr "Un semestre Welcome Week"
|
msgstr "Un semestre Welcome Week"
|
||||||
|
|
||||||
|
#: sith/settings.py
|
||||||
|
msgid "One month for free"
|
||||||
|
msgstr "Un mois gratuit"
|
||||||
|
|
||||||
|
#: sith/settings.py
|
||||||
|
msgid "Two months for free"
|
||||||
|
msgstr "Deux mois gratuits"
|
||||||
|
|
||||||
#: sith/settings.py
|
#: sith/settings.py
|
||||||
msgid "Eurok's volunteer"
|
msgid "Eurok's volunteer"
|
||||||
msgstr "Bénévole Eurockéennes"
|
msgstr "Bénévole Eurockéennes"
|
||||||
@@ -5172,10 +5133,8 @@ msgid "One day"
|
|||||||
msgstr "Un jour"
|
msgstr "Un jour"
|
||||||
|
|
||||||
#: sith/settings.py
|
#: sith/settings.py
|
||||||
#, fuzzy
|
msgid "GA staff member (2 weeks)"
|
||||||
#| msgid "GA staff member"
|
msgstr "Membre staff GA (2 semaines)"
|
||||||
msgid "GA staff member"
|
|
||||||
msgstr "Membre staff GA"
|
|
||||||
|
|
||||||
#: sith/settings.py
|
#: sith/settings.py
|
||||||
msgid "One semester (-20%)"
|
msgid "One semester (-20%)"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
msgid ""
|
msgid ""
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Report-Msgid-Bugs-To: \n"
|
"Report-Msgid-Bugs-To: \n"
|
||||||
"POT-Creation-Date: 2025-11-26 15:45+0100\n"
|
"POT-Creation-Date: 2025-08-23 15:30+0200\n"
|
||||||
"PO-Revision-Date: 2024-09-17 11:54+0200\n"
|
"PO-Revision-Date: 2024-09-17 11:54+0200\n"
|
||||||
"Last-Translator: Sli <antoine@bartuccio.fr>\n"
|
"Last-Translator: Sli <antoine@bartuccio.fr>\n"
|
||||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||||
@@ -206,10 +206,6 @@ msgstr "capture.%s"
|
|||||||
msgid "Not enough money"
|
msgid "Not enough money"
|
||||||
msgstr "Pas assez d'argent"
|
msgstr "Pas assez d'argent"
|
||||||
|
|
||||||
#: counter/static/bundled/counter/counter-click-index.ts
|
|
||||||
msgid "Formula %(formula)s applied"
|
|
||||||
msgstr "Formule %(formula)s appliquée"
|
|
||||||
|
|
||||||
#: counter/static/bundled/counter/counter-click-index.ts
|
#: counter/static/bundled/counter/counter-click-index.ts
|
||||||
msgid "You can't send an empty basket."
|
msgid "You can't send an empty basket."
|
||||||
msgstr "Vous ne pouvez pas envoyer un panier vide."
|
msgstr "Vous ne pouvez pas envoyer un panier vide."
|
||||||
@@ -266,9 +262,3 @@ msgstr "Il n'a pas été possible de modérer l'image"
|
|||||||
#: sas/static/bundled/sas/viewer-index.ts
|
#: sas/static/bundled/sas/viewer-index.ts
|
||||||
msgid "Couldn't delete picture"
|
msgid "Couldn't delete picture"
|
||||||
msgstr "Il n'a pas été possible de supprimer l'image"
|
msgstr "Il n'a pas été possible de supprimer l'image"
|
||||||
|
|
||||||
#: timetable/static/bundled/timetable/generator-index.ts
|
|
||||||
msgid ""
|
|
||||||
"Wrong timetable format. Make sure you copied if from your student folder."
|
|
||||||
msgstr ""
|
|
||||||
"Mauvais format d'emploi du temps. Assurez-vous que vous l'avez copié depuis votre dossier étudiants."
|
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ from ast import literal_eval
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.db.models import F
|
|
||||||
from django.http.response import HttpResponseRedirect
|
from django.http.response import HttpResponseRedirect
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
@@ -35,7 +34,7 @@ from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
|||||||
|
|
||||||
from core.auth.mixins import FormerSubscriberMixin
|
from core.auth.mixins import FormerSubscriberMixin
|
||||||
from core.models import User
|
from core.models import User
|
||||||
from core.schemas import UserFilterSchema
|
from core.views import search_user
|
||||||
from core.views.forms import SelectDate
|
from core.views.forms import SelectDate
|
||||||
|
|
||||||
# Enum to select search type
|
# Enum to select search type
|
||||||
@@ -106,7 +105,7 @@ class SearchFormListView(FormerSubscriberMixin, SingleObjectMixin, ListView):
|
|||||||
self.can_see_hidden = True
|
self.can_see_hidden = True
|
||||||
if not (request.user.is_board_member or request.user.is_root):
|
if not (request.user.is_board_member or request.user.is_root):
|
||||||
self.can_see_hidden = False
|
self.can_see_hidden = False
|
||||||
self.init_query = self.init_query.filter(is_viewable=True)
|
self.init_query = self.init_query.exclude(is_subscriber_viewable=False)
|
||||||
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@@ -127,13 +126,11 @@ class SearchFormListView(FormerSubscriberMixin, SingleObjectMixin, ListView):
|
|||||||
q = q.filter(phone=self.valid_form["phone"]).all()
|
q = q.filter(phone=self.valid_form["phone"]).all()
|
||||||
elif self.search_type == SearchType.QUICK:
|
elif self.search_type == SearchType.QUICK:
|
||||||
if self.valid_form["quick"].strip():
|
if self.valid_form["quick"].strip():
|
||||||
q = list(
|
q = search_user(self.valid_form["quick"])
|
||||||
UserFilterSchema(search=self.valid_form["quick"])
|
|
||||||
.filter(User.objects.viewable_by(self.request.user))
|
|
||||||
.order_by(F("last_login").desc(nulls_last=True))
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
q = []
|
q = []
|
||||||
|
if not self.can_see_hidden and len(q) > 0:
|
||||||
|
q = [user for user in q if user.is_subscriber_viewable]
|
||||||
else:
|
else:
|
||||||
search_dict = {}
|
search_dict = {}
|
||||||
for key, value in self.valid_form.items():
|
for key, value in self.valid_form.items():
|
||||||
|
|||||||
53
package-lock.json
generated
53
package-lock.json
generated
@@ -25,6 +25,7 @@
|
|||||||
"country-flag-emoji-polyfill": "^0.1.8",
|
"country-flag-emoji-polyfill": "^0.1.8",
|
||||||
"cytoscape": "^3.33.1",
|
"cytoscape": "^3.33.1",
|
||||||
"cytoscape-cxtmenu": "^3.5.0",
|
"cytoscape-cxtmenu": "^3.5.0",
|
||||||
|
"cytoscape-d3-force": "^1.1.4",
|
||||||
"cytoscape-klay": "^3.1.4",
|
"cytoscape-klay": "^3.1.4",
|
||||||
"d3-force-3d": "^3.0.6",
|
"d3-force-3d": "^3.0.6",
|
||||||
"easymde": "^2.20.0",
|
"easymde": "^2.20.0",
|
||||||
@@ -46,6 +47,7 @@
|
|||||||
"@rollup/plugin-inject": "^5.0.5",
|
"@rollup/plugin-inject": "^5.0.5",
|
||||||
"@types/alpinejs": "^3.13.11",
|
"@types/alpinejs": "^3.13.11",
|
||||||
"@types/cytoscape-cxtmenu": "^3.4.5",
|
"@types/cytoscape-cxtmenu": "^3.4.5",
|
||||||
|
"@types/cytoscape-d3-force": "^1.0.0",
|
||||||
"@types/cytoscape-klay": "^3.1.5",
|
"@types/cytoscape-klay": "^3.1.5",
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
@@ -2890,6 +2892,16 @@
|
|||||||
"cytoscape": "^3.31"
|
"cytoscape": "^3.31"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/cytoscape-d3-force": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/cytoscape-d3-force/-/cytoscape-d3-force-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-1eRd9xr/DvJ4MIA5lCEG8DMX2Ha87qAbpP7irpuKZun0ZCBQPpoOBo9mPl0WrkJbXH+hHwG8s3E2CpUz3HxLrw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/cytoscape": "^3.0.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/cytoscape-klay": {
|
"node_modules/@types/cytoscape-klay": {
|
||||||
"version": "3.1.5",
|
"version": "3.1.5",
|
||||||
"resolved": "https://registry.npmjs.org/@types/cytoscape-klay/-/cytoscape-klay-3.1.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/cytoscape-klay/-/cytoscape-klay-3.1.5.tgz",
|
||||||
@@ -3559,6 +3571,18 @@
|
|||||||
"cytoscape": "^3.2.0"
|
"cytoscape": "^3.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cytoscape-d3-force": {
|
||||||
|
"version": "1.1.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/cytoscape-d3-force/-/cytoscape-d3-force-1.1.4.tgz",
|
||||||
|
"integrity": "sha512-8NjI/yEoB3YqVsdf7ud7Oh8Kyi+C9Lhh1fICmtemIo6EC1ZUtm8KcPNLkQySYO8nRS2mQKj5eVdCr7W0L8ONoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-force": "^2.0.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"cytoscape": "^3.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cytoscape-klay": {
|
"node_modules/cytoscape-klay": {
|
||||||
"version": "3.1.4",
|
"version": "3.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/cytoscape-klay/-/cytoscape-klay-3.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/cytoscape-klay/-/cytoscape-klay-3.1.4.tgz",
|
||||||
@@ -3607,6 +3631,17 @@
|
|||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/d3-force": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-force/-/d3-force-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-nAuHEzBqMvpFVMf9OX75d00OxvOXdxY+xECIXjW6Gv8BRrXu6gAWbv/9XKrvfJ5i5DCokDW7RYE50LRoK092ew==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-dispatch": "1 - 2",
|
||||||
|
"d3-quadtree": "1 - 2",
|
||||||
|
"d3-timer": "1 - 2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/d3-force-3d": {
|
"node_modules/d3-force-3d": {
|
||||||
"version": "3.0.6",
|
"version": "3.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/d3-force-3d/-/d3-force-3d-3.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/d3-force-3d/-/d3-force-3d-3.0.6.tgz",
|
||||||
@@ -3623,6 +3658,24 @@
|
|||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/d3-force/node_modules/d3-dispatch": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-S/m2VsXI7gAti2pBoLClFFTMOO1HTtT0j99AuXLoGFKO6deHDdnv6ZGTxSTTUTgO1zVcv82fCOtDjYK4EECmWA==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/d3-force/node_modules/d3-quadtree": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-b0Ed2t1UUalJpc3qXzKi+cPGxeXRr4KU9YSlocN74aTzp6R/Ud43t79yLLqxHRWZfsvWXmbDWPpoENK1K539xw==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/d3-force/node_modules/d3-timer": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-TO4VLh0/420Y/9dO3+f9abDEFYeCUr2WZRlxJvbp4HPTQcSylXNiL6yZa9FIUvV1yRiFufl1bszTCLDqv9PWNA==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
"node_modules/d3-format": {
|
"node_modules/d3-format": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
|
||||||
|
|||||||
@@ -31,6 +31,7 @@
|
|||||||
"@rollup/plugin-inject": "^5.0.5",
|
"@rollup/plugin-inject": "^5.0.5",
|
||||||
"@types/alpinejs": "^3.13.11",
|
"@types/alpinejs": "^3.13.11",
|
||||||
"@types/cytoscape-cxtmenu": "^3.4.5",
|
"@types/cytoscape-cxtmenu": "^3.4.5",
|
||||||
|
"@types/cytoscape-d3-force": "^1.0.0",
|
||||||
"@types/cytoscape-klay": "^3.1.5",
|
"@types/cytoscape-klay": "^3.1.5",
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
@@ -55,6 +56,7 @@
|
|||||||
"country-flag-emoji-polyfill": "^0.1.8",
|
"country-flag-emoji-polyfill": "^0.1.8",
|
||||||
"cytoscape": "^3.33.1",
|
"cytoscape": "^3.33.1",
|
||||||
"cytoscape-cxtmenu": "^3.5.0",
|
"cytoscape-cxtmenu": "^3.5.0",
|
||||||
|
"cytoscape-d3-force": "^1.1.4",
|
||||||
"cytoscape-klay": "^3.1.4",
|
"cytoscape-klay": "^3.1.4",
|
||||||
"d3-force-3d": "^3.0.6",
|
"d3-force-3d": "^3.0.6",
|
||||||
"easymde": "^2.20.0",
|
"easymde": "^2.20.0",
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
from typing import Annotated, Literal
|
from typing import Literal
|
||||||
|
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from django.utils import html
|
from django.utils import html
|
||||||
from haystack.query import SearchQuerySet
|
from haystack.query import SearchQuerySet
|
||||||
from ninja import FilterLookup, FilterSchema, ModelSchema, Schema
|
from ninja import FilterSchema, ModelSchema, Schema
|
||||||
from pydantic import AliasPath, ConfigDict, Field, TypeAdapter
|
from pydantic import AliasPath, ConfigDict, Field, TypeAdapter
|
||||||
from pydantic.alias_generators import to_camel
|
from pydantic.alias_generators import to_camel
|
||||||
|
|
||||||
@@ -114,14 +114,13 @@ class UvSchema(ModelSchema):
|
|||||||
|
|
||||||
|
|
||||||
class UvFilterSchema(FilterSchema):
|
class UvFilterSchema(FilterSchema):
|
||||||
search: Annotated[str | None, FilterLookup("code__icontains")] = None
|
search: str | None = Field(None, q="code__icontains")
|
||||||
semester: set[Literal["AUTUMN", "SPRING"]] | None = None
|
semester: set[Literal["AUTUMN", "SPRING"]] | None = None
|
||||||
credit_type: Annotated[
|
credit_type: set[Literal["CS", "TM", "EC", "OM", "QC"]] | None = Field(
|
||||||
set[Literal["CS", "TM", "EC", "OM", "QC"]] | None,
|
None, q="credit_type__in"
|
||||||
FilterLookup("credit_type__in"),
|
)
|
||||||
] = None
|
|
||||||
language: str = "FR"
|
language: str = "FR"
|
||||||
department: Annotated[set[str] | None, FilterLookup("department__in")] = None
|
department: set[str] | None = Field(None, q="department__in")
|
||||||
|
|
||||||
def filter_search(self, value: str | None) -> Q:
|
def filter_search(self, value: str | None) -> Q:
|
||||||
"""Special filter for the search text.
|
"""Special filter for the search text.
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ license = { text = "GPL-3.0-only" }
|
|||||||
requires-python = "<4.0,>=3.12"
|
requires-python = "<4.0,>=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"django>=5.2.8,<6.0.0",
|
"django>=5.2.8,<6.0.0",
|
||||||
"django-ninja>=1.5.0,<6.0.0",
|
"django-ninja>=1.4.5,<2.0.0",
|
||||||
"django-ninja-extra>=0.30.6",
|
"django-ninja-extra>=0.30.2,<1.0.0",
|
||||||
"Pillow>=12.0.0,<13.0.0",
|
"Pillow>=12.0.0,<13.0.0",
|
||||||
"mistune>=3.1.4,<4.0.0",
|
"mistune>=3.1.4,<4.0.0",
|
||||||
"django-jinja<3.0.0,>=2.11.0",
|
"django-jinja<3.0.0,>=2.11.0",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user