Exemple #1
0
 def add_subject(self, form_model, values, location_tree):
     reporter_id = values.get('eid')
     contact = contact_by_short_code(self.dbm, reporter_id)
     service = IdentificationNumberService(self.dbm)
     response = service.save_identification_number(form_model.form_code,
                                                   values, location_tree)
     return response
Exemple #2
0
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 = contact_by_short_code(dbm, reporter_id)
            reporter_email = email.lower()
            set_email_for_contact(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
Exemple #3
0
def _update_group_for_contacts(contact_ids, dbm, group_names, action):
    for contact_id in contact_ids:
        contact = contact_by_short_code(dbm, contact_id)
        action_to_perform = contact.add_custom_group if action == 'add' else contact.remove_custom_group
        for group_name in group_names:
            action_to_perform(group_name)
        contact.save()
Exemple #4
0
def _rename_group_for_contacts(contact_ids, dbm, current_group_name,
                               new_group_name):
    for contact_id in contact_ids:
        contact = contact_by_short_code(dbm, contact_id)
        contact.remove_custom_group(current_group_name)
        contact.add_custom_group(new_group_name)
        contact.save()
Exemple #5
0
def _set_contacts_email_address(dbm, request):
    web_user_id_email_map = {}
    for item in json.loads(request.POST['post_data']):
        contact = contact_by_short_code(dbm, item['reporter_id'])
        if contact.is_contact:
            set_email_for_contact(dbm, contact, item['email'])
        else:
            web_user_id_email_map.update({item['reporter_id']: item['email']})

    return web_user_id_email_map
Exemple #6
0
def _get_poll_recipients(dbm, questionnaire):
    datasender_ids = questionnaire.data_senders
    contact_dict = {}
    for datasender_id in datasender_ids:
        contact = contact_by_short_code(dbm, datasender_id)
        if contact.name != '':
            contact_dict[contact.name] = contact.short_code
        else:
            contact_dict[contact.data.get('mobile_number')
                         ['value']] = contact.short_code
    return contact_dict
Exemple #7
0
 def _get_mobile_number_for_contacts(self, dbm, poll_recipients,
                                     recipient_option):
     if recipient_option == 'poll_recipients':
         poll_recipients = ast.literal_eval(poll_recipients)
         mobile_numbers = []
         for poll_recipient in poll_recipients:
             contact = contact_by_short_code(dbm, poll_recipient)
             mobile_numbers.append(
                 contact.data.get('mobile_number')['value'])
         return mobile_numbers
     else:
         return []
 def _convert_contacts_to_datasenders(self, contact_short_codes, manager, request):
     datasender_id_email_map = {}
     for contact_short_code in contact_short_codes:
         datasender = contact_by_short_code(manager, contact_short_code)
         if datasender.is_contact:
             datasender.change_status_to_datasender()
             datasender.save(process_post_update=False)
             if datasender.email:
                 datasender_id_email_map.update({datasender.short_code: datasender.email})
         update_datasender_index_by_id(contact_short_code, manager)
     org_id = get_org_id(request)
     create_web_users(org_id, datasender_id_email_map, request.LANGUAGE_CODE)
Exemple #9
0
def update_corresponding_datasender_details(user, ngo_user_profile, old_phone_number):
    manager = get_database_manager(user)
    reporter_entity = contact_by_short_code(manager, ngo_user_profile.reporter_id)
    current_phone_number = ngo_user_profile.mobile_phone
    _void_existing_data_records(manager, ngo_user_profile.reporter_id)
    reporter_entity.add_data(data=_create_data_from_entity(reporter_entity, user.first_name, current_phone_number),
                             submission={"form_code": "reg"})
    datasender_dict = {'name': user.first_name, 'mobile_number': current_phone_number}
    update_submission_search_for_datasender_edition(manager, ngo_user_profile.reporter_id, datasender_dict)

    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)
Exemple #10
0
def my_poll_recipients_count(request, project_id):
    dbm = get_database_manager(request.user)
    questionnaire = Project.get(dbm, project_id)
    datasender_ids = questionnaire.data_senders
    contact_dict = {}
    for datasender_id in datasender_ids:
        contact = contact_by_short_code(dbm, datasender_id)
        if contact.name != '':
            contact_dict[contact.name] = contact.short_code
        else:
            contact_dict[contact.data.get('mobile_number')
                         ['value']] = contact.short_code
    return HttpResponse(content_type='application/json',
                        content=json.dumps(
                            {'my_poll_recipients': contact_dict}))
def update_datasender_on_open_submissions(database_name, reporter_id):
    logger = logging.getLogger('datawinners.tasks')
    try:
        dbm = get_db_manager(database_name)
        logger.error(reporter_id)

        reporter_entity = ReporterEntity(contact_by_short_code(dbm, reporter_id))
        rows = dbm.load_all_rows_in_view("anonymous_submissions", key=reporter_entity.mobile_number)

        for row in rows:
            _update_survey_response(dbm, row, reporter_entity.entity.id)

    except Exception as e:
        logger.exception('Failed for db: %s ,reporter_id: %s' % (database_name, reporter_id))
        logger.exception(e)
Exemple #12
0
    def post(self, request, reporter_id, *args, **kwargs):
        reporter_id = reporter_id.lower()
        manager = get_database_manager(request.user)
        reporter_entity = ReporterEntity(contact_by_short_code(manager, reporter_id))
        email = reporter_entity.email
        org_id = request.user.get_profile().org_id
        form = EditReporterRegistrationForm(org_id=org_id, existing_email=email, data=request.POST)
        message = None
        if form.is_valid():
            try:
                organization = Organization.objects.get(org_id=org_id)
                response = self._edit_contact(form, manager, organization, reporter_id)

                if response.success:
                    email = form.cleaned_data['email']
                    if email:
                        email = self._send_email_to_datasender(email, org_id, reporter_entity, reporter_id,
                                                               request)

                    self._update_mobile_number_if_trial_organization(form, org_id, organization, reporter_entity)

                    data_sender_name = self._update_name_in_postgres_if_exists(form, reporter_entity)

                    datasender_dict = {'name': data_sender_name, 'mobile_number': form.cleaned_data['telephone_number'],
                                       'geo_code': form.cleaned_data['geo_code'].split(' '),
                                       'location': response.processed_data['l']}
                    update_submission_search_for_datasender_edition(manager, reporter_id, datasender_dict)
                    message = _("Your changes have been saved.")

                    self._update_user_activity_log(form, reporter_entity, reporter_id, request)
                else:
                    form.update_errors(response.errors)

            except MangroveException as exception:
                message = exception.message

        entity_links = {'registered_datasenders_link': reverse("all_datasenders")}

        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))
Exemple #13
0
def create_web_users(org_id, reporter_details, language_code):
    organization = Organization.objects.get(org_id=org_id)
    dbm = get_database_manager_for_org(organization)
    for reporter_id, email in reporter_details.iteritems():
        reporter_entity = contact_by_short_code(dbm, reporter_id)
        reporter_email = email.lower()
        set_email_for_contact(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)
    return json.dumps({'success': True, 'message': "Users has been created"})
Exemple #14
0
def get_name_short_code_mobile_numbers_for_contacts(dbm, poll_recipients,
                                                    failed_numbers):
    short_codes = []
    poll_recipients = ast.literal_eval(poll_recipients)
    mobile_numbers = []
    contact_dict_list = []
    for poll_recipient in poll_recipients:
        contact = contact_by_short_code(dbm, poll_recipient)
        contact_mobile_number = contact.data.get('mobile_number')['value']
        if contact_mobile_number not in failed_numbers:
            mobile_numbers.append(contact.data.get('mobile_number')['value'])
            if contact.name != "":
                contact_dict_list.append("%s (%s)" %
                                         (contact.name, contact.short_code))
            else:
                contact_dict_list.append(
                    "%s (%s)" % (contact.data['mobile_number']['value'],
                                 contact.short_code))
            short_codes.append(contact.short_code)
    return mobile_numbers, contact_dict_list, short_codes
Exemple #15
0
    def _is_request_valid(self, form_model, reporter_id, extra_data):

        try:
            contact = contact_by_short_code(self.dbm, reporter_id)
            project = Project.from_form_model(form_model=form_model)

            if not project.is_open_survey and reporter_id not in project.data_senders:
                return Response(success=False, errors=_create_error("reporter not linked to questionnaire"))

            if form_model.xform:
                return Response(success=False, errors=_create_error("advanced questionnaire not supported"))

            if extra_data:
                return Response(success=False, errors=_create_error("Wrong number of answers"))

            return Response(success=True)

        except FormModelDoesNotExistsException:
            return Response(success=False, errors=_create_error("form_code not valid"))
        except DataObjectNotFound:
            return Response(success=False, errors= _create_error("reporter id not valid"))
Exemple #16
0
def recreate_data_records_for_account_users(database_name):
    try:
        start = time.time()
        organization_setting = OrganizationSetting.objects.get(
            document_store=database_name)
        org_id = organization_setting.organization_id
        account_user_ids = User.objects.filter(ngouserprofile__org_id=org_id,
                                               groups__name__in=[
                                                   "Project Managers",
                                                   "Extended Users",
                                                   "NGO Admins"
                                               ]).values_list('id', flat=True)
        account_user_rep_ids = NGOUserProfile.objects.filter(
            user__id__in=account_user_ids).values_list('reporter_id',
                                                       flat=True)
        dbm = get_db_manager(database_name)

        rows = dbm.database.query(map_all_account_users)
        rep_ids_for_migration = [
            row.key for row in rows if row.key in account_user_rep_ids
        ]

        for rep_id in rep_ids_for_migration:
            reporter_entity = contact_by_short_code(dbm, rep_id)
            _void_existing_data_records(dbm, rep_id)
            reporter_entity.add_data(
                data=_create_data_from_entity(reporter_entity),
                submission={"form_code": "reg"})

        mark_as_completed(database_name)
        logger.info(
            'Time taken (seconds) for migrating {database_name} : {timetaken}'.
            format(database_name=database_name,
                   timetaken=(time.time() - start)))
    except Exception as e:
        logger.exception(
            'Unexpected error while migrating data records for users',
            e.message)
        raise
Exemple #17
0
def update_corresponding_datasender_details(user, ngo_user_profile,
                                            old_phone_number):
    manager = get_database_manager(user)
    reporter_entity = contact_by_short_code(manager,
                                            ngo_user_profile.reporter_id)
    current_phone_number = ngo_user_profile.mobile_phone
    reporter_entity.update_latest_data([('name', user.first_name),
                                        ("mobile_number", current_phone_number)
                                        ])

    datasender_dict = {
        'name': user.first_name,
        'mobile_number': current_phone_number
    }
    update_submission_search_for_datasender_edition(
        manager, ngo_user_profile.reporter_id, datasender_dict)

    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)
Exemple #18
0
 def get_entity(self, dbm):
     return entity.contact_by_short_code(dbm=dbm,
                                         short_code=self.short_code)
Exemple #19
0
def update_datasender_index_by_id(short_code, dbm):
    datasender = contact_by_short_code(dbm, short_code)
    update_datasender_index(datasender, dbm)