def test_should_return_data_sender_TESTER_when_send_from_TEST_REPORTER_MOBILE_NUMBER( self): survey_response = SurveyResponse( TestDataSenderHelper.manager, TransportInfo("sms", TEST_REPORTER_MOBILE_NUMBER, "destination"), owner_uid=self.test_ds_id) data_sender = get_data_sender(TestDataSenderHelper.manager, survey_response) self.assertEqual(('TEST', 'test', data_sender[2]), data_sender)
def test_should_return_data_sender_information_send_from_web(self): beany_tester_id = get_by_short_code_include_voided( TestDataSenderHelper.manager, "rep1", REPORTER_ENTITY_TYPE).id survey_response = SurveyResponse(TestDataSenderHelper.manager, TransportInfo( "web", "*****@*****.**", "destination"), owner_uid=beany_tester_id) data_sender = get_data_sender(TestDataSenderHelper.manager, survey_response) self.assertEqual(("Beany", "rep1", data_sender[2]), data_sender)
def test_should_return_N_A_when_the_data_sender_was_deleted_and_send_from_smart_phone( self): survey_response = SurveyResponse(TestDataSenderHelper.manager, TransportInfo("smartPhone", "*****@*****.**", "destination"), owner_uid=self.deleted_ds_id) data_sender = get_data_sender(TestDataSenderHelper.manager, survey_response) self.assertEqual(("M K Gandhi", u"del1"), data_sender[:2])
def delete_subjects(request): manager = get_database_manager(request.user) entity_type = request.POST['entity_type'] all_ids = subject_short_codes_to_delete(request, manager, entity_type) transport_info = TransportInfo("web", request.user.username, "") delete_entity_instance(manager, all_ids, entity_type, transport_info) log_activity(request, DELETED_SUBJECTS, "%s: [%s]" % (entity_type.capitalize(), ", ".join(all_ids))) messages.success(request, get_success_message(entity_type)) return HttpResponse(json.dumps({'success': True}))
def _create_survey_response(self, form_model, reporter_id, values, extra_data): transport_info = TransportInfo(transport='api', source=reporter_id, destination='') response = self._is_request_valid(form_model, reporter_id, extra_data) if response.success: service = SurveyResponseService(self.dbm) response = service.save_survey(form_model.form_code, values, [], transport_info, reporter_id) if response.success: self._increment_web_counter() return response else: return response
def create_survey_response(submission, dbm): response = SurveyResponse( dbm, TransportInfo(submission.channel, submission.source, submission.destination), form_code=submission.form_code, form_model_revision=submission.form_model_revision, values=copy(submission.values)) response.create_migrated_response(submission.status, submission.errors, submission.is_void(), submission._doc.submitted_on, submission.test, submission.event_time, submission._doc.data_record_id) return response
def process_create_data_sender_form(dbm, form, org_id): message = None data_sender_id = None if form.is_valid(): try: organization = Organization.objects.get(org_id=org_id) if organization.in_trial_mode: _add_data_sender_to_trial_organization( form.cleaned_data["telephone_number"], org_id) web_player = WebPlayer( dbm, LocationBridge(location_tree=get_location_tree(), get_loc_hierarchy=get_location_hierarchy)) reporter_id = form.cleaned_data["short_code"].lower( ) if form.cleaned_data != "" else None request = Request(message=_get_data(form.cleaned_data, organization.country_name(), reporter_id), transportInfo=TransportInfo( transport='web', source='web', destination='mangrove')) response = web_player.accept(request, logger=websubmission_logger) if response.success: data_sender_id = response.short_code message = get_success_msg_for_ds_registration_using( response, "web") else: form.update_errors(response.errors) except IntegrityError as e: form.update_errors({ MOBILE_NUMBER_FIELD_CODE: _(u'Sorry, the telephone number %s has already been registered.' ) % form.cleaned_data["telephone_number"] }) except DataObjectAlreadyExists as e: message = _("%s with %s = %s already exists.") % ( e.data[2], e.data[0], e.data[1], ) except MangroveException as exception: message = exception.message return data_sender_id, message
def __init__(self, request): self.request = request self.request_user = request.user self.manager = get_database_manager(self.request_user) self.player = XFormPlayerV2(self.manager, get_feeds_database(self.request_user)) self.xml_submission_file = request.POST['form_data'] self.retain_files = request.POST['retain_files'].split(',') if request.POST.get('retain_files') else None self.add_preview_files() self.user_profile = NGOUserProfile.objects.get(user=self.request_user) self.mangrove_request = Request(message=self.xml_submission_file, media=request.FILES, retain_files=self.retain_files, transportInfo= TransportInfo(transport=WEB, source=self.request_user.email, destination='' )) self.organization = Organization.objects.get(org_id=self.user_profile.org_id)
def delete_data_senders(request): manager = get_database_manager(request.user) organization = get_organization(request) entity_type = request.POST['entity_type'] all_ids = data_sender_short_codes(request, manager) superusers = rep_id_name_dict_of_users(manager) non_superuser_rep_ids = [id for id in all_ids if id not in superusers.keys()] transport_info = TransportInfo("web", request.user.username, "") delete_datasenders_from_project(manager, non_superuser_rep_ids) delete_entity_instance(manager, non_superuser_rep_ids, entity_type, transport_info) delete_datasender_users_if_any(non_superuser_rep_ids, organization) if organization.in_trial_mode: delete_datasender_for_trial_mode(manager, non_superuser_rep_ids, entity_type) log_activity(request, DELETED_DATA_SENDERS, "%s: [%s]" % (entity_type.capitalize(), ", ".join(non_superuser_rep_ids)), ) messages = get_success_message(entity_type) return HttpResponse(json.dumps({'success': True, 'message': messages}))
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 }))
def setUp(self): self.dbm = Mock(spec=DatabaseManager) self.mock_form_model = Mock(spec=FormModel) self.mock_form_model.entity_question.code = '123' self.transport_info = TransportInfo('web', 'source', 'destination') self.values = [ { 'q1': 'q1', 'q2': '30.07.2012', 'entity_question_code': '001' }, { 'q1': 'q1', 'q2': '30.08.2012', 'entity_question_code': '005' }, { 'q1': 'q1', 'q2': '30.08.2012', 'entity_question_code': '002' }, ] self.submissions = [ Submission(self.dbm, self.transport_info, form_code='test', values=self.values[0]), Submission(self.dbm, transport_info=self.transport_info, form_code='test', values=self.values[1]), Submission(self.dbm, transport_info=self.transport_info, form_code='test', values=self.values[2]) ]
def import_submission(self, form_code, organization, registered_emails, registered_phone_numbers, responses, values): transport_info = TransportInfo(transport=self.channel_name, source=self.channel_name, destination="") submission = self._create_submission(transport_info, form_code, copy(values)) try: form_model, values = self._process(form_code, values) log_entry = "message: " + str(values) + "|source: web|" if case_insensitive_lookup(values, ENTITY_TYPE_FIELD_CODE) == REPORTER: response = self.import_data_sender(form_model, organization, registered_emails, registered_phone_numbers, submission, values) else: response = self.submit(form_model, values, submission, []) if not response.success: response.errors = dict(error=response.errors, row=values) log_entry += "Status: False" else: log_entry += "Status: True" self.logger.info(log_entry) responses.append(response) except DataObjectAlreadyExists as e: if self.logger is not None: log_entry += "Status: False" self.logger.info(log_entry) self.appendFailedResponse(responses, "%s with %s = %s already exists." % (e.data[2], e.data[0], e.data[1]), values=values) except (InvalidEmailException, MangroveException) as e: self.appendFailedResponse(responses, e.message, values=values)
def process_create_data_sender_form(dbm, form, org_id): message = None data_sender_id = None if form.is_valid(): try: organization = Organization.objects.get(org_id=org_id) if organization.in_trial_mode: _add_data_sender_to_trial_organization( form.cleaned_data["telephone_number"], org_id) web_player = WebPlayer( dbm, LocationBridge(location_tree=get_location_tree(), get_loc_hierarchy=get_location_hierarchy)) reporter_id = form.cleaned_data["short_code"].lower( ) if form.cleaned_data != "" else None request = Request(message=_get_data(form.cleaned_data, organization.country_name(), reporter_id), transportInfo=TransportInfo( transport='web', source='web', destination='mangrove')) response = web_player.accept(request, logger=websubmission_logger) if response.success: data_sender_id = response.short_code message = get_success_msg_for_registration_using( response, "web") else: form.update_errors(response.errors) except MangroveException as exception: message = exception.message return data_sender_id, message
def test_should_return_all_data_senders_that_have_submitted_data(self): FROM_NUMBER1 = '1234567890' FROM_NUMBER2 = '261332592634' FROM_NUMBER_NOT_EXIST = '434543545' TO_NUMBER = '919880734937' EMAIL = "*****@*****.**" EMAIL1 = "*****@*****.**" EMAIL2 = "*****@*****.**" EMAIL_NOT_EXIST = "[email protected]" Submission(self.manager, TransportInfo(SMS, FROM_NUMBER1, TO_NUMBER), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMS, FROM_NUMBER1, TO_NUMBER), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMS, FROM_NUMBER2, TO_NUMBER), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMS, FROM_NUMBER_NOT_EXIST, TO_NUMBER), FORM_CODE, []).save() Submission(self.manager, TransportInfo(WEB, EMAIL, "destination"), FORM_CODE, []).save() Submission(self.manager, TransportInfo(WEB, EMAIL, "destination"), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMART_PHONE, EMAIL, "destination"), FORM_CODE, []).save() Submission(self.manager, TransportInfo(WEB, EMAIL1, "destination"), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMART_PHONE, EMAIL2, "destination"), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMART_PHONE, EMAIL_NOT_EXIST, "destination"), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMS, TEST_REPORTER_MOBILE_NUMBER, TO_NUMBER), FORM_CODE, []).save() Submission(self.manager, TransportInfo(SMS, "4008123123", TO_NUMBER), "sent for other form_code which shouldn't be included in the result", []).save() data_sender_list = DataSenderHelper(self.manager, FORM_CODE).get_all_data_senders_ever_submitted(self.org_id) self.assertEqual(6, len(data_sender_list)) self.assertIn(DataSender([FROM_NUMBER1], "Beany", "rep1"), data_sender_list) self.assertIn(DataSender([FROM_NUMBER2], "Qingshan", "rep2"), data_sender_list) self.assertIn(DataSender([EMAIL1], "Tester Pune", "admin"), data_sender_list) self.assertIn(DataSender([TEST_REPORTER_MOBILE_NUMBER], "TEST", "test"), data_sender_list) self.assertIn(DataSender(sorted([EMAIL_NOT_EXIST, FROM_NUMBER_NOT_EXIST, EMAIL]), ugettext(NOT_AVAILABLE_DS), None), data_sender_list) self.assertIn(DataSender([EMAIL2], "mamy rasamoel", "rep11"), data_sender_list)
def test_should_return_data_sender_TESTER_when_send_from_TEST_REPORTER_MOBILE_NUMBER(self): submission = Submission(self.manager, TransportInfo("sms", TEST_REPORTER_MOBILE_NUMBER, "destination")) data_sender = DataSenderHelper(self.manager).get_data_sender(self.org_id, submission) self.assertEqual(('TEST', '', 'TEST'), data_sender)
def test_should_return_N_A_when_the_data_sender_was_deleted_and_send_from_smart_phone(self): submission = Submission(self.manager, TransportInfo("smartPhone", "*****@*****.**", "destination")) data_sender = DataSenderHelper(self.manager).get_data_sender(self.org_id, submission) self.assertEqual((NOT_AVAILABLE_DS, None, '*****@*****.**'), data_sender)
def test_should_return_data_sender_information_send_from_web(self): submission = Submission(self.manager, TransportInfo("web", "*****@*****.**", "destination")) data_sender = DataSenderHelper(self.manager).get_data_sender(self.org_id, submission) self.assertEqual(("Tester Pune", "admin", "*****@*****.**"), data_sender)
def test_should_return_N_A_when_the_data_sender_was_deleted_and_send_from_sms(self): submission = Submission(self.manager, TransportInfo("sms", "123123", "destination")) data_sender = DataSenderHelper(self.manager).get_data_sender(self.org_id, submission) self.assertEqual((NOT_AVAILABLE_DS, None, '123123'), data_sender)
def process(self, http_request, mangrove_request): organization_settings = OrganizationSetting.objects.get(organization=mangrove_request['organization']) _to = get_organization_number(organization_settings.get_organisation_sms_number()[0]) _from = TEST_REPORTER_MOBILE_NUMBER mangrove_request['transport_info']=TransportInfo(SMS, _from, _to)
def setUp(self): self.request = dict(incoming_message='message', dbm=MagicMock(), transport_info=TransportInfo(transport='SMS', source='123', destination='456'))
def post(self, request, reporter_id, *args, **kwargs): reporter_id = reporter_id.lower() manager = get_database_manager(request.user) reporter_entity = ReporterEntity( get_by_short_code(manager, reporter_id, [REPORTER])) entity_links = { 'registered_datasenders_link': reverse("all_datasenders") } datasender = {'short_code': reporter_id} get_datasender_user_detail(datasender, request.user) email = datasender.get( 'email') if datasender.get('email') != '--' else False org_id = request.user.get_profile().org_id form = ReporterRegistrationForm(org_id=org_id, data=request.POST) message = None if form.is_valid(): try: org_id = request.user.get_profile().org_id current_telephone_number = reporter_entity.mobile_number current_name = reporter_entity.name organization = Organization.objects.get(org_id=org_id) web_player = WebPlayer( manager, LocationBridge(location_tree=get_location_tree(), get_loc_hierarchy=get_location_hierarchy)) response = web_player.accept( Request(message=_get_data(form.cleaned_data, organization.country_name(), reporter_id), transportInfo=TransportInfo( transport='web', source='web', destination='mangrove'), is_update=True)) if response.success: if organization.in_trial_mode: update_data_sender_from_trial_organization( current_telephone_number, form.cleaned_data["telephone_number"], org_id) if email and current_name != form.cleaned_data["name"]: update_user_name_if_exists(email, form.cleaned_data["name"]) message = _("Your changes have been saved.") detail_dict = {"Unique ID": reporter_id} current_lang = get_language() activate("en") field_mapping = dict(mobile_number="telephone_number") for field in [ "geo_code", "location", "mobile_number", "name" ]: if getattr(reporter_entity, field) != form.cleaned_data.get( field_mapping.get(field, field)): label = u"%s" % form.fields[field_mapping.get( field, field)].label detail_dict.update({ label: form.cleaned_data.get( field_mapping.get(field, field)) }) activate(current_lang) if len(detail_dict) > 1: detail_as_string = json.dumps(detail_dict) UserActivityLog().log(request, action=EDITED_DATA_SENDER, detail=detail_as_string) else: form.update_errors(response.errors) except MangroveException as exception: message = exception.message return render_to_response('edit_datasender_form.html', { 'form': form, 'message': message, 'reporter_id': reporter_id, 'email': email, 'project_links': entity_links }, context_instance=RequestContext(request))
def edit_data_sender(request, project_id, reporter_id): manager = get_database_manager(request.user) reporter_entity = ReporterEntity( get_by_short_code(manager, reporter_id, [REPORTER])) project, links = _get_project_and_project_link(manager, project_id, reporter_id) user_profile = get_user_profile_by_reporter_id(reporter_id, request.user) email = user_profile.user.email if user_profile else None if request.method == 'GET': location = reporter_entity.location geo_code = reporter_entity.geo_code form = ReporterRegistrationForm( initial={ 'project_id': project_id, 'name': reporter_entity.name, 'telephone_number': reporter_entity.mobile_number, 'location': location, 'geo_code': geo_code }) return render_to_response('project/edit_datasender.html', { 'project': project, 'reporter_id': reporter_id, 'form': form, 'project_links': links, 'in_trial_mode': _in_trial_mode(request), 'email': email }, context_instance=RequestContext(request)) if request.method == 'POST': org_id = request.user.get_profile().org_id form = ReporterRegistrationForm(org_id=org_id, data=request.POST) message = None if form.is_valid(): try: organization = Organization.objects.get(org_id=org_id) current_telephone_number = reporter_entity.mobile_number web_player = WebPlayer( manager, LocationBridge(location_tree=get_location_tree(), get_loc_hierarchy=get_location_hierarchy)) response = web_player.accept( Request(message=_get_data(form.cleaned_data, organization.country_name(), reporter_id), transportInfo=TransportInfo( transport='web', source='web', destination='mangrove'), is_update=True)) if response.success: if organization.in_trial_mode: update_data_sender_from_trial_organization( current_telephone_number, form.cleaned_data["telephone_number"], org_id) message = _("Your changes have been saved.") detail_dict = {"Unique ID": reporter_id} current_lang = get_language() activate("en") field_mapping = dict(mobile_number="telephone_number") for field in [ "geo_code", "location", "mobile_number", "name" ]: if getattr(reporter_entity, field) != form.cleaned_data.get( field_mapping.get(field, field)): label = u"%s" % form.fields[field_mapping.get( field, field)].label detail_dict.update({ label: form.cleaned_data.get( field_mapping.get(field, field)) }) activate(current_lang) if len(detail_dict) > 1: detail_as_string = json.dumps(detail_dict) UserActivityLog().log(request, action=EDITED_DATA_SENDER, detail=detail_as_string, project=project.name) else: form.update_errors(response.errors) except MangroveException as exception: message = exception.message return render_to_response('edit_datasender_form.html', { 'project': project, 'form': form, 'reporter_id': reporter_id, 'message': message, 'project_links': links, 'in_trial_mode': _in_trial_mode(request), 'email': email }, context_instance=RequestContext(request))
def get_web_transport_info(username): return TransportInfo(transport="web", source=username, destination="")
def setUp(self): MangroveTestCase.setUp(self) self._create_entities() self.player = SMSPlayer(self.manager, location_tree=LocationBridge(get_location_tree(), get_loc_hierarchy=get_location_hierarchy)) self.transport = TransportInfo(transport="sms", source="1234", destination="5678") initializer.run(self.manager)
def process(self, http_request, mangrove_request): vumi_parameters = get_vumi_parameters(http_request) mangrove_request['transport_info'] = TransportInfo( SMS, vumi_parameters.from_number, vumi_parameters.to_number)