mirror of
https://github.com/ae-utbm/sith.git
synced 2025-12-11 07:35:59 +00:00
Compare commits
1 Commits
product-fo
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b927b9c0f2 |
@@ -8,7 +8,7 @@ from django.utils.crypto import constant_time_compare
|
||||
|
||||
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.
|
||||
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,
|
||||
)
|
||||
from counter.models import Counter, Selling
|
||||
from counter.schemas import SaleFilterSchema
|
||||
|
||||
|
||||
class ClubEditForm(forms.ModelForm):
|
||||
@@ -192,18 +191,6 @@ class SellingsForm(forms.Form):
|
||||
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):
|
||||
members_old = forms.ModelMultipleChoiceField(
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
from typing import Annotated
|
||||
|
||||
from annotated_types import MinLen
|
||||
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 core.schemas import NonEmptyStr, SimpleUserSchema
|
||||
from core.schemas import SimpleUserSchema
|
||||
|
||||
|
||||
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
|
||||
parent_id: int | None = None
|
||||
parent_name: str | None = Field(None, q="parent__name__icontains")
|
||||
exclude_ids: set[int] | None = 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 %}
|
||||
{{ form }}
|
||||
<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>
|
||||
<p>
|
||||
{% trans %}Quantity: {% endtrans %}{{ total_quantity }} {% trans %}units{% endtrans %}<br/>
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
{% extends "core/base.jinja" %}
|
||||
{% from 'core/page/macros.jinja' import page_history %}
|
||||
{% from 'core/macros_pages.jinja' import page_history %}
|
||||
|
||||
{% block content %}
|
||||
{{ page_history(club.page) }}
|
||||
{% if club.page %}
|
||||
{{ page_history(club.page) }}
|
||||
{% else %}
|
||||
{% trans %}No page existing for this club{% endtrans %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
{% extends "core/base.jinja" %}
|
||||
{% from 'core/macros_pages.jinja' import page_edit_form %}
|
||||
|
||||
{% block content %}
|
||||
<h2>{% trans %}Edit page{% endtrans %}</h2>
|
||||
<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>
|
||||
{{ page_edit_form(page, form, url('club:club_edit_page', club_id=page.club.id), csrf_token) }}
|
||||
{% endblock %}
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from django.conf import settings
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.core.cache import cache
|
||||
from django.db.models import Max
|
||||
from django.test import Client, TestCase
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from django.utils.timezone import localdate, localtime, now
|
||||
from model_bakery import baker
|
||||
@@ -532,35 +532,6 @@ class TestMembership(TestClub):
|
||||
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
|
||||
class TestJoinClub:
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@@ -3,10 +3,9 @@ from bs4 import BeautifulSoup
|
||||
from django.test import Client
|
||||
from django.urls import reverse
|
||||
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 core.baker_recipes import subscriber_user
|
||||
from club.models import Club
|
||||
from core.markdown import markdown
|
||||
from core.models import PageRev, User
|
||||
|
||||
@@ -17,6 +16,7 @@ def test_page_display_on_club_main_page(client: Client):
|
||||
club = baker.make(Club)
|
||||
content = "# foo\nLorem ipsum dolor sit amet"
|
||||
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}))
|
||||
|
||||
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"""
|
||||
club = baker.make(Club)
|
||||
club.page.revisions.all().delete()
|
||||
client.force_login(baker.make(User))
|
||||
res = client.get(reverse("club:club_view", kwargs={"club_id": club.id}))
|
||||
|
||||
assert res.status_code == 200
|
||||
soup = BeautifulSoup(res.text, "lxml")
|
||||
detail_html = soup.find(id="club_detail")
|
||||
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
|
||||
from django.test import Client
|
||||
from django.urls import reverse
|
||||
@@ -10,20 +7,16 @@ from club.forms import SellingsForm
|
||||
from club.models import Club
|
||||
from core.models import User
|
||||
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
|
||||
def test_sales_page_doesnt_crash(client: Client):
|
||||
"""Basic crashtest on club sales view."""
|
||||
club = baker.make(Club)
|
||||
product = baker.make(Product, club=club)
|
||||
admin = baker.make(User, is_superuser=True)
|
||||
client.force_login(admin)
|
||||
url = reverse("club:club_sellings", kwargs={"club_id": club.id})
|
||||
assert client.get(url).status_code == 200
|
||||
assert client.post(url).status_code == 200
|
||||
assert client.post(url, data={"products": [product.id]}).status_code == 200
|
||||
response = client.get(reverse("club:club_sellings", kwargs={"club_id": club.id}))
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -43,62 +36,3 @@ def test_sales_form_counter_filter():
|
||||
form = SellingsForm(club)
|
||||
form_counters = list(form.fields["counters"].queryset)
|
||||
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 itertools
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import Any
|
||||
|
||||
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.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
|
||||
from django.core.paginator import InvalidPage, Paginator
|
||||
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.urls import reverse, reverse_lazy
|
||||
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.translation import gettext
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
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 club.forms import (
|
||||
@@ -64,14 +61,11 @@ from com.views import (
|
||||
PosterListBaseView,
|
||||
)
|
||||
from core.auth.mixins import CanEditMixin, PermissionOrClubBoardRequiredMixin
|
||||
from core.models import Page, PageRev
|
||||
from core.views import BasePageEditView, DetailFormView, UseFragmentsMixin
|
||||
from core.models import PageRev
|
||||
from core.views import DetailFormView, PageEditViewBase, UseFragmentsMixin
|
||||
from core.views.mixins import FragmentMixin, FragmentRenderer, TabedViewMixin
|
||||
from counter.models import Selling
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.utils.safestring import SafeString
|
||||
|
||||
|
||||
class ClubTabsMixin(TabedViewMixin):
|
||||
def get_tabs_title(self):
|
||||
@@ -81,8 +75,6 @@ class ClubTabsMixin(TabedViewMixin):
|
||||
self.object = self.object.page.club
|
||||
elif isinstance(self.object, Poster):
|
||||
self.object = self.object.club
|
||||
elif hasattr(self, "club"):
|
||||
self.object = self.club
|
||||
return self.object.get_display_name()
|
||||
|
||||
def get_list_of_tabs(self):
|
||||
@@ -210,7 +202,7 @@ class ClubView(ClubTabsMixin, DetailView):
|
||||
return kwargs
|
||||
|
||||
|
||||
class ClubRevView(LoginRequiredMixin, ClubView):
|
||||
class ClubRevView(ClubView):
|
||||
"""Display a specific page revision."""
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
@@ -224,26 +216,26 @@ class ClubRevView(LoginRequiredMixin, ClubView):
|
||||
return kwargs
|
||||
|
||||
|
||||
class ClubPageEditView(ClubTabsMixin, BasePageEditView):
|
||||
class ClubPageEditView(ClubTabsMixin, PageEditViewBase):
|
||||
template_name = "club/pagerev_edit.jinja"
|
||||
current_tab = "page_edit"
|
||||
|
||||
@cached_property
|
||||
def club(self):
|
||||
return get_object_or_404(Club, pk=self.kwargs["club_id"])
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
||||
if not self.club.page:
|
||||
raise Http404
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
@cached_property
|
||||
def page(self) -> Page:
|
||||
page = self.club.page
|
||||
page.set_lock(self.request.user)
|
||||
return page
|
||||
def get_object(self):
|
||||
self.page = self.club.page
|
||||
return self._get_revision()
|
||||
|
||||
def get_success_url(self, **kwargs):
|
||||
return reverse_lazy("club:club_view", kwargs={"club_id": self.club.id})
|
||||
|
||||
|
||||
class ClubPageHistView(ClubTabsMixin, PermissionRequiredMixin, DetailView):
|
||||
"""Modification history of the page."""
|
||||
"""Modification hostory of the page."""
|
||||
|
||||
model = Club
|
||||
pk_url_kwarg = "club_id"
|
||||
@@ -407,14 +399,33 @@ class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView):
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
|
||||
kwargs["result"] = Selling.objects.none()
|
||||
kwargs["paginated_result"] = kwargs["result"]
|
||||
kwargs["total"] = 0
|
||||
kwargs["total_quantity"] = 0
|
||||
kwargs["benefit"] = 0
|
||||
|
||||
form: SellingsForm = self.get_form()
|
||||
if form.is_valid() and any(v for v in form.cleaned_data.values()):
|
||||
filters = form.to_filter_schema()
|
||||
qs = filters.filter(Selling.objects.filter(club=self.object))
|
||||
form = self.get_form()
|
||||
if form.is_valid():
|
||||
qs = 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(
|
||||
price=F("quantity") * F("unit_price")
|
||||
).aggregate(total=Sum("price", default=0))["total"]
|
||||
@@ -461,15 +472,15 @@ class ClubSellingCSVView(ClubSellingView):
|
||||
*row,
|
||||
selling.label,
|
||||
selling.quantity,
|
||||
selling.unit_price,
|
||||
selling.quantity * selling.unit_price,
|
||||
selling.get_payment_method_display(),
|
||||
]
|
||||
if selling.product:
|
||||
row.append(selling.product.selling_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:
|
||||
row = [*row, "", ""]
|
||||
row = [*row, "", "", ""]
|
||||
return row
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
@@ -490,9 +501,9 @@ class ClubSellingCSVView(ClubSellingView):
|
||||
gettext("Customer"),
|
||||
gettext("Label"),
|
||||
gettext("Quantity"),
|
||||
gettext("Unit price"),
|
||||
gettext("Total"),
|
||||
gettext("Payment method"),
|
||||
gettext("Selling price"),
|
||||
gettext("Purchase price"),
|
||||
gettext("Benefit"),
|
||||
],
|
||||
@@ -545,17 +556,33 @@ class ClubCreateView(PermissionRequiredMixin, CreateView):
|
||||
permission_required = "club.add_club"
|
||||
|
||||
|
||||
class MembershipSetOldView(CanEditMixin, SingleObjectMixin, View):
|
||||
"""Set a membership as being old."""
|
||||
class MembershipSetOldView(CanEditMixin, DetailView):
|
||||
"""Set a membership as beeing old."""
|
||||
|
||||
model = Membership
|
||||
pk_url_kwarg = "membership_id"
|
||||
|
||||
def post(self, *_args, **_kwargs):
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
self.object.end_date = timezone.now()
|
||||
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):
|
||||
@@ -567,7 +594,7 @@ class MembershipDeleteView(PermissionRequiredMixin, DeleteView):
|
||||
permission_required = "club.delete_membership"
|
||||
|
||||
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):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
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.context import RouteContext
|
||||
from pydantic import Field
|
||||
|
||||
from club.schemas import ClubProfileSchema
|
||||
from com.models import News, NewsDate
|
||||
@@ -11,12 +11,12 @@ from core.markdown import markdown
|
||||
|
||||
|
||||
class NewsDateFilterSchema(FilterSchema):
|
||||
before: Annotated[datetime | None, FilterLookup("end_date__lt")] = None
|
||||
after: Annotated[datetime | None, FilterLookup("start_date__gt")] = None
|
||||
club_id: Annotated[int | None, FilterLookup("news__club_id")] = None
|
||||
before: datetime | None = Field(None, q="end_date__lt")
|
||||
after: datetime | None = Field(None, q="start_date__gt")
|
||||
club_id: int | None = Field(None, q="news__club_id")
|
||||
news_id: int | None = None
|
||||
is_published: Annotated[bool | None, FilterLookup("news__is_published")] = None
|
||||
title: Annotated[str | None, FilterLookup("news__title__icontains")] = None
|
||||
is_published: bool | None = Field(None, q="news__is_published")
|
||||
title: str | None = Field(None, q="news__title__icontains")
|
||||
|
||||
|
||||
class NewsSchema(ModelSchema):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
@@ -17,6 +18,16 @@ from core.markdown import markdown
|
||||
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:
|
||||
redirect = Path(response.headers.get("X-Accel-Redirect", ""))
|
||||
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"):
|
||||
return []
|
||||
return itertools.groupby(
|
||||
User.objects.viewable_by(self.request.user)
|
||||
.filter(
|
||||
User.objects.filter(
|
||||
date_of_birth__month=localdate().month,
|
||||
date_of_birth__day=localdate().day,
|
||||
is_viewable=True,
|
||||
is_subscriber_viewable=True,
|
||||
)
|
||||
.filter(role__in=["STUDENT", "FORMER STUDENT"])
|
||||
.order_by("-date_of_birth"),
|
||||
@@ -701,7 +700,7 @@ class PosterModerateView(PermissionRequiredMixin, ComTabsMixin, View):
|
||||
parsed = urlparse(referer)
|
||||
if parsed.netloc == settings.SITH_URL:
|
||||
return redirect(parsed.path)
|
||||
return redirect("com:poster_list")
|
||||
return redirect(reverse("com:poster_list"))
|
||||
|
||||
|
||||
class ScreenListView(PermissionRequiredMixin, ComTabsMixin, ListView):
|
||||
|
||||
@@ -74,19 +74,9 @@ class UserBanAdmin(admin.ModelAdmin):
|
||||
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)
|
||||
class PermissionAdmin(admin.ModelAdmin):
|
||||
search_fields = ("codename",)
|
||||
inlines = (GroupInline,)
|
||||
|
||||
|
||||
@admin.register(Page)
|
||||
|
||||
26
core/api.py
26
core/api.py
@@ -1,6 +1,6 @@
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from annotated_types import Ge, Le, MinLen
|
||||
import annotated_types
|
||||
from django.conf import settings
|
||||
from django.db.models import F
|
||||
from django.http import HttpResponse
|
||||
@@ -28,7 +28,6 @@ from core.schemas import (
|
||||
UserSchema,
|
||||
)
|
||||
from core.templatetags.renderer import markdown
|
||||
from counter.utils import is_logged_in_counter
|
||||
|
||||
|
||||
@api_controller("/markdown")
|
||||
@@ -73,9 +72,9 @@ class MailingListController(ControllerBase):
|
||||
|
||||
@api_controller("/user")
|
||||
class UserController(ControllerBase):
|
||||
@route.get("", response=list[UserProfileSchema])
|
||||
@route.get("", response=list[UserProfileSchema], permissions=[CanAccessLookup])
|
||||
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])
|
||||
def fetch_user(self, user_id: int):
|
||||
@@ -86,18 +85,13 @@ class UserController(ControllerBase):
|
||||
"/search",
|
||||
response=PaginatedResponseSchema[UserProfileSchema],
|
||||
url_name="search_users",
|
||||
# logged in barmen aren't authenticated stricto sensu, so no auth here
|
||||
auth=None,
|
||||
permissions=[CanAccessLookup],
|
||||
)
|
||||
@paginate(PageNumberPaginationExtra, page_size=20)
|
||||
def search_users(self, filters: Query[UserFilterSchema]):
|
||||
qs = User.objects
|
||||
# the logged in barmen can see all users (even the hidden one),
|
||||
# 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)))
|
||||
return filters.filter(
|
||||
User.objects.order_by(F("last_login").desc(nulls_last=True))
|
||||
)
|
||||
|
||||
|
||||
@api_controller("/file")
|
||||
@@ -109,7 +103,7 @@ class SithFileController(ControllerBase):
|
||||
permissions=[CanAccessLookup],
|
||||
)
|
||||
@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)
|
||||
|
||||
|
||||
@@ -122,11 +116,11 @@ class GroupController(ControllerBase):
|
||||
permissions=[CanAccessLookup],
|
||||
)
|
||||
@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()
|
||||
|
||||
|
||||
DepthValue = Annotated[int, Ge(0), Le(10)]
|
||||
DepthValue = Annotated[int, annotated_types.Ge(0), annotated_types.Le(10)]
|
||||
DEFAULT_DEPTH = 4
|
||||
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import types
|
||||
import warnings
|
||||
from typing import TYPE_CHECKING, Any, LiteralString
|
||||
|
||||
from django.contrib.auth.mixins import AccessMixin, PermissionRequiredMixin
|
||||
@@ -146,6 +147,45 @@ class GenericContentPermissionMixinBuilder(View):
|
||||
return super().dispatch(request, *arg, **kwargs)
|
||||
|
||||
|
||||
class CanCreateMixin(View):
|
||||
"""Protect any child view that would create an object.
|
||||
|
||||
Raises:
|
||||
PermissionDenied:
|
||||
If the user has not the necessary permission
|
||||
to create the object of the view.
|
||||
"""
|
||||
|
||||
def __init_subclass__(cls, **kwargs):
|
||||
warnings.warn(
|
||||
f"{cls.__name__} is deprecated and should be replaced "
|
||||
"by other permission verification mecanism.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
super().__init_subclass__(**kwargs)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
warnings.warn(
|
||||
f"{self.__class__.__name__} is deprecated and should be replaced "
|
||||
"by other permission verification mecanism.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def dispatch(self, request, *arg, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *arg, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
obj = form.instance
|
||||
if can_edit_prop(obj, self.request.user):
|
||||
return super().form_valid(form)
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
class CanEditPropMixin(GenericContentPermissionMixinBuilder):
|
||||
"""Ensure the user has owner permissions on the child view object.
|
||||
|
||||
|
||||
@@ -150,8 +150,7 @@ class Command(BaseCommand):
|
||||
|
||||
Weekmail().save()
|
||||
|
||||
# Here we add a lot of test datas, that are not necessary for the Sith,
|
||||
# but that provide a basic development environment
|
||||
# Here we add a lot of test datas, that are not necessary for the Sith, but that provide a basic development environment
|
||||
self.now = timezone.now().replace(hour=12, second=0)
|
||||
|
||||
skia = User.objects.create_user(
|
||||
|
||||
@@ -350,6 +350,7 @@ class Command(BaseCommand):
|
||||
date=make_aware(
|
||||
self.faker.date_time_between(customer.since, localdate())
|
||||
),
|
||||
is_validated=True,
|
||||
)
|
||||
)
|
||||
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
|
||||
|
||||
import difflib
|
||||
import string
|
||||
import unicodedata
|
||||
from datetime import timedelta
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final, Self
|
||||
from typing import TYPE_CHECKING, Self
|
||||
from uuid import uuid4
|
||||
|
||||
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.staticfiles.storage import staticfiles_storage
|
||||
from django.core import validators
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import PermissionDenied, ValidationError
|
||||
from django.core.files import File
|
||||
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 PIL import Image, ImageOps
|
||||
|
||||
from core.utils import get_last_promo
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.core.files.uploadedfile import UploadedFile
|
||||
from pydantic import NonNegativeInt
|
||||
@@ -76,13 +74,24 @@ class Group(AuthGroup):
|
||||
def get_absolute_url(self) -> str:
|
||||
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:
|
||||
last_promo = get_last_promo()
|
||||
if not 0 < value <= last_promo:
|
||||
start_year = settings.SITH_SCHOOL_START_YEAR
|
||||
delta = (localdate() + timedelta(days=180)).year - start_year
|
||||
if value < 0 or delta < value:
|
||||
raise ValidationError(
|
||||
_("%(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))
|
||||
)
|
||||
|
||||
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)):
|
||||
# see https://docs.djangoproject.com/fr/stable/topics/migrations/#model-managers
|
||||
@@ -271,24 +271,13 @@ class User(AbstractUser):
|
||||
parent_address = models.CharField(
|
||||
_("parent address"), max_length=128, blank=True, default=""
|
||||
)
|
||||
is_viewable = models.BooleanField(
|
||||
_("Profile visible by subscribers"),
|
||||
help_text=_(
|
||||
"If you disable this option, only admin users "
|
||||
"will be able to see your profile."
|
||||
),
|
||||
default=True,
|
||||
is_subscriber_viewable = models.BooleanField(
|
||||
_("is subscriber viewable"), default=True
|
||||
)
|
||||
godfathers = models.ManyToManyField("User", related_name="godchildren", blank=True)
|
||||
|
||||
objects = CustomUserManager()
|
||||
|
||||
class Meta(AbstractUser.Meta):
|
||||
abstract = False
|
||||
permissions = [
|
||||
("view_hidden_user", "Can view hidden users"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.get_display_name()
|
||||
|
||||
@@ -562,12 +551,8 @@ class User(AbstractUser):
|
||||
def can_be_edited_by(self, user):
|
||||
return user.is_root or user.is_board_member
|
||||
|
||||
def can_be_viewed_by(self, user: User) -> bool:
|
||||
return (
|
||||
user.id == self.id
|
||||
or user.has_perm("core.view_hidden_user")
|
||||
or (user.has_perm("core.view_user") and self.is_viewable)
|
||||
)
|
||||
def can_be_viewed_by(self, user):
|
||||
return (user.was_subscribed and self.is_subscriber_viewable) or user.is_root
|
||||
|
||||
def get_mini_item(self):
|
||||
return """
|
||||
@@ -1334,9 +1319,6 @@ class PageRev(models.Model):
|
||||
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"))
|
||||
title = models.CharField(_("page title"), max_length=255, 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:
|
||||
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():
|
||||
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.utils import is_image
|
||||
|
||||
NonEmptyStr = Annotated[str, MinLen(1)]
|
||||
|
||||
|
||||
class UploadedImage(UploadedFile):
|
||||
@classmethod
|
||||
|
||||
@@ -21,8 +21,6 @@ $secondary-neutral-dark-color: hsl(40, 57.6%, 17%);
|
||||
|
||||
$white-color: hsl(219.6, 20.8%, 98%);
|
||||
$black-color: hsl(0, 0%, 17%);
|
||||
$red-text-color: #eb2f06;
|
||||
$hovered-red-text-color: #ff4d4d;
|
||||
|
||||
$faceblue: hsl(221, 44%, 41%);
|
||||
$twitblue: hsl(206, 82%, 63%);
|
||||
|
||||
@@ -65,7 +65,7 @@ footer.bottom-links {
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
background-color: $primary-neutral-dark-color;
|
||||
box-shadow: $shadow-color 0 0 15px;
|
||||
box-shadow: black 0 8px 15px;
|
||||
|
||||
a {
|
||||
color: $white-color;
|
||||
|
||||
@@ -745,32 +745,4 @@ form {
|
||||
background-repeat: no-repeat;
|
||||
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;
|
||||
|
||||
$red-text-color: #eb2f06;
|
||||
$hovered-red-text-color: #ff4d4d;
|
||||
|
||||
.header {
|
||||
box-sizing: border-box;
|
||||
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;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
@@ -96,7 +100,7 @@ $background-color-hovered: #283747;
|
||||
border-radius: 0;
|
||||
margin: 0;
|
||||
box-sizing: border-box;
|
||||
background-color: $deepblue;
|
||||
background-color: transparent;
|
||||
width: 45px;
|
||||
height: 25px;
|
||||
padding: 0;
|
||||
@@ -248,15 +252,12 @@ $background-color-hovered: #283747;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
a {
|
||||
color: $text-color;
|
||||
}
|
||||
|
||||
a,
|
||||
button {
|
||||
font-size: 100%;
|
||||
margin: 0;
|
||||
text-align: right;
|
||||
color: $text-color;
|
||||
margin-top: auto;
|
||||
|
||||
&:hover {
|
||||
@@ -268,6 +269,19 @@ $background-color-hovered: #283747;
|
||||
margin: 0;
|
||||
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;
|
||||
z-index: 100;
|
||||
border-radius: 10px;
|
||||
box-shadow: 3px 3px 3px 0 #767676;
|
||||
@include shadow;
|
||||
|
||||
>ul {
|
||||
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 {
|
||||
padding: 1em 1%;
|
||||
box-shadow: $shadow-color 0 5px 10px;
|
||||
padding: 1.5em 2%;
|
||||
border-radius: 5px;
|
||||
box-shadow: black 0 8px 15px;
|
||||
background: $white-color;
|
||||
overflow: auto;
|
||||
}
|
||||
@@ -519,6 +520,7 @@ th {
|
||||
td {
|
||||
margin: 5px;
|
||||
border-collapse: collapse;
|
||||
vertical-align: top;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
|
||||
@@ -7,13 +7,10 @@
|
||||
.profile {
|
||||
&-visible {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding-top: 10px;
|
||||
input[type="checkbox"]+label {
|
||||
max-width: unset;
|
||||
}
|
||||
}
|
||||
|
||||
&-pictures {
|
||||
@@ -119,19 +116,23 @@
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--nf-input-size) 10px;
|
||||
gap: 10px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
&-field {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
max-width: 330px;
|
||||
min-width: 300px;
|
||||
|
||||
@media (max-width: 750px) {
|
||||
gap: 4px;
|
||||
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 {
|
||||
height: 7rem;
|
||||
}
|
||||
|
||||
@@ -44,6 +44,18 @@
|
||||
|
||||
{% block additional_css %}{% 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 %}
|
||||
</head>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<header class="header">
|
||||
<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 class="header-logo-text" href="{{ url('core:index') }}">
|
||||
@@ -61,9 +61,7 @@
|
||||
<a href="{{ url('core:user_tools') }}">{% trans %}Tools{% endtrans %}</a>
|
||||
<form id="logout-form" method="post" action="{{ url("core:logout") }}">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="link-like link-red">
|
||||
{% trans %}Logout{% endtrans %}
|
||||
</button>
|
||||
<button type="submit">{% trans %}Logout{% endtrans %}</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -17,3 +17,12 @@
|
||||
{%- endfor -%}
|
||||
</ul>
|
||||
{% 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 %}
|
||||
<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>
|
||||
<form action="" method="post">
|
||||
{% csrf_token %}
|
||||
{{ form.as_p() }}
|
||||
<p><input type="submit" value="{% trans %}Save{% endtrans %}" /></p>
|
||||
</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 %}
|
||||
|
||||
|
||||
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 %}
|
||||
<h4>{% trans %}Users{% endtrans %}</h4>
|
||||
<ul>
|
||||
{% for user in users %}
|
||||
<li>
|
||||
{{ user_link_with_pict(user) }}
|
||||
</li>
|
||||
{% for i in result.users %}
|
||||
{% if user.can_view(i) %}
|
||||
<li>
|
||||
{{ user_link_with_pict(i) }}
|
||||
</li>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<h4>{% trans %}Clubs{% endtrans %}</h4>
|
||||
<ul>
|
||||
{% for club in clubs %}
|
||||
{% for i in result.clubs %}
|
||||
<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>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
@@ -17,9 +17,7 @@
|
||||
<td>{% trans %}Description{% endtrans %}</td>
|
||||
<td>{% trans %}Since{% endtrans %}</td>
|
||||
<td></td>
|
||||
{% if user.has_perm("club.delete_membership") %}
|
||||
<td></td>
|
||||
{% endif %}
|
||||
<td></td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -30,16 +28,7 @@
|
||||
<td>{{ m.description }}</td>
|
||||
<td>{{ m.start_date }}</td>
|
||||
{% if m.can_be_edited_by(user) %}
|
||||
<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>
|
||||
<td><a href="{{ url('club:membership_set_old', membership_id=m.id) }}">{% trans %}Mark as old{% endtrans %}</a></td>
|
||||
{% endif %}
|
||||
{% if user.has_perm("club.delete_membership") %}
|
||||
<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 %}From{% endtrans %}</td>
|
||||
<td>{% trans %}To{% endtrans %}</td>
|
||||
{% if user.has_perm("club.delete_membership") %}
|
||||
<td></td>
|
||||
{% endif %}
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
@@ -116,12 +116,12 @@
|
||||
{# All fields #}
|
||||
<div class="profile-fields">
|
||||
{%- 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 -%}
|
||||
{%- endif -%}
|
||||
|
||||
<div class="profile-field">
|
||||
{{ field.label_tag() }}
|
||||
<div class="profile-field-label">{{ field.label }}</div>
|
||||
<div class="profile-field-content">
|
||||
{{ field }}
|
||||
{%- if field.errors -%}
|
||||
@@ -136,7 +136,7 @@
|
||||
<div class="profile-fields">
|
||||
{%- for field in [form.quote, form.forum_signature] -%}
|
||||
<div class="profile-field">
|
||||
{{ field.label_tag() }}
|
||||
<div class="profile-field-label">{{ field.label }}</div>
|
||||
<div class="profile-field-content">
|
||||
{{ field }}
|
||||
{%- if field.errors -%}
|
||||
@@ -149,13 +149,8 @@
|
||||
|
||||
{# Checkboxes #}
|
||||
<div class="profile-visible">
|
||||
<div class="row">
|
||||
{{ form.is_viewable }}
|
||||
{{ form.is_viewable.label_tag() }}
|
||||
</div>
|
||||
<span class="helptext">
|
||||
{{ form.is_viewable.help_text }}
|
||||
</span>
|
||||
{{ form.is_subscriber_viewable }}
|
||||
{{ form.is_subscriber_viewable.label }}
|
||||
</div>
|
||||
<div class="final-actions">
|
||||
|
||||
|
||||
@@ -11,35 +11,32 @@
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
{% if total_perm_time %}
|
||||
{% if profile.permanencies %}
|
||||
<div>
|
||||
<h3>{% trans %}Permanencies{% endtrans %}</h3>
|
||||
<div class="flexed">
|
||||
{% for perm in perm_time %}
|
||||
<div>
|
||||
<span>{{ perm["counter__name"] }} :</span>
|
||||
<span>{{ perm["total"]|format_timedelta }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div><b>Total :</b><b>{{ total_perm_time|format_timedelta }}</b></div>
|
||||
<div><span>Foyer :</span><span>{{ total_foyer_time }}</span></div>
|
||||
<div><span>Gommette :</span><span>{{ total_gommette_time }}</span></div>
|
||||
<div><span>MDE :</span><span>{{ total_mde_time }}</span></div>
|
||||
<div><b>Total :</b><b>{{ total_perm_time }}</b></div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div>
|
||||
<h3>{% trans %}Buyings{% endtrans %}</h3>
|
||||
<div class="flexed">
|
||||
{% for sum in purchase_sums %}
|
||||
<div>
|
||||
<span>{{ sum["counter__name"] }}</span>
|
||||
<span>{{ sum["total"] }} €</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div><b>Total : </b><b>{{ total_purchases }} €</b></div>
|
||||
<div><span>Foyer :</span><span>{{ total_foyer_buyings }} €</span></div>
|
||||
<div><span>Gommette :</span><span>{{ total_gommette_buyings }} €</span></div>
|
||||
<div><span>MDE :</span><span>{{ total_mde_buyings }} €</span></div>
|
||||
<div><b>Total :</b><b>{{ total_foyer_buyings + total_gommette_buyings + total_mde_buyings }} €</b>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>{% trans %}Product top 15{% endtrans %}</h3>
|
||||
<h3>{% trans %}Product top 10{% endtrans %}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
@@ -55,17 +55,31 @@ def phonenumber(
|
||||
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")
|
||||
def format_timedelta(value: datetime.timedelta) -> str:
|
||||
value = value - datetime.timedelta(microseconds=value.microseconds)
|
||||
days = value.days
|
||||
if days == 0:
|
||||
return str(value)
|
||||
remainder = value - datetime.timedelta(days=days)
|
||||
return ngettext(
|
||||
"%(nb_days)d day, %(remainder)s",
|
||||
"%(nb_days)d days, %(remainder)s",
|
||||
days,
|
||||
"%(nb_days)d day, %(remainder)s", "%(nb_days)d days, %(remainder)s", days
|
||||
) % {"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.core import mail
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.mail import EmailMessage
|
||||
from django.test import Client, RequestFactory, TestCase
|
||||
from django.urls import reverse
|
||||
@@ -35,10 +34,9 @@ from pytest_django.asserts import assertInHTML, assertRedirects
|
||||
|
||||
from antispam.models import ToxicDomain
|
||||
from club.models import Club, Membership
|
||||
from core.baker_recipes import subscriber_user
|
||||
from core.markdown import markdown
|
||||
from core.models import AnonymousUser, Group, Page, User, validate_promo
|
||||
from core.utils import get_last_promo, get_semester_code, get_start_of_semester
|
||||
from core.models import AnonymousUser, Group, Page, User
|
||||
from core.utils import get_semester_code, get_start_of_semester
|
||||
from core.views import AllowFragment
|
||||
from counter.models import Customer
|
||||
from sith import settings
|
||||
@@ -320,8 +318,9 @@ class TestPageHandling(TestCase):
|
||||
def test_access_page_not_found(self):
|
||||
"""Should not display a page correctly."""
|
||||
response = self.client.get(reverse("core:page", kwargs={"page_name": "swagg"}))
|
||||
assert response.status_code == 404
|
||||
assert '<a href="/page/create/?page=swagg">' in response.text
|
||||
assert response.status_code == 200
|
||||
html = response.text
|
||||
self.assertIn('<a href="/page/create/?page=swagg">', html)
|
||||
|
||||
def test_create_page_markdown_safe(self):
|
||||
"""Should format the markdown and escape html correctly."""
|
||||
@@ -524,21 +523,6 @@ class TestDateUtils(TestCase):
|
||||
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():
|
||||
class TestAllowFragmentView(AllowFragment, ContextMixin, View):
|
||||
def get(self, *args, **kwargs):
|
||||
@@ -552,10 +536,3 @@ def test_allow_fragment_mixin():
|
||||
assert not TestAllowFragmentView.as_view()(request)
|
||||
request.headers = {"HX-Request": True, **base_headers}
|
||||
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
|
||||
|
||||
def test_fetch_family_hidden_user(self):
|
||||
self.main_user.is_viewable = False
|
||||
self.main_user.is_subscriber_viewable = False
|
||||
self.main_user.save()
|
||||
for user_to_login, error_code in [
|
||||
(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
|
||||
from bs4 import BeautifulSoup
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import Client
|
||||
from django.urls import reverse
|
||||
from django.utils.timezone import now
|
||||
from model_bakery import baker
|
||||
from pytest_django.asserts import assertHTMLEqual, assertRedirects
|
||||
from pytest_django.asserts import assertRedirects
|
||||
|
||||
from club.models import Club
|
||||
from core.baker_recipes import board_user, subscriber_user
|
||||
from core.markdown import markdown
|
||||
from core.models import AnonymousUser, Page, PageRev, User
|
||||
from core.models import AnonymousUser, Page, User
|
||||
from sith.settings import SITH_GROUP_OLD_SUBSCRIBERS_ID, SITH_GROUP_SUBSCRIBERS_ID
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestEditPage:
|
||||
def test_edit_page(self, client: Client):
|
||||
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."""
|
||||
def test_edit_page(client: Client):
|
||||
user = board_user.make()
|
||||
page = baker.prepare(Page)
|
||||
page.save(force_lock=True)
|
||||
page.view_groups.add(settings.SITH_GROUP_SUBSCRIBERS_ID)
|
||||
revisions = baker.make(
|
||||
PageRev, page=page, _quantity=3, content=iter(["foo", "bar", "baz"])
|
||||
)
|
||||
client.force_login(subscriber_user.make())
|
||||
url = reverse(
|
||||
"core:page_rev",
|
||||
kwargs={"page_name": page._full_name, "rev": revisions[1].id},
|
||||
)
|
||||
page.view_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
|
||||
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_page_club_redirection(client: Client):
|
||||
club = baker.make(Club)
|
||||
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)
|
||||
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"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -125,9 +35,9 @@ def test_viewable_by():
|
||||
Page.objects.all().delete()
|
||||
view_groups = [
|
||||
[settings.SITH_GROUP_PUBLIC_ID],
|
||||
[settings.SITH_GROUP_PUBLIC_ID, settings.SITH_GROUP_SUBSCRIBERS_ID],
|
||||
[settings.SITH_GROUP_SUBSCRIBERS_ID],
|
||||
[settings.SITH_GROUP_SUBSCRIBERS_ID, settings.SITH_GROUP_OLD_SUBSCRIBERS_ID],
|
||||
[settings.SITH_GROUP_PUBLIC_ID, SITH_GROUP_SUBSCRIBERS_ID],
|
||||
[SITH_GROUP_SUBSCRIBERS_ID],
|
||||
[SITH_GROUP_SUBSCRIBERS_ID, SITH_GROUP_OLD_SUBSCRIBERS_ID],
|
||||
[],
|
||||
]
|
||||
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)
|
||||
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 unittest import mock
|
||||
|
||||
import pytest
|
||||
from django.conf import settings
|
||||
from django.contrib import auth
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.core.management import call_command
|
||||
from django.test import Client, RequestFactory, TestCase
|
||||
from django.urls import reverse
|
||||
@@ -21,11 +18,10 @@ from core.baker_recipes import (
|
||||
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 counter.baker_recipes import sale_recipe
|
||||
from counter.models import Counter, Customer, Permanency, Refilling, Selling
|
||||
from counter.utils import is_logged_in_counter
|
||||
from counter.models import Counter, Customer, Refilling, Selling
|
||||
from eboutic.models import Invoice, InvoiceItem
|
||||
|
||||
|
||||
@@ -63,9 +59,7 @@ class TestSearchUsersAPI(TestSearchUsers):
|
||||
"""Test that users are ordered by last login date."""
|
||||
self.client.force_login(subscriber_user.make())
|
||||
|
||||
response = self.client.get(
|
||||
reverse("api:search_users", query={"search": "First"})
|
||||
)
|
||||
response = self.client.get(reverse("api:search_users") + "?search=First")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["count"] == 11
|
||||
# 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):
|
||||
"""Test that the search is case-insensitive."""
|
||||
"""Test that the search is case insensitive."""
|
||||
self.client.force_login(subscriber_user.make())
|
||||
|
||||
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
|
||||
|
||||
def test_search_nick_name(self):
|
||||
"""Test that the search can be done on the nickname."""
|
||||
# hidden users should not be in the final result,
|
||||
# even when the nickname matches
|
||||
self.users[10].is_viewable = False
|
||||
self.users[10].save()
|
||||
"""Test that the search can be done on the nick name."""
|
||||
self.client.force_login(subscriber_user.make())
|
||||
|
||||
# this should return users with nicknames Nick11, Nick10 and Nick1
|
||||
response = self.client.get(
|
||||
reverse("api:search_users", query={"search": "Nick1"})
|
||||
)
|
||||
response = self.client.get(reverse("api:search_users") + "?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,
|
||||
]
|
||||
@@ -111,25 +100,10 @@ class TestSearchUsersAPI(TestSearchUsers):
|
||||
self.client.force_login(subscriber_user.make())
|
||||
|
||||
# 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 [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):
|
||||
"""Test the search user view (`GET /search`)."""
|
||||
@@ -188,7 +162,11 @@ class TestFilterInactive(TestCase):
|
||||
time_inactive = time_active - timedelta(days=3)
|
||||
counter, seller = baker.make(Counter), baker.make(User)
|
||||
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 = [
|
||||
@@ -390,63 +368,3 @@ class TestRedirectMe:
|
||||
def test_promo_has_logo(promo):
|
||||
user = baker.make(User, promo=promo)
|
||||
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.views.generic import RedirectView
|
||||
|
||||
from com.views import NewsListView
|
||||
from core.converters import (
|
||||
BooleanStringConverter,
|
||||
FourDigitYearConverter,
|
||||
@@ -54,7 +53,6 @@ from core.views import (
|
||||
PagePropView,
|
||||
PageRevView,
|
||||
PageView,
|
||||
SearchView,
|
||||
SithLoginView,
|
||||
SithPasswordChangeDoneView,
|
||||
SithPasswordChangeView,
|
||||
@@ -78,9 +76,13 @@ from core.views import (
|
||||
UserUpdateProfileView,
|
||||
UserView,
|
||||
delete_user_godfather,
|
||||
index,
|
||||
logout,
|
||||
notification,
|
||||
password_root_change,
|
||||
search_json,
|
||||
search_user_json,
|
||||
search_view,
|
||||
send_file,
|
||||
)
|
||||
|
||||
@@ -89,11 +91,13 @@ register_converter(TwoDigitMonthConverter, "mm")
|
||||
register_converter(BooleanStringConverter, "bool")
|
||||
|
||||
urlpatterns = [
|
||||
path("", NewsListView.as_view(), name="index"),
|
||||
path("", index, name="index"),
|
||||
path("notifications/", NotificationList.as_view(), name="notification_list"),
|
||||
path("notification/<int:notif_id>/", notification, name="notification"),
|
||||
# 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
|
||||
path("login/", SithLoginView.as_view(), name="login"),
|
||||
path("logout/", logout, name="logout"),
|
||||
|
||||
@@ -112,16 +112,6 @@ def get_semester_code(d: date | None = None) -> str:
|
||||
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):
|
||||
try:
|
||||
im = PIL.Image.open(file.file)
|
||||
@@ -196,7 +186,7 @@ def exif_auto_rotate(image):
|
||||
|
||||
def get_client_ip(request: HttpRequest) -> str | None:
|
||||
headers = (
|
||||
"X_FORWARDED_FOR", # Common header for proxies
|
||||
"X_FORWARDED_FOR", # Common header for proixes
|
||||
"FORWARDED", # Standard header defined by RFC 7239.
|
||||
"REMOTE_ADDR", # Default IP Address (direct connection)
|
||||
)
|
||||
|
||||
@@ -21,10 +21,10 @@
|
||||
# Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||
#
|
||||
#
|
||||
|
||||
from django.http import (
|
||||
Http404,
|
||||
HttpRequest,
|
||||
HttpResponseForbidden,
|
||||
HttpResponseNotFound,
|
||||
HttpResponseServerError,
|
||||
)
|
||||
from django.shortcuts import render
|
||||
@@ -33,20 +33,17 @@ from django.views.generic.edit import FormView
|
||||
from sentry_sdk import last_event_id
|
||||
|
||||
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()}
|
||||
return HttpResponseForbidden(render(request, "core/403.jinja", context=context))
|
||||
|
||||
|
||||
def not_found(request: HttpRequest, exception: Http404):
|
||||
if isinstance(exception, PageNotFound):
|
||||
template_name = "core/page/not_found.jinja"
|
||||
else:
|
||||
template_name = "core/404.jinja"
|
||||
return render(request, template_name, context={"exception": exception}, status=404)
|
||||
def not_found(request, exception):
|
||||
return HttpResponseNotFound(
|
||||
render(request, "core/404.jinja", context={"exception": exception})
|
||||
)
|
||||
|
||||
|
||||
def internal_servor_error(request):
|
||||
|
||||
@@ -21,7 +21,6 @@
|
||||
#
|
||||
#
|
||||
import re
|
||||
from copy import copy
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
|
||||
@@ -43,12 +42,13 @@ from django.forms import (
|
||||
Widget,
|
||||
)
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
||||
from PIL import Image
|
||||
|
||||
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.views.widgets.ajax_select import (
|
||||
AutoCompleteSelect,
|
||||
@@ -56,7 +56,6 @@ from core.views.widgets.ajax_select import (
|
||||
AutoCompleteSelectMultipleGroup,
|
||||
AutoCompleteSelectUser,
|
||||
)
|
||||
from core.views.widgets.markdown import MarkdownInput
|
||||
|
||||
# Widgets
|
||||
|
||||
@@ -87,6 +86,30 @@ class NFCTextInput(TextInput):
|
||||
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
|
||||
|
||||
|
||||
@@ -179,7 +202,7 @@ class UserProfileForm(forms.ModelForm):
|
||||
"school",
|
||||
"promo",
|
||||
"forum_signature",
|
||||
"is_viewable",
|
||||
"is_subscriber_viewable",
|
||||
]
|
||||
widgets = {
|
||||
"date_of_birth": SelectDate,
|
||||
@@ -188,8 +211,8 @@ class UserProfileForm(forms.ModelForm):
|
||||
"quote": forms.Textarea,
|
||||
}
|
||||
|
||||
def __init__(self, *args, label_suffix: str = "", **kwargs):
|
||||
super().__init__(*args, label_suffix=label_suffix, **kwargs)
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# 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
|
||||
@@ -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 Meta:
|
||||
model = Gift
|
||||
|
||||
@@ -22,49 +22,106 @@
|
||||
#
|
||||
#
|
||||
|
||||
import json
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.db.models import F
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core import serializers
|
||||
from django.db.models.query import QuerySet
|
||||
from django.http import HttpRequest
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.views.generic import ListView, TemplateView
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import redirect, render
|
||||
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 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
|
||||
template_name = "core/notification_list.jinja"
|
||||
|
||||
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:
|
||||
self.request.user.notifications.filter(viewed=False).update(viewed=True)
|
||||
return self.request.user.notifications.order_by("-date")[:20]
|
||||
|
||||
|
||||
def notification(request: HttpRequest, notif_id: int):
|
||||
notif = get_object_or_404(Notification, id=notif_id)
|
||||
if notif.type not in settings.SITH_PERMANENT_NOTIFICATIONS:
|
||||
notif.viewed = True
|
||||
else:
|
||||
notif.callback()
|
||||
notif.save()
|
||||
return redirect(notif.url)
|
||||
def notification(request, notif_id):
|
||||
notif = Notification.objects.filter(id=notif_id).first()
|
||||
if notif:
|
||||
if notif.type not in settings.SITH_PERMANENT_NOTIFICATIONS:
|
||||
notif.viewed = True
|
||||
else:
|
||||
notif.callback()
|
||||
notif.save()
|
||||
return redirect(notif.url)
|
||||
return redirect("/")
|
||||
|
||||
|
||||
class SearchView(LoginRequiredMixin, TemplateView):
|
||||
template_name = "core/search.jinja"
|
||||
def search_user(query):
|
||||
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 = [], []
|
||||
if query := self.request.GET.get("query"):
|
||||
users = list(
|
||||
UserFilterSchema(search=query)
|
||||
.filter(User.objects.viewable_by(self.request.user))
|
||||
.order_by(F("last_login").desc(nulls_last=True))
|
||||
)
|
||||
clubs = list(Club.objects.filter(name__icontains=query)[:5])
|
||||
return super().get_context_data(**kwargs) | {"users": users, "clubs": clubs}
|
||||
|
||||
def search_club(query, *, as_json=False):
|
||||
clubs = []
|
||||
if query:
|
||||
clubs = Club.objects.filter(name__icontains=query).all()
|
||||
clubs = clubs[:5]
|
||||
if as_json:
|
||||
# Re-loads json to avoid double encoding by JsonResponse, but still benefit from serializers
|
||||
clubs = json.loads(serializers.serialize("json", clubs, fields=("name")))
|
||||
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.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.shortcuts import get_object_or_404, redirect
|
||||
from django.shortcuts import redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.functional import cached_property
|
||||
from django.views.generic import DetailView, ListView
|
||||
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||
|
||||
from core.auth.mixins import CanEditPropMixin, CanViewMixin
|
||||
from core.models import Page, PageRev
|
||||
from core.views.forms import PageForm, PagePropForm, PageRevisionForm
|
||||
from core.auth.mixins import (
|
||||
CanEditMixin,
|
||||
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):
|
||||
"""Http404 Exception, but specifically for when the not found object is a Page."""
|
||||
|
||||
def __init__(self, page_name: str):
|
||||
self.page_name = page_name
|
||||
|
||||
|
||||
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 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 PageListView(ListView):
|
||||
model = Page
|
||||
template_name = "core/page/list.jinja"
|
||||
template_name = "core/page_list.jinja"
|
||||
|
||||
def get_queryset(self):
|
||||
return (
|
||||
@@ -64,57 +64,80 @@ class PageListView(ListView):
|
||||
)
|
||||
|
||||
|
||||
class BasePageDetailView(CanViewMixin, DetailView):
|
||||
class PageView(CanViewMixin, DetailView):
|
||||
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"
|
||||
_cached_object: Page | None = None
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
page = self.get_object()
|
||||
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)
|
||||
|
||||
def get_object(self, *args, **kwargs):
|
||||
if not self._cached_object:
|
||||
full_name = self.kwargs.get(self.slug_url_kwarg)
|
||||
self._cached_object = get_page_or_404(full_name)
|
||||
self._cached_object = super().get_object()
|
||||
return self._cached_object
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(**kwargs) | {
|
||||
"last_revision": self.object.revisions.last()
|
||||
}
|
||||
|
||||
|
||||
class PageView(BasePageDetailView):
|
||||
template_name = "core/page/detail.jinja"
|
||||
|
||||
|
||||
class PageHistView(BasePageDetailView):
|
||||
template_name = "core/page/history.jinja"
|
||||
|
||||
|
||||
class PageRevView(BasePageDetailView):
|
||||
template_name = "core/page/detail.jinja"
|
||||
class PageRevView(CanViewMixin, DetailView):
|
||||
model = Page
|
||||
template_name = "core/page_detail.jinja"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
page = self.get_object()
|
||||
if page.need_club_redirection:
|
||||
res = super().dispatch(request, *args, **kwargs)
|
||||
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(
|
||||
"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 super().dispatch(request, *args, **kwargs)
|
||||
return res
|
||||
|
||||
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):
|
||||
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):
|
||||
model = Page
|
||||
form_class = PageForm
|
||||
template_name = "core/create.jinja"
|
||||
template_name = "core/page_prop.jinja"
|
||||
permission_required = "core.add_page"
|
||||
|
||||
def get_initial(self):
|
||||
@@ -129,67 +152,88 @@ class PageCreateView(PermissionRequiredMixin, CreateView):
|
||||
init["name"] = page_name[-1]
|
||||
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):
|
||||
form.instance.set_lock(self.request.user)
|
||||
ret = super().form_valid(form)
|
||||
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):
|
||||
model = Page
|
||||
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):
|
||||
self.page = get_page_or_404(full_name=self.kwargs["page_name"])
|
||||
self.page.set_lock_recursive(self.request.user)
|
||||
self.page = super().get_object()
|
||||
try:
|
||||
self.page.set_lock_recursive(self.request.user)
|
||||
except LockError as e:
|
||||
raise e
|
||||
return self.page
|
||||
|
||||
|
||||
class BasePageEditView(UserPassesTestMixin, UpdateView):
|
||||
class PageEditViewBase(CanEditMixin, UpdateView):
|
||||
model = PageRev
|
||||
form_class = PageRevisionForm
|
||||
template_name = "core/page/edit.jinja"
|
||||
|
||||
def test_func(self):
|
||||
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
|
||||
form_class = modelform_factory(
|
||||
model=PageRev, fields=["title", "content"], widgets={"content": MarkdownInput}
|
||||
)
|
||||
template_name = "core/pagerev_edit.jinja"
|
||||
|
||||
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):
|
||||
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):
|
||||
return super().get_form_kwargs() | {
|
||||
"author": self.request.user,
|
||||
"page": self.page,
|
||||
}
|
||||
def form_valid(self, form):
|
||||
# TODO : factor that, but first make some tests
|
||||
rev = form.instance
|
||||
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):
|
||||
if self.page.need_club_redirection:
|
||||
return redirect("club:club_edit_page", club_id=self.page.club.id)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
res = super().dispatch(request, *args, **kwargs)
|
||||
if self.object and self.object.page.need_club_redirection:
|
||||
return redirect("club:club_edit_page", club_id=self.object.page.club.id)
|
||||
return res
|
||||
|
||||
|
||||
class PageDeleteView(CanEditPagePropMixin, DeleteView):
|
||||
model = Page
|
||||
template_name = "core/delete_confirm.jinja"
|
||||
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
|
||||
from datetime import timedelta
|
||||
|
||||
# This file contains all the views that concern the user model
|
||||
from datetime import date, timedelta
|
||||
from operator import itemgetter
|
||||
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.mixins import LoginRequiredMixin
|
||||
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.forms.models import modelform_factory
|
||||
from django.http import Http404
|
||||
@@ -66,8 +66,9 @@ from core.views.forms import (
|
||||
UserProfileForm,
|
||||
)
|
||||
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 subscription.models import Subscription
|
||||
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."""
|
||||
if not request.user.is_root:
|
||||
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":
|
||||
form = views.SetPasswordForm(user=user, data=request.POST)
|
||||
if form.is_valid():
|
||||
@@ -352,40 +355,87 @@ class UserStatsView(UserTabsMixin, CanViewMixin, DetailView):
|
||||
context_object_name = "profile"
|
||||
template_name = "core/user_stats.jinja"
|
||||
current_tab = "stats"
|
||||
queryset = User.objects.exclude(customer=None).select_related("customer")
|
||||
|
||||
def dispatch(self, request, *arg, **kwargs):
|
||||
profile = self.get_object()
|
||||
|
||||
if not hasattr(profile, "customer"):
|
||||
raise Http404
|
||||
|
||||
if not (
|
||||
profile == request.user or request.user.has_perm("counter.view_customer")
|
||||
):
|
||||
raise PermissionDenied
|
||||
|
||||
return super().dispatch(request, *arg, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
from django.db.models import Sum
|
||||
|
||||
kwargs["perm_time"] = list(
|
||||
self.object.permanencies.filter(end__isnull=False, counter__type="BAR")
|
||||
.values("counter", "counter__name")
|
||||
.annotate(total=Sum(F("end") - F("start"), default=timedelta(seconds=0)))
|
||||
.order_by("-total")
|
||||
)
|
||||
foyer = Counter.objects.filter(name="Foyer").first()
|
||||
mde = Counter.objects.filter(name="MDE").first()
|
||||
gommette = Counter.objects.filter(name="La Gommette").first()
|
||||
semester_start = Subscription.compute_start(d=date.today(), duration=3)
|
||||
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(
|
||||
self.object.customer.buyings.filter(counter__type="BAR")
|
||||
.values("counter", "counter__name")
|
||||
.annotate(total=Sum(F("unit_price") * F("quantity")))
|
||||
.order_by("-total")
|
||||
kwargs["total_foyer_time"] = sum(
|
||||
[
|
||||
p.end - p.start
|
||||
for p in self.object.permanencies.filter(counter=foyer).exclude(
|
||||
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"] = (
|
||||
self.object.customer.buyings.values("product__name")
|
||||
.annotate(product_sum=Sum("quantity"))
|
||||
.exclude(product_sum=None)
|
||||
.order_by("-product_sum")
|
||||
.all()[:15]
|
||||
.all()[:10]
|
||||
)
|
||||
return kwargs
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
PAYMENT_METHOD = [
|
||||
("CHECK", _("Check")),
|
||||
("CASH", _("Cash")),
|
||||
("CARD", _("Credit card")),
|
||||
]
|
||||
|
||||
|
||||
class CounterConfig(AppConfig):
|
||||
name = "counter"
|
||||
|
||||
109
counter/forms.py
109
counter/forms.py
@@ -1,11 +1,10 @@
|
||||
import json
|
||||
import math
|
||||
import uuid
|
||||
from datetime import date, datetime, timezone
|
||||
from datetime import date
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
from django import forms
|
||||
from django.core.validators import MaxValueValidator
|
||||
from django.db.models import Exists, OuterRef, Q
|
||||
from django.forms import BaseModelFormSet
|
||||
from django.utils.timezone import now
|
||||
@@ -35,7 +34,6 @@ from counter.models import (
|
||||
Eticket,
|
||||
InvoiceCall,
|
||||
Product,
|
||||
ProductFormula,
|
||||
Refilling,
|
||||
ReturnableProduct,
|
||||
ScheduledProductAction,
|
||||
@@ -138,10 +136,7 @@ class GetUserForm(forms.Form):
|
||||
|
||||
|
||||
class RefillForm(forms.ModelForm):
|
||||
allowed_refilling_methods = [
|
||||
Refilling.PaymentMethod.CASH,
|
||||
Refilling.PaymentMethod.CARD,
|
||||
]
|
||||
allowed_refilling_methods = ["CASH", "CARD"]
|
||||
|
||||
error_css_class = "error"
|
||||
required_css_class = "required"
|
||||
@@ -151,7 +146,7 @@ class RefillForm(forms.ModelForm):
|
||||
|
||||
class Meta:
|
||||
model = Refilling
|
||||
fields = ["amount", "payment_method"]
|
||||
fields = ["amount", "payment_method", "bank"]
|
||||
widgets = {"payment_method": forms.RadioSelect}
|
||||
|
||||
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:
|
||||
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 Meta:
|
||||
@@ -237,19 +235,6 @@ class ScheduledProductActionForm(forms.ModelForm):
|
||||
)
|
||||
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):
|
||||
def __init__(self, *args, product: Product, **kwargs):
|
||||
@@ -318,6 +303,7 @@ class ProductForm(forms.ModelForm):
|
||||
}
|
||||
|
||||
counters = forms.ModelMultipleChoiceField(
|
||||
help_text=None,
|
||||
label=_("Counters"),
|
||||
required=False,
|
||||
widget=AutoCompleteSelectMultipleCounter,
|
||||
@@ -328,81 +314,18 @@ class ProductForm(forms.ModelForm):
|
||||
super().__init__(*args, instance=instance, **kwargs)
|
||||
if self.instance.id:
|
||||
self.fields["counters"].initial = self.instance.counters.all()
|
||||
if hasattr(self.instance, "formula"):
|
||||
self.formula_init(self.instance.formula)
|
||||
self.action_formset = ScheduledProductActionFormSet(
|
||||
*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):
|
||||
return super().is_valid() and self.action_formset.is_valid()
|
||||
|
||||
def save(self, *args, **kwargs) -> Product:
|
||||
product = super().save(*args, **kwargs)
|
||||
product.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)
|
||||
def save(self, *args, **kwargs):
|
||||
ret = super().save(*args, **kwargs)
|
||||
self.instance.counters.set(self.cleaned_data["counters"])
|
||||
self.action_formset.save()
|
||||
return product
|
||||
|
||||
|
||||
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
|
||||
return ret
|
||||
|
||||
|
||||
class ReturnableProductForm(forms.ModelForm):
|
||||
@@ -410,8 +333,8 @@ class ReturnableProductForm(forms.ModelForm):
|
||||
model = ReturnableProduct
|
||||
fields = ["product", "returned_product", "max_return"]
|
||||
widgets = {
|
||||
"product": AutoCompleteSelectProduct,
|
||||
"returned_product": AutoCompleteSelectProduct,
|
||||
"product": AutoCompleteSelectProduct(),
|
||||
"returned_product": AutoCompleteSelectProduct(),
|
||||
}
|
||||
|
||||
def save(self, commit: bool = True) -> ReturnableProduct: # noqa FBT
|
||||
@@ -446,6 +369,7 @@ class EticketForm(forms.ModelForm):
|
||||
class CloseCustomerAccountForm(forms.Form):
|
||||
user = forms.ModelChoiceField(
|
||||
label=_("Refound this account"),
|
||||
help_text=None,
|
||||
required=True,
|
||||
widget=AutoCompleteSelectUser,
|
||||
queryset=User.objects.all(),
|
||||
@@ -565,14 +489,13 @@ class InvoiceCallForm(forms.Form):
|
||||
def __init__(self, *args, month: date, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.month = month
|
||||
month_start = datetime(month.year, month.month, month.day, tzinfo=timezone.utc)
|
||||
self.clubs = list(
|
||||
Club.objects.filter(
|
||||
Exists(
|
||||
Selling.objects.filter(
|
||||
club=OuterRef("pk"),
|
||||
date__gte=month_start,
|
||||
date__lte=month_start + relativedelta(months=1),
|
||||
date__gte=month,
|
||||
date__lte=month + relativedelta(months=1),
|
||||
)
|
||||
)
|
||||
).annotate(
|
||||
|
||||
@@ -119,6 +119,7 @@ class Command(BaseCommand):
|
||||
quantity=1,
|
||||
unit_price=account.amount,
|
||||
date=now(),
|
||||
is_validated=True,
|
||||
)
|
||||
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.models import Group, Notification, User
|
||||
from core.utils import get_start_of_semester
|
||||
from counter.apps import PAYMENT_METHOD
|
||||
from counter.fields import CurrencyField
|
||||
from subscription.models import Subscription
|
||||
|
||||
@@ -79,8 +80,7 @@ class CustomerQuerySet(models.QuerySet):
|
||||
)
|
||||
money_out = Subquery(
|
||||
Selling.objects.filter(
|
||||
customer=OuterRef("pk"),
|
||||
payment_method=Selling.PaymentMethod.SITH_ACCOUNT,
|
||||
customer=OuterRef("pk"), payment_method="SITH_ACCOUNT"
|
||||
)
|
||||
.values("customer_id")
|
||||
.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
|
||||
|
||||
|
||||
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):
|
||||
def annotate_has_barman(self, user: User) -> Self:
|
||||
"""Annotate the queryset with the `user_is_barman` field.
|
||||
@@ -762,11 +731,6 @@ class RefillingQuerySet(models.QuerySet):
|
||||
class Refilling(models.Model):
|
||||
"""Handle the refilling."""
|
||||
|
||||
class PaymentMethod(models.IntegerChoices):
|
||||
CARD = 0, _("Credit card")
|
||||
CASH = 1, _("Cash")
|
||||
CHECK = 2, _("Check")
|
||||
|
||||
counter = models.ForeignKey(
|
||||
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
|
||||
)
|
||||
date = models.DateTimeField(_("date"))
|
||||
payment_method = models.PositiveSmallIntegerField(
|
||||
_("payment method"), choices=PaymentMethod, default=PaymentMethod.CARD
|
||||
payment_method = models.CharField(
|
||||
_("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()
|
||||
|
||||
@@ -800,9 +771,10 @@ class Refilling(models.Model):
|
||||
if not self.date:
|
||||
self.date = timezone.now()
|
||||
self.full_clean()
|
||||
if self._state.adding:
|
||||
if not self.is_validated:
|
||||
self.customer.amount += self.amount
|
||||
self.customer.save()
|
||||
self.is_validated = True
|
||||
if self.customer.user.preferences.notify_on_refill:
|
||||
Notification(
|
||||
user=self.customer.user,
|
||||
@@ -842,10 +814,6 @@ class SellingQuerySet(models.QuerySet):
|
||||
class Selling(models.Model):
|
||||
"""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
|
||||
label = models.CharField(_("label"), max_length=128)
|
||||
product = models.ForeignKey(
|
||||
@@ -882,9 +850,13 @@ class Selling(models.Model):
|
||||
on_delete=models.SET_NULL,
|
||||
)
|
||||
date = models.DateTimeField(_("date"), db_index=True)
|
||||
payment_method = models.PositiveSmallIntegerField(
|
||||
_("payment method"), choices=PaymentMethod, default=PaymentMethod.SITH_ACCOUNT
|
||||
payment_method = models.CharField(
|
||||
_("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()
|
||||
|
||||
@@ -903,12 +875,10 @@ class Selling(models.Model):
|
||||
if not self.date:
|
||||
self.date = timezone.now()
|
||||
self.full_clean()
|
||||
if (
|
||||
self._state.adding
|
||||
and self.payment_method == self.PaymentMethod.SITH_ACCOUNT
|
||||
):
|
||||
if not self.is_validated:
|
||||
self.customer.amount -= self.quantity * self.unit_price
|
||||
self.customer.save(allow_negative=allow_negative)
|
||||
self.is_validated = True
|
||||
user = self.customer.user
|
||||
if user.was_subscribed:
|
||||
if (
|
||||
@@ -978,9 +948,7 @@ class Selling(models.Model):
|
||||
def is_owned_by(self, user: User) -> bool:
|
||||
if user.is_anonymous:
|
||||
return False
|
||||
return self.payment_method != self.PaymentMethod.CARD and user.is_owner(
|
||||
self.counter
|
||||
)
|
||||
return self.payment_method != "CARD" and user.is_owner(self.counter)
|
||||
|
||||
def can_be_viewed_by(self, user: User) -> bool:
|
||||
if (
|
||||
@@ -990,7 +958,7 @@ class Selling(models.Model):
|
||||
return user == self.customer.user
|
||||
|
||||
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.save()
|
||||
super().delete(*args, **kwargs)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Self
|
||||
|
||||
from annotated_types import MinLen
|
||||
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 club.schemas import SimpleClubSchema
|
||||
from core.schemas import GroupSchema, NonEmptyStr, SimpleUserSchema
|
||||
from core.schemas import GroupSchema, SimpleUserSchema
|
||||
from counter.models import Counter, Product, ProductType
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ class CounterSchema(ModelSchema):
|
||||
|
||||
|
||||
class CounterFilterSchema(FilterSchema):
|
||||
search: Annotated[NonEmptyStr | None, FilterLookup("name__icontains")] = None
|
||||
search: Annotated[str, MinLen(1)] = Field(None, q="name__icontains")
|
||||
|
||||
|
||||
class SimplifiedCounterSchema(ModelSchema):
|
||||
@@ -92,18 +92,11 @@ class ProductSchema(ModelSchema):
|
||||
|
||||
|
||||
class ProductFilterSchema(FilterSchema):
|
||||
search: Annotated[
|
||||
NonEmptyStr | None, FilterLookup(["name__icontains", "code__icontains"])
|
||||
] = None
|
||||
is_archived: Annotated[bool | None, FilterLookup("archived")] = None
|
||||
buying_groups: Annotated[set[int] | None, FilterLookup("buying_groups__in")] = None
|
||||
product_type: Annotated[set[int] | None, FilterLookup("product_type__in")] = None
|
||||
club: Annotated[set[int] | None, FilterLookup("club__in")] = None
|
||||
counter: Annotated[set[int] | None, FilterLookup("counters__in")] = None
|
||||
|
||||
|
||||
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
|
||||
search: Annotated[str, MinLen(1)] | None = Field(
|
||||
None, q=["name__icontains", "code__icontains"]
|
||||
)
|
||||
is_archived: bool | None = Field(None, q="archived")
|
||||
buying_groups: set[int] | None = Field(None, q="buying_groups__in")
|
||||
product_type: set[int] | None = Field(None, q="product_type__in")
|
||||
club: set[int] | None = Field(None, q="club__in")
|
||||
counter: set[int] | None = Field(None, q="counters__in")
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { AlertMessage } from "#core:utils/alert-message";
|
||||
import { BasketItem } from "#counter:counter/basket";
|
||||
import type {
|
||||
CounterConfig,
|
||||
ErrorMessage,
|
||||
ProductFormula,
|
||||
} from "#counter:counter/types";
|
||||
import type { CounterConfig, ErrorMessage } from "#counter:counter/types";
|
||||
import type { CounterProductSelect } from "./components/counter-product-select-index.ts";
|
||||
|
||||
document.addEventListener("alpine:init", () => {
|
||||
@@ -51,43 +47,15 @@ document.addEventListener("alpine:init", () => {
|
||||
|
||||
this.basket[id] = item;
|
||||
|
||||
this.checkFormulas();
|
||||
|
||||
if (this.sumBasket() > this.customerBalance) {
|
||||
item.quantity = oldQty;
|
||||
if (item.quantity === 0) {
|
||||
delete this.basket[id];
|
||||
}
|
||||
this.alertMessage.display(gettext("Not enough money"), { success: false });
|
||||
return gettext("Not enough money");
|
||||
}
|
||||
},
|
||||
|
||||
checkFormulas() {
|
||||
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);
|
||||
return "";
|
||||
},
|
||||
|
||||
getBasketSize() {
|
||||
@@ -102,7 +70,14 @@ document.addEventListener("alpine:init", () => {
|
||||
(acc: number, cur: BasketItem) => acc + cur.sum(),
|
||||
0,
|
||||
) 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) {
|
||||
@@ -141,7 +116,7 @@ document.addEventListener("alpine:init", () => {
|
||||
this.finish();
|
||||
}
|
||||
} else {
|
||||
this.addToBasket(code, quantity);
|
||||
this.addToBasketWithMessage(code, quantity);
|
||||
}
|
||||
this.codeField.widget.clear();
|
||||
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[];
|
||||
}
|
||||
|
||||
export interface ProductFormula {
|
||||
result: number;
|
||||
products: number[];
|
||||
}
|
||||
|
||||
export interface CounterConfig {
|
||||
customerBalance: number;
|
||||
customerId: number;
|
||||
products: Record<string, Product>;
|
||||
formulas: ProductFormula[];
|
||||
formInitial: InitialFormData[];
|
||||
cancelUrl: string;
|
||||
}
|
||||
|
||||
@@ -10,12 +10,12 @@
|
||||
float: right;
|
||||
}
|
||||
|
||||
.basket-message-container {
|
||||
.basket-error-container {
|
||||
position: relative;
|
||||
display: block
|
||||
}
|
||||
|
||||
.basket-message {
|
||||
.basket-error {
|
||||
z-index: 10; // to get on top of tomselect
|
||||
text-align: center;
|
||||
position: absolute;
|
||||
|
||||
@@ -32,11 +32,13 @@
|
||||
<div id="bar-ui" x-data="counter({
|
||||
customerBalance: {{ customer.amount }},
|
||||
products: products,
|
||||
formulas: formulas,
|
||||
customerId: {{ customer.pk }},
|
||||
formInitial: formInitial,
|
||||
cancelUrl: '{{ cancel_url }}',
|
||||
})">
|
||||
<noscript>
|
||||
<p class="important">Javascript is required for the counter UI.</p>
|
||||
</noscript>
|
||||
|
||||
<div id="user_info">
|
||||
<h5>{% trans %}Customer{% endtrans %}</h5>
|
||||
@@ -86,12 +88,11 @@
|
||||
|
||||
<form x-cloak method="post" action="" x-ref="basketForm">
|
||||
|
||||
<div class="basket-message-container">
|
||||
<div class="basket-error-container">
|
||||
<div
|
||||
x-cloak
|
||||
class="alert basket-message"
|
||||
:class="alertMessage.success ? 'alert-green' : 'alert-red'"
|
||||
x-show="alertMessage.open"
|
||||
class="alert alert-red basket-error"
|
||||
x-show="alertMessage.show"
|
||||
x-transition.duration.500ms
|
||||
x-text="alertMessage.content"
|
||||
></div>
|
||||
@@ -110,9 +111,9 @@
|
||||
</div>
|
||||
</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>
|
||||
<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.sum().toLocaleString(undefined, { minimumFractionDigits: 2 })">€</span>
|
||||
@@ -212,7 +213,7 @@
|
||||
<h5 class="margin-bottom">{{ category }}</h5>
|
||||
<div class="row gap-2x">
|
||||
{% for product in categories[category] -%}
|
||||
<button class="card shadow" @click="addToBasket('{{ product.id }}', 1)">
|
||||
<button class="card shadow" @click="addToBasketWithMessage('{{ product.id }}', 1)">
|
||||
<img
|
||||
class="card-image"
|
||||
alt="image de {{ product.name }}"
|
||||
@@ -251,18 +252,6 @@
|
||||
},
|
||||
{%- endfor -%}
|
||||
};
|
||||
const formulas = [
|
||||
{%- for formula in formulas -%}
|
||||
{
|
||||
result: {{ formula.result_id }},
|
||||
products: [
|
||||
{%- for product in formula.products.all() -%}
|
||||
{{ product.id }},
|
||||
{%- endfor -%}
|
||||
]
|
||||
},
|
||||
{%- endfor -%}
|
||||
];
|
||||
const formInitial = [
|
||||
{%- for f in form -%}
|
||||
{%- 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"
|
||||
: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>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
<td>{{ loop.index }}</td>
|
||||
<td>{{ barman.name }} {% if barman.nickname %}({{ barman.nickname }}){% endif %}</td>
|
||||
<td>{{ barman.promo or '' }}</td>
|
||||
<td>{{ barman.perm_sum|format_timedelta }}</td>
|
||||
<td>{{ barman.perm_sum|format_timedelta|truncate_time("millis") }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -73,7 +73,7 @@
|
||||
<td>{{ loop.index }}</td>
|
||||
<td>{{ barman.name }} {% if barman.nickname %}({{ barman.nickname }}){% endif %}</td>
|
||||
<td>{{ barman.promo or '' }}</td>
|
||||
<td>{{ barman.perm_sum|format_timedelta }}</td>
|
||||
<td>{{ barman.perm_sum|format_timedelta|truncate_time("millis") }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
@@ -116,6 +116,7 @@ class TestAccountDumpCommand(TestAccountDump):
|
||||
operation: Selling = customer.buyings.order_by("date").last()
|
||||
assert operation.unit_price == initial_amount
|
||||
assert operation.counter_id == settings.SITH_COUNTER_ACCOUNT_DUMP_ID
|
||||
assert operation.is_validated is True
|
||||
dump = customer.dumps.last()
|
||||
assert dump.dump_operation == operation
|
||||
|
||||
|
||||
@@ -11,12 +11,8 @@ from model_bakery import baker
|
||||
|
||||
from core.models import Group, User
|
||||
from counter.baker_recipes import counter_recipe, product_recipe
|
||||
from counter.forms import (
|
||||
ProductForm,
|
||||
ScheduledProductActionForm,
|
||||
ScheduledProductActionFormSet,
|
||||
)
|
||||
from counter.models import Product, ScheduledProductAction
|
||||
from counter.forms import ScheduledProductActionForm, ScheduledProductActionFormSet
|
||||
from counter.models import ScheduledProductAction
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -38,39 +34,6 @@ def test_edit_product(client: Client):
|
||||
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
|
||||
class TestProductActionForm:
|
||||
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):
|
||||
baker.make(Refilling, amount=amount, customer=user.customer)
|
||||
baker.make(Refilling, amount=amount, customer=user.customer, is_validated=False)
|
||||
|
||||
|
||||
class TestFullClickBase(TestCase):
|
||||
@@ -115,10 +115,18 @@ class TestRefilling(TestFullClickBase):
|
||||
) -> HttpResponse:
|
||||
used_client = client if client is not None else self.client
|
||||
return used_client.post(
|
||||
reverse("counter:refilling_create", kwargs={"customer_id": user.pk}),
|
||||
{"amount": str(amount), "payment_method": Refilling.PaymentMethod.CASH},
|
||||
reverse(
|
||||
"counter:refilling_create",
|
||||
kwargs={"customer_id": user.pk},
|
||||
),
|
||||
{
|
||||
"amount": str(amount),
|
||||
"payment_method": "CASH",
|
||||
"bank": "OTHER",
|
||||
},
|
||||
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",
|
||||
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)
|
||||
|
||||
@@ -298,6 +298,7 @@ def test_update_balance():
|
||||
_quantity=len(customers),
|
||||
unit_price=10,
|
||||
quantity=1,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
_save_related=True,
|
||||
),
|
||||
*sale_recipe.prepare(
|
||||
@@ -305,12 +306,14 @@ def test_update_balance():
|
||||
_quantity=3,
|
||||
unit_price=5,
|
||||
quantity=2,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
_save_related=True,
|
||||
),
|
||||
sale_recipe.prepare(
|
||||
customer=customers[4],
|
||||
quantity=1,
|
||||
unit_price=50,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
_save_related=True,
|
||||
),
|
||||
*sale_recipe.prepare(
|
||||
@@ -321,7 +324,7 @@ def test_update_balance():
|
||||
_quantity=len(customers),
|
||||
unit_price=50,
|
||||
quantity=1,
|
||||
payment_method=Selling.PaymentMethod.CARD,
|
||||
payment_method="CARD",
|
||||
_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.test import Client
|
||||
from django.urls import reverse
|
||||
from django.utils.timezone import now
|
||||
from django.utils.timezone import localdate
|
||||
from model_bakery import baker
|
||||
from pytest_django.asserts import assertRedirects
|
||||
|
||||
@@ -57,7 +57,7 @@ def test_invoice_call_view(client: Client, query: dict | None):
|
||||
@pytest.mark.django_db
|
||||
def test_invoice_call_form():
|
||||
Selling.objects.all().delete()
|
||||
month = now() - relativedelta(months=1)
|
||||
month = localdate() - relativedelta(months=1)
|
||||
clubs = baker.make(Club, _quantity=2)
|
||||
recipe = sale_recipe.extend(date=month, customer=baker.make(Customer, amount=10000))
|
||||
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 core.baker_recipes import board_user, subscriber_user
|
||||
from core.models import Group, User
|
||||
from counter.baker_recipes import product_recipe
|
||||
from counter.forms import ProductForm
|
||||
from counter.models import Product, ProductFormula, ProductType
|
||||
from counter.models import Product, ProductType
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -94,9 +93,6 @@ class TestCreateProduct(TestCase):
|
||||
def setUpTestData(cls):
|
||||
cls.product_type = baker.make(ProductType)
|
||||
cls.club = baker.make(Club)
|
||||
cls.counter_admin = baker.make(
|
||||
User, groups=[Group.objects.get(id=settings.SITH_GROUP_COUNTER_ADMIN_ID)]
|
||||
)
|
||||
cls.data = {
|
||||
"name": "foo",
|
||||
"description": "bar",
|
||||
@@ -120,36 +116,13 @@ class TestCreateProduct(TestCase):
|
||||
assert instance.name == "foo"
|
||||
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):
|
||||
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")
|
||||
response = self.client.get(url)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -25,10 +25,6 @@ from counter.views.admin import (
|
||||
CounterStatView,
|
||||
ProductCreateView,
|
||||
ProductEditView,
|
||||
ProductFormulaCreateView,
|
||||
ProductFormulaDeleteView,
|
||||
ProductFormulaEditView,
|
||||
ProductFormulaListView,
|
||||
ProductListView,
|
||||
ProductTypeCreateView,
|
||||
ProductTypeEditView,
|
||||
@@ -120,24 +116,6 @@ urlpatterns = [
|
||||
ProductEditView.as_view(),
|
||||
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(
|
||||
"admin/product-type/list/",
|
||||
ProductTypeListView.as_view(),
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
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.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.timezone import get_current_timezone
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.generic import DetailView, ListView, TemplateView
|
||||
from django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView
|
||||
@@ -34,13 +33,11 @@ from counter.forms import (
|
||||
CloseCustomerAccountForm,
|
||||
CounterEditForm,
|
||||
ProductForm,
|
||||
ProductFormulaForm,
|
||||
ReturnableProductForm,
|
||||
)
|
||||
from counter.models import (
|
||||
Counter,
|
||||
Product,
|
||||
ProductFormula,
|
||||
ProductType,
|
||||
Refilling,
|
||||
ReturnableProduct,
|
||||
@@ -164,49 +161,6 @@ class ProductEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
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(
|
||||
CounterAdminTabsMixin, PermissionRequiredMixin, ListView
|
||||
):
|
||||
@@ -331,13 +285,7 @@ class CounterStatView(PermissionRequiredMixin, DetailView):
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add stats to the context."""
|
||||
counter: Counter = self.object
|
||||
start_date = get_start_of_semester()
|
||||
semester_start = datetime(
|
||||
start_date.year,
|
||||
start_date.month,
|
||||
start_date.day,
|
||||
tzinfo=get_current_timezone(),
|
||||
)
|
||||
semester_start = get_start_of_semester()
|
||||
office_hours = counter.get_top_barmen()
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs.update(
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from collections import defaultdict
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db import transaction
|
||||
@@ -32,7 +31,6 @@ from counter.forms import BasketForm, RefillForm
|
||||
from counter.models import (
|
||||
Counter,
|
||||
Customer,
|
||||
ProductFormula,
|
||||
ReturnableProduct,
|
||||
Selling,
|
||||
)
|
||||
@@ -208,13 +206,12 @@ class CounterClick(
|
||||
"""Add customer to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["products"] = self.products
|
||||
kwargs["formulas"] = ProductFormula.objects.filter(
|
||||
result__in=self.products
|
||||
).prefetch_related("products")
|
||||
kwargs["categories"] = defaultdict(list)
|
||||
kwargs["categories"] = {}
|
||||
for product in kwargs["products"]:
|
||||
if product.product_type:
|
||||
kwargs["categories"][product.product_type].append(product)
|
||||
kwargs["categories"].setdefault(product.product_type, []).append(
|
||||
product
|
||||
)
|
||||
kwargs["customer"] = self.customer
|
||||
kwargs["cancel_url"] = self.get_success_url()
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
@@ -63,18 +63,19 @@ class InvoiceCallView(
|
||||
"""Add sums to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["months"] = Selling.objects.datetimes("date", "month", order="DESC")
|
||||
month = self.get_month()
|
||||
start_date = datetime(month.year, month.month, month.day, tzinfo=timezone.utc)
|
||||
start_date = self.get_month()
|
||||
end_date = start_date + relativedelta(months=1)
|
||||
|
||||
kwargs["sum_cb"] = Refilling.objects.filter(
|
||||
payment_method=Refilling.PaymentMethod.CARD,
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
date__gte=start_date,
|
||||
date__lte=end_date,
|
||||
).aggregate(res=Sum("amount", default=0))["res"]
|
||||
kwargs["sum_cb"] += (
|
||||
Selling.objects.filter(
|
||||
payment_method=Selling.PaymentMethod.CARD,
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
date__gte=start_date,
|
||||
date__lte=end_date,
|
||||
)
|
||||
|
||||
@@ -100,11 +100,6 @@ class CounterAdminTabsMixin(TabedViewMixin):
|
||||
"slug": "products",
|
||||
"name": _("Products"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:product_formula_list"),
|
||||
"slug": "formulas",
|
||||
"name": _("Formulas"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:product_type_list"),
|
||||
"slug": "product_types",
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
- can_edit_prop
|
||||
- can_edit
|
||||
- can_view
|
||||
- CanCreateMixin
|
||||
- CanEditMixin
|
||||
- CanViewMixin
|
||||
- CanEditPropMixin
|
||||
|
||||
@@ -212,7 +212,7 @@ Pour les vues sous forme de fonction, il y a le décorateur
|
||||
obj = self.get_object()
|
||||
obj.is_moderated = True
|
||||
obj.save()
|
||||
return redirect("com:news_list")
|
||||
return redirect(reverse("com:news_list"))
|
||||
```
|
||||
|
||||
=== "Function-based view"
|
||||
@@ -233,7 +233,7 @@ Pour les vues sous forme de fonction, il y a le décorateur
|
||||
news = get_object_or_404(News, id=news_id)
|
||||
news.is_moderated = True
|
||||
news.save()
|
||||
return redirect("com:news_list")
|
||||
return redirect(reverse("com:news_list"))
|
||||
```
|
||||
|
||||
## Accès à des éléments en particulier
|
||||
@@ -447,9 +447,10 @@ l'utilisateur recevra une liste vide d'objet.
|
||||
Voici un exemple d'utilisation en reprenant l'objet Article crée précédemment :
|
||||
|
||||
```python
|
||||
from django.views.generic import DetailView
|
||||
from django.views.generic import CreateView, DetailView
|
||||
|
||||
from core.auth.mixins import CanViewMixin, CanCreateMixin
|
||||
|
||||
from core.auth.mixins import CanViewMixin
|
||||
from com.models import WeekmailArticle
|
||||
|
||||
|
||||
@@ -458,15 +459,48 @@ from com.models import WeekmailArticle
|
||||
# d'une classe de base pour fonctionner correctement.
|
||||
class ArticlesDetailView(CanViewMixin, DetailView):
|
||||
model = WeekmailArticle
|
||||
|
||||
|
||||
# Même chose pour une vue de création de l'objet Article
|
||||
class ArticlesCreateView(CanCreateMixin, CreateView):
|
||||
model = WeekmailArticle
|
||||
```
|
||||
|
||||
Les mixins suivants sont implémentés :
|
||||
|
||||
- [CanCreateMixin][core.auth.mixins.CanCreateMixin] : l'utilisateur peut-il créer l'objet ?
|
||||
Ce mixin existe, mais est déprécié et ne doit plus être utilisé !
|
||||
- [CanEditPropMixin][core.auth.mixins.CanEditPropMixin] : l'utilisateur peut-il éditer les propriétés de l'objet ?
|
||||
- [CanEditMixin][core.auth.mixins.CanEditMixin] : L'utilisateur peut-il éditer l'objet ?
|
||||
- [CanViewMixin][core.auth.mixins.CanViewMixin] : L'utilisateur peut-il voir l'objet ?
|
||||
- [FormerSubscriberMixin][core.auth.mixins.FormerSubscriberMixin] : L'utilisateur a-t-il déjà été cotisant ?
|
||||
|
||||
!!!danger "CanCreateMixin"
|
||||
|
||||
L'usage de `CanCreateMixin` est dangereux et ne doit en aucun cas être
|
||||
étendu.
|
||||
La façon dont ce mixin marche est qu'il valide le formulaire
|
||||
de création et crée l'objet sans le persister en base de données, puis
|
||||
vérifie les droits sur cet objet non-persisté.
|
||||
Le danger de ce système vient de multiples raisons :
|
||||
|
||||
- Les vérifications se faisant sur un objet non persisté,
|
||||
l'utilisation de mécanismes nécessitant une persistance préalable
|
||||
peut mener à des comportements indésirés, voire à des erreurs.
|
||||
- Les développeurs de django ayant tendance à restreindre progressivement
|
||||
les actions qui peuvent être faites sur des objets non-persistés,
|
||||
les mises-à-jour de django deviennent plus compliquées.
|
||||
- La vérification des droits ne se fait que dans les requêtes POST,
|
||||
à la toute fin de la requête.
|
||||
Tout ce qui arrive avant n'est absolument pas protégé.
|
||||
Toute opération (même les suppressions et les créations) qui ont
|
||||
lieu avant la persistance de l'objet seront appliquées,
|
||||
même sans permission.
|
||||
- Si un développeur du site fait l'erreur de surcharger
|
||||
la méthode `form_valid` (ce qui est plutôt courant,
|
||||
lorsqu'on veut accomplir certaines actions
|
||||
quand un formulaire est valide), on peut se retrouver
|
||||
dans une situation où l'objet est persisté sans aucune protection.
|
||||
|
||||
!!!danger "Performance"
|
||||
|
||||
|
||||
@@ -110,9 +110,7 @@ class Basket(models.Model):
|
||||
)["total"]
|
||||
)
|
||||
|
||||
def generate_sales(
|
||||
self, counter, seller: User, payment_method: Selling.PaymentMethod
|
||||
):
|
||||
def generate_sales(self, counter, seller: User, payment_method: str):
|
||||
"""Generate a list of sold items corresponding to the items
|
||||
of this basket WITHOUT saving them NOR deleting the basket.
|
||||
|
||||
@@ -253,7 +251,8 @@ class Invoice(models.Model):
|
||||
customer=customer,
|
||||
operator=self.user,
|
||||
amount=i.product_unit_price * i.quantity,
|
||||
payment_method=Refilling.PaymentMethod.CARD,
|
||||
payment_method="CARD",
|
||||
bank="OTHER",
|
||||
date=self.date,
|
||||
)
|
||||
new.save()
|
||||
@@ -268,7 +267,8 @@ class Invoice(models.Model):
|
||||
customer=customer,
|
||||
unit_price=i.product_unit_price,
|
||||
quantity=i.quantity,
|
||||
payment_method=Selling.PaymentMethod.CARD,
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
date=self.date,
|
||||
)
|
||||
new.save()
|
||||
|
||||
@@ -108,22 +108,12 @@ def test_eboutic_basket_expiry(
|
||||
|
||||
client.force_login(customer.user)
|
||||
|
||||
if sellings:
|
||||
for date in sellings:
|
||||
sale_recipe.make(
|
||||
customer=customer,
|
||||
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,
|
||||
customer=customer, counter=eboutic, date=date, is_validated=True
|
||||
)
|
||||
for date in refillings:
|
||||
refill_recipe.make(customer=customer, counter=eboutic, date=date)
|
||||
|
||||
assert (
|
||||
f'x-data="basket({int(expected.timestamp() * 1000) if expected else "null"})"'
|
||||
|
||||
@@ -114,13 +114,13 @@ class TestPaymentSith(TestPaymentBase):
|
||||
"quantity"
|
||||
)
|
||||
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].unit_price == self.snack.selling_price
|
||||
assert sellings[0].counter.type == "EBOUTIC"
|
||||
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].unit_price == self.beer.selling_price
|
||||
assert sellings[1].counter.type == "EBOUTIC"
|
||||
@@ -198,13 +198,13 @@ class TestPaymentCard(TestPaymentBase):
|
||||
"quantity"
|
||||
)
|
||||
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].unit_price == self.snack.selling_price
|
||||
assert sellings[0].counter.type == "EBOUTIC"
|
||||
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].unit_price == self.beer.selling_price
|
||||
assert sellings[1].counter.type == "EBOUTIC"
|
||||
|
||||
@@ -275,9 +275,7 @@ class EbouticPayWithSith(CanViewMixin, SingleObjectMixin, View):
|
||||
return redirect("eboutic:payment_result", "failure")
|
||||
|
||||
eboutic = get_eboutic()
|
||||
sales = basket.generate_sales(
|
||||
eboutic, basket.user, Selling.PaymentMethod.SITH_ACCOUNT
|
||||
)
|
||||
sales = basket.generate_sales(eboutic, basket.user, "SITH_ACCOUNT")
|
||||
try:
|
||||
with transaction.atomic():
|
||||
# Selling.save has some important business logic in it.
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<label for="{{ input_id }}">
|
||||
{%- endif %}
|
||||
<figure>
|
||||
{%- if user.is_viewable %}
|
||||
{%- if user.is_subscriber_viewable %}
|
||||
{% if candidature.user.profile_pict %}
|
||||
<img class="candidate__picture" src="{{ candidature.user.profile_pict.get_download_url() }}" alt="{% trans %}Profile{% endtrans %}">
|
||||
{% else %}
|
||||
|
||||
@@ -27,14 +27,14 @@ from functools import partial
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
|
||||
from django.db import IntegrityError
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils import html, timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.functional import cached_property
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import DetailView, ListView, RedirectView
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
@@ -44,6 +44,7 @@ from honeypot.decorators import check_honeypot
|
||||
|
||||
from club.widgets.ajax_select import AutoCompleteSelectClub
|
||||
from core.auth.mixins import (
|
||||
CanCreateMixin,
|
||||
CanEditMixin,
|
||||
CanEditPropMixin,
|
||||
CanViewMixin,
|
||||
@@ -179,19 +180,11 @@ class ForumForm(forms.ModelForm):
|
||||
)
|
||||
|
||||
|
||||
class ForumCreateView(UserPassesTestMixin, CreateView):
|
||||
class ForumCreateView(CanCreateMixin, CreateView):
|
||||
model = Forum
|
||||
form_class = ForumForm
|
||||
template_name = "core/create.jinja"
|
||||
|
||||
def test_func(self):
|
||||
if self.request.user.has_perm("forum.add_forum"):
|
||||
return True
|
||||
parent = Forum.objects.filter(id=self.request.GET["parent"]).first()
|
||||
if parent is not None:
|
||||
return self.request.user.is_owner(parent)
|
||||
return False
|
||||
|
||||
def get_initial(self):
|
||||
init = super().get_initial()
|
||||
parent = Forum.objects.filter(id=self.request.GET["parent"]).first()
|
||||
@@ -265,19 +258,18 @@ class TopicForm(forms.ModelForm):
|
||||
@method_decorator(
|
||||
partial(check_honeypot, field_name=settings.HONEYPOT_FIELD_NAME_FORUM), name="post"
|
||||
)
|
||||
class ForumTopicCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView):
|
||||
class ForumTopicCreateView(CanCreateMixin, CreateView):
|
||||
model = ForumMessage
|
||||
form_class = TopicForm
|
||||
template_name = "forum/reply.jinja"
|
||||
|
||||
@cached_property
|
||||
def forum(self):
|
||||
return get_object_or_404(Forum, id=self.kwargs["forum_id"], is_category=False)
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.has_perm("forum.add_forumtopic") or (
|
||||
self.request.user.can_view(self.forum)
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.forum = get_object_or_404(
|
||||
Forum, id=self.kwargs["forum_id"], is_category=False
|
||||
)
|
||||
if not request.user.can_view(self.forum):
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
topic = ForumTopic(
|
||||
@@ -412,7 +404,7 @@ class ForumMessageUndeleteView(SingleObjectMixin, RedirectView):
|
||||
@method_decorator(
|
||||
partial(check_honeypot, field_name=settings.HONEYPOT_FIELD_NAME_FORUM), name="post"
|
||||
)
|
||||
class ForumMessageCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView):
|
||||
class ForumMessageCreateView(CanCreateMixin, CreateView):
|
||||
model = ForumMessage
|
||||
form_class = forms.modelform_factory(
|
||||
model=ForumMessage,
|
||||
@@ -421,14 +413,11 @@ class ForumMessageCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView
|
||||
)
|
||||
template_name = "forum/reply.jinja"
|
||||
|
||||
@cached_property
|
||||
def topic(self):
|
||||
return get_object_or_404(ForumTopic, id=self.kwargs["topic_id"])
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.has_perm(
|
||||
"forum.add_forummessage"
|
||||
) or self.request.user.can_view(self.topic)
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.topic = get_object_or_404(ForumTopic, id=self.kwargs["topic_id"])
|
||||
if not request.user.can_view(self.topic):
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_initial(self):
|
||||
init = super().get_initial()
|
||||
|
||||
@@ -199,7 +199,7 @@ class Galaxy(models.Model):
|
||||
cls, picture_count_threshold: int = DEFAULT_PICTURE_COUNT_THRESHOLD
|
||||
) -> QuerySet[User]:
|
||||
return (
|
||||
User.objects.filter(is_viewable=True)
|
||||
User.objects.filter(is_subscriber_viewable=True)
|
||||
.exclude(subscriptions=None)
|
||||
.annotate(
|
||||
pictures_count=Count("pictures"),
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"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"
|
||||
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||
@@ -247,7 +247,8 @@ msgstr "description"
|
||||
msgid "past member"
|
||||
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
|
||||
#: core/templates/core/user_clubs.jinja
|
||||
#: counter/templates/counter/invoices_call.jinja
|
||||
@@ -388,7 +389,7 @@ msgstr "Montrer"
|
||||
|
||||
#: club/templates/club/club_sellings.jinja
|
||||
#: counter/templates/counter/product_list.jinja
|
||||
msgid "Download as csv"
|
||||
msgid "Download as cvs"
|
||||
msgstr "Télécharger en CSV"
|
||||
|
||||
#: 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_moderation.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_clubs.jinja core/templates/core/user_edit.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 "
|
||||
"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
|
||||
#: com/templates/com/news_edit.jinja com/templates/com/poster_edit.jinja
|
||||
#: com/templates/com/screen_edit.jinja com/templates/com/weekmail.jinja
|
||||
#: core/templates/core/create.jinja core/templates/core/edit.jinja
|
||||
#: core/templates/core/file_edit.jinja core/templates/core/page/edit.jinja
|
||||
#: core/templates/core/page/prop.jinja
|
||||
#: club/templates/club/edit_club.jinja com/templates/com/news_edit.jinja
|
||||
#: com/templates/com/poster_edit.jinja com/templates/com/screen_edit.jinja
|
||||
#: com/templates/com/weekmail.jinja core/templates/core/create.jinja
|
||||
#: core/templates/core/edit.jinja core/templates/core/file_edit.jinja
|
||||
#: core/templates/core/macros_pages.jinja core/templates/core/page_prop.jinja
|
||||
#: core/templates/core/user_godfathers.jinja
|
||||
#: core/templates/core/user_godfathers_tree.jinja
|
||||
#: core/templates/core/user_preferences.jinja
|
||||
@@ -638,9 +638,9 @@ msgstr "Nouvelle liste de diffusion"
|
||||
msgid "Create mailing list"
|
||||
msgstr "Créer une liste de diffusion"
|
||||
|
||||
#: club/templates/club/pagerev_edit.jinja core/templates/core/page/edit.jinja
|
||||
msgid "Edit page"
|
||||
msgstr "Éditer la page"
|
||||
#: club/templates/club/page_history.jinja
|
||||
msgid "No page existing for this club"
|
||||
msgstr "Aucune page n'existe pour ce club"
|
||||
|
||||
#: club/views.py core/views/user.py sas/templates/sas/picture.jinja
|
||||
msgid "Infos"
|
||||
@@ -654,7 +654,7 @@ msgstr "Membres"
|
||||
msgid "Old members"
|
||||
msgstr "Anciens membres"
|
||||
|
||||
#: club/views.py core/templates/core/page/base.jinja
|
||||
#: club/views.py core/templates/core/page.jinja
|
||||
msgid "History"
|
||||
msgstr "Historique"
|
||||
|
||||
@@ -666,7 +666,7 @@ msgstr "Outils"
|
||||
#: club/views.py com/templates/com/news_admin_list.jinja
|
||||
#: com/templates/com/poster_list.jinja com/templates/com/screen_list.jinja
|
||||
#: com/templates/com/weekmail.jinja core/templates/core/file.jinja
|
||||
#: core/templates/core/group_list.jinja core/templates/core/page/base.jinja
|
||||
#: core/templates/core/group_list.jinja core/templates/core/page.jinja
|
||||
#: core/templates/core/user_tools.jinja core/views/user.py
|
||||
#: counter/templates/counter/cash_summary_list.jinja
|
||||
#: counter/templates/counter/counter_list.jinja
|
||||
@@ -704,8 +704,8 @@ msgid "Benefit"
|
||||
msgstr "Bénéfice"
|
||||
|
||||
#: club/views.py
|
||||
msgid "Unit price"
|
||||
msgstr "Prix unitaire"
|
||||
msgid "Selling price"
|
||||
msgstr "Prix de vente"
|
||||
|
||||
#: club/views.py
|
||||
msgid "Purchase price"
|
||||
@@ -980,7 +980,7 @@ msgid "Dates"
|
||||
msgstr "Dates"
|
||||
|
||||
#: 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"
|
||||
msgstr "Voir"
|
||||
|
||||
@@ -1017,10 +1017,6 @@ msgstr "Événements à modérer"
|
||||
msgid "Back to news"
|
||||
msgstr "Retour aux nouvelles"
|
||||
|
||||
#: com/templates/com/news_detail.jinja
|
||||
msgid "Share on Facebook"
|
||||
msgstr "Partager sur Facebook"
|
||||
|
||||
#: com/templates/com/news_detail.jinja
|
||||
msgid "Author: "
|
||||
msgstr "Auteur : "
|
||||
@@ -1536,15 +1532,8 @@ msgid "parent address"
|
||||
msgstr "adresse des parents"
|
||||
|
||||
#: core/models.py
|
||||
msgid "Profile visible by subscribers"
|
||||
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."
|
||||
msgid "is subscriber viewable"
|
||||
msgstr "profil visible par les cotisants"
|
||||
|
||||
#: core/models.py
|
||||
msgid "A user with that username already exists"
|
||||
@@ -1960,7 +1949,7 @@ msgstr "Liste de fichiers"
|
||||
msgid "New file"
|
||||
msgstr "Nouveau fichier"
|
||||
|
||||
#: core/templates/core/file.jinja
|
||||
#: core/templates/core/file.jinja core/templates/core/page.jinja
|
||||
msgid "Not found"
|
||||
msgstr "Non trouvé"
|
||||
|
||||
@@ -1968,7 +1957,7 @@ msgstr "Non trouvé"
|
||||
msgid "My files"
|
||||
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"
|
||||
msgstr "Propriétés"
|
||||
|
||||
@@ -2106,6 +2095,14 @@ msgstr "Mot de passe perdu ?"
|
||||
msgid "Create account"
|
||||
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
|
||||
#, python-format
|
||||
msgid "Subscribed until %(subscription_end)s"
|
||||
@@ -2127,6 +2124,19 @@ msgstr "Tout sélectionner"
|
||||
msgid "Unselect All"
|
||||
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
|
||||
msgid ""
|
||||
"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"
|
||||
msgstr "Liste des notifications"
|
||||
|
||||
#: core/templates/core/page/base.jinja
|
||||
msgid "Page"
|
||||
msgstr "Page"
|
||||
#: core/templates/core/page.jinja core/templates/core/page_list.jinja
|
||||
msgid "Page list"
|
||||
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"
|
||||
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
|
||||
msgid "This may not be the last update, you are seeing revision %(rev_id)s!"
|
||||
msgstr ""
|
||||
"Ceci n'est peut-être pas la dernière version de la page. Vous consultez la "
|
||||
"version %(rev_id)s."
|
||||
|
||||
#: core/templates/core/page/history.jinja
|
||||
#: core/templates/core/page_hist.jinja
|
||||
msgid "Page history"
|
||||
msgstr "Historique de la page"
|
||||
|
||||
#: core/templates/core/page/list.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
|
||||
#: core/templates/core/page_prop.jinja
|
||||
msgid "Page properties"
|
||||
msgstr "Propriétés de la page"
|
||||
|
||||
@@ -2658,8 +2659,8 @@ msgid "Buyings"
|
||||
msgstr "Achats"
|
||||
|
||||
#: core/templates/core/user_stats.jinja
|
||||
msgid "Product top 15"
|
||||
msgstr "Top 15 produits"
|
||||
msgid "Product top 10"
|
||||
msgstr "Top 10 produits"
|
||||
|
||||
#: core/templates/core/user_stats.jinja
|
||||
msgid "Product"
|
||||
@@ -2819,8 +2820,8 @@ msgstr "Outils Trombi"
|
||||
#, python-format
|
||||
msgid "%(nb_days)d day, %(remainder)s"
|
||||
msgid_plural "%(nb_days)d days, %(remainder)s"
|
||||
msgstr[0] "%(nb_days)d jour, %(remainder)s"
|
||||
msgstr[1] "%(nb_days)d jours, %(remainder)s"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: core/views/files.py
|
||||
msgid "Add a new folder"
|
||||
@@ -2840,6 +2841,10 @@ msgstr "Erreur d'envoi du fichier %(file_name)s : %(msg)s"
|
||||
msgid "Apply rights recursively"
|
||||
msgstr "Appliquer les droits récursivement"
|
||||
|
||||
#: core/views/forms.py
|
||||
msgid "Choose user"
|
||||
msgstr "Choisir un utilisateur"
|
||||
|
||||
#: core/views/forms.py
|
||||
msgid "Ensure this timestamp is set in the future"
|
||||
msgstr "Assurez-vous que cet horodatage est dans le futur"
|
||||
@@ -2928,6 +2933,18 @@ msgstr "Photos"
|
||||
msgid "Account"
|
||||
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
|
||||
msgid "counter"
|
||||
msgstr "comptoir"
|
||||
@@ -2960,38 +2977,6 @@ msgstr ""
|
||||
"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)."
|
||||
|
||||
#: 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
|
||||
msgid "Refound this account"
|
||||
msgstr "Rembourser ce compte"
|
||||
@@ -3152,18 +3137,6 @@ msgstr "produit"
|
||||
msgid "products"
|
||||
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
|
||||
msgid "counter type"
|
||||
msgstr "type de comptoir"
|
||||
@@ -3184,29 +3157,21 @@ msgstr "vendeurs"
|
||||
msgid "token"
|
||||
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
|
||||
msgid "payment method"
|
||||
msgstr "méthode de paiement"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "refilling"
|
||||
msgstr "rechargement"
|
||||
msgid "bank"
|
||||
msgstr "banque"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "Sith account"
|
||||
msgstr "Compte utilisateur"
|
||||
msgid "is validated"
|
||||
msgstr "est validé"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "refilling"
|
||||
msgstr "rechargement"
|
||||
|
||||
#: counter/models.py eboutic/models.py
|
||||
msgid "unit price"
|
||||
@@ -3216,6 +3181,10 @@ msgstr "prix unitaire"
|
||||
msgid "quantity"
|
||||
msgstr "quantité"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "Sith account"
|
||||
msgstr "Compte utilisateur"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "selling"
|
||||
msgstr "vente"
|
||||
@@ -3368,10 +3337,6 @@ msgid ""
|
||||
"“%(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."
|
||||
|
||||
#: counter/models.py
|
||||
msgid "is validated"
|
||||
msgstr "est validé"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "invoice date"
|
||||
msgstr "date de la facture"
|
||||
@@ -3584,14 +3549,6 @@ msgstr "Nouveau eticket"
|
||||
msgid "There is no eticket in this website."
|
||||
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
|
||||
msgid "No student card registered."
|
||||
msgstr "Aucune carte étudiante enregistrée."
|
||||
@@ -3931,10 +3888,6 @@ msgstr "Dernières opérations"
|
||||
msgid "Counter administration"
|
||||
msgstr "Administration des comptoirs"
|
||||
|
||||
#: counter/views/mixins.py
|
||||
msgid "Formulas"
|
||||
msgstr "Formules"
|
||||
|
||||
#: counter/views/mixins.py
|
||||
msgid "Product types"
|
||||
msgstr "Types de produit"
|
||||
@@ -5159,6 +5112,14 @@ msgstr "Membre de Sbarro ou de l'ESTA"
|
||||
msgid "One semester 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
|
||||
msgid "Eurok's volunteer"
|
||||
msgstr "Bénévole Eurockéennes"
|
||||
@@ -5172,10 +5133,8 @@ msgid "One day"
|
||||
msgstr "Un jour"
|
||||
|
||||
#: sith/settings.py
|
||||
#, fuzzy
|
||||
#| msgid "GA staff member"
|
||||
msgid "GA staff member"
|
||||
msgstr "Membre staff GA"
|
||||
msgid "GA staff member (2 weeks)"
|
||||
msgstr "Membre staff GA (2 semaines)"
|
||||
|
||||
#: sith/settings.py
|
||||
msgid "One semester (-20%)"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"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"
|
||||
"Last-Translator: Sli <antoine@bartuccio.fr>\n"
|
||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||
@@ -206,10 +206,6 @@ msgstr "capture.%s"
|
||||
msgid "Not enough money"
|
||||
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
|
||||
msgid "You can't send an empty basket."
|
||||
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
|
||||
msgid "Couldn't delete picture"
|
||||
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 django import forms
|
||||
from django.db.models import F
|
||||
from django.http.response import HttpResponseRedirect
|
||||
from django.urls import reverse
|
||||
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.models import User
|
||||
from core.schemas import UserFilterSchema
|
||||
from core.views import search_user
|
||||
from core.views.forms import SelectDate
|
||||
|
||||
# Enum to select search type
|
||||
@@ -106,7 +105,7 @@ class SearchFormListView(FormerSubscriberMixin, SingleObjectMixin, ListView):
|
||||
self.can_see_hidden = True
|
||||
if not (request.user.is_board_member or request.user.is_root):
|
||||
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)
|
||||
|
||||
@@ -127,13 +126,11 @@ class SearchFormListView(FormerSubscriberMixin, SingleObjectMixin, ListView):
|
||||
q = q.filter(phone=self.valid_form["phone"]).all()
|
||||
elif self.search_type == SearchType.QUICK:
|
||||
if self.valid_form["quick"].strip():
|
||||
q = list(
|
||||
UserFilterSchema(search=self.valid_form["quick"])
|
||||
.filter(User.objects.viewable_by(self.request.user))
|
||||
.order_by(F("last_login").desc(nulls_last=True))
|
||||
)
|
||||
q = search_user(self.valid_form["quick"])
|
||||
else:
|
||||
q = []
|
||||
if not self.can_see_hidden and len(q) > 0:
|
||||
q = [user for user in q if user.is_subscriber_viewable]
|
||||
else:
|
||||
search_dict = {}
|
||||
for key, value in self.valid_form.items():
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from typing import Annotated, Literal
|
||||
from typing import Literal
|
||||
|
||||
from django.db.models import Q
|
||||
from django.utils import html
|
||||
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.alias_generators import to_camel
|
||||
|
||||
@@ -114,14 +114,13 @@ class UvSchema(ModelSchema):
|
||||
|
||||
|
||||
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
|
||||
credit_type: Annotated[
|
||||
set[Literal["CS", "TM", "EC", "OM", "QC"]] | None,
|
||||
FilterLookup("credit_type__in"),
|
||||
] = None
|
||||
credit_type: set[Literal["CS", "TM", "EC", "OM", "QC"]] | None = Field(
|
||||
None, q="credit_type__in"
|
||||
)
|
||||
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:
|
||||
"""Special filter for the search text.
|
||||
|
||||
@@ -20,8 +20,8 @@ license = { text = "GPL-3.0-only" }
|
||||
requires-python = "<4.0,>=3.12"
|
||||
dependencies = [
|
||||
"django>=5.2.8,<6.0.0",
|
||||
"django-ninja>=1.5.0,<6.0.0",
|
||||
"django-ninja-extra>=0.30.6",
|
||||
"django-ninja>=1.4.5,<2.0.0",
|
||||
"django-ninja-extra>=0.30.2,<1.0.0",
|
||||
"Pillow>=12.0.0,<13.0.0",
|
||||
"mistune>=3.1.4,<4.0.0",
|
||||
"django-jinja<3.0.0,>=2.11.0",
|
||||
@@ -73,7 +73,7 @@ dev = [
|
||||
]
|
||||
tests = [
|
||||
"freezegun>=1.5.5,<2.0.0",
|
||||
"pytest>=8.4.2,<9.0.0",
|
||||
"pytest>=8.4.2,<10.0.0",
|
||||
"pytest-cov>=7.0.0,<8.0.0",
|
||||
"pytest-django<5.0.0,>=4.10.0",
|
||||
"model-bakery<2.0.0,>=1.20.4",
|
||||
|
||||
@@ -114,6 +114,7 @@ class TestMergeUser(TestCase):
|
||||
seller=self.root,
|
||||
unit_price=2,
|
||||
quantity=2,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
).save()
|
||||
Selling(
|
||||
label="barbar",
|
||||
@@ -124,6 +125,7 @@ class TestMergeUser(TestCase):
|
||||
seller=self.root,
|
||||
unit_price=2,
|
||||
quantity=4,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
).save()
|
||||
today = localtime(now()).date()
|
||||
# both subscriptions began last month and shall end in 5 months
|
||||
@@ -195,6 +197,7 @@ class TestMergeUser(TestCase):
|
||||
seller=self.root,
|
||||
unit_price=2,
|
||||
quantity=4,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
).save()
|
||||
data = {"user1": self.to_keep.id, "user2": self.to_delete.id}
|
||||
res = self.client.post(reverse("rootplace:merge"), data)
|
||||
@@ -222,6 +225,7 @@ class TestMergeUser(TestCase):
|
||||
seller=self.root,
|
||||
unit_price=2,
|
||||
quantity=4,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
).save()
|
||||
data = {"user1": self.to_keep.id, "user2": self.to_delete.id}
|
||||
res = self.client.post(reverse("rootplace:merge"), data)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user