Skip to content

Commit

Permalink
Permet la gestion de contributeurs sur les billets
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnaud-D committed Oct 29, 2023
1 parent 0a733a7 commit 38c735b
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 126 deletions.
4 changes: 2 additions & 2 deletions templates/tutorialv2/messages/add_contribution_pm.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{% load i18n %}

{% blocktrans with title=content.title|safe type=type|safe user=user|safe %}
{% blocktrans with title=content.title|safe user=user|safe %}
Bonjour {{ user }},

Vous avez été ajouté à la liste des contributeurs {{type}} « {{ title }} », en tant que {{role}}.
Vous avez été ajouté à la liste des contributeurs de la publication « {{ title }} », en tant que {{ role }}.

Merci pour votre participation !
{% endblocktrans %}
62 changes: 1 addition & 61 deletions zds/tutorialv2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from zds.utils.models import SubCategory, Licence
from zds.tutorialv2.models import TYPE_CHOICES
from zds.tutorialv2.models.help_requests import HelpWriting
from zds.tutorialv2.models.database import PublishableContent, ContentContributionRole, ContentSuggestion
from zds.tutorialv2.models.database import PublishableContent, ContentSuggestion
from django.utils.translation import gettext_lazy as _
from zds.member.models import Profile
from zds.utils.forms import TagValidator, IncludeEasyMDE
Expand Down Expand Up @@ -48,66 +48,6 @@ def label_from_instance(self, obj):
return obj.title


class ContributionForm(forms.Form):
contribution_role = ReviewerTypeModelChoiceField(
label=_("Role"),
required=True,
queryset=ContentContributionRole.objects.order_by("title").all(),
)

username = forms.CharField(
label=_("Contributeur"),
required=True,
widget=forms.TextInput(
attrs={"placeholder": _("Pseudo du membre à ajouter."), "data-autocomplete": "{ 'type': 'single' }"}
),
)

comment = forms.CharField(
label=_("Commentaire"),
required=False,
widget=forms.Textarea(attrs={"placeholder": _("Commentaire sur ce contributeur."), "rows": "3"}),
)

def __init__(self, content, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_class = "modal modal-flex"
self.helper.form_id = "add-contributor"
self.helper.form_method = "post"
self.helper.form_action = reverse("content:add-contributor", kwargs={"pk": content.pk})
self.helper.layout = Layout(
Field("username"),
Field("contribution_role"),
Field("comment"),
ButtonHolder(
StrictButton(_("Ajouter"), type="submit", css_class="btn-submit"),
),
)
super().__init__(*args, **kwargs)

def clean_username(self):
cleaned_data = super().clean()
if cleaned_data.get("username"):
username = cleaned_data.get("username")
user = Profile.objects.contactable_members().filter(user__username__iexact=username.strip().lower()).first()
if user is not None:
cleaned_data["user"] = user.user
else:
self._errors["user"] = self.error_class([_("L'utilisateur sélectionné n'existe pas")])

if "user" not in cleaned_data:
self._errors["user"] = self.error_class([_("Veuillez renseigner l'utilisateur")])

return cleaned_data


class RemoveContributionForm(forms.Form):
pk_contribution = forms.CharField(
label=_("Contributeur"),
required=True,
)


class AuthorForm(forms.Form):
username = forms.CharField(label=_("Auteurs à ajouter séparés d'une virgule."), required=True)

Expand Down
28 changes: 8 additions & 20 deletions zds/tutorialv2/tests/tests_views/tests_addcontributor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from zds.member.tests.factories import ProfileFactory, StaffProfileFactory
from zds.tutorialv2.tests.factories import ContentContributionRoleFactory, PublishableContentFactory
from zds.tutorialv2.forms import ContributionForm
from zds.tutorialv2.views.contributors import ContributionForm
from zds.tutorialv2.models.database import ContentContribution
from zds.tutorialv2.tests import TutorialTestMixin, override_for_contents

Expand Down Expand Up @@ -61,26 +61,14 @@ def test_authenticated_author(self):
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)

def test_authenticated_staff_tutorial(self):
def test_authenticated_staff(self):
self.client.force_login(self.staff)
self.content.type = "TUTORIAL"
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)

def test_authenticated_staff_article(self):
self.client.force_login(self.staff)
self.content.type = "ARTICLE"
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)

def test_authenticated_staff_opinion(self):
self.client.force_login(self.staff)
self.content.type = "OPINION"
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertEqual(response.status_code, 403)
types = ["TUTORIAL", "ARTICLE", "OPINION"]
for type in types:
self.content.type = type
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)


class AddContributorWorkflowTests(TutorialTestMixin, TestCase):
Expand Down
27 changes: 8 additions & 19 deletions zds/tutorialv2/tests/tests_views/tests_removecontributor.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,26 +60,15 @@ def test_authenticated_author(self):
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)

def test_authenticated_staff_tutorial(self):
def test_authenticated_staff(self):
self.client.force_login(self.staff)
self.content.type = "TUTORIAL"
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)

def test_authenticated_staff_article(self):
self.client.force_login(self.staff)
self.content.type = "ARTICLE"
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)

def test_authenticated_staff_opinion(self):
self.client.force_login(self.staff)
self.content.type = "OPINION"
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertEqual(response.status_code, 403)
types = ["TUTORIAL", "ARTICLE", "OPINION"]
for type in types:
self.contribution = create_contribution(self.role, self.contributor, self.content)
self.content.type = type
self.content.save()
response = self.client.post(self.form_url, self.form_data)
self.assertRedirects(response, self.content_url)


class RemoveContributorWorkflowTests(TutorialTestMixin, TestCase):
Expand Down
95 changes: 73 additions & 22 deletions zds/tutorialv2/views/contributors.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,85 @@
from collections import OrderedDict

from crispy_forms.bootstrap import StrictButton
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder
from django import forms

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _

from zds.member.decorator import LoggedWithReadWriteHability
from zds.member.models import Profile
from zds.member.utils import get_bot_account
from zds.notification.models import NewPublicationSubscription
from zds.tutorialv2 import signals
from zds.tutorialv2.forms import ContributionForm, RemoveContributionForm
from zds.tutorialv2.forms import ReviewerTypeModelChoiceField
from zds.tutorialv2.mixins import SingleContentFormViewMixin
from zds.tutorialv2.models import TYPE_CHOICES_DICT
from zds.tutorialv2.models.database import ContentContribution, PublishableContent
from zds.tutorialv2.models.database import ContentContribution, PublishableContent, ContentContributionRole
from zds.mp.utils import send_mp
from zds.utils.paginator import ZdSPagingListView


class ContributionForm(forms.Form):
contribution_role = ReviewerTypeModelChoiceField(
label=_("Role"),
required=True,
queryset=ContentContributionRole.objects.order_by("title").all(),
)

username = forms.CharField(
label=_("Contributeur"),
required=True,
widget=forms.TextInput(
attrs={"placeholder": _("Pseudo du membre à ajouter."), "data-autocomplete": "{ 'type': 'single' }"}
),
)

comment = forms.CharField(
label=_("Commentaire"),
required=False,
widget=forms.Textarea(attrs={"placeholder": _("Commentaire sur ce contributeur."), "rows": "3"}),
)

def __init__(self, content, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_class = "modal modal-flex"
self.helper.form_id = "add-contributor"
self.helper.form_method = "post"
self.helper.form_action = reverse("content:add-contributor", kwargs={"pk": content.pk})
self.helper.layout = Layout(
Field("username"),
Field("contribution_role"),
Field("comment"),
ButtonHolder(
StrictButton(_("Ajouter"), type="submit", css_class="btn-submit"),
),
)
super().__init__(*args, **kwargs)

def clean_username(self):
cleaned_data = super().clean()
if cleaned_data.get("username"):
username = cleaned_data.get("username")
user = Profile.objects.contactable_members().filter(user__username__iexact=username.strip().lower()).first()
if user is not None:
cleaned_data["user"] = user.user
else:
self._errors["user"] = self.error_class([_("L'utilisateur sélectionné n'existe pas")])

if "user" not in cleaned_data:
self._errors["user"] = self.error_class([_("Veuillez renseigner l'utilisateur")])

return cleaned_data


class AddContributorToContent(LoggedWithReadWriteHability, SingleContentFormViewMixin):
must_be_author = True
form_class = ContributionForm
Expand All @@ -39,18 +96,11 @@ def get(self, request, *args, **kwargs):
return redirect(url, self.request.user)

def form_valid(self, form):
_type = _("à l'article")

if self.object.is_tutorial:
_type = _("au tutoriel")
elif self.object.is_opinion:
raise PermissionDenied

bot = get_bot_account()
all_authors_pk = [author.pk for author in self.object.authors.all()]
user = form.cleaned_data["user"]
if user.pk in all_authors_pk:
messages.error(self.request, _("Un auteur ne peut pas être désigné comme contributeur"))
messages.error(self.request, _("Un auteur ne peut pas être désigné comme contributeur."))
return redirect(self.object.get_absolute_url())
else:
contribution_role = form.cleaned_data.get("contribution_role")
Expand All @@ -62,7 +112,7 @@ def form_valid(self, form):
self.request,
_(
"Ce membre fait déjà partie des "
'contributeurs {} avec pour rôle "{}"'.format(_type, contribution_role.title)
'contributeurs à la publication avec pour rôle "{}"'.format(contribution_role.title)
),
)
return redirect(self.object.get_absolute_url())
Expand All @@ -75,13 +125,12 @@ def form_valid(self, form):
send_mp(
bot,
[user],
format_lazy("{} {}", _("Contribution"), _type),
_("Contribution à la publication"),
self.versioned_object.title,
render_to_string(
"tutorialv2/messages/add_contribution_pm.md",
{
"content": self.object,
"type": _type,
"url": self.object.get_absolute_url(),
"index": url_index,
"user": user.username,
Expand All @@ -104,26 +153,28 @@ def form_invalid(self, form):
return super().form_valid(form)


class RemoveContributionForm(forms.Form):
pk_contribution = forms.CharField(
label=_("Contributeur"),
required=True,
)


class RemoveContributorFromContent(LoggedWithReadWriteHability, SingleContentFormViewMixin):
form_class = RemoveContributionForm
must_be_author = True
authorized_for_staff = True

def form_valid(self, form):
_type = _("cet article")
if self.object.is_tutorial:
_type = _("ce tutoriel")
elif self.object.is_opinion:
raise PermissionDenied

contribution = get_object_or_404(ContentContribution, pk=form.cleaned_data["pk_contribution"])
user = contribution.user
contribution.delete()
signals.contributors_management.send(
sender=self.__class__, content=self.object, performer=self.request.user, contributor=user, action="remove"
)
messages.success(
self.request, _("Vous avez enlevé {} de la liste des contributeurs de {}.").format(user.username, _type)
self.request,
_("Vous avez enlevé {} de la liste des contributeurs de cette publication.").format(user.username),
)
self.success_url = self.object.get_absolute_url()

Expand Down
2 changes: 1 addition & 1 deletion zds/tutorialv2/views/display/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def show_authors_management(self) -> bool:
return self.enabled and self.is_allowed

def show_contributors_management(self) -> bool:
return self.enabled and self.is_allowed and self.requires_validation
return self.enabled and self.is_allowed

def show_ready_to_publish(self) -> bool:
return self.enabled and self.is_allowed and self.requires_validation
Expand Down
2 changes: 1 addition & 1 deletion zds/tutorialv2/views/display/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
UnpickOpinionForm,
PromoteOpinionToArticleForm,
SearchSuggestionForm,
ContributionForm,
)
from zds.tutorialv2.views.contributors import ContributionForm
from zds.tutorialv2.mixins import SingleContentDetailViewMixin, SingleOnlineContentDetailViewMixin
from zds.tutorialv2.models.database import (
ContentSuggestion,
Expand Down

0 comments on commit 38c735b

Please sign in to comment.