diff --git a/.github/actions/setup_project/action.yml b/.github/actions/setup_project/action.yml index 720d36bc..74f2b9ad 100644 --- a/.github/actions/setup_project/action.yml +++ b/.github/actions/setup_project/action.yml @@ -18,10 +18,7 @@ runs: version: 1.0 # increment to reset cache - name: Install Redis - if: ${{ inputs.full == 'true' }} uses: shogo82148/actions-setup-redis@v1 - with: - redis-version: "7.x" - name: "Set up Python" uses: actions/setup-python@v6 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e92bf82e..766ffec1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,17 @@ jobs: with: extra_args: --all-files + migration-check: + name: Check missing migrations + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: ./.github/actions/setup_project + with: + full: false + - name: check migrations + run: uv run ./manage.py makemigrations --check + tests: name: Run tests and generate coverage report runs-on: ubuntu-latest diff --git a/antispam/forms.py b/antispam/forms.py index 0e327f2a..6576322c 100644 --- a/antispam/forms.py +++ b/antispam/forms.py @@ -2,7 +2,7 @@ from django import forms from django.core.validators import EmailValidator from django.utils.translation import gettext_lazy as _ -from antispam.models import ToxicDomain +from antispam.models.models import ToxicDomain class AntiSpamEmailValidator(EmailValidator): @@ -17,6 +17,6 @@ validate_antispam_email = AntiSpamEmailValidator() class AntiSpamEmailField(forms.EmailField): - """An email field that email addresses with a known toxic domain.""" + """An email field that forbids email addresses with a known toxic domain.""" default_validators = [validate_antispam_email] diff --git a/antispam/management/commands/update_spam_database.py b/antispam/management/commands/update_spam_database.py index 2761c649..d4e40d2c 100644 --- a/antispam/management/commands/update_spam_database.py +++ b/antispam/management/commands/update_spam_database.py @@ -38,22 +38,31 @@ class Command(BaseCommand): return domains def _update_domains(self, domains: set[str]): - # Cleanup database - ToxicDomain.objects.filter(is_externally_managed=True).delete() - - # Create database - ToxicDomain.objects.bulk_create( - [ - ToxicDomain(domain=domain, is_externally_managed=True) - for domain in domains - ], - ignore_conflicts=True, - ) + existing = set(ToxicDomain.objects.values_list("domain", flat=True)) + if existing == domains: + self.stdout.write("Domain database was up to date") + return + if to_remove := (existing - domains): + # Cleanup database + ToxicDomain.objects.filter( + domain__in=to_remove, is_externally_managed=True + ).delete() + if to_create := (domains - existing): + # Create database + ToxicDomain.objects.bulk_create( + [ + ToxicDomain(domain=domain, is_externally_managed=True) + for domain in to_create + ], + ignore_conflicts=True, + ) self.stdout.write("Domain database updated") def handle(self, *args, **options): if not self._should_update(force=options["force"]): - self.stdout.write("Domain database is up to date") + self.stdout.write( + "No update required. Use --force if you want to do it anyway." + ) return self.stdout.write("Updating domain database") diff --git a/antispam/models/__init__.py b/antispam/models/__init__.py new file mode 100644 index 00000000..ab6041d3 --- /dev/null +++ b/antispam/models/__init__.py @@ -0,0 +1,4 @@ +from antispam.models.fields import AntiSpamEmailField +from antispam.models.models import ToxicDomain + +__all__ = ["AntiSpamEmailField", "ToxicDomain"] diff --git a/antispam/models/fields.py b/antispam/models/fields.py new file mode 100644 index 00000000..cc747e0b --- /dev/null +++ b/antispam/models/fields.py @@ -0,0 +1,21 @@ +from django.conf import settings +from django.db import models + +from antispam import forms + + +class AntiSpamEmailField(models.EmailField): + """An email field that forbids email addresses with a known toxic domain.""" + + default_validators = [forms.validate_antispam_email] + + +if settings.TESTING: + from model_bakery import baker + + baker.generators.add( + AntiSpamEmailField, lambda: baker.random_gen.gen_email(max_length=100) + ) +else: # pragma: no cover + # baker is only used in tests, so we don't need coverage for this part + pass diff --git a/antispam/models.py b/antispam/models/models.py similarity index 100% rename from antispam/models.py rename to antispam/models/models.py diff --git a/antispam/tests/__init__.py b/antispam/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/club/forms.py b/club/forms.py index 80d4c058..f14a545f 100644 --- a/club/forms.py +++ b/club/forms.py @@ -31,20 +31,10 @@ from django.forms.models import ModelChoiceField, ModelChoiceIterator from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ -from club.models import ( - Club, - ClubLink, - ClubRole, - Mailing, - MailingSubscription, - Membership, -) +from club.models import Club, ClubLink, ClubRole, Membership from core.models import User from core.views.forms import SelectDateTime -from core.views.widgets.ajax_select import ( - AutoCompleteSelectMultipleUser, - AutoCompleteSelectUser, -) +from core.views.widgets.ajax_select import AutoCompleteSelectUser from counter.models import Counter, Selling from counter.schemas import SaleFilterSchema @@ -131,107 +121,6 @@ class ClubAdminEditForm(ClubEditForm): fields = ["name", "parent", "is_active", *ClubEditForm.Meta.fields] -class MailingForm(forms.Form): - """Form handling mailing lists right.""" - - ACTION_NEW_MAILING = 1 - ACTION_NEW_SUBSCRIPTION = 2 - ACTION_REMOVE_SUBSCRIPTION = 3 - - subscription_users = forms.ModelMultipleChoiceField( - label=_("Users to add"), - help_text=_("Search users to add (one or more)."), - required=False, - widget=AutoCompleteSelectMultipleUser, - queryset=User.objects.all(), - ) - - def __init__(self, club_id, user_id, mailings, *args, **kwargs): - super().__init__(*args, **kwargs) - - self.fields["action"] = forms.TypedChoiceField( - choices=( - (self.ACTION_NEW_MAILING, _("New Mailing")), - (self.ACTION_NEW_SUBSCRIPTION, _("Subscribe")), - (self.ACTION_REMOVE_SUBSCRIPTION, _("Remove")), - ), - coerce=int, - label=_("Action"), - initial=1, - required=True, - widget=forms.HiddenInput(), - ) - - # Generate bulk removal forms, they are never required - for mailing in mailings: - self.fields["removal_" + str(mailing.id)] = forms.ModelMultipleChoiceField( - mailing.subscriptions.all(), - label=_("Remove"), - required=False, - widget=forms.CheckboxSelectMultiple, - ) - - # Include fields for handling mailing creation - mailing_fields = ("email",) - self.fields.update(forms.fields_for_model(Mailing, fields=mailing_fields)) - for field in mailing_fields: - self.fields["mailing_" + field] = self.fields.pop(field) - self.fields["mailing_" + field].required = False - - # Include fields for handling subscription creation - subscription_fields = ("mailing", "email") - self.fields.update( - forms.fields_for_model(MailingSubscription, fields=subscription_fields) - ) - for field in subscription_fields: - self.fields["subscription_" + field] = self.fields.pop(field) - self.fields["subscription_" + field].required = False - - self.fields["subscription_mailing"].queryset = Mailing.objects.filter( - club__id=club_id, is_moderated=True - ) - - def check_required(self, cleaned_data, field): - """If the given field doesn't exist or has no value, add a required error on it.""" - if not cleaned_data.get(field, None): - self.add_error(field, _("This field is required")) - - def clean_subscription_users(self): - """Convert given users into real users and check their validity.""" - cleaned_data = super().clean() - users = [] - for user in cleaned_data["subscription_users"]: - if not user.email: - raise forms.ValidationError( - _("One of the selected users doesn't have an email address"), - code="invalid", - ) - users.append(user) - return users - - def clean(self): - cleaned_data = super().clean() - - if "action" not in cleaned_data: - # If there is no action provided, we can stop here - raise forms.ValidationError(_("An action is required"), code="invalid") - - if cleaned_data["action"] == self.ACTION_NEW_MAILING: - self.check_required(cleaned_data, "mailing_email") - - if cleaned_data["action"] == self.ACTION_NEW_SUBSCRIPTION: - self.check_required(cleaned_data, "subscription_mailing") - if not cleaned_data.get( - "subscription_users", None - ) and not cleaned_data.get("subscription_email", None): - raise forms.ValidationError( - _("You must specify at least an user or an email address"), - code="invalid", - ) - - return cleaned_data - - class SellingsForm(forms.Form): begin_date = forms.DateTimeField( label=_("Begin date"), widget=SelectDateTime, required=False @@ -413,12 +302,22 @@ class ClubRoleForm(forms.ModelForm): class Meta: model = ClubRole - fields = ["name", "description", "is_presidency", "is_board", "is_active"] + fields = [ + "name", + "name_en", + "description", + "is_presidency", + "is_board", + "is_active", + ] widgets = { "is_presidency": forms.HiddenInput(), "is_board": forms.HiddenInput(), "is_active": forms.CheckboxInput(attrs={"class": "switch"}), } + help_texts = { + "name_en": _("Provide an english name for non-french speaking users.") + } def clean(self): cleaned_data = super().clean() @@ -465,7 +364,10 @@ class ClubRoleCreateForm(forms.ModelForm): class Meta: 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__( self, *args, club: Club, is_presidency: bool, is_board: bool, **kwargs diff --git a/club/migrations/0019_remove_mailingsubscription_mailing_and_more.py b/club/migrations/0019_remove_mailingsubscription_mailing_and_more.py new file mode 100644 index 00000000..de4046c6 --- /dev/null +++ b/club/migrations/0019_remove_mailingsubscription_mailing_and_more.py @@ -0,0 +1,16 @@ +# Generated by Django 5.2.17 on 2026-10-15 13:13 + +from django.db import migrations + + +class Migration(migrations.Migration): + dependencies = [("club", "0018_clubrole_linked_groups")] + + operations = [ + migrations.AlterUniqueTogether( + name="mailingsubscription", unique_together=None + ), + migrations.RemoveField(model_name="mailingsubscription", name="user"), + migrations.DeleteModel(name="Mailing"), + migrations.DeleteModel(name="MailingSubscription"), + ] diff --git a/club/migrations/0020_clubrole_name_en_clubrole_name_fr.py b/club/migrations/0020_clubrole_name_en_clubrole_name_fr.py new file mode 100644 index 00000000..257048b7 --- /dev/null +++ b/club/migrations/0020_clubrole_name_en_clubrole_name_fr.py @@ -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 + ), + ] diff --git a/club/models.py b/club/models.py index e9ad358e..e300b346 100644 --- a/club/models.py +++ b/club/models.py @@ -28,8 +28,7 @@ from functools import reduce from typing import Iterable, Self from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist, ValidationError -from django.core.validators import RegexValidator, validate_email +from django.core.exceptions import ValidationError from django.db import ProgrammingError, models, transaction from django.db.models import Exists, F, OuterRef, Q from django.urls import reverse @@ -41,7 +40,7 @@ from django.utils.translation import gettext_lazy as _ from ordered_model.models import OrderedModel from core.fields import ResizedImageField -from core.models import Group, Notification, Page, SithFile, User +from core.models import Group, Page, SithFile, User class ClubQuerySet(models.QuerySet): @@ -308,7 +307,12 @@ class ClubRole(OrderedModel): violation_error_message=_( "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): @@ -633,169 +637,6 @@ class Membership(models.Model): return User.groups.through.objects.bulk_create(groups, ignore_conflicts=True) -class Mailing(models.Model): - """A Mailing list for a club. - - Warning: - Remember that mailing lists should be validated by UTBM. - """ - - club = models.ForeignKey( - Club, - verbose_name=_("Club"), - related_name="mailings", - null=False, - blank=False, - on_delete=models.CASCADE, - ) - email = models.CharField( - _("Email address"), - unique=True, - null=False, - blank=False, - max_length=256, - validators=[ - RegexValidator( - validate_email.user_regex, - _("Enter a valid address. Only the root of the address is needed."), - ) - ], - ) - is_moderated = models.BooleanField(_("is moderated"), default=False) - moderator = models.ForeignKey( - User, - related_name="moderated_mailings", - verbose_name=_("moderator"), - null=True, - on_delete=models.CASCADE, - ) - - def __str__(self): - return "%s - %s" % (self.club, self.email_full) - - def save(self, *args, **kwargs): - if not self.is_moderated: - unread_notif_subquery = Notification.objects.filter( - user=OuterRef("pk"), type="MAILING_MODERATION", viewed=False - ) - for user in User.objects.filter( - ~Exists(unread_notif_subquery), - groups__id__in=[settings.SITH_GROUP_COM_ADMIN_ID], - ): - Notification( - user=user, - url=reverse("com:mailing_admin"), - type="MAILING_MODERATION", - ).save(*args, **kwargs) - super().save(*args, **kwargs) - - def clean(self): - if Mailing.objects.filter(email=self.email).exists(): - raise ValidationError(_("This mailing list already exists.")) - if self.can_moderate(self.moderator): - self.is_moderated = True - else: - self.moderator = None - super().clean() - - @property - def email_full(self): - return self.email + "@" + settings.SITH_MAILING_DOMAIN - - def can_moderate(self, user): - return user.is_root or user.is_com_admin - - def is_owned_by(self, user): - if user.is_anonymous: - return False - return user.is_root or user.is_com_admin - - def can_view(self, user): - return self.club.has_rights_in_club(user) - - def can_be_edited_by(self, user): - return self.club.has_rights_in_club(user) - - def delete(self, *args, **kwargs): - self.subscriptions.all().delete() - super().delete() - - def fetch_format(self): - destination = "".join(s.fetch_format() for s in self.subscriptions.all()) - return f"{self.email}: {destination}" - - -class MailingSubscription(models.Model): - """Link between user and mailing list.""" - - mailing = models.ForeignKey( - Mailing, - verbose_name=_("Mailing"), - related_name="subscriptions", - null=False, - blank=False, - on_delete=models.CASCADE, - ) - user = models.ForeignKey( - User, - verbose_name=_("User"), - related_name="mailing_subscriptions", - null=True, - blank=True, - on_delete=models.CASCADE, - ) - email = models.EmailField(_("Email address"), blank=False, null=False) - - class Meta: - unique_together = (("user", "email", "mailing"),) - - def __str__(self): - return "(%s) - %s : %s" % (self.mailing, self.get_username, self.email) - - def clean(self): - if not self.user and not self.email: - raise ValidationError(_("At least user or email is required")) - try: - if self.user and not self.email: - self.email = self.user.email - if MailingSubscription.objects.filter( - mailing=self.mailing, email=self.email - ).exists(): - raise ValidationError( - _("This email is already suscribed in this mailing") - ) - except ObjectDoesNotExist: - pass - super().clean() - - def is_owned_by(self, user): - if user.is_anonymous: - return False - return ( - self.mailing.club.has_rights_in_club(user) - or user.is_root - or self.user.is_com_admin - ) - - def can_be_edited_by(self, user): - return self.user is not None and user.id == self.user.id - - @cached_property - def get_email(self): - if self.user and not self.email: - return self.user.email - return self.email - - @cached_property - def get_username(self): - if self.user: - return str(self.user) - return _("Unregistered user") - - def fetch_format(self): - return self.get_email + " " - - class LinkType(models.Model): """A link type, in order to group links and give them icons. diff --git a/club/templates/club/club_roles.jinja b/club/templates/club/club_roles.jinja index bb860f10..f312d28e 100644 --- a/club/templates/club/club_roles.jinja +++ b/club/templates/club/club_roles.jinja @@ -37,6 +37,9 @@
{{ subform.name.as_field_group() }}
+
+ {{ subform.name_en.as_field_group() }} +
{{ subform.description.as_field_group() }}
diff --git a/club/templates/club/club_tools.jinja b/club/templates/club/club_tools.jinja index a69d5c26..3c4e2e6e 100644 --- a/club/templates/club/club_tools.jinja +++ b/club/templates/club/club_tools.jinja @@ -15,9 +15,6 @@ {% trans %}Post in the Weekmail{% endtrans %} - {% if object.can_roles_be_edited_by(user) %} -
  • - {% endif %} {% if object.trombi %}
  • {% trans %}Edit Trombi{% endtrans %}
  • {% else %} diff --git a/club/templates/club/mailing.jinja b/club/templates/club/mailing.jinja deleted file mode 100644 index a7421602..00000000 --- a/club/templates/club/mailing.jinja +++ /dev/null @@ -1,108 +0,0 @@ -{% extends "core/base.jinja" %} -{% from 'core/macros.jinja' import select_all_checkbox %} - -{% block title %} - {% trans %}Mailing lists{% endtrans %} -{% endblock %} - -{% block content %} - - {% trans %}Remember : mailing lists need to be moderated, if your new created list is not shown wait until moderation takes action{% endtrans %} - - {% if mailings_not_moderated %} -

    {% trans %}Mailing lists waiting for moderation{% endtrans %}

    - - {% endif %} - - {% if mailings_moderated %} - {% for mailing in mailings_moderated %} -

    {% trans %}Mailing{% endtrans %} {{ mailing.email_full }} - {%- if user.is_owner(mailing) -%} - - {% trans %}Delete{% endtrans %} - {%- endif -%} -

    -
    - -
    - {% set form_mailing_removal = form["removal_" + mailing.id|string] %} - {% if form_mailing_removal.field.choices %} - {% set ms = dict(mailing.subscriptions.all() | groupby('id')) %} -
    -

    {{ select_all_checkbox(form_mailing_removal.auto_id) }}

    - {% csrf_token %} - - - - - - - - - - - {% for widget in form_mailing_removal.subwidgets %} - {% set user = ms[widget.data.value.value][0] %} - - - - - - {% endfor %} - -
    {% trans %}User{% endtrans %}{% trans %}Email{% endtrans %}{% trans %}Delete{% endtrans %}
    {{ user.get_username }}{{ user.get_email }}{{ widget.tag() }}
    - {{ form_mailing_removal.errors }} -

    -
    - - {% else %} -

    {% trans %}There is no subscriber for this mailing list{% endtrans %}

    - {% endif %} - {% endfor %} - - {% else %} -

    {% trans %}No mailing list existing for this club{% endtrans %}

    - {% endif %} - -

    {{ form.non_field_errors() }}

    - {% if mailings_moderated %} -

    {% trans %}New member{% endtrans %}

    -
    - {% csrf_token %} -

    - {{ form.subscription_mailing.errors }} - - {{ form.subscription_mailing }} -

    -

    - {{ form.subscription_users.errors }} - - {{ form.subscription_users }} - {{ form.subscription_users.help_text }} -

    -

    - {{ form.subscription_email.errors }} - - {{ form.subscription_email }} -

    - -

    -
    - {% endif %} - -

    {% trans %}New mailing{% endtrans %}

    -
    - {% csrf_token %} -

    - {{ form.mailing_email.errors }} - - {{ form.mailing_email }} -

    - -

    -
    - -{% endblock %} diff --git a/club/tests/test_clubrole.py b/club/tests/test_clubrole.py index 983c2aa4..3a6121cc 100644 --- a/club/tests/test_clubrole.py +++ b/club/tests/test_clubrole.py @@ -4,6 +4,7 @@ import pytest from django.contrib.auth.models import Permission from django.test import Client, TestCase from django.urls import reverse +from django.utils import translation from django.utils.timezone import now from model_bakery import baker, seq 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 assert members[0].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 diff --git a/club/tests/test_mailing.py b/club/tests/test_mailing.py deleted file mode 100644 index 2217281c..00000000 --- a/club/tests/test_mailing.py +++ /dev/null @@ -1,328 +0,0 @@ -from django.conf import settings -from django.test import TestCase -from django.urls import reverse -from django.utils import timezone -from django.utils.translation import gettext as _ -from model_bakery import baker - -from club.forms import MailingForm -from club.models import Club, ClubRole, Mailing, Membership -from core.models import User - - -class TestMailingForm(TestCase): - """Perform validation tests for MailingForm.""" - - @classmethod - def setUpTestData(cls): - cls.skia = User.objects.get(username="skia") - cls.rbatsbak = User.objects.get(username="rbatsbak") - cls.krophil = User.objects.get(username="krophil") - cls.comunity = User.objects.get(username="comunity") - cls.root = User.objects.get(username="root") - cls.club = Club.objects.get(id=settings.SITH_PDF_CLUB_ID) - cls.mail_url = reverse("club:mailing", kwargs={"club_id": cls.club.id}) - Membership( - user=cls.rbatsbak, - club=cls.club, - start_date=timezone.now(), - role=baker.make(ClubRole, club=cls.club, is_board=True), - ).save() - - def test_mailing_list_add_no_moderation(self): - # Test with Communication admin - self.client.force_login(self.comunity) - response = self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "foyer"}, - ) - self.assertRedirects(response, self.mail_url) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - assert "Liste de diffusion foyer@utbm.fr" in response.text - - # Test with Root - self.client.force_login(self.root) - self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"}, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - assert "Liste de diffusion mde@utbm.fr" in response.text - - def test_mailing_list_add_moderation(self): - self.client.force_login(self.rbatsbak) - self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"}, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - assert "Liste de diffusion mde@utbm.fr" not in content - assert "

    Listes de diffusions en attente de modération

    " in content - assert "
  • mde@utbm.fr" in content - - def test_mailing_list_forbidden(self): - # With anonymous user - response = self.client.get(self.mail_url) - self.assertContains(response, "", status_code=403) - - # With user not in club - self.client.force_login(self.krophil) - response = self.client.get(self.mail_url) - assert response.status_code == 403 - - def test_add_new_subscription_fail_not_moderated(self): - self.client.force_login(self.rbatsbak) - self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"}, - ) - - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": self.skia.id, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - assert "skia@git.an" not in response.text - - def test_add_new_subscription_success(self): - # Prepare mailing list - self.client.force_login(self.comunity) - self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"}, - ) - - # Add single user - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": self.skia.id, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - assert "skia@git.an" in response.text - - # Add multiple users - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": (self.comunity.id, self.rbatsbak.id), - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - assert "richard@git.an" in content - assert "comunity@git.an" in content - assert "skia@git.an" in content - - # Add arbitrary email - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_email": "arbitrary@git.an", - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - assert "richard@git.an" in content - assert "comunity@git.an" in content - assert "skia@git.an" in content - assert "arbitrary@git.an" in content - - # Add user and arbitrary email - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_email": "more.arbitrary@git.an", - "subscription_users": self.krophil.id, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - assert "richard@git.an" in content - assert "comunity@git.an" in content - assert "skia@git.an" in content - assert "arbitrary@git.an" in content - assert "more.arbitrary@git.an" in content - assert "krophil@git.an" in content - - def test_add_new_subscription_fail_form_errors(self): - # Prepare mailing list - self.client.force_login(self.comunity) - self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"}, - ) - - # Neither email or email is specified - response = self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - assert response.status_code - self.assertInHTML( - _("You must specify at least an user or an email address"), - response.text, - ) - - # No mailing specified - response = self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": self.krophil.id, - }, - ) - assert response.status_code == 200 - assert _("This field is required") in response.text - - # One of the selected users doesn't exist - response = self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": [789], - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - assert response.status_code == 200 - self.assertInHTML( - _("You must specify at least an user or an email address"), - response.text, - ) - - # An user has no email address - self.krophil.email = "" - self.krophil.save() - - response = self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": self.krophil.id, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - assert response.status_code == 200 - self.assertInHTML( - _("One of the selected users doesn't have an email address"), - response.text, - ) - - self.krophil.email = "krophil@git.an" - self.krophil.save() - - # An user is added twice - - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": self.krophil.id, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - - response = self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": self.krophil.id, - "subscription_mailing": Mailing.objects.get(email="mde").id, - }, - ) - assert response.status_code == 200 - self.assertInHTML( - _("This email is already suscribed in this mailing"), - response.text, - ) - - def test_remove_subscription_success(self): - # Prepare mailing list - self.client.force_login(self.comunity) - self.client.post( - self.mail_url, - {"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"}, - ) - mde = Mailing.objects.get(email="mde") - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_NEW_SUBSCRIPTION, - "subscription_users": ( - self.comunity.id, - self.rbatsbak.id, - self.krophil.id, - ), - "subscription_mailing": mde.id, - }, - ) - - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - - assert "comunity@git.an" in content - assert "richard@git.an" in content - assert "krophil@git.an" in content - - # Delete one user - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_REMOVE_SUBSCRIPTION, - "removal_%d" % mde.id: mde.subscriptions.get(user=self.krophil).id, - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - - assert "comunity@git.an" in content - assert "richard@git.an" in content - assert "krophil@git.an" not in content - - # Delete multiple users - self.client.post( - self.mail_url, - { - "action": MailingForm.ACTION_REMOVE_SUBSCRIPTION, - "removal_%d" % mde.id: [ - user.id - for user in mde.subscriptions.filter( - user__in=[self.rbatsbak, self.comunity] - ).all() - ], - }, - ) - response = self.client.get(self.mail_url) - assert response.status_code == 200 - content = response.text - - assert "comunity@git.an" not in content - assert "richard@git.an" not in content - assert "krophil@git.an" not in content diff --git a/club/translation.py b/club/translation.py new file mode 100644 index 00000000..ff402d87 --- /dev/null +++ b/club/translation.py @@ -0,0 +1,8 @@ +from modeltranslation.translator import TranslationOptions, register + +from club.models import ClubRole + + +@register(ClubRole) +class ClubRoleTranslationOptions(TranslationOptions): + fields = ("name",) diff --git a/club/urls.py b/club/urls.py index d5b9f1a5..4d29d30b 100644 --- a/club/urls.py +++ b/club/urls.py @@ -29,7 +29,6 @@ from club.views import ( ClubCreateView, ClubEditView, ClubListView, - ClubMailingView, ClubMembersView, ClubNewsView, ClubOldMembersView, @@ -44,9 +43,6 @@ from club.views import ( ClubSellingView, ClubToolsView, ClubView, - MailingAutoGenerationView, - MailingDeleteView, - MailingSubscriptionDeleteView, MembershipDeleteView, MembershipSetOldView, PosterCreateView, @@ -97,22 +93,6 @@ urlpatterns = [ "/sellings/csv/", ClubSellingCSVView.as_view(), name="sellings_csv" ), path("/tools/", ClubToolsView.as_view(), name="tools"), - path("/mailing/", ClubMailingView.as_view(), name="mailing"), - path( - "/mailing/generate/", - MailingAutoGenerationView.as_view(), - name="mailing_generate", - ), - path( - "/mailing/delete/", - MailingDeleteView.as_view(), - name="mailing_delete", - ), - path( - "/mailing/delete/subscription/", - MailingSubscriptionDeleteView.as_view(), - name="mailing_subscription_delete", - ), path( "membership//set_old/", MembershipSetOldView.as_view(), diff --git a/club/views.py b/club/views.py index fcf63f6a..b5532111 100644 --- a/club/views.py +++ b/club/views.py @@ -34,7 +34,6 @@ from django.contrib.auth.mixins import ( UserPassesTestMixin, ) from django.contrib.messages.views import SuccessMessageMixin -from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError from django.core.paginator import InvalidPage, Paginator from django.db.models import F, Prefetch, Q, Sum from django.db.models.expressions import OuterRef, Subquery @@ -60,7 +59,6 @@ from club.forms import ( ClubRoleFormSet, ClubSearchForm, JoinClubForm, - MailingForm, SellingsForm, ) from club.models import ( @@ -68,8 +66,6 @@ from club.models import ( ClubLink, ClubRole, LinkType, - Mailing, - MailingSubscription, Membership, ) from com.models import NewsDate, Poster @@ -166,13 +162,6 @@ class ClubTabsMixin(TabedViewMixin): "slug": "sellings", "name": _("Sellings"), }, - { - "url": reverse( - "club:mailing", kwargs={"club_id": self.object.id} - ), - "slug": "mailing", - "name": _("Mailing list"), - }, { "url": reverse( "club:poster_list", kwargs={"club_id": self.object.id} @@ -727,166 +716,6 @@ class MembershipDeleteView(PermissionRequiredMixin, DeleteView): return reverse_lazy("core:user_clubs", kwargs={"user_id": self.object.user_id}) -class ClubMailingView(ClubTabsMixin, CanEditMixin, DetailFormView): - """A list of mailing for a given club.""" - - model = Club - form_class = MailingForm - pk_url_kwarg = "club_id" - template_name = "club/mailing.jinja" - current_tab = "mailing" - - def get_form_kwargs(self): - kwargs = super().get_form_kwargs() - kwargs["club_id"] = self.object.id - kwargs["user_id"] = self.request.user.id - kwargs["mailings"] = self.object.mailings.all() - return kwargs - - def get_context_data(self, **kwargs): - kwargs = super().get_context_data(**kwargs) - mailings = list(self.object.mailings.all()) - kwargs["club"] = self.object - kwargs["user"] = self.request.user - kwargs["mailings"] = mailings - kwargs["mailings_moderated"] = [m for m in mailings if m.is_moderated] - kwargs["mailings_not_moderated"] = [m for m in mailings if not m.is_moderated] - kwargs["form_actions"] = { - "NEW_MALING": self.form_class.ACTION_NEW_MAILING, - "NEW_SUBSCRIPTION": self.form_class.ACTION_NEW_SUBSCRIPTION, - "REMOVE_SUBSCRIPTION": self.form_class.ACTION_REMOVE_SUBSCRIPTION, - } - return kwargs - - def add_new_mailing(self, cleaned_data) -> ValidationError | None: - """Create a new mailing list from the form.""" - mailing = Mailing( - club=self.object, - email=cleaned_data["mailing_email"], - moderator=self.request.user, - is_moderated=False, - ) - try: - mailing.clean() - except ValidationError as validation_error: - return validation_error - mailing.save() - return None - - def add_new_subscription(self, cleaned_data) -> ValidationError | None: - """Add mailing subscriptions for each user given and/or for the specified email in form.""" - users_to_save = [] - - for user in cleaned_data["subscription_users"]: - sub = MailingSubscription( - mailing=cleaned_data["subscription_mailing"], user=user - ) - try: - sub.clean() - except ValidationError as validation_error: - return validation_error - - sub.save() - users_to_save.append(sub) - - if cleaned_data["subscription_email"]: - sub = MailingSubscription( - mailing=cleaned_data["subscription_mailing"], - email=cleaned_data["subscription_email"], - ) - - try: - sub.clean() - except ValidationError as validation_error: - return validation_error - sub.save() - - # Save users after we are sure there is no error - for user in users_to_save: - user.save() - - return None - - def remove_subscription(self, cleaned_data): - """Remove specified users from a mailing list.""" - fields = [ - val for key, val in cleaned_data.items() if key.startswith("removal_") - ] - for field in fields: - for sub in field: - sub.delete() - - def form_valid(self, form): - resp = super().form_valid(form) - - cleaned_data = form.clean() - error = None - - if cleaned_data["action"] == self.form_class.ACTION_NEW_MAILING: - error = self.add_new_mailing(cleaned_data) - - if cleaned_data["action"] == self.form_class.ACTION_NEW_SUBSCRIPTION: - error = self.add_new_subscription(cleaned_data) - - if cleaned_data["action"] == self.form_class.ACTION_REMOVE_SUBSCRIPTION: - self.remove_subscription(cleaned_data) - - if error: - form.add_error(NON_FIELD_ERRORS, error) - return self.form_invalid(form) - - return resp - - def get_success_url(self, **kwargs): - return reverse("club:mailing", kwargs={"club_id": self.object.id}) - - -class MailingDeleteView(CanEditMixin, DeleteView): - model = Mailing - template_name = "core/delete_confirm.jinja" - pk_url_kwarg = "mailing_id" - redirect_page = None - - def dispatch(self, request, *args, **kwargs): - self.club_id = self.get_object().club.id - return super().dispatch(request, *args, **kwargs) - - def get_success_url(self, **kwargs): - if self.redirect_page: - return reverse_lazy(self.redirect_page) - else: - return reverse_lazy("club:mailing", kwargs={"club_id": self.club_id}) - - -class MailingSubscriptionDeleteView(CanEditMixin, DeleteView): - model = MailingSubscription - template_name = "core/delete_confirm.jinja" - pk_url_kwarg = "mailing_subscription_id" - - def dispatch(self, request, *args, **kwargs): - self.club_id = self.get_object().mailing.club.id - return super().dispatch(request, *args, **kwargs) - - def get_success_url(self, **kwargs): - return reverse_lazy("club:mailing", kwargs={"club_id": self.club_id}) - - -class MailingAutoGenerationView(View): - def dispatch(self, request, *args, **kwargs): - self.mailing = get_object_or_404(Mailing, pk=kwargs["mailing_id"]) - if not request.user.can_edit(self.mailing): - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - def get(self, request, *args, **kwargs): - club = self.mailing.club - self.mailing.subscriptions.all().delete() - members = club.members.ongoing().filter(role__is_board=True) - for member in members.all(): - MailingSubscription(user=member.user, mailing=self.mailing).save() - return redirect("club:mailing", club_id=club.id) - - class PosterListView( PermissionOrClubBoardRequiredMixin, ClubTabsMixin, PosterListBaseView ): diff --git a/com/models.py b/com/models.py index 6a9100b5..3f3e332a 100644 --- a/com/models.py +++ b/com/models.py @@ -259,10 +259,7 @@ class Weekmail(models.Model): return f"Weekmail {self.id} (sent: {self.sent}) - {self.title}" def send(self): - """Send the weekmail to all users with the receive weekmail option opt-in. - - Also send the weekmail to the mailing list in settings.SITH_COM_EMAIL. - """ + """Send the weekmail to all users with the receive weekmail option opt-in.""" dest = [ i[0] for i in Preferences.objects.filter(receive_weekmail=True).values_list( diff --git a/com/templates/com/mailing_admin.jinja b/com/templates/com/mailing_admin.jinja deleted file mode 100644 index 3096e435..00000000 --- a/com/templates/com/mailing_admin.jinja +++ /dev/null @@ -1,45 +0,0 @@ -{% extends "core/base.jinja" %} - -{% block title %} - {% trans %}Mailing lists administration{% endtrans %} -{% endblock %} - -{% macro display_mailings(list) %} - - - - - - - {% for mailing in list %} - - - - - - {% endfor %} -
    {% trans %}Email{% endtrans %}{% trans %}Club{%endtrans%}{% trans %}Actions{% endtrans %}
    {{ mailing.email_full }}{{ mailing.club }} - {% trans %}Delete{% endtrans %} - {% if not mailing.is_moderated %}{% trans %}Moderate{% endtrans %}{% else %}{% trans user=mailing.moderator %}Moderated by {{ user }}{% endtrans %}{% endif %} -
    - -{% endmacro %} - -{% block content %} -

    {% trans %}This page lists all mailing lists{% endtrans %}

    - - {% if has_unmoderated %} -

    {% trans %}Not moderated mailing lists{% endtrans %}

    - {{ display_mailings(unmoderated) }} - {% endif %} - -

    {% trans %}Moderated mailing lists{% endtrans %}

    - {% if has_moderated %} - {{ display_mailings(moderated) }} - {% else %} -

    {% trans %}No mailing list existing{% endtrans %}

    - {% endif %} - -{% endblock %} - - - diff --git a/com/tests/test_views.py b/com/tests/test_views.py index 1e765ca6..9e42ce1e 100644 --- a/com/tests/test_views.py +++ b/com/tests/test_views.py @@ -31,8 +31,9 @@ from pytest_django.asserts import assertNumQueries, assertRedirects from club.models import Club, ClubRole, Membership from com.models import News, NewsDate, Poster, Sith, Weekmail, WeekmailArticle -from core.baker_recipes import subscriber_user +from core.baker_recipes import old_subscriber_user, subscriber_user from core.models import AnonymousUser, Group, User +from core.templatetags.renderer import markdown from core.utils import RED_PIXEL_PNG @@ -42,68 +43,32 @@ def user_community(): @pytest.mark.django_db -@pytest.mark.parametrize( - "url", - [ - reverse("com:alert_edit"), - reverse("com:info_edit"), - ], -) -def test_com_page_is_working(client, url, user_community): +def test_com_page_is_working(client, user_community): client.force_login(user_community) - response = client.get(url) + response = client.get(reverse("com:banner_edit")) assert response.status_code == 200 class TestCom(TestCase): @classmethod def setUpTestData(cls): - cls.skia = User.objects.get(username="skia") cls.com_group = Group.objects.get(id=settings.SITH_GROUP_COM_ADMIN_ID) - cls.skia.groups.set([cls.com_group]) + cls.com_admin = subscriber_user.make(groups=[cls.com_group]) - def setUp(self): - self.client.force_login(self.skia) - - def test_alert_msg(self): + def test_banner_messages(self): + self.client.force_login(self.com_admin) + alert_msg = "### ALERTE!\n\n**Caaaataaaapuuuulte!!!!**\n" + info_msg = "### INFO:\n\n**Caaaataaaapuuuulte!!!!**\n" self.client.post( - reverse("com:alert_edit"), - { - "alert_msg": """ -### ALERTE! - -**Caaaataaaapuuuulte!!!!** -""" - }, + reverse("com:banner_edit"), {"alert_msg": alert_msg, "info_msg": info_msg} ) r = self.client.get(reverse("core:index")) assert r.status_code == 200 - self.assertInHTML( - """

    ALERTE!

    -

    Caaaataaaapuuuulte!!!!

    """, - r.content.decode(), - ) - - def test_info_msg(self): - self.client.post( - reverse("com:info_edit"), - { - "info_msg": """ -### INFO: **Caaaataaaapuuuulte!!!!** -""" - }, - ) - r = self.client.get(reverse("core:index")) - - assert r.status_code == 200 - self.assertInHTML( - """
    -

    INFO: Caaaataaaapuuuulte!!!!

    """, - r.content.decode(), - ) + self.assertInHTML(f'
    {markdown(alert_msg)}
    ', r.text) + self.assertInHTML(f'
    {markdown(info_msg)}
    ', r.text) def test_birthday_non_subscribed_user(self): - self.client.force_login(User.objects.get(username="guy")) + self.client.force_login(baker.make(User)) response = self.client.get(reverse("core:index")) self.assertContains( response, @@ -111,6 +76,7 @@ class TestCom(TestCase): ) def test_birthday_subscibed_user(self): + self.client.force_login(subscriber_user.make()) response = self.client.get(reverse("core:index")) self.assertNotContains( @@ -119,7 +85,7 @@ class TestCom(TestCase): ) def test_birthday_old_subscibed_user(self): - self.client.force_login(User.objects.get(username="old_subscriber")) + self.client.force_login(old_subscriber_user.make()) response = self.client.get(reverse("core:index")) self.assertNotContains( diff --git a/com/urls.py b/com/urls.py index 51861316..6984ae13 100644 --- a/com/urls.py +++ b/com/urls.py @@ -15,12 +15,8 @@ from django.urls import path -from club.views import MailingDeleteView from com.views import ( - AlertMsgEditView, - InfoMsgEditView, - MailingListAdminView, - MailingModerateView, + BannerMessagesEditView, NewsAdminListView, NewsCreateView, NewsDeleteView, @@ -48,8 +44,7 @@ from com.views import ( ) urlpatterns = [ - path("sith/edit/alert/", AlertMsgEditView.as_view(), name="alert_edit"), - path("sith/edit/info/", InfoMsgEditView.as_view(), name="info_edit"), + path("sith/edit/banner/", BannerMessagesEditView.as_view(), name="banner_edit"), path( "sith/edit/weekmail_destinations/", WeekmailDestinationEditView.as_view(), @@ -82,17 +77,6 @@ urlpatterns = [ "news//moderate/", NewsModerateView.as_view(), name="news_moderate" ), path("news//", NewsDetailView.as_view(), name="news_detail"), - path("mailings/", MailingListAdminView.as_view(), name="mailing_admin"), - path( - "mailings//moderate/", - MailingModerateView.as_view(), - name="mailing_moderate", - ), - path( - "mailings//delete/", - MailingDeleteView.as_view(redirect_page="com:mailing_admin"), - name="mailing_delete", - ), path("poster/", PosterListView.as_view(), name="poster_list"), path("poster/create/", PosterCreateView.as_view(), name="poster_create"), path("poster//edit/", PosterEditView.as_view(), name="poster_edit"), diff --git a/com/views.py b/com/views.py index 82075aa8..28c1de43 100644 --- a/com/views.py +++ b/com/views.py @@ -30,11 +30,9 @@ from urllib.parse import urlparse from dateutil.relativedelta import relativedelta from django.conf import settings from django.contrib import messages -from django.contrib.auth.mixins import ( - PermissionRequiredMixin, -) +from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.syndication.views import Feed -from django.core.exceptions import PermissionDenied, ValidationError +from django.core.exceptions import ValidationError from django.db.models import Exists, Max, OuterRef, Value from django.forms.models import modelform_factory from django.http import HttpResponseRedirect @@ -46,7 +44,7 @@ from django.utils.translation import gettext_lazy as _ from django.views.generic import DetailView, ListView, TemplateView, View from django.views.generic.edit import CreateView, DeleteView, UpdateView -from club.models import Club, Mailing, Membership +from club.models import Club, Membership from com.forms import NewsDateForm, NewsForm, PosterForm from com.ics_calendar import IcsCalendar from com.models import News, NewsDate, Poster, Screen, Sith, Weekmail, WeekmailArticle @@ -77,19 +75,9 @@ class ComTabsMixin(TabedViewMixin): "name": _("Weekmail destinations"), }, { - "url": reverse("com:info_edit"), - "slug": "info", - "name": _("Info message"), - }, - { - "url": reverse("com:alert_edit"), - "slug": "alert", - "name": _("Alert message"), - }, - { - "url": reverse("com:mailing_admin"), - "slug": "mailings", - "name": _("Mailing lists administration"), + "url": reverse("com:banner_edit"), + "slug": "banner", + "name": _("Banner messages"), }, { "url": reverse("com:poster_list"), @@ -112,20 +100,14 @@ class ComEditView(ComTabsMixin, CanEditPropMixin, UpdateView): return Sith.objects.first() -class AlertMsgEditView(ComEditView): +class BannerMessagesEditView(ComEditView): form_class = modelform_factory( - Sith, fields=["alert_msg"], widgets={"alert_msg": MarkdownInput} + Sith, + fields=["alert_msg", "info_msg"], + widgets={"alert_msg": MarkdownInput, "info_msg": MarkdownInput}, ) - current_tab = "alert" - success_url = reverse_lazy("com:alert_edit") - - -class InfoMsgEditView(ComEditView): - form_class = modelform_factory( - Sith, fields=["info_msg"], widgets={"info_msg": MarkdownInput} - ) - current_tab = "info" - success_url = reverse_lazy("com:info_edit") + current_tab = "banner" + success_url = reverse_lazy("com:banner_edit") class WeekmailDestinationEditView(ComEditView): @@ -533,37 +515,6 @@ class WeekmailArticleDeleteView(CanEditPropMixin, DeleteView): pk_url_kwarg = "article_id" -class MailingListAdminView(ComTabsMixin, ListView): - template_name = "com/mailing_admin.jinja" - model = Mailing - current_tab = "mailings" - - def dispatch(self, request, *args, **kwargs): - if not (request.user.is_com_admin or request.user.is_root): - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - def get_context_data(self, **kwargs): - kwargs = super().get_context_data(**kwargs) - kwargs["moderated"] = self.get_queryset().filter(is_moderated=True).all() - kwargs["unmoderated"] = self.get_queryset().filter(is_moderated=False).all() - kwargs["has_moderated"] = len(kwargs["moderated"]) > 0 - kwargs["has_unmoderated"] = len(kwargs["unmoderated"]) > 0 - return kwargs - - -class MailingModerateView(View): - def get(self, request, *args, **kwargs): - mailing = get_object_or_404(Mailing, pk=kwargs["mailing_id"]) - if mailing.can_moderate(request.user): - mailing.is_moderated = True - mailing.moderator = request.user - mailing.save() - return redirect("com:mailing_admin") - - raise PermissionDenied - - class PosterListBaseView(ListView): """List communication posters.""" diff --git a/core/api.py b/core/api.py index d46548f5..075ae5b1 100644 --- a/core/api.py +++ b/core/api.py @@ -1,18 +1,15 @@ from typing import Annotated, Literal from annotated_types import Ge, Le, MinLen -from django.conf import settings from django.db.models import F from ninja import File, Query from ninja.security import SessionAuth from ninja_extra import ControllerBase, api_controller, paginate, route -from ninja_extra.exceptions import PermissionDenied from ninja_extra.pagination import PageNumberPaginationExtra from ninja_extra.schemas import PaginatedResponseSchema from api.auth import ApiKeyAuth from api.permissions import CanAccessLookup, CanView, HasPerm -from club.models import Mailing from core.models import Group, QuickUploadImage, SithFile, User from core.schemas import ( FamilyGodfatherSchema, @@ -48,19 +45,6 @@ class UploadController(ControllerBase): return image -@api_controller("/mailings") -class MailingListController(ControllerBase): - @route.get("", response=str) - def fetch_mailing_lists(self, key: str): - if key != settings.SITH_MAILING_FETCH_KEY: - raise PermissionDenied - mailings = Mailing.objects.filter( - is_moderated=True, club__is_active=True - ).prefetch_related("subscriptions") - data = "\n".join(m.fetch_format() for m in mailings) - return data - - @api_controller("/user") class UserController(ControllerBase): @route.get("", response=list[UserProfileSchema]) diff --git a/core/management/commands/populate.py b/core/management/commands/populate.py index d3c880c7..42f6c537 100644 --- a/core/management/commands/populate.py +++ b/core/management/commands/populate.py @@ -252,7 +252,6 @@ class Command(BaseCommand): date_of_birth="1942-06-12", password="plop", ) - User.objects.all().update(cgu_approved_at=now()) User.groups.through.objects.bulk_create( [ User.groups.through(group=groups.counter_admin, user=counter), @@ -277,6 +276,10 @@ class Command(BaseCommand): ) 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(skia) @@ -779,28 +782,47 @@ class Command(BaseCommand): name="Carte AE", address="Jamais imprimée", parent=ae ) roles = [] - presidency_roles = ["Président⸱e", "Vice-Président⸱e"] + presidency_roles = [ + ("Président⸱e", "President"), + ("Vice-Président⸱e", "Vice-president"), + ] board_roles = [ - "Trésorier⸱e", - "Secrétaire", - "Respo Info", - "Respo Com", - "Membre du bureau", + ("Trésorier⸱e", "Treasurer"), + ("Secrétaire", "Secretary"), + ("Respo Info", "IT manager"), + ("Respo Com", "Communication manager"), + ("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 i, role in enumerate(presidency_roles): + for i, (role_fr, role_en) in enumerate(presidency_roles): roles.append( 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)): - roles.append(ClubRole(club=club, order=i, name=role, is_board=True)) - for i, role in enumerate( + for i, (role_fr, role_en) in enumerate( + board_roles, start=len(presidency_roles) + ): + 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) ): - 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) insta, fb, discord, _ = LinkType.objects.bulk_create( [ diff --git a/core/migrations/0053_alter_user_email_alter_user_second_email.py b/core/migrations/0053_alter_user_email_alter_user_second_email.py new file mode 100644 index 00000000..709b01a8 --- /dev/null +++ b/core/migrations/0053_alter_user_email_alter_user_second_email.py @@ -0,0 +1,29 @@ +# Generated by Django 5.2.18 on 2026-11-15 11:46 + +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", + ), + ), + ] diff --git a/core/models.py b/core/models.py index 7baec8d1..b4ebc7be 100644 --- a/core/models.py +++ b/core/models.py @@ -55,6 +55,7 @@ from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from PIL import Image, ImageOps +from antispam.models import AntiSpamEmailField from core.utils import get_last_promo if TYPE_CHECKING: @@ -158,7 +159,7 @@ class User(AbstractUser): first_name = models.CharField(_("first name"), max_length=64) last_name = models.CharField(_("last name"), max_length=64) - email = models.EmailField(_("email address"), unique=True) + email = AntiSpamEmailField(_("email address"), unique=True) date_of_birth = models.DateField(_("date of birth"), blank=True, null=True) nick_name = models.CharField(_("nick name"), max_length=64, null=True, blank=True) last_update = models.DateTimeField(_("last update"), auto_now=True) @@ -267,7 +268,7 @@ class User(AbstractUser): forum_signature = models.TextField( _("forum signature"), max_length=256, blank=True, default="" ) - second_email = models.EmailField(_("second email address"), null=True, blank=True) + second_email = AntiSpamEmailField(_("second email address"), null=True, blank=True) phone = PhoneNumberField(_("phone"), null=True, blank=True) parent_phone = PhoneNumberField(_("parent phone"), null=True, blank=True) address = models.CharField(_("address"), max_length=128, blank=True, default="") @@ -768,6 +769,14 @@ class UserBan(models.Model): def __str__(self): 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): """Little hack to have permissions not linked to a specific db table.""" diff --git a/core/static/core/header.scss b/core/static/core/header.scss index 95409c2b..d794d38a 100644 --- a/core/static/core/header.scss +++ b/core/static/core/header.scss @@ -240,13 +240,6 @@ $background-color-hovered: #283747; >.links { width: 100%; - display: flex; - justify-content: flex-end; - gap: 15px; - - @media (max-width: 1200px) { - justify-content: flex-start; - } a { color: $text-color; diff --git a/core/templates/core/base/header.jinja b/core/templates/core/base/header.jinja index 5735f099..1548a0f9 100644 --- a/core/templates/core/base/header.jinja +++ b/core/templates/core/base/header.jinja @@ -54,6 +54,7 @@