Exemple #1
0
def task_import(request, task_pk):
    task = get_object_or_404(Task, pk=task_pk)
    if not request.user.has_perm('exmo2010.fill_task', task):
        return HttpResponseForbidden(_('Forbidden'))
    if not request.FILES.has_key('taskfile'):
        return HttpResponseRedirect(reverse('exmo2010:score_list_by_task', args=[task_pk]))
    reader = UnicodeReader(request.FILES['taskfile'])
    errLog = []
    rowOKCount = 0
    rowALLCount = 0
    try:
        for row in reader:
            rowALLCount += 1
            if row[0].startswith('#'):
                errLog.append(_("row %d. Starts with '#'. Skipped") % reader.line_num)
                continue
            try:
                code = re.match('^(\d+)$', row[0])
                if not code:
                    errLog.append(_("row %(row)d (csv). Not a code: %(raw)s") % {'row': reader.line_num, 'raw': row[0]})
                    continue
                if not any(row[2:16]):
                    errLog.append(_("row %(row)d (csv). Empty score: %(raw)s") % {'row': reader.line_num, 'raw': row[0]})
                    continue
                parameter = Parameter.objects.get(code=code.group(1), monitoring=task.organization.monitoring)
                try:
                    score = Score.objects.get(task=task, parameter=parameter)
                except Score.DoesNotExist:
                    score = Score()
                score.task = task
                score.parameter = parameter
                for i, key in enumerate(['found', 'complete', 'completeComment', 'topical', 'topicalComment',
                                         'accessible', 'accessibleComment', 'hypertext', 'hypertextComment',
                                         'document', 'documentComment', 'image', 'imageComment', 'comment']):
                    value = row[i+2]
                    setattr(score, key, value if value else None)
                score.full_clean()
                score.save()
            except ValidationError, e:
                errLog.append(_("row %(row)d (validation). %(raw)s") % {
                    'row': reader.line_num,
                    'raw': '; '.join(['%s: %s' % (i[0], ', '.join(i[1])) for i in e.message_dict.items()])})
            except Parameter.DoesNotExist:
                errLog.append(_("row %(row)d. %(raw)s") % {
                    'row': reader.line_num,
                    'raw': _('Parameter matching query does not exist')})
            except Exception, e:
                errLog.append(_("row %(row)d. %(raw)s") % {
                    'row': reader.line_num,
                    'raw': filter(lambda x: x in string.printable, e.__str__())})
Exemple #2
0
def task_import(request, task_pk):
    task = get_object_or_404(Task, pk=task_pk)
    if not request.user.has_perm('exmo2010.fill_task', task):
        raise PermissionDenied

    if 'taskfile' not in request.FILES:
        return HttpResponseRedirect(
            reverse('exmo2010:task_scores', args=[task_pk]))
    reader = UnicodeReader(request.FILES['taskfile'])
    errors = []
    rowOKCount = 0
    row_num = 0
    try:
        for row_num, row in enumerate(reader, start=1):
            if row[0].startswith('#'):
                errors.append(_("row %d. Starts with '#'. Skipped") % row_num)
                continue
            try:
                code = re.match('^(\d+)$', row[0])
                if not code:
                    errors.append(
                        _("row %(row)d (csv). Not a code: %(raw)s") % {
                            'row': row_num,
                            'raw': row[0]
                        })
                    continue
                if not any(row[2:16]):
                    errors.append(
                        _("row %(row)d (csv). Empty score: %(raw)s") % {
                            'row': row_num,
                            'raw': row[0]
                        })
                    continue
                parameter = Parameter.objects.get(
                    code=code.group(1),
                    monitoring=task.organization.monitoring)
                try:
                    score = Score.objects.get(task=task, parameter=parameter)
                except Score.DoesNotExist:
                    score = Score()
                score.task = task
                score.parameter = parameter
                for i, key in enumerate([
                        'found', 'complete', 'topical', 'accessible',
                        'hypertext', 'document', 'image', 'links',
                        'recommendations'
                ]):
                    value = row[i + 2]
                    setattr(score, key, value if value else None)
                score.full_clean()
                score.save()
            except ValidationError, e:
                errors.append(
                    _("row %(row)d (validation). %(raw)s") % {
                        'row':
                        row_num,
                        'raw':
                        '; '.join([
                            '%s: %s' % (i[0], ', '.join(i[1]))
                            for i in e.message_dict.items()
                        ])
                    })
            except Parameter.DoesNotExist:
                errors.append(
                    _("row %(row)d. %(raw)s") % {
                        'row': row_num,
                        'raw': _('Parameter matching query does not exist')
                    })
            except Exception, e:
                errors.append(
                    _("row %(row)d. %(raw)s") % {
                        'row': row_num,
                        'raw': filter(lambda x: x in string.printable,
                                      e.__str__())
                    })
Exemple #3
0
def task_import(request, id):
    task = get_object_or_404(Task, pk=id)
    if not request.user.has_perm('exmo2010.fill_task', task):
        return HttpResponseForbidden(_('Forbidden'))
    if not request.FILES.has_key('taskfile'):
        return HttpResponseRedirect(reverse('exmo2010:score_list_by_task', args=[id]))
    reader = UnicodeReader(request.FILES['taskfile'])
    errLog = []
    rowOKCount = 0
    rowALLCount = 0
    try:
        for row in reader:
            rowALLCount += 1
            if row[0].startswith('#'):
                errLog.append(_("row %d. Starts with '#'. Skipped") % reader.line_num)
                continue
            try:
                code = re.match('^(\d+)$', row[0])
                if not code:
                  errLog.append(_("row %(row)d (csv). Not a code: %(raw)s") % {'row': reader.line_num, 'raw': row[0]})
                  continue
                if (
                    row[2]  == '' and
                    row[3]  == '' and
                    row[4]  == '' and
                    row[5]  == '' and
                    row[6]  == '' and
                    row[7]  == '' and
                    row[8]  == '' and
                    row[9]  == '' and
                    row[10] == '' and
                    row[11] == '' and
                    row[12] == '' and
                    row[13] == '' and
                    row[14] == '' and
                    row[15] == ''
                  ):
                    errLog.append(_("row %(row)d (csv). Empty score: %(raw)s") % {'row': reader.line_num, 'raw': row[0]})
                    continue
                parameter = Parameter.objects.get(code=code.group(1), monitoring = task.organization.monitoring)
                try:
                    score = Score.objects.get(task = task, parameter = parameter)
                except Score.DoesNotExist:
                    score = Score()
                score.task              = task
                score.parameter         = parameter
                score.found             = row[2]
                score.complete          = row[3]
                score.completeComment   = row[4]
                score.topical           = row[5]
                score.topicalComment    = row[6]
                score.accessible        = row[7]
                score.accessibleComment = row[8]
                score.hypertext         = row[9]
                score.hypertextComment  = row[10]
                score.document          = row[11]
                score.documentComment   = row[12]
                score.image             = row[13]
                score.imageComment      = row[14]
                score.comment           = row[15]
                score.full_clean()
                score.save()
            except ValidationError, e:
                errLog.append(_("row %(row)d (validation). %(raw)s") % {
                    'row': reader.line_num,
                    'raw': '; '.join(['%s: %s' % (i[0], ', '.join(i[1])) for i in e.message_dict.items()])})
            except Parameter.DoesNotExist:
                errLog.append(_("row %(row)d. %(raw)s") % {
                    'row': reader.line_num,
                    'raw': _('Parameter matching query does not exist')})
            except Exception, e:
                errLog.append(_("row %(row)d. %(raw)s") % {
                    'row': reader.line_num,
                    'raw': filter(lambda x: x in string.printable, e.__str__())})
Exemple #4
0
def score_view(request, **kwargs):
    if request.method not in ['POST', 'GET']:
        return HttpResponseNotAllowed(permitted_methods=['POST', 'GET'])

    if 'score_pk' in kwargs:
        # Score edit or view
        score = get_object_or_404(Score, pk=kwargs['score_pk'])
        task = score.task
        param = score.parameter
        if request.method == 'POST' and not request.user.has_perm('exmo2010.edit_score', score):
            raise PermissionDenied
        if request.method == 'GET' and not request.user.has_perm('exmo2010.view_score', score):
            raise PermissionDenied
    else:
        # Score creation by task and param
        task = get_object_or_404(Task, pk=kwargs['task_pk'])
        param = get_object_or_404(Parameter, pk=kwargs['parameter_pk'])
        if not request.user.has_perm('exmo2010.fill_task', task):
            raise PermissionDenied

        # Check if score already exist.
        try:
            score = Score.objects.get(parameter=param, task=task, revision=Score.FINAL)
        except Score.DoesNotExist:
            # OK, score does not exist and can be created.
            score = Score(parameter=param, task=task, revision=Score.FINAL)
        else:
            # User requested score creation by task and param, but score already exist.
            if request.user.has_perm('exmo2010.view_score', score):
                # Redirect user to GET score page, even if current request method is POST.
                # This way duplicate POST to create score will be ignored.
                return HttpResponseRedirect(reverse('exmo2010:score', args=[score.pk]))
            else:
                raise PermissionDenied

    org = task.organization
    param.relevant = bool(task.organization not in param.exclude.all())

    if not param.relevant and not request.user.is_expert:
        raise PermissionDenied

    # Relevant criteria names
    criteria = ['found'] + filter(param.__getattribute__, Parameter.OPTIONAL_CRITERIA)

    ScoreForm = modelform_factory(
        Score,
        fields=criteria + ['recommendations', 'links', 'editor'],
        widgets=dict((crit, RadioSelect) for crit in criteria))

    ScoreForm.base_fields['comment'] = RichTextFormField(config_name='advanced', required=False)

    # Replace '-----' with '-' in empty radio choices.
    for f in criteria:
        ScoreForm.base_fields[f].widget.choices[0] = ('', '–')

    form = ScoreForm(request.POST if request.method == 'POST' else None, instance=score)

    if request.method == 'POST' and form.is_valid():
        if score.pk and not request.user.has_perm('exmo2010.edit_score', score):
            raise PermissionDenied

        with transaction.commit_on_success():
            if org.monitoring.status in Monitoring.after_interaction_status and 'score_pk' in kwargs:
                if not Score.objects.filter(parameter=param, task=task, revision=Score.INTERIM).exists():
                    # Interim revision does not exist and should be created. It will have new pk.
                    interim_score = Score.objects.get(pk=kwargs['score_pk'])
                    last_modified = interim_score.last_modified
                    interim_score.pk = None
                    interim_score.revision = Score.INTERIM
                    interim_score.save()
                    # Restore last_modified field, that was overwritten by save()
                    Score.objects.filter(pk=interim_score.pk).update(last_modified=last_modified)

                _add_comment(request, score)
            score = form.save(commit=False)
            score.editor = request.user
            score.save()
        if org.monitoring.is_interact or org.monitoring.is_finishing:
            return HttpResponseRedirect(reverse('exmo2010:score', args=[score.pk]))
        else:
            url = reverse('exmo2010:task_scores', args=[task.pk])
            return HttpResponseRedirect('%s#parameter_%s' % (url, param.code))

    score_interim = Score.objects.filter(parameter=param, task=task, revision=Score.INTERIM)
    score_table = [{
        'label': score._meta.get_field_by_name(criterion)[0].verbose_name,
        'score': getattr(score, criterion),
        'score_interim': getattr(score_interim[0], criterion) if score_interim else '',
        'criterion': criterion,
        'max_score': getattr(score, criterion) == score._meta.get_field(criterion).choices[-1][-1]
    } for criterion in criteria]

    score_delta = score.openness - score_interim[0].openness if score_interim else 0
    if request.user.is_expert:
        show_interim_score = True
    elif request.user.is_anonymous():
        show_interim_score = False
    else:
        show_interim_score = request.user.profile.show_interim_score

    all_max = True  # Flag if all criteria set to max
    for crit in criteria:
        if getattr(score, crit) != score._meta.get_field(crit).choices[-1][-1]:
            all_max = False

    criteria = [form[crit] for crit in criteria]
    for boundfield in criteria:
        # Add attribute with initial value to each criterion boundfield
        boundfield.initial = form.initial.get(boundfield.name, boundfield.field.initial)

    if request.user.is_expertA:
        claim_list = score.claim_set.all()
    elif request.user.is_expertB:
        claim_list = score.claim_set.filter(addressee=request.user)
    else:
        claim_list = []

    context = {
        'form': form,
        'score': annotate_exmo_perms(score, request.user),
        'score_interim': annotate_exmo_perms(score_interim[0] if score_interim else None, request.user),
        'param': annotate_exmo_perms(param, request.user),
        'task': annotate_exmo_perms(task, request.user),
        'org': org,
        'score_table': score_table,
        'score_delta': score_delta,
        'show_interim_score': show_interim_score,
        'masked_expert_name': _(config_value('GlobalParameters', 'EXPERT')),
        'criteria': criteria,
        'interaction': org.monitoring.is_interact or org.monitoring.is_finishing,
        'claim_list': claim_list,
        'recommendations_required': param.monitoring.no_interact is False and not all_max,
        'comment_form': score.comment_form(request.POST if request.method == 'POST' else None),
        'invcodeform': SettingsInvCodeForm(),
    }

    return TemplateResponse(request, 'scores/score.html', context)
Exemple #5
0
def score_view(request, **kwargs):
    if request.method not in ['POST', 'GET']:
        return HttpResponseNotAllowed(permitted_methods=['POST', 'GET'])

    if 'score_pk' in kwargs:
        # Score edit or view
        score = get_object_or_404(Score, pk=kwargs['score_pk'])
        task = score.task
        param = score.parameter
        if request.method == 'POST' and not request.user.has_perm(
                'exmo2010.edit_score', score):
            raise PermissionDenied
        if request.method == 'GET' and not request.user.has_perm(
                'exmo2010.view_score', score):
            raise PermissionDenied
    else:
        # Score creation by task and param
        task = get_object_or_404(Task, pk=kwargs['task_pk'])
        param = get_object_or_404(Parameter, pk=kwargs['parameter_pk'])
        if not request.user.has_perm('exmo2010.fill_task', task):
            raise PermissionDenied

        # Check if score already exist.
        try:
            score = Score.objects.get(parameter=param,
                                      task=task,
                                      revision=Score.FINAL)
        except Score.DoesNotExist:
            # OK, score does not exist and can be created.
            score = Score(parameter=param, task=task, revision=Score.FINAL)
        else:
            # User requested score creation by task and param, but score already exist.
            if request.user.has_perm('exmo2010.view_score', score):
                # Redirect user to GET score page, even if current request method is POST.
                # This way duplicate POST to create score will be ignored.
                return HttpResponseRedirect(
                    reverse('exmo2010:score', args=[score.pk]))
            else:
                raise PermissionDenied

    org = task.organization
    param.relevant = bool(task.organization not in param.exclude.all())

    if not param.relevant and not request.user.is_expert:
        raise PermissionDenied

    # Relevant criteria names
    criteria = ['found'] + filter(param.__getattribute__,
                                  Parameter.OPTIONAL_CRITERIA)

    ScoreForm = modelform_factory(
        Score,
        fields=criteria + ['recommendations', 'links', 'editor'],
        widgets=dict((crit, RadioSelect) for crit in criteria))

    ScoreForm.base_fields['comment'] = RichTextFormField(
        config_name='advanced', required=False)

    # Replace '-----' with '-' in empty radio choices.
    for f in criteria:
        ScoreForm.base_fields[f].widget.choices[0] = ('', '–')

    form = ScoreForm(request.POST if request.method == 'POST' else None,
                     instance=score)

    if request.method == 'POST' and form.is_valid():
        if score.pk and not request.user.has_perm('exmo2010.edit_score',
                                                  score):
            raise PermissionDenied

        with transaction.commit_on_success():
            if org.monitoring.status in Monitoring.after_interaction_status and 'score_pk' in kwargs:
                if not Score.objects.filter(parameter=param,
                                            task=task,
                                            revision=Score.INTERIM).exists():
                    # Interim revision does not exist and should be created. It will have new pk.
                    interim_score = Score.objects.get(pk=kwargs['score_pk'])
                    last_modified = interim_score.last_modified
                    interim_score.pk = None
                    interim_score.revision = Score.INTERIM
                    interim_score.save()
                    # Restore last_modified field, that was overwritten by save()
                    Score.objects.filter(pk=interim_score.pk).update(
                        last_modified=last_modified)

                _add_comment(request, score)
            score = form.save(commit=False)
            score.editor = request.user
            score.save()
        if org.monitoring.is_interact or org.monitoring.is_finishing:
            return HttpResponseRedirect(
                reverse('exmo2010:score', args=[score.pk]))
        else:
            url = reverse('exmo2010:task_scores', args=[task.pk])
            return HttpResponseRedirect('%s#parameter_%s' % (url, param.code))

    score_interim = Score.objects.filter(parameter=param,
                                         task=task,
                                         revision=Score.INTERIM)
    score_table = [{
        'label':
        score._meta.get_field_by_name(criterion)[0].verbose_name,
        'score':
        getattr(score, criterion),
        'score_interim':
        getattr(score_interim[0], criterion) if score_interim else '',
        'criterion':
        criterion,
        'max_score':
        getattr(score,
                criterion) == score._meta.get_field(criterion).choices[-1][-1]
    } for criterion in criteria]

    score_delta = score.openness - score_interim[
        0].openness if score_interim else 0
    if request.user.is_expert:
        show_interim_score = True
    elif request.user.is_anonymous():
        show_interim_score = False
    else:
        show_interim_score = request.user.profile.show_interim_score

    all_max = True  # Flag if all criteria set to max
    for crit in criteria:
        if getattr(score, crit) != score._meta.get_field(crit).choices[-1][-1]:
            all_max = False

    criteria = [form[crit] for crit in criteria]
    for boundfield in criteria:
        # Add attribute with initial value to each criterion boundfield
        boundfield.initial = form.initial.get(boundfield.name,
                                              boundfield.field.initial)

    if request.user.is_expertA:
        claim_list = score.claim_set.all()
    elif request.user.is_expertB:
        claim_list = score.claim_set.filter(addressee=request.user)
    else:
        claim_list = []

    context = {
        'form':
        form,
        'score':
        annotate_exmo_perms(score, request.user),
        'score_interim':
        annotate_exmo_perms(score_interim[0] if score_interim else None,
                            request.user),
        'param':
        annotate_exmo_perms(param, request.user),
        'task':
        annotate_exmo_perms(task, request.user),
        'org':
        org,
        'score_table':
        score_table,
        'score_delta':
        score_delta,
        'show_interim_score':
        show_interim_score,
        'masked_expert_name':
        _(config_value('GlobalParameters', 'EXPERT')),
        'criteria':
        criteria,
        'interaction':
        org.monitoring.is_interact or org.monitoring.is_finishing,
        'claim_list':
        claim_list,
        'recommendations_required':
        param.monitoring.no_interact is False and not all_max,
        'comment_form':
        score.comment_form(request.POST if request.method == 'POST' else None),
        'invcodeform':
        SettingsInvCodeForm(),
    }

    return TemplateResponse(request, 'scores/score.html', context)