Example #1
0
def sms(request):
    _message = request.POST["message"]
    _from, _to = _get_from_and_to_numbers(request)
    try:
        dbm = get_db_manager_for(_to)
        sms_player = SMSPlayer(dbm, SubmissionHandler(dbm))
        transportInfo = TransportInfo(transport=SMS, source=_from, destination=_to)
        response = sms_player.accept(Request(transportInfo=transportInfo, message=_message))
        message = SMSResponse(response).text()

    except (SubmissionParseException, FormModelDoesNotExistsException,) as exception:
        message = get_exception_message_for(exception=exception, channel=SMS)
        log = DatawinnerLog(message=_message, from_number=_from, to_number=_to, form_code=exception.data[0],
                            error=message)
        log.save()
    except NumberNotRegisteredException as exception:
        message = get_exception_message_for(exception=exception, channel=SMS)
        log = DatawinnerLog(message=_message, from_number=_from, to_number=_to, form_code=None, error=message)
        log.save()
    except MangroveException as exception:
        message = get_exception_message_for(exception=exception, channel=SMS)
    except Exception as exception:
        logger.exception('SMS Processing failure: message')
        message = get_exception_message_for(exception=exception, channel=SMS)

    return HttpResponse(message)
Example #2
0
def submit(request):
    dbm = get_database_manager(request)
    post = _get_submission(request.POST)
    success = True
    try:
        web_player = WebPlayer(dbm, SubmissionHandler(dbm))
        message = {
            k: v
            for (k, v) in post.get('message').items() if not is_empty(v)
        }
        if message.get(LOCATION_TYPE_FIELD_CODE) is not None:
            message[LOCATION_TYPE_FIELD_CODE] += COUNTRY
        request = Request(message=message,
                          transportInfo=TransportInfo(
                              transport=post.get('transport'),
                              source=post.get('source'),
                              destination=post.get('destination')))
        response = web_player.accept(request)
        if response.success:
            message = get_success_msg_for_registration_using(response, "web")
        else:
            message = get_submission_error_message_for(response.errors)
        entity_id = response.datarecord_id
    except MangroveException as exception:
        message = get_exception_message_for(exception=exception, channel="web")
        success = False
        entity_id = None
    return HttpResponse(
        json.dumps({
            'success': success,
            'message': message,
            'entity_id': entity_id
        }))
Example #3
0
 def success_resposne(self, is_update, organization, questionnaire_form):
     success_message = None
     error_message = None
     try:
         created_request = helper.create_request(questionnaire_form, self.request.user.username, is_update=is_update)
         response = self.player_response(created_request)
         if response.success:
             ReportRouter().route(organization.org_id, response)
             success_message = _("Your changes have been saved.") if is_update else self.success_message(
                 response.short_code)
         if not is_update:
             questionnaire_form = self.form(country=organization.country_name())
         else:
             questionnaire_form._errors = helper.errors_to_list(response.errors, self.form_model.fields)
     except DataObjectNotFound as exception:
         logger.exception(exception)
         message = exception_messages.get(DataObjectNotFound).get(WEB)
         error_message = _(message) % (self.form_model.entity_type[0], self.form_model.entity_type[0])
     except Exception as exception:
         logger.exception('Web Submission failure:-')
         error_message = _(get_exception_message_for(exception=exception, channel=Channel.WEB))
     _project_context = get_form_context(self.form_code, self.project, questionnaire_form,
                                         self.manager, self.hide_link_class, self.disable_link_class,
                                         is_update=is_update)
     _project_context.update({'success_message': success_message, 'error_message': error_message})
     self._update_form_context(_project_context, questionnaire_form)
     return render_to_response(self.template, _project_context,
                               context_instance=RequestContext(self.request))
 def test_should_return_default_msg_for_exception_if_channel_specific_msg_missing(
         self):
     message = get_exception_message_for(
         exception=NumberNotRegisteredException("1234567890"),
         channel="web")
     expected_message = "This telephone number is not registered in our system."
     self.assertEqual(expected_message, message)
 def test_should_return_default_exception_message_for_unknown_exception(
         self):
     message = get_exception_message_for(
         exception=MangroveException(message="This is an error"),
         channel="web")
     expected_message = "This is an error"
     self.assertEqual(expected_message, message)
 def test_should_return_exception_message_for_incorrect_number_of_sms_answers(
         self):
     message = get_exception_message_for(
         exception=SMSParserWrongNumberOfAnswersException("form_code"),
         channel="sms")
     expected_message = u'Error. Incorrect number of responses. Please review printed Questionnaire and resend entire SMS.'
     self.assertEqual(expected_message, message)
Example #7
0
    def response_for_post_request(self, is_update=None):
        questionnaire_form = self.form(self.request.POST)
        quota_reached = is_quota_reached(self.request)
        if not questionnaire_form.is_valid() or quota_reached:
            form_context = get_form_context(self.questionnaire,
                                            questionnaire_form, self.manager,
                                            self.hide_link_class,
                                            self.disable_link_class)
            form_context.update({'is_quota_reached': quota_reached})
            return render_to_response(self.template,
                                      form_context,
                                      context_instance=RequestContext(
                                          self.request))

        success_message = None
        error_message = None
        # if self.is_data_sender:
        #     questionnaire_form.cleaned_data['eid'] = self.request.user.get_profile().reporter_id
        try:
            created_request = helper.create_request(questionnaire_form,
                                                    self.request.user.username,
                                                    is_update=is_update)
            reporter_id = self.request.POST.get('dsid')
            response = self.player_response(created_request, reporter_id)
            if response.success:
                ReportRouter().route(
                    get_organization(self.request).org_id, response)
                success_message = _("Successfully submitted")
            else:
                questionnaire_form._errors = helper.errors_to_list(
                    response.errors, self.questionnaire.fields)
        except DataObjectNotFound as exception:
            logger.exception(exception)
            message = exception_messages.get(DataObjectNotFound).get(WEB)
            error_message = _(message) % (self.questionnaire.entity_type[0],
                                          self.questionnaire.entity_type[0])
        except Exception as exception:
            logger.exception('Web Submission failure:-')
            error_message = _(
                get_exception_message_for(exception=exception,
                                          channel=Channel.WEB))

        _project_context = get_form_context(self.questionnaire,
                                            questionnaire_form,
                                            self.manager,
                                            self.hide_link_class,
                                            self.disable_link_class,
                                            is_update=is_update)

        _project_context.update({
            'success_message': success_message,
            'error_message': error_message,
            'questionnaire_form': self.form(),
        })

        return render_to_response(self.template,
                                  _project_context,
                                  context_instance=RequestContext(
                                      self.request))
Example #8
0
    def test_should_handle_SMSParserWrongNumberOfAnswersException(self):
        exception = SMSParserWrongNumberOfAnswersException('test_code')

        form_model_mock = Mock(spec=FormModel)
        form_model_mock.activeLanguages = ['en']
        self.request['dbm'] = Mock(spec=DatabaseManager)
        expected_message = get_exception_message_for(exception, channel=SMS)

        response = handle(exception, self.request)

        self.assertEqual(expected_message, response)
    def test_should_handle_NumberNotRegisteredException(self):
        patcher = patch('datawinners.messageprovider.handlers.create_failure_log')
        create_failure_log_mock = patcher.start()

        exception = NumberNotRegisteredException('1234312')

        expected_message = get_exception_message_for(exception, SMS)
        response = handle(exception, self.request)
        patcher.stop()

        self.assertEqual(expected_message, response)
        create_failure_log_mock.assert_called_with(expected_message,self.request)
Example #10
0
def sms(request):
    _message = request.POST["message"]
    _from, _to = _get_from_and_to_numbers(request)
    try:
        dbm = get_db_manager_for(_to)
        sms_player = SMSPlayer(dbm, SubmissionHandler(dbm))
        transportInfo = TransportInfo(transport=SMS,
                                      source=_from,
                                      destination=_to)
        response = sms_player.accept(
            Request(transportInfo=transportInfo, message=_message))
        message = SMSResponse(response).text()

    except (
            SubmissionParseException,
            FormModelDoesNotExistsException,
    ) as exception:
        message = get_exception_message_for(exception=exception, channel=SMS)
        log = DatawinnerLog(message=_message,
                            from_number=_from,
                            to_number=_to,
                            form_code=exception.data[0],
                            error=message)
        log.save()
    except NumberNotRegisteredException as exception:
        message = get_exception_message_for(exception=exception, channel=SMS)
        log = DatawinnerLog(message=_message,
                            from_number=_from,
                            to_number=_to,
                            form_code=None,
                            error=message)
        log.save()
    except MangroveException as exception:
        message = get_exception_message_for(exception=exception, channel=SMS)
    except Exception as exception:
        logger.exception('SMS Processing failure: message')
        message = get_exception_message_for(exception=exception, channel=SMS)

    return HttpResponse(message)
    def test_should_handle_SMSParserWrongNumberOfAnswersException(self):
        exception = SMSParserWrongNumberOfAnswersException('test_code')

        form_model_mock = Mock(spec=FormModel)
        patcher = patch('datawinners.messageprovider.handlers.get_form_model_by_code')
        get_form_model_mock = patcher.start()
        get_form_model_mock.return_value = form_model_mock
        form_model_mock.activeLanguages = ['en']
        self.request['dbm'] = Mock(spec=DatabaseManager)
        expected_message = get_exception_message_for(exception, channel=SMS)

        response = handle(exception, self.request)

        self.assertEqual(expected_message, response)
        self.assertEqual('en', get_language())
        patcher.stop()
Example #12
0
def submit(request):
    dbm = get_database_manager(request.user)
    post = json.loads(request.POST['data'])
    success = True
    try:
        web_player = WebPlayer(
            dbm,
            LocationBridge(location_tree=get_location_tree(),
                           get_loc_hierarchy=get_location_hierarchy))
        message = post['message']
        message[LOCATION_TYPE_FIELD_CODE] = get_country_appended_location(
            message.get(LOCATION_TYPE_FIELD_CODE),
            get_organization_country(request))
        request = Request(message=message,
                          transportInfo=TransportInfo(
                              transport=post.get('transport'),
                              source=post.get('source'),
                              destination=post.get('destination')))
        response = web_player.accept(request)
        if response.success:
            message = get_success_msg_for_registration_using(response, "web")
        else:
            message = get_submission_error_message_for(response.errors)
        entity_id = response.datarecord_id
    except DataObjectAlreadyExists as exception:
        message = _(
            "Entity with Unique Identification Number (ID) = %s already exists."
        ) % exception.data[1]
        success, entity_id = False, None
    except MangroveException as exception:
        message = get_exception_message_for(exception=exception, channel="web")
        message = _("Please add subject type and then add a subject"
                    ) if message == "t should be present" else message
        success = False
        entity_id = None
    return HttpResponse(
        json.dumps({
            'success': success,
            'message': message,
            'entity_id': entity_id
        }))
Example #13
0
def submit(request):
    dbm = get_database_manager(request)
    post = _get_submission(request.POST)
    success = True
    try:
        web_player = WebPlayer(dbm, SubmissionHandler(dbm))
        message = {k: v for (k, v) in post.get('message').items() if not is_empty(v)}
        if message.get(LOCATION_TYPE_FIELD_CODE) is not None:
            message[LOCATION_TYPE_FIELD_CODE]+= COUNTRY
        request = Request(message=message,
                          transportInfo=TransportInfo(transport=post.get('transport'), source=post.get('source'),
                                                      destination=post.get('destination')))
        response = web_player.accept(request)
        if response.success:
            message = get_success_msg_for_registration_using(response, "web")
        else:
            message = get_submission_error_message_for(response.errors)
        entity_id = response.datarecord_id
    except MangroveException as exception:
        message = get_exception_message_for(exception=exception, channel="web")
        success = False
        entity_id = None
    return HttpResponse(json.dumps({'success': success, 'message': message, 'entity_id': entity_id}))
 def test_should_return_message_for_exception_for_channel(self):
     message = get_exception_message_for(exception=FormModelDoesNotExistsException("QC1"), channel="sms")
     expected_message = "Error with Questionnaire ID QC1. Find the Questionnaire ID on the printed questionnaire and resend SMS"
     self.assertEqual(expected_message, message)
 def test_should_return_default_message_for_exception_for_no_channel_passed(
         self):
     message = get_exception_message_for(
         exception=FormModelDoesNotExistsException("QC1"))
     expected_message = "Questionnaire ID QC1 doesnt exist."
     self.assertEqual(expected_message, message)
 def test_should_return_message_for_exception_for_channel(self):
     message = get_exception_message_for(
         exception=FormModelDoesNotExistsException("QC1"), channel="sms")
     expected_message = "Error with Questionnaire code QC1. Find the Questionnaire code on the printed questionnaire and resend SMS starting with this questionnaire code."
     self.assertEqual(expected_message, message)
 def test_should_return_default_message_for_exception_for_no_channel_passed(self):
     message = get_exception_message_for(exception=FormModelDoesNotExistsException("QC1"))
     expected_message = "Questionnaire ID QC1 doesnt exist."
     self.assertEqual(expected_message, message)
Example #18
0
def create_subject(request, entity_type=None):
    manager = get_database_manager(request.user)
    form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])
    web_questionnaire_template = get_template(request.user)
    disable_link_class, hide_link_class = get_visibility_settings_for(
        request.user)

    if request.method == 'GET':
        questionnaire_form = SubjectRegistrationForm(form_model)

        form_context = _make_form_context(
            questionnaire_form,
            entity_type,
            disable_link_class,
            hide_link_class,
            form_model.form_code,
            get_organization_telephone_number(request),
            form_model.fields,
            web_view=request.GET.get("web_view", False))
        form_context.update(
            {'is_pro_sms': get_organization(request).is_pro_sms})

        return render_to_response(web_questionnaire_template,
                                  form_context,
                                  context_instance=RequestContext(request))

    if request.method == 'POST':
        questionnaire_form = SubjectRegistrationForm(
            form_model,
            data=request.POST,
            country=get_organization_country(request))
        if not questionnaire_form.is_valid():
            form_context = _make_form_context(
                questionnaire_form,
                entity_type,
                disable_link_class,
                hide_link_class,
                form_model.form_code,
                get_organization_telephone_number(request),
                form_model.fields,
                web_view=True)
            return render_to_response(web_questionnaire_template,
                                      form_context,
                                      context_instance=RequestContext(request))

        success_message = None
        error_message = None
        try:
            from datawinners.project.helper import create_request

            response = WebPlayer(
                manager,
                LocationBridge(
                    location_tree=get_location_tree(),
                    get_loc_hierarchy=get_location_hierarchy)).accept(
                        create_request(questionnaire_form,
                                       request.user.username),
                        logger=websubmission_logger)
            if response.success:
                ReportRouter().route(
                    get_organization(request).org_id, response)
                success_message = _(
                    "%s with Identification Number %s successfully registered."
                ) % (entity_type.capitalize(), response.short_code)

                detail_dict = dict({
                    "Subject Type": entity_type.capitalize(),
                    "Unique ID": response.short_code
                })
                UserActivityLog().log(request,
                                      action=REGISTERED_IDENTIFICATION_NUMBER,
                                      detail=json.dumps(detail_dict))
                questionnaire_form = SubjectRegistrationForm(form_model)
            else:
                from datawinners.project.helper import errors_to_list

                questionnaire_form._errors = errors_to_list(
                    response.errors, form_model.fields)
                form_context = _make_form_context(
                    questionnaire_form,
                    entity_type,
                    disable_link_class,
                    hide_link_class,
                    form_model.form_code,
                    get_organization_telephone_number(request),
                    form_model.fields,
                    web_view=True)
                return render_to_response(
                    web_questionnaire_template,
                    form_context,
                    context_instance=RequestContext(request))

        except DataObjectNotFound:
            message = exception_messages.get(DataObjectNotFound).get(WEB)
            error_message = _(message) % (form_model.entity_type[0],
                                          form_model.entity_type[0])
        except DataObjectAlreadyExists as exception:
            error_message = _(
                "%s with ID Number '%s' already exists or has previously collected data."
            ) % (exception.data[2], exception.data[1])
        except Exception as exception:
            error_message = _(
                get_exception_message_for(exception=exception,
                                          channel=Channel.WEB))

        subject_context = _make_form_context(
            questionnaire_form,
            entity_type,
            disable_link_class,
            hide_link_class,
            form_model.form_code,
            get_organization_telephone_number(request),
            form_model.fields,
            web_view=True)
        subject_context.update({
            'success_message': success_message,
            'error_message': error_message
        })

        return render_to_response(web_questionnaire_template,
                                  subject_context,
                                  context_instance=RequestContext(request))
 def test_should_return_valid_message_if_its_not_parameterized(self):
     message = get_exception_message_for(exception=NumberNotRegisteredException("1234567"), channel="web")
     expected_message = "This telephone number is not registered in our system."
     self.assertEqual(expected_message, message)
 def test_should_return_valid_message_if_its_not_parameterized(self):
     message = get_exception_message_for(
         exception=NumberNotRegisteredException("1234567"), channel="web")
     expected_message = "This telephone number is not registered in our system."
     self.assertEqual(expected_message, message)
 def test_should_return_default_exception_message_for_unknown_exception(self):
     message = get_exception_message_for(exception=MangroveException(message="This is an error"), channel="web")
     expected_message = "This is an error"
     self.assertEqual(expected_message, message)
Example #22
0
def default_exception_handler_with_logger(exception, request):
    exception_message = get_exception_message_for(exception=exception,
                                                  channel=SMS)
    create_failure_log(exception_message, request)
    return exception_message
 def test_should_return_valid_message_even_if_code_is_None(self):
     message = get_exception_message_for(
         exception=EntityQuestionCodeNotSubmitted(), channel="web")
     expected_message = "Error. Invalid Submission. Refer to printed Questionnaire. Unique Identification Number(ID) is missing."
     self.assertEqual(expected_message, message)
 def test_should_return_valid_message_even_if_code_is_None(self):
     message = get_exception_message_for(exception=EntityQuestionCodeNotSubmitted(), channel="web")
     expected_message = "Error. Invalid Submission. Refer to printed Questionnaire. Unique Identification Number(ID) is missing."
     self.assertEqual(expected_message, message)
Example #25
0
def create_subject(request, entity_type=None):
    manager = get_database_manager(request.user)
    form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])

    QuestionnaireForm = WebQuestionnaireFormCreator(
        None, form_model=form_model).create()

    web_questionnaire_template = get_template(request.user)
    disable_link_class, hide_link_class = get_visibility_settings_for(
        request.user)

    if request.method == 'GET':
        questionnaire_form = QuestionnaireForm()
        form_context = _make_form_context(questionnaire_form, entity_type,
                                          disable_link_class, hide_link_class)
        return render_to_response(web_questionnaire_template,
                                  form_context,
                                  context_instance=RequestContext(request))

    if request.method == 'POST':
        questionnaire_form = QuestionnaireForm(
            country=get_organization_country(request), data=request.POST)
        if not questionnaire_form.is_valid():
            form_context = _make_form_context(questionnaire_form, entity_type,
                                              disable_link_class,
                                              hide_link_class)
            return render_to_response(web_questionnaire_template,
                                      form_context,
                                      context_instance=RequestContext(request))

        success_message = None
        error_message = None
        try:
            from datawinners.project.helper import create_request

            response = WebPlayer(
                manager,
                LocationBridge(
                    location_tree=get_location_tree(),
                    get_loc_hierarchy=get_location_hierarchy)).accept(
                        create_request(questionnaire_form,
                                       request.user.username),
                        logger=websubmission_logger)
            if response.success:
                ReportRouter().route(
                    get_organization(request).org_id, response)
                success_message = (_(
                    "Successfully submitted. Unique identification number(ID) is:"
                ) + " %s") % (response.short_code, )
                detail_dict = dict({
                    "Subject Type": entity_type.capitalize(),
                    "Unique ID": response.short_code
                })
                UserActivityLog().log(request,
                                      action=REGISTERED_SUBJECT,
                                      detail=json.dumps(detail_dict))
                questionnaire_form = QuestionnaireForm()
            else:
                from datawinners.project.helper import errors_to_list

                questionnaire_form._errors = errors_to_list(
                    response.errors, form_model.fields)
                form_context = _make_form_context(questionnaire_form,
                                                  entity_type,
                                                  disable_link_class,
                                                  hide_link_class)
                return render_to_response(
                    web_questionnaire_template,
                    form_context,
                    context_instance=RequestContext(request))

        except DataObjectNotFound:
            message = exception_messages.get(DataObjectNotFound).get(WEB)
            error_message = _(message) % (form_model.entity_type[0],
                                          form_model.entity_type[0])
        except DataObjectAlreadyExists as exception:
            error_message = _(
                "Entity with Unique Identification Number (ID) = %s already exists."
            ) % exception.data[1]
        except Exception as exception:
            error_message = _(
                get_exception_message_for(exception=exception,
                                          channel=Channel.WEB))

        subject_context = _make_form_context(questionnaire_form, entity_type,
                                             disable_link_class,
                                             hide_link_class)
        subject_context.update({
            'success_message': success_message,
            'error_message': error_message
        })

        return render_to_response(web_questionnaire_template,
                                  subject_context,
                                  context_instance=RequestContext(request))
 def test_should_return_valid_message_even_if_code_is_None(self):
     message = get_exception_message_for(
         exception=EntityQuestionCodeNotSubmitted(), channel="web")
     expected_message = "This field is required."
     self.assertEqual(expected_message, message)
 def test_should_return_default_msg_for_exception_if_channel_specific_msg_missing(self):
     message = get_exception_message_for(exception=NumberNotRegisteredException("1234567890"), channel="web")
     expected_message = "This telephone number is not registered in our system."
     self.assertEqual(expected_message, message)
Example #28
0
def default_exception_handler(exception, request):
    return get_exception_message_for(exception=exception, channel=SMS)
Example #29
0
def edit_subject(request, entity_type, entity_id, project_id=None):
    manager = get_database_manager(request.user)
    form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])
    subject = get_by_short_code(manager, entity_id, [entity_type.lower()])
    back_link = reverse(all_subjects, args=[entity_type])

    web_questionnaire_template = get_template(request.user)
    disable_link_class, hide_link_class = get_visibility_settings_for(
        request.user)
    if request.method == 'GET':
        initialize_values(form_model, subject)
        questionnaire_form = SubjectRegistrationForm(form_model)
        form_context = _make_form_context(
            questionnaire_form,
            entity_type,
            disable_link_class,
            hide_link_class,
            form_model.form_code,
            get_organization_telephone_number(request),
            form_model.fields,
            is_update=True,
            back_link=back_link)
        form_context.update(
            {'is_pro_sms': get_organization(request).is_pro_sms})
        return render_to_response(web_questionnaire_template,
                                  form_context,
                                  context_instance=RequestContext(request))
    if request.method == 'POST':
        questionnaire_form = SubjectRegistrationForm(
            form_model,
            data=request.POST,
            country=get_organization_country(request))
        if not questionnaire_form.is_valid():
            form_context = _make_form_context(
                questionnaire_form,
                entity_type,
                disable_link_class,
                hide_link_class,
                form_model.form_code,
                get_organization_telephone_number(request),
                form_model.fields,
                is_update=True,
                back_link=back_link)
            return render_to_response(web_questionnaire_template,
                                      form_context,
                                      context_instance=RequestContext(request))

        success_message = None
        error_message = None
        try:
            response = WebPlayer(
                manager,
                LocationBridge(
                    location_tree=get_location_tree(),
                    get_loc_hierarchy=get_location_hierarchy)).accept(
                        create_request(questionnaire_form,
                                       request.user.username,
                                       is_update=True))

            if response.success:
                #assumption q6 - unique_id code and q2 - lastname codes cannot be changed
                update_submission_search_for_subject_edition(
                    manager, [entity_type], response.processed_data)
                success_message = _("Your changes have been saved.")
                questionnaire_form = SubjectRegistrationForm(
                    form_model,
                    data=request.POST,
                    country=get_organization_country(request))
            else:
                from datawinners.project.helper import errors_to_list

                questionnaire_form._errors = errors_to_list(
                    response.errors, form_model.fields)
                form_context = _make_form_context(
                    questionnaire_form,
                    entity_type,
                    disable_link_class,
                    hide_link_class,
                    form_model.form_code,
                    get_organization_telephone_number(request),
                    form_model.fields,
                    is_update=True,
                    back_link=back_link)
                return render_to_response(
                    web_questionnaire_template,
                    form_context,
                    context_instance=RequestContext(request))

        except DataObjectNotFound:
            message = exception_messages.get(DataObjectNotFound).get(WEB)
            error_message = _(message) % (form_model.entity_type[0],
                                          form_model.entity_type[0])
        except Exception as exception:
            error_message = _(
                get_exception_message_for(exception=exception,
                                          channel=Channel.WEB))
        subject_context = _make_form_context(
            questionnaire_form,
            entity_type,
            disable_link_class,
            hide_link_class,
            form_model.form_code,
            get_organization_telephone_number(request),
            form_model.fields,
            is_update=True,
            back_link=back_link)
        subject_context.update({
            'success_message': success_message,
            'error_message': error_message
        })

        return render_to_response(web_questionnaire_template,
                                  subject_context,
                                  context_instance=RequestContext(request))
Example #30
0
def data_object_not_found_handler(exception, request):
    return get_exception_message_for(exception=exception,
                                     channel=SMS,
                                     formatter=data_object_not_found_formatter)
Example #31
0
def edit_subject(request, entity_type, entity_id, project_id=None):
    manager = get_database_manager(request.user)
    form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])
    subject = get_by_short_code(manager, entity_id, [entity_type.lower()])
    if project_id is not None:
        back_link = '/project/registered_subjects/%s/' % project_id
    else:
        back_link = reverse(all_subjects)

    for field in form_model.fields:
        if field.name == LOCATION_TYPE_FIELD_NAME:
            field.value = ','.join(subject.location_path)
        elif field.name == GEO_CODE_FIELD_NAME:
            field.value = ','.join(map(str, subject.geometry['coordinates']))
        elif field.name == SHORT_CODE_FIELD:
            field.value = subject.short_code
        else:
            field.value = subject.data[
                field.name]['value'] if field.name in subject.data.keys(
                ) else None
        field.value = field._to_str()

    QuestionnaireForm = WebQuestionnaireFormCreator(
        None, form_model=form_model).create()
    web_questionnaire_template = get_template(request.user)
    disable_link_class, hide_link_class = get_visibility_settings_for(
        request.user)
    if request.method == 'GET':
        questionnaire_form = QuestionnaireForm()
        form_context = _make_form_context(questionnaire_form, entity_type,
                                          disable_link_class, hide_link_class,
                                          True, back_link)
        return render_to_response(web_questionnaire_template,
                                  form_context,
                                  context_instance=RequestContext(request))
    if request.method == 'POST':
        post_data = QueryDict(request.raw_post_data, mutable=True)
        post_data[
            QuestionnaireForm.short_code_question_code] = subject.short_code
        questionnaire_form = QuestionnaireForm(
            country=get_organization_country(request), data=post_data)
        if not questionnaire_form.is_valid():
            form_context = _make_form_context(questionnaire_form, entity_type,
                                              disable_link_class,
                                              hide_link_class, True, back_link)
            return render_to_response(web_questionnaire_template,
                                      form_context,
                                      context_instance=RequestContext(request))

        success_message = None
        error_message = None
        try:
            from datawinners.project.helper import create_request

            response = WebPlayer(
                manager,
                LocationBridge(
                    location_tree=get_location_tree(),
                    get_loc_hierarchy=get_location_hierarchy)).accept(
                        create_request(questionnaire_form,
                                       request.user.username,
                                       is_update=True))

            if response.success:
                success_message = _("Your changes have been saved.")
                questionnaire_form = QuestionnaireForm(
                    country=get_organization_country(request), data=post_data)
            else:
                from datawinners.project.helper import errors_to_list

                questionnaire_form._errors = errors_to_list(
                    response.errors, form_model.fields)
                form_context = _make_form_context(questionnaire_form,
                                                  entity_type,
                                                  disable_link_class,
                                                  hide_link_class, True,
                                                  back_link)
                return render_to_response(
                    web_questionnaire_template,
                    form_context,
                    context_instance=RequestContext(request))

        except DataObjectNotFound:
            message = exception_messages.get(DataObjectNotFound).get(WEB)
            error_message = _(message) % (form_model.entity_type[0],
                                          form_model.entity_type[0])
        except Exception as exception:
            error_message = _(
                get_exception_message_for(exception=exception,
                                          channel=Channel.WEB))

        subject_context = _make_form_context(questionnaire_form, entity_type,
                                             disable_link_class,
                                             hide_link_class, True, back_link)
        subject_context.update({
            'success_message': success_message,
            'error_message': error_message
        })

        return render_to_response(web_questionnaire_template,
                                  subject_context,
                                  context_instance=RequestContext(request))