示例#1
0
def user_domain_transfer(request, domain, prescription, template="users/domain_transfer.html"):
    target_domain = prescription.params["target_domain"]
    if not request.couch_user.is_domain_admin(target_domain):
        return HttpResponseForbidden()
    if request.method == "POST":
        user_ids = request.POST.getlist("user_id")
        app_id = request.POST["app_id"]
        errors = []
        for user_id in user_ids:
            user = CommCareUser.get_by_user_id(user_id, domain)
            try:
                user.transfer_to_domain(target_domain, app_id)
            except Exception as e:
                errors.append((user_id, user, e))
            else:
                messages.success(request, "Successfully transferred {user.username}".format(user=user))
        if errors:
            messages.error(request, "Failed to transfer the following users")
            for user_id, user, e in errors:
                if user:
                    messages.error(request, "{user.username} ({user.user_id}): {e}".format(user=user, e=e))
                else:
                    messages.error(request, "CommCareUser {user_id} not found".format(user_id=user_id))
        return HttpResponseRedirect(reverse("commcare_users", args=[target_domain]))
    else:
        from corehq.apps.app_manager.models import VersionedDoc

        # apps from the *target* domain
        apps = VersionedDoc.view("app_manager/applications_brief", startkey=[target_domain], endkey=[target_domain, {}])
        # users from the *originating* domain
        users = list(CommCareUser.by_domain(domain))
        users.extend(CommCareUser.by_domain(domain, is_active=False))
        context = _users_context(request, domain)
        context.update({"apps": apps, "commcare_users": users, "target_domain": target_domain})
        return render(request, template, context)
示例#2
0
def user_list(domain):
    #todo cleanup
    #referenced in filters.users.SelectMobileWorkerFilter
    users = list(CommCareUser.by_domain(domain))
    users.extend(CommCareUser.by_domain(domain, is_active=False))
    users.sort(key=lambda user: (not user.is_active, user.username))
    return users
示例#3
0
def commcare_users(request, domain, template="users/commcare_users.html"):
    show_inactive = json.loads(request.GET.get('show_inactive', 'false'))
    sort_by = request.GET.get('sortBy', 'abc')
    cannot_share = json.loads(request.GET.get('cannot_share', 'false'))
    show_more_columns = request.GET.get('show_more_columns') is not None
    context = _users_context(request, domain)
    if cannot_share:
        users = CommCareUser.cannot_share(domain)
    else:
        users = CommCareUser.by_domain(domain)
        if show_inactive:
            users.extend(CommCareUser.by_domain(domain, is_active=False))

    if sort_by == 'forms':
        users.sort(key=lambda user: -user.form_count)

    context.update({
        'commcare_users': users,
        'groups': Group.get_case_sharing_groups(domain),
        'show_case_sharing': request.project.case_sharing_included(),
        'show_inactive': show_inactive,
        'cannot_share': cannot_share,
        'show_more_columns': show_more_columns or cannot_share,
    })
    return render_to_response(request, template, context)
示例#4
0
    def test_create(self):
        self.client.login(username=self.username, password=self.password)

        group = Group({"name": "test"})
        group.save()

        self.assertEqual(0, len(CommCareUser.by_domain(self.domain.name)))

        user_json = {
            "username": "******",
            "password": "******",
            "first_name": "John",
            "last_name": "Doe",
            "email": "*****@*****.**",
            "language": "en",
            "phone_numbers": ["+50253311399", "50253314588"],
            "groups": [group._id],
            "user_data": {"chw_id": "13/43/DFA"},
        }
        response = self.client.post(self.list_endpoint, json.dumps(user_json), content_type="application/json")
        self.assertEqual(response.status_code, 201)
        [user_back] = CommCareUser.by_domain(self.domain.name)
        self.assertEqual(user_back.username, "jdoe")
        self.assertEqual(user_back.first_name, "John")
        self.assertEqual(user_back.last_name, "Doe")
        self.assertEqual(user_back.email, "*****@*****.**")
        self.assertEqual(user_back.language, "en")
        self.assertEqual(user_back.get_group_ids()[0], group._id)
        self.assertEqual(user_back.user_data["chw_id"], "13/43/DFA")
        self.assertEqual(user_back.default_phone_number, "50253311399")
        user_back.delete()
        group.delete()
示例#5
0
def user_list(domain):
    #todo cleanup
    #referenced in fields -> SelectMobileWorkerField
    users = list(CommCareUser.by_domain(domain))
    users.extend(CommCareUser.by_domain(domain, is_active=False))
    users.sort(key=lambda user: (not user.is_active, user.username))
    return users
示例#6
0
def get_all_users_by_domain(domain=None, group=None, user_ids=None,
                            user_filter=None, simplified=False, CommCareUser=None, include_inactive=False):
    """
        WHEN THERE ARE A LOT OF USERS, THIS IS AN EXPENSIVE OPERATION.
        Returns a list of CommCare Users based on domain, group, and user 
        filter (demo_user, admin, registered, unknown)
    """
    user_ids = user_ids if user_ids and user_ids[0] else None
    if not CommCareUser:
        from corehq.apps.users.models import CommCareUser

    if group:
        # get all the users only in this group and don't bother filtering.
        if not isinstance(group, Group):
            group = Group.get(group)
        users = group.get_users(is_active=(not include_inactive), only_commcare=True)
    elif user_ids is not None:
        try:
            users = [CommCareUser.get_by_user_id(id) for id in user_ids]
        except Exception:
            users = []
        if users and users[0] is None:
            raise Http404()
    else:
        if not user_filter:
            user_filter = HQUserType.all()
        users = []
        submitted_user_ids = get_all_user_ids_submitted(domain)
        registered_user_ids = dict([(user.user_id, user) for user in CommCareUser.by_domain(domain)])
        if include_inactive:
            registered_user_ids.update(dict([(u.user_id, u) for u in CommCareUser.by_domain(domain, is_active=False)]))
        for user_id in submitted_user_ids:
            if user_id in registered_user_ids and user_filter[HQUserType.REGISTERED].show:
                user = registered_user_ids[user_id]
                users.append(user)
            elif not user_id in registered_user_ids and \
                 (user_filter[HQUserType.ADMIN].show or
                  user_filter[HQUserType.DEMO_USER].show or
                  user_filter[HQUserType.UNKNOWN].show):
                username = get_username_from_forms(domain, user_id).lower()
                temp_user = TempCommCareUser(domain, username, user_id)
                if user_filter[temp_user.filter_flag].show:
                    users.append(temp_user)
        if user_filter[HQUserType.UNKNOWN].show:
            users.append(TempCommCareUser(domain, '*', None))

        if user_filter[HQUserType.REGISTERED].show:
            # now add all the registered users who never submitted anything
            for user_id in registered_user_ids:
                if not user_id in submitted_user_ids:
                    user = CommCareUser.get_by_user_id(user_id)
                    users.append(user)

    if simplified:
        return [_report_user_dict(user) for user in users]
    return users
示例#7
0
def get_all_users_by_domain(domain=None, group=None, user_ids=None,
                            user_filter=None, simplified=False, CommCareUser=None, include_inactive=False):
    """
        WHEN THERE ARE A LOT OF USERS, THIS IS AN EXPENSIVE OPERATION.
        Returns a list of CommCare Users based on domain, group, and user 
        filter (demo_user, admin, registered, unknown)
    """
    user_ids = user_ids if user_ids and user_ids[0] else None
    if not CommCareUser:
        from corehq.apps.users.models import CommCareUser

    if group:
        # get all the users only in this group and don't bother filtering.
        if not isinstance(group, Group):
            group = Group.get(group)
        users = group.get_users(only_commcare=True)
    elif user_ids is not None:
        try:
            users = [CommCareUser.get_by_user_id(id) for id in user_ids]
        except Exception:
            users = []
        if users and users[0] is None:
            raise Http404()
    else:
        if not user_filter:
            user_filter = HQUserType.all()
        users = []
        submitted_user_ids = get_all_userids_submitted(domain)
        registered_user_ids = dict([(user.user_id, user) for user in CommCareUser.by_domain(domain)])
        if include_inactive:
            registered_user_ids.update(dict([(u.user_id, u) for u in CommCareUser.by_domain(domain, is_active=False)]))
        for user_id in submitted_user_ids:
            if user_id in registered_user_ids and user_filter[HQUserType.REGISTERED].show:
                user = registered_user_ids[user_id]
                users.append(user)
            elif not user_id in registered_user_ids and \
                 (user_filter[HQUserType.ADMIN].show or
                  user_filter[HQUserType.DEMO_USER].show or
                  user_filter[HQUserType.UNKNOWN].show):
                username = get_username_from_forms(domain, user_id)
                temp_user = TempCommCareUser(domain, username, user_id)
                if user_filter[temp_user.filter_flag].show:
                    users.append(temp_user)
        if user_filter[HQUserType.UNKNOWN].show:
            users.append(TempCommCareUser(domain, '*', None))

        if user_filter[HQUserType.REGISTERED].show:
            # now add all the registered users who never submitted anything
            for user_id in registered_user_ids:
                if not user_id in submitted_user_ids:
                    user = CommCareUser.get_by_user_id(user_id)
                    users.append(user)

    if simplified:
        return [_report_user_dict(user) for user in users]
    return users
示例#8
0
 def mobile_worker_ids(self):
     ids = self.request.GET.getlist('select_mw')
     if '_all' in ids or self.request.GET.get('all_mws', 'off') == 'on':
         cache_str = "mw_ids:%s" % self.domain
         ids = cache.get(cache_str)
         if not ids:
             cc_users = CommCareUser.by_domain(self.domain)
             if self.include_inactive:
                 cc_users += CommCareUser.by_domain(self.domain, is_active=False)
             ids = [ccu._id for ccu in cc_users]
             cache.set(cache_str, ids, 24*60*60)
     return ids
示例#9
0
 def mobile_worker_ids(self):
     ids = self.request.GET.getlist('select_mw')
     if '_all' in ids or self.request.GET.get('all_mws', 'off') == 'on':
         cache_str = "mw_ids:%s" % self.domain
         ids = cache.get(cache_str)
         if not ids:
             cc_users = CommCareUser.by_domain(self.domain)
             if self.include_inactive:
                 cc_users += CommCareUser.by_domain(self.domain, is_active=False)
             ids = [ccu._id for ccu in cc_users]
             cache.set(cache_str, ids, 24*60*60)
     return ids
示例#10
0
 def mobile_worker_ids(self):
     ids = self.request.GET.getlist("select_mw")
     if "_all" in ids or self.request.GET.get("all_mws", "off") == "on":
         cache_str = "mw_ids:%s" % self.domain
         ids = cache.get(cache_str)
         if not ids:
             cc_users = CommCareUser.by_domain(self.domain)
             if self.include_inactive:
                 cc_users += CommCareUser.by_domain(self.domain, is_active=False)
             ids = [ccu._id for ccu in cc_users]
             cache.set(cache_str, ids, 24 * 60 * 60)
     return ids
示例#11
0
def user_domain_transfer(request,
                         domain,
                         prescription,
                         template="users/domain_transfer.html"):
    target_domain = prescription.params['target_domain']
    if not request.couch_user.is_domain_admin(target_domain):
        return HttpResponseForbidden()
    if request.method == "POST":
        user_ids = request.POST.getlist('user_id')
        app_id = request.POST['app_id']
        errors = []
        for user_id in user_ids:
            user = CommCareUser.get_by_user_id(user_id, domain)
            try:
                user.transfer_to_domain(target_domain, app_id)
            except Exception as e:
                errors.append((user_id, user, e))
            else:
                messages.success(
                    request, "Successfully transferred {user.username}".format(
                        user=user))
        if errors:
            messages.error(request, "Failed to transfer the following users")
            for user_id, user, e in errors:
                if user:
                    messages.error(
                        request,
                        "{user.username} ({user.user_id}): {e}".format(
                            user=user, e=e))
                else:
                    messages.error(
                        request, "CommCareUser {user_id} not found".format(
                            user_id=user_id))
        return HttpResponseRedirect(
            reverse('commcare_users', args=[target_domain]))
    else:
        from corehq.apps.app_manager.models import VersionedDoc
        # apps from the *target* domain
        apps = VersionedDoc.view('app_manager/applications_brief',
                                 startkey=[target_domain],
                                 endkey=[target_domain, {}])
        # users from the *originating* domain
        users = list(CommCareUser.by_domain(domain))
        users.extend(CommCareUser.by_domain(domain, is_active=False))
        context = _users_context(request, domain)
        context.update({
            'apps': apps,
            'commcare_users': users,
            'target_domain': target_domain
        })
        return render(request, template, context)
示例#12
0
def get_group_params(domain, group='', users=None, user_id_only=False, **kwargs):
    # refrenced in reports/views and create_export_filter below
    if group:
        if not isinstance(group, Group):
            group = Group.get(group)
        users = group.get_user_ids() if user_id_only else group.get_users()
    else:
        users = users or []
        if user_id_only:
            users = users or [user.user_id for user in CommCareUser.by_domain(domain)]
        else:
            users = [CommCareUser.get_by_user_id(userID) for userID in users] or CommCareUser.by_domain(domain)
    if not user_id_only:
        users = sorted(users, key=lambda user: user.user_id)
    return group, users
示例#13
0
def get_group_params(domain, group='', users=None, user_id_only=False, **kwargs):
    # refrenced in reports/views and create_export_filter below
    if group:
        if not isinstance(group, Group):
            group = Group.get(group)
        users = group.get_user_ids() if user_id_only else group.get_users()
    else:
        users = users or []
        if user_id_only:
            users = users or [user.user_id for user in CommCareUser.by_domain(domain)]
        else:
            users = [CommCareUser.get_by_user_id(userID) for userID in users] or CommCareUser.by_domain(domain)
    if not user_id_only:
        users = sorted(users, key=lambda user: user.user_id)
    return group, users
示例#14
0
def second_soh_reminder():
    domains = EWSGhanaConfig.get_all_enabled_domains()
    for domain in domains:
        for user in CommCareUser.by_domain(domain):
            roles = user.user_data.get('role')
            if roles and IN_CHARGE_ROLE in roles:
                second_soh_process_user(user)
示例#15
0
def group_members(request,
                  domain,
                  group_id,
                  template="groups/group_members.html"):
    context = _users_context(request, domain)
    all_groups = _get_sorted_groups(domain)
    try:
        group = Group.get(group_id)
    except ResourceNotFound:
        raise Http404("Group %s does not exist" % group_id)
    member_ids = group.get_user_ids()
    members = CouchUser.view("_all_docs", keys=member_ids,
                             include_docs=True).all()
    members.sort(key=lambda user: user.username)
    all_users = CommCareUser.by_domain(domain)
    member_ids = set(member_ids)
    nonmembers = [user for user in all_users if user.user_id not in member_ids]

    context.update({
        "domain": domain,
        "group": group,
        "all_groups": all_groups,
        "members": members,
        "nonmembers": nonmembers,
    })
    return render(request, template, context)
示例#16
0
def send_ror_reminder(domain, date, loc_type='FACILITY', test_list=None):
    if loc_type == 'FACILITY':
        status_type = SupplyPointStatusTypes.R_AND_R_FACILITY
        sms_text = REMINDER_R_AND_R_FACILITY
    elif loc_type == 'DISTRICT':
        status_type = SupplyPointStatusTypes.R_AND_R_DISTRICT
        sms_text = REMINDER_R_AND_R_DISTRICT
    else:
        return
    current_group = DeliveryGroups().current_submitting_group(date.month)
    sp_ids = set()
    users = CommCareUser.by_domain(domain) if not test_list else test_list
    for user in users:
        location = user.location
        if user.is_active and location and location.location_type == loc_type:
            status_exists = SupplyPointStatus.objects.filter(
                location_id=location._id,
                status_type=status_type,
                status_date__gte=date).exists()
            if current_group in location.metadata.get(
                    'group', None) and not status_exists:
                result = send_translated_message(user, sms_text)
                if not test_list and result:
                    sp_ids.add(location._id)

    update_statuses(sp_ids, status_type, SupplyPointStatusValues.REMINDER_SENT)
示例#17
0
 def _send_submission_alert_to_msd(self, params):
     users = filter(lambda u: u.user_data.get('role', None) == 'MSD', CommCareUser.by_domain(self.domain))
     for user in users:
         if not user.get_verified_number():
             continue
         with localize(user.get_language_code()):
             send_sms_to_verified_number(user.get_verified_number(), SUBMITTED_NOTIFICATION_MSD % params)
示例#18
0
    def rows(self):
        group_id = self.request.GET.get("group", None)
        month = self.request.GET.get("month", None)
        year = self.request.GET.get("year", None)
        curval = float(self.request.GET.get("curval", 1.0))
        curname = self.request.GET.get("curname", "MK")

        if not (month and year):
            return []

        rows = []
        if group_id:
            group = Group.get(group_id)
            users = group.users
        else:
            users = CommCareUser.by_domain(self.domain)

        for user in users:
            row = []
            lg = LendingGroupAggregate(user.full_name, [user._id], month, year,
                                       curval, curname)
            for v in self.columns:
                try:
                    if v[1]:
                        row.append(getattr(lg, v[1]))
                    else:
                        row.append('-')
                except TypeError:
                    row.append('-')
            rows.append(row)

        return rows
 def handle(self, domain, indicator, startdate, enddate, **options):
     self.datespan = DateSpan(startdate, enddate)
     self.domain = domain
     self.user_ids = [
         user.user_id for user in CommCareUser.by_domain(self.domain)
     ]
     self.get_indicator_response(indicator)
示例#20
0
def second_soh_reminder():
    domains = EWSGhanaConfig.get_all_enabled_domains()
    for domain in domains:
        for user in CommCareUser.by_domain(domain):
            roles = user.user_data.get('role')
            if roles and IN_CHARGE_ROLE in roles:
                second_soh_process_user(user)
示例#21
0
 def handle(self, *args, **options):
     users = CommCareUser.by_domain('icds-cas')
     web_users = WebUser.by_domain('icds-cas')
     users = users + web_users
     user_details = self._get_details(users)
     usernames_list = list(user_details.keys())
     chunk_size = 100
     headers = ["username", "last_access_time", "created_on", "role"]
     rows = [headers]
     usernames_usage = set()
     for user_chunk in chunked(usernames_list, chunk_size):
         usage_data = ICDSAuditEntryRecord.objects.filter(
             username__in=list(user_chunk)).values('username').annotate(
                 time=Max('time_of_use'))
         for usage in usage_data:
             row_data = [
                 usage['username'],
                 self.convert_to_ist(usage['time']),
                 self.convert_to_ist(user_details[usage['username']][0]),
                 user_details[usage['username']][1]
             ]
             usernames_usage.add(usage['username'])
             rows.append(row_data)
     users_not_logged_in = set(usernames_list) - usernames_usage
     for user in users_not_logged_in:
         rows.extend([
             user, 'N/A',
             self.convert_to_ist(user_details[usage['username']][0]),
             user_details[usage['username']][1]
         ])
     fout = open('/home/cchq/National_users_usage_data.csv', 'w')
     writer = csv.writer(fout)
     writer.writerows(rows)
示例#22
0
def third_soh_to_super():
    domains = EWSGhanaConfig.get_all_enabled_domains()
    for domain in domains:
        facilities = SQLLocation.objects.filter(
            location_type__name__in=reporting_types(domain))
        users = CommCareUser.by_domain(domain)
        third_soh_process_users_and_facilities(users, facilities)
示例#23
0
 def _send_submission_alert_to_msd(self, params):
     users = [
         u for u in CommCareUser.by_domain(self.domain)
         if u.user_data.get('role', None) == 'MSD'
     ]
     for user in users:
         send_translated_message(user, SUBMITTED_NOTIFICATION_MSD, **params)
示例#24
0
def explode_cases(request, domain, template="hqcase/explode_cases.html"):
    if request.method == 'POST':
        user_id = request.POST['user_id']
        user = CommCareUser.get_by_user_id(user_id, domain)
        factor = request.POST.get('factor', '2')
        try:
            factor = int(factor)
        except ValueError:
            messages.error(request, 'factor must be an int; was: %s' % factor)
        else:
            keys = [[domain, owner_id, False] for owner_id in user.get_owner_ids()]
            for case in CommCareCase.view('hqcase/by_owner',
                keys=keys,
                include_docs=True,
                reduce=False
            ):
                # we'll be screwing with this guy, so make him unsaveable
                case.save = None
                for i in range(factor - 1):

                    case._id = uuid.uuid4().hex
                    case_block = get_case_xml(case, (const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE), version='2.0')
                    submit_case_blocks(case_block, domain)
            messages.success(request, "All of %s's cases were exploded by a factor of %d" % (user.raw_username, factor))

    return render(request, template, {
        'domain': domain,
        'users': CommCareUser.by_domain(domain),
    })
示例#25
0
def second_soh_reminder():
    now = datetime.datetime.utcnow()
    date = now - datetime.timedelta(days=DAYS_UNTIL_LATE)
    domains = EWSGhanaConfig.get_all_enabled_domains()
    for domain in domains:
        for user in CommCareUser.by_domain(domain):
            second_soh_process_user(user, date)
示例#26
0
 def _send_delivery_alert_to_facilities(self, sp_name, location):
     locs = [c._id for c in location.children]
     users = filter(lambda u: u.location_id in locs, CommCareUser.by_domain(self.domain))
     for user in users:
         if user.get_verified_number():
             send_sms_to_verified_number(user.get_verified_number(), DELIVERY_CONFIRM_CHILDREN %
                                         {"district_name": sp_name})
示例#27
0
def first_soh_reminder():
    domains = EWSGhanaConfig.get_all_enabled_domains()
    for domain in domains:
        for user in CommCareUser.by_domain(domain):
            role = user.user_data.get('role')
            if role and role != IN_CHARGE_ROLE:
                first_soh_process_user(user)
示例#28
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        domain = kwargs.pop('domain', None)
        super(DomainMetadataForm, self).__init__(*args, **kwargs)
        if not (user and user.is_previewer):
            # commtrack is pre-release
            self.fields['commtrack_enabled'].widget = forms.HiddenInput()
            self.fields['call_center_enabled'].widget = forms.HiddenInput()
            self.fields['call_center_case_owner'].widget = forms.HiddenInput()
            self.fields['call_center_case_type'].widget = forms.HiddenInput()

        if not (user and user.is_staff):
            self.fields['restrict_superusers'].widget = forms.HiddenInput()

        if domain is not None:
            groups = Group.get_case_sharing_groups(domain)
            users = CommCareUser.by_domain(domain)

            domain_group_choices = [(group._id, group.name) for group in groups]
            domain_user_choices = [(user._id, user.raw_username) for user in users]
            domain_owner_choices = domain_group_choices + domain_user_choices

            self.fields["sms_case_registration_owner_id"].choices = domain_owner_choices
            self.fields["sms_case_registration_user_id"].choices = domain_user_choices

            call_center_user_choices = [(user._id, user.name + ' (user)')
                                         for user in users]
            call_center_group_choices = [(group._id, group.name + ' (group)')
                                         for group in groups]

            self.fields["call_center_case_owner"].choices = \
                [('', '')] + \
                call_center_user_choices + \
                call_center_group_choices
示例#29
0
def explode_cases(request, domain, template="hqcase/explode_cases.html"):
    if request.method == 'POST':
        user_id = request.POST['user_id']
        user = CommCareUser.get_by_user_id(user_id, domain)
        factor = request.POST.get('factor', '2')
        try:
            factor = int(factor)
        except ValueError:
            messages.error(request, 'factor must be an int; was: %s' % factor)
        else:
            keys = [[domain, owner_id, False] for owner_id in user.get_owner_ids()]
            for case in CommCareCase.view('hqcase/by_owner',
                keys=keys,
                include_docs=True,
                reduce=False
            ):
                for i in range(factor - 1):
                    new_case_id = uuid.uuid4().hex
                    case_block, attachments = make_creating_casexml(case, new_case_id)
                    submit_case_blocks(case_block, domain, attachments=attachments)

            messages.success(request, "All of %s's cases were exploded by a factor of %d" % (user.raw_username, factor))

    return render(request, template, {
        'domain': domain,
        'users': CommCareUser.by_domain(domain),
    })
示例#30
0
 def update_context(self):
     results = CommCareUser.by_domain('pathfinder')
     self.context['names'] = {}
     for result in results:
         self.context['names'].update(
             {result.username_in_report: result.get_id})
     self.context['provider'] = self.request.GET.get('user', None)
示例#31
0
    def test(self, existing_users_mock):
        # starting off, no users
        self.assertUserState(active=[], inactive=[])

        # turning it on should make users for the existing counties
        existing_users_mock.return_value = {}
        county = self.location_types['county']
        county.has_user = True
        county.save()
        self.assertUserState(active=['middlesex', 'suffolk'], inactive=[])

        # add a location, it should auto create a user
        self.submit_form('Essex')
        self.assertUserState(active=['middlesex', 'suffolk', 'essex'], inactive=[])

        # turning it off should inactivate location users
        county = LocationType.objects.get(pk=county.pk)
        county.has_user = False
        county.save()
        self.assertUserState(active=[], inactive=['middlesex', 'suffolk', 'essex'])

        # add a location, it shouldn't create a user
        self.submit_form('Worcester')
        self.assertUserState(active=[], inactive=['middlesex', 'suffolk', 'essex'])

        # turning it back on should reactivate the previous users and create a
        # new user for Worcester
        existing_users_mock.return_value = {
            user.user_location_id: user for user in
            CommCareUser.by_domain(self.domain, is_active=False)
        }
        county = self.location_types['county']
        county.has_user = True
        county.save()
        self.assertUserState(active=['middlesex', 'suffolk', 'essex', 'worcester'], inactive=[])
示例#32
0
def get_user_data_set():
    users = CommCareUser.by_domain(DOMAIN)
    return {
        'blocks': sorted(list(set(u.user_data.get('block') for u in users))),
        'awcs': sorted(list(set(u.user_data.get('awc') for u in users))),
        'gp': sorted(list(set(u.user_data.get('gp') for u in users))),
    }
示例#33
0
    def __init__(self, *args, **kwargs):
        domain = kwargs.pop('domain', None)
        self.can_use_custom_logo = kwargs.pop('can_use_custom_logo', False)
        super(DomainGlobalSettingsForm, self).__init__(*args, **kwargs)
        if not self.can_use_custom_logo:
            del self.fields['logo']
            del self.fields['delete_logo']

        if domain:
            if not CALLCENTER.enabled(domain):
                self.fields['call_center_enabled'].widget = forms.HiddenInput()
                self.fields['call_center_case_owner'].widget = forms.HiddenInput()
                self.fields['call_center_case_type'].widget = forms.HiddenInput()
            else:
                groups = Group.get_case_sharing_groups(domain)
                users = CommCareUser.by_domain(domain)

                call_center_user_choices = [
                    (user._id, user.raw_username + ' [user]') for user in users
                ]
                call_center_group_choices = [
                    (group._id, group.name + ' [group]') for group in groups
                ]

                self.fields["call_center_case_owner"].choices = \
                    [('', '')] + \
                    call_center_user_choices + \
                    call_center_group_choices
示例#34
0
def on_going_non_reporting():
    now = datetime.datetime.utcnow()
    date = now - datetime.timedelta(days=21)
    domains = EWSGhanaConfig.get_all_enabled_domains()

    for domain in domains:
        for user in CommCareUser.by_domain(domain):
            try:
                user_location = SQLLocation.objects.get(domain=domain, location_id=user.location._id)
            except AttributeError:
                continue
            if user_location:
                facilities = []
                if user_location.location_type == 'district':
                    facilities = user_location.get_children()
                elif user_location.location_type == 'region':
                    facilities = SQLLocation.objects.filter(domain=domain,
                                                            parent__parent__location_id=user.location._id)
                fac = set()
                for facility in facilities:
                    sp = facility.supply_point_id
                    if sp and not StockTransaction.objects.filter(
                            case_id=sp, type="stockonhand", report__date__gte=date).exists():
                        fac.add(str(facility.name))
                if fac and user.get_verified_number():
                    message = ONGOING_NON_REPORTING % " \n".join(fac)
                    send_sms_to_verified_number(user.get_verified_number(), message)
                    if user.email:
                        email = str(user.email)
                        send_mail('ONGOING NON REPORTING', message, '*****@*****.**', [email])
示例#35
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        domain = kwargs.pop('domain', None)
        super(DomainMetadataForm, self).__init__(*args, **kwargs)
        if not (user and user.is_previewer):
            # commtrack is pre-release
            self.fields['commtrack_enabled'].widget = forms.HiddenInput()
            self.fields['call_center_enabled'].widget = forms.HiddenInput()
            self.fields['call_center_case_owner'].widget = forms.HiddenInput()
            self.fields['call_center_case_type'].widget = forms.HiddenInput()

        if domain is not None:
            groups = Group.get_case_sharing_groups(domain)
            users = CommCareUser.by_domain(domain)

            domain_group_choices = [(group._id, group.name) for group in groups]
            domain_user_choices = [(user._id, user.raw_username) for user in users]
            domain_owner_choices = domain_group_choices + domain_user_choices

            self.fields["sms_case_registration_owner_id"].choices = domain_owner_choices
            self.fields["sms_case_registration_user_id"].choices = domain_user_choices

            call_center_user_choices = [(user._id, user.name + ' (user)')
                                         for user in users]
            call_center_group_choices = [(group._id, group.name + ' (group)')
                                         for group in groups]

            self.fields["call_center_case_owner"].choices = \
                [('','')] + \
                call_center_user_choices + \
                call_center_group_choices
示例#36
0
 def test_migration(self):
     bootstrap_domain(ILSGatewayAPI(TEST_DOMAIN, MockEndpoint('http://test-api.com/', 'dummy', 'dummy')))
     self.assertEqual(6, len(list(Product.by_domain(TEST_DOMAIN))))
     self.assertEqual(5, len(list(Location.by_domain(TEST_DOMAIN))))
     self.assertEqual(6, len(list(CommCareUser.by_domain(TEST_DOMAIN))))
     self.assertEqual(5, len(list(WebUser.by_domain(TEST_DOMAIN))))
     self.assertEqual(ILSMigrationStats.objects.filter(domain=TEST_DOMAIN).count(), 1)
示例#37
0
def add_survey(request, domain, survey_id=None):
    survey = None
    if survey_id is not None:
        survey = Survey.get(survey_id)
    
    if request.method == "POST":
        form = SurveyForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            waves = form.cleaned_data.get("waves")
            followups = form.cleaned_data.get("followups")
            samples = form.cleaned_data.get("samples")
            send_automatically = form.cleaned_data.get("send_automatically")
            send_followup = form.cleaned_data.get("send_followup")
            
            if survey is None:
                survey = Survey (
                    domain = domain,
                    name = name,
                    waves = waves,
                    followups = followups,
                    samples = samples,
                    send_automatically = send_automatically,
                    send_followup = send_followup
                )
            else:
                survey.name = name
                survey.waves = waves
                survey.followups = followups
                survey.samples = samples
                survey.send_automatically = send_automatically
                survey.send_followup = send_followup
            survey.save()
            return HttpResponseRedirect(reverse("survey_list", args=[domain]))
    else:
        initial = {}
        if survey is not None:
            initial["name"] = survey.name
            initial["waves"] = survey.waves
            initial["followups"] = survey.followups
            initial["samples"] = survey.samples
            initial["send_automatically"] = survey.send_automatically
            initial["send_followup"] = survey.send_followup
        form = SurveyForm(initial=initial)
    
    form_list = get_form_list(domain)
    form_list.insert(0, {"code":"--choose--", "name":"-- Choose --"})
    sample_list = get_sample_list(domain)
    sample_list.insert(0, {"code":"--choose--", "name":"-- Choose --"})
    
    context = {
        "domain" : domain,
        "survey_id" : survey_id,
        "form" : form,
        "form_list" : form_list,
        "sample_list" : sample_list,
        "method_list" : SURVEY_METHOD_LIST,
        "user_list" : CommCareUser.by_domain(domain),
    }
    return render_to_response(request, "reminders/partial/add_survey.html", context)
 def handle(self, *args, **options):
     startdate = dateutil.parser.parse(args[2])
     enddate = dateutil.parser.parse(args[3])
     self.datespan = DateSpan(startdate, enddate)
     self.domain = args[0]
     self.user_ids = [user.user_id for user in CommCareUser.by_domain(self.domain)]
     self.get_indicator_response(args[1])
示例#39
0
    def main_context(self):
        try:
            facilities = Location.filter_by_type_count(self.domain, 'FACILITY')
        except TypeError:
            facilities = 0

        contacts = CommCareUser.by_domain(self.domain, reduce=True)
        web_users = WebUser.by_domain(self.domain, reduce=True)

        try:
            products = len(Product.by_domain(self.domain))
        except ResourceNotFound:
            products = 0

        main_context = super(GlobalStats, self).main_context
        context = {
            'supply_points':  len(list(Location.by_domain(self.domain))),
            'facilities': facilities,
            'contacts':  contacts[0]['value'] if contacts else 0,
            'web_users': web_users[0]['value'] if web_users else 0,
            'products':  products,
            #TODO add next after the enlargement ILS migration
            'product_stocks':  0,
            'stock_transactions':  0,
            'inbound_messages':  0,
            'outbound_messages':  0
        }
        main_context.update(context)
        return main_context
示例#40
0
 def by_domain(self, domain, is_active=True):
     users = CommCareUser.by_domain(domain, is_active=is_active)
     for user in users:
         # put users in the cache for get_by_user_id
         # so that function never has to touch the database
         self.get_by_user_id.get_cache(self)[(self, user.user_id)] = user
     return users
示例#41
0
    def test_phone_numbers_edit(self):
        with open(os.path.join(self.datapath, 'sample_smsusers.json')) as f:
            smsuser = SMSUser(json.loads(f.read())[2])

        self.assertEqual(0, len(CommCareUser.by_domain(TEST_DOMAIN)))
        ilsgateway_smsuser = self.api_object.sms_user_sync(smsuser)
        self.assertListEqual(ilsgateway_smsuser.phone_numbers, ['2222', '3333'])
        vn1 = VerifiedNumber.by_phone('2222')
        vn2 = VerifiedNumber.by_phone('3333')
        self.assertIsNotNone(vn1)
        self.assertIsNotNone(vn2)

        smsuser.phone_numbers = smsuser.phone_numbers[:1]
        ilsgateway_smsuser = self.api_object.sms_user_sync(smsuser)
        self.assertListEqual(ilsgateway_smsuser.phone_numbers, ['2222'])
        vn1 = VerifiedNumber.by_phone('2222')
        vn2 = VerifiedNumber.by_phone('3333')
        self.assertIsNotNone(vn1)
        self.assertIsNone(vn2)

        smsuser.phone_numbers = []
        ilsgateway_smsuser = self.api_object.sms_user_sync(smsuser)
        self.assertListEqual(ilsgateway_smsuser.phone_numbers, [])
        vn1 = VerifiedNumber.by_phone('2222')
        vn2 = VerifiedNumber.by_phone('3333')
        self.assertIsNone(vn1)
        self.assertIsNone(vn2)
示例#42
0
 def _send_submission_alert_to_msd(self, params):
     users = filter(lambda u: u.user_data.get('role', None) == 'MSD', CommCareUser.by_domain(self.domain))
     for user in users:
         if not user.get_verified_number():
             continue
         with localize(user.get_language_code()):
             send_sms_to_verified_number(user.get_verified_number(), SUBMITTED_NOTIFICATION_MSD % params)
示例#43
0
    def main_context(self):
        try:
            facilities = Location.filter_by_type_count(self.domain, 'FACILITY')
        except TypeError:
            facilities = 0

        contacts = CommCareUser.by_domain(self.domain, reduce=True)
        web_users = WebUser.by_domain(self.domain, reduce=True)

        try:
            products = len(Product.by_domain(self.domain))
        except ResourceNotFound:
            products = 0

        main_context = super(GlobalStats, self).main_context
        context = {
            'supply_points': len(list(Location.by_domain(self.domain))),
            'facilities': facilities,
            'contacts': contacts[0]['value'] if contacts else 0,
            'web_users': web_users[0]['value'] if web_users else 0,
            'products': products,
            #TODO add next after the enlargement ILS migration
            'product_stocks': 0,
            'stock_transactions': 0,
            'inbound_messages': 0,
            'outbound_messages': 0
        }
        main_context.update(context)
        return main_context
示例#44
0
def send_ror_reminder(domain, date, loc_type='FACILITY', test_list=None):
    if loc_type == 'FACILITY':
        status_type = SupplyPointStatusTypes.R_AND_R_FACILITY
        sms_text = REMINDER_R_AND_R_FACILITY
    elif loc_type == 'DISTRICT':
        status_type = SupplyPointStatusTypes.R_AND_R_DISTRICT
        sms_text = REMINDER_R_AND_R_DISTRICT
    else:
        return
    current_group = DeliveryGroups().current_submitting_group(date.month)
    sp_ids = set()
    users = CommCareUser.by_domain(domain) if not test_list else test_list
    for user in users:
        location = user.location
        if user.is_active and location and location.location_type == loc_type:
            status_exists = SupplyPointStatus.objects.filter(
                location_id=location._id,
                status_type=status_type,
                status_date__gte=date
            ).exists()
            if current_group in location.metadata.get('group', None) and not status_exists:
                result = send_translated_message(user, sms_text)
                if not test_list and result:
                    sp_ids.add(location._id)

    update_statuses(sp_ids, status_type, SupplyPointStatusValues.REMINDER_SENT)
示例#45
0
    def test_update(self):
        self.client.login(username=self.username, password=self.password)

        user = CommCareUser.create(domain=self.domain.name, username="******", password="******")
        group = Group({"name": "test"})
        group.save()

        user_json = {
            "first_name": "test",
            "last_name": "last",
            "email": "*****@*****.**",
            "language": "pol",
            "phone_numbers": ["+50253311399", "50253314588"],
            "groups": [group._id],
            "user_data": {"chw_id": "13/43/DFA"},
        }

        backend_id = user._id
        response = self.client.put(
            self.single_endpoint(backend_id), json.dumps(user_json), content_type="application/json"
        )
        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(1, len(CommCareUser.by_domain(self.domain.name)))
        modified = CommCareUser.get(backend_id)
        self.assertEqual(modified.username, "test")
        self.assertEqual(modified.first_name, "test")
        self.assertEqual(modified.last_name, "last")
        self.assertEqual(modified.email, "*****@*****.**")
        self.assertEqual(modified.language, "pol")
        self.assertEqual(modified.get_group_ids()[0], group._id)
        self.assertEqual(modified.user_data["chw_id"], "13/43/DFA")
        self.assertEqual(modified.default_phone_number, "50253311399")
        modified.delete()
        group.delete()
示例#46
0
    def rows(self):
        group_id = self.request.GET.get("group", None)
        month = self.request.GET.get("month", None)
        year = self.request.GET.get("year", None)
        curval = float(self.request.GET.get("curval", 1.0))
        curname = self.request.GET.get("curname", "MK")

        if not (month and year):
            return []

        rows = []
        if group_id:
            group = Group.get(group_id)
            users = group.users
        else:
            users = CommCareUser.by_domain(self.domain)

        for user in users:
            row = []
            lg = LendingGroupAggregate(user.full_name, [user._id], month, year, curval, curname)
            for v in self.columns:
                try:
                    if v[1]:
                        row.append(getattr(lg, v[1]))
                    else:
                        row.append('-')
                except TypeError:
                    row.append('-')
            rows.append(row)

        return rows
示例#47
0
 def by_domain(self, domain, is_active=True):
     users = CommCareUser.by_domain(domain, is_active=is_active)
     for user in users:
         # put users in the cache for get_by_user_id
         # so that function never has to touch the database
         self.get_by_user_id.get_cache(self)[(self, user.user_id)] = user
     return users
示例#48
0
def get_user_data_set():
    users = CommCareUser.by_domain(DOMAIN)
    return {
        'blocks': sorted(list(set(u.user_data.get('block') for u in users))),
        'awcs': sorted(list(set(u.user_data.get('awc') for u in users))),
        'gp': sorted(list(set(u.user_data.get('gp') for u in users))),
    }
示例#49
0
    def test_user_deactivation(self):
        with open(os.path.join(self.datapath, 'sample_smsusers.json')) as f:
            smsuser = SMSUser(json.loads(f.read())[2])
        ilsgateway_smsuser = self.api_object.sms_user_sync(smsuser)
        self.assertIsNotNone(ilsgateway_smsuser.get_id)
        self.assertEqual(len(CommCareUser.by_domain(TEST_DOMAIN)), 1)

        smsuser.is_active = False
        ilsgateway_smsuser = self.api_object.sms_user_sync(smsuser)
        self.assertIsNotNone(ilsgateway_smsuser)
        self.assertEqual(len(CommCareUser.by_domain(TEST_DOMAIN)), 0)

        smsuser.is_active = True
        ilsgateway_smsuser = self.api_object.sms_user_sync(smsuser)
        self.assertIsNotNone(ilsgateway_smsuser)
        self.assertEqual(len(CommCareUser.by_domain(TEST_DOMAIN)), 1)
示例#50
0
def create_usercases(domain_name):
    from corehq.apps.callcenter.sync_usercase import sync_usercase
    if USH_USERCASES_FOR_WEB_USERS.enabled(domain_name):
        users = CouchUser.by_domain(domain_name)
    else:
        users = CommCareUser.by_domain(domain_name)
    for user in users:
        sync_usercase(user, domain_name)
示例#51
0
    def setUp(self):
        self.endpoint = MockEndpoint('http://test-api.com/', 'dummy', 'dummy')
        self.api_object = ILSGatewayAPI(TEST_DOMAIN, self.endpoint)
        self.datapath = os.path.join(os.path.dirname(__file__), 'data')
        initial_bootstrap(TEST_DOMAIN)

        for user in CommCareUser.by_domain(TEST_DOMAIN):
            user.delete()
示例#52
0
 def test_migration(self):
     ils_bootstrap_domain_test_task(
         TEST_DOMAIN, MockEndpoint('http://test-api.com/', 'dummy',
                                   'dummy'))
     self.assertEqual(6, len(list(Product.by_domain(TEST_DOMAIN))))
     self.assertEqual(5, len(list(Location.by_domain(TEST_DOMAIN))))
     self.assertEqual(6, len(list(CommCareUser.by_domain(TEST_DOMAIN))))
     self.assertEqual(5, len(list(WebUser.by_domain(TEST_DOMAIN))))
示例#53
0
 def assertUserState(self, active, inactive):
     """active and inactive should be lists of usernames"""
     for usernames, is_active in [(active, True), (inactive, False)]:
         self.assertItemsEqual(usernames, [
             user.raw_username
             for user in CommCareUser.by_domain(self.domain,
                                                is_active=is_active)
         ])
示例#54
0
def get_user_id_map():
    print "Retrieving migrated pact users from HQ and setting map"
    all_users = CommCareUser.by_domain(PACT_DOMAIN)
    old_id_map = {}
    for u in all_users:
        old_user_id = getattr(u, 'old_user_id', None)
        if old_user_id is not None:
            old_id_map[str(u['old_user_id'])] = u.get_id
    return old_id_map
示例#55
0
 def handle(self, *args, **options):
     startdate = dateutil.parser.parse(args[2])
     enddate = dateutil.parser.parse(args[3])
     self.datespan = DateSpan(startdate, enddate)
     self.domain = args[0]
     self.user_ids = [
         user.user_id for user in CommCareUser.by_domain(self.domain)
     ]
     self.get_indicator_response(args[1])
示例#56
0
def _household_verification_json(
        domain="dodoma",
        last_hvid_path=["household_verification"],
        next_hvid_path=["followup_id"],
        xmlns='http://openrosa.org/formdesigner/9DAACA82-A414-499A-9C40-BC43775CEE79',
        range=None):
    if range:
        start, end = map(string_to_datetime, range)
    else:
        now = datetime.utcnow()
        start, end = now - timedelta(days=7), now

    key = make_form_couch_key(domain, xmlns=xmlns)
    submissions = XFormInstance.view(
        'reports_forms/all_forms',
        reduce=False,
        startkey=key + [json_format_datetime(start)],
        endkey=key + [json_format_datetime(end)],
        include_docs=True,
    )

    stats = get_household_verification_data(
        submissions=submissions,
        next_hvid_path=next_hvid_path,
        last_hvid_path=last_hvid_path,
    )

    stats_by_userID = {}
    for s in stats:
        stats_by_userID[s['userID']] = s
        s['username'] = "******" % s['userID']
    users = CommCareUser.by_domain(domain)

    for user in users:
        userID = user.user_id
        username = user_id_to_username(userID)
        if userID in stats_by_userID:
            stats_by_userID[userID]['username'] = username
        else:
            stats.append({
                'userID': userID,
                'username': username,
                'total': 0,
                'correct': 0
            })
    stats.sort(key=lambda s: s['username'])

    return {
        "headers": ["Username", "Correct", "Total", "Percent Correct"],
        "rows": [[
            s['username'], s['correct'], s['total'],
            ("%s%%" %
             int(s['correct'] * 100 / s['total']) if s['total'] else "---")
        ] for s in stats],
    }
示例#57
0
    def test_create(self):

        group = Group({"name": "test"})
        group.save()
        self.addCleanup(group.delete)

        self.assertEqual(0, len(CommCareUser.by_domain(self.domain.name)))

        user_json = {
            "username": "******",
            "password": "******",
            "first_name": "John",
            "last_name": "Doe",
            "email": "*****@*****.**",
            "language": "en",
            "phone_numbers": [
                "+50253311399",
                "50253314588"
            ],
            "groups": [
                group._id
            ],
            "user_data": {
                "chw_id": "13/43/DFA"
            }
        }
        response = self._assert_auth_post_resource(self.list_endpoint,
                                    json.dumps(user_json),
                                    content_type='application/json')
        self.assertEqual(response.status_code, 201)
        [user_back] = CommCareUser.by_domain(self.domain.name)
        self.addCleanup(user_back.delete, deleted_by=None)
        self.addCleanup(lambda: send_to_elasticsearch('users', user_back.to_json(), delete=True))

        self.assertEqual(user_back.username, "jdoe")
        self.assertEqual(user_back.first_name, "John")
        self.assertEqual(user_back.last_name, "Doe")
        self.assertEqual(user_back.email, "*****@*****.**")
        self.assertEqual(user_back.language, "en")
        self.assertEqual(user_back.get_group_ids()[0], group._id)
        self.assertEqual(user_back.user_data["chw_id"], "13/43/DFA")
        self.assertEqual(user_back.default_phone_number, "50253311399")
示例#58
0
def project_id_mapping(request, domain):
    from corehq.apps.users.models import CommCareUser
    from corehq.apps.groups.models import Group

    users = CommCareUser.by_domain(domain)
    groups = Group.by_domain(domain)

    return json_response({
        'users': dict([(user.raw_username, user.user_id) for user in users]),
        'groups': dict([(group.name, group.get_id) for group in groups]),
    })
示例#59
0
 def obj_get_list(self, bundle, **kwargs):
     domain = kwargs['domain']
     group_id = bundle.request.GET.get('group')
     if group_id:
         group = Group.get(group_id)
         if not group or group.domain != domain:
             raise BadRequest('Project %s has no group with id=%s' %
                              (domain, group_id))
         return list(group.get_users(only_commcare=True))
     else:
         return list(CommCareUser.by_domain(domain, strict=True))
示例#60
0
    def test_create(self):
        self.client.login(username=self.username, password=self.password)

        group = Group({"name": "test"})
        group.save()

        self.assertEqual(0, len(CommCareUser.by_domain(self.domain.name)))

        user_json = {
            "username": "******",
            "password": "******",
            "first_name": "John",
            "last_name": "Doe",
            "email": "*****@*****.**",
            "language": "en",
            "phone_numbers": [
                "+50253311399",
                "50253314588"
            ],
            "groups": [
                group._id
            ],
            "user_data": {
                "chw_id": "13/43/DFA"
            }
        }
        response = self.client.post(self.list_endpoint,
                                    simplejson.dumps(user_json),
                                    content_type='application/json')
        self.assertEqual(response.status_code, 201)
        [user_back] = CommCareUser.by_domain(self.domain.name)
        self.assertEqual(user_back.username, "jdoe")
        self.assertEqual(user_back.first_name, "John")
        self.assertEqual(user_back.last_name, "Doe")
        self.assertEqual(user_back.email, "*****@*****.**")
        self.assertEqual(user_back.language, "en")
        self.assertEqual(user_back.get_group_ids()[0], group._id)
        self.assertEqual(user_back.user_data["chw_id"], "13/43/DFA")
        self.assertEqual(user_back.default_phone_number, "+50253311399")
        user_back.delete()
        group.delete()