Browse Source

Merging and syncing polls. #28

Rafał Pitoń 11 years ago
parent
commit
8ba57a1945

+ 2 - 2
misago/apps/threads/forms.py

@@ -76,8 +76,8 @@ class PollFormMixin(object):
             for choice in data.splitlines():
             for choice in data.splitlines():
                 choice = choice.strip()
                 choice = choice.strip()
                 if not choice in self.clean_choices:
                 if not choice in self.clean_choices:
-                    if len(choice) < 3:
-                        raise forms.ValidationError(_("Poll choices should be at least three characters long."))
+                    if len(choice) < 2:
+                        raise forms.ValidationError(_("Poll choices should be at least two characters long."))
                     if len(choice) > 250:
                     if len(choice) > 250:
                         raise forms.ValidationError(_("Poll choices should be no longer than 250 characters."))
                         raise forms.ValidationError(_("Poll choices should be no longer than 250 characters."))
                     self.clean_choices.append(choice)
                     self.clean_choices.append(choice)

+ 28 - 16
misago/apps/threadtype/list/forms.py

@@ -2,7 +2,7 @@ from django.utils.translation import ugettext_lazy as _
 import floppyforms as forms
 import floppyforms as forms
 from misago.conf import settings
 from misago.conf import settings
 from misago.forms import Form, ForumChoiceField
 from misago.forms import Form, ForumChoiceField
-from misago.models import Forum
+from misago.models import Forum, Poll
 from misago.validators import validate_sluggable
 from misago.validators import validate_sluggable
 from misago.apps.threadtype.mixins import ValidateThreadNameMixin
 from misago.apps.threadtype.mixins import ValidateThreadNameMixin
 
 
@@ -14,9 +14,9 @@ class MoveThreadsForm(Form):
         super(MoveThreadsForm, self).__init__(data, request=request, *args, **kwargs)
         super(MoveThreadsForm, self).__init__(data, request=request, *args, **kwargs)
 
 
     def finalize_form(self):
     def finalize_form(self):
-        self.fields['new_forum'] = ForumChoiceField(label=_("Move Threads to"),
-                                                    help_text=_("Select forum you want to move threads to."),
-                                                    queryset=Forum.objects.get(special='root').get_descendants().filter(pk__in=self.request.acl.forums.acl['can_browse']))
+        self.add_field('new_forum', ForumChoiceField(label=_("Move Threads to"),
+                                                     help_text=_("Select forum you want to move threads to."),
+                                                     queryset=Forum.objects.get(special='root').get_descendants().filter(pk__in=self.request.acl.forums.acl['can_browse'])))
 
 
     def clean_new_forum(self):
     def clean_new_forum(self):
         new_forum = self.cleaned_data['new_forum']
         new_forum = self.cleaned_data['new_forum']
@@ -34,18 +34,30 @@ class MergeThreadsForm(Form, ValidateThreadNameMixin):
         super(MergeThreadsForm, self).__init__(data, request=request, *args, **kwargs)
         super(MergeThreadsForm, self).__init__(data, request=request, *args, **kwargs)
 
 
     def finalize_form(self):
     def finalize_form(self):
-        self.fields['new_forum'] = ForumChoiceField(label=_("Thread Forum"),
-                                                    help_text=_("Select forum you want to put new thread in."),
-                                                    queryset=Forum.objects.get(special='root').get_descendants().filter(pk__in=self.request.acl.forums.acl['can_browse']),
-                                                    initial=self.threads[0].forum)
-        self.fields['thread_name'] = forms.CharField(label=_("Thread Name"),
-                                                     help_text=_("Name of new thread that will be created as result of merge."),
-                                                     max_length=settings.thread_name_max,
-                                                     initial=self.threads[-1].name,
-                                                     validators=[validate_sluggable(
-                                                                                    _("Thread name must contain at least one alpha-numeric character."),
-                                                                                    _("Thread name is too long. Try shorter name.")
-                                                                                    )])
+        choices = [(0, _("Don't use any polls"))]
+        for thread in self.threads:
+            if thread.has_poll:
+                choices.append((thread.pk, thread.name))
+
+        if len(choices) > 2:
+            self.add_field('final_poll', forms.TypedChoiceField(label=_("Final Poll"),
+                                                                help_text=_("More than one of threads that you are going to merge has poll. Select poll that will be used in merged thread of delete all polls."),
+                                                                choices=choices,
+                                                                coerce=int,
+                                                                initial=choices[1][0]))
+
+        self.add_field('new_forum', ForumChoiceField(label=_("Thread Forum"),
+                                                      help_text=_("Select forum you want to put new thread in."),
+                                                      queryset=Forum.objects.get(special='root').get_descendants().filter(pk__in=self.request.acl.forums.acl['can_browse']),
+                                                      initial=self.threads[0].forum))
+        self.add_field('thread_name', forms.CharField(label=_("Thread Name"),
+                                                      help_text=_("Name of new thread that will be created as result of merge."),
+                                                      max_length=settings.thread_name_max,
+                                                      initial=self.threads[-1].name,
+                                                      validators=[validate_sluggable(
+                                                                                     _("Thread name must contain at least one alpha-numeric character."),
+                                                                                     _("Thread name is too long. Try shorter name.")
+                                                                                     )]))
 
 
     def clean_new_forum(self):
     def clean_new_forum(self):
         new_forum = self.cleaned_data['new_forum']
         new_forum = self.cleaned_data['new_forum']

+ 22 - 1
misago/apps/threadtype/list/moderation.py

@@ -149,10 +149,31 @@ class ThreadsListModeration(object):
                 for thread in reversed(threads):
                 for thread in reversed(threads):
                     merged.append(thread.pk)
                     merged.append(thread.pk)
                     thread.merge_with(new_thread)
                     thread.merge_with(new_thread)
-                Thread.objects.filter(id__in=merged).delete()
+
                 new_thread.sync()
                 new_thread.sync()
                 new_thread.save(force_update=True)
                 new_thread.save(force_update=True)
                 new_thread.update_current_dates()
                 new_thread.update_current_dates()
+
+                poll_action = form.cleaned_data.get('final_poll', 'no')
+                if poll_action == 'no':
+                    for thread in threads:
+                        if thread.has_poll:
+                            thread.poll.move_to(forum=new_thread.forum, thread=new_thread)
+                            new_thread.has_poll = True
+                            new_thread.save(force_update=True)
+                            break
+                else:
+                    if poll_action > 0:
+                        for thread in threads:
+                            if thread.pk == poll_action:
+                                thread.poll.move_to(forum=new_thread.forum, thread=new_thread)
+                                new_thread.has_poll = True
+                                new_thread.save(force_update=True)
+                                break
+
+                for thread in Thread.objects.filter(id__in=merged):
+                    thread.delete()
+
                 self.forum.sync()
                 self.forum.sync()
                 self.forum.save(force_update=True)
                 self.forum.save(force_update=True)
                 if form.cleaned_data['new_forum'].pk != self.forum.pk:
                 if form.cleaned_data['new_forum'].pk != self.forum.pk:

+ 44 - 1
misago/models/pollmodel.py

@@ -6,6 +6,9 @@ try:
     import cPickle as pickle
     import cPickle as pickle
 except ImportError:
 except ImportError:
     import pickle
     import pickle
+from misago.signals import (delete_user_content, merge_thread,
+                            move_forum_content, move_thread,
+                            rename_user)
 
 
 class Poll(models.Model):
 class Poll(models.Model):
     forum = models.ForeignKey('Forum')
     forum = models.ForeignKey('Forum')
@@ -25,6 +28,18 @@ class Poll(models.Model):
     class Meta:
     class Meta:
         app_label = 'misago'
         app_label = 'misago'
 
 
+    def move_to(self, forum=None, thread=None):
+        kwargs = {}
+        if forum:
+            self.forum = forum
+            kwargs['forum'] = forum
+        if thread:
+            self.thread = thread
+            kwargs['thread'] = thread
+        self.vote_set.all().update(**kwargs)
+        self.option_set.all().update(**kwargs)
+        self.save()
+
     @property
     @property
     def end_date(self):
     def end_date(self):
         return self.start_date + timedelta(days=self.length)
         return self.start_date + timedelta(days=self.length)
@@ -115,4 +130,32 @@ class Poll(models.Model):
                              date=timezone.now(),
                              date=timezone.now(),
                              ip=request.session.get_ip(request),
                              ip=request.session.get_ip(request),
                              agent=request.META.get('HTTP_USER_AGENT'),
                              agent=request.META.get('HTTP_USER_AGENT'),
-                             )
+                             )
+
+
+def rename_user_handler(sender, **kwargs):
+    Poll.objects.filter(user=sender).update(
+                                            user_name=sender.username,
+                                            user_slug=sender.username_slug,
+                                            )
+
+rename_user.connect(rename_user_handler, dispatch_uid="rename_user_poll")
+
+
+def delete_user_content_handler(sender, **kwargs):
+    for poll in Poll.objects.filter(user=sender).iterator():
+        poll.delete()
+
+delete_user_content.connect(delete_user_content_handler, dispatch_uid="delete_user_polls")
+
+
+def move_forum_content_handler(sender, **kwargs):
+    Poll.objects.filter(forum=sender).update(forum=kwargs['move_to'])
+
+move_forum_content.connect(move_forum_content_handler, dispatch_uid="move_forum_polls")
+
+
+def move_thread_handler(sender, **kwargs):
+    Poll.objects.filter(thread=sender).update(forum=kwargs['move_to'])
+
+move_thread.connect(move_thread_handler, dispatch_uid="move_thread_polls")

+ 14 - 1
misago/models/polloptionmodel.py

@@ -1,4 +1,5 @@
 from django.db import models
 from django.db import models
+from misago.signals import move_thread, move_thread, move_forum_content
 
 
 class PollOption(models.Model):
 class PollOption(models.Model):
     poll = models.ForeignKey('Poll', related_name="option_set")
     poll = models.ForeignKey('Poll', related_name="option_set")
@@ -8,4 +9,16 @@ class PollOption(models.Model):
     votes = models.PositiveIntegerField(default=0)
     votes = models.PositiveIntegerField(default=0)
 
 
     class Meta:
     class Meta:
-        app_label = 'misago'
+        app_label = 'misago'
+
+
+def move_forum_content_handler(sender, **kwargs):
+    PollOption.objects.filter(forum=sender).update(forum=kwargs['move_to'])
+
+move_forum_content.connect(move_forum_content_handler, dispatch_uid="move_forum_polls_options")
+
+
+def move_thread_handler(sender, **kwargs):
+    PollOption.objects.filter(thread=sender).update(forum=kwargs['move_to'])
+
+move_thread.connect(move_thread_handler, dispatch_uid="move_thread_polls_options")

+ 24 - 1
misago/models/pollvotemodel.py

@@ -1,4 +1,6 @@
 from django.db import models
 from django.db import models
+from misago.signals import (rename_user, move_thread,
+                            move_forum_content)
 
 
 class PollVote(models.Model):
 class PollVote(models.Model):
     poll = models.ForeignKey('Poll', related_name="vote_set")
     poll = models.ForeignKey('Poll', related_name="vote_set")
@@ -13,4 +15,25 @@ class PollVote(models.Model):
     agent = models.CharField(max_length=255)
     agent = models.CharField(max_length=255)
 
 
     class Meta:
     class Meta:
-        app_label = 'misago'
+        app_label = 'misago'
+
+
+def rename_user_handler(sender, **kwargs):
+    PollVote.objects.filter(user=sender).update(
+                                                user_name=sender.username,
+                                                user_slug=sender.username_slug,
+                                                )
+
+rename_user.connect(rename_user_handler, dispatch_uid="rename_user_poll_votes")
+
+
+def move_forum_content_handler(sender, **kwargs):
+    PollVote.objects.filter(forum=sender).update(forum=kwargs['move_to'])
+
+move_forum_content.connect(move_forum_content_handler, dispatch_uid="move_forum_polls_votes")
+
+
+def move_thread_handler(sender, **kwargs):
+    PollVote.objects.filter(thread=sender).update(forum=kwargs['move_to'])
+
+move_thread.connect(move_thread_handler, dispatch_uid="move_thread_polls_votes")

+ 3 - 0
templates/cranefly/threads/merge.html

@@ -50,6 +50,9 @@
           {% endfor %}
           {% endfor %}
           <div class="form-fields">
           <div class="form-fields">
             {{ form_theme.row(form.thread_name, attrs={'class': 'span6'}) }}
             {{ form_theme.row(form.thread_name, attrs={'class': 'span6'}) }}
+            {% if 'final_poll' in form.fields %}
+            {{ form_theme.row(form.final_poll, attrs={'class': 'span6'}) }}
+            {% endif %}
             {{ form_theme.row(form.new_forum, attrs={'class': 'span6'}) }}
             {{ form_theme.row(form.new_forum, attrs={'class': 'span6'}) }}
           </div>
           </div>
           <div class="form-actions">
           <div class="form-actions">