Пример #1
0
    def get(self, request, *args, **kwargs):
        task = get_object_or_404(Task, pk=args[0])
        parameter = get_object_or_404(Parameter, pk=args[1])
        title = parameter

        try:
            score = Score.objects.get(parameter=parameter, task=task)
        except Score.DoesNotExist:
            pass
        else:
            return HttpResponseRedirect(reverse("exmo2010:score_view", args=(score.pk,)))

        if not request.user.has_perm("exmo2010.fill_task", task):
            return HttpResponseForbidden(_("Forbidden"))

        self.success_url = self.get_redirect(request, task, parameter)

        self.initial = {"task": task, "parameter": parameter}

        crumbs = ["Home", "Monitoring", "Organization", "ScoreList"]
        breadcrumbs(request, crumbs, task)
        current_title = _("Parameter")

        self.extra_context = {"task": task, "parameter": parameter, "current_title": current_title, "title": title}

        return super(ScoreAddView, self).get(request, *args, **kwargs)
Пример #2
0
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.success_url = self.get_redirect(request)

        if request.user.has_perm("exmo2010.view_score", self.object):
            current_title = _("Parameter")
            all_score_claims = Claim.objects.filter(score=self.object)
            all_score_clarifications = Clarification.objects.filter(score=self.object)
            crumbs = ["Home", "Monitoring", "Organization", "ScoreList"]
            breadcrumbs(request, crumbs, self.object.task)

            self.template_name = "detail.html"
            title = _('Score for parameter "%s"') % self.object.parameter.name
            time_to_answer = self.object.task.organization.monitoring.time_to_answer
            delta = datetime.timedelta(days=time_to_answer)
            today = datetime.date.today()
            peremptory_day = today + delta

            self.extra_context = {
                "current_title": current_title,
                "title": title,
                "task": self.object.task,
                "parameter": self.object.parameter,
                "claim_list": all_score_claims,
                "clarification_list": all_score_clarifications,
                "peremptory_day": peremptory_day,
                "view": True,
                "invcodeform": SettingsInvCodeForm(),
                "claim_form": ClaimAddForm(prefix="claim"),
                "clarification_form": ClarificationAddForm(prefix="clarification"),
            }

        return super(ScoreDetailView, self).get(request, *args, **kwargs)
Пример #3
0
    def get(self, request, *args, **kwargs):
        task = get_object_or_404(Task, pk=self.kwargs["task_id"])
        self.success_url = self.get_redirect(request, task)
        self.object = self.get_object()

        if self.kwargs["method"] == 'delete':
            if not request.user.has_perm('exmo2010.admin_monitoring', task.organization.monitoring):
                return HttpResponseForbidden(_('Forbidden'))
            self.template_name = "exmo2010/parameter_confirm_delete.html"
            title = _('Delete parameter %s') % self.object
            current_title = _('Delete parameter')
            crumbs = ['Home', 'Monitoring', 'Organization', 'ScoreList']
            breadcrumbs(request, crumbs, task)
            self.extra_context = {'current_title': current_title,
                                  'title': title,
                                  'task': task,
                                  'deleted_objects': Score.objects.filter(parameter=self.object), }

        if self.kwargs["method"] == 'exclude':
            if not request.user.has_perm('exmo2010.exclude_parameter', self.object):
                return HttpResponseForbidden(_('Forbidden'))
            if task.organization not in self.object.exclude.all():
                self.object.exclude.add(task.organization)
            return HttpResponseRedirect(self.success_url)

        if self.kwargs["method"] == 'update':
            if not request.user.has_perm('exmo2010.admin_monitoring', task.organization.monitoring):
                return HttpResponseForbidden(_('Forbidden'))
            self.update(request, task)

        return super(ParameterManagerView, self).get(request, *args, **kwargs)
Пример #4
0
def comment_list(request):
    """
    Страница сводного списка комментариев.

    """
    user = request.user
    if not (user.is_active and user.profile.is_expert):
        return HttpResponseForbidden(_('Forbidden'))

    if request.is_ajax():
        comments = user.profile.get_answered_comments()
        return render_to_response(
            'comment_list_table.html',
            {'comments': comments},
            context_instance=RequestContext(request))

    else:
        comments = user.profile.get_filtered_not_answered_comments()
        title = current_title = _('Comments')

        crumbs = ['Home']
        breadcrumbs(request, crumbs)

        return render_to_response('comment_list.html',
                                  {
                                      'current_title': current_title,
                                      'title': title,
                                      'comments': comments,
                                  },
                                  RequestContext(request))
Пример #5
0
def tasks_by_monitoring_and_organization(request, monitoring_id, organization_id):
    """
    We have 3 generic group: experts, customers, organizations.
    Superusers: all tasks
    Experts: only own tasks
    Customers: all approved tasks
    organizations: all approved tasks of organizations that belongs to user
    Also for every ogranization we can have group.

    """
    monitoring = get_object_or_404(Monitoring, pk = monitoring_id)
    organization = get_object_or_404(Organization, pk = organization_id)
    user = request.user
    profile = None
    if user.is_active: profile = user.profile
    if not user.has_perm('exmo2010.view_monitoring', monitoring):
        return HttpResponseForbidden(_('Forbidden'))
    title = _('Task list for %s') % organization.name
    queryset = Task.objects.filter(organization = organization)
    # Or, filtered by user
    if user.has_perm('exmo2010.admin_monitoring', monitoring):
      headers = (
                (_('organization'), 'organization__name', 'organization__name', None, None),
                (_('expert'), 'user__username', 'user__username', None, None),
                (_('status'), 'status', 'status', int, Task.TASK_STATUS),
                (_('complete, %'), None, None, None, None),
                (_('openness, %'), None, None, None, None),
      )
    elif profile and profile.is_expert:
    # Or, without Expert
      headers = (
                (_('organization'), 'organization__name', 'organization__name', None, None),
                (_('status'), 'status', 'status', int, Task.TASK_STATUS),
                (_('complete, %'), None, None, None, None),
                (_('openness, %'), None, None, None, None)
      )
    else:
      queryset = Task.approved_tasks.all()
      queryset = queryset.filter(organization = organization)
      headers = (
                (_('organization'), 'organization__name', 'organization__name', None, None),
                (_('openness, %'), None, None, None, None)
              )
    task_list = []
    for task in queryset:
        if user.has_perm('exmo2010.view_task', task): task_list.append(task.pk)
    queryset = Task.objects.filter(pk__in = task_list)

    crumbs = ['Home', 'Monitoring', 'Organization']
    breadcrumbs(request, crumbs, monitoring)
    current_title = _('Organization')

    return table(request, headers, queryset=queryset, paginate_by=15,
                 extra_context={
                     'monitoring': monitoring,
                     'organization': organization,
                     'current_title': current_title,
                     'title': title,
                 },
                 template_name="task_list.html",)
Пример #6
0
def monitoring_rating(request, m_id):
    """
    Вывод мониторинга.

    """
    monitoring = get_object_or_404(Monitoring, pk=m_id)
    if not request.user.has_perm('exmo2010.rating_monitoring', monitoring):
        return HttpResponseForbidden(_('Forbidden'))
    title = _('Rating')

    has_npa = monitoring.has_npa
    rating_type, parameter_list, form = _rating_type_parameter(request, monitoring, has_npa)
    rating_list, avg = rating(monitoring, parameters=parameter_list, rating_type=rating_type)

    crumbs = ['Home', 'Monitoring']
    breadcrumbs(request, crumbs)

    if request.expert:
        current_title = _('Monitoring cycle')
    else:
        current_title = _('Rating') if monitoring.status == 5 else _('Tasks')

    total_orgs = _total_orgs_translate(avg, rating_list, rating_type)

    return render_to_response('rating.html', {
        'monitoring': monitoring,
        'has_npa': has_npa,
        'object_list': rating_list,
        'rating_type': rating_type,
        'average': avg,
        'total_orgs': total_orgs,
        'current_title': current_title,
        'title': title,
        'form': form,
    }, context_instance=RequestContext(request))
Пример #7
0
def claim_list(request):
    """
    Страница сводного списка претензий для аналитиков.

    """
    user = request.user
    if not (user.is_active and user.profile.is_expert):
        return HttpResponseForbidden(_('Forbidden'))

    if request.is_ajax():
        claims = user.profile.get_closed_claims()
        return render_to_response(
            'claim_list_table.html',
            {'claims': claims},
            context_instance=RequestContext(request))

    else:
        claims = user.profile.get_filtered_opened_claims()
        title = current_title = _('Claims')

        crumbs = ['Home']
        breadcrumbs(request, crumbs)

        return render_to_response('claim_list.html',
                                  {
                                      'current_title': current_title,
                                      'title': title,
                                      'claims': claims,
                                  },
                                  RequestContext(request))
Пример #8
0
def monitoring_add(request):
    """
    Создание мониторинга
    """
    if not request.user.has_perm('exmo2010.create_monitoring', Monitoring()):
        return HttpResponseForbidden(_('Forbidden'))
    title = _('Add new monitoring')
    if request.method == 'POST':
        form = MonitoringForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            with transaction.commit_on_success():
                # Чтобы нельзя было создать удачно мониторинг, а потом словить
                # ошибку создания опроса для него.
                monitoring_instance = form.save()
                if cd.get("add_questionnaire"):
                    questionnaire = Questionnaire(monitoring=monitoring_instance)
                    questionnaire.save()
            redirect = reverse('exmo2010:monitoring_manager',
                args=[monitoring_instance.pk, 'update'])
            return HttpResponseRedirect(redirect)
    else:
        form = MonitoringForm()
        form.fields['status'].choices = Monitoring.MONITORING_STATUS_NEW

    crumbs = ['Home', 'Monitoring']
    breadcrumbs(request, crumbs)
    current_title = _('Add monitoring cycle')

    return render_to_response('monitoring_form.html',
            {'current_title': current_title, 'media': form.media, 'form': form, 'title': title,
             'formset': None, }, context_instance=RequestContext(request))
Пример #9
0
    def get(self, request, *args, **kwargs):
        self.success_url = self.get_redirect(request)
        self.object = self.get_object()
        if self.kwargs["method"] == 'delete':
            if not request.user.has_perm('exmo2010.delete_monitoring', self.object):
                return HttpResponseForbidden(_('Forbidden'))

            title = _('Delete monitoring %s') % self.object
            crumbs = ['Home', 'Monitoring']
            breadcrumbs(request, crumbs)
            current_title = _('Delete monitoring cycle')
            self.template_name = "exmo2010/monitoring_confirm_delete.html"
            self.extra_context = {
                'current_title': current_title,
                'title': title,
                'deleted_objects': Task.objects.filter(organization__monitoring=self.object),
            }

        if self.kwargs["method"] == 'update':
            if not request.user.has_perm('exmo2010.edit_monitoring', self.object):
                return HttpResponseForbidden(_('Forbidden'))
            title = _('Edit monitoring %s') % self.object
            crumbs = ['Home', 'Monitoring']
            breadcrumbs(request, crumbs)
            current_title = _('Edit monitoring cycle')
            self.extra_context = {
                'current_title': current_title,
                'title': title,
            }

        return super(MonitoringManagerView, self).get(request, *args, **kwargs)
Пример #10
0
    def get(self, request, *args, **kwargs):
        monitoring = get_object_or_404(Monitoring, pk=self.kwargs["monitoring_id"])
        if not request.user.has_perm('exmo2010.admin_monitoring', monitoring):
            return HttpResponseForbidden(_('Forbidden'))
        self.success_url = self.get_redirect(request, monitoring)
        self.initial = {'monitoring': monitoring}

        if self.kwargs["method"] == 'add':
            self.add(request, monitoring)

        if self.kwargs["method"] == 'delete':
            self.object = self.get_object()
            self.template_name = "exmo2010/organization_confirm_delete.html"
            title = _('Delete organization %s') % monitoring
            crumbs = ['Home', 'Monitoring', 'Organization']
            breadcrumbs(request, crumbs, monitoring)
            current_title = _('Edit organization')
            self.extra_context = {'current_title': current_title,
                                  'title': title,
                                  'monitoring': monitoring,
                                  'deleted_objects': Task.objects.filter(organization=self.object), }
        if self.kwargs["method"] == 'update':
            self.update(request, monitoring)

        return super(OrganizationManagerView, self).get(request, *args, **kwargs)
Пример #11
0
def parameter_add(request, task_id):
    task = get_object_or_404(Task, pk=task_id)
    if not request.user.has_perm('exmo2010.admin_monitoring', task.organization.monitoring):
        return HttpResponseForbidden(_('Forbidden'))
    redirect = '%s?%s' % (reverse('exmo2010:score_list_by_task', args=[task.pk]), request.GET.urlencode())
    redirect = redirect.replace("%", "%%")
    title = _('Add parameter for %s') % task
    form = None
    if request.method == 'GET':
        form = ParameterForm(monitoring=task.organization.monitoring)
    elif request.method == 'POST':
        form = ParameterForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(redirect)

    crumbs = ['Home', 'Monitoring', 'Organization', 'ScoreList']
    breadcrumbs(request, crumbs, task)
    current_title = _('Add parameter')

    return render_to_response(
        'parameter_form.html',
        {
            'form': form,
            'current_title': current_title,
            'title': title,
            'task': task,
            'media': CORE_MEDIA + form.media,
        },
        context_instance=RequestContext(request),
    )
Пример #12
0
def password_reset_redirect(request, **kwargs):
    if request.user.is_authenticated():
        return redirect('exmo2010:index')
    kwargs['extra_context'] = {'current_title': _('Password reset (step %d from 3)') % 1}
    kwargs['password_reset_form'] = CustomPasswordResetForm
    crumbs = ['Home']
    breadcrumbs(request, crumbs)
    return auth_password_reset(request, **kwargs)
Пример #13
0
 def update(self, request, task):
     title = _('Edit parameter %s') % self.object
     current_title = _('Edit parameter')
     crumbs = ['Home', 'Monitoring', 'Organization', 'ScoreList']
     breadcrumbs(request, crumbs, task)
     self.extra_context = {'current_title': current_title,
                           'title': title,
                           'task': task,
                           'media': CORE_MEDIA + ParameterForm().media, }
Пример #14
0
def clarification_create(request, score_id):
    """
    Добавление уточнения на странице параметра.

    """
    user = request.user
    score = get_object_or_404(Score, pk=score_id)
    redirect = reverse('exmo2010:score_view', args=[score.pk])
    redirect += '#clarifications'  # Named Anchor для открытия нужной вкладки
    title = _('Add new claim for %s') % score
    if request.method == 'POST' and (
        user.has_perm('exmo2010.add_clarification_score', score) or
            user.has_perm('exmo2010.answer_clarification_score', score)):
        form = ClarificationAddForm(request.POST, prefix="clarification")
        if form.is_valid():
            # Если заполнено поле clarification_id,
            # значит это ответ на уточнение
            if form.cleaned_data['clarification_id'] is not None and \
                    user.has_perm('exmo2010.answer_clarification_score', score):
                clarification_id = form.cleaned_data['clarification_id']
                clarification = get_object_or_404(Clarification,
                                                  pk=clarification_id)
                answer = form.cleaned_data['comment']
                clarification.add_answer(user, answer)
            else:
                # Если поле claim_id пустое, значит это выставление уточнения
                clarification = score.add_clarification(
                    user, form.cleaned_data['comment'])

            clarification_was_posted.send(
                sender=Clarification.__class__,
                clarification=clarification,
                request=request,
            )

            return HttpResponseRedirect(redirect)

        else:

            crumbs = ['Home', 'Monitoring', 'Organization', 'ScoreList', 'ScoreView']
            breadcrumbs(request, crumbs, score)
            current_title = _('Create clarification')

            return render_to_response(
                'clarification_form.html',
                {
                    'monitoring': score.task.organization.monitoring,
                    'task': score.task,
                    'score': score,
                    'current_title': current_title,
                    'title': title,
                    'form': form,
                },
                context_instance=RequestContext(request),
            )
    else:
        raise Http404
Пример #15
0
 def update(self, request, monitoring):
     self.object = self.get_object()
     title = _('Edit organization %s') % monitoring
     crumbs = ['Home', 'Monitoring', 'Organization']
     breadcrumbs(request, crumbs, monitoring)
     current_title = _('Edit organization')
     self.extra_context = {'current_title': current_title,
                           'title': title,
                           'monitoring': monitoring, }
Пример #16
0
 def add(self, request, monitoring):
     self.object = None
     title = _('Add new organization for %s') % monitoring
     crumbs = ['Home', 'Monitoring', 'Organization']
     breadcrumbs(request, crumbs, monitoring)
     current_title = _('Add organization')
     self.extra_context = {'current_title': current_title,
                           'title': title,
                           'org_type': 'add',
                           'monitoring': monitoring}
Пример #17
0
def task_add(request, monitoring_id, organization_id=None):
    monitoring = get_object_or_404(Monitoring, pk = monitoring_id)
    if organization_id:
        organization = get_object_or_404(Organization, pk = organization_id)
        redirect = '%s?%s' % (reverse('exmo2010:tasks_by_monitoring_and_organization', args=[monitoring.pk, organization.pk]), request.GET.urlencode())
        title = _('Add new task for %s') % organization.name
    else:
        organization = None
        redirect = '%s?%s' % (reverse('exmo2010:tasks_by_monitoring', args=[monitoring.pk]), request.GET.urlencode())
        title = _('Add new task for %s') % monitoring

    redirect = redirect.replace("%","%%")
    current_title = _('Add task')
    if request.user.has_perm('exmo2010.admin_monitoring', monitoring):
        if request.method == 'GET':
            form = TaskForm(initial={'organization': organization}, monitoring=monitoring)

            crumbs = ['Home', 'Monitoring', 'Organization']
            breadcrumbs(request, crumbs, monitoring)

            return render_to_response(
                'exmo2010/task_form.html',
                {
                    'monitoring': monitoring,
                    'organization': organization,
                    'current_title': current_title,
                    'title': title,
                    'form': form
                },
                context_instance=RequestContext(request),
            )
        if request.method == 'POST':
            form = TaskForm(request.POST, monitoring=monitoring)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(redirect)
            else:

                crumbs = ['Home', 'Monitoring', 'Organization']
                breadcrumbs(request, crumbs, monitoring)

                return render_to_response(
                    'exmo2010/task_form.html',
                    {
                        'monitoring': monitoring,
                        'organization': organization,
                        'current_title': current_title,
                        'title': title,
                        'form': form
                    },
                    context_instance=RequestContext(request),
                )
    else:
        return HttpResponseForbidden(_('Forbidden'))
Пример #18
0
def claim_manager(request, score_id, claim_id=None, method=None):
    """
    Вью для манипуляции с претензиями.

    """
    score = get_object_or_404(Score, pk=score_id)
    redirect = reverse('exmo2010:score_view', args=[score.pk])
    title = _('Add new claim for %s') % score

    if claim_id:
        claim = get_object_or_404(Claim, pk=claim_id)
    elif not method:  # create new
        if not request.user.has_perm('exmo2010.add_claim', score):
            return HttpResponseForbidden(_('Forbidden'))
        if request.method == 'GET':
            form = ClaimForm()
            form.fields['creator'].initial = request.user.pk
            form.fields['score'].initial = score.pk
        elif request.method == 'POST':
            form = ClaimForm(request.POST)
            if form.is_valid():
                if form.cleaned_data['score'] == score and form.cleaned_data['creator'] == request.user:
                    claim = score.add_claim(request.user,
                                            form.cleaned_data['comment'])
                    claim_was_posted_or_deleted.send(
                        sender=Claim.__class__,
                        claim=claim,
                        request=request,
                        creation=True,
                    )
                    return HttpResponseRedirect(redirect)

        crumbs = ['Home', 'Monitoring', 'Organization', 'ScoreList', 'ScoreView']
        breadcrumbs(request, crumbs, score)
        current_title = _('Edit claim')

        return render_to_response(
            'claim_form.html',
            {
                'monitoring': score.task.organization.monitoring,
                'task': score.task,
                'score': score,
                'current_title': current_title,
                'title': title,
                'form': form,
            },
            context_instance=RequestContext(request),
        )
Пример #19
0
def score_add_comment(request, score_id):
    score = get_object_or_404(Score, pk=score_id)
    title = _("Add new comment")
    if request.user.has_perm("exmo2010.add_comment_score", score):

        crumbs = ["Home", "Monitoring", "Organization", "ScoreList", "ScoreView"]
        breadcrumbs(request, crumbs, score)
        current_title = _("Add comment")

        return render_to_response(
            "score_comment_form.html",
            {"score": score, "current_title": current_title, "title": title},
            context_instance=RequestContext(request),
        )
    else:
        return HttpResponseForbidden(_("Forbidden"))
Пример #20
0
def monitoring_list(request):
    """
    Список мониторингов.

    """
    queryset = _get_monitoring_list(request)

    headers =   (
                (_('monitoring'), 'name', 'name', None, None),
                (_('status'), 'status', 'status', int, MONITORING_STATUS),
                )
    title = _('Monitoring list')

    #todo: remove this
    active_tasks = None
    if request.user.is_active and request.user.userprofile.is_organization:
        active_tasks = Task.objects.filter(
            organization__monitoring__status=MONITORING_INTERACT,
            organization__in=request.user.profile.organization.all(),
            status=Task.TASK_APPROVED,
        )
        invcodeform = SettingsInvCodeForm()
    else:
        invcodeform = None

    if not queryset.count() and not request.user.has_perm('exmo2010.create_monitoring', Monitoring()):
        return HttpResponseForbidden(_('Forbidden'))

    crumbs = ['Home']
    breadcrumbs(request, crumbs)
    current_title = _('Monitoring cycles')

    return table(
        request,
        headers,
        queryset = queryset,
        paginate_by = 25,
        extra_context = {
            'current_title': current_title,
            'title': title,
            'fakeobject': Monitoring(),
            'active_tasks': active_tasks,
            'invcodeform': invcodeform,
        },
    )
Пример #21
0
def task_history(request, task_id):

    task = Task.objects.get(pk=task_id)
    history = TaskHistory.objects.filter(task=task_id)

    crumbs = ['Home', 'Monitoring', 'Organization']
    breadcrumbs(request, crumbs, task)

    return render_to_response(
        'task_history.html',
        {
            'task': task,
            'history': history,
            'current_title': _('Organization'),
            'title': _('%s') % task.organization.name,
        },
        context_instance=RequestContext(request),
    )
Пример #22
0
def feedback(request):
    success = False

    if request.user.is_active:
        form = FeedbackForm(initial={'email': request.user.email})
    else:
        form = FeedbackForm()

    if request.method == "POST":
        form = FeedbackForm(request.POST)
        if form.is_valid():
            support_email = config_value('EmailServer', 'DEFAULT_SUPPORT_EMAIL'),
            email = form.cleaned_data['email']
            comment = form.cleaned_data['comment']
            if request.user.is_active:
                user = request.user
            else:
                user = None
            _send_feedback_mail(support_email,
                                [email, ],
                                comment,
                                "exmo2010/emails/feedback_recipient.txt",
                                "exmo2010/emails/feedback_recipient.html",
                                user=user)
            _send_feedback_mail([email, ],
                                [email, ],
                                comment,
                                "exmo2010/emails/feedback_creator.txt",
                                "exmo2010/emails/feedback_creator.html",
                                user=user)
            success = True

    crumbs = ['Home']
    breadcrumbs(request, crumbs)
    title = _('Feedback')

    t = 'exmo2010/feedback.html'
    c = {
        'current_title': title,
        'title': title,
        'form': form,
        'success': success,
    }
    return render_to_response(t, c, context_instance=RequestContext(request))
Пример #23
0
def password_reset_confirm(request, uidb36=None, token=None,
                   template_name='registration/password_reset_confirm.html',
                   token_generator=default_token_generator,
                   current_app=None, extra_context=None):
    """
    Переприсанная стандартная вьюха для смены пароля.
    Изменение - немедленный логин после установки нового пароля.
    """
    assert uidb36 is not None and token is not None # checked by URLconf
    post_reset_redirect = reverse('exmo2010:index')
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
    except (ValueError, User.DoesNotExist):
        user = None

    if user is not None and token_generator.check_token(user, token):
        validlink = True
        if request.method == 'POST':
            form = SetPasswordForm(user, request.POST)
            if form.is_valid():
                form.save()
                user.backend='django.contrib.auth.backends.ModelBackend'
                login(request, user)
                return HttpResponseRedirect(post_reset_redirect)
        else:
            form = SetPasswordForm(None)
    else:
        validlink = False
        form = None
    title = _('Password reset (step %d from 3)') % 3
    context = {
        'form': form,
        'validlink': validlink,
        'current_title': title,
        }
    context.update(extra_context or {})

    crumbs = ['Home']
    breadcrumbs(request, crumbs)

    return render_to_response(template_name, context,
        context_instance=RequestContext(request, current_app=current_app))
Пример #24
0
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        organization = self.object.organization
        monitoring = organization.monitoring
        organization_id = self.kwargs.get('organization_id')
        self.success_url = self.get_redirect(request, monitoring, organization, organization_id)

        valid_methods = ['delete', 'approve', 'close',
                         'open', 'update', 'get', ]
        if self.kwargs["method"] not in valid_methods:
            HttpResponseForbidden(_('Forbidden'))

        current_title = title = _('Edit task')

        if self.kwargs["method"] == 'delete':
            title = _('Delete task %s') % self.object
            if not request.user.has_perm('exmo2010.admin_monitoring', monitoring):
                return HttpResponseForbidden(_('Forbidden'))
            else:
                self.template_name = "exmo2010/task_confirm_delete.html"
                crumbs = ['Home', 'Monitoring', 'Organization']
                breadcrumbs(request, crumbs, self.object)
                current_title = _('Delete task')
                self.extra_context = {'monitoring': monitoring,
                                      'organization': organization,
                                      'current_title': current_title,
                                      'title': title,
                                      'deleted_objects': Score.objects.filter(task=self.object), }

        if self.kwargs["method"] == 'close':
            title = _('Close task %s') % self.object
            if not request.user.has_perm('exmo2010.close_task', self.object):
                return HttpResponseForbidden(_('Forbidden'))
            else:
                if self.object.open:
                    try:
                        reversion.set_comment(_('Task ready'))
                        self.object.ready = True
                    except ValidationError, e:
                        return HttpResponse('%s' % e.message_dict.get('__all__')[0])
                else:
                    return HttpResponse(_('Already closed'))
Пример #25
0
def ratings(request):
    """
    Рейтинги.

    """
    m_id = request.GET.get('monitoring')
    mform = MonitoringFilterForm(request.GET)
    title = _('Ratings')
    current_title = _('Ratings')

    context = {
        'title': title,
        'current_title': current_title,
        'report': True,
        'mform': mform,
    }

    if m_id:
        monitoring = get_object_or_404(Monitoring, pk=m_id)
        if not request.user.has_perm('exmo2010.rating_monitoring', monitoring):
            return HttpResponseForbidden(_('Forbidden'))
        has_npa = monitoring.has_npa
        rating_type, parameter_list, form = _rating_type_parameter(request, monitoring, has_npa)
        rating_list, avg = rating(monitoring, parameters=parameter_list, rating_type=rating_type)
        con = {
            'monitoring': monitoring,
            'has_npa': has_npa,
            'object_list': rating_list,
            'rating_type': rating_type,
            'average': avg,
            'form': form,
        }
        context.update(con)
        context['total_orgs'] = _total_orgs_translate(avg, rating_list, rating_type)

    crumbs = ['Home']
    breadcrumbs(request, crumbs)

    return render_to_response('rating_report.html', context, context_instance=RequestContext(request))
Пример #26
0
def set_npa_params(request, m_id):
    """
    Страница 'Выбрать согласованные параметры'.

    """
    # На админа проверять не надо. Они и так все is_expertA.
    if not request.user.is_active or not request.user.profile.is_expertA:
        return HttpResponseForbidden(_('Forbidden'))
    monitoring = get_object_or_404(Monitoring, pk=m_id)
    parameters = monitoring.parameter_set.all()
    ParameterTypeFormSet = modelformset_factory(Parameter,
                                                extra=0,
                                                form=ParameterTypeForm)
    if request.method == "POST":
        formset = ParameterTypeFormSet(request.POST, queryset=parameters)
        # Нельзя изменять опубликованные мониторинги.
        if monitoring.status == MONITORING_PUBLISH:
            messages.warning(request, _("Forbidden to modify already "
                                        "published monitorings."), 'warning')
        else:
            if formset.is_valid():
                formset.save()
                messages.success(request, _("Changes have saved."))
    else:
        formset = ParameterTypeFormSet(queryset=parameters)

    crumbs = ['Home', 'Monitoring']
    breadcrumbs(request, crumbs)

    if request.expert:
        current_title = _('Monitoring cycle')
    else:
        current_title = _('Rating') if monitoring.status == 5 else _('Tasks')

    return render_to_response('set_npa_params.html',
                              {"formset": formset, "monitoring": monitoring, "current_title": current_title},
                              context_instance=RequestContext(request))
Пример #27
0
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if request.user.has_perm("exmo2010.edit_score", self.object):
            current_title = _("Parameter")
            all_score_claims = Claim.objects.filter(score=self.object)
            all_score_clarifications = Clarification.objects.filter(score=self.object)
            crumbs = ["Home", "Monitoring", "Organization", "ScoreList"]
            breadcrumbs(request, crumbs, self.object.task)

            title = _("%s") % self.object.parameter
            self.extra_context = {
                "task": self.object.task,
                "parameter": self.object.parameter,
                "current_title": current_title,
                "title": title,
                "claim_list": all_score_claims,
                "clarification_list": all_score_clarifications,
                "claim_form": ClaimAddForm(prefix="claim"),
                "clarification_form": ClarificationAddForm(prefix="clarification"),
            }
        else:
            return HttpResponseForbidden(_("Forbidden"))

        return super(ScoreEditView, self).get(request, *args, **kwargs)
Пример #28
0
def organization_list(request, monitoring_id):
    name_filter = invite_filter = None
    alert = request.GET.get('alert', False)
    if request.method == "GET":
        name_filter = request.GET.get('name_filter', False)
        invite_filter = request.GET.get('invite_filter', False)

    monitoring = get_object_or_404(Monitoring, pk=monitoring_id)
    if not request.user.has_perm('exmo2010.view_monitoring', monitoring):
        return HttpResponseForbidden(_('Forbidden'))
    title = _('Organizations for monitoring %s') % monitoring

    orgs = Organization.objects.filter(monitoring=monitoring)
    sent = orgs.exclude(inv_status='NTS')

    initial = {'monitoring': monitoring}

    org_type = 'all'

    if request.method == "POST" and "submit_invite" in request.POST:
        inv_form = InviteOrgsForm(request.POST)
        comment = inv_form.data['comment']
        inv_status = inv_form.data['inv_status']
        if inv_form.is_valid():
            inv_form.save()

            if inv_status != 'ALL':
                orgs = orgs.filter(inv_status=inv_status)

            for org in orgs:
                subject = _('Email Subject')
                message = comment.replace('%code%', org.inv_code)
                context = {
                    'subject': subject,
                    'message': message
                }
                if org.email:
                    emails = filter(None, org.email.split(', '))
                else:
                    continue
                task_id = send_email.delay(emails, subject, 'organizations/invitation_email', context=context, mdn=True)

                task = EmailTasks()
                task.task_id = task_id
                task.organization = org
                task.save()

            redirect = reverse('exmo2010:organization_list', args=[monitoring_id])+"?alert=success"
            return HttpResponseRedirect(redirect)
        else:
            initial.update({'comment': comment, 'inv_status': inv_status})
            alert = 'fail'

    inv_form = InviteOrgsForm(initial=initial)

    if request.user.has_perm('exmo2010.admin_monitoring', monitoring):
        queryset = Organization.objects.filter(monitoring=monitoring).extra(
            select={
                'task__count': 'SELECT count(*) FROM %s WHERE organization_id = %s.id' % (
                    Task._meta.db_table,
                    Organization._meta.db_table,
                ),
            }
        )

        headers = (
            (_('organization'), 'name', None, None, None),
            (_('email'), 'email', None, None, None),
            (_('phone'), 'phone', None, None, None),
            (_('invitation code'), 'inv_code', None, None, None),
            (_('tasks'), 'task__count', None, None, None),
            (_('invitation'), 'inv_status', None, None, None),
        )
    else:
        org_list = []
        for task in Task.objects.filter(organization__monitoring=monitoring).select_related():
            if request.user.has_perm('exmo2010.view_task', task):
                org_list.append(task.organization.pk)
        org_list = list(set(org_list))
        if not org_list:
            return HttpResponseForbidden(_('Forbidden'))
        queryset = Organization.objects.filter(pk__in=org_list)
        headers = (
            (_('organization'), 'name', None, None, None),
            (_('email'), 'email', None, None, None),
            (_('phone'), 'phone', None, None, None),
            (_('invitation code'), 'inv_code', None, None, None),
            (_('invitation'), 'inv_status', None, None, None),
        )

    if not sent:
        headers_list = list(headers)
        headers_list.pop()
        headers = tuple(headers_list)

    if name_filter:
        queryset = queryset.filter(name__icontains=name_filter)
    if invite_filter and invite_filter != 'ALL':
        queryset = queryset.filter(inv_status=invite_filter)

    crumbs = ['Home', 'Monitoring']
    breadcrumbs(request, crumbs)

    if request.expert:
        current_title = _('Monitoring cycle')
    else:
        current_title = _('Rating') if monitoring.status == 5 else _('Tasks')

    initial = {'monitoring': monitoring}
    form = OrganizationForm(initial=initial)
    if request.method == "POST" and "submit_add" in request.POST:
        form = OrganizationForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            org_type = 'add'

    inv_history = InviteOrgs.objects.filter(monitoring=monitoring)

    date_filter_history = None
    invite_filter_history = None

    if request.method == "GET":
        date_filter_history = request.GET.get('date_filter_history', False)
        invite_filter_history = request.GET.get('invite_filter_history', False)

        if date_filter_history:
            start_datetime = datetime.strptime("%s 00:00:00" % date_filter_history, '%d.%m.%Y %H:%M:%S')
            finish_datetime = datetime.strptime("%s 23:59:59" % date_filter_history, '%d.%m.%Y %H:%M:%S')
            inv_history = inv_history.filter(timestamp__gt=start_datetime,
                                             timestamp__lt=finish_datetime)
        if invite_filter_history and invite_filter_history != 'ALL':
            inv_history = inv_history.filter(inv_status=invite_filter_history)

    return table(
        request,
        headers,
        queryset=queryset,
        paginate_by=100,
        extra_context={
            'current_title': current_title,
            'title': title,
            'sent': sent,
            'inv_form': inv_form,
            'alert': alert,
            'org_type': org_type,
            'inv_status': INV_STATUS,
            'monitoring': monitoring,
            'invcodeform': SettingsInvCodeForm(),
            'form': form,
            'inv_history': inv_history,
            'date_filter_history': date_filter_history,
            'invite_filter_history': invite_filter_history,
        },
    )
Пример #29
0
def claim_report(request, monitoring_id):
    """
    Отчёт по претензиям.

    """
    if not request.user.profile.is_expertA:
        return HttpResponseForbidden(_('Forbidden'))
    monitoring = get_object_or_404(Monitoring, pk=monitoring_id)
    all_claims = Claim.objects.filter(
        score__task__organization__monitoring=monitoring).order_by("open_date")
    title = _('Claims report for "%s"') % monitoring

    if request.is_ajax():
        creator_id = request.REQUEST.get('creator_id')
        addressee_id = request.REQUEST.get('addressee_id')
        if creator_id is not None and addressee_id is not None:
            creator_id = int(creator_id)
            addressee_id = int(addressee_id)
            claims = all_claims.filter(close_date__isnull=False)
            if creator_id != 0:
                claims = claims.filter(creator__id=creator_id)
            if addressee_id != 0:
                claims = claims.filter(addressee__id=addressee_id)
            return render_to_response(
                'claim_report_table.html',
                {'claims': claims},
                context_instance=RequestContext(request))
        else:
            raise Http404

    claims = all_claims.filter(close_date__isnull=True)

    addressee_id_list = all_claims.order_by().values_list(
        "addressee", flat=True).distinct()
    creator_id_list = all_claims.order_by().values_list(
        "creator", flat=True).distinct()

    if request.method == "POST":
        form = ClaimReportForm(request.POST,
                               creator_id_list=creator_id_list,
                               addressee_id_list=addressee_id_list)
        if form.is_valid():
            cd = form.cleaned_data
            creator_id = int(cd["creator"])
            addressee_id = int(cd["addressee"])
            if creator_id != 0:
                claims = claims.filter(creator__id=creator_id)
            if addressee_id != 0:
                claims = claims.filter(addressee__id=addressee_id)
    else:
        form = ClaimReportForm(creator_id_list=creator_id_list,
                               addressee_id_list=addressee_id_list)

    crumbs = ['Home', 'Monitoring']
    breadcrumbs(request, crumbs)

    if request.expert:
        current_title = _('Monitoring cycle')
    else:
        current_title = _('Rating') if monitoring.status == 5 else _('Tasks')

    return render_to_response(
        'claim_report.html',
        {
            'monitoring': monitoring,
            'current_title': current_title,
            'title': title,
            'claims': claims,
            'form': form,
        },
        context_instance=RequestContext(request),
    )
Пример #30
0
def tasks_by_monitoring(request, monitorgin_id):
    monitoring = get_object_or_404(Monitoring, pk=monitorgin_id)
    profile = None
    if request.user.is_active:
        profile = request.user.profile
    if not request.user.has_perm('exmo2010.view_monitoring', monitoring):
        return HttpResponseForbidden(_('Forbidden'))
    title = _('Task list for %(monitoring)s') % {'monitoring': monitoring}
    task_list = []
    queryset = Task.objects.filter(organization__monitoring=monitoring).\
    select_related()
    for task in queryset:
        if request.user.has_perm('exmo2010.view_task', task):
            task_list.append(task.pk)
    if not task_list and not \
    request.user.has_perm('exmo2010.admin_monitoring', monitoring):
        return HttpResponseForbidden(_('Forbidden'))
    queryset = Task.objects.filter(pk__in=task_list)
    if request.user.has_perm('exmo2010.admin_monitoring', monitoring):
        users = User.objects.filter(task__organization__monitoring = monitoring).distinct()
        UserChoice = [(u.username, u.profile.legal_name) for u in users]
        headers = (
            (_('organization'), 'organization__name', 'organization__name',
             None, None),
            (_('expert'), 'user__username', 'user__username', None, UserChoice),
            (_('status'), 'status', 'status', int, Task.TASK_STATUS),
            (_('complete, %'), None, None, None, None),
            )
    elif profile and profile.is_expert:
        headers = (
            (_('organization'), 'organization__name', 'organization__name',
             None, None),
             (_('status'), 'status', 'status', int, Task.TASK_STATUS),
             (_('complete, %'), None, None, None, None),
            )
    else:
        headers = (
            (_('organization'), 'organization__name', 'organization__name',
             None, None),
            )

    crumbs = ['Home', 'Monitoring']
    breadcrumbs(request, crumbs)

    if request.expert:
        current_title = _('Monitoring cycle')
    else:
        current_title = _('Rating') if monitoring.status == 5 else _('Tasks')

    return table(
        request,
        headers,
        queryset = queryset,
        paginate_by = 50,
        extra_context = {
            'monitoring': monitoring,
            'current_title': current_title,
            'title': title,
            'invcodeform': SettingsInvCodeForm(),
        },
        template_name="task_list.html",
    )