Beispiel #1
0
def create_profile(request):
    manager = get_database_manager(request)
    entity_list = get_all_entity_types(manager)
    entity_list = helper.remove_reporter(entity_list)
    project_summary = dict(name='New Project')
    if request.method == 'GET':
        form = ProjectProfile(entity_list=entity_list,initial={'activity_report':'yes'})
        return render_to_response('project/profile.html', {'form': form, 'project': project_summary, 'edit':False},
                                  context_instance=RequestContext(request))

    form = ProjectProfile(data=request.POST, entity_list=entity_list)
    if form.is_valid():
        entity_type=form.cleaned_data['entity_type']
        project = Project(name=form.cleaned_data["name"], goals=form.cleaned_data["goals"],
                          project_type=form.cleaned_data['project_type'], entity_type=entity_type,
                          devices=form.cleaned_data['devices'], activity_report=form.cleaned_data['activity_report'], sender_group=form.cleaned_data['sender_group'])
        form_model = helper.create_questionnaire(post=form.cleaned_data, dbm=manager)
        try:
            pid = project.save(manager)
            qid = form_model.save()
            project.qid = qid
            pid = project.save(manager)
        except DataObjectAlreadyExists as e:
            messages.error(request, e.message)
            return render_to_response('project/profile.html', {'form': form, 'project': project_summary, 'edit':False},
                                      context_instance=RequestContext(request))
        return HttpResponseRedirect(reverse(subjects_wizard, args=[pid]))
    else:
        return render_to_response('project/profile.html', {'form': form, 'project': project_summary, 'edit':False},
                                  context_instance=RequestContext(request))
Beispiel #2
0
    def test_should_return_data_senders_without_submissions(self):
        reminder_and_deadline_for_month = {
            "reminders_enabled": "True",
            "deadline_month": "5",
            "deadline_type": "current",
            "frequency_enabled": "True",
            "has_deadline": "True",
            "frequency_period": "month"
        }
        project = Project()
        project.reminder_and_deadline = reminder_and_deadline_for_month
        project.data_senders = ["rep1", "rep2", "rep3", "rep4", "rep5"]
        dbm = Mock(spec=DatabaseManager)

        with patch(
            "datawinners.project.models.get_reporters_who_submitted_data_for_frequency_period") as get_reporters_who_submitted_data_for_frequency_period_mock:
            with patch("datawinners.project.models.load_all_subjects_of_type") as load_all_subjects_of_type_mock:
                load_all_subjects_of_type_mock.return_value = (
                [{"cols": ["rep%s" % i, i], "short_code": "rep%s" % i}  for i in
                                                                        range(
                                                                            10)], ["short_code", "mobile_number"],
                ["What is DS Unique ID", "What is DS phone number"])
                get_reporters_who_submitted_data_for_frequency_period_mock.return_value = [
                    self._create_reporter_entity("rep1"), self._create_reporter_entity("rep3")]

                data_senders = project.get_data_senders_without_submissions_for(date(2011, 11, 5), dbm)

        self.assertEqual(3, len(data_senders))
        self.assertIn("rep2", [ds["short_code"]  for ds in data_senders])
        self.assertIn("rep4", [ds["short_code"]  for ds in data_senders])
        self.assertIn("rep5", [ds["short_code"]  for ds in data_senders])
Beispiel #3
0
 def setUpClass(cls):
     FormModelDocument.registered_functions = []
     cls.db_name = uniq('mangrove-test')
     cls.manager = get_db_manager('http://localhost:5984/', cls.db_name)
     initializer._create_views(cls.manager)
     create_views(cls.manager)
     question1 = UniqueIdField(unique_id_type='clinic',
                               name="entity_question",
                               code="ID",
                               label="What is associated entity")
     question2 = TextField(name="question1_Name",
                           code="Q1",
                           label="What is your name",
                           defaultValue="some default value",
                           constraints=[TextLengthConstraint(5, 10)])
     cls.project1 = Project(dbm=cls.manager,
                            name=project1_name,
                            goals="Testing",
                            devices=['web'],
                            form_code="abc",
                            fields=[question1, question2])
     cls.project1_id = cls.project1.save()
     cls.project2 = Project(dbm=cls.manager,
                            name=project2_name,
                            goals="Testing",
                            devices=['web'],
                            form_code="def",
                            fields=[question1, question2])
     cls.project2_id = cls.project2.save()
Beispiel #4
0
 def test_project_name_should_be_case_insensitively_unique(self):
     project = Project(name="tEsT2",
                       goals="Testing",
                       project_type="Survey",
                       entity_type="Clinic",
                       devices=['web'])
     with self.assertRaises(DataObjectAlreadyExists):
         project.save(self.dbm)
Beispiel #5
0
    def setUp(self):
        self.dbm = get_db_manager(database='mangrove-test')
        create_views(self.dbm)
        self.project1 = Project(name="Test1", goals="Testing", project_type="Survey", entity_type="Clinic",
                                devices=['web'])
        self.project1_id = self.project1.save(self.dbm)
        self.project2 = Project(name="Test2", goals="Testing", project_type="Survey", entity_type="Clinic",
                                devices=['web'])
        self.project2_id = self.project2.save(self.dbm)

        self._create_form_model_for_project(self.project1)
Beispiel #6
0
    def test_should_update_project(self):
        self.project1 = Project.get(self.manager, self.project1_id)
        self.project1.update(
            dict(name=project1_name, devices=['web', 'sms'],
                 goals="New goals"))
        project1_id = self.project1.save()

        project = Project.get(self.manager, project1_id)
        self.assertEquals(project.name, project1_name)
        self.assertEquals(project.goals, 'New goals')
        self.assertEquals(project.devices, ['web', 'sms'])
Beispiel #7
0
    def setUp(self):
        MangroveTestCase.setUp(self)
        create_views(self.manager)
        self.project1 = Project(name="Test1", goals="Testing", project_type="Survey", entity_type="Clinic",
            devices=['web'])
        self.project1_id = self.project1.save(self.manager)
        self.project2 = Project(name="Test2", goals="Testing", project_type="Survey", entity_type="Clinic",
            devices=['web'])
        self.project2_id = self.project2.save(self.manager)

        self._create_form_model_for_project(self.project1)
Beispiel #8
0
def register_postsave_handlers():
    global _postsave_registered
    if _postsave_registered: return
    EntityDocument.register_post_update(entity_search_update)

    FormModelDocument.register_post_update(form_model_change_handler)
    Project.register_post_update(update_datasender_for_project_change)

    SurveyResponseDocument.register_post_update(update_submission_search_index)
    EntityDocument.register_post_update(submission_update_on_entity_edition)
    _postsave_registered = True
Beispiel #9
0
 def test_project_name_should_be_case_insensitively_unique(self):
     questionnaire = Project(self.manager,
                             name=project2_name.upper(),
                             goals="Testing",
                             devices=['web'])
     with self.assertRaises(Exception) as cm:
         questionnaire.save()
     the_exception = cm.exception
     self.assertEqual(
         the_exception.message,
         "Questionnaire with Name = '%s' already exists." %
         project2_name.upper())
Beispiel #10
0
 def test_get_deadline_day(self):
     reminder_and_deadline_for_month = {
         "reminders_enabled": "True",
         "deadline_month": "5",
         "deadline_type": "current",
         "frequency_enabled": "True",
         "has_deadline": "True",
         "frequency_period": "month"
     }
     project_reminders = Project(self.manager, name="ReminderProject")
     project_reminders.reminder_and_deadline = reminder_and_deadline_for_month
     self.assertEquals(5, project_reminders.get_deadline_day())
Beispiel #11
0
 def test_project_name_should_be_unique(self):
     questionnaire = Project(dbm=self.manager,
                             name=project2_name,
                             goals="Testing",
                             devices=['web'],
                             form_code="name_form",
                             fields=[])
     with self.assertRaises(Exception) as cm:
         questionnaire.save()
     the_exception = cm.exception
     self.assertEqual(
         the_exception.message,
         "Questionnaire with Name = '%s' already exists." % project2_name)
Beispiel #12
0
 def test_should_delete_datasender_from_project(self):
     self.project1 = Project.get(self.manager, self.project1_id)
     self.project1.data_senders = ['rep1', 'rep2']
     datasender_to_be_deleted = 'rep1'
     with patch(
             "datawinners.search.datasender_index.update_datasender_index_by_id"
     ) as update_datasender_index_by_id:
         update_datasender_index_by_id.return_value = None
         self.project1.delete_datasender(self.manager,
                                         datasender_to_be_deleted)
         self.project1 = Project.get(self.manager, self.project1_id)
         expected_data_senders = ['rep2']
         self.assertEqual(self.project1.data_senders, expected_data_senders)
Beispiel #13
0
    def test_should_deactivate_form_on_project_deactivate(self):
        project = Project(state=ProjectState.ACTIVE)
        dbm = Mock(spec=DatabaseManager)
        form_model_mock = Mock(spec=FormModel)
        dbm.get.return_value = form_model_mock

        with patch("datawinners.project.models.Project.save") as project_save_mock:
            project.deactivate(dbm)

            form_model_mock.deactivate.assert_called_once_with()
            form_model_mock.save.assert_called_once_with()
            project_save_mock.assert_called_once_with(dbm)

        self.assertEqual(ProjectState.INACTIVE, project.state)
Beispiel #14
0
    def test_should_deactivate_form_on_project_deactivate(self):
        project = Project(state=ProjectState.ACTIVE)
        dbm = Mock(spec=DatabaseManager)
        form_model_mock = Mock(spec=FormModel)
        dbm.get.return_value = form_model_mock

        with patch("datawinners.project.models.Project.save") as project_save_mock:
            project.deactivate(dbm)

            form_model_mock.deactivate.assert_called_once_with()
            form_model_mock.save.assert_called_once_with()
            project_save_mock.assert_called_once_with(dbm)

        self.assertEqual( ProjectState.INACTIVE, project.state)
Beispiel #15
0
def create_profile(request):
    manager = get_database_manager(request)
    entity_list = get_all_entity_types(manager)
    entity_list = helper.remove_reporter(entity_list)
    project_summary = dict(name='New Project')
    if request.method == 'GET':
        form = ProjectProfile(entity_list=entity_list,
                              initial={'activity_report': 'yes'})
        return render_to_response('project/profile.html', {
            'form': form,
            'project': project_summary,
            'edit': False
        },
                                  context_instance=RequestContext(request))

    form = ProjectProfile(data=request.POST, entity_list=entity_list)
    if form.is_valid():
        entity_type = form.cleaned_data['entity_type']
        project = Project(name=form.cleaned_data["name"],
                          goals=form.cleaned_data["goals"],
                          project_type=form.cleaned_data['project_type'],
                          entity_type=entity_type,
                          devices=form.cleaned_data['devices'],
                          activity_report=form.cleaned_data['activity_report'],
                          sender_group=form.cleaned_data['sender_group'])
        form_model = helper.create_questionnaire(post=form.cleaned_data,
                                                 dbm=manager)
        try:
            pid = project.save(manager)
            qid = form_model.save()
            project.qid = qid
            pid = project.save(manager)
        except DataObjectAlreadyExists as e:
            messages.error(request, e.message)
            return render_to_response('project/profile.html', {
                'form': form,
                'project': project_summary,
                'edit': False
            },
                                      context_instance=RequestContext(request))
        return HttpResponseRedirect(reverse(subjects_wizard, args=[pid]))
    else:
        return render_to_response('project/profile.html', {
            'form': form,
            'project': project_summary,
            'edit': False
        },
                                  context_instance=RequestContext(request))
Beispiel #16
0
def get_submission_breakup(request, project_id):
    dbm = get_database_manager(request.user)
    project = Project.load(dbm.database, project_id)
    form_model = FormModel.get(dbm, project.qid)
    submission_success, submission_errors = submission_stats(dbm, form_model.form_code)
    response = json.dumps([submission_success, submission_errors])
    return HttpResponse(response)
Beispiel #17
0
 def test_should_delete_datasender_from_project(self):
     self.project1.data_senders = ['rep1', 'rep2']
     datasender_to_be_deleted = 'rep1'
     self.project1.delete_datasender(self.manager, datasender_to_be_deleted)
     self.project1 = Project.load(self.manager.database, self.project1_id)
     expected_datasenders = ['rep2']
     self.assertEqual(self.project1.data_senders, expected_datasenders)
    def post(self, request, form_code):
        manager = get_database_manager(request.user)
        feeds_dbm = get_feeds_database(request.user)
        project_id = request.GET["project_id"]
        project = Project.load(manager.database, project_id)
        form_model = get_form_model_by_code(manager, form_code)
        user_profile = NGOUserProfile.objects.get(user=request.user)
        organization = Organization.objects.get(org_id=user_profile.org_id)
        submission_importer = SubmissionImporter(
            manager, feeds_dbm, request.user, form_model, project,
            SubmissionQuotaService(organization))
        response = submission_importer.import_submission(request)

        return HttpResponse(
            json.dumps({
                "success":
                self._successful(response),
                "question_map":
                self._get_question_code_map(form_model, request),
                "success_submissions":
                response.saved_entries,
                "errored_submission_details":
                response.errored_entrie_details,
                "message":
                response.message,
                "total_submissions":
                response.total_submissions,
                "quota_over":
                self._is_submission_quota_over(response)
            }))
Beispiel #19
0
def save_questionnaire(request):
    manager = get_database_manager(request.user)
    if request.method == 'POST':
        questionnaire_code = request.POST['questionnaire-code']
        json_string = request.POST['question-set']
        question_set = json.loads(json_string)
        pid = request.POST['pid']
        project = Project.load(manager.database, pid)
        form_model = FormModel.get(manager, project.qid)
        old_fields = form_model.fields
        try:
            QuestionnaireBuilder(form_model, manager).update_questionnaire_with_questions(question_set)
        except QuestionCodeAlreadyExistsException as e:
            return HttpResponseServerError(e)
        except QuestionAlreadyExistsException as e:
            return HttpResponseServerError(e)
        except EntityQuestionAlreadyExistsException as e:
            return HttpResponseServerError(e.message)
        else:
            try:
                form_model.form_code = questionnaire_code.lower()
            except DataObjectAlreadyExists as e:
                if e.message.find("Form") >= 0:
                    return HttpResponseServerError("Questionnaire with this code already exists")
                return HttpResponseServerError(e.message)
            form_model.name = project.name
            form_model.entity_id = project.entity_type
            detail = utils.get_changed_questions(old_fields, form_model.fields, subject=False)
            form_model.save()
            UserActivityLog().log(request, project=project.name, action=EDITED_PROJECT, detail=json.dumps(detail))
            return HttpResponse(json.dumps({"response": "ok"}))
Beispiel #20
0
def edit_my_subject_questionnaire(request, project_id, entity_type=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    if not entity_type:
        entity_type = questionnaire.entity_type[0]
    project_links = get_project_link(questionnaire, entity_type)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    reg_form = _get_subject_form_model(manager, entity_type)
    if reg_form is None:
        reg_form = form_model.get_form_model_by_code(manager,
                                                     REGISTRATION_FORM_CODE)
    fields = reg_form.fields
    existing_questions = json.dumps(fields, default=field_to_json)
    subject = get_entity_type_info(entity_type, manager=manager)
    return render_to_response('project/subject_questionnaire.html', {
        'project': questionnaire,
        'entity_type': entity_type,
        'project_links': project_links,
        'is_quota_reached': is_quota_reached(request),
        'existing_questions': repr(existing_questions),
        'questionnaire_code': reg_form.form_code,
        'language': reg_form.activeLanguages[0],
        'project_id': questionnaire.id,
        'subject': subject,
        'post_url': reverse(subject_save_questionnaire)
    },
                              context_instance=RequestContext(request))
Beispiel #21
0
def subject_registration_form_preview(request,
                                      project_id=None,
                                      entity_type=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    if not entity_type:
        entity_type = questionnaire.entity_type[0]
    if request.method == "GET":
        fields, project_links, questions, registration_questionnaire = _get_registration_form(
            manager, questionnaire, entity_type)
        example_sms = get_example_sms_message(
            fields, registration_questionnaire.form_code)
        return render_to_response(
            'project/questionnaire_preview_list.html', {
                "questions": questions,
                'questionnaire_code': registration_questionnaire.form_code,
                'project': questionnaire,
                'project_links': project_links,
                'is_quota_reached': is_quota_reached(request),
                'example_sms': example_sms,
                'org_number': get_organization_telephone_number(request)
            },
            context_instance=RequestContext(request))
Beispiel #22
0
def questionnaire_preview(request, project_id=None, sms_preview=False):
    manager = get_database_manager(request.user)
    if request.method == 'GET':
        dashboard_page = settings.HOME_PAGE + "?deleted=true"
        questionnaire = Project.get(manager, project_id)
        if questionnaire.is_void():
            return HttpResponseRedirect(dashboard_page)
            #if form_model.is_entity_type_reporter():
        #    fields = helper.hide_entity_question(form_model.fields)
        project_links = make_project_links(questionnaire)
        questions = []
        fields = questionnaire.fields
        for field in fields:
            question = helper.get_preview_for_field(field)
            questions.append(question)
        example_sms = "%s" % (questionnaire.form_code)
        example_sms += get_example_sms(fields)

    template = 'project/questionnaire_preview.html' if sms_preview else 'project/questionnaire_preview_list.html'
    return render_to_response(
        template, {
            "questions": questions,
            'questionnaire_code': questionnaire.form_code,
            'project': questionnaire,
            'project_links': project_links,
            'is_quota_reached': is_quota_reached(request),
            'example_sms': example_sms,
            'org_number': get_organization_telephone_number(request)
        },
        context_instance=RequestContext(request))
Beispiel #23
0
def questionnaire(request, project_id):
    manager = get_database_manager(request.user)
    if request.method == 'GET':
        questionnaire = Project.get(manager, project_id)
        if questionnaire.is_void():
            return HttpResponseRedirect(settings.HOME_PAGE + "?deleted=true")
        fields = questionnaire.fields
        existing_questions = json.dumps(fields, default=field_to_json)
        project_links = make_project_links(questionnaire)
        success, error = submission_stats(manager, questionnaire.form_code)
        project_has_submissions = (success + error > 0)
        in_trial_mode = _in_trial_mode(request)
        is_success = False
        active_language = request.LANGUAGE_CODE
        if "success" in [m.message for m in messages.get_messages(request)]:
            is_success = True
        return render_to_response(
            'project/questionnaire.html', {
                "existing_questions": repr(existing_questions),
                'questionnaire_code': questionnaire.form_code,
                'project': questionnaire,
                'project_has_submissions': project_has_submissions,
                'project_links': project_links,
                'is_quota_reached': is_quota_reached(request),
                'in_trial_mode': in_trial_mode,
                'is_success': is_success,
                'active_language': active_language,
                'post_url': reverse(edit_project, args=[project_id]),
                'unique_id_types': get_unique_id_types(manager),
                'preview_links': get_preview_and_instruction_links()
            },
            context_instance=RequestContext(request))
Beispiel #24
0
def registered_subjects(request, project_id, entity_type=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    current_entity_type = entity_type
    if not current_entity_type:
        current_entity_type = questionnaire.entity_type[0]

    subject = get_entity_type_info(current_entity_type, manager=manager)
    project_links = get_project_link(questionnaire, current_entity_type)
    subject_form_model = get_form_model_by_entity_type(manager,
                                                       [current_entity_type])
    in_trial_mode = _in_trial_mode(request)
    return render_to_response(
        'project/subjects/registered_subjects_list.html', {
            'project': questionnaire,
            'project_links': project_links,
            'is_quota_reached': is_quota_reached(request),
            "subject": subject,
            'in_trial_mode': in_trial_mode,
            'project_id': project_id,
            'entity_type': current_entity_type,
            'subject_headers': header_fields(subject_form_model),
            'questionnaire_code': questionnaire.form_code,
            'form_code': subject_form_model.form_code
        },
        context_instance=RequestContext(request))
Beispiel #25
0
def sent_reminders(request, project_id):
    dbm = get_database_manager(request.user)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    questionnaire = Project.get(dbm, project_id)
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    organization = Organization.objects.get(
        org_id=request.user.get_profile().org_id)
    is_trial_account = organization.in_trial_mode
    html = 'project/sent_reminders_trial.html' if organization.in_trial_mode else 'project/sent_reminders.html'
    return render_to_response(html, {
        'project':
        questionnaire,
        "project_links":
        make_project_links(questionnaire),
        'is_quota_reached':
        is_quota_reached(request, organization=organization),
        'reminders':
        get_all_reminder_logs_for_project(project_id, dbm),
        'in_trial_mode':
        is_trial_account,
        'questionnaire_code':
        questionnaire.form_code
    },
                              context_instance=RequestContext(request))
Beispiel #26
0
def project_info(request, manager, form_model, project_id,
                 questionnaire_code):  #revisit:export
    project = Project.load(manager.database, project_id)
    is_summary_report = form_model.is_entity_type_reporter()
    rp_field = form_model.event_time_question
    organization = get_organization(request)
    in_trial_mode = organization.in_trial_mode
    has_rp = rp_field is not None
    is_monthly_reporting = rp_field.date_format.find(
        'dd') < 0 if has_rp else False

    return {
        "date_format": rp_field.date_format if has_rp else "dd.mm.yyyy",
        "is_monthly_reporting": is_monthly_reporting,
        "entity_type": form_model.entity_type[0].capitalize(),
        'project_links': (make_project_links(project, questionnaire_code)),
        'is_quota_reached': is_quota_reached(request,
                                             organization=organization),
        'project': project,
        'encoded_project_name': (urlquote(project.name)),
        'import_template_file_name': slugify(project.name),
        'questionnaire_code': questionnaire_code,
        'in_trial_mode': in_trial_mode,
        'reporting_period_question_text': rp_field.label if has_rp else None,
        'has_reporting_period': has_rp,
        'is_summary_report': is_summary_report
    }
Beispiel #27
0
    def test_get_correct_web_submission_link(self):
        request = Mock()
        request.user = Mock(spec=User)
        manager = Mock(spec=DatabaseManager)
        manager.database = dict()
        raw_project = dict(
            value=dict(_id="pid",
                       devices=["sms", "web"],
                       activity_report=["no"],
                       name="Project Name",
                       created="2012-05-23T02:57:09.788294+00:00",
                       project_type="survey"))

        project = Project(project_type="survey",
                          entity_type="clinic",
                          state=ProjectState.ACTIVE)

        profile = Mock(spec=NGOUserProfile)

        questionnaire = Mock()
        questionnaire.form_code = "q01"

        with patch("datawinners.project.models.Project.load") as get_project:
            get_project.return_value = project
            with patch.object(DatabaseManager, "get") as db_manager:
                db_manager.return_value = questionnaire
                with patch("django.contrib.auth.models.User.get_profile"
                           ) as get_profile:
                    get_profile.return_value = profile
                    profile.reporter = False
                    project_info = get_project_info(manager, raw_project)
                    self.assertEqual(project_info["web_submission_link"],
                                     "/project/testquestionnaire/pid/")
Beispiel #28
0
def associate_user_with_existing_project(manager, reporter_id):
    rows = get_all_projects(manager)
    for row in rows:
        project_id = row['value']['_id']
        project = Project.load(manager.database, project_id)
        project.data_senders.append(reporter_id)
        project.save(manager, process_post_update=True)
Beispiel #29
0
def review_and_test(request, project_id=None):
    manager = get_database_manager(request.user)
    project = Project.load(manager.database, project_id)
    form_model = FormModel.get(manager, project.qid)
    if request.method == 'GET':
        number_of_registered_subjects = get_non_voided_entity_count_for_type(manager, project.entity_type)
        number_of_registered_data_senders = len(project.data_senders)
        fields = form_model.fields
        if form_model.is_entity_type_reporter():
            fields = helper.hide_entity_question(form_model.fields)
        is_reminder = "enabled" if len(Reminder.objects.filter(project_id=project.id)) != 0 else "disabled"

        project_devices = project.devices
        devices = ", ".join(project_devices).replace('sms', 'SMS').replace('web', 'Web').replace('smartPhone',
                                                                                                 'Smartphone')

        in_trial_mode = _in_trial_mode(request)
        return render_to_response('project/review_and_test.html', {'project': project, 'fields': fields,
                                                                   'project_links': make_project_links(project,
                                                                                                       form_model.form_code),
                                                                   'is_quota_reached': is_quota_reached(request),
                                                                   'number_of_datasenders': number_of_registered_data_senders
            ,
                                                                   'number_of_subjects': number_of_registered_subjects,
                                                                   "is_reminder": is_reminder,
                                                                   "in_trial_mode": in_trial_mode,
                                                                   "devices": devices},
                                  context_instance=RequestContext(request))
def remove_deleted_ds_from_project(db_name):
    logger = logging.getLogger(db_name)
    try:
        dbm = get_db_manager(db_name)
        logger.info("starting data fix for " + db_name)
        all_data_senders = set(get_all_active_data_senders(dbm))
        for project_doc in dbm.database.view("project_names/project_names",
                                             include_docs=True):
            try:
                project_data_senders = set(project_doc["doc"]["data_senders"])

                invalid_ds = project_data_senders.difference(all_data_senders)

                project_doc = Project._wrap_row(project_doc)
                for ds in invalid_ds:
                    logger.info("Found invalid data senders in project : " +
                                str(project_doc) + " " + str(invalid_ds))
                    project_doc.delete_datasender(dbm, ds)

            except Exception as e:
                print "Error : " + db_name + " : " + str(
                    project_doc) + e.message
                traceback.print_exc(file=sys.stdout)
        logger.info("done:" + db_name)
        mark_as_completed(db_name)
    except Exception as e:
        logger.exception("Failed Database : %s , with error :%s " %
                         (db_name, e.message))
Beispiel #31
0
def rename_project(request, project_id):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    new_project_name = request.POST.get('data', '').strip()
    if len(new_project_name) == 0:
        return HttpResponse(json.dumps({
            "status":
            "error",
            "message":
            ugettext("This field is required.")
        }),
                            content_type='application/json')

    if (questionnaire.name != new_project_name):
        questionnaire.name = new_project_name
        try:
            questionnaire.save(process_post_update=True)
            UserActivityLog().log(request,
                                  action=RENAMED_PROJECT,
                                  project=questionnaire.name)
            return HttpResponse(json.dumps({"status": "success"}),
                                content_type='application/json')
        except DataObjectAlreadyExists as e:
            return HttpResponse(json.dumps({
                "status":
                "error",
                "message":
                ugettext("Questionnaire with same name already exists.")
            }),
                                content_type='application/json')
    return HttpResponse(json.dumps({"status": "success"}),
                        content_type='application/json')
def get_project_info(manager, raw_project):
    project_id = raw_project['value']['_id']
    project = Project.load(manager.database, project_id)
    questionnaire = manager.get(project.qid, FormModel)
    questionnaire_code = questionnaire.form_code

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

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

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

    create_subjects_link = ''
    if 'no' in raw_project['value']['activity_report']:
        create_subjects_link = append_query_strings_to_url(reverse("create_subject", args=[project.entity_type]),
                                                           web_view=True)

    project_info = dict(project_id=project_id,
                        name=raw_project['value']['name'],
                        qid=questionnaire_code,
                        created=raw_project['value']['created'],
                        type=raw_project['value']['project_type'],
                        link=(reverse('project-overview', args=[project_id])),
                        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_link,
                        entity_type=project.entity_type,
                        encoded_name=urlquote(raw_project['value']['name']),
                        import_template_file_name=slugify(raw_project['value']['name']))
    return project_info
def update_submission_search_for_subject_edition(entity_doc, dbm):
    from datawinners.search.submission_query import SubmissionQueryBuilder

    entity_type = entity_doc.entity_type
    projects = []
    for row in dbm.load_all_rows_in_view('projects_by_subject_type',
                                         key=entity_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] == entity_type:
                entity_field_code = field.code

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

            fields_mapping = {
                unique_id_field_name: entity_doc.data['name']['value']
            }
            args = {
                es_unique_id_code_field_name(unique_id_field_name):
                entity_doc.short_code
            }

            survey_response_filtered_query = SubmissionQueryBuilder(
                project).query_all(dbm.database_name, project.id, **args)

            for survey_response in survey_response_filtered_query.all():
                SubmissionIndexUpdateHandler(
                    dbm.database_name,
                    project.id).update_field_in_submission_index(
                        survey_response._id, fields_mapping)
Beispiel #34
0
class TestProjectModel(unittest.TestCase):
    def setUp(self):
        self.dbm = get_db_manager(database='mangrove-test')
        create_views(self.dbm)
        self.project1 = Project(name="Test1", goals="Testing", project_type="Survey", entity_type="Clinic",
                                devices=['web'])
        self.project1_id = self.project1.save(self.dbm)
        self.project2 = Project(name="Test2", goals="Testing", project_type="Survey", entity_type="Clinic",
                                devices=['web'])
        self.project2_id = self.project2.save(self.dbm)

        self._create_form_model_for_project(self.project1)


    def tearDown(self):
        _delete_db_and_remove_db_manager(self.dbm)

    def test_get_all_projects(self):
        projects = get_all_projects(self.dbm)
        self.assertEquals(len(projects), 2)

    def test_get_one_project(self):
        self.assertEquals(get_project(self.project1_id, self.dbm)['_id'], self.project1_id)

    def test_should_update_project(self):
        self.project1.update(dict(name='Test1', devices=['web', 'sms'], goals="New goals"))
        self.project1.save(self.dbm)
        self.assertEquals(self.project1.name, 'test1')
        self.assertEquals(self.project1.goals, 'New goals')
        self.assertEquals(self.project1.devices, ['web', 'sms'])

    def test_project_name_should_be_unique(self):
        project = Project(name="Test2", goals="Testing", project_type="Survey", entity_type="Clinic", devices=['web'])
        with self.assertRaises(DataObjectAlreadyExists):
            project.save(self.dbm)

    def test_project_name_should_be_case_insensitively_unique(self):
        project = Project(name="tEsT2", goals="Testing", project_type="Survey", entity_type="Clinic", devices=['web'])
        with self.assertRaises(DataObjectAlreadyExists):
            project.save(self.dbm)

    def test_should_check_for_unique_name_while_update_project(self):
        self.project1.update(dict(name='Test2', devices=['web', 'sms'], goals="New goals"))
        with self.assertRaises(DataObjectAlreadyExists):
            self.project1.save(self.dbm)

    def _create_form_model_for_project(self,project):
        ddtype = DataDictType(self.dbm, name='Default String Datadict Type', slug='string_default',
                              primitive_type='string')
        question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=ddtype)
        question2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=ddtype)
        self.form_model = FormModel(self.dbm, name=self.project1.name, form_code="abc", fields=[question1, question2],
                               entity_type=["Clinic"], state=attributes.INACTIVE_STATE)
        qid = self.form_model.save()
        project.qid = qid
        project.save(self.dbm)

    def test_should_update_questionnaire(self):
        self.project1.name = "New Name"
        self.project1.update_questionnaire(self.dbm)
        form_model = self.dbm.get(self.project1.qid, FormModel)
        self.assertEqual("New Name", form_model.name)

    def test_should_activate_form_on_project_activate(self):
        form_model = self.dbm.get(self.project1.qid, FormModel)
        self.assertFalse(form_model.is_active())
        self.project1.activate(self.dbm)
        form_model = self.dbm.get(self.project1.qid, FormModel)
        self.assertTrue(form_model.is_active())
        self.assertEquals(ProjectState.ACTIVE,self.project1.state)

    def test_should_deactivate_form_on_project_deactivate(self):
        project = Project(state=ProjectState.ACTIVE)
        dbm = Mock(spec=DatabaseManager)
        form_model_mock = Mock(spec=FormModel)
        dbm.get.return_value = form_model_mock

        with patch("datawinners.project.models.Project.save") as project_save_mock:
            project.deactivate(dbm)

            form_model_mock.deactivate.assert_called_once_with()
            form_model_mock.save.assert_called_once_with()
            project_save_mock.assert_called_once_with(dbm)

        self.assertEqual( ProjectState.INACTIVE, project.state)

    def test_should_set_form_to_test_on_project_set_to_test(self):
        project = Project(state=ProjectState.ACTIVE)
        dbm = Mock(spec=DatabaseManager)
        form_model_mock = Mock(spec=FormModel)
        dbm.get.return_value = form_model_mock

        with patch("datawinners.project.models.Project.save") as project_save_mock:
            project.to_test_mode(dbm)

            form_model_mock.set_test_mode.assert_called_once_with()
            form_model_mock.save.assert_called_once_with()
            project_save_mock.assert_called_once_with(dbm)

        self.assertEqual( ProjectState.TEST, project.state)
def create_clinic_projects(CLINIC_ENTITY_TYPE, manager):
    name_type = create_data_dict(manager, name='Name', slug='Name', primitive_type='string')
    # Entity id is a default type in the system.
    entity_id_type = get_datadict_type_by_slug(manager, slug='entity_id')
    age_type = create_data_dict(manager, name='Age Type', slug='age', primitive_type='integer')
    date_type = create_data_dict(manager, name='Report Date', slug='date', primitive_type='date')
    select_type = create_data_dict(manager, name='Choice Type', slug='choice', primitive_type='select')
    geo_code_type = create_data_dict(manager, name='GeoCode Type', slug='geo_code', primitive_type='geocode')
    question1 = TextField(label="entity_question", code="EID", name="What is associated entity?",
                          language="eng", entity_question_flag=True, ddtype=entity_id_type,
                          length=TextConstraint(min=1, max=12))
    question2 = TextField(label="Name", code="NA", name="What is your name?",
                          length=TextConstraint(min=1, max=10),
                          defaultValue="some default value", language="eng", ddtype=name_type)
    question3 = IntegerField(label="Father age", code="FA", name="What is age of father?",
                             range=NumericConstraint(min=18, max=100), ddtype=age_type)
    question4 = DateField(label="Report date", code="RD", name="What is reporting date?",
                          date_format="dd.mm.yyyy", ddtype=date_type)
    question5 = SelectField(label="Blood Group", code="BG", name="What is your blood group?",
                            options=[("O+", "a"), ("O-", "b"), ("AB", "c"), ("B+", "d")], single_select_flag=True,
                            ddtype=select_type)
    question6 = SelectField(label="Symptoms", code="SY", name="What are symptoms?",
                            options=[("Rapid weight loss", "a"), ("Dry cough", "b"), ("Pneumonia", "c"),
                                     ("Memory loss", "d"), ("Neurological disorders ", "e")], single_select_flag=False,
                            ddtype=select_type)
    question7 = GeoCodeField(name="What is the GPS code for clinic", code="GPS", label="What is the GPS code for clinic?",
                             language="eng", ddtype=geo_code_type)
    form_model = FormModel(manager, name="AIDS", label="Aids form_model",
                           form_code="cli001", type='survey',
                           fields=[question1, question2, question3, question4, question5, question6, question7],
                           entity_type=CLINIC_ENTITY_TYPE
    )
    try:
        qid = form_model.save()
    except DataObjectAlreadyExists as e:
        get_form_model_by_code(manager, "cli001").delete()
        qid = form_model.save()
    project = Project(name="Clinic Test Project", goals="This project is for automation", project_type="survey",
                      entity_type=CLINIC_ENTITY_TYPE[-1], devices=["sms"], activity_report='no',sender_group="close")
    project.qid = qid
    project.state = ProjectState.ACTIVE
    try:
        project.save(manager)
    except Exception:
        pass
    form_model2 = FormModel(manager, name="AIDS", label="Aids form_model",
                            form_code="cli002", type='survey',
                            fields=[question1, question2, question3, question4, question5, question6, question7],
                            entity_type=CLINIC_ENTITY_TYPE)
    try:
        qid2 = form_model2.save()
    except DataObjectAlreadyExists as e:
        get_form_model_by_code(manager, "cli002").delete()
        qid2 = form_model2.save()
    project2 = Project(name="Clinic2 Test Project", goals="This project is for automation", project_type="survey",
                       entity_type=CLINIC_ENTITY_TYPE[-1], devices=["sms"], activity_report='no', sender_group="close")
    project2.qid = qid2
    project2.state = ProjectState.ACTIVE
    try:
        project2.save(manager)
    except Exception:
        pass
Beispiel #36
0
 def test_project_name_should_be_case_insensitively_unique(self):
     project = Project(name="tEsT2", goals="Testing", project_type="Survey", entity_type="Clinic", devices=['web'])
     with self.assertRaises(DataObjectAlreadyExists):
         project.save(self.dbm)