Example #1
0
def paginate_web_users(request, domain):
    limit = int(request.GET.get('limit', 10))
    page = int(request.GET.get('page', 1))
    skip = limit * (page - 1)
    query = request.GET.get('query')

    result = (UserES().domain(
        domain).web_users().sort('username.exact').search_string_query(
            query, ["username", "last_name", "first_name"
                    ]).start(skip).size(limit).run())

    web_users = [WebUser.wrap(w) for w in result.hits]
    web_users_fmt = [{
        'email':
        u.get_email(),
        'domain':
        domain,
        'name':
        u.full_name,
        'role':
        u.role_label(domain),
        'phoneNumbers':
        u.phone_numbers,
        'id':
        u.get_id,
        'editUrl':
        reverse('user_account', args=[domain, u.get_id]),
        'removeUrl': (reverse('remove_web_user', args=[domain, u.user_id])
                      if request.user.username != u.username else None),
    } for u in web_users]

    return JsonResponse({
        'users': web_users_fmt,
        'total': result.total,
        'page': page,
        'query': query,
    })
Example #2
0
def get_commcare_users_by_filters(domain, user_filters, count_only=False):
    """
    Returns CommCareUsers in domain per given filters. If user_filters is empty
        returns all users in the domain

    args:
        user_filters: a dict with below structure.
            {'role_id': <Role ID to filter users by>,
             'search_string': <string to search users by username>,
             'location_id': <Location ID to filter users by>}
    kwargs:
        count_only: If True, returns count of search results
    """
    role_id = user_filters.get('role_id', None)
    search_string = user_filters.get('search_string', None)
    location_id = user_filters.get('location_id', None)
    if not any([role_id, search_string, location_id, count_only]):
        return get_all_commcare_users_by_domain(domain)

    query = UserES().domain(domain).mobile_users()

    if role_id:
        query = query.role_id(role_id)
    if search_string:
        query = query.search_string_query(
            search_string,
            default_fields=['first_name', 'last_name', 'username'])
    if location_id:
        location_ids = SQLLocation.objects.get_locations_and_children_ids(
            [location_id])
        query = query.location(location_ids)

    if count_only:
        return query.count()
    user_ids = query.scroll_ids()
    return map(CommCareUser.wrap, iter_docs(CommCareUser.get_db(), user_ids))
Example #3
0
def get_users_created_since_startdate(domain, startdate):
    """
    Had to use created_on because last_modified did not seem to work
    """
    return UserES(for_export=True).mobile_users().domain(domain)\
        .date_range('created_on', gte=startdate).run().hits
Example #4
0
def has_dimagi_user(domain):
    return UserES().web_users().domain(domain).search_string_query(
        '@dimagi.com').count()
Example #5
0
def user_es_call(domain, q, fields, size, start_at):
    query = (UserES().domain(domain).fields(fields).size(size).start(start_at))
    if q is not None:
        query.set_query({"query_string": {"query": q}})
    return query.run().hits
 def _verify_user_in_es(self, username):
     results = UserES().run()
     self.assertEqual(1, results.total)
     user_doc = results.hits[0]
     self.assertEqual(username, user_doc['username'])
Example #7
0
 def user_es_query(self, query):
     search_fields = ["first_name", "last_name", "base_username"]
     return (UserES().domain(self.domain).search_string_query(
         query, default_fields=search_fields))
Example #8
0
 def get_choices_for_known_values(self, values, user):
     user_es = UserES().domain(self.domain).doc_id(values)
     return self.get_choices_from_es_query(user_es)
Example #9
0
def get_user_stubs(user_ids):
    from corehq.apps.reports.util import SimplifiedUserInfo
    return (UserES().user_ids(user_ids).show_inactive().values(
        *SimplifiedUserInfo.ES_FIELDS))
Example #10
0
 def test_chained_metadata_queries_with_only_one_match(self):
     direwolf_families = (UserES()
                          .metadata('sigil', 'direwolf')
                          .metadata('seat', 'Casterly Rock')
                          .values_list('username', flat=True))
     self.assertEqual(direwolf_families, [])
Example #11
0
 def test_chained_metadata_queries_where_both_match(self):
     direwolf_families = (UserES()
                          .metadata('sigil', 'direwolf')
                          .metadata('seat', 'Winterfell')
                          .values_list('username', flat=True))
     self.assertEqual(direwolf_families, ['stark'])
Example #12
0
 def test_basic_metadata_query(self):
     direwolf_families = UserES().metadata('sigil', 'direwolf').values_list('username', flat=True)
     self.assertEqual(direwolf_families, ['stark'])
Example #13
0
 def options(self):
     users = get_simplified_users(UserES().domain(
         self.domain).mobile_users())
     return [(user.user_id, user.username_in_report) for user in users]
Example #14
0
def mobile_user_ids_at_locations(location_ids):
    # this doesn't include web users
    return UserES().location(location_ids).get_ids()
Example #15
0
def get_users_location_ids(domain, user_ids):
    """Get the ids of the locations the users are assigned to"""
    result = (UserES().domain(domain).user_ids(user_ids).non_null(
        'location_id').fields(['location_id']).run())
    return [r['location_id'] for r in result.hits if 'location_id' in r]
Example #16
0
def get_user_stubs(user_ids):
    return (UserES()
        .user_ids(user_ids)
        .show_inactive()
        .values('_id', 'username', 'first_name', 'last_name', 'doc_type', 'is_active'))
Example #17
0
 def users_at_location(self):
     return (UserES().domain(
         self.domain_object.name).mobile_users().location(
             self.location.location_id).get_ids())
def login_as_user_query(domain,
                        couch_user,
                        search_string,
                        limit,
                        offset,
                        user_data_fields=None):
    '''
    Takes in various parameters to determine which users to populate the login as screen.

    :param domain: String domain
    :param couch_user: The CouchUser that is using the Login As feature
    :param search_string: The query that filters the users returned. Filters based on the
        `search_fields` as well as any fields defined in `user_data_fields`.
    :param limit: The max amount of users returned.
    :param offset: From where to start the query.
    :param user_data_fields: A list of custom user data fields that should also be searched
        by the `search_string`

    :returns: An EsQuery instance.
    '''
    search_fields = [
        "base_username", "last_name", "first_name", "phone_numbers"
    ]

    should_criteria_query = [
        queries.search_string_query(search_string, search_fields),
    ]

    if user_data_fields:
        or_criteria = []
        for field in user_data_fields:
            or_criteria.append(
                filters.AND(
                    filters.term('user_data_es.key', field),
                    filters.term('user_data_es.value', search_string),
                ), )

        should_criteria_query.append(
            queries.nested_filter('user_data_es', filters.OR(*or_criteria)))

    user_es = (
        UserES().domain(domain).start(offset).size(limit).
        sort('username.exact').set_query(
            queries.BOOL_CLAUSE(
                queries.SHOULD_CLAUSE(
                    should_criteria_query,
                    # It should either match on the search fields like username or it
                    # should match on the custom user data fields. If this were 2, then
                    # it would require the search string to match both on the search fields and
                    # the custom user data fields.
                    minimum_should_match=1,
                ), )))

    if not couch_user.has_permission(domain, 'access_all_locations'):
        loc_ids = SQLLocation.objects.accessible_to_user(
            domain, couch_user).location_ids()
        user_es = user_es.location(list(loc_ids))

    if not couch_user.has_permission(
            domain, get_permission_name(Permissions.login_as_all_users)):
        user_es = user_es.filter(
            filters.nested(
                'user_data_es',
                filters.AND(
                    filters.term('user_data_es.key', 'login_as_user'),
                    filters.term('user_data_es.value', couch_user.username),
                )))
    return user_es.mobile_users()
Example #19
0
 def _iter_active_user_ids(self, groups):
     all_user_ids = {user_id for group in groups for user_id in group.users}
     for user_ids_chunk in chunked(all_user_ids, 1000):
         yield from (UserES().domain(self.domain).user_ids(
             user_ids_chunk).is_active(True).values_list('_id', flat=True))
Example #20
0
def get_user_stubs(user_ids, extra_fields=None):
    from corehq.apps.reports.util import SimplifiedUserInfo
    return (UserES().user_ids(user_ids).show_inactive().values(
        *SimplifiedUserInfo.ES_FIELDS, *(extra_fields or [])))
Example #21
0
def get_practice_mode_mobile_workers(domain):
    """
    Returns list of practice mode mobile workers formatted for HTML select
    """
    return (UserES().domain(domain).mobile_users().is_practice_user().fields(
        ['_id', 'username']).run().hits)
Example #22
0
 def users_at_location(self):
     user_query = (UserES().domain(
         self.domain_object.name).mobile_users().location(
             self.location.location_id).fields([]))
     return user_query.run().doc_ids
    def rendered_content(self):
        from corehq.apps.users.views.mobile.users import EditCommCareUserView
        users = get_users_by_location_id(self.config['domain'],
                                         self.config['location_id'])
        in_charges = FacilityInCharge.objects.filter(
            location=self.location).values_list('user_id', flat=True)
        if self.location.parent.location_type.name == 'district':
            children = self.location.parent.get_descendants()
            availaible_in_charges = list(
                chain.from_iterable([
                    filter(
                        lambda u: 'In Charge' in u.user_data.get('role', []),
                        get_users_by_location_id(self.config['domain'],
                                                 child.location_id))
                    for child in children
                ]))
        else:
            availaible_in_charges = filter(
                lambda u: 'In Charge' in u.user_data.get('role', []),
                get_users_by_location_id(self.domain, self.location_id))
        user_to_dict = lambda sms_user: {
            'id':
            sms_user.get_id,
            'full_name':
            sms_user.full_name,
            'phone_numbers':
            sms_user.phone_numbers,
            'in_charge':
            sms_user.get_id in in_charges,
            'location_name':
            sms_user.location.sql_location.name,
            'url':
            reverse(EditCommCareUserView.urlname,
                    args=[self.config['domain'], sms_user.get_id])
        }

        web_users_from_extension = list(
            iter_docs(
                WebUser.get_db(),
                EWSExtension.objects.filter(
                    domain=self.domain,
                    location_id=self.location_id).values_list('user_id',
                                                              flat=True)))

        WebUserInfo = collections.namedtuple('WebUserInfo',
                                             'id first_name last_name email')

        web_users = {
            WebUserInfo(id=web_user['_id'],
                        first_name=web_user['first_name'],
                        last_name=web_user['last_name'],
                        email=web_user['email'])
            for web_user in (UserES().web_users().domain(
                self.config['domain']).term("domain_memberships.location_id",
                                            self.location_id).run().hits +
                             web_users_from_extension)
        }

        return render_to_string(
            'ewsghana/partials/users_tables.html', {
                'users': [user_to_dict(user) for user in users],
                'domain':
                self.domain,
                'location_id':
                self.location_id,
                'web_users':
                web_users,
                'district_in_charges':
                [user_to_dict(user) for user in availaible_in_charges]
            })
Example #24
0
 def already_have_locations(self, users):
     user_query = (UserES().domain(
         self.domain_object.name).mobile_users().doc_id(
             list(users)).exists('location_id').fields(['username']))
     return [raw_username(u['username']) for u in user_query.run().hits]
Example #25
0
 def obj_get_list(self, bundle, **kwargs):
     if 'username' in bundle.request.GET:
         return [WebUser.get_by_username(bundle.request.GET['username'])]
     return [WebUser.wrap(u) for u in UserES().web_users().run().hits]
Example #26
0
def user_ids_at_locations(location_ids):
    return UserES().location(location_ids).get_ids()
Example #27
0
 def user_query(self):
     user_query = UserES().domain(self.domain).filter(mobile_users())
     locations_id = self.locations_id
     if locations_id:
         user_query = user_query.location(locations_id)
     return user_query
Example #28
0
def get_role_user_count(domain, role_id):
    from corehq.apps.es.users import UserES
    return UserES().is_active().domain(domain).role_id(role_id).count()