Example #1
0
    def test_should_throw_unsupported_xform_edit_exception(self):
        new_questionnaire = Project.new_from_doc(DatabaseManagerStub(), ProjectDocument())
        old_questionnaire = Project.new_from_doc(DatabaseManagerStub(), ProjectDocument())
        validator = Mock(Validator)
        validator.valid.return_value = False

        self.assertRaises(UnsupportedXformEditException,
                          XFormEditor(Mock(Submission), validator, Mock(Questionnaire)).edit,
                          new_questionnaire, old_questionnaire, {})
Example #2
0
    def test_should_save_questionnaire_and_update_submission_when_valid_change(self):
        new_questionnaire = Project.new_from_doc(DatabaseManagerStub(), ProjectDocument())
        old_questionnaire = Project.new_from_doc(DatabaseManagerStub(), ProjectDocument())
        submission = Mock(Submission)
        validator = Mock(Validator)
        questionnaire = Mock(Questionnaire)
        validator.valid.return_value = True

        XFormEditor(submission, validator, questionnaire).edit(new_questionnaire, old_questionnaire, {})
        questionnaire.save.assert_called_once_with(new_questionnaire)
        submission.update_all.assert_called_once_with(new_questionnaire.id)
Example #3
0
    def test_should_validate_xform_change(self):
        rule1 = Mock(Rule)
        rule2 = Mock(Rule)

        new_questionnaire = Project.new_from_doc(DatabaseManagerStub(), ProjectDocument())
        old_questionnaire = Project.new_from_doc(DatabaseManagerStub(), ProjectDocument())
        old_questionnaire.xform_model = Mock(Xform)
        new_questionnaire.xform_model = Mock(Xform)

        old_questionnaire.xform_model.equals.return_value = True
        activity_log_detail = {}
        self.assertTrue(Validator([rule1, rule2]).valid(new_questionnaire, old_questionnaire, activity_log_detail))
        rule1.update_xform.assert_called_once_with(old_questionnaire, new_questionnaire, activity_log_detail)

        old_questionnaire.xform_model.equals.return_value = False
        self.assertFalse(Validator([rule1, rule2]).valid(new_questionnaire, old_questionnaire, activity_log_detail))
Example #4
0
    def _get_cascade_questionnaire(self, cascades):
        fields = []
        for cascade in cascades:
            fields.append(
                SelectField(cascade,
                            cascade,
                            "Please select",
                            cascades[cascade],
                            is_cascade=True))

        doc = ProjectDocument()
        doc.xform = self._build_xform(fields=fields,
                                      field_type="cascade",
                                      cascades=cascades)
        questionnaire = Project.new_from_doc(DatabaseManagerStub(), doc)
        questionnaire.name = "q1"
        questionnaire.form_code = "007"
        questionnaire.fields.append(
            FieldSet(code="group_outer",
                     name="group_outer",
                     label="Enter the outer group details",
                     field_set=[
                         FieldSet(code="repeat_outer",
                                  name="repeat_outer",
                                  label="Enter the details you wanna repeat",
                                  field_set=fields)
                     ]))
        return questionnaire
def update_submission_search_for_subject_edition(dbm, unique_id_type,
                                                 short_code, last_name):
    projects = []
    for row in dbm.load_all_rows_in_view('projects_by_subject_type',
                                         key=unique_id_type[0],
                                         include_docs=True):
        projects.append(
            Project.new_from_doc(dbm, ProjectDocument.wrap(row['doc'])))
    for project in projects:
        entity_field_code = None
        for field in project.entity_questions:
            if [field.unique_id_type] == unique_id_type:
                entity_field_code = field.code

        if entity_field_code:
            unique_id_field_name = es_questionnaire_field_name(
                entity_field_code, project.id)

            fields_mapping = {unique_id_field_name: last_name}
            args = {
                es_unique_id_code_field_name(unique_id_field_name): short_code
            }

            query = _get_submissions_for_unique_id_entry(args, dbm, project)

            for survey_response in query.values_dict('void'):
                SubmissionIndexUpdateHandler(
                    dbm.database_name,
                    project.id).update_field_in_submission_index(
                        survey_response._id, fields_mapping)
Example #6
0
def get_projects_by_unique_id_type(dbm, unique_id_type):
    projects = []
    for row in dbm.load_all_rows_in_view('projects_by_subject_type',
                                         key=unique_id_type[0],
                                         include_docs=True):
        projects.append(
            Project.new_from_doc(dbm, ProjectDocument.wrap(row['doc'])))
    return projects
Example #7
0
def get_projects_by_unique_id_type(dbm, unique_id_type):
    projects = []
    for row in dbm.load_all_rows_in_view('projects_by_subject_type',
                                         key=unique_id_type[0],
                                         include_docs=True):
        if row['doc']['is_registration_model']:
            questionnaire = EntityFormModel.new_from_doc(
                dbm, EntityFormModelDocument.wrap(row['doc']))
        else:
            questionnaire = Project.new_from_doc(
                dbm, ProjectDocument.wrap(row['doc']))
        projects.append(questionnaire)
    return projects
Example #8
0
def get_project_info(manager, project):
    project_id = project['_id']
    questionnaire = Project.new_from_doc(manager,
                                         ProjectDocument.wrap(project))
    questionnaire_code = questionnaire.form_code

    analysis, disabled, log = get_project_analysis_and_log_link(
        project_id, questionnaire_code)

    web_submission_link = reverse("web_questionnaire", args=[project_id])

    web_submission_link_disabled = 'disable_link'
    if 'web' in project['devices']:
        web_submission_link_disabled = ""

    create_subjects_links = {}
    for entity_type in questionnaire.entity_type:
        create_subjects_links.update({
            entity_type:
            append_query_strings_to_url(reverse("subject_questionnaire",
                                                args=[project_id,
                                                      entity_type]),
                                        web_view=True)
        })
    if questionnaire.is_poll:
        project_link = reverse("submissions",
                               args=[project_id, questionnaire_code])
    else:
        project_link = reverse('project-overview', args=[project_id])

    project_info = dict(
        project_id=project_id,
        _id=project_id,
        name=project['name'],
        qid=questionnaire_code,
        created=project['created'],
        is_advanced_questionnaire=bool(project.get('xform')),
        link=project_link,
        log=log,
        analysis=analysis,
        disabled=disabled,
        web_submission_link=web_submission_link,
        web_submission_link_disabled=web_submission_link_disabled,
        create_subjects_link=create_subjects_links,
        entity_type=questionnaire.entity_type,
        encoded_name=urlquote(project['name']),
        import_template_file_name=slugify(project['name']),
        is_poll=bool(questionnaire.is_poll),
        is_project_manager=project.get('is_project_manager', False))
    return project_info
Example #9
0
def deactivate_poll_questionnaire():
    now = datetime.now()
    try:
        logger.info("Deactivating polls for date :- %s" % now)
        paid_organizations = _get_active_paid_organizations()
        for org in paid_organizations:
            dbm = get_database_manager_for_org(org)
            projects = dbm.load_all_rows_in_view("all_projects")
            for project_row in projects:
                project_doc = ProjectDocument.wrap(project_row.get('value'))
                project = Project.new_from_doc(dbm, project_doc)
                if project.end_date:
                    if project.end_date.date() <= now.date():
                        project.active = "deactivated"
                        project.save()
    except Exception:
        logger.exception("Exception while deactivating poll for this project")
Example #10
0
    def _get_questionnaire(self,
                           group_label="Enter the outer group details",
                           group_name="group_outer",
                           field_label="Name please",
                           field_name="text2",
                           hint=None,
                           constraint_message=None,
                           appearance=None,
                           default=None,
                           required=False,
                           xform_constraint=None,
                           relevant=None,
                           field_choices=None):
        field = SelectField(field_name, field_name, field_label, field_choices) if field_choices is not None \
            else Field(code=field_name, name=field_name, label=field_label, parent_field_code=group_name, hint=hint,
                      constraint_message=constraint_message, appearance=appearance, default=default, required=required,
                      xform_constraint=xform_constraint, relevant=relevant)
        repeat = FieldSet(code="repeat_outer",
                          name="repeat_outer",
                          label="Enter the details you wanna repeat",
                          field_set=[field])

        xform = self._build_xform(group_label=group_label,
                                  fields=[field],
                                  field_type=field.type)
        if field.relevant:
            xform = _replace_node_name_with_xpath(field.relevant, xform)
        elif field.xform_constraint:
            xform = _replace_node_name_with_xpath(field.xform_constraint,
                                                  xform)

        doc = ProjectDocument()
        doc.xform = xform
        questionnaire = Project.new_from_doc(DatabaseManagerStub(), doc)
        questionnaire.name = "q1"
        questionnaire.form_code = "007"
        questionnaire.fields.append(
            FieldSet(code=group_name,
                     name=group_name,
                     label=group_label,
                     field_set=[repeat]))
        return questionnaire
Example #11
0
 def _get_questionnaire_with_field_removed(
         self,
         group_label="Enter the outer group details",
         group_name="group_outer",
         field_type=None):
     repeat = FieldSet(code="repeat_outer",
                       name="repeat_outer",
                       label="Enter the details you wanna repeat",
                       field_set=[])
     doc = ProjectDocument()
     doc.xform = self._build_xform(group_label=group_label,
                                   field_type=field_type)
     questionnaire = Project.new_from_doc(DatabaseManagerStub(), doc)
     questionnaire.name = "q1"
     questionnaire.form_code = "007"
     questionnaire.fields.append(
         FieldSet(code=group_name,
                  name=group_name,
                  label=group_label,
                  field_set=[repeat]))
     return questionnaire
Example #12
0
def create_submission_index(dbm, row):
    form_model = Project.new_from_doc(dbm, ProjectDocument.wrap(row["value"]))
    form_code = form_model.form_code
    start_key = [form_code]
    end_key = [form_code, {}]
    rows = dbm.database.iterview("surveyresponse/surveyresponse",
                                 1000,
                                 reduce=False,
                                 include_docs=False,
                                 startkey=start_key,
                                 endkey=end_key)
    es = get_elasticsearch_handle(timeout=600)

    survey_response_docs = []
    for row in rows:
        survey_response = SurveyResponseDocument._wrap_row(row)
        search_dict = _meta_fields(survey_response, dbm)
        _update_with_form_model_fields(dbm, survey_response, search_dict,
                                       form_model)
        search_dict.update({'id': survey_response.id})
        survey_response_docs.append(search_dict)

    if survey_response_docs:
        es.bulk_index(dbm.database_name, form_model.id, survey_response_docs)
Example #13
0
def _edit_questionnaire(request,
                        project_id,
                        excel_file=None,
                        excel_as_dict=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    try:
        xls_parser_response = _try_parse_xls(manager, request,
                                             questionnaire.name, excel_file)

        if isinstance(xls_parser_response, HttpResponse):
            return xls_parser_response

        doc = deepcopy(questionnaire._doc)
        doc.xform = MangroveService(
            request,
            questionnaire_code=questionnaire.form_code,
            xls_parser_response=xls_parser_response).xform_with_form_code
        new_questionnaire = Project.new_from_doc(manager, doc)
        QuestionnaireBuilder(new_questionnaire,
                             manager).update_questionnaire_with_questions(
                                 xls_parser_response.json_xform_data)
        xform_rules = get_all_rules()
        if excel_file is None:
            excel_file = _temp_file(request)
        else:
            excel_file.seek(0)
        questionnaire_wrapper = Questionnaire(excel_file)
        activity_log_detail = {}
        XFormEditor(
            Submission(manager, get_database_name(request.user), xform_rules),
            Validator(xform_rules),
            questionnaire_wrapper).edit(new_questionnaire, questionnaire,
                                        activity_log_detail)
        questionnaire = Project.get(manager, project_id)
        _save_questionnaire_as_dict_for_builder(questionnaire, excel_as_dict,
                                                excel_file)
        UserActivityLog().log(request,
                              action=EDITED_QUESTIONNAIRE,
                              project=questionnaire.name,
                              detail=json.dumps(activity_log_detail))

    except UnsupportedXformEditException as e:
        return HttpResponse(
            content_type='application/json',
            content=json.dumps({
                'success': False,
                'unsupported': True,
                'error_msg': [_("Unsupported edit operation")],
                "status": "error",
                'reason':
                "Unsupported edit operation",  # TODO: i18n translation
                'details': e.message
            }))
    except QuestionAlreadyExistsException as e:
        return HttpResponse(
            content_type='application/json',
            content=json.dumps({
                'success': False,
                'error_msg': [_(e.message)],
                "status": "error",
                'reason': "Save Failed",  # TODO: i18n translation
                'details': _(e.message)
            }))
    return HttpResponse(
        json.dumps({
            "success": True,
            "status": "success",
            'reason': 'Successfully updated'  # TODO: i18n translation
        }),
        content_type='application/json')
Example #14
0
def update_datasender_for_project_change(project_doc, dbm, old_project=None):
    if not old_project or project_doc.name != old_project.name or project_doc.void != old_project.void:
        project = Project.new_from_doc(dbm, project_doc)
        for entity_doc in project.get_associated_datasenders(dbm):
            update_datasender_index(entity_doc, dbm)