<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.contrib import messages
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.forms.models import model_to_dict
from django.shortcuts import redirect
from django.template.loader import get_template
from django.views import generic

from braces.views import LoginRequiredMixin
from datetime import date, timedelta
from django_filters.views import FilterView
from rest_framework import generics
from tower import ugettext as _, ugettext_lazy as _lazy

from oneanddone.base.util import get_object_or_none, SortHeaders
from oneanddone.tasks.filters import ActivityFilterSet, TasksFilterSet
from oneanddone.tasks.forms import (FeedbackForm, PreviewConfirmationForm,
                                    TaskImportBatchForm,
                                    TaskInvalidCriteriaFormSet, TaskForm)
from oneanddone.tasks.mixins import (APIRecordCreatorMixin,
                                     APIOnlyCreatorMayDeleteMixin)
from oneanddone.tasks.mixins import (TaskMustBeAvailableMixin,
                                     HideNonRepeatableTaskMixin)
from oneanddone.tasks.mixins import GetUserAttemptMixin
from oneanddone.tasks.models import (BugzillaBug, Feedback, Task, TaskAttempt,
                                     TaskMetrics)
from oneanddone.tasks.serializers import TaskSerializer
from oneanddone.users.models import User
from oneanddone.users.mixins import (MyStaffUserRequiredMixin,
                                     PrivacyPolicyRequiredMixin)


class ActivityView(LoginRequiredMixin, MyStaffUserRequiredMixin, FilterView):
    list_headers = (
        (_lazy(u'Task'), 'task__name'),
        (_lazy(u'User'), 'user__profile__name'),
        (_lazy(u'Status'), 'state_display'),
        (_lazy(u'Time'), 'elapsed_time'),
    )
    context_object_name = 'attempts'
    template_name = 'tasks/activity.html'
    paginate_by = 20
    filterset_class = ActivityFilterSet

    def get_context_data(self, *args, **kwargs):
        ctx = super(ActivityView, self).get_context_data(*args, **kwargs)
        ctx['headers'] = self.sort_headers
        return ctx

    def get_queryset(self):
        self.sort_headers = SortHeaders(self.request, self.list_headers)
        qs = TaskAttempt.objects.extra(
            select={
                'state_display': TaskAttempt.choice_display_extra_expression('state'),
                'elapsed_time': 'TIMESTAMPDIFF(SECOND, tasks_taskattempt.created, tasks_taskattempt.modified)'
            })
        return qs.order_by(self.sort_headers.get_order_by())


class AvailableTasksView(TaskMustBeAvailableMixin, FilterView):
    queryset = Task.objects.all()
    context_object_name = 'tasks'
    template_name = 'tasks/list.html'
    paginate_by = 10
    filterset_class = TasksFilterSet

    def get_context_data(self, *args, **kwargs):
        ctx = super(AvailableTasksView, self).get_context_data(*args, **kwargs)
        ctx['task_list_heading'] = _('Tasks')
        return ctx


class CreateFeedbackView(LoginRequiredMixin, PrivacyPolicyRequiredMixin,
                         HideNonRepeatableTaskMixin, GetUserAttemptMixin,
                         generic.CreateView):
    model = Feedback
    form_class = FeedbackForm
    template_name = 'tasks/feedback.html'

    def get_context_data(self, *args, **kwargs):
        ctx = super(CreateFeedbackView, self).get_context_data(*args, **kwargs)
        ctx['attempt'] = self.attempt
        return ctx

    def form_valid(self, form):
        feedback = form.save(commit=False)
        feedback.attempt = self.attempt
        feedback.save()

        # Send email to task owner
        task_name = feedback.attempt.task.name
        subject = 'Feedback on %s from One and Done' % task_name
        link_prefix = 'http'
        if self.request.is_secure():
            link_prefix += 's'
        task_link = link_prefix + '://%s%s' % (
            self.request.get_host(),
            feedback.attempt.task.get_absolute_url())
        feedback_link = link_prefix + '://%s/admin/tasks/feedback/%s' % (
            self.request.get_host(), feedback.id)
        template = get_template('tasks/emails/feedback_email.txt')

        message = template.render({
            'feedback_user': feedback.attempt.user,
            'task_name': task_name,
            'task_link': task_link,
            'task_state': feedback.attempt.get_state_display(),
            'feedback': feedback.text,
            'feedback_link': feedback_link,
            'time_spent_on_task': feedback.time_spent_in_minutes})

        # Manually replace quotes and double-quotes as these get
        # escaped by the template and this makes the message look bad.
        filtered_message = message.replace('&#34;', '"').replace('&#39;', "'")

        send_mail(
            subject,
            filtered_message,
            '<EMAIL>',
            [feedback.attempt.task.owner.email])

        messages.success(self.request, _('Your feedback has been submitted. Thanks!'))
        return redirect('tasks.whats_next', feedback.attempt.task.id)


class CreateTaskView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.CreateView):
    model = Task
    form_class = TaskForm
    template_name = 'tasks/form.html'

    def get_form_kwargs(self):
        kwargs = super(CreateTaskView, self).get_form_kwargs()
        kwargs['initial']['owner'] = self.request.user
        if self.kwargs.get('clone'):
            original_task = Task.objects.get(pk=self.kwargs['clone'])
            kwargs['initial'].update(model_to_dict(original_task))
            kwargs['initial']['keywords'] = original_task.keywords_list
            kwargs['initial']['name'] = ' '.join(['Copy of', original_task.name])
        return kwargs

    def get_context_data(self, *args, **kwargs):
        ctx = super(CreateTaskView, self).get_context_data(*args, **kwargs)
        ctx['task_form'] = ctx.get('form')
        ctx['action'] = 'Add'
        ctx['cancel_url'] = reverse('tasks.list')
        return ctx

    def form_valid(self, form):
        form.save(self.request.user)

        messages.success(self.request, _('Your task has been created.'))
        return redirect('tasks.list')


class ImportTasksView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.TemplateView):

    def get_template_names(self):
        if self.stage == 'preview':
            # After initial form submission
            return ['tasks/confirmation.html']
        else:
            # Initial form load, error or after cancelling from confirmation
            return ['tasks/form.html']

    def get_forms(self):
        kwargs = {'initial': None}
        if self.request.method == 'POST':
            kwargs['data'] = self.request.POST
        batch_form = TaskImportBatchForm(instance=None, prefix='batch',
                                         **kwargs)
        criterion_formset = TaskInvalidCriteriaFormSet(prefix='criterion',
                                                       **kwargs)
        kwargs['initial'] = {'end_date': date.today() + timedelta(days=30),
                             'repeatable': False,
                             'owner': self.request.user}

        task_form = TaskForm(instance=None, prefix='task', **kwargs)

        forms = {'criterion_formset': criterion_formset,
                 'batch_form': batch_form,<commit_msg>Bug 1132472 - Task detail page should display after creating a task<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.contrib import messages
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.forms.models import model_to_dict
from django.shortcuts import redirect
from django.template.loader import get_template
from django.views import generic

from braces.views import LoginRequiredMixin
from datetime import date, timedelta
from django_filters.views import FilterView
from rest_framework import generics
from tower import ugettext as _, ugettext_lazy as _lazy

from oneanddone.base.util import get_object_or_none, SortHeaders
from oneanddone.tasks.filters import ActivityFilterSet, TasksFilterSet
from oneanddone.tasks.forms import (FeedbackForm, PreviewConfirmationForm,
                                    TaskImportBatchForm,
                                    TaskInvalidCriteriaFormSet, TaskForm)
from oneanddone.tasks.mixins import (APIRecordCreatorMixin,
                                     APIOnlyCreatorMayDeleteMixin)
from oneanddone.tasks.mixins import (TaskMustBeAvailableMixin,
                                     HideNonRepeatableTaskMixin)
from oneanddone.tasks.mixins import GetUserAttemptMixin
from oneanddone.tasks.models import (BugzillaBug, Feedback, Task, TaskAttempt,
                                     TaskMetrics)
from oneanddone.tasks.serializers import TaskSerializer
from oneanddone.users.models import User
from oneanddone.users.mixins import (MyStaffUserRequiredMixin,
                                     PrivacyPolicyRequiredMixin)


class ActivityView(LoginRequiredMixin, MyStaffUserRequiredMixin, FilterView):
    list_headers = (
        (_lazy(u'Task'), 'task__name'),
        (_lazy(u'User'), 'user__profile__name'),
        (_lazy(u'Status'), 'state_display'),
        (_lazy(u'Time'), 'elapsed_time'),
    )
    context_object_name = 'attempts'
    template_name = 'tasks/activity.html'
    paginate_by = 20
    filterset_class = ActivityFilterSet

    def get_context_data(self, *args, **kwargs):
        ctx = super(ActivityView, self).get_context_data(*args, **kwargs)
        ctx['headers'] = self.sort_headers
        return ctx

    def get_queryset(self):
        self.sort_headers = SortHeaders(self.request, self.list_headers)
        qs = TaskAttempt.objects.extra(
            select={
                'state_display': TaskAttempt.choice_display_extra_expression('state'),
                'elapsed_time': 'TIMESTAMPDIFF(SECOND, tasks_taskattempt.created, tasks_taskattempt.modified)'
            })
        return qs.order_by(self.sort_headers.get_order_by())


class AvailableTasksView(TaskMustBeAvailableMixin, FilterView):
    queryset = Task.objects.all()
    context_object_name = 'tasks'
    template_name = 'tasks/list.html'
    paginate_by = 10
    filterset_class = TasksFilterSet

    def get_context_data(self, *args, **kwargs):
        ctx = super(AvailableTasksView, self).get_context_data(*args, **kwargs)
        ctx['task_list_heading'] = _('Tasks')
        return ctx


class CreateFeedbackView(LoginRequiredMixin, PrivacyPolicyRequiredMixin,
                         HideNonRepeatableTaskMixin, GetUserAttemptMixin,
                         generic.CreateView):
    model = Feedback
    form_class = FeedbackForm
    template_name = 'tasks/feedback.html'

    def get_context_data(self, *args, **kwargs):
        ctx = super(CreateFeedbackView, self).get_context_data(*args, **kwargs)
        ctx['attempt'] = self.attempt
        return ctx

    def form_valid(self, form):
        feedback = form.save(commit=False)
        feedback.attempt = self.attempt
        feedback.save()

        # Send email to task owner
        task_name = feedback.attempt.task.name
        subject = 'Feedback on %s from One and Done' % task_name
        link_prefix = 'http'
        if self.request.is_secure():
            link_prefix += 's'
        task_link = link_prefix + '://%s%s' % (
            self.request.get_host(),
            feedback.attempt.task.get_absolute_url())
        feedback_link = link_prefix + '://%s/admin/tasks/feedback/%s' % (
            self.request.get_host(), feedback.id)
        template = get_template('tasks/emails/feedback_email.txt')

        message = template.render({
            'feedback_user': feedback.attempt.user,
            'task_name': task_name,
            'task_link': task_link,
            'task_state': feedback.attempt.get_state_display(),
            'feedback': feedback.text,
            'feedback_link': feedback_link,
            'time_spent_on_task': feedback.time_spent_in_minutes})

        # Manually replace quotes and double-quotes as these get
        # escaped by the template and this makes the message look bad.
        filtered_message = message.replace('&#34;', '"').replace('&#39;', "'")

        send_mail(
            subject,
            filtered_message,
            '<EMAIL>',
            [feedback.attempt.task.owner.email])

        messages.success(self.request, _('Your feedback has been submitted. Thanks!'))
        return redirect('tasks.whats_next', feedback.attempt.task.id)


class CreateTaskView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.CreateView):
    model = Task
    form_class = TaskForm
    template_name = 'tasks/form.html'

    def get_form_kwargs(self):
        kwargs = super(CreateTaskView, self).get_form_kwargs()
        kwargs['initial']['owner'] = self.request.user
        if self.kwargs.get('clone'):
            original_task = Task.objects.get(pk=self.kwargs['clone'])
            kwargs['initial'].update(model_to_dict(original_task))
            kwargs['initial']['keywords'] = original_task.keywords_list
            kwargs['initial']['name'] = ' '.join(['Copy of', original_task.name])
        return kwargs

    def get_context_data(self, *args, **kwargs):
        ctx = super(CreateTaskView, self).get_context_data(*args, **kwargs)
        ctx['task_form'] = ctx.get('form')
        ctx['action'] = 'Add'
        ctx['cancel_url'] = reverse('tasks.list')
        return ctx

    def form_valid(self, form):
        task = form.save(self.request.user)

        messages.success(self.request, _('Your task has been created.'))
        return redirect('tasks.detail', task.id)


class ImportTasksView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.TemplateView):

    def get_template_names(self):
        if self.stage == 'preview':
            # After initial form submission
            return ['tasks/confirmation.html']
        else:
            # Initial form load, error or after cancelling from confirmation
            return ['tasks/form.html']

    def get_forms(self):
        kwargs = {'initial': None}
        if self.request.method == 'POST':
            kwargs['data'] = self.request.POST
        batch_form = TaskImportBatchForm(instance=None, prefix='batch',
                                         **kwargs)
        criterion_formset = TaskInvalidCriteriaFormSet(prefix='criterion',
                                                       **kwargs)
        kwargs['initial'] = {'end_date': date.today() + timedelta(days=30),
                             'repeatable': False,
                             'owner': self.request.user}

        task_form = TaskForm(instance=None, prefix='task', **kwargs)

        forms = {'criterion_formset': criterion_formset,
                 'batch_form': batch_form,
{'fraction_non_alphanumeric': 0.10160568570676494, 'fraction_numerical': 0.0023032376941300343, 'mean_word_length': 2.6984667802385007, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '325793', 'n_tokens_mistral': 4278, 'n_tokens_neox': 4101, 'n_words': 917}