def test_should_register_new_entity(self): message1 = """reg +t dog +n Clinic in Diégo–Suarez +l Diégo–Suarez +g -12.35 49.3 +d This is a Clinic in Diégo–Suarez + m 87654325 """ response = self.send_sms(message1) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) expected_short_code = "dog1" self.assertEqual(response.short_code, expected_short_code) a = get_by_short_code(self.dbm, expected_short_code, ["dog"]) self.assertEqual(a.short_code, expected_short_code) text = "reg +N buddy +S bud +T dog +G 80 80 +D its a dog! +M 45557" response = self.send_sms(text) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) self.assertEqual(response.short_code, "bud", ["dog"]) a = get_by_short_code(self.dbm, "bud", ["dog"]) self.assertEqual(a.short_code, "bud") text = "reg +N buddy2 +T dog +L 80 80 +D its another dog! +M 78541" response = self.send_sms(text) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) expected_short_code = "dog3" self.assertEqual(response.short_code, expected_short_code) b = get_by_short_code(self.dbm, expected_short_code, ["dog"]) self.assertEqual(b.short_code, expected_short_code)
def test_sms_player(self): self.CreateSchoolEntityType() bh = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='BeiHang', short_code="bh") bh = get_by_short_code(self.manager, "bh", self.entity_type) print "Create School:", bh.short_code, bh.id bd_id = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='BeiDa', short_code="bd") bd = get_by_short_code(self.manager, "bd", self.entity_type) print "Create School:", bd.short_code, bd.id qh_id = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='QingHua', short_code="qh") qh = get_by_short_code(self.manager, "qh", self.entity_type) print "Create School:", qh.short_code, qh.id self.CreateSchoolByFormModel() self.CreateSchoolByGlobalFormModel() rpt_id, reporter = self.CreateReporter() print "Create Reporter:", reporter.short_code, reporter.id form_code, form_id = self.CreateFormModel() print "Create Questionnaire:", form_code, form_id self.PrintResult(self.SendSubmission("form001 bh zhangsan 22 RED")) self.PrintResult(self.SendSubmission("form001 bh lisi 23 2")) self.PrintResult(self.SendSubmission("form001 bd wangwu 27 1")) self.PrintResult(self.SendSubmission("form001 bd zhaoliu 25 1")) self.PrintResult(self.SendSubmission("form001 qh zhouqi 24 2")) self.PrintResult(self.SendSubmission("form001 qh zhengba 30 1")) count = submission_count(self.manager, "form001", None, None) self.assertEqual(6, count)
def test_should_get_entity_by_short_code(self): reporter = Entity(self.dbm, entity_type=["Reporter"], location=["Pune", "India"], short_code="repx") reporter.save() entity = get_by_short_code(self.dbm, short_code="repx", entity_type=["Reporter"]) self.assertTrue(entity is not None) self.assertEqual("repx", entity.short_code) with self.assertRaises(DataObjectNotFound): entity = get_by_short_code(self.dbm, short_code="ABC", entity_type=["Waterpoint"])
def validate(self, values, fields, dbm): errors = OrderedDict() entity_type_field, entity_id_field = self._get_field_codes(fields) try: get_by_short_code(dbm, entity_id_field.value, [entity_type_field.value]) except DataObjectNotFound as exception: errors[entity_type_field.code] = exception.message errors[entity_id_field.code] = exception.message return errors
def validate(self, values, fields, dbm=None): errors = OrderedDict() unique_id_fields = self.get_unique_id_field(fields) self.exception = [] for field in unique_id_fields: unique_id = case_insensitive_lookup(values, field.code) try: get_by_short_code(dbm, unique_id, [field.unique_id_type]) except DataObjectNotFound as e: self.exception.append(e) errors[field.code] = e.message return errors
def create_or_update_entity(manager, entity_type, location, aggregation_paths, short_code, geometry=None): try: entity = get_by_short_code(manager, short_code, entity_type) entity.delete() except DataObjectNotFound: pass return create_entity(manager, entity_type, short_code, location, aggregation_paths, geometry)
def test_migrate(self): try: get_by_short_code(self.dbm, self.new_short_code, self.form.entity_type) except DataObjectNotFound as e: self.assertIsInstance(e, DataObjectNotFound) migrate([self.database]) submission_after_migration = self.dbm.get( self.id_of_submission_with_wrong_short_code, Submission) short_code_migrated_submission = self.get_short_code_in_submission( submission_after_migration, self.entity_question_code) self.assertIsInstance( get_by_short_code(self.dbm, short_code_migrated_submission, self.form.entity_type), Entity)
def __create_web_users(org_id, reporter_details, language_code): duplicate_email_ids = User.objects.filter( email__in=[x['email'].lower() for x in reporter_details]).values('email') errors = [] dbm = get_database_manager_for_org(Organization.objects.get(org_id=org_id)) if len(duplicate_email_ids) > 0: for duplicate_email in duplicate_email_ids: errors.append("User with email %s already exists" % duplicate_email['email']) content = json.dumps({'success': False, 'errors': errors}) else: for reporter in reporter_details: reporter_entity = get_by_short_code(dbm, reporter['reporter_id'], [REPORTER]) user = User.objects.create_user(reporter['email'].lower(), reporter['email'].lower(), 'test123') group = Group.objects.filter(name="Data Senders")[0] user.groups.add(group) user.first_name = reporter_entity.value(NAME_FIELD) user.save() profile = NGOUserProfile(user=user, org_id=org_id, title="Mr", reporter_id=reporter['reporter_id']) profile.save() send_email_to_data_sender(user, language_code) content = json.dumps({ 'success': True, 'message': "Users has been created" }) return content
def get(self, request, reporter_id, *args, **kwargs): create_data_sender = False 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 name = reporter_entity.name phone_number = reporter_entity.mobile_number location = reporter_entity.location geo_code = reporter_entity.geo_code form = ReporterRegistrationForm( initial={ 'name': name, 'telephone_number': phone_number, 'location': location, 'geo_code': geo_code }) return self.render_to_response({ 'reporter_id': reporter_id, 'form': form, 'project_links': entity_links, 'email': email, 'create_data_sender': create_data_sender })
def test_should_create_entity_with_short_code(self): with self.assertRaises(AssertionError): entity = create_entity(self.dbm, entity_type=["reporter"], short_code=None) with self.assertRaises(AssertionError): entity = create_entity(self.dbm, entity_type=["reporter"], short_code="") with self.assertRaises(AssertionError): entity = create_entity(self.dbm, entity_type="Reporter", short_code="BLAH") with self.assertRaises(AssertionError): entity = create_entity(self.dbm, entity_type=[], short_code="BLAH") with self.assertRaises(AssertionError): entity = create_entity(self.dbm, entity_type=("reporter"), short_code="BLAH") entity = create_entity(self.dbm, entity_type=["reporter"], short_code="ABC") saved_entity = get_by_short_code(self.dbm, short_code="ABC", entity_type=["reporter"]) self.assertEqual(saved_entity.id, entity.id) with self.assertRaises(DataObjectAlreadyExists): create_entity(self.dbm, entity_type=["reporter"], short_code="ABC") with self.assertRaises(EntityTypeDoesNotExistsException): create_entity(self.dbm, entity_type=["Dog"], short_code="ABC")
def to_entity(self, dbm): if self.form_model.is_registration_form(): location = self.cleaned_data.get(LOCATION_TYPE_FIELD_CODE) return entity.create_entity(dbm=dbm, entity_type=self.entity_type, location=location, short_code=self.short_code, geometry=convert_to_geometry(self.cleaned_data.get(GEO_CODE))) return entity.get_by_short_code(dbm, self.short_code, self.entity_type)
def __create_web_users(org_id, reporter_details, language_code): duplicate_entries = {} [ duplicate_entries.update({item[0]: item[1]}) for item in reporter_details.items() if [val for val in reporter_details.values()].count(item[1]) > 1 ] errors = [] if len(duplicate_entries) > 0: content = json.dumps({ 'success': False, 'errors': errors, 'duplicate_entries': duplicate_entries }) organization = Organization.objects.get(org_id=org_id) dbm = get_database_manager_for_org(organization) existent_email_addresses = User.objects.filter( email__in=reporter_details.values()).values('email') if len(existent_email_addresses) > 0: for duplicate_email in existent_email_addresses: errors.append("User with email %s already exists" % duplicate_email['email']) content = json.dumps({ 'success': False, 'errors': errors, 'duplicate_entries': duplicate_entries }) if errors.__len__() == 0 and duplicate_entries.keys().__len__() == 0: for reporter_id, email in reporter_details.iteritems(): reporter_entity = get_by_short_code(dbm, reporter_id, [REPORTER]) reporter_email = email.lower() put_email_information_to_entity(dbm, reporter_entity, email=reporter_email) user = User.objects.create_user(reporter_email, reporter_email, 'test123') group = Group.objects.filter(name="Data Senders")[0] user.groups.add(group) user.first_name = reporter_entity.value(NAME_FIELD) user.save() profile = NGOUserProfile(user=user, org_id=org_id, title="Mr", reporter_id=reporter_id.lower()) profile.save() send_email_to_data_sender(user, language_code, organization=organization) content = json.dumps({ 'success': True, 'message': "Users has been created" }) return content
def create_or_update_entity(self, manager, entity_type, location, aggregation_paths, short_code, geometry=None): try: entity = get_by_short_code(manager, short_code, entity_type) entity.delete() except DataObjectNotFound: pass if entity_type == [REPORTER]: return create_contact(manager, short_code, location, aggregation_paths, geometry) return create_entity(manager, entity_type, short_code, location, aggregation_paths, geometry)
def edit_my_subject(request, entity_type, entity_id, project_id=None): manager = get_database_manager(request.user) subject = get_by_short_code(manager, entity_id, [entity_type.lower()]) subject_request = SubjectWebQuestionnaireRequest(request, project_id) form_model = subject_request.form_model if request.method == 'GET': initialize_values(form_model, subject) return subject_request.response_for_get_request(is_update=True) elif request.method == 'POST': return subject_request.post(is_update=True)
def delete_and_create_entity_instance(manager, ENTITY_TYPE, location, short_code): try: entity = get_by_short_code(dbm=manager, short_code=short_code,entity_type=ENTITY_TYPE) entity.delete() except DataObjectNotFound: pass e = Entity(manager, entity_type=ENTITY_TYPE, location=location, short_code=short_code) id1 = e.save() return e, id1
def update_corresponding_datasender_details(user,ngo_user_profile,old_phone_number): manager = get_database_manager(user) reporter_entity = get_by_short_code(manager, ngo_user_profile.reporter_id, [REPORTER]) current_phone_number = ngo_user_profile.mobile_phone reporter_entity.update_latest_data([('name',user.first_name),("mobile_number", current_phone_number)]) organization = Organization.objects.get(org_id=ngo_user_profile.org_id) if organization.in_trial_mode: update_data_sender_from_trial_organization(old_phone_number, current_phone_number, organization.org_id)
def to_entity(self, dbm): if self.form_model.is_registration_form(): location = self.cleaned_data.get(LOCATION_TYPE_FIELD_CODE) return entity.create_entity(dbm=dbm, entity_type=self.entity_type, location=location, short_code=self.short_code, geometry=convert_to_geometry( self.cleaned_data.get(GEO_CODE))) return entity.get_by_short_code(dbm, self.short_code, self.entity_type)
def test_should_register_entity_with_geocode_if_only_location_provided(self): message1 = """reg +t dog +n Dog in AMPIZARANTANY +l AMPIZARANTANY +d This is a Dog in AMPIZARANTANY + m 87654325 """ response = self.send_sms(message1) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) expected_short_code = 'dog1' self.assertEqual(response.short_code, expected_short_code) dog = get_by_short_code(self.dbm, expected_short_code, ["dog"]) self.assertEqual([-12, 60] ,dog.geometry.get("coordinates"))
def map_entities(request): dbm = get_database_manager(request.user) project = Project.load(dbm.database, request.GET['project_id']) if project.is_activity_report(): entity_list = [ get_by_short_code(dbm, short_code, ["reporter"]) for short_code in project.data_senders ] else: entity_list = get_entities_by_type(dbm, request.GET['id']) location_geojson = helper.create_location_geojson(entity_list) return HttpResponse(location_geojson)
def test_should_register_entity_with_geo_code(self): message1 = """reg +t dog +n Dog in Diégo–Suarez +g -12.35 49.3 +d This is a Dog in Diégo–Suarez + m 87654325 """ response = self.send_sms(message1) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) expected_short_code = 'dog1' self.assertEqual(response.short_code, expected_short_code) dog = get_by_short_code(self.dbm, expected_short_code, ["dog"]) self.assertEqual([-12.35 , 49.3] ,dog.geometry.get("coordinates"))
def test_should_register_entity_with_geo_code(self): message1 = """reg +t dog +n Dog in Diégo–Suarez +g -12.35 49.3 +d This is a Dog in Diégo–Suarez + m 87654325 """ response = self.send_sms(message1) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) expected_short_code = 'dog1' self.assertEqual(response.short_code, expected_short_code) dog = get_by_short_code(self.dbm, expected_short_code, ["dog"]) self.assertEqual([-12.35, 49.3], dog.geometry.get("coordinates"))
def _process(self, form_code, values): form_model = get_form_model_by_code(self.dbm, form_code) values = GeneralWorkFlow().process(values) if form_model.is_registration_form(): values = RegistrationWorkFlow(self.dbm, form_model, self.location_tree).process(values) if form_model.entity_defaults_to_reporter(): reporter_entity = entity.get_by_short_code( self.dbm, values.get(form_model.entity_question.code.lower()), form_model.entity_type) values = ActivityReportWorkFlow(form_model, reporter_entity).process(values) return form_model, values
def test_should_register_entity_with_geocode_and_location_provided(self): message1 = """reg +t dog +n Dog in AMPIZARANTANY +l AMPIZARANTANY +g 10 10 +d This is a Dog in AMPIZARANTANY + m 87654325 """ response = self.send_sms(message1) self.assertTrue(response.success) self.assertIsNotNone(response.datarecord_id) expected_short_code = 'dog1' self.assertEqual(response.short_code, expected_short_code) dog = get_by_short_code(self.dbm, expected_short_code, ["dog"]) self.assertEqual([10, 10], dog.geometry.get("coordinates")) self.assertEqual(["ampizarantany"], dog.location_path)
def create_default_reporter(manager): try: entity = get_by_short_code(manager, REPORTER_SHORT_CODE, REPORTER_ENTITY_TYPE) entity.delete() except DataObjectNotFound: pass entity = create_entity(dbm=manager, entity_type=REPORTER_ENTITY_TYPE, short_code=REPORTER_SHORT_CODE, location=DEFAULT_LOCATION) mobile_number_type = get_or_create_data_dict(manager, name='Mobile Number Type', slug='mobile_number', primitive_type='string') name_type = get_or_create_data_dict(manager, name='Name', slug='name', primitive_type='string') data = [(MOBILE_NUMBER_FIELD, TEST_REPORTER_MOBILE_NUMBER,mobile_number_type),(NAME_FIELD,'TEST',name_type)] entity.add_data(data=data)
def _hard_delete_unique_ids(unique_ids, dbm, form_model, request): for unique_id in unique_ids: entity = get_by_short_code(dbm, unique_id, form_model.entity_type) _delete_unique_id_from_elastic_search(dbm, form_model.entity_type[0], entity.id) delete_data_record(dbm, form_model.form_code, unique_id) dbm._save_document( EntityActionDocument(form_model.entity_type[0], unique_id, HARD_DELETE)) entity.delete() if unique_ids: _refresh_elastic_search_index(dbm) log_activity( request, DELETED_IDENTIFICATION_NUMBER, "%s: [%s]" % (request.POST['entity_type'], ", ".join(unique_ids)))
def _get_subject(self, submission): subject_code = case_insensitive_lookup( self.form_model.entity_question.code, submission.values) for each in self._subject_list: if each[-1] == subject_code: return each else: try: entity = get_by_short_code(self.manager, subject_code, [self.form_model.entity_type[0]]) subject = entity.data['name']['value'], entity.short_code except Exception: subject = NOT_AVAILABLE, str(subject_code) self._subject_list.append(subject) return subject
def test_latest_value_are_stored_in_entity(self): clinic_entity, clinic_shortcode, reporter_entity, reporter_entity_short_code = self._create_clinic_and_reporter() doctor_type, facility_type, med_type, opened_type = self._create_data_dict_type() data_record = [('meds', 30, med_type), ('doc', "asif", doctor_type), ('facility', 'clinic', facility_type), ('opened_on', datetime(2011, 01, 02, tzinfo=UTC), opened_type)] data_record_id = clinic_entity.add_data(data=data_record, event_time=datetime(2011, 01, 02, tzinfo=UTC), submission=dict(submission_id="123456")) self.assertTrue(data_record_id is not None) updated_clinic_entity = get_by_short_code(dbm=self.dbm, short_code=clinic_shortcode, entity_type=['clinic']) self.assertEqual(30, updated_clinic_entity.data['meds']['value']) self.assertEqual('asif', updated_clinic_entity.data['doc']['value']) self.assertEqual('clinic', updated_clinic_entity.data['facility']['value'])
def test_latest_value_are_stored_in_entity(self): clinic_entity, clinic_shortcode, reporter_entity, reporter_entity_short_code = self._create_clinic_and_reporter( ) doctor_type, facility_type, med_type, opened_type = self._create_data_dict_type( ) data_record = [('meds', 30, med_type), ('doc', "asif", doctor_type), ('facility', 'clinic', facility_type), ('opened_on', datetime(2011, 01, 02, tzinfo=UTC), opened_type)] data_record_id = clinic_entity.add_data( data=data_record, event_time=datetime(2011, 01, 02, tzinfo=UTC), submission=dict(submission_id="123456")) self.assertTrue(data_record_id is not None) updated_clinic_entity = get_by_short_code(dbm=self.dbm, short_code=clinic_shortcode, entity_type=['clinic']) self.assertEqual(30, updated_clinic_entity.data['meds']['value']) self.assertEqual('asif', updated_clinic_entity.data['doc']['value']) self.assertEqual('clinic', updated_clinic_entity.data['facility']['value'])
def create_default_reporter(manager): try: entity = get_by_short_code(manager, REPORTER_SHORT_CODE, REPORTER_ENTITY_TYPE) entity.delete() except DataObjectNotFound: pass entity = create_entity(dbm=manager, entity_type=REPORTER_ENTITY_TYPE, short_code=REPORTER_SHORT_CODE, location=DEFAULT_LOCATION) mobile_number_type = get_or_create_data_dict(manager, name='Mobile Number Type', slug='mobile_number', primitive_type='string') name_type = get_or_create_data_dict(manager, name='Name', slug='name', primitive_type='string') data = [(MOBILE_NUMBER_FIELD, TEST_REPORTER_MOBILE_NUMBER, mobile_number_type), (NAME_FIELD, 'TEST', name_type)] entity.add_data(data=data)
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 get_entity(self, dbm): return entity.get_by_short_code(dbm=dbm, short_code=self.short_code, entity_type=self.entity_type)
def migrate_01(managers): failed_managers = [] failed_users = [] print "Updating existing project that have web device to have smartPhone device" for user in User.objects.filter(groups=Group.objects.filter( name='Data Senders')): try: print 'getting user profile for %s' % user.username ngo_user_profile = user.get_profile() db = OrganizationSetting.objects.get( organization=ngo_user_profile.org_id).document_store print 'getting db manager for %s' % user.username manager = get_db_manager(server=settings.COUCH_DB_SERVER, database=db) print 'getting reporter entity for %s' % user.username reporter_entity = get_by_short_code(manager, ngo_user_profile.reporter_id, [REPORTER]) print 'setting first name for %s' % user.username user.first_name = reporter_entity.value(NAME_FIELD) user.save() except Exception as e: failed_users.append((user.username, e.message)) for manager in managers: print("Database %s") % (manager.database_name, ) try: rows = manager.load_all_rows_in_view('all_projects') for row in rows: document = row['value'] document['devices'] = ["sms", "web", "smartPhone"] print("Updating project %s devices to have smartPhone option" ) % (document['name'], ) manager.database.save(document) except Exception as e: failed_managers.append((manager, e.message)) for manager in managers: try: print manager.database print manager print "migrating date fields" form_model_rows = manager.database.query( map_fun_form_model_with_date_field_docs) for form_model_row in form_model_rows: fields = form_model_row.key['json_fields'] for field in fields: if field['type'] == 'date': field_name = field['name'] date_format = field['date_format'] form_code = form_model_row.key['form_code'] data_records = manager.database.query( map_fun_data_records_on_a_form_model, key=form_code) for data in data_records: document = data.value value = document['data'][field_name]['value'] if not isinstance(value, datetime): document['data'][field_name][ 'value'] = datetime.strptime( value, DateField.DATE_DICTIONARY.get( date_format)) manager.database.save(document) except Exception as e: failed_managers.append((manager, e.message)) print 'failed managers if any' for manager, exception_message in failed_managers: print " %s failed. the reason : %s" % (manager, exception_message) print 'failed data sender users if any' for username, exception_message in failed_users: print " %s failed. the reason : %s" % (username, exception_message)
def test_create_school_entity(self): school = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='BeiHang', short_code="bh") school = get_by_short_code(self.manager, "bh", self.entity_type) self.assertEqual(beihang_id, 'BeiHang') self.assertEqual(school.short_code, 'bh')
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 add_email_data_to_entity_document(manager, short_code, data): datasender = get_by_short_code(manager, short_code, REPORTER_ENTITY_TYPE) datasender.update_latest_data([data])
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))
def create_entity(self, dbm): return entity.get_by_short_code(dbm, self.short_code, self.entity_type)
def test_create_reporter(self): reporter_id,r = self.CreateReporter() self.assertEqual(reporter_id, 'Reporter001') reporter = get_by_short_code(self.manager, "rpt_bj", self.reporter_type) self.assertEqual(reporter.short_code, "rpt_bj")
def change_subject(self, dbm, form, short_code, new_value): subject = get_by_short_code(dbm, short_code, form.entity_type) self.update_subject(subject, new_value)