mirror of
https://github.com/ae-utbm/sith.git
synced 2025-12-13 19:01:20 +00:00
Compare commits
28 Commits
room-reser
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af11cbdc96 | ||
|
|
d3edcaff14 | ||
|
|
8c127a96f7 | ||
|
|
55d6e2bbec | ||
|
|
e9fbac8264 | ||
|
|
1911f2e6dd | ||
|
|
77bdc8dcb5 | ||
|
|
00acdcd1a5 | ||
|
|
aa77cfd1c8 | ||
|
|
0d4b77ba1c | ||
|
|
5271783e88 | ||
|
|
4ff4d179a1 | ||
|
|
7cbb3a2c5d | ||
|
|
a0768d6d7f | ||
|
|
f55627a292 | ||
|
|
4f802ac56e | ||
|
|
16a6e07d4b | ||
|
|
33d6300131 | ||
|
|
6709befb1f | ||
|
|
ddfb88ca2a | ||
|
|
acdb9660f6 | ||
|
|
b60bd3a42b | ||
|
|
0c046b6164 | ||
|
|
c588e5117d | ||
|
|
ad87617018 | ||
|
|
56c2c2b70e | ||
|
|
78fe4e52ca | ||
|
|
2a5893aa79 |
@@ -1,18 +1,16 @@
|
||||
from typing import Annotated
|
||||
|
||||
from annotated_types import MinLen
|
||||
from django.db.models import Q
|
||||
from ninja import Field, FilterSchema, ModelSchema
|
||||
from ninja import FilterLookup, FilterSchema, ModelSchema
|
||||
|
||||
from club.models import Club, Membership
|
||||
from core.schemas import SimpleUserSchema
|
||||
from core.schemas import NonEmptyStr, SimpleUserSchema
|
||||
|
||||
|
||||
class ClubSearchFilterSchema(FilterSchema):
|
||||
search: Annotated[str, MinLen(1)] | None = Field(None, q="name__icontains")
|
||||
search: Annotated[NonEmptyStr | None, FilterLookup("name__icontains")] = None
|
||||
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):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated
|
||||
|
||||
from ninja import FilterSchema, ModelSchema
|
||||
from ninja import FilterLookup, 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: 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")
|
||||
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
|
||||
news_id: int | None = None
|
||||
is_published: bool | None = Field(None, q="news__is_published")
|
||||
title: str | None = Field(None, q="news__title__icontains")
|
||||
is_published: Annotated[bool | None, FilterLookup("news__is_published")] = None
|
||||
title: Annotated[str | None, FilterLookup("news__title__icontains")] = None
|
||||
|
||||
|
||||
class NewsSchema(ModelSchema):
|
||||
|
||||
@@ -350,7 +350,6 @@ class Command(BaseCommand):
|
||||
date=make_aware(
|
||||
self.faker.date_time_between(customer.since, localdate())
|
||||
),
|
||||
is_validated=True,
|
||||
)
|
||||
)
|
||||
sales.extend(this_customer_sales)
|
||||
|
||||
@@ -38,7 +38,6 @@ 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
|
||||
@@ -77,16 +76,6 @@ 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()
|
||||
|
||||
@@ -15,6 +15,8 @@ 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
|
||||
|
||||
@@ -195,8 +195,9 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.delete {
|
||||
form .link-like {
|
||||
margin-top: 10px;
|
||||
display: block;
|
||||
text-align: center;
|
||||
@@ -209,7 +210,6 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
>a.mini_profile_link {
|
||||
display: none;
|
||||
|
||||
@@ -78,12 +78,6 @@
|
||||
{% endif %}
|
||||
{% endmacro %}
|
||||
|
||||
{% macro delete_godfather(user, profile, godfather, is_father) %}
|
||||
{% if user == profile or user.is_root or user.is_board_member %}
|
||||
<a class="delete" href="{{ url("core:user_godfathers_delete", user_id=profile.id, godfather_id=godfather.id, is_father=is_father) }}">{% trans %}Delete{% endtrans %}</a>
|
||||
{% endif %}
|
||||
{% endmacro %}
|
||||
|
||||
{% macro paginate_alpine(page, nb_pages) %}
|
||||
{# Add pagination buttons for ajax based content with alpine
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
{% block content %}
|
||||
|
||||
{% if target %}
|
||||
<p>{% trans user=target.get_display_name() %}Change password for {{ user }}{% endtrans %}</p>
|
||||
<p>{% trans user=form.user.get_display_name() %}Change password for {{ user }}{% endtrans %}</p>
|
||||
{% endif %}
|
||||
<form method="post" action="">
|
||||
{% csrf_token %}
|
||||
|
||||
@@ -9,19 +9,17 @@
|
||||
{% block content %}
|
||||
<h4>{% trans %}Users{% endtrans %}</h4>
|
||||
<ul>
|
||||
{% for i in result.users %}
|
||||
{% if user.can_view(i) %}
|
||||
{% for user in users %}
|
||||
<li>
|
||||
{{ user_link_with_pict(i) }}
|
||||
{{ user_link_with_pict(user) }}
|
||||
</li>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<h4>{% trans %}Clubs{% endtrans %}</h4>
|
||||
<ul>
|
||||
{% for i in result.clubs %}
|
||||
{% for club in clubs %}
|
||||
<li>
|
||||
<a href="{{ url("club:club_view", club_id=i.id) }}">{{ i }}</a>
|
||||
<a href="{{ url("club:club_view", club_id=club.id) }}">{{ club }}</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
@@ -29,7 +29,16 @@
|
||||
<a href="{{ url('core:user_godfathers', user_id=u.id) }}" class="mini_profile_link">
|
||||
{{ u.get_mini_item() | safe }}
|
||||
</a>
|
||||
{{ delete_godfather(user, profile, u, True) }}
|
||||
{% if user == profile or user.is_root or user.is_board_member %}
|
||||
<form
|
||||
method="post"
|
||||
class="no-margin"
|
||||
action="{{ url("core:user_godfathers_delete", user_id=profile.id, godfather_id=u.id, is_father=True) }}"
|
||||
>
|
||||
{% csrf_token %}
|
||||
<input type="submit" class="link-like" value="{% trans %}Delete{% endtrans %}">
|
||||
</form>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
@@ -46,7 +55,16 @@
|
||||
<a href="{{ url('core:user_godfathers', user_id=u.id) }}" class="mini_profile_link">
|
||||
{{ u.get_mini_item()|safe }}
|
||||
</a>
|
||||
{{ delete_godfather(user, profile, u, False) }}
|
||||
{% if user == profile or user.is_root or user.is_board_member %}
|
||||
<form
|
||||
method="post"
|
||||
class="no-margin"
|
||||
action="{{ url("core:user_godfathers_delete", user_id=profile.id, godfather_id=u.id, is_father=False) }}"
|
||||
>
|
||||
{% csrf_token %}
|
||||
<input type="submit" class="link-like link-red" value="{% trans %}Delete{% endtrans %}">
|
||||
</form>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
@@ -11,32 +11,35 @@
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
{% if profile.permanencies %}
|
||||
{% if total_perm_time %}
|
||||
<div>
|
||||
<h3>{% trans %}Permanencies{% endtrans %}</h3>
|
||||
<div class="flexed">
|
||||
<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>
|
||||
{% 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>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div>
|
||||
<h3>{% trans %}Buyings{% endtrans %}</h3>
|
||||
<div class="flexed">
|
||||
<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>
|
||||
|
||||
{% for sum in purchase_sums %}
|
||||
<div>
|
||||
<h3>{% trans %}Product top 10{% endtrans %}</h3>
|
||||
<span>{{ sum["counter__name"] }}</span>
|
||||
<span>{{ sum["total"] }} €</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div><b>Total : </b><b>{{ total_purchases }} €</b></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{% trans %}Product top 15{% endtrans %}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
@@ -55,31 +55,17 @@ 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)}
|
||||
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ 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
|
||||
@@ -551,3 +552,10 @@ 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
|
||||
|
||||
64
core/tests/test_notification.py
Normal file
64
core/tests/test_notification.py
Normal file
@@ -0,0 +1,64 @@
|
||||
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,3 +1,4 @@
|
||||
import itertools
|
||||
from datetime import timedelta
|
||||
from unittest import mock
|
||||
|
||||
@@ -23,7 +24,7 @@ from core.baker_recipes import (
|
||||
from core.models import AnonymousUser, Group, User
|
||||
from core.views import UserTabsMixin
|
||||
from counter.baker_recipes import sale_recipe
|
||||
from counter.models import Counter, Customer, Refilling, Selling
|
||||
from counter.models import Counter, Customer, Permanency, Refilling, Selling
|
||||
from counter.utils import is_logged_in_counter
|
||||
from eboutic.models import Invoice, InvoiceItem
|
||||
|
||||
@@ -187,11 +188,7 @@ 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,
|
||||
is_validated=True,
|
||||
Selling, counter=counter, club=counter.club, seller=seller, unit_price=0
|
||||
)
|
||||
|
||||
cls.users = [
|
||||
@@ -428,3 +425,106 @@ class TestUserQuerySetViewableBy:
|
||||
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_preferences(client: Client):
|
||||
user = subscriber_user.make()
|
||||
client.force_login(user)
|
||||
url = reverse("core:user_prefs", kwargs={"user_id": user.id})
|
||||
response = client.get(url)
|
||||
assert response.status_code == 200
|
||||
response = client.post(url, {"notify_on_click": "true"})
|
||||
assertRedirects(response, url)
|
||||
user.preferences.refresh_from_db()
|
||||
assert user.preferences.notify_on_click is True
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestChangeUserPassword:
|
||||
def test_as_root(self, client: Client, admin_user: User):
|
||||
client.force_login(admin_user)
|
||||
user = subscriber_user.make()
|
||||
url = reverse("core:password_root_change", kwargs={"user_id": user.id})
|
||||
response = client.get(url)
|
||||
assert response.status_code == 200
|
||||
response = client.post(
|
||||
url, {"new_password1": "poutou", "new_password2": "poutou"}
|
||||
)
|
||||
assertRedirects(response, reverse("core:password_change_done"))
|
||||
user.refresh_from_db()
|
||||
assert user.check_password("poutou") is True
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUserGodfather:
|
||||
@pytest.mark.parametrize("godfather", [True, False])
|
||||
def test_add_family(self, client: Client, godfather):
|
||||
user = subscriber_user.make()
|
||||
other_user = subscriber_user.make()
|
||||
client.force_login(user)
|
||||
url = reverse("core:user_godfathers", kwargs={"user_id": user.id})
|
||||
response = client.get(url)
|
||||
assert response.status_code == 200
|
||||
response = client.post(
|
||||
url,
|
||||
{"type": "godfather" if godfather else "godchild", "user": other_user.id},
|
||||
)
|
||||
assertRedirects(response, url)
|
||||
if godfather:
|
||||
assert user.godfathers.contains(other_user)
|
||||
else:
|
||||
assert user.godchildren.contains(other_user)
|
||||
|
||||
def test_tree(self, client: Client):
|
||||
user = subscriber_user.make()
|
||||
client.force_login(user)
|
||||
response = client.get(
|
||||
reverse("core:user_godfathers_tree", kwargs={"user_id": user.id})
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_remove_family(self, client: Client):
|
||||
user = subscriber_user.make()
|
||||
other_user = subscriber_user.make()
|
||||
user.godfathers.add(other_user)
|
||||
client.force_login(user)
|
||||
response = client.post(
|
||||
reverse(
|
||||
"core:user_godfathers_delete",
|
||||
kwargs={
|
||||
"user_id": user.id,
|
||||
"godfather_id": other_user.id,
|
||||
"is_father": True,
|
||||
},
|
||||
)
|
||||
)
|
||||
assertRedirects(
|
||||
response, reverse("core:user_godfathers", kwargs={"user_id": user.id})
|
||||
)
|
||||
assert not user.godfathers.contains(other_user)
|
||||
|
||||
16
core/urls.py
16
core/urls.py
@@ -24,6 +24,7 @@
|
||||
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,
|
||||
@@ -53,6 +54,8 @@ from core.views import (
|
||||
PagePropView,
|
||||
PageRevView,
|
||||
PageView,
|
||||
PasswordRootChangeView,
|
||||
SearchView,
|
||||
SithLoginView,
|
||||
SithPasswordChangeDoneView,
|
||||
SithPasswordChangeView,
|
||||
@@ -76,13 +79,8 @@ from core.views import (
|
||||
UserUpdateProfileView,
|
||||
UserView,
|
||||
delete_user_godfather,
|
||||
index,
|
||||
logout,
|
||||
notification,
|
||||
password_root_change,
|
||||
search_json,
|
||||
search_user_json,
|
||||
search_view,
|
||||
send_file,
|
||||
)
|
||||
|
||||
@@ -91,20 +89,18 @@ register_converter(TwoDigitMonthConverter, "mm")
|
||||
register_converter(BooleanStringConverter, "bool")
|
||||
|
||||
urlpatterns = [
|
||||
path("", index, name="index"),
|
||||
path("", NewsListView.as_view(), name="index"),
|
||||
path("notifications/", NotificationList.as_view(), name="notification_list"),
|
||||
path("notification/<int:notif_id>/", notification, name="notification"),
|
||||
# Search
|
||||
path("search/", search_view, name="search"),
|
||||
path("search_json/", search_json, name="search_json"),
|
||||
path("search_user/", search_user_json, name="search_user"),
|
||||
path("search/", SearchView.as_view(), name="search"),
|
||||
# Login and co
|
||||
path("login/", SithLoginView.as_view(), name="login"),
|
||||
path("logout/", logout, name="logout"),
|
||||
path("password_change/", SithPasswordChangeView.as_view(), name="password_change"),
|
||||
path(
|
||||
"password_change/<int:user_id>/",
|
||||
password_root_change,
|
||||
PasswordRootChangeView.as_view(),
|
||||
name="password_root_change",
|
||||
),
|
||||
path(
|
||||
|
||||
@@ -303,7 +303,6 @@ class UserGodfathersForm(forms.Form):
|
||||
)
|
||||
user = forms.ModelChoiceField(
|
||||
label=_("Select user"),
|
||||
help_text=None,
|
||||
required=True,
|
||||
widget=AutoCompleteSelectUser,
|
||||
queryset=User.objects.all(),
|
||||
@@ -315,8 +314,6 @@ class UserGodfathersForm(forms.Form):
|
||||
|
||||
def clean_user(self):
|
||||
other_user = self.cleaned_data.get("user")
|
||||
if not other_user:
|
||||
raise ValidationError(_("This user does not exist"))
|
||||
if other_user == self.target_user:
|
||||
raise ValidationError(_("You cannot be related to yourself"))
|
||||
return other_user
|
||||
|
||||
@@ -22,106 +22,49 @@
|
||||
#
|
||||
#
|
||||
|
||||
import json
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core import serializers
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.db.models import F
|
||||
from django.db.models.query import QuerySet
|
||||
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 django.http import HttpRequest
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.views.generic import ListView, TemplateView
|
||||
|
||||
from club.models import Club
|
||||
from core.models import Notification, User
|
||||
from core.schemas import UserFilterSchema
|
||||
|
||||
|
||||
def index(request, context=None):
|
||||
from com.views import NewsListView
|
||||
|
||||
return NewsListView.as_view()(request)
|
||||
|
||||
|
||||
class NotificationList(ListView):
|
||||
class NotificationList(LoginRequiredMixin, 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, notif_id):
|
||||
notif = Notification.objects.filter(id=notif_id).first()
|
||||
if notif:
|
||||
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)
|
||||
return redirect("/")
|
||||
|
||||
|
||||
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]
|
||||
class SearchView(LoginRequiredMixin, TemplateView):
|
||||
template_name = "core/search.jinja"
|
||||
|
||||
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))
|
||||
)
|
||||
return [r.object for r in res]
|
||||
except TypeError:
|
||||
return []
|
||||
|
||||
|
||||
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)
|
||||
clubs = list(Club.objects.filter(name__icontains=query)[:5])
|
||||
return super().get_context_data(**kwargs) | {"users": users, "clubs": clubs}
|
||||
|
||||
@@ -22,27 +22,28 @@
|
||||
#
|
||||
#
|
||||
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
|
||||
|
||||
from django.contrib.auth import login, views
|
||||
from django.contrib.auth.forms import PasswordChangeForm
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db.models import DateField, QuerySet
|
||||
from django.db.models import DateField, F, QuerySet, Sum
|
||||
from django.db.models.functions import Trunc
|
||||
from django.forms.models import modelform_factory
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.template.loader import render_to_string
|
||||
from django.template.response import TemplateResponse
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.safestring import SafeString
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.decorators.http import require_POST
|
||||
from django.views.generic import (
|
||||
CreateView,
|
||||
DeleteView,
|
||||
@@ -66,9 +67,8 @@ from core.views.forms import (
|
||||
UserProfileForm,
|
||||
)
|
||||
from core.views.mixins import TabedViewMixin, UseFragmentsMixin
|
||||
from counter.models import Counter, Refilling, Selling
|
||||
from counter.models import Refilling, Selling
|
||||
from eboutic.models import Invoice
|
||||
from subscription.models import Subscription
|
||||
from trombi.views import UserTrombiForm
|
||||
|
||||
|
||||
@@ -99,21 +99,23 @@ def logout(request):
|
||||
return views.logout_then_login(request)
|
||||
|
||||
|
||||
def password_root_change(request, user_id):
|
||||
class PasswordRootChangeView(UserPassesTestMixin, FormView):
|
||||
"""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)
|
||||
if request.method == "POST":
|
||||
form = views.SetPasswordForm(user=user, data=request.POST)
|
||||
if form.is_valid():
|
||||
|
||||
template_name = "core/password_change.jinja"
|
||||
form_class = SetPasswordForm
|
||||
success_url = reverse_lazy("core:password_change_done")
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.is_root
|
||||
|
||||
def get_form_kwargs(self):
|
||||
user = get_object_or_404(User, id=self.kwargs["user_id"])
|
||||
return super().get_form_kwargs() | {"user": user}
|
||||
|
||||
def form_valid(self, form: SetPasswordForm):
|
||||
form.save()
|
||||
return redirect("core:password_change_done")
|
||||
else:
|
||||
form = views.SetPasswordForm(user=user)
|
||||
return TemplateResponse(
|
||||
request, "core/password_change.jinja", {"form": form, "target": user}
|
||||
)
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
@method_decorator(check_honeypot, name="post")
|
||||
@@ -288,10 +290,12 @@ class UserView(UserTabsMixin, CanViewMixin, DetailView):
|
||||
return kwargs
|
||||
|
||||
|
||||
@require_POST
|
||||
@login_required
|
||||
def delete_user_godfather(request, user_id, godfather_id, is_father):
|
||||
user_is_admin = request.user.is_root or request.user.is_board_member
|
||||
if user_id != request.user.id and not user_is_admin:
|
||||
raise PermissionDenied()
|
||||
raise PermissionDenied
|
||||
user = get_object_or_404(User, id=user_id)
|
||||
to_remove = get_object_or_404(User, id=godfather_id)
|
||||
if is_father:
|
||||
@@ -353,87 +357,40 @@ 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
|
||||
|
||||
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["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")
|
||||
)
|
||||
kwargs["total_perm_time"] = sum(
|
||||
[p.end - p.start for p in self.object.permanencies.exclude(end=None)],
|
||||
timedelta(),
|
||||
[perm["total"] for perm in kwargs["perm_time"]], start=timedelta(seconds=0)
|
||||
)
|
||||
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["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_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()[:10]
|
||||
.all()[:15]
|
||||
)
|
||||
return kwargs
|
||||
|
||||
@@ -465,7 +422,6 @@ class UserUpdateProfileView(UserTabsMixin, CanEditMixin, UpdateView):
|
||||
form_class = UserProfileForm
|
||||
current_tab = "edit"
|
||||
edit_once = ["profile_pict", "date_of_birth", "first_name", "last_name"]
|
||||
board_only = []
|
||||
|
||||
def remove_restricted_fields(self, request):
|
||||
"""Removes edit_once and board_only fields."""
|
||||
@@ -474,9 +430,6 @@ class UserUpdateProfileView(UserTabsMixin, CanEditMixin, UpdateView):
|
||||
request.user.is_board_member or request.user.is_root
|
||||
):
|
||||
self.form.fields.pop(i, None)
|
||||
for i in self.board_only:
|
||||
if not (request.user.is_board_member or request.user.is_root):
|
||||
self.form.fields.pop(i, None)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
@@ -528,10 +481,10 @@ class UserPreferencesView(UserTabsMixin, UseFragmentsMixin, CanEditMixin, Update
|
||||
current_tab = "prefs"
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
pref = self.object.preferences
|
||||
kwargs.update({"instance": pref})
|
||||
return kwargs
|
||||
return super().get_form_kwargs() | {"instance": self.object.preferences}
|
||||
|
||||
def get_success_url(self):
|
||||
return self.request.path
|
||||
|
||||
def get_fragment_context_data(self) -> dict[str, SafeString]:
|
||||
# Avoid cyclic import error
|
||||
|
||||
@@ -24,12 +24,6 @@
|
||||
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"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
import math
|
||||
import uuid
|
||||
from datetime import date
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
from django import forms
|
||||
@@ -136,7 +136,10 @@ class GetUserForm(forms.Form):
|
||||
|
||||
|
||||
class RefillForm(forms.ModelForm):
|
||||
allowed_refilling_methods = ["CASH", "CARD"]
|
||||
allowed_refilling_methods = [
|
||||
Refilling.PaymentMethod.CASH,
|
||||
Refilling.PaymentMethod.CARD,
|
||||
]
|
||||
|
||||
error_css_class = "error"
|
||||
required_css_class = "required"
|
||||
@@ -146,7 +149,7 @@ class RefillForm(forms.ModelForm):
|
||||
|
||||
class Meta:
|
||||
model = Refilling
|
||||
fields = ["amount", "payment_method", "bank"]
|
||||
fields = ["amount", "payment_method"]
|
||||
widgets = {"payment_method": forms.RadioSelect}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
@@ -160,9 +163,6 @@ 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:
|
||||
@@ -235,6 +235,19 @@ 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):
|
||||
@@ -321,11 +334,19 @@ class ProductForm(forms.ModelForm):
|
||||
def is_valid(self):
|
||||
return super().is_valid() and self.action_formset.is_valid()
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
ret = super().save(*args, **kwargs)
|
||||
self.instance.counters.set(self.cleaned_data["counters"])
|
||||
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)
|
||||
self.action_formset.save()
|
||||
return ret
|
||||
return product
|
||||
|
||||
|
||||
class ReturnableProductForm(forms.ModelForm):
|
||||
@@ -369,7 +390,6 @@ 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(),
|
||||
@@ -489,13 +509,14 @@ 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,
|
||||
date__lte=month + relativedelta(months=1),
|
||||
date__gte=month_start,
|
||||
date__lte=month_start + relativedelta(months=1),
|
||||
)
|
||||
)
|
||||
).annotate(
|
||||
|
||||
@@ -119,7 +119,6 @@ class Command(BaseCommand):
|
||||
quantity=1,
|
||||
unit_price=account.amount,
|
||||
date=now(),
|
||||
is_validated=True,
|
||||
)
|
||||
for account in accounts
|
||||
]
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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"),
|
||||
]
|
||||
@@ -44,7 +44,6 @@ 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
|
||||
|
||||
@@ -80,7 +79,8 @@ class CustomerQuerySet(models.QuerySet):
|
||||
)
|
||||
money_out = Subquery(
|
||||
Selling.objects.filter(
|
||||
customer=OuterRef("pk"), payment_method="SITH_ACCOUNT"
|
||||
customer=OuterRef("pk"),
|
||||
payment_method=Selling.PaymentMethod.SITH_ACCOUNT,
|
||||
)
|
||||
.values("customer_id")
|
||||
.annotate(res=Sum(F("unit_price") * F("quantity"), default=0))
|
||||
@@ -731,6 +731,11 @@ 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
|
||||
)
|
||||
@@ -745,16 +750,9 @@ class Refilling(models.Model):
|
||||
Customer, related_name="refillings", blank=False, on_delete=models.CASCADE
|
||||
)
|
||||
date = models.DateTimeField(_("date"))
|
||||
payment_method = models.CharField(
|
||||
_("payment method"),
|
||||
max_length=255,
|
||||
choices=PAYMENT_METHOD,
|
||||
default="CARD",
|
||||
payment_method = models.PositiveSmallIntegerField(
|
||||
_("payment method"), choices=PaymentMethod, default=PaymentMethod.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()
|
||||
|
||||
@@ -771,10 +769,9 @@ class Refilling(models.Model):
|
||||
if not self.date:
|
||||
self.date = timezone.now()
|
||||
self.full_clean()
|
||||
if not self.is_validated:
|
||||
if self._state.adding:
|
||||
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,
|
||||
@@ -814,6 +811,10 @@ 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(
|
||||
@@ -850,13 +851,9 @@ class Selling(models.Model):
|
||||
on_delete=models.SET_NULL,
|
||||
)
|
||||
date = models.DateTimeField(_("date"), db_index=True)
|
||||
payment_method = models.CharField(
|
||||
_("payment method"),
|
||||
max_length=255,
|
||||
choices=[("SITH_ACCOUNT", _("Sith account")), ("CARD", _("Credit card"))],
|
||||
default="SITH_ACCOUNT",
|
||||
payment_method = models.PositiveSmallIntegerField(
|
||||
_("payment method"), choices=PaymentMethod, default=PaymentMethod.SITH_ACCOUNT
|
||||
)
|
||||
is_validated = models.BooleanField(_("is validated"), default=False)
|
||||
|
||||
objects = SellingQuerySet.as_manager()
|
||||
|
||||
@@ -875,10 +872,12 @@ class Selling(models.Model):
|
||||
if not self.date:
|
||||
self.date = timezone.now()
|
||||
self.full_clean()
|
||||
if not self.is_validated:
|
||||
if (
|
||||
self._state.adding
|
||||
and self.payment_method == self.PaymentMethod.SITH_ACCOUNT
|
||||
):
|
||||
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 (
|
||||
@@ -948,7 +947,9 @@ class Selling(models.Model):
|
||||
def is_owned_by(self, user: User) -> bool:
|
||||
if user.is_anonymous:
|
||||
return False
|
||||
return self.payment_method != "CARD" and user.is_owner(self.counter)
|
||||
return self.payment_method != self.PaymentMethod.CARD and user.is_owner(
|
||||
self.counter
|
||||
)
|
||||
|
||||
def can_be_viewed_by(self, user: User) -> bool:
|
||||
if (
|
||||
@@ -958,7 +959,7 @@ class Selling(models.Model):
|
||||
return user == self.customer.user
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
if self.payment_method == "SITH_ACCOUNT":
|
||||
if self.payment_method == Selling.PaymentMethod.SITH_ACCOUNT:
|
||||
self.customer.amount += self.quantity * self.unit_price
|
||||
self.customer.save()
|
||||
super().delete(*args, **kwargs)
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Self
|
||||
|
||||
from annotated_types import MinLen
|
||||
from django.urls import reverse
|
||||
from ninja import Field, FilterSchema, ModelSchema, Schema
|
||||
from ninja import FilterLookup, FilterSchema, ModelSchema, Schema
|
||||
from pydantic import model_validator
|
||||
|
||||
from club.schemas import SimpleClubSchema
|
||||
from core.schemas import GroupSchema, SimpleUserSchema
|
||||
from core.schemas import GroupSchema, NonEmptyStr, SimpleUserSchema
|
||||
from counter.models import Counter, Product, ProductType
|
||||
|
||||
|
||||
@@ -21,7 +20,7 @@ class CounterSchema(ModelSchema):
|
||||
|
||||
|
||||
class CounterFilterSchema(FilterSchema):
|
||||
search: Annotated[str, MinLen(1)] = Field(None, q="name__icontains")
|
||||
search: Annotated[NonEmptyStr | None, FilterLookup("name__icontains")] = None
|
||||
|
||||
|
||||
class SimplifiedCounterSchema(ModelSchema):
|
||||
@@ -93,18 +92,18 @@ class ProductSchema(ModelSchema):
|
||||
|
||||
|
||||
class ProductFilterSchema(FilterSchema):
|
||||
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")
|
||||
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: datetime | None = Field(None, q="date__lt")
|
||||
after: datetime | None = Field(None, q="date__gt")
|
||||
counters: set[int] | None = Field(None, q="counter__in")
|
||||
products: set[int] | None = Field(None, q="product__in")
|
||||
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
|
||||
|
||||
@@ -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|truncate_time("millis") }}</td>
|
||||
<td>{{ barman.perm_sum|format_timedelta }}</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|truncate_time("millis") }}</td>
|
||||
<td>{{ barman.perm_sum|format_timedelta }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
@@ -116,7 +116,6 @@ 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,8 +11,12 @@ from model_bakery import baker
|
||||
|
||||
from core.models import Group, User
|
||||
from counter.baker_recipes import counter_recipe, product_recipe
|
||||
from counter.forms import ScheduledProductActionForm, ScheduledProductActionFormSet
|
||||
from counter.models import ScheduledProductAction
|
||||
from counter.forms import (
|
||||
ProductForm,
|
||||
ScheduledProductActionForm,
|
||||
ScheduledProductActionFormSet,
|
||||
)
|
||||
from counter.models import Product, ScheduledProductAction
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -34,6 +38,39 @@ 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, is_validated=False)
|
||||
baker.make(Refilling, amount=amount, customer=user.customer)
|
||||
|
||||
|
||||
class TestFullClickBase(TestCase):
|
||||
@@ -115,18 +115,10 @@ 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": "CASH",
|
||||
"bank": "OTHER",
|
||||
},
|
||||
reverse("counter:refilling_create", kwargs={"customer_id": user.pk}),
|
||||
{"amount": str(amount), "payment_method": Refilling.PaymentMethod.CASH},
|
||||
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}
|
||||
),
|
||||
)
|
||||
|
||||
@@ -149,11 +141,7 @@ class TestRefilling(TestFullClickBase):
|
||||
"counter:refilling_create",
|
||||
kwargs={"customer_id": self.customer.pk},
|
||||
),
|
||||
{
|
||||
"amount": "10",
|
||||
"payment_method": "CASH",
|
||||
"bank": "OTHER",
|
||||
},
|
||||
{"amount": "10", "payment_method": "CASH"},
|
||||
)
|
||||
|
||||
self.client.force_login(self.club_admin)
|
||||
|
||||
@@ -298,7 +298,6 @@ def test_update_balance():
|
||||
_quantity=len(customers),
|
||||
unit_price=10,
|
||||
quantity=1,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
_save_related=True,
|
||||
),
|
||||
*sale_recipe.prepare(
|
||||
@@ -306,14 +305,12 @@ 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(
|
||||
@@ -324,7 +321,7 @@ def test_update_balance():
|
||||
_quantity=len(customers),
|
||||
unit_price=50,
|
||||
quantity=1,
|
||||
payment_method="CARD",
|
||||
payment_method=Selling.PaymentMethod.CARD,
|
||||
_save_related=True,
|
||||
),
|
||||
]
|
||||
|
||||
@@ -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 localdate
|
||||
from django.utils.timezone import now
|
||||
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 = localdate() - relativedelta(months=1)
|
||||
month = now() - 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)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
|
||||
@@ -23,6 +23,7 @@ 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
|
||||
@@ -285,7 +286,13 @@ class CounterStatView(PermissionRequiredMixin, DetailView):
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add stats to the context."""
|
||||
counter: Counter = self.object
|
||||
semester_start = get_start_of_semester()
|
||||
start_date = get_start_of_semester()
|
||||
semester_start = datetime(
|
||||
start_date.year,
|
||||
start_date.month,
|
||||
start_date.day,
|
||||
tzinfo=get_current_timezone(),
|
||||
)
|
||||
office_hours = counter.get_top_barmen()
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs.update(
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
@@ -63,19 +63,18 @@ class InvoiceCallView(
|
||||
"""Add sums to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["months"] = Selling.objects.datetimes("date", "month", order="DESC")
|
||||
start_date = self.get_month()
|
||||
month = self.get_month()
|
||||
start_date = datetime(month.year, month.month, month.day, tzinfo=timezone.utc)
|
||||
end_date = start_date + relativedelta(months=1)
|
||||
|
||||
kwargs["sum_cb"] = Refilling.objects.filter(
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
payment_method=Refilling.PaymentMethod.CARD,
|
||||
date__gte=start_date,
|
||||
date__lte=end_date,
|
||||
).aggregate(res=Sum("amount", default=0))["res"]
|
||||
kwargs["sum_cb"] += (
|
||||
Selling.objects.filter(
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
payment_method=Selling.PaymentMethod.CARD,
|
||||
date__gte=start_date,
|
||||
date__lte=end_date,
|
||||
)
|
||||
|
||||
@@ -110,7 +110,9 @@ class Basket(models.Model):
|
||||
)["total"]
|
||||
)
|
||||
|
||||
def generate_sales(self, counter, seller: User, payment_method: str):
|
||||
def generate_sales(
|
||||
self, counter, seller: User, payment_method: Selling.PaymentMethod
|
||||
):
|
||||
"""Generate a list of sold items corresponding to the items
|
||||
of this basket WITHOUT saving them NOR deleting the basket.
|
||||
|
||||
@@ -251,8 +253,7 @@ class Invoice(models.Model):
|
||||
customer=customer,
|
||||
operator=self.user,
|
||||
amount=i.product_unit_price * i.quantity,
|
||||
payment_method="CARD",
|
||||
bank="OTHER",
|
||||
payment_method=Refilling.PaymentMethod.CARD,
|
||||
date=self.date,
|
||||
)
|
||||
new.save()
|
||||
@@ -267,8 +268,7 @@ class Invoice(models.Model):
|
||||
customer=customer,
|
||||
unit_price=i.product_unit_price,
|
||||
quantity=i.quantity,
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
payment_method=Selling.PaymentMethod.CARD,
|
||||
date=self.date,
|
||||
)
|
||||
new.save()
|
||||
|
||||
@@ -108,12 +108,22 @@ def test_eboutic_basket_expiry(
|
||||
|
||||
client.force_login(customer.user)
|
||||
|
||||
for date in sellings:
|
||||
if sellings:
|
||||
sale_recipe.make(
|
||||
customer=customer, counter=eboutic, date=date, is_validated=True
|
||||
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,
|
||||
)
|
||||
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 == "SITH_ACCOUNT"
|
||||
assert sellings[0].payment_method == Selling.PaymentMethod.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 == "SITH_ACCOUNT"
|
||||
assert sellings[1].payment_method == Selling.PaymentMethod.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 == "CARD"
|
||||
assert sellings[0].payment_method == Selling.PaymentMethod.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 == "CARD"
|
||||
assert sellings[1].payment_method == Selling.PaymentMethod.CARD
|
||||
assert sellings[1].quantity == 2
|
||||
assert sellings[1].unit_price == self.beer.selling_price
|
||||
assert sellings[1].counter.type == "EBOUTIC"
|
||||
|
||||
@@ -275,7 +275,9 @@ class EbouticPayWithSith(CanViewMixin, SingleObjectMixin, View):
|
||||
return redirect("eboutic:payment_result", "failure")
|
||||
|
||||
eboutic = get_eboutic()
|
||||
sales = basket.generate_sales(eboutic, basket.user, "SITH_ACCOUNT")
|
||||
sales = basket.generate_sales(
|
||||
eboutic, basket.user, Selling.PaymentMethod.SITH_ACCOUNT
|
||||
)
|
||||
try:
|
||||
with transaction.atomic():
|
||||
# Selling.save has some important business logic in it.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2025-11-12 21:44+0100\n"
|
||||
"POT-Creation-Date: 2025-11-24 11:05+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"
|
||||
@@ -2658,8 +2658,8 @@ msgid "Buyings"
|
||||
msgstr "Achats"
|
||||
|
||||
#: core/templates/core/user_stats.jinja
|
||||
msgid "Product top 10"
|
||||
msgstr "Top 10 produits"
|
||||
msgid "Product top 15"
|
||||
msgstr "Top 15 produits"
|
||||
|
||||
#: core/templates/core/user_stats.jinja
|
||||
msgid "Product"
|
||||
@@ -2819,8 +2819,8 @@ msgstr "Outils Trombi"
|
||||
#, python-format
|
||||
msgid "%(nb_days)d day, %(remainder)s"
|
||||
msgid_plural "%(nb_days)d days, %(remainder)s"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
msgstr[0] "%(nb_days)d jour, %(remainder)s"
|
||||
msgstr[1] "%(nb_days)d jours, %(remainder)s"
|
||||
|
||||
#: core/views/files.py
|
||||
msgid "Add a new folder"
|
||||
@@ -2928,18 +2928,6 @@ 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"
|
||||
@@ -3152,22 +3140,30 @@ 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 "bank"
|
||||
msgstr "banque"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "is validated"
|
||||
msgstr "est validé"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "refilling"
|
||||
msgstr "rechargement"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "Sith account"
|
||||
msgstr "Compte utilisateur"
|
||||
|
||||
#: counter/models.py eboutic/models.py
|
||||
msgid "unit price"
|
||||
msgstr "prix unitaire"
|
||||
@@ -3176,10 +3172,6 @@ msgstr "prix unitaire"
|
||||
msgid "quantity"
|
||||
msgstr "quantité"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "Sith account"
|
||||
msgstr "Compte utilisateur"
|
||||
|
||||
#: counter/models.py
|
||||
msgid "selling"
|
||||
msgstr "vente"
|
||||
@@ -3332,6 +3324,10 @@ 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"
|
||||
|
||||
@@ -24,6 +24,7 @@ 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 _
|
||||
@@ -34,7 +35,7 @@ from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
||||
|
||||
from core.auth.mixins import FormerSubscriberMixin
|
||||
from core.models import User
|
||||
from core.views import search_user
|
||||
from core.schemas import UserFilterSchema
|
||||
from core.views.forms import SelectDate
|
||||
|
||||
# Enum to select search type
|
||||
@@ -126,11 +127,13 @@ 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 = search_user(self.valid_form["quick"])
|
||||
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))
|
||||
)
|
||||
else:
|
||||
q = []
|
||||
if not self.can_see_hidden and len(q) > 0:
|
||||
q = [user for user in q if user.is_viewable]
|
||||
else:
|
||||
search_dict = {}
|
||||
for key, value in self.valid_form.items():
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from typing import Literal
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from django.db.models import Q
|
||||
from django.utils import html
|
||||
from haystack.query import SearchQuerySet
|
||||
from ninja import FilterSchema, ModelSchema, Schema
|
||||
from ninja import FilterLookup, FilterSchema, ModelSchema, Schema
|
||||
from pydantic import AliasPath, ConfigDict, Field, TypeAdapter
|
||||
from pydantic.alias_generators import to_camel
|
||||
|
||||
@@ -114,13 +114,14 @@ class UvSchema(ModelSchema):
|
||||
|
||||
|
||||
class UvFilterSchema(FilterSchema):
|
||||
search: str | None = Field(None, q="code__icontains")
|
||||
search: Annotated[str | None, FilterLookup("code__icontains")] = None
|
||||
semester: set[Literal["AUTUMN", "SPRING"]] | None = None
|
||||
credit_type: set[Literal["CS", "TM", "EC", "OM", "QC"]] | None = Field(
|
||||
None, q="credit_type__in"
|
||||
)
|
||||
credit_type: Annotated[
|
||||
set[Literal["CS", "TM", "EC", "OM", "QC"]] | None,
|
||||
FilterLookup("credit_type__in"),
|
||||
] = None
|
||||
language: str = "FR"
|
||||
department: set[str] | None = Field(None, q="department__in")
|
||||
department: Annotated[set[str] | None, FilterLookup("department__in")] = None
|
||||
|
||||
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.4.5,<2.0.0",
|
||||
"django-ninja-extra>=0.30.2,<1.0.0",
|
||||
"django-ninja>=1.5.0,<6.0.0",
|
||||
"django-ninja-extra>=0.30.6",
|
||||
"Pillow>=12.0.0,<13.0.0",
|
||||
"mistune>=3.1.4,<4.0.0",
|
||||
"django-jinja<3.0.0,>=2.11.0",
|
||||
@@ -83,7 +83,7 @@ tests = [
|
||||
docs = [
|
||||
"mkdocs<2.0.0,>=1.6.1",
|
||||
"mkdocs-material>=9.6.23,<10.0.0",
|
||||
"mkdocstrings>=0.30.1,<1.0.0",
|
||||
"mkdocstrings>=0.30.1,<2.0.0",
|
||||
"mkdocstrings-python>=1.18.2,<2.0.0",
|
||||
"mkdocs-include-markdown-plugin>=7.2.0,<8.0.0",
|
||||
]
|
||||
|
||||
@@ -114,7 +114,6 @@ class TestMergeUser(TestCase):
|
||||
seller=self.root,
|
||||
unit_price=2,
|
||||
quantity=2,
|
||||
payment_method="SITH_ACCOUNT",
|
||||
).save()
|
||||
Selling(
|
||||
label="barbar",
|
||||
@@ -125,7 +124,6 @@ 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
|
||||
@@ -197,7 +195,6 @@ 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)
|
||||
@@ -225,7 +222,6 @@ 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)
|
||||
|
||||
@@ -2,20 +2,19 @@ from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from annotated_types import MinLen
|
||||
from django.urls import reverse
|
||||
from ninja import FilterSchema, ModelSchema, Schema
|
||||
from ninja import FilterLookup, FilterSchema, ModelSchema, Schema
|
||||
from pydantic import Field, NonNegativeInt
|
||||
|
||||
from core.schemas import SimpleUserSchema, UserProfileSchema
|
||||
from core.schemas import NonEmptyStr, SimpleUserSchema, UserProfileSchema
|
||||
from sas.models import Album, Picture, PictureModerationRequest
|
||||
|
||||
|
||||
class AlbumFilterSchema(FilterSchema):
|
||||
search: Annotated[str, MinLen(1)] | None = Field(None, q="name__icontains")
|
||||
before_date: datetime | None = Field(None, q="event_date__lte")
|
||||
after_date: datetime | None = Field(None, q="event_date__gte")
|
||||
parent_id: int | None = Field(None, q="parent_id")
|
||||
search: Annotated[NonEmptyStr | None, FilterLookup("name__icontains")] = None
|
||||
before_date: Annotated[datetime | None, FilterLookup("event_date__lte")] = None
|
||||
after_date: Annotated[datetime | None, FilterLookup("event_date__gte")] = None
|
||||
parent_id: Annotated[int | None, FilterLookup("parent_id")] = None
|
||||
|
||||
|
||||
class SimpleAlbumSchema(ModelSchema):
|
||||
@@ -60,10 +59,12 @@ class AlbumAutocompleteSchema(ModelSchema):
|
||||
|
||||
|
||||
class PictureFilterSchema(FilterSchema):
|
||||
before_date: datetime | None = Field(None, q="date__lte")
|
||||
after_date: datetime | None = Field(None, q="date__gte")
|
||||
users_identified: set[int] | None = Field(None, q="people__user_id__in")
|
||||
album_id: int | None = Field(None, q="parent_id")
|
||||
before_date: Annotated[datetime | None, FilterLookup("date__lte")] = None
|
||||
after_date: Annotated[datetime | None, FilterLookup("date__gte")] = None
|
||||
users_identified: Annotated[
|
||||
set[int] | None, FilterLookup("people__user_id__in")
|
||||
] = None
|
||||
album_id: Annotated[int | None, FilterLookup("parent_id")] = None
|
||||
|
||||
|
||||
class PictureSchema(ModelSchema):
|
||||
|
||||
@@ -177,7 +177,6 @@ TEMPLATES = [
|
||||
"filters": {
|
||||
"markdown": "core.templatetags.renderer.markdown",
|
||||
"phonenumber": "core.templatetags.renderer.phonenumber",
|
||||
"truncate_time": "core.templatetags.renderer.truncate_time",
|
||||
"format_timedelta": "core.templatetags.renderer.format_timedelta",
|
||||
"add_attr": "core.templatetags.renderer.add_attr",
|
||||
},
|
||||
@@ -216,7 +215,7 @@ TEMPLATES = [
|
||||
},
|
||||
},
|
||||
]
|
||||
FORM_RENDERER = "django.forms.renderers.DjangoDivFormRenderer"
|
||||
|
||||
|
||||
HAYSTACK_CONNECTIONS = {
|
||||
"default": {
|
||||
@@ -440,19 +439,6 @@ SITH_SUBSCRIPTION_LOCATIONS = [
|
||||
|
||||
SITH_COUNTER_BARS = [(1, "MDE"), (2, "Foyer"), (35, "La Gommette")]
|
||||
|
||||
SITH_COUNTER_BANK = [
|
||||
("OTHER", "Autre"),
|
||||
("SOCIETE-GENERALE", "Société générale"),
|
||||
("BANQUE-POPULAIRE", "Banque populaire"),
|
||||
("BNP", "BNP"),
|
||||
("CAISSE-EPARGNE", "Caisse d'épargne"),
|
||||
("CIC", "CIC"),
|
||||
("CREDIT-AGRICOLE", "Crédit Agricole"),
|
||||
("CREDIT-MUTUEL", "Credit Mutuel"),
|
||||
("CREDIT-LYONNAIS", "Credit Lyonnais"),
|
||||
("LA-POSTE", "La Poste"),
|
||||
]
|
||||
|
||||
SITH_PEDAGOGY_UV_TYPE = [
|
||||
("FREE", _("Free")),
|
||||
("CS", _("CS")),
|
||||
|
||||
@@ -24,7 +24,6 @@ from django.views.generic import CreateView, DetailView, TemplateView
|
||||
from django.views.generic.edit import FormView
|
||||
|
||||
from core.views.group import PermissionGroupsUpdateView
|
||||
from counter.apps import PAYMENT_METHOD
|
||||
from subscription.forms import (
|
||||
SelectionDateForm,
|
||||
SubscriptionExistingUserForm,
|
||||
@@ -129,6 +128,6 @@ class SubscriptionsStatsView(FormView):
|
||||
subscription_end__gte=self.end_date, subscription_start__lte=self.start_date
|
||||
)
|
||||
kwargs["subscriptions_types"] = settings.SITH_SUBSCRIPTIONS
|
||||
kwargs["payment_types"] = PAYMENT_METHOD
|
||||
kwargs["payment_types"] = settings.SITH_SUBSCRIPTION_PAYMENT_METHOD
|
||||
kwargs["locations"] = settings.SITH_SUBSCRIPTION_LOCATIONS
|
||||
return kwargs
|
||||
|
||||
Reference in New Issue
Block a user