mirror of
https://github.com/ae-utbm/sith.git
synced 2026-11-20 07:59:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c1a94e83d | ||
|
|
cacc243562 | ||
|
|
3065783492 | ||
|
|
6805ef4912 | ||
|
|
884940af30 | ||
|
|
aab5cc178e | ||
|
|
fa14bcb608 | ||
|
|
cda00e88df | ||
|
|
a31062a271 | ||
|
|
01112a89aa | ||
|
|
e45b4eb9e0 | ||
|
|
079ec8a8e5 |
No files matched your search
@@ -32,5 +32,3 @@ site/
|
|||||||
# Ignore redis binary dump (dump.rdb) files
|
# Ignore redis binary dump (dump.rdb) files
|
||||||
|
|
||||||
*.rdb
|
*.rdb
|
||||||
|
|
||||||
.devenv
|
|
||||||
+15
-16
@@ -299,25 +299,25 @@ class ClubSearchForm(forms.ModelForm):
|
|||||||
class ClubRoleForm(forms.ModelForm):
|
class ClubRoleForm(forms.ModelForm):
|
||||||
error_css_class = "error"
|
error_css_class = "error"
|
||||||
required_css_class = "required"
|
required_css_class = "required"
|
||||||
is_stock_group = forms.BooleanField(
|
|
||||||
required=False,
|
|
||||||
label=_("Can edit stock"),
|
|
||||||
widget=forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
help_text=_("Tell if the user can edit all stocks belongings to the club"),
|
|
||||||
)
|
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = ClubRole
|
model = ClubRole
|
||||||
fields = ["name", "description", "is_presidency", "is_board", "is_active"]
|
fields = [
|
||||||
|
"name",
|
||||||
|
"name_en",
|
||||||
|
"description",
|
||||||
|
"is_presidency",
|
||||||
|
"is_board",
|
||||||
|
"is_active",
|
||||||
|
]
|
||||||
widgets = {
|
widgets = {
|
||||||
"is_presidency": forms.HiddenInput(),
|
"is_presidency": forms.HiddenInput(),
|
||||||
"is_board": forms.HiddenInput(),
|
"is_board": forms.HiddenInput(),
|
||||||
"is_active": forms.CheckboxInput(attrs={"class": "switch"}),
|
"is_active": forms.CheckboxInput(attrs={"class": "switch"}),
|
||||||
}
|
}
|
||||||
|
help_texts = {
|
||||||
def __init__(self, *args, **kwargs):
|
"name_en": _("Provide an english name for non-french speaking users.")
|
||||||
super().__init__(*args, **kwargs)
|
}
|
||||||
self.fields["is_stock_group"].initial = self.instance.is_stock_group
|
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
cleaned_data = super().clean()
|
cleaned_data = super().clean()
|
||||||
@@ -325,10 +325,6 @@ class ClubRoleForm(forms.ModelForm):
|
|||||||
self.instance.order = cleaned_data["ORDER"] - 1
|
self.instance.order = cleaned_data["ORDER"] - 1
|
||||||
return cleaned_data
|
return cleaned_data
|
||||||
|
|
||||||
def _save_m2m(self):
|
|
||||||
super()._save_m2m()
|
|
||||||
self.instance.is_stock_group = self.cleaned_data["is_stock_group"]
|
|
||||||
|
|
||||||
def save(self, commit=True): # noqa: FBT002
|
def save(self, commit=True): # noqa: FBT002
|
||||||
instance: ClubRole = super().save(commit=commit)
|
instance: ClubRole = super().save(commit=commit)
|
||||||
if commit and "is_board" in self.changed_data:
|
if commit and "is_board" in self.changed_data:
|
||||||
@@ -368,7 +364,10 @@ class ClubRoleCreateForm(forms.ModelForm):
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = ClubRole
|
model = ClubRole
|
||||||
fields = ["name", "description"]
|
fields = ["name", "name_en", "description"]
|
||||||
|
help_texts = {
|
||||||
|
"name_en": _("Provide an english name for non-french speaking users.")
|
||||||
|
}
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self, *args, club: Club, is_presidency: bool, is_board: bool, **kwargs
|
self, *args, club: Club, is_presidency: bool, is_board: bool, **kwargs
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
# Generated by Django 5.2.18 on 2026-11-09 06:57
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
def add_stock_groups(apps, schema_editor):
|
|
||||||
Club = apps.get_model("club", "Club")
|
|
||||||
Group = apps.get_model("core", "Group")
|
|
||||||
for club in Club.objects.all():
|
|
||||||
new_group = Group.objects.create(
|
|
||||||
name=f"{club.name} - Stock",
|
|
||||||
is_manually_manageable=False,
|
|
||||||
)
|
|
||||||
club.stock_group = new_group
|
|
||||||
club.save()
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("club", "0019_remove_mailingsubscription_mailing_and_more"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="club",
|
|
||||||
name="stock_group",
|
|
||||||
field=models.OneToOneField(
|
|
||||||
null=True,
|
|
||||||
editable=False,
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="club_stock",
|
|
||||||
to="core.group",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.RunPython(add_stock_groups),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="club",
|
|
||||||
name="stock_group",
|
|
||||||
field=models.OneToOneField(
|
|
||||||
editable=False,
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="club_stock",
|
|
||||||
to="core.group",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Generated by Django 5.2.18 on 2026-11-14 11:44
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
from django.db.models import F
|
||||||
|
from django.db.models.expressions import Case, Value, When
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from django.db.migrations.state import StateApps
|
||||||
|
|
||||||
|
|
||||||
|
def copy_name(apps: StateApps, schema_editor):
|
||||||
|
"""Automatically populate French names and the most common English ones"""
|
||||||
|
ClubRole = apps.get_model("club", "ClubRole")
|
||||||
|
ClubRole.objects.update(
|
||||||
|
name_fr=F("name"),
|
||||||
|
name_en=Case(
|
||||||
|
When(name="Président⸱e", then=Value("President")),
|
||||||
|
When(name="Vice-Président⸱e", then=Value("Vice-president")),
|
||||||
|
When(name="Trésorier⸱e", then=Value("Treasurer")),
|
||||||
|
When(name="Responsable communication", then=Value("Communication manager")),
|
||||||
|
When(name="Secrétaire", then=Value("Secretary")),
|
||||||
|
When(name="Responsable info", then=Value("IT manager")),
|
||||||
|
When(name="Membre du bureau", then=Value("Board member")),
|
||||||
|
When(name="Membre actif⸱ve", then=Value("Active member")),
|
||||||
|
When(name="Curieux⸱euse", then=Value("Curious")),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [("club", "0019_remove_mailingsubscription_mailing_and_more")]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="clubrole",
|
||||||
|
name="name_en",
|
||||||
|
field=models.CharField(max_length=50, null=True, verbose_name="name"),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="clubrole",
|
||||||
|
name="name_fr",
|
||||||
|
field=models.CharField(max_length=50, null=True, verbose_name="name"),
|
||||||
|
),
|
||||||
|
migrations.AddConstraint(
|
||||||
|
model_name="clubrole",
|
||||||
|
constraint=models.UniqueConstraint(
|
||||||
|
fields=("club", "name"),
|
||||||
|
name="clubrole_club_name_unique",
|
||||||
|
violation_error_message="There is already a role with that name",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddConstraint(
|
||||||
|
model_name="clubrole",
|
||||||
|
constraint=models.UniqueConstraint(
|
||||||
|
fields=("club", "name_fr"),
|
||||||
|
name="clubrole_club_name_unique-fr",
|
||||||
|
violation_error_message="There is already a role with that name",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddConstraint(
|
||||||
|
model_name="clubrole",
|
||||||
|
constraint=models.UniqueConstraint(
|
||||||
|
fields=("club", "name_en"),
|
||||||
|
name="clubrole_club_name_unique-en",
|
||||||
|
violation_error_message="There is already a role with that name",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.RunPython(
|
||||||
|
copy_name, reverse_code=migrations.RunPython.noop, elidable=True
|
||||||
|
),
|
||||||
|
]
|
||||||
+6
-20
@@ -98,9 +98,6 @@ class Club(models.Model):
|
|||||||
board_group = models.OneToOneField(
|
board_group = models.OneToOneField(
|
||||||
Group, related_name="club_board", on_delete=models.PROTECT, editable=False
|
Group, related_name="club_board", on_delete=models.PROTECT, editable=False
|
||||||
)
|
)
|
||||||
stock_group = models.OneToOneField(
|
|
||||||
Group, related_name="club_stock", on_delete=models.PROTECT, editable=False
|
|
||||||
)
|
|
||||||
|
|
||||||
objects = ClubQuerySet.as_manager()
|
objects = ClubQuerySet.as_manager()
|
||||||
|
|
||||||
@@ -132,9 +129,6 @@ class Club(models.Model):
|
|||||||
self.members_group = Group.objects.create(
|
self.members_group = Group.objects.create(
|
||||||
name=f"{self.name} - Membres", is_manually_manageable=False
|
name=f"{self.name} - Membres", is_manually_manageable=False
|
||||||
)
|
)
|
||||||
self.stock_group = Group.objects.create(
|
|
||||||
name=f"{self.name} - Stock", is_manually_manageable=False
|
|
||||||
)
|
|
||||||
self.make_home()
|
self.make_home()
|
||||||
self.make_page()
|
self.make_page()
|
||||||
super().save(*args, **kwargs)
|
super().save(*args, **kwargs)
|
||||||
@@ -301,19 +295,6 @@ class ClubRole(OrderedModel):
|
|||||||
|
|
||||||
order_with_respect_to = "club"
|
order_with_respect_to = "club"
|
||||||
|
|
||||||
@property
|
|
||||||
def is_stock_group(self):
|
|
||||||
if not self.pk:
|
|
||||||
return False
|
|
||||||
return self.linked_groups.contains(self.club.stock_group)
|
|
||||||
|
|
||||||
@is_stock_group.setter
|
|
||||||
def is_stock_group(self, value):
|
|
||||||
if value is True:
|
|
||||||
self.linked_groups.add(self.club.stock_group)
|
|
||||||
else:
|
|
||||||
self.linked_groups.remove(self.club.stock_group)
|
|
||||||
|
|
||||||
class Meta(OrderedModel.Meta):
|
class Meta(OrderedModel.Meta):
|
||||||
verbose_name = _("club role")
|
verbose_name = _("club role")
|
||||||
verbose_name_plural = _("club roles")
|
verbose_name_plural = _("club roles")
|
||||||
@@ -326,7 +307,12 @@ class ClubRole(OrderedModel):
|
|||||||
violation_error_message=_(
|
violation_error_message=_(
|
||||||
"A role cannot be in the presidency while not being in the board"
|
"A role cannot be in the presidency while not being in the board"
|
||||||
),
|
),
|
||||||
)
|
),
|
||||||
|
models.UniqueConstraint(
|
||||||
|
fields=("club", "name"),
|
||||||
|
name="clubrole_club_name_unique",
|
||||||
|
violation_error_message=_("There is already a role with that name"),
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
|
|||||||
@@ -37,6 +37,9 @@
|
|||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
{{ subform.name.as_field_group() }}
|
{{ subform.name.as_field_group() }}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
{{ subform.name_en.as_field_group() }}
|
||||||
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
{{ subform.description.as_field_group() }}
|
{{ subform.description.as_field_group() }}
|
||||||
</div>
|
</div>
|
||||||
@@ -49,18 +52,7 @@
|
|||||||
{{ subform.is_active.help_text }}
|
{{ subform.is_active.help_text }}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
{% set groups = subform.instance.linked_groups.all()|list %}
|
||||||
<div>
|
|
||||||
{{ subform.is_stock_group }}
|
|
||||||
{{ subform.is_stock_group.label_tag() }}
|
|
||||||
</div>
|
|
||||||
<span class="helptext">
|
|
||||||
{{ subform.is_stock_group.help_text }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{# I don't know why it has no id in my case.... Maybe I'm big dum #}
|
|
||||||
{% set groups = subform.instance.linked_groups.all()|list if subform.instance.pk else [] %}
|
|
||||||
{% if groups %}
|
{% if groups %}
|
||||||
<div>
|
<div>
|
||||||
<p>
|
<p>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import pytest
|
|||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.test import Client, TestCase
|
from django.test import Client, TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from django.utils import translation
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from model_bakery import baker, seq
|
from model_bakery import baker, seq
|
||||||
from model_bakery.recipe import Recipe
|
from model_bakery.recipe import Recipe
|
||||||
@@ -281,3 +282,14 @@ class TestClubRoleUpdate(TestCase):
|
|||||||
# the second membership is finished, so its user shouldn't get the role
|
# the second membership is finished, so its user shouldn't get the role
|
||||||
assert members[0].user.groups.contains(self.club.board_group)
|
assert members[0].user.groups.contains(self.club.board_group)
|
||||||
assert not members[1].user.groups.contains(self.club.board_group)
|
assert not members[1].user.groups.contains(self.club.board_group)
|
||||||
|
|
||||||
|
def test_name_translation(self):
|
||||||
|
"""Test that setting the english name works."""
|
||||||
|
name_en = "something something"
|
||||||
|
self.payload["roles-0-name_en"] = name_en
|
||||||
|
formset = ClubRoleFormSet(data=self.payload, instance=self.club)
|
||||||
|
assert formset.is_valid()
|
||||||
|
formset.save()
|
||||||
|
self.roles[0].refresh_from_db()
|
||||||
|
with translation.override("en"):
|
||||||
|
assert self.roles[0].name == name_en
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
from modeltranslation.translator import TranslationOptions, register
|
||||||
|
|
||||||
|
from club.models import ClubRole
|
||||||
|
|
||||||
|
|
||||||
|
@register(ClubRole)
|
||||||
|
class ClubRoleTranslationOptions(TranslationOptions):
|
||||||
|
fields = ("name",)
|
||||||
@@ -252,7 +252,6 @@ class Command(BaseCommand):
|
|||||||
date_of_birth="1942-06-12",
|
date_of_birth="1942-06-12",
|
||||||
password="plop",
|
password="plop",
|
||||||
)
|
)
|
||||||
User.objects.all().update(cgu_approved_at=now())
|
|
||||||
User.groups.through.objects.bulk_create(
|
User.groups.through.objects.bulk_create(
|
||||||
[
|
[
|
||||||
User.groups.through(group=groups.counter_admin, user=counter),
|
User.groups.through(group=groups.counter_admin, user=counter),
|
||||||
@@ -277,6 +276,10 @@ class Command(BaseCommand):
|
|||||||
)
|
)
|
||||||
|
|
||||||
self._create_pages(groups)
|
self._create_pages(groups)
|
||||||
|
# the "approve cgu" button is shown if the cgu were approved
|
||||||
|
# before the last version of the CGU page.
|
||||||
|
# Hence, it's better for this update to be after page creation.
|
||||||
|
User.objects.all().update(cgu_approved_at=now())
|
||||||
|
|
||||||
self._create_subscription(root)
|
self._create_subscription(root)
|
||||||
self._create_subscription(skia)
|
self._create_subscription(skia)
|
||||||
@@ -779,28 +782,47 @@ class Command(BaseCommand):
|
|||||||
name="Carte AE", address="Jamais imprimée", parent=ae
|
name="Carte AE", address="Jamais imprimée", parent=ae
|
||||||
)
|
)
|
||||||
roles = []
|
roles = []
|
||||||
presidency_roles = ["Président⸱e", "Vice-Président⸱e"]
|
presidency_roles = [
|
||||||
|
("Président⸱e", "President"),
|
||||||
|
("Vice-Président⸱e", "Vice-president"),
|
||||||
|
]
|
||||||
board_roles = [
|
board_roles = [
|
||||||
"Trésorier⸱e",
|
("Trésorier⸱e", "Treasurer"),
|
||||||
"Secrétaire",
|
("Secrétaire", "Secretary"),
|
||||||
"Respo Info",
|
("Respo Info", "IT manager"),
|
||||||
"Respo Com",
|
("Respo Com", "Communication manager"),
|
||||||
"Membre du bureau",
|
("Membre du bureau", "Board member"),
|
||||||
|
]
|
||||||
|
simple_roles = [
|
||||||
|
("Membre actif⸱ve", "Active member"),
|
||||||
|
("Curieux⸱euse", "Curious"),
|
||||||
]
|
]
|
||||||
simple_roles = ["Membre actif⸱ve", "Curieux⸱euse"]
|
|
||||||
for club in ae, pdf, troll, refound:
|
for club in ae, pdf, troll, refound:
|
||||||
for i, role in enumerate(presidency_roles):
|
for i, (role_fr, role_en) in enumerate(presidency_roles):
|
||||||
roles.append(
|
roles.append(
|
||||||
ClubRole(
|
ClubRole(
|
||||||
club=club, order=i, name=role, is_presidency=True, is_board=True
|
club=club,
|
||||||
|
order=i,
|
||||||
|
name=role_fr,
|
||||||
|
name_en=role_en,
|
||||||
|
is_presidency=True,
|
||||||
|
is_board=True,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
for i, role in enumerate(board_roles, start=len(presidency_roles)):
|
for i, (role_fr, role_en) in enumerate(
|
||||||
roles.append(ClubRole(club=club, order=i, name=role, is_board=True))
|
board_roles, start=len(presidency_roles)
|
||||||
for i, role in enumerate(
|
):
|
||||||
|
roles.append(
|
||||||
|
ClubRole(
|
||||||
|
club=club, order=i, name=role_fr, name_en=role_en, is_board=True
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for i, (role_fr, role_en) in enumerate(
|
||||||
simple_roles, start=len(presidency_roles) + len(board_roles)
|
simple_roles, start=len(presidency_roles) + len(board_roles)
|
||||||
):
|
):
|
||||||
roles.append(ClubRole(club=club, order=i, name=role))
|
roles.append(
|
||||||
|
ClubRole(club=club, order=i, name=role_fr, name_en=role_en)
|
||||||
|
)
|
||||||
ClubRole.objects.bulk_create(roles)
|
ClubRole.objects.bulk_create(roles)
|
||||||
insta, fb, discord, _ = LinkType.objects.bulk_create(
|
insta, fb, discord, _ = LinkType.objects.bulk_create(
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
# Generated by Django 5.2.18 on 2026-11-09 01:33
|
|
||||||
|
|
||||||
from django.db import migrations
|
|
||||||
|
|
||||||
import antispam.models.fields
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("core", "0052_preferences_show_my_timetable"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="user",
|
|
||||||
name="email",
|
|
||||||
field=antispam.models.fields.AntiSpamEmailField(
|
|
||||||
max_length=254, unique=True, verbose_name="email address"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="user",
|
|
||||||
name="second_email",
|
|
||||||
field=antispam.models.fields.AntiSpamEmailField(
|
|
||||||
blank=True,
|
|
||||||
max_length=254,
|
|
||||||
null=True,
|
|
||||||
verbose_name="second email address",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -769,6 +769,14 @@ class UserBan(models.Model):
|
|||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"Ban of user {self.user.id}"
|
return f"Ban of user {self.user.id}"
|
||||||
|
|
||||||
|
def save(self, *args, **kwargs):
|
||||||
|
if self.ban_group_id in [
|
||||||
|
settings.SITH_GROUP_BANNED_COUNTER_ID,
|
||||||
|
settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||||
|
]:
|
||||||
|
self.user.counters.clear()
|
||||||
|
return super().save(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class GlobalPermissionRights(models.Model):
|
class GlobalPermissionRights(models.Model):
|
||||||
"""Little hack to have permissions not linked to a specific db table."""
|
"""Little hack to have permissions not linked to a specific db table."""
|
||||||
|
|||||||
@@ -321,6 +321,7 @@ class UserTabTestView(UserTabsMixin, DetailView): ...
|
|||||||
"edit",
|
"edit",
|
||||||
"prefs",
|
"prefs",
|
||||||
"clubs",
|
"clubs",
|
||||||
|
"timetable",
|
||||||
"stats",
|
"stats",
|
||||||
"account",
|
"account",
|
||||||
],
|
],
|
||||||
@@ -337,6 +338,7 @@ class UserTabTestView(UserTabsMixin, DetailView): ...
|
|||||||
"edit",
|
"edit",
|
||||||
"prefs",
|
"prefs",
|
||||||
"clubs",
|
"clubs",
|
||||||
|
"timetable",
|
||||||
"groups",
|
"groups",
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -370,6 +372,7 @@ def test_displayed_user_self_tabs(user_factory, expected_tabs: list[str]):
|
|||||||
"edit",
|
"edit",
|
||||||
"prefs",
|
"prefs",
|
||||||
"clubs",
|
"clubs",
|
||||||
|
"timetable",
|
||||||
"groups",
|
"groups",
|
||||||
"stats",
|
"stats",
|
||||||
"account",
|
"account",
|
||||||
|
|||||||
@@ -275,6 +275,27 @@ class UserTabsMixin(TabedViewMixin):
|
|||||||
"name": _("Clubs"),
|
"name": _("Clubs"),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
if user == self.request.user and not user.timetables.exists():
|
||||||
|
tab_list.append(
|
||||||
|
{
|
||||||
|
"url": reverse("timetable:generator"),
|
||||||
|
"slug": "timetable",
|
||||||
|
"name": _("Timetable"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif user == self.request.user or (
|
||||||
|
self.request.user.has_perm("timetable.view_timetable")
|
||||||
|
and user.preferences.show_my_timetable
|
||||||
|
):
|
||||||
|
tab_list.append(
|
||||||
|
{
|
||||||
|
"url": reverse(
|
||||||
|
"core:user_timetable", kwargs={"user_id": user.id}
|
||||||
|
),
|
||||||
|
"slug": "timetable",
|
||||||
|
"name": _("Timetable"),
|
||||||
|
}
|
||||||
|
)
|
||||||
if self.request.user.is_owner(user):
|
if self.request.user.is_owner(user):
|
||||||
tab_list.append(
|
tab_list.append(
|
||||||
{
|
{
|
||||||
|
|||||||
+37
-4
@@ -3,7 +3,7 @@ import math
|
|||||||
import uuid
|
import uuid
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date, datetime, timezone
|
||||||
from typing import TYPE_CHECKING, ClassVar
|
from typing import TYPE_CHECKING, ClassVar, LiteralString
|
||||||
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from django import forms
|
from django import forms
|
||||||
@@ -19,7 +19,7 @@ from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
|||||||
|
|
||||||
from club.models import Club
|
from club.models import Club
|
||||||
from club.widgets.ajax_select import AutoCompleteSelectClub
|
from club.widgets.ajax_select import AutoCompleteSelectClub
|
||||||
from core.models import User, UserQuerySet
|
from core.models import User, UserBan, UserQuerySet
|
||||||
from core.views import LoginForm
|
from core.views import LoginForm
|
||||||
from core.views.forms import (
|
from core.views.forms import (
|
||||||
FutureDateTimeField,
|
FutureDateTimeField,
|
||||||
@@ -257,6 +257,41 @@ class CounterEditForm(forms.ModelForm):
|
|||||||
countersellers__is_regular=False
|
countersellers__is_regular=False
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
|
def clean_sellers(self, field: LiteralString):
|
||||||
|
sellers = self.cleaned_data[field]
|
||||||
|
bans = [
|
||||||
|
settings.SITH_GROUP_BANNED_COUNTER_ID,
|
||||||
|
settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||||
|
]
|
||||||
|
invalid_sellers = sellers.annotate(
|
||||||
|
is_banned=Exists(
|
||||||
|
UserBan.objects.filter(user=OuterRef("pk"), ban_group__in=bans)
|
||||||
|
)
|
||||||
|
).filter(Q(is_banned=True) | Q(date_of_birth=None))
|
||||||
|
for seller in invalid_sellers:
|
||||||
|
if seller.is_banned:
|
||||||
|
self.add_error(
|
||||||
|
field,
|
||||||
|
ValidationError(
|
||||||
|
_("%(user)s is banned.") % {"user": seller.get_full_name()}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if not seller.date_of_birth:
|
||||||
|
self.add_error(
|
||||||
|
field,
|
||||||
|
ValidationError(
|
||||||
|
_("%(user)s has not filled its birthdate.")
|
||||||
|
% {"user": seller.get_full_name()}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return sellers
|
||||||
|
|
||||||
|
def clean_sellers_regular(self):
|
||||||
|
return self.clean_sellers("sellers_regular")
|
||||||
|
|
||||||
|
def clean_sellers_temporary(self):
|
||||||
|
return self.clean_sellers("sellers_temporary")
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
regular: UserQuerySet = self.cleaned_data["sellers_regular"]
|
regular: UserQuerySet = self.cleaned_data["sellers_regular"]
|
||||||
temporary: UserQuerySet = self.cleaned_data["sellers_temporary"]
|
temporary: UserQuerySet = self.cleaned_data["sellers_temporary"]
|
||||||
@@ -472,8 +507,6 @@ class ProductForm(forms.ModelForm):
|
|||||||
self.fields["name"].widget.attrs["autofocus"] = "autofocus"
|
self.fields["name"].widget.attrs["autofocus"] = "autofocus"
|
||||||
if self.instance.id:
|
if self.instance.id:
|
||||||
self.fields["counters"].initial = self.instance.counters.all()
|
self.fields["counters"].initial = self.instance.counters.all()
|
||||||
if hasattr(self.instance, "formula"):
|
|
||||||
self.formula_init(self.instance.formula)
|
|
||||||
self.price_formset = ProductPriceFormSet(
|
self.price_formset = ProductPriceFormSet(
|
||||||
*args, instance=self.instance, prefix="price", **kwargs
|
*args, instance=self.instance, prefix="price", **kwargs
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -405,7 +405,7 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
self.assertRedirects(res, self.counter.get_absolute_url())
|
self.assertRedirects(res, self.counter.get_absolute_url())
|
||||||
assert self.updated_amount(self.customer) == Decimal(8)
|
assert self.updated_amount(self.customer) == Decimal(8)
|
||||||
|
|
||||||
def test_click_alcool_unauthorized(self):
|
def test_click_alcohol_unauthorized(self):
|
||||||
self.login_in_bar()
|
self.login_in_bar()
|
||||||
|
|
||||||
for user in [self.underage_customer, self.banned_alcohol_customer]:
|
for user in [self.underage_customer, self.banned_alcohol_customer]:
|
||||||
@@ -423,6 +423,31 @@ class TestCounterClick(TestFullClickBase):
|
|||||||
|
|
||||||
assert self.updated_amount(user) == Decimal(7)
|
assert self.updated_amount(user) == Decimal(7)
|
||||||
|
|
||||||
|
def test_click_no_alcohol_if_minor_barman(self):
|
||||||
|
"""Test that no age restricted product can be sold if the barman is minor."""
|
||||||
|
set_age(self.barmen, 17)
|
||||||
|
self.login_in_bar(self.barmen)
|
||||||
|
res = self.client.get(
|
||||||
|
reverse(
|
||||||
|
"counter:click",
|
||||||
|
kwargs={"counter_id": self.counter.id, "user_id": self.customer.id},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
messages = list(get_messages(res.wsgi_request))
|
||||||
|
assert len(messages) == 1
|
||||||
|
assert messages[0].level == DEFAULT_LEVELS["WARNING"]
|
||||||
|
assert messages[0].message == (
|
||||||
|
"Un mineur est barman sur cet appareil, "
|
||||||
|
"vous ne pouvez donc pas vendre d'alcool actuellement."
|
||||||
|
)
|
||||||
|
assert res.context_data["prices"] == [
|
||||||
|
self.gift,
|
||||||
|
self.snack,
|
||||||
|
self.cons,
|
||||||
|
self.dcons,
|
||||||
|
]
|
||||||
|
|
||||||
def test_click_unauthorized_customer(self):
|
def test_click_unauthorized_customer(self):
|
||||||
self.login_in_bar()
|
self.login_in_bar()
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from dateutil.utils import today
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
@@ -6,7 +9,7 @@ from model_bakery import baker
|
|||||||
|
|
||||||
from club.models import Membership
|
from club.models import Membership
|
||||||
from core.baker_recipes import subscriber_user
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import Group, User
|
from core.models import Group, User, UserBan
|
||||||
from counter.baker_recipes import product_recipe
|
from counter.baker_recipes import product_recipe
|
||||||
from counter.forms import CounterEditForm
|
from counter.forms import CounterEditForm
|
||||||
from counter.models import Counter, CounterSellers
|
from counter.models import Counter, CounterSellers
|
||||||
@@ -18,7 +21,11 @@ class TestEditCounterSellers(TestCase):
|
|||||||
cls.counter = baker.make(Counter, type="BAR")
|
cls.counter = baker.make(Counter, type="BAR")
|
||||||
cls.products = product_recipe.make(_quantity=2, _bulk_create=True)
|
cls.products = product_recipe.make(_quantity=2, _bulk_create=True)
|
||||||
cls.counter.products.add(*cls.products)
|
cls.counter.products.add(*cls.products)
|
||||||
users = subscriber_user.make(_quantity=6, _bulk_create=True)
|
users = subscriber_user.make(
|
||||||
|
date_of_birth=today() - timedelta(days=365 * 20),
|
||||||
|
_quantity=6,
|
||||||
|
_bulk_create=True,
|
||||||
|
)
|
||||||
cls.regular_barmen = users[:2]
|
cls.regular_barmen = users[:2]
|
||||||
cls.tmp_barmen = users[2:4]
|
cls.tmp_barmen = users[2:4]
|
||||||
cls.not_barmen = users[4:]
|
cls.not_barmen = users[4:]
|
||||||
@@ -128,6 +135,54 @@ class TestEditCounterSellers(TestCase):
|
|||||||
self.counter.sellers.filter(countersellers__is_regular=False)
|
self.counter.sellers.filter(countersellers__is_regular=False)
|
||||||
) == set(self.tmp_barmen)
|
) == set(self.tmp_barmen)
|
||||||
|
|
||||||
|
def test_barman_without_birthdate(self):
|
||||||
|
"""Test that users without a birthdate cannot be sellers."""
|
||||||
|
user = subscriber_user.make()
|
||||||
|
form = CounterEditForm(
|
||||||
|
data={
|
||||||
|
"sellers_regular": [*self.regular_barmen, user],
|
||||||
|
"sellers_temporary": self.tmp_barmen,
|
||||||
|
"products": self.products,
|
||||||
|
},
|
||||||
|
instance=self.counter,
|
||||||
|
user=self.operator,
|
||||||
|
)
|
||||||
|
assert not form.is_valid()
|
||||||
|
assert form.errors == {
|
||||||
|
"sellers_regular": [
|
||||||
|
f"{user.get_full_name()} n'a pas renseigné sa date de naissance."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_banned_barman_forbidden(self):
|
||||||
|
"""Test that users with a counter ban cannot be sellers."""
|
||||||
|
UserBan.objects.create(
|
||||||
|
user=self.not_barmen[0],
|
||||||
|
ban_group_id=settings.SITH_GROUP_BANNED_COUNTER_ID,
|
||||||
|
reason="ban comptoir",
|
||||||
|
)
|
||||||
|
UserBan.objects.create(
|
||||||
|
user=self.not_barmen[1],
|
||||||
|
ban_group_id=settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||||
|
reason="ban comptoir",
|
||||||
|
)
|
||||||
|
form = CounterEditForm(
|
||||||
|
data={
|
||||||
|
"sellers_regular": [*self.regular_barmen, *self.not_barmen[0:2]],
|
||||||
|
"sellers_temporary": self.tmp_barmen,
|
||||||
|
"products": self.products,
|
||||||
|
},
|
||||||
|
instance=self.counter,
|
||||||
|
user=self.operator,
|
||||||
|
)
|
||||||
|
assert not form.is_valid()
|
||||||
|
assert form.errors == {
|
||||||
|
"sellers_regular": [
|
||||||
|
f"{self.not_barmen[0].get_full_name()} est banni.",
|
||||||
|
f"{self.not_barmen[1].get_full_name()} est banni.",
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class TestEditCounterProducts(TestCase):
|
class TestEditCounterProducts(TestCase):
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -145,7 +145,7 @@ class TestStudentCard(TestCase):
|
|||||||
|
|
||||||
self.login_in_counter()
|
self.login_in_counter()
|
||||||
barman = subscriber_user.make()
|
barman = subscriber_user.make()
|
||||||
self.counter.sellers.add(barman)
|
self.counter.sellers.add(barman, through_defaults={"is_regular": True})
|
||||||
# We want to test sending requests from another counter while
|
# We want to test sending requests from another counter while
|
||||||
# we are currently registered to another counter
|
# we are currently registered to another counter
|
||||||
# so we connect to a counter and
|
# so we connect to a counter and
|
||||||
|
|||||||
+78
-4
@@ -43,8 +43,8 @@ from counter.views.mixins import CounterTabsMixin
|
|||||||
from counter.views.student_card import StudentCardFormFragment
|
from counter.views.student_card import StudentCardFormFragment
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
from django.http import HttpRequest
|
||||||
from django.utils.safestring import SafeString
|
from django.utils.safestring import SafeString
|
||||||
from ninja.main import HttpRequest
|
|
||||||
|
|
||||||
from core.models import User
|
from core.models import User
|
||||||
|
|
||||||
@@ -60,9 +60,70 @@ def get_operator(request: HttpRequest, counter: Counter, customer: Customer) ->
|
|||||||
class CounterClick(
|
class CounterClick(
|
||||||
CounterTabsMixin, UseFragmentsMixin, CanViewMixin, SingleObjectMixin, FormView
|
CounterTabsMixin, UseFragmentsMixin, CanViewMixin, SingleObjectMixin, FormView
|
||||||
):
|
):
|
||||||
"""The click view
|
"""The click view.
|
||||||
This is a detail view not to have to worry about loading the counter
|
|
||||||
Everything is made by hand in the post method.
|
This page is reached from the counter main page, after selecting
|
||||||
|
the user who is purchasing stuff.
|
||||||
|
|
||||||
|
# Counter access
|
||||||
|
|
||||||
|
Who can perform barman actions depends on the type of the counter :
|
||||||
|
|
||||||
|
- for eboutic counters, no barman access at all is granted ;
|
||||||
|
it's just a 404, as there should be only one eboutic,
|
||||||
|
accessible only at `/eboutic/`
|
||||||
|
- office counters are accessible to the board members of the
|
||||||
|
club owning the counter and to users that have been
|
||||||
|
explicitly added to the sellers of this counter.
|
||||||
|
- bar counters are accessible to users that have been added to
|
||||||
|
the counter sellers and that are currently logged as barmen
|
||||||
|
on the current device.
|
||||||
|
|
||||||
|
The bar case is really tricky,
|
||||||
|
as it doesn't use the usual django auth backend.
|
||||||
|
Barmen must not be logged in as regular users,
|
||||||
|
but as barmen, granting the session some special privileges,
|
||||||
|
even in the case where no regular user is logged in.
|
||||||
|
|
||||||
|
This is because of two reasons :
|
||||||
|
|
||||||
|
- we track the barmen connection, for logging,
|
||||||
|
statistics and dick contest purposes.
|
||||||
|
We want to know who was barman, where and when,
|
||||||
|
as barmen are accountable of what happens during their duty.
|
||||||
|
- multiple users must be able to log on the same device,
|
||||||
|
while keeping the session anonymous.
|
||||||
|
The bar PC must be a reliable way for any barman to click users,
|
||||||
|
but without requiring a user session.
|
||||||
|
Just imagine if someone who is superuser had to log in with
|
||||||
|
all its privileges on a device everyone can access.
|
||||||
|
|
||||||
|
# Available items
|
||||||
|
|
||||||
|
A counter can have multiple products.
|
||||||
|
A product can have multiple prices.
|
||||||
|
To select what the user can buy, we select
|
||||||
|
all the prices that can be applied to the current
|
||||||
|
customer, among the products of the counter.
|
||||||
|
The price selection logic is described in
|
||||||
|
[PriceQuerySet][counter.models.PriceQuerySet].
|
||||||
|
|
||||||
|
On top of that, some additional rules are applied,
|
||||||
|
because alcohol can be sold on counters :
|
||||||
|
|
||||||
|
- if the customer is minor (or has not filled its birthdate)
|
||||||
|
age restricted products are removed
|
||||||
|
([L.3342-1, Code de la santé publique](https://www.legifrance.gouv.fr/codes/article_lc/LEGIARTI000031927682))
|
||||||
|
- if any barman on the current device is minor,
|
||||||
|
age restricted products are also removed
|
||||||
|
([L.3336-4, Code de la santé publique](https://www.legifrance.gouv.fr/codes/article_lc/LEGIARTI000048654800))
|
||||||
|
|
||||||
|
The minor barman case is a little bit unclear, legally speaking,
|
||||||
|
as barmen are volunteers, but the law speaks only of employees and interns.
|
||||||
|
As such, we don't apply the law to its full extent.
|
||||||
|
It would be harsh for young students not to be able to
|
||||||
|
be barmen at the MDE, where no alcohol at all is sold during daytime.
|
||||||
|
However, we restrict items that can be sold as a token of good will.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
model = Counter
|
model = Counter
|
||||||
@@ -111,6 +172,19 @@ class CounterClick(
|
|||||||
return redirect(obj) # Redirect to counter
|
return redirect(obj) # Redirect to counter
|
||||||
|
|
||||||
self.prices = list(obj.get_prices_for(self.customer))
|
self.prices = list(obj.get_prices_for(self.customer))
|
||||||
|
if any(user.age < 18 for user in request.barmen):
|
||||||
|
# users without a birthdate cannot be sellers on counters,
|
||||||
|
# so the `user.age == 0` case shouldn't happen
|
||||||
|
filtered = [p for p in self.prices if p.product.limit_age < 18]
|
||||||
|
if len(filtered) != len(self.prices):
|
||||||
|
self.prices = filtered
|
||||||
|
messages.warning(
|
||||||
|
request,
|
||||||
|
_(
|
||||||
|
"A minor is barman on this on this device, "
|
||||||
|
"so you cannot currently sell alcohol."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|||||||
-65
@@ -1,65 +0,0 @@
|
|||||||
{
|
|
||||||
"nodes": {
|
|
||||||
"devenv": {
|
|
||||||
"locked": {
|
|
||||||
"dir": "src/modules",
|
|
||||||
"lastModified": 1790181305,
|
|
||||||
"narHash": "sha256-0L4uJEyhPImq8GsiDki5AtpOcCT2O7q0V1yXB1ZAbgg=",
|
|
||||||
"owner": "cachix",
|
|
||||||
"repo": "devenv",
|
|
||||||
"rev": "9272f920ccb6bfc72e87b3c712caffcf3cacecd8",
|
|
||||||
"type": "github"
|
|
||||||
},
|
|
||||||
"original": {
|
|
||||||
"dir": "src/modules",
|
|
||||||
"owner": "cachix",
|
|
||||||
"repo": "devenv",
|
|
||||||
"type": "github"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nixpkgs": {
|
|
||||||
"inputs": {
|
|
||||||
"nixpkgs-src": "nixpkgs-src"
|
|
||||||
},
|
|
||||||
"locked": {
|
|
||||||
"lastModified": 1789506231,
|
|
||||||
"narHash": "sha256-vNkJbtmqyBfFhn/HnzQo4ROuoyYWuy/allqTfJb4kMY=",
|
|
||||||
"owner": "cachix",
|
|
||||||
"repo": "devenv-nixpkgs",
|
|
||||||
"rev": "c2f38fe7f9e04d9aadd354d380f2bd40531d9737",
|
|
||||||
"type": "github"
|
|
||||||
},
|
|
||||||
"original": {
|
|
||||||
"owner": "cachix",
|
|
||||||
"ref": "rolling",
|
|
||||||
"repo": "devenv-nixpkgs",
|
|
||||||
"type": "github"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nixpkgs-src": {
|
|
||||||
"flake": false,
|
|
||||||
"locked": {
|
|
||||||
"lastModified": 1789370336,
|
|
||||||
"narHash": "sha256-6RSEDHIWQtesQKWSu5qRai8L2h4KgCgMEfJHstW99G4=",
|
|
||||||
"owner": "NixOS",
|
|
||||||
"repo": "nixpkgs",
|
|
||||||
"rev": "c7def046b9a883d46974757852106483d741586f",
|
|
||||||
"type": "github"
|
|
||||||
},
|
|
||||||
"original": {
|
|
||||||
"owner": "NixOS",
|
|
||||||
"ref": "nixpkgs-unstable",
|
|
||||||
"repo": "nixpkgs",
|
|
||||||
"type": "github"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"root": {
|
|
||||||
"inputs": {
|
|
||||||
"devenv": "devenv",
|
|
||||||
"nixpkgs": "nixpkgs"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"root": "root",
|
|
||||||
"version": 7
|
|
||||||
}
|
|
||||||
-335
@@ -1,335 +0,0 @@
|
|||||||
# devenv.nix
|
|
||||||
{ pkgs, lib, config, inputs, ... }:
|
|
||||||
|
|
||||||
let
|
|
||||||
pythonVersion = pkgs.python314;
|
|
||||||
|
|
||||||
xapian2 = import ./nix/xapian-2.nix {
|
|
||||||
inherit pkgs;
|
|
||||||
python3 = pythonVersion;
|
|
||||||
};
|
|
||||||
|
|
||||||
# Make a package
|
|
||||||
xapianPythonPkg = pkgs.python314Packages.buildPythonPackage {
|
|
||||||
pname = "xapian";
|
|
||||||
version = "2.1.0";
|
|
||||||
format = "other";
|
|
||||||
src = xapian2.xapianBindings;
|
|
||||||
installPhase = ''
|
|
||||||
mkdir -p $out/lib/python3.14/site-packages
|
|
||||||
cp -r $src/lib/python3.14/site-packages/* $out/lib/python3.14/site-packages/
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
pythonWithXapian = pythonVersion.withPackages (ps: [
|
|
||||||
xapianPythonPkg
|
|
||||||
]);
|
|
||||||
in
|
|
||||||
{
|
|
||||||
|
|
||||||
# https://devenv.sh/basics/
|
|
||||||
env.GREET = "devenv";
|
|
||||||
env.HTTPS = "off";
|
|
||||||
env.SITH_DEBUG = "true";
|
|
||||||
env.SECRET_KEY = "(4sjxvhz@m5$0a$j0_pqicnc$s!vbve)z+&++m%g%bjhlz4+g2";
|
|
||||||
env.REDIS_PORT = toString config.services.redis.port;
|
|
||||||
env.CACHE_URL = "redis://127.0.0.1:${toString config.services.redis.port}/0";
|
|
||||||
env.TASK_BROKER_URL = "redis://127.0.0.1:${toString config.services.redis.port}/1";
|
|
||||||
|
|
||||||
# https://devenv.sh/packages/
|
|
||||||
packages = [
|
|
||||||
pkgs.git
|
|
||||||
pkgs.pkg-config
|
|
||||||
pkgs.openssl
|
|
||||||
pkgs.libjpeg
|
|
||||||
pkgs.zlib
|
|
||||||
pkgs.gettext
|
|
||||||
pkgs.gnumake
|
|
||||||
pkgs.gcc
|
|
||||||
];
|
|
||||||
|
|
||||||
|
|
||||||
languages.python = {
|
|
||||||
enable = true;
|
|
||||||
package = pythonWithXapian; # use custom package.
|
|
||||||
lsp.enable = true;
|
|
||||||
venv.enable = true;
|
|
||||||
uv = {
|
|
||||||
enable = true;
|
|
||||||
sync = {
|
|
||||||
enable = true;
|
|
||||||
groups = [
|
|
||||||
"dev"
|
|
||||||
"tests"
|
|
||||||
"docs"
|
|
||||||
];
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
languages.javascript = {
|
|
||||||
enable = true;
|
|
||||||
lsp.enable = true;
|
|
||||||
package = pkgs.nodejs_24;
|
|
||||||
npm = {
|
|
||||||
enable = true;
|
|
||||||
install.enable = true;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
services.redis = {
|
|
||||||
enable = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
processes = {
|
|
||||||
server = {
|
|
||||||
ports = {
|
|
||||||
sith.allocate = 8000;
|
|
||||||
};
|
|
||||||
exec = "uv run $DEVENV_ROOT/manage.py runserver 0.0.0.0:${toString config.processes.server.ports.sith.value}";
|
|
||||||
restart = {
|
|
||||||
on = "always";
|
|
||||||
};
|
|
||||||
after = [ "devenv:processes:redis" ];
|
|
||||||
};
|
|
||||||
|
|
||||||
celery = {
|
|
||||||
exec = "uv run celery -A sith worker --beat -l INFO";
|
|
||||||
restart = {
|
|
||||||
on = "always";
|
|
||||||
};
|
|
||||||
after = [ "devenv:processes:redis" ];
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
profiles.dev = {
|
|
||||||
module = {
|
|
||||||
env.DATABASE_URL = "sqlite:///db.sqlite3";
|
|
||||||
env.PROCFILE_STATIC = "Procfile.static";
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
profiles.full = {
|
|
||||||
module = {
|
|
||||||
|
|
||||||
packages = [
|
|
||||||
pkgs.libpq
|
|
||||||
pkgs.postgrest
|
|
||||||
];
|
|
||||||
|
|
||||||
languages.python.package = lib.mkForce (pythonVersion.withPackages (ps: [
|
|
||||||
xapianPythonPkg
|
|
||||||
ps.psycopg
|
|
||||||
]));
|
|
||||||
|
|
||||||
env.PROCFILE_STATIC = "";
|
|
||||||
|
|
||||||
# Postgress
|
|
||||||
services.postgres = {
|
|
||||||
enable = true;
|
|
||||||
initialDatabases = [
|
|
||||||
{
|
|
||||||
name = "sith";
|
|
||||||
}
|
|
||||||
];
|
|
||||||
initialScript = ''
|
|
||||||
CREATE USER sith WITH PASSWORD 'password';
|
|
||||||
|
|
||||||
ALTER ROLE sith SET client_encoding TO 'utf8';
|
|
||||||
ALTER ROLE sith SET default_transaction_isolation TO 'read committed';
|
|
||||||
ALTER ROLE sith SET timezone TO 'UTC';
|
|
||||||
|
|
||||||
GRANT ALL PRIVILEGES ON DATABASE sith TO sith;
|
|
||||||
GRANT ALL PRIVILEGES ON SCHEMA public TO sith;
|
|
||||||
'';
|
|
||||||
settings = {
|
|
||||||
listen_addresses = lib.mkForce "127.0.0.1";
|
|
||||||
};
|
|
||||||
};
|
|
||||||
env.DATABASE_URL = "postgres://sith:password@127.0.0.1:${toString config.services.postgres.port}/sith";
|
|
||||||
processes.server.after = [ "devenv:processes:redis" "devenv:processes:postgres" ];
|
|
||||||
|
|
||||||
# Nginx
|
|
||||||
services.nginx = {
|
|
||||||
enable = true;
|
|
||||||
eventsConfig = ''
|
|
||||||
worker_connections 1024;
|
|
||||||
'';
|
|
||||||
httpConfig = ''
|
|
||||||
server {
|
|
||||||
listen 127.0.0.1:8001;
|
|
||||||
|
|
||||||
server_name localhost;
|
|
||||||
|
|
||||||
# Gestion des fichiers statiques
|
|
||||||
location /static/ {
|
|
||||||
root ${config.devenv.root};
|
|
||||||
}
|
|
||||||
|
|
||||||
# Fichiers médias publics
|
|
||||||
location ~ ^/data/(products|com|club_logos|upload)/ {
|
|
||||||
root ${config.devenv.root};
|
|
||||||
}
|
|
||||||
|
|
||||||
# Fichiers médias privés/protégés
|
|
||||||
location ~ ^/data/(SAS|profiles|users|.compressed|.thumbnails)/ {
|
|
||||||
internal;
|
|
||||||
root ${config.devenv.root};
|
|
||||||
}
|
|
||||||
|
|
||||||
# On redirige tout le reste vers Django (sur le port 8001)
|
|
||||||
location / {
|
|
||||||
proxy_pass http://127.0.0.1:${toString config.processes.server.ports.sith.value};
|
|
||||||
proxy_set_header Host $http_host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
# Watcher for statics
|
|
||||||
processes = {
|
|
||||||
"watcher" = {
|
|
||||||
exec = "uv run $DEVENV_ROOT/manage.py collectstatic --noinput";
|
|
||||||
watch = {
|
|
||||||
paths = [
|
|
||||||
./.
|
|
||||||
];
|
|
||||||
extensions = [
|
|
||||||
"js"
|
|
||||||
"css"
|
|
||||||
"scss"
|
|
||||||
"ts"
|
|
||||||
];
|
|
||||||
ignore = [
|
|
||||||
".devenv/*"
|
|
||||||
".git/*"
|
|
||||||
"node_modules/*"
|
|
||||||
"staticfiles/*"
|
|
||||||
"static/*"
|
|
||||||
];
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
enterShell = ''
|
|
||||||
psql -d sith -c "GRANT ALL PRIVILEGES ON SCHEMA public to sith";
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
tasks = {
|
|
||||||
|
|
||||||
# Init Prject
|
|
||||||
"project:init" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py setup
|
|
||||||
'';
|
|
||||||
before = [ "tras:compile" ];
|
|
||||||
};
|
|
||||||
|
|
||||||
# Install Translations
|
|
||||||
"tras:compile" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py compilemessages
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
scripts = {
|
|
||||||
|
|
||||||
"db:migrate" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py migrate "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"db:make-migration" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py makemigrations "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"db:squash" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py squasmigrations "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"db:create-su" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py createsuperuser "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"db:populate" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py populate "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"db:populate-more" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py populate_more "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"trans:make" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py makemessages --locale=fr -e py,jinja --ignore=.venv --ignore=node_modules --add-location=file
|
|
||||||
uv run $DEVENV_ROOT/manage.py makemessages --locale=fr -d djangojs -e js,ts --ignore=.venv --ignore=node_modules --ignore=staticfiles/generated --add-location=file
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"trans:compile" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py compilemessages "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"project:line-cont" = {
|
|
||||||
exec = ''
|
|
||||||
cloc $DEVENV_ROOT --exclude-dir=doc,env "$@"
|
|
||||||
'';
|
|
||||||
packages = [ pkgs.cloc ];
|
|
||||||
};
|
|
||||||
|
|
||||||
"project:pre-commit" = {
|
|
||||||
exec = ''
|
|
||||||
uv run pre-commit run
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"test:run" = {
|
|
||||||
exec = ''
|
|
||||||
uv run pytest "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"server:anti-spam-update" = {
|
|
||||||
exec = ''
|
|
||||||
uv run $DEVENV_ROOT/manage.py update_spam_database "$@"
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
"start-pycharm" = {
|
|
||||||
exec = ''
|
|
||||||
2>/dev/null 1>&2 pycharm &
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
enterTest = ''
|
|
||||||
|
|
||||||
'';
|
|
||||||
|
|
||||||
enterShell = ''
|
|
||||||
# Create a symlink to the Python virtual environment for IDE compatibility
|
|
||||||
if [ ! -L "$DEVENV_ROOT/venv" ]; then
|
|
||||||
ln -s "$DEVENV_STATE/venv/" "$DEVENV_ROOT/venv"
|
|
||||||
fi
|
|
||||||
'';
|
|
||||||
|
|
||||||
}
|
|
||||||
-20
@@ -1,20 +0,0 @@
|
|||||||
# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json
|
|
||||||
inputs:
|
|
||||||
nixpkgs:
|
|
||||||
url: github:cachix/devenv-nixpkgs/rolling
|
|
||||||
|
|
||||||
# If you're using non-OSS software, you can set allow_unfree to true.
|
|
||||||
allow_unfree: true
|
|
||||||
|
|
||||||
# If you're not willing to allow unsupported packages:
|
|
||||||
# allow_unsupported_system: false
|
|
||||||
|
|
||||||
# If you're willing to use a package that's vulnerable
|
|
||||||
# permitted_insecure_packages:
|
|
||||||
# - "openssl-1.1.1w"
|
|
||||||
|
|
||||||
# If you have more than one devenv you can merge them
|
|
||||||
#imports:
|
|
||||||
# - ./backend
|
|
||||||
|
|
||||||
profile: "dev"
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
::: counter.views
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
::: counter.views.click
|
||||||
|
handler: python
|
||||||
|
options:
|
||||||
|
members:
|
||||||
|
- CounterClick
|
||||||
|
- RefillingCreateView
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
::: counter.views.home
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
::: counter.views.mixins
|
||||||
|
handler: python
|
||||||
|
options:
|
||||||
|
heading_level: 3
|
||||||
|
members:
|
||||||
|
- CounterTabsMixin
|
||||||
|
- CounterAdminTabsMixin
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
::: counter.views.admin
|
||||||
|
::: counter.views.cash
|
||||||
|
::: counter.views.eticket
|
||||||
|
::: counter.views.invoice
|
||||||
|
::: counter.views.student_card
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
msgid ""
|
msgid ""
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Report-Msgid-Bugs-To: \n"
|
"Report-Msgid-Bugs-To: \n"
|
||||||
"POT-Creation-Date: 2026-11-06 17:22+0100\n"
|
"POT-Creation-Date: 2026-11-14 13:59+0100\n"
|
||||||
"PO-Revision-Date: 2016-07-18\n"
|
"PO-Revision-Date: 2016-07-18\n"
|
||||||
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
||||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||||
@@ -251,6 +251,10 @@ msgstr "Inactif"
|
|||||||
msgid "All clubs"
|
msgid "All clubs"
|
||||||
msgstr "Tous les clubs"
|
msgstr "Tous les clubs"
|
||||||
|
|
||||||
|
#: club/forms.py
|
||||||
|
msgid "Provide an english name for non-french speaking users."
|
||||||
|
msgstr "Fournissez un nom anglais pour les utilisateurs non-francophones."
|
||||||
|
|
||||||
#: club/models.py
|
#: club/models.py
|
||||||
msgid "slug name"
|
msgid "slug name"
|
||||||
msgstr "nom slug"
|
msgstr "nom slug"
|
||||||
@@ -340,6 +344,10 @@ msgid "A role cannot be in the presidency while not being in the board"
|
|||||||
msgstr ""
|
msgstr ""
|
||||||
"Un rôle ne peut pas appartenir à la présidence sans être dans le bureau"
|
"Un rôle ne peut pas appartenir à la présidence sans être dans le bureau"
|
||||||
|
|
||||||
|
#: club/models.py
|
||||||
|
msgid "There is already a role with that name"
|
||||||
|
msgstr "Il existe déjà un rôle avec ce nom"
|
||||||
|
|
||||||
#: club/models.py
|
#: club/models.py
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid "Role %(role)s cannot be placed below a member role"
|
msgid "Role %(role)s cannot be placed below a member role"
|
||||||
@@ -3257,6 +3265,16 @@ msgstr ""
|
|||||||
"Si vous souhaitez ajouter sur ce comptoir un produit qui n'appartient pas à "
|
"Si vous souhaitez ajouter sur ce comptoir un produit qui n'appartient pas à "
|
||||||
"votre club, vous devriez demander à un admin."
|
"votre club, vous devriez demander à un admin."
|
||||||
|
|
||||||
|
#: counter/forms.py
|
||||||
|
#, python-format
|
||||||
|
msgid "%(user)s is banned."
|
||||||
|
msgstr "%(user)s est banni."
|
||||||
|
|
||||||
|
#: counter/forms.py
|
||||||
|
#, python-format
|
||||||
|
msgid "%(user)s has not filled its birthdate."
|
||||||
|
msgstr "%(user)s n'a pas renseigné sa date de naissance."
|
||||||
|
|
||||||
#: counter/forms.py
|
#: counter/forms.py
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid ""
|
msgid ""
|
||||||
@@ -4329,6 +4347,14 @@ msgstr "Nombre de chèque"
|
|||||||
msgid "You cannot click users on this counter"
|
msgid "You cannot click users on this counter"
|
||||||
msgstr "Vous ne pouvez pas cliquer des gens sur ce comptoir"
|
msgstr "Vous ne pouvez pas cliquer des gens sur ce comptoir"
|
||||||
|
|
||||||
|
#: counter/views/click.py
|
||||||
|
msgid ""
|
||||||
|
"A minor is barman on this on this device, so you cannot currently sell "
|
||||||
|
"alcohol."
|
||||||
|
msgstr ""
|
||||||
|
"Un mineur est barman sur cet appareil, vous ne pouvez donc pas vendre "
|
||||||
|
"d'alcool actuellement."
|
||||||
|
|
||||||
#: counter/views/eticket.py
|
#: counter/views/eticket.py
|
||||||
msgid "people(s)"
|
msgid "people(s)"
|
||||||
msgstr "personne(s)"
|
msgstr "personne(s)"
|
||||||
@@ -5482,14 +5508,14 @@ msgstr "Photos de %(user_name)s"
|
|||||||
msgid "Download all my pictures"
|
msgid "Download all my pictures"
|
||||||
msgstr "Télécharger toutes mes photos"
|
msgstr "Télécharger toutes mes photos"
|
||||||
|
|
||||||
#: sith/settings.py
|
|
||||||
msgid "English"
|
|
||||||
msgstr "Anglais"
|
|
||||||
|
|
||||||
#: sith/settings.py
|
#: sith/settings.py
|
||||||
msgid "French"
|
msgid "French"
|
||||||
msgstr "Français"
|
msgstr "Français"
|
||||||
|
|
||||||
|
#: sith/settings.py
|
||||||
|
msgid "English"
|
||||||
|
msgstr "Anglais"
|
||||||
|
|
||||||
#: sith/settings.py
|
#: sith/settings.py
|
||||||
msgid "TC"
|
msgid "TC"
|
||||||
msgstr "TC"
|
msgstr "TC"
|
||||||
|
|||||||
+5
-1
@@ -113,7 +113,11 @@ nav:
|
|||||||
- reference/core/auth.md
|
- reference/core/auth.md
|
||||||
- counter:
|
- counter:
|
||||||
- reference/counter/models.md
|
- reference/counter/models.md
|
||||||
- reference/counter/views.md
|
- Views:
|
||||||
|
- reference/counter/views/home.md
|
||||||
|
- reference/counter/views/click.md
|
||||||
|
- reference/counter/views/mixins.md
|
||||||
|
- reference/counter/views/others.md
|
||||||
- reference/counter/schemas.md
|
- reference/counter/schemas.md
|
||||||
- eboutic:
|
- eboutic:
|
||||||
- reference/eboutic/models.md
|
- reference/eboutic/models.md
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
{ pkgs, python3 }:
|
|
||||||
|
|
||||||
let
|
|
||||||
version = "2.1.0";
|
|
||||||
|
|
||||||
pythonEnv = python3.withPackages (ps: [
|
|
||||||
ps.sphinx
|
|
||||||
]);
|
|
||||||
|
|
||||||
xapianCore = pkgs.stdenv.mkDerivation rec {
|
|
||||||
pname = "xapian-core";
|
|
||||||
inherit version;
|
|
||||||
|
|
||||||
src = pkgs.fetchurl {
|
|
||||||
url = "https://oligarchy.co.uk/xapian/${version}/xapian-core-${version}.tar.xz";
|
|
||||||
sha256 = "8e1259586d342e3d12b5e1f772e9185a10f2ba16e541566b5c3c239f71b8aacc";
|
|
||||||
};
|
|
||||||
|
|
||||||
nativeBuildInputs = [ pkgs.pkg-config ];
|
|
||||||
buildInputs = [ pkgs.zlib pkgs.util-linux ];
|
|
||||||
|
|
||||||
configureFlags = [ "--enable-shared" ];
|
|
||||||
};
|
|
||||||
|
|
||||||
xapianBindings = pkgs.stdenv.mkDerivation rec {
|
|
||||||
pname = "xapian-bindings";
|
|
||||||
inherit version;
|
|
||||||
|
|
||||||
src = pkgs.fetchurl {
|
|
||||||
url = "https://oligarchy.co.uk/xapian/${version}/xapian-bindings-${version}.tar.xz";
|
|
||||||
sha256 = "f52ec189f13b4fa66ea625a6eb94bb32dd651b9ec806be6a911dda54cbe3875c";
|
|
||||||
};
|
|
||||||
|
|
||||||
nativeBuildInputs = [ pkgs.pkg-config pythonEnv ];
|
|
||||||
buildInputs = [ xapianCore pythonEnv ];
|
|
||||||
|
|
||||||
# Create the output site-packages directory before configuring
|
|
||||||
preConfigure = ''
|
|
||||||
mkdir -p "$out/lib/python3.14/site-packages"
|
|
||||||
'';
|
|
||||||
|
|
||||||
# Tell Autotools exactly where to put the Python binding files
|
|
||||||
configureFlags = [
|
|
||||||
"--with-python3"
|
|
||||||
"XAPIAN_CONFIG=${xapianCore}/bin/xapian-config"
|
|
||||||
"PYTHON3_LIB=$(out)/lib/python3.14/site-packages"
|
|
||||||
];
|
|
||||||
|
|
||||||
installPhase = ''
|
|
||||||
make install
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
in
|
|
||||||
{
|
|
||||||
inherit xapianCore xapianBindings;
|
|
||||||
}
|
|
||||||
@@ -52,6 +52,7 @@ dependencies = [
|
|||||||
"celery[redis]>=5.6.3,<7",
|
"celery[redis]>=5.6.3,<7",
|
||||||
"django-celery-results>=2.6.0,<3",
|
"django-celery-results>=2.6.0,<3",
|
||||||
"django-celery-beat>=2.9.0,<3",
|
"django-celery-beat>=2.9.0,<3",
|
||||||
|
"django-modeltranslation>=0.20.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
|
|||||||
@@ -8,7 +8,10 @@ from django.utils.timezone import localtime
|
|||||||
from model_bakery import baker
|
from model_bakery import baker
|
||||||
from pytest_django.asserts import assertRedirects
|
from pytest_django.asserts import assertRedirects
|
||||||
|
|
||||||
|
from core.baker_recipes import subscriber_user
|
||||||
from core.models import BanGroup, User, UserBan
|
from core.models import BanGroup, User, UserBan
|
||||||
|
from counter.models import Counter
|
||||||
|
from sith import settings
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from django.test import Client
|
from django.test import Client
|
||||||
@@ -33,11 +36,7 @@ def test_ban_user(client: Client, operator: User, expires_at: datetime):
|
|||||||
client.force_login(operator)
|
client.force_login(operator)
|
||||||
user = baker.make(User)
|
user = baker.make(User)
|
||||||
ban_group = BanGroup.objects.first()
|
ban_group = BanGroup.objects.first()
|
||||||
data = {
|
data = {"user": user.id, "ban_group": ban_group.id, "reason": "Being naughty"}
|
||||||
"user": user.id,
|
|
||||||
"ban_group": ban_group.id,
|
|
||||||
"reason": "Being naughty",
|
|
||||||
}
|
|
||||||
if expires_at is not None:
|
if expires_at is not None:
|
||||||
data["expires_at"] = expires_at.strftime("%Y-%m-%d %H:%M")
|
data["expires_at"] = expires_at.strftime("%Y-%m-%d %H:%M")
|
||||||
response = client.post(reverse("rootplace:ban_create"), data)
|
response = client.post(reverse("rootplace:ban_create"), data)
|
||||||
@@ -49,6 +48,24 @@ def test_ban_user(client: Client, operator: User, expires_at: datetime):
|
|||||||
assert bans[0].ban_group == ban_group
|
assert bans[0].ban_group == ban_group
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
def test_ban_counter_ends_barmanship():
|
||||||
|
user = subscriber_user.make()
|
||||||
|
counter = baker.make(Counter)
|
||||||
|
counter.sellers.add(user, through_defaults={"is_regular": True})
|
||||||
|
|
||||||
|
UserBan.objects.create(
|
||||||
|
user=user,
|
||||||
|
ban_group_id=settings.SITH_GROUP_BANNED_SUBSCRIPTION_ID,
|
||||||
|
reason="ban comptoir",
|
||||||
|
)
|
||||||
|
|
||||||
|
# check that we did effectively delete the barmanship
|
||||||
|
# and not the bar itself (better safe than sorry)
|
||||||
|
assert Counter.objects.filter(id=counter.id).exists()
|
||||||
|
assert not user.counters.exists()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_remove_ban(client: Client, operator: User):
|
def test_remove_ban(client: Client, operator: User):
|
||||||
client.force_login(operator)
|
client.force_login(operator)
|
||||||
|
|||||||
+2
-2
@@ -103,6 +103,7 @@ DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
|
|||||||
SITE_ID = 4000
|
SITE_ID = 4000
|
||||||
|
|
||||||
INSTALLED_APPS = (
|
INSTALLED_APPS = (
|
||||||
|
"modeltranslation",
|
||||||
"django.contrib.admin",
|
"django.contrib.admin",
|
||||||
"django.contrib.auth",
|
"django.contrib.auth",
|
||||||
"django.contrib.contenttypes",
|
"django.contrib.contenttypes",
|
||||||
@@ -136,7 +137,6 @@ INSTALLED_APPS = (
|
|||||||
"antispam",
|
"antispam",
|
||||||
"timetable",
|
"timetable",
|
||||||
"api",
|
"api",
|
||||||
"stock",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
MIDDLEWARE = (
|
MIDDLEWARE = (
|
||||||
@@ -286,7 +286,7 @@ LOGGING = {
|
|||||||
|
|
||||||
LANGUAGE_CODE = "fr-FR"
|
LANGUAGE_CODE = "fr-FR"
|
||||||
|
|
||||||
LANGUAGES = [("en", _("English")), ("fr", _("French"))]
|
LANGUAGES = [("fr", _("French")), ("en", _("English"))]
|
||||||
|
|
||||||
TIME_ZONE = "Europe/Paris"
|
TIME_ZONE = "Europe/Paris"
|
||||||
|
|
||||||
|
|||||||
@@ -55,7 +55,6 @@ urlpatterns = [
|
|||||||
path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
|
path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
|
||||||
path("captcha/", include("captcha.urls")),
|
path("captcha/", include("captcha.urls")),
|
||||||
path("edt/", include(("timetable.urls", "timetable"), namespace="timetable")),
|
path("edt/", include(("timetable.urls", "timetable"), namespace="timetable")),
|
||||||
path("stock/", include(("stock.urls", "stock"), namespace="stock")),
|
|
||||||
]
|
]
|
||||||
|
|
||||||
if settings.DEBUG:
|
if settings.DEBUG:
|
||||||
|
|||||||
Whitespace-only changes.
@@ -1,46 +0,0 @@
|
|||||||
from django.contrib import admin
|
|
||||||
|
|
||||||
from stock.models import Stock, StockAction, StockItem, StockItemAction, StockItemStock
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Stock)
|
|
||||||
class StockAdmin(admin.ModelAdmin):
|
|
||||||
list_display = ("name", "club", "can_be_view_by_board", "created_at", "updated_at")
|
|
||||||
search_fields = ("name",)
|
|
||||||
autocomplete_fields = ("club",)
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(StockAction)
|
|
||||||
class StockActionAdmin(admin.ModelAdmin):
|
|
||||||
list_display = ("action", "comment", "user", "created_at")
|
|
||||||
search_fields = ("action",)
|
|
||||||
autocomplete_fields = ("user",)
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(StockItem)
|
|
||||||
class StockItemAdmin(admin.ModelAdmin):
|
|
||||||
list_display = (
|
|
||||||
"name",
|
|
||||||
"description",
|
|
||||||
"is_hidden",
|
|
||||||
"is_allow_negative",
|
|
||||||
"created_at",
|
|
||||||
)
|
|
||||||
search_fields = ("name",)
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(StockItemStock)
|
|
||||||
class StockItemStockAdmin(admin.ModelAdmin):
|
|
||||||
list_display = ("stock", "item", "quantity")
|
|
||||||
autocomplete_fields = ("stock", "item")
|
|
||||||
|
|
||||||
|
|
||||||
@admin.register(StockItemAction)
|
|
||||||
class StockItemActionAdmin(admin.ModelAdmin):
|
|
||||||
list_display = (
|
|
||||||
"action",
|
|
||||||
"item",
|
|
||||||
"quantity_before",
|
|
||||||
"quantity_after",
|
|
||||||
)
|
|
||||||
search_fields = ("item",)
|
|
||||||
Whitespace-only changes.
@@ -1,6 +0,0 @@
|
|||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
|
|
||||||
class StockConfig(AppConfig):
|
|
||||||
default_auto_field = "django.db.models.BigAutoField"
|
|
||||||
name = "stock"
|
|
||||||
-213
@@ -1,213 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
from django import forms
|
|
||||||
from django.utils.translation import gettext_lazy as _
|
|
||||||
|
|
||||||
from core.views.widgets.ajax_select import (
|
|
||||||
AutoCompleteSelect,
|
|
||||||
)
|
|
||||||
from stock import models
|
|
||||||
from stock.widgets.ajax_select import StockItemSelect
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from club.models import Club
|
|
||||||
|
|
||||||
|
|
||||||
class StockForm(forms.ModelForm):
|
|
||||||
required_css_class = "required"
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = models.Stock
|
|
||||||
fields = ["name", "club"]
|
|
||||||
widgets = {"club": forms.HiddenInput}
|
|
||||||
|
|
||||||
def __init__(self, *args, club: Club, **kwargs):
|
|
||||||
instance = kwargs.get("instance")
|
|
||||||
if instance is not None:
|
|
||||||
instance.club = club
|
|
||||||
super().__init__(*args, **kwargs)
|
|
||||||
self.initial["club"] = club.pk
|
|
||||||
|
|
||||||
def clean(self):
|
|
||||||
self.instance.clean()
|
|
||||||
return super().clean()
|
|
||||||
|
|
||||||
|
|
||||||
class StockItemStockForm(forms.ModelForm):
|
|
||||||
required_css_class = "required"
|
|
||||||
|
|
||||||
name = forms.CharField(max_length=64, label=_("name"))
|
|
||||||
description = forms.CharField(
|
|
||||||
required=False, label=_("description"), widget=forms.Textarea
|
|
||||||
)
|
|
||||||
is_hidden = forms.BooleanField(
|
|
||||||
required=False,
|
|
||||||
label=_("is hidden"),
|
|
||||||
widget=forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
)
|
|
||||||
is_allow_negative = forms.BooleanField(
|
|
||||||
required=False,
|
|
||||||
label=_("can be negative"),
|
|
||||||
widget=forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = models.StockItemStock
|
|
||||||
fields = ["name", "description", "is_hidden", "is_allow_negative"]
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
super().__init__(*args, **kwargs)
|
|
||||||
if self.instance.pk:
|
|
||||||
for name in self.fields:
|
|
||||||
self.initial[name] = getattr(self.instance.item, name)
|
|
||||||
|
|
||||||
def save(self, commit=True): # noqa: FBT002
|
|
||||||
if self.instance.pk:
|
|
||||||
stock_item = self.instance.item
|
|
||||||
for name in ("name", "description", "is_hidden", "is_allow_negative"):
|
|
||||||
setattr(stock_item, name, self.cleaned_data[name])
|
|
||||||
if commit:
|
|
||||||
stock_item.save()
|
|
||||||
else:
|
|
||||||
stock_item, _ = models.StockItem.objects.get_or_create(
|
|
||||||
name=self.cleaned_data["name"],
|
|
||||||
defaults={
|
|
||||||
name: self.cleaned_data[name]
|
|
||||||
for name in ("description", "is_hidden", "is_allow_negative")
|
|
||||||
},
|
|
||||||
)
|
|
||||||
self.instance.item = stock_item
|
|
||||||
return super().save(commit=commit)
|
|
||||||
|
|
||||||
|
|
||||||
ItemLineForm = forms.inlineformset_factory(
|
|
||||||
models.Stock,
|
|
||||||
models.StockItemStock,
|
|
||||||
form=StockItemStockForm,
|
|
||||||
fields=["name", "description", "is_hidden", "is_allow_negative"],
|
|
||||||
widgets={
|
|
||||||
"is_hidden": forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
"is_allow_negative": forms.CheckboxInput(attrs={"class": "switch"}),
|
|
||||||
},
|
|
||||||
can_delete_extra=False,
|
|
||||||
can_delete=False,
|
|
||||||
min_num=1,
|
|
||||||
validate_min=True,
|
|
||||||
extra=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
AUTHORIZED_OPERATION_TYPES = [
|
|
||||||
models.OperationType.Refuel,
|
|
||||||
models.OperationType.TransferTo,
|
|
||||||
models.OperationType.Overwrite,
|
|
||||||
]
|
|
||||||
|
|
||||||
HIDDEN_QUANTITY_ACTIONS = (
|
|
||||||
models.OperationType.Refuel,
|
|
||||||
models.OperationType.TransferTo,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class StockActionForm(forms.ModelForm):
|
|
||||||
required_css_class = "required"
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = models.StockAction
|
|
||||||
fields = ["comment", "action"]
|
|
||||||
widgets = {
|
|
||||||
"action": forms.Select,
|
|
||||||
}
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
super().__init__(*args, **kwargs)
|
|
||||||
# Alpine
|
|
||||||
self.fields["action"].choices = [
|
|
||||||
(operation_type.value, operation_type.label)
|
|
||||||
for operation_type in AUTHORIZED_OPERATION_TYPES
|
|
||||||
]
|
|
||||||
self.fields["action"].widget.attrs["x-model"] = "action"
|
|
||||||
|
|
||||||
|
|
||||||
StockItemActionFormSet = forms.inlineformset_factory(
|
|
||||||
models.StockAction,
|
|
||||||
models.StockItemAction,
|
|
||||||
fields=["item", "quantity_after"],
|
|
||||||
can_delete_extra=False,
|
|
||||||
can_delete=False,
|
|
||||||
min_num=1,
|
|
||||||
validate_min=True,
|
|
||||||
extra=0,
|
|
||||||
widgets={
|
|
||||||
"quantity_after": forms.NumberInput(
|
|
||||||
attrs={
|
|
||||||
"x-show": "!"
|
|
||||||
+ str([str(action.value) for action in HIDDEN_QUANTITY_ACTIONS])
|
|
||||||
+ ".includes(action)"
|
|
||||||
}
|
|
||||||
),
|
|
||||||
"item": StockItemSelect,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class RefuelMetadataForm(forms.ModelForm):
|
|
||||||
required_css_class = "required"
|
|
||||||
|
|
||||||
added_quantity = forms.DecimalField(
|
|
||||||
required=True,
|
|
||||||
min_value=0,
|
|
||||||
label=_("Quantity added"),
|
|
||||||
widget=forms.NumberInput(),
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_initial_for_field(self, field, field_name):
|
|
||||||
if field_name == "added_quantity" and self.instance.pk:
|
|
||||||
return self.instance.added_quantity
|
|
||||||
return super().get_initial_for_field(field, field_name)
|
|
||||||
|
|
||||||
def clean(self):
|
|
||||||
cleaned = super().clean()
|
|
||||||
if cleaned.get("added_quantity") is not None:
|
|
||||||
self.instance.added_quantity = cleaned["added_quantity"]
|
|
||||||
return cleaned
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = models.StockRefuelMetadata
|
|
||||||
fields = ["unit_price"]
|
|
||||||
|
|
||||||
|
|
||||||
class TransferMetadataForm(forms.ModelForm):
|
|
||||||
required_css_class = "required"
|
|
||||||
|
|
||||||
transfer_quantity = forms.DecimalField(
|
|
||||||
required=True,
|
|
||||||
min_value=0,
|
|
||||||
label=_("Quantity transferred"),
|
|
||||||
widget=forms.NumberInput(),
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_initial_for_field(self, field, field_name):
|
|
||||||
if field_name == "transfer_quantity" and self.instance.pk:
|
|
||||||
return self.instance.remove_quantity
|
|
||||||
return super().get_initial_for_field(field, field_name)
|
|
||||||
|
|
||||||
def clean(self):
|
|
||||||
cleaned = super().clean()
|
|
||||||
if cleaned.get("transfer_quantity") is not None:
|
|
||||||
self.instance.added_quantity = cleaned["transfer_quantity"]
|
|
||||||
return cleaned
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = models.StockTransferMetadata
|
|
||||||
fields = ["new_stock"]
|
|
||||||
widgets = {
|
|
||||||
"new_stock": AutoCompleteSelect,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
METADATA_FORMS = {
|
|
||||||
models.OperationType.Refuel: RefuelMetadataForm,
|
|
||||||
models.OperationType.TransferTo: TransferMetadataForm,
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from club.models import Club
|
|
||||||
from core.models import User
|
|
||||||
from stock.models import Stock
|
|
||||||
|
|
||||||
|
|
||||||
def can_be_edited_by(user: User, club: Club):
|
|
||||||
return user.is_in_group(pk=club.stock_group) or user.is_root
|
|
||||||
|
|
||||||
|
|
||||||
def can_be_view_by(user: User, club: Club, stock: Stock):
|
|
||||||
return can_be_edited_by(user, club) or (
|
|
||||||
stock.can_be_view_by_board and user.is_in_group(pk=club.stock_group)
|
|
||||||
)
|
|
||||||
@@ -1,309 +0,0 @@
|
|||||||
# Generated by Django 5.2.18 on 2026-11-09 06:57
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
("club", "0020_club_stock_group"),
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="Stock",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
("name", models.CharField(max_length=64, verbose_name="name")),
|
|
||||||
(
|
|
||||||
"created_at",
|
|
||||||
models.DateTimeField(auto_now_add=True, verbose_name="created at"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"updated_at",
|
|
||||||
models.DateTimeField(auto_now_add=True, verbose_name="updated at"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"can_be_view_by_board",
|
|
||||||
models.BooleanField(
|
|
||||||
default=False, verbose_name="can be view by board members"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"club",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT, to="club.club"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="StockAction",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"action",
|
|
||||||
models.IntegerField(
|
|
||||||
choices=[
|
|
||||||
(1, "overwrite"),
|
|
||||||
(2, "refuel"),
|
|
||||||
(3, "transfer to"),
|
|
||||||
(4, "transfer from"),
|
|
||||||
],
|
|
||||||
default=1,
|
|
||||||
verbose_name="action type",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"created_at",
|
|
||||||
models.DateTimeField(auto_now_add=True, verbose_name="created at"),
|
|
||||||
),
|
|
||||||
("comment", models.TextField(default="", verbose_name="comment")),
|
|
||||||
(
|
|
||||||
"user",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
to=settings.AUTH_USER_MODEL,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="StockItem",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
("name", models.CharField(max_length=64, verbose_name="name")),
|
|
||||||
(
|
|
||||||
"description",
|
|
||||||
models.TextField(default="", verbose_name="description"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"created_at",
|
|
||||||
models.DateTimeField(auto_now_add=True, verbose_name="created at"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"is_hidden",
|
|
||||||
models.BooleanField(default=False, verbose_name="is hidden"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"is_allow_negative",
|
|
||||||
models.BooleanField(default=False, verbose_name="can be negative"),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
"constraints": [
|
|
||||||
models.UniqueConstraint(fields=("name",), name="unique_item_name")
|
|
||||||
],
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="StockItemStock",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"quantity",
|
|
||||||
models.DecimalField(
|
|
||||||
decimal_places=2,
|
|
||||||
default=0,
|
|
||||||
max_digits=15,
|
|
||||||
verbose_name="quantity",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"item",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="stock_links",
|
|
||||||
to="stock.stockitem",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"stock",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="item_links",
|
|
||||||
to="stock.stock",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="StockItemAction",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"quantity_before",
|
|
||||||
models.DecimalField(
|
|
||||||
decimal_places=2,
|
|
||||||
default=0,
|
|
||||||
max_digits=15,
|
|
||||||
verbose_name="quantity before",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"quantity_after",
|
|
||||||
models.DecimalField(
|
|
||||||
decimal_places=2,
|
|
||||||
default=0,
|
|
||||||
max_digits=15,
|
|
||||||
verbose_name="quantity after",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"action",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
to="stock.stockaction",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"item",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
to="stock.stockitemstock",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="StockRefuelMetadata",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"unit_price",
|
|
||||||
models.DecimalField(
|
|
||||||
decimal_places=2, max_digits=20, verbose_name="unit price"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"item_action",
|
|
||||||
models.OneToOneField(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="%(class)s_metadata",
|
|
||||||
to="stock.stockitemaction",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name="StockTransferMetadata",
|
|
||||||
fields=[
|
|
||||||
(
|
|
||||||
"id",
|
|
||||||
models.BigAutoField(
|
|
||||||
auto_created=True,
|
|
||||||
primary_key=True,
|
|
||||||
serialize=False,
|
|
||||||
verbose_name="ID",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"item_action",
|
|
||||||
models.OneToOneField(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="%(class)s_metadata",
|
|
||||||
to="stock.stockitemaction",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"new_stock",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="incoming_transfers",
|
|
||||||
to="stock.stock",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"old_stock",
|
|
||||||
models.ForeignKey(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="outgoing_transfers",
|
|
||||||
to="stock.stock",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"other_item_action",
|
|
||||||
models.OneToOneField(
|
|
||||||
on_delete=django.db.models.deletion.PROTECT,
|
|
||||||
related_name="transfer_other_item_metadata",
|
|
||||||
to="stock.stockitemaction",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
"abstract": False,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.AddConstraint(
|
|
||||||
model_name="stock",
|
|
||||||
constraint=models.UniqueConstraint(
|
|
||||||
fields=("name", "club"),
|
|
||||||
name="unique_name_club",
|
|
||||||
violation_error_message="errere",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AddConstraint(
|
|
||||||
model_name="stockitemstock",
|
|
||||||
constraint=models.UniqueConstraint(
|
|
||||||
fields=("item", "stock"), name="unique_item_stock"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AddConstraint(
|
|
||||||
model_name="stockrefuelmetadata",
|
|
||||||
constraint=models.CheckConstraint(
|
|
||||||
condition=models.Q(("unit_price__gt", 0)), name="unit_price_gt_0"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
Whitespace-only changes.
-211
@@ -1,211 +0,0 @@
|
|||||||
from django.db import models
|
|
||||||
from django.utils.translation import gettext_lazy as _
|
|
||||||
|
|
||||||
from club.models import Club
|
|
||||||
from core.models import User
|
|
||||||
|
|
||||||
|
|
||||||
class OperationType(models.IntegerChoices):
|
|
||||||
Overwrite = 1, _("overwrite")
|
|
||||||
Refuel = 2, _("refuel")
|
|
||||||
TransferTo = 3, _("transfer to")
|
|
||||||
TransferFrom = 4, _("transfer from")
|
|
||||||
|
|
||||||
|
|
||||||
class Stock(models.Model):
|
|
||||||
name = models.CharField(_("name"), max_length=64)
|
|
||||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(_("updated at"), auto_now_add=True)
|
|
||||||
club = models.ForeignKey(Club, on_delete=models.PROTECT)
|
|
||||||
can_be_view_by_board = models.BooleanField(
|
|
||||||
_("can be view by board members"), default=False
|
|
||||||
)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
constraints = [
|
|
||||||
models.UniqueConstraint(
|
|
||||||
fields=["name", "club"],
|
|
||||||
name="unique_name_club",
|
|
||||||
violation_error_message="errere",
|
|
||||||
)
|
|
||||||
]
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.name
|
|
||||||
|
|
||||||
|
|
||||||
class StockAction(models.Model):
|
|
||||||
action = models.IntegerField(
|
|
||||||
_("action type"), choices=OperationType, default=OperationType.Overwrite
|
|
||||||
)
|
|
||||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
|
||||||
comment = models.TextField(_("comment"), default="")
|
|
||||||
user = models.ForeignKey(User, on_delete=models.PROTECT)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return str(OperationType(self.action).label)
|
|
||||||
|
|
||||||
|
|
||||||
class StockItem(models.Model):
|
|
||||||
name = models.CharField(_("name"), max_length=64)
|
|
||||||
description = models.TextField(_("description"), default="")
|
|
||||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
|
||||||
is_hidden = models.BooleanField(_("is hidden"), default=False)
|
|
||||||
is_allow_negative = models.BooleanField(_("can be negative"), default=False)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
constraints = [
|
|
||||||
models.UniqueConstraint(fields=["name"], name="unique_item_name")
|
|
||||||
]
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.name
|
|
||||||
|
|
||||||
|
|
||||||
class StockItemStock(models.Model):
|
|
||||||
item = models.ForeignKey(
|
|
||||||
StockItem, on_delete=models.PROTECT, related_name="stock_links"
|
|
||||||
)
|
|
||||||
stock = models.ForeignKey(
|
|
||||||
Stock, on_delete=models.PROTECT, related_name="item_links"
|
|
||||||
)
|
|
||||||
quantity = models.DecimalField(
|
|
||||||
_("quantity"), max_digits=15, decimal_places=2, default=0
|
|
||||||
)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
constraints = [
|
|
||||||
models.UniqueConstraint(fields=["item", "stock"], name="unique_item_stock")
|
|
||||||
]
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.item.name
|
|
||||||
|
|
||||||
@property
|
|
||||||
def name(self):
|
|
||||||
return self.item.name
|
|
||||||
|
|
||||||
@property
|
|
||||||
def description(self):
|
|
||||||
return self.item.description
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_hidden(self):
|
|
||||||
return self.item.is_hidden
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_allow_negative(self):
|
|
||||||
return self.item.is_allow_negative
|
|
||||||
|
|
||||||
@property
|
|
||||||
def last_known_quantity(self):
|
|
||||||
return self.quantity
|
|
||||||
|
|
||||||
|
|
||||||
class StockItemAction(models.Model):
|
|
||||||
quantity_before = models.DecimalField(
|
|
||||||
_("quantity before"), max_digits=15, decimal_places=2, default=0
|
|
||||||
)
|
|
||||||
quantity_after = models.DecimalField(
|
|
||||||
_("quantity after"), max_digits=15, decimal_places=2, default=0
|
|
||||||
)
|
|
||||||
action = models.ForeignKey(StockAction, on_delete=models.PROTECT)
|
|
||||||
item = models.ForeignKey(StockItemStock, on_delete=models.PROTECT)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return str(self.quantity_after - self.quantity_before)
|
|
||||||
|
|
||||||
|
|
||||||
class LinkedModel(models.Model):
|
|
||||||
class Meta:
|
|
||||||
abstract = True
|
|
||||||
|
|
||||||
def link(self, **ids):
|
|
||||||
for name, pk in ids.items():
|
|
||||||
field = self._meta.get_field(name)
|
|
||||||
if not (field.many_to_one or field.one_to_one) or not field.concrete:
|
|
||||||
raise ValueError(f"{name} is not a forward FK/OneToOne")
|
|
||||||
setattr(self, field.attname, pk)
|
|
||||||
|
|
||||||
|
|
||||||
class StockItemActionMetadataBase(LinkedModel):
|
|
||||||
item_action = models.OneToOneField(
|
|
||||||
StockItemAction,
|
|
||||||
on_delete=models.PROTECT,
|
|
||||||
related_name="%(class)s_metadata",
|
|
||||||
)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
abstract = True
|
|
||||||
|
|
||||||
def set_relations(self, item_action_pk, **ids):
|
|
||||||
self.item_action_id = item_action_pk
|
|
||||||
return super().link(**ids)
|
|
||||||
|
|
||||||
|
|
||||||
class StockRefuelMetadata(StockItemActionMetadataBase):
|
|
||||||
unit_price = models.DecimalField(_("unit price"), max_digits=20, decimal_places=2)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
constraints = [
|
|
||||||
models.CheckConstraint(
|
|
||||||
condition=models.Q(unit_price__gt=0), name="unit_price_gt_0"
|
|
||||||
)
|
|
||||||
]
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return _("refuel with unit price %s") % self.unit_price
|
|
||||||
|
|
||||||
@property
|
|
||||||
def added_quantity(self):
|
|
||||||
if hasattr(self, "_added_quantity"):
|
|
||||||
return self._added_quantity
|
|
||||||
return self.item_action.quantity_after - self.item_action.quantity_before
|
|
||||||
|
|
||||||
@added_quantity.setter
|
|
||||||
def added_quantity(self, value):
|
|
||||||
self._added_quantity = value
|
|
||||||
|
|
||||||
@added_quantity.deleter
|
|
||||||
def added_quantity(self):
|
|
||||||
self.__dict__.pop("_added_quantity", None)
|
|
||||||
|
|
||||||
|
|
||||||
class StockTransferMetadata(StockItemActionMetadataBase):
|
|
||||||
old_stock = models.ForeignKey(
|
|
||||||
Stock, related_name="outgoing_transfers", on_delete=models.PROTECT
|
|
||||||
)
|
|
||||||
new_stock = models.ForeignKey(
|
|
||||||
Stock, related_name="incoming_transfers", on_delete=models.PROTECT
|
|
||||||
)
|
|
||||||
other_item_action = models.OneToOneField(
|
|
||||||
StockItemAction,
|
|
||||||
on_delete=models.PROTECT,
|
|
||||||
related_name="transfer_other_item_metadata",
|
|
||||||
)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return _("transfer %s to stock of id %s") % (
|
|
||||||
self.transfer_quantity,
|
|
||||||
self.new_stock_id,
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def added_quantity(self):
|
|
||||||
if hasattr(self, "_added_quantity"):
|
|
||||||
return self._added_quantity
|
|
||||||
return self.item_action.quantity_before - self.item_action.quantity_after
|
|
||||||
|
|
||||||
@added_quantity.setter
|
|
||||||
def added_quantity(self, value):
|
|
||||||
self._added_quantity = value
|
|
||||||
|
|
||||||
@added_quantity.deleter
|
|
||||||
def added_quantity(self):
|
|
||||||
self.__dict__.pop("_added_quantity", None)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def remove_quantity(self):
|
|
||||||
if hasattr(self, "_added_quantity"):
|
|
||||||
return self._added_quantity
|
|
||||||
return self.item_action.quantity_before - self.item_action.quantity_after
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
.stock-form label {
|
|
||||||
text-transform: capitalize;
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("stock/css/forms.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% macro field_row(field) %}
|
|
||||||
<div class="form-group"
|
|
||||||
{% if field.name == "item" %}
|
|
||||||
x-data="{ existingQuantity: null }"
|
|
||||||
x-init="existingQuantity = $el.querySelector('select')?.selectedOptions[0]?.dataset.quantity ?? null"
|
|
||||||
@change="existingQuantity = $event.target.selectedOptions[0]?.dataset.quantity ?? null"
|
|
||||||
{% endif %}
|
|
||||||
{% if field.field.widget.attrs.get("x-show") %} x-show="{{ field.field.widget.attrs.get("x-show") }}"{% endif %}
|
|
||||||
>
|
|
||||||
{{ field.label_tag() }} {{ field }} {{ field.errors }}
|
|
||||||
{% if field.name == "item" %}
|
|
||||||
<div x-show="existingQuantity !== null">
|
|
||||||
{% trans %}Current quantity:{% endtrans %}
|
|
||||||
<span x-text="existingQuantity"></span>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endmacro %}
|
|
||||||
|
|
||||||
|
|
||||||
{% macro action_row(f, removable=true) %}
|
|
||||||
<div>
|
|
||||||
<div class="action-row">
|
|
||||||
{% for h in f.hidden_fields() %}{{ h }}{% endfor %}
|
|
||||||
{{ f.non_field_errors() }}
|
|
||||||
{% for field in f.visible_fields() %}
|
|
||||||
{{ field_row(field) }}
|
|
||||||
{% endfor %}
|
|
||||||
|
|
||||||
{% for b in f.blocks %}
|
|
||||||
<fieldset x-cloak
|
|
||||||
x-show="action === '{{ b.action }}'"
|
|
||||||
:disabled="action !== '{{ b.action }}'">
|
|
||||||
{{ b.form.non_field_errors() }}
|
|
||||||
{% for h in b.form.hidden_fields() %}{{ h }}{% endfor %}
|
|
||||||
{% for field in b.form.visible_fields() %}
|
|
||||||
{{ field_row(field) }}
|
|
||||||
{% endfor %}
|
|
||||||
</fieldset>
|
|
||||||
{% endfor %}
|
|
||||||
{% if removable %}
|
|
||||||
<button class="btn btn-grey" type="button"
|
|
||||||
@click.prevent="$el.closest('.action-row').parentElement.remove()">
|
|
||||||
<i class="fa fa-minus"></i>
|
|
||||||
{% trans %}Remove{% endtrans %}
|
|
||||||
</button>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
<hr class="margin-bottom">
|
|
||||||
</div>
|
|
||||||
{% endmacro %}
|
|
||||||
|
|
||||||
{% block script %}
|
|
||||||
<script>
|
|
||||||
document.addEventListener("alpine:init", () => {
|
|
||||||
Alpine.data("rows", (prefix, base) => ({
|
|
||||||
prefix, base, added: [],
|
|
||||||
get total() { return this.base + this.added.length },
|
|
||||||
add() { this.added.push(this.base + this.added.length) },
|
|
||||||
html(i) {
|
|
||||||
return this.$refs.tpl.innerHTML.replaceAll(
|
|
||||||
`${this.prefix}-__prefix__`, `${this.prefix}-${i}`)
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{% trans %}New stock action{% endtrans %}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
|
|
||||||
<h2>{% trans %}New stock action in {% endtrans %}{{ stock.name }}</h2>
|
|
||||||
|
|
||||||
{% set action_value = form["action"].value() %}
|
|
||||||
|
|
||||||
<form method="post" class="stock-form" enctype="multipart/form-data"
|
|
||||||
x-data="{ action: '{{ action_value if action_value is not none else '' }}' }">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.non_field_errors() }}
|
|
||||||
|
|
||||||
<div class="margin-bottom">
|
|
||||||
{% for field in form.visible_fields() %}
|
|
||||||
{{ field_row(field) }}
|
|
||||||
{% endfor %}
|
|
||||||
<hr>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div x-data="rows('{{ formset.prefix }}', {{ formset.total_form_count() }})">
|
|
||||||
<input type="hidden" name="{{ formset.prefix }}-TOTAL_FORMS" :value="total">
|
|
||||||
{{ formset.management_form["INITIAL_FORMS"] }}
|
|
||||||
{{ formset.management_form["MIN_NUM_FORMS"] }}
|
|
||||||
{{ formset.management_form["MAX_NUM_FORMS"] }}
|
|
||||||
|
|
||||||
{{ formset.non_form_errors() }}
|
|
||||||
|
|
||||||
<h3 class="margin-bottom">{% trans %}Items{% endtrans %}</h3>
|
|
||||||
|
|
||||||
{% for f in formset %}
|
|
||||||
{{ action_row(f, not loop.first) }}
|
|
||||||
{% endfor %}
|
|
||||||
|
|
||||||
<template x-for="i in added" :key="i">
|
|
||||||
<div x-html="html(i)"></div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<template x-ref="tpl">
|
|
||||||
{{ action_row(empty_form) }}
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<div class="row gap margin-bottom">
|
|
||||||
<button class="btn btn-grey" type="button" @click="add()">
|
|
||||||
<i class="fa fa-plus"></i>
|
|
||||||
{% trans %}Add{% endtrans %}
|
|
||||||
</button>
|
|
||||||
<button class="btn btn-blue" type="submit">{% trans %}Save{% endtrans %}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("stock/css/forms.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block title %}{% trans %}Create stock{% endtrans %}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2>{% trans %}Create stock{% endtrans %}</h2>
|
|
||||||
<form method="post" action="" class="stock-form">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.as_p() }}
|
|
||||||
<p><button class="btn btn-blue" type="submit">{% trans %}Save{% endtrans %}</button></p>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("stock/css/forms.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block title %}{% trans %}Edit stock{% endtrans %}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2>{% trans %}Edit stock{% endtrans %}</h2>
|
|
||||||
<form method="post" class="stock-form">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.as_p() }}
|
|
||||||
<p><button class="btn btn-blue" type="submit">{% trans %}Save{% endtrans %}</button></p>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{% trans %}Stock{% endtrans %}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2 class="margin-bottom">{% trans %}Stock{% endtrans %}</h2>
|
|
||||||
|
|
||||||
{% if is_editor %}
|
|
||||||
<p class="margin-bottom">
|
|
||||||
<a class="btn btn-blue" href="{{ url('stock:create', club_id=club.id) }}">
|
|
||||||
{% trans %}Create a stock{% endtrans %}
|
|
||||||
<i class="fa fa-plus"></i>
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% if stocks %}
|
|
||||||
<ul>
|
|
||||||
{% for stock in stocks %}
|
|
||||||
{% if stock.can_be_view_by_board or is_editor %}
|
|
||||||
<li>
|
|
||||||
<a href="{{ url('stock:items_list', club_id=club.id, stock_id=stock.id) }}">
|
|
||||||
{{ stock.name }}
|
|
||||||
</a>
|
|
||||||
{% if is_editor %}
|
|
||||||
-
|
|
||||||
<a href="{{ url('stock:edit', club_id=club.id, stock_id=stock.id) }}">
|
|
||||||
{% trans %}Edit{% endtrans %}
|
|
||||||
</a>
|
|
||||||
{% endif %}
|
|
||||||
</li>
|
|
||||||
{% endif %}
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
{% else %}
|
|
||||||
<p>{% trans %}No stock has been created yet.{% endtrans %}</p>
|
|
||||||
{% endif %}
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("stock/css/forms.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block title %}{% trans %}Edit stock item{% endtrans %}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2>{% trans %}Edit stock item{% endtrans %}</h2>
|
|
||||||
<form method="post" class="stock-form">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.as_p() }}
|
|
||||||
<p><button class="btn btn-blue" type="submit">{% trans %}Save{% endtrans %}</button></p>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("stock/css/forms.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block additional_js %}
|
|
||||||
<script type="module" src="{{ static("bundled/core/dynamic-formset-index.ts") }}"></script>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block title %}{% trans %}Create stock item{% endtrans %}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2>{% trans %}Create stock items in{% endtrans %}{{ stock.name }}</h2>
|
|
||||||
<form method="post" class="stock-form"
|
|
||||||
x-data="dynamicFormSet({ prefix: '{{ formset.prefix }}' })">
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ formset.management_form }}
|
|
||||||
<div x-ref="formContainer" class="margin-bottom">
|
|
||||||
{% for item_form in formset.forms %}
|
|
||||||
<div>
|
|
||||||
<fieldset>
|
|
||||||
{{ item_form.as_p() }}
|
|
||||||
{% if not loop.first %}
|
|
||||||
<button type="button" class="btn btn-grey"
|
|
||||||
@click.prevent="removeForm($event.target.closest('div'))">
|
|
||||||
<i class="fa fa-minus"></i> {% trans %}Remove{% endtrans %}
|
|
||||||
</button>
|
|
||||||
{% endif %}
|
|
||||||
</fieldset>
|
|
||||||
<hr>
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
</div>
|
|
||||||
<template x-ref="formTemplate" class="margin-bottom">
|
|
||||||
<div class="margin-bottom">
|
|
||||||
<fieldset>
|
|
||||||
<div class="margin-bottom">
|
|
||||||
{{ formset.empty_form.as_p() }}
|
|
||||||
</div>
|
|
||||||
<button type="button" class="btn btn-grey"
|
|
||||||
@click.prevent="removeForm($event.target.closest('div'))">
|
|
||||||
<i class="fa fa-minus"></i> {% trans %}Remove{% endtrans %}
|
|
||||||
</button>
|
|
||||||
</fieldset>
|
|
||||||
<hr>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<div class="row gap margin-bottom">
|
|
||||||
<button type="button" class="btn btn-grey" @click.prevent="addForm()">
|
|
||||||
<i class="fa fa-plus"></i> {% trans %}Add an item{% endtrans %}
|
|
||||||
</button>
|
|
||||||
<button type="submit" class="btn btn-blue">{% trans %}Save{% endtrans %}</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
{% extends "core/base.jinja" %}
|
|
||||||
|
|
||||||
{% block additional_css %}
|
|
||||||
<link rel="stylesheet" href="{{ static("core/components/card.scss") }}">
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block title %}{% trans %}Stock items{% endtrans %}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h2 class="margin-bottom">{% trans %}Items in {% endtrans %}{{ stock.name }}</h2>
|
|
||||||
{% if is_editor %}
|
|
||||||
<div class="row gap margin-bottom">
|
|
||||||
<a href="{{ url('stock:items_create', club_id=club.id, stock_id=stock.id) }}" class="btn btn-blue">
|
|
||||||
{% trans %}Create items{% endtrans %} <i class="fa fa-plus"></i>
|
|
||||||
</a>
|
|
||||||
<a href="{{ url('stock:action_create', club_id=club.id, stock_id=stock.id) }}" class="btn btn-blue">
|
|
||||||
{% trans %}Create action{% endtrans %} <i class="fa fa-plus"></i>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
{% if items %}
|
|
||||||
<div>
|
|
||||||
{% for item in items %}
|
|
||||||
<div class="card card-row shadow margin-bottom">
|
|
||||||
<div class="card-content">
|
|
||||||
<strong class="card-title">{{ item.item.name }}</strong>
|
|
||||||
<p>{% trans %}Last known quantity:{% endtrans %} {{ item.last_known_quantity }}</p>
|
|
||||||
</div>
|
|
||||||
{% if is_editor %}
|
|
||||||
<a class="btn btn-grey" href="{{ url('stock:item_edit', club_id=club.id, stock_id=stock.id, item_id=item.id) }}">
|
|
||||||
<i class="fa fa-pen"></i> {% trans %}Edit{% endtrans %}
|
|
||||||
</a>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
</div>
|
|
||||||
{% else %}
|
|
||||||
<p>{% trans %}No item has been created yet.{% endtrans %}</p>
|
|
||||||
{% endif %}
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Create your tests here.
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
from django.urls import path
|
|
||||||
|
|
||||||
from stock.views.core import (
|
|
||||||
StockCreateView,
|
|
||||||
StockHomeView,
|
|
||||||
StockUpdateView,
|
|
||||||
)
|
|
||||||
from stock.views.items import (
|
|
||||||
ItemActionCreateView,
|
|
||||||
ItemCreateView,
|
|
||||||
ItemListView,
|
|
||||||
ItemUpdateView,
|
|
||||||
)
|
|
||||||
|
|
||||||
urlpatterns = [
|
|
||||||
path("<int:club_id>/create/", StockCreateView.as_view(), name="create"),
|
|
||||||
path("<int:club_id>/edit/<int:stock_id>", StockUpdateView.as_view(), name="edit"),
|
|
||||||
path("<int:club_id>/home/", StockHomeView.as_view(), name="home"),
|
|
||||||
path(
|
|
||||||
"<int:club_id>/stock/<int:stock_id>/items/create/",
|
|
||||||
ItemCreateView.as_view(),
|
|
||||||
name="items_create",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"<int:club_id>/stock/<int:stock_id>/items/",
|
|
||||||
ItemListView.as_view(),
|
|
||||||
name="items_list",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"<int:club_id>/stock/<int:stock_id>/items/<int:item_id>/edit/",
|
|
||||||
ItemUpdateView.as_view(),
|
|
||||||
name="item_edit",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"<int:club_id>/stock/<int:stock_id>/actions/create",
|
|
||||||
ItemActionCreateView.as_view(),
|
|
||||||
name="action_create",
|
|
||||||
),
|
|
||||||
]
|
|
||||||
Whitespace-only changes.
@@ -1,83 +0,0 @@
|
|||||||
from django.contrib.auth.mixins import UserPassesTestMixin
|
|
||||||
from django.contrib.messages.views import SuccessMessageMixin
|
|
||||||
from django.shortcuts import get_object_or_404
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.utils.translation import gettext_lazy as _
|
|
||||||
from django.views.generic import TemplateView
|
|
||||||
from django.views.generic.edit import CreateView, UpdateView
|
|
||||||
|
|
||||||
from club.models import Club
|
|
||||||
from stock.forms import StockForm
|
|
||||||
from stock.heper import can_be_edited_by
|
|
||||||
from stock.models import Stock
|
|
||||||
|
|
||||||
|
|
||||||
class StockHomeView(UserPassesTestMixin, TemplateView):
|
|
||||||
pk_url_kwarg = "club_id"
|
|
||||||
template_name = "stock/home.jinja"
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=self.kwargs.get(self.pk_url_kwarg))
|
|
||||||
self.is_editor = can_be_edited_by(self.request.user, self.club)
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return (
|
|
||||||
self.club in self.request.user.clubs_with_rights
|
|
||||||
or self.request.user.is_root
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
|
||||||
context = super().get_context_data(**kwargs)
|
|
||||||
context["club"] = self.club
|
|
||||||
context["stocks"] = Stock.objects.filter(club=self.club)
|
|
||||||
context["is_editor"] = self.is_editor
|
|
||||||
return context
|
|
||||||
|
|
||||||
|
|
||||||
class StockCreateView(UserPassesTestMixin, SuccessMessageMixin, CreateView):
|
|
||||||
model = Stock
|
|
||||||
form_class = StockForm
|
|
||||||
template_name = "stock/create.jinja"
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return can_be_edited_by(self.request.user, self.club)
|
|
||||||
|
|
||||||
def get_form_kwargs(self):
|
|
||||||
return super().get_form_kwargs() | {"club": self.club}
|
|
||||||
|
|
||||||
def get_success_url(self):
|
|
||||||
return reverse("stock:home", kwargs={"club_id": self.club.id})
|
|
||||||
|
|
||||||
def get_success_message(self, cleaned_data):
|
|
||||||
return cleaned_data["name"] + _(" created.")
|
|
||||||
|
|
||||||
|
|
||||||
class StockUpdateView(UserPassesTestMixin, SuccessMessageMixin, UpdateView):
|
|
||||||
model = Stock
|
|
||||||
form_class = StockForm
|
|
||||||
pk_url_kwarg = "stock_id"
|
|
||||||
template_name = "stock/edit.jinja"
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return can_be_edited_by(self.request.user, self.club)
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
return Stock.objects.filter(club=self.club)
|
|
||||||
|
|
||||||
def get_form_kwargs(self):
|
|
||||||
return super().get_form_kwargs() | {"club": self.club}
|
|
||||||
|
|
||||||
def get_success_url(self):
|
|
||||||
return reverse("stock:home", kwargs={"club_id": self.club.id})
|
|
||||||
|
|
||||||
def get_success_message(self, cleaned_data):
|
|
||||||
return cleaned_data["name"] + _(" edited.")
|
|
||||||
@@ -1,413 +0,0 @@
|
|||||||
from django import forms
|
|
||||||
from django.contrib.auth.mixins import UserPassesTestMixin
|
|
||||||
from django.contrib.messages.views import SuccessMessageMixin
|
|
||||||
from django.db import transaction
|
|
||||||
from django.http import HttpResponseRedirect
|
|
||||||
from django.shortcuts import get_object_or_404
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.utils.translation import gettext_lazy as _
|
|
||||||
from django.views.generic import ListView
|
|
||||||
from django.views.generic.edit import CreateView, FormView, UpdateView
|
|
||||||
|
|
||||||
from club.models import Club
|
|
||||||
from stock.forms import (
|
|
||||||
METADATA_FORMS,
|
|
||||||
ItemLineForm,
|
|
||||||
StockActionForm,
|
|
||||||
StockItemActionFormSet,
|
|
||||||
StockItemStockForm,
|
|
||||||
)
|
|
||||||
from stock.heper import can_be_edited_by, can_be_view_by
|
|
||||||
from stock.models import (
|
|
||||||
OperationType,
|
|
||||||
Stock,
|
|
||||||
StockAction,
|
|
||||||
StockItemAction,
|
|
||||||
StockItemStock,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ItemListView(UserPassesTestMixin, ListView):
|
|
||||||
model = StockItemStock
|
|
||||||
template_name = "stock/items_list.jinja"
|
|
||||||
context_object_name = "items"
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
|
||||||
self.stock = get_object_or_404(Stock, pk=kwargs["stock_id"], club=self.club)
|
|
||||||
self.is_editor = can_be_edited_by(self.request.user, self.club)
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return can_be_view_by(self.request.user, self.club, self.stock)
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
return (
|
|
||||||
StockItemStock.objects.filter(stock=self.stock)
|
|
||||||
.select_related("item")
|
|
||||||
.order_by("item__name")
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
|
||||||
context = super().get_context_data(**kwargs) | {
|
|
||||||
"club": self.club,
|
|
||||||
"stock": self.stock,
|
|
||||||
"is_editor": self.is_editor,
|
|
||||||
}
|
|
||||||
return context
|
|
||||||
|
|
||||||
|
|
||||||
class ItemCreateView(UserPassesTestMixin, SuccessMessageMixin, FormView):
|
|
||||||
form_class = ItemLineForm
|
|
||||||
template_name = "stock/items_create.jinja"
|
|
||||||
success_message = _("Item(s) created.")
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
|
||||||
self.stock = get_object_or_404(Stock, pk=kwargs["stock_id"], club=self.club)
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return can_be_edited_by(self.request.user, self.club)
|
|
||||||
|
|
||||||
def get_form_kwargs(self):
|
|
||||||
return super().get_form_kwargs() | {
|
|
||||||
"instance": self.stock,
|
|
||||||
"queryset": StockItemStock.objects.none(),
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
|
||||||
context = super().get_context_data(**kwargs)
|
|
||||||
context.update(
|
|
||||||
{
|
|
||||||
"club": self.club,
|
|
||||||
"stock": self.stock,
|
|
||||||
"formset": context["form"],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return context
|
|
||||||
|
|
||||||
def form_valid(self, form):
|
|
||||||
form.save()
|
|
||||||
return super().form_valid(form)
|
|
||||||
|
|
||||||
def get_success_url(self):
|
|
||||||
return reverse(
|
|
||||||
"stock:items_list",
|
|
||||||
kwargs={"club_id": self.club.id, "stock_id": self.stock.id},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ItemUpdateView(UserPassesTestMixin, SuccessMessageMixin, UpdateView):
|
|
||||||
model = StockItemStock
|
|
||||||
form_class = StockItemStockForm
|
|
||||||
pk_url_kwarg = "item_id"
|
|
||||||
template_name = "stock/item_edit.jinja"
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
|
||||||
self.stock = get_object_or_404(Stock, pk=kwargs["stock_id"], club=self.club)
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return can_be_edited_by(self.request.user, self.club)
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
return StockItemStock.objects.filter(stock=self.stock).select_related("item")
|
|
||||||
|
|
||||||
def get_success_url(self):
|
|
||||||
return reverse(
|
|
||||||
"stock:items_list",
|
|
||||||
kwargs={"club_id": self.club.id, "stock_id": self.stock.id},
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_success_message(self, cleaned_data):
|
|
||||||
return cleaned_data["name"] + _(" edited.")
|
|
||||||
|
|
||||||
|
|
||||||
def update_quantities(stock_items, item_actions, metadata_entries, operation_type):
|
|
||||||
match operation_type:
|
|
||||||
case OperationType.TransferFrom | OperationType.Refuel:
|
|
||||||
for item_action, metadata_entry in zip(
|
|
||||||
item_actions, metadata_entries, strict=True
|
|
||||||
):
|
|
||||||
item = stock_items[item_action.item_id]
|
|
||||||
item_action.quantity_before = item.quantity
|
|
||||||
item_action.quantity_after = (
|
|
||||||
item_action.quantity_before + metadata_entry.added_quantity
|
|
||||||
)
|
|
||||||
item.quantity = item_action.quantity_after
|
|
||||||
case _:
|
|
||||||
for item_action in item_actions:
|
|
||||||
item = stock_items[item_action.item_id]
|
|
||||||
item_action.quantity_before = item.quantity
|
|
||||||
item.quantity = item_action.quantity_after
|
|
||||||
|
|
||||||
|
|
||||||
def apply_transfer(stock_items, item_actions, metadata_entries, user, source_stock):
|
|
||||||
destinations = {}
|
|
||||||
for item_action, metadata_entry in zip(item_actions, metadata_entries, strict=True):
|
|
||||||
key = (item_action.item.item_id, metadata_entry.new_stock_id)
|
|
||||||
if key not in destinations:
|
|
||||||
destinations[key], _created = (
|
|
||||||
StockItemStock.objects.select_for_update().get_or_create(
|
|
||||||
item_id=key[0],
|
|
||||||
stock_id=key[1],
|
|
||||||
defaults={"quantity": 0},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
destination_stock_action = StockAction(
|
|
||||||
action=OperationType.TransferFrom,
|
|
||||||
comment=_("Transferred from stock %s") % source_stock.name,
|
|
||||||
user=user,
|
|
||||||
)
|
|
||||||
destination_item_actions = []
|
|
||||||
|
|
||||||
for item_action, metadata_entry in zip(item_actions, metadata_entries, strict=True):
|
|
||||||
source_item = stock_items[item_action.item_id]
|
|
||||||
destination = destinations[(source_item.item_id, metadata_entry.new_stock_id)]
|
|
||||||
quantity = metadata_entry.remove_quantity
|
|
||||||
if source_item.quantity - quantity < 0:
|
|
||||||
raise forms.ValidationError(
|
|
||||||
_("The new quantity cannot be less than zero for item %s.")
|
|
||||||
% source_item.name,
|
|
||||||
code="lesser_than_zero",
|
|
||||||
)
|
|
||||||
|
|
||||||
item_action.quantity_before = source_item.quantity
|
|
||||||
source_item.quantity -= quantity
|
|
||||||
item_action.quantity_after = source_item.quantity
|
|
||||||
destination_item_actions.append(
|
|
||||||
StockItemAction(
|
|
||||||
action=destination_stock_action,
|
|
||||||
item=destination,
|
|
||||||
quantity_before=destination.quantity,
|
|
||||||
quantity_after=destination.quantity + quantity,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
destination.quantity += quantity
|
|
||||||
metadata_entry.other_item_action = destination_item_actions[-1]
|
|
||||||
|
|
||||||
return (
|
|
||||||
destination_stock_action,
|
|
||||||
list(destinations.values()),
|
|
||||||
destination_item_actions,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ItemActionCreateView(UserPassesTestMixin, SuccessMessageMixin, CreateView):
|
|
||||||
model = StockAction
|
|
||||||
form_class = StockActionForm
|
|
||||||
template_name = "stock/action_form.jinja"
|
|
||||||
metadata_required = True
|
|
||||||
success_message = _("Action complete")
|
|
||||||
|
|
||||||
def test_func(self):
|
|
||||||
return can_be_edited_by(self.request.user, self.club)
|
|
||||||
|
|
||||||
def posted_operation_type(self):
|
|
||||||
try:
|
|
||||||
return int(self.request.POST.get("action"))
|
|
||||||
except TypeError, ValueError:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def attach_metadata_forms(self, form, active_operation_type=None):
|
|
||||||
form.blocks = []
|
|
||||||
for operation_type, metadata_form_class in METADATA_FORMS.items():
|
|
||||||
kwargs = {
|
|
||||||
"prefix": f"{form.prefix}-{operation_type.name.lower()}",
|
|
||||||
"empty_permitted": not self.metadata_required,
|
|
||||||
}
|
|
||||||
if active_operation_type == operation_type.value:
|
|
||||||
kwargs.update(data=self.request.POST, files=self.request.FILES)
|
|
||||||
metadata_form = metadata_form_class(**kwargs)
|
|
||||||
if operation_type == OperationType.TransferTo:
|
|
||||||
metadata_form.fields["new_stock"].queryset = Stock.objects.filter(
|
|
||||||
club=self.club
|
|
||||||
).exclude(pk=self.stock.pk)
|
|
||||||
form.blocks.append(
|
|
||||||
{
|
|
||||||
"action": operation_type.value,
|
|
||||||
"label": operation_type.label,
|
|
||||||
"form": metadata_form,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return form
|
|
||||||
|
|
||||||
def build_formset(self, instance=None, *, bound=False, active_operation_type=None):
|
|
||||||
kwargs = {"instance": instance, "prefix": "item_action"}
|
|
||||||
if bound:
|
|
||||||
kwargs.update(data=self.request.POST, files=self.request.FILES)
|
|
||||||
formset = StockItemActionFormSet(**kwargs)
|
|
||||||
item_queryset = (
|
|
||||||
StockItemStock.objects.filter(stock=self.stock)
|
|
||||||
.select_related("item")
|
|
||||||
.order_by("item__name")
|
|
||||||
)
|
|
||||||
for item_action_form in (*formset.forms, formset.empty_form):
|
|
||||||
item_action_form.fields["item"].queryset = item_queryset
|
|
||||||
self.attach_metadata_forms(
|
|
||||||
item_action_form, active_operation_type if bound else None
|
|
||||||
)
|
|
||||||
return formset
|
|
||||||
|
|
||||||
def live_forms(self, formset):
|
|
||||||
return [
|
|
||||||
f
|
|
||||||
for f in formset.forms
|
|
||||||
if f not in formset.deleted_forms and f.has_changed()
|
|
||||||
]
|
|
||||||
|
|
||||||
def active_metadata_form(self, item_action_form, operation_type):
|
|
||||||
return next(
|
|
||||||
(
|
|
||||||
block["form"]
|
|
||||||
for block in item_action_form.blocks
|
|
||||||
if block["action"] == operation_type
|
|
||||||
),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
|
|
||||||
def render_form(self, form, formset):
|
|
||||||
empty = self.attach_metadata_forms(formset.empty_form)
|
|
||||||
return self.render_to_response(
|
|
||||||
self.get_context_data(form=form, formset=formset, empty_form=empty)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
|
||||||
ctx = super().get_context_data(**kwargs)
|
|
||||||
if "formset" not in ctx:
|
|
||||||
ctx["formset"] = self.build_formset()
|
|
||||||
ctx["empty_form"] = self.attach_metadata_forms(ctx["formset"].empty_form)
|
|
||||||
ctx["stock"] = self.stock
|
|
||||||
return ctx
|
|
||||||
|
|
||||||
def form_valid(self, form):
|
|
||||||
self.object = form.save(commit=False)
|
|
||||||
operation_type = self.object.action
|
|
||||||
formset = self.build_formset(
|
|
||||||
self.object,
|
|
||||||
bound=True,
|
|
||||||
active_operation_type=operation_type,
|
|
||||||
)
|
|
||||||
|
|
||||||
ok = formset.is_valid()
|
|
||||||
if ok:
|
|
||||||
for item_action_form in self.live_forms(formset):
|
|
||||||
metadata_form = self.active_metadata_form(
|
|
||||||
item_action_form, operation_type
|
|
||||||
)
|
|
||||||
if metadata_form is not None:
|
|
||||||
ok = metadata_form.is_valid() and ok
|
|
||||||
|
|
||||||
if ok:
|
|
||||||
stock_actions, item_actions, metadata_entries = self.serialize_forms(
|
|
||||||
form, formset, operation_type
|
|
||||||
)
|
|
||||||
|
|
||||||
with transaction.atomic():
|
|
||||||
stock_items = (
|
|
||||||
StockItemStock.objects.select_for_update()
|
|
||||||
.select_related("item")
|
|
||||||
.in_bulk(item_action.item_id for item_action in item_actions)
|
|
||||||
)
|
|
||||||
for item_action in item_actions:
|
|
||||||
item_action.item = stock_items[item_action.item_id]
|
|
||||||
|
|
||||||
try:
|
|
||||||
if operation_type == OperationType.TransferTo:
|
|
||||||
(
|
|
||||||
destination_stock_action,
|
|
||||||
destination_stock_items,
|
|
||||||
destination_item_actions,
|
|
||||||
) = apply_transfer(
|
|
||||||
stock_items,
|
|
||||||
item_actions,
|
|
||||||
metadata_entries,
|
|
||||||
user=stock_actions[0].user,
|
|
||||||
source_stock=self.stock,
|
|
||||||
)
|
|
||||||
stock_actions.append(destination_stock_action)
|
|
||||||
item_actions.extend(destination_item_actions)
|
|
||||||
stock_items.update(
|
|
||||||
{item.pk: item for item in destination_stock_items}
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
update_quantities(
|
|
||||||
stock_items, item_actions, metadata_entries, operation_type
|
|
||||||
)
|
|
||||||
except forms.ValidationError as error:
|
|
||||||
error.message = error.message + _(
|
|
||||||
" Check if the quantity has not changed."
|
|
||||||
)
|
|
||||||
form.add_error(None, error)
|
|
||||||
transaction.set_rollback(True)
|
|
||||||
return self.render_form(form, formset)
|
|
||||||
|
|
||||||
self.save_all(
|
|
||||||
list(stock_items.values()),
|
|
||||||
stock_actions,
|
|
||||||
item_actions,
|
|
||||||
metadata_entries,
|
|
||||||
)
|
|
||||||
return HttpResponseRedirect(self.get_success_url())
|
|
||||||
return self.render_form(form, formset)
|
|
||||||
|
|
||||||
def form_invalid(self, form):
|
|
||||||
formset = self.build_formset(
|
|
||||||
form.instance,
|
|
||||||
bound=True,
|
|
||||||
active_operation_type=self.posted_operation_type(),
|
|
||||||
)
|
|
||||||
return self.render_form(form, formset)
|
|
||||||
|
|
||||||
def save_all(self, stock_items, stock_actions, item_actions, metadata_entries):
|
|
||||||
# MariaDB dosen't populate IDs after bulk_create, But we dont use it
|
|
||||||
StockAction.objects.bulk_create(stock_actions, batch_size=1000)
|
|
||||||
StockItemAction.objects.bulk_create(item_actions, batch_size=1000)
|
|
||||||
if metadata_entries:
|
|
||||||
type(metadata_entries[0]).objects.bulk_create(
|
|
||||||
metadata_entries, batch_size=1000
|
|
||||||
)
|
|
||||||
StockItemStock.objects.bulk_update(stock_items, ["quantity"], batch_size=1000)
|
|
||||||
|
|
||||||
def serialize_forms(self, form, formset, operation_type):
|
|
||||||
stock_action = form.save(commit=False)
|
|
||||||
stock_action.user = self.request.user
|
|
||||||
item_action_forms = self.live_forms(formset)
|
|
||||||
item_actions = [
|
|
||||||
item_action_form.save(commit=False)
|
|
||||||
for item_action_form in item_action_forms
|
|
||||||
]
|
|
||||||
for _item_action_form, item_action in zip(
|
|
||||||
item_action_forms, item_actions, strict=True
|
|
||||||
):
|
|
||||||
item_action.action = stock_action
|
|
||||||
|
|
||||||
metadata_entries = []
|
|
||||||
for item_action_form, item_action in zip(
|
|
||||||
item_action_forms, item_actions, strict=True
|
|
||||||
):
|
|
||||||
metadata_form = self.active_metadata_form(item_action_form, operation_type)
|
|
||||||
if metadata_form is None or (
|
|
||||||
not self.metadata_required and not metadata_form.has_changed()
|
|
||||||
):
|
|
||||||
continue
|
|
||||||
metadata_entry = metadata_form.save(commit=False)
|
|
||||||
metadata_entry.item_action = item_action
|
|
||||||
if operation_type == OperationType.TransferTo:
|
|
||||||
metadata_entry.old_stock = self.stock
|
|
||||||
metadata_entries.append(metadata_entry)
|
|
||||||
return [stock_action], item_actions, metadata_entries
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
self.club = get_object_or_404(Club, pk=kwargs["club_id"])
|
|
||||||
self.stock = get_object_or_404(Stock, pk=kwargs["stock_id"], club=self.club)
|
|
||||||
return super().dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def get_success_url(self):
|
|
||||||
return reverse(
|
|
||||||
"stock:items_list",
|
|
||||||
kwargs={"club_id": self.club.id, "stock_id": self.stock.id},
|
|
||||||
)
|
|
||||||
Whitespace-only changes.
@@ -1,21 +0,0 @@
|
|||||||
from core.views.widgets.ajax_select import AutoCompleteSelect
|
|
||||||
|
|
||||||
|
|
||||||
class StockItemSelect(AutoCompleteSelect):
|
|
||||||
def get_context(self, name, value, attrs):
|
|
||||||
self._quantities = {
|
|
||||||
str(item.pk): item.quantity
|
|
||||||
for item in self.choices.queryset.only("pk", "quantity", "item__name")
|
|
||||||
}
|
|
||||||
return super().get_context(name, value, attrs)
|
|
||||||
|
|
||||||
def create_option(
|
|
||||||
self, name, value, label, selected, index, subindex=None, attrs=None
|
|
||||||
):
|
|
||||||
option = super().create_option(
|
|
||||||
name, value, label, selected, index, subindex=subindex, attrs=attrs
|
|
||||||
)
|
|
||||||
quantity = self._quantities.get(str(value))
|
|
||||||
if quantity is not None:
|
|
||||||
option["attrs"]["data-quantity"] = str(quantity)
|
|
||||||
return option
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# Generated by Django 5.2.18 on 2026-11-09 01:33
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("timetable", "0001_initial"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="timetableslot",
|
|
||||||
name="week_group",
|
|
||||||
field=models.CharField(
|
|
||||||
blank=True,
|
|
||||||
choices=[("A", "A"), ("B", "B"), ("", "Both")],
|
|
||||||
default="",
|
|
||||||
max_length=1,
|
|
||||||
verbose_name="week group",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -703,6 +703,19 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/f1/ae/63083bf0614a80857e264b9d3ae16af2e2eff7372da6e249abec7919cb0b/django_jinja-2.11.0-py3-none-any.whl", hash = "sha256:cc4c72246a6e346aa0574e0c56c3e534c1a20ef47b8476f05d7287781f69a0a9", size = 23748, upload-time = "2023-09-03T21:20:43.482Z" },
|
{ url = "https://files.pythonhosted.org/packages/f1/ae/63083bf0614a80857e264b9d3ae16af2e2eff7372da6e249abec7919cb0b/django_jinja-2.11.0-py3-none-any.whl", hash = "sha256:cc4c72246a6e346aa0574e0c56c3e534c1a20ef47b8476f05d7287781f69a0a9", size = 23748, upload-time = "2023-09-03T21:20:43.482Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "django-modeltranslation"
|
||||||
|
version = "0.20.6"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "django" },
|
||||||
|
{ name = "typing-extensions" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/a9/b7/049969e77ff4825836c78312b3b82bd58f94162ffe20bc46500f98391731/django_modeltranslation-0.20.6.tar.gz", hash = "sha256:29eb584f017206a0bea5e2a44ae5da514ad6ebf1e43536ff7fed7df67b795b0c", size = 82542, upload-time = "2026-09-07T12:03:24.651Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ab/55/dfd72b735f50bb633409326311598d9a5bc861ee81ae3d137844ab903add/django_modeltranslation-0.20.6-py3-none-any.whl", hash = "sha256:913658af75510a4f71573441f267b5831a6034c524f917f337adc666a60fe724", size = 99206, upload-time = "2026-09-07T12:03:23.238Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "django-ninja"
|
name = "django-ninja"
|
||||||
version = "1.7.3"
|
version = "1.7.3"
|
||||||
@@ -2061,6 +2074,7 @@ dependencies = [
|
|||||||
{ name = "django-haystack" },
|
{ name = "django-haystack" },
|
||||||
{ name = "django-honeypot" },
|
{ name = "django-honeypot" },
|
||||||
{ name = "django-jinja" },
|
{ name = "django-jinja" },
|
||||||
|
{ name = "django-modeltranslation" },
|
||||||
{ name = "django-ninja" },
|
{ name = "django-ninja" },
|
||||||
{ name = "django-ninja-extra" },
|
{ name = "django-ninja-extra" },
|
||||||
{ name = "django-ordered-model" },
|
{ name = "django-ordered-model" },
|
||||||
@@ -2129,6 +2143,7 @@ requires-dist = [
|
|||||||
{ name = "django-haystack", specifier = ">=3.4.0,<4.0.0" },
|
{ name = "django-haystack", specifier = ">=3.4.0,<4.0.0" },
|
||||||
{ name = "django-honeypot", specifier = ">=1.3.0,<2" },
|
{ name = "django-honeypot", specifier = ">=1.3.0,<2" },
|
||||||
{ name = "django-jinja", specifier = ">=2.11.0,<3.0.0" },
|
{ name = "django-jinja", specifier = ">=2.11.0,<3.0.0" },
|
||||||
|
{ name = "django-modeltranslation", specifier = ">=0.20.6" },
|
||||||
{ name = "django-ninja", specifier = ">=1.7.1,<2.0.0" },
|
{ name = "django-ninja", specifier = ">=1.7.1,<2.0.0" },
|
||||||
{ name = "django-ninja-extra", specifier = ">=0.31.7" },
|
{ name = "django-ninja-extra", specifier = ">=0.31.7" },
|
||||||
{ name = "django-ordered-model", specifier = ">=3.7.4,<4.0.0" },
|
{ name = "django-ordered-model", specifier = ">=3.7.4,<4.0.0" },
|
||||||
|
|||||||
Reference in new issue
Block a user