Пример #1
0
    def setUpClass(cls):
        domain_name = "cc_test_case_sharing"
        cls.domain = create_domain(domain_name)
        cls.supervisor = CommCareUser.create(domain_name, "supervisor@" + domain_name, "***")

        cls.domain.call_center_config.enabled = True
        cls.domain.call_center_config.case_owner_id = cls.supervisor.get_id
        cls.domain.call_center_config.case_type = "cc_flw"
        cls.domain.save()

        cls.user = CommCareUser.create(domain_name, "user@" + domain_name, "***")
        sync_user_cases(cls.user)

        cls.group = Group(domain=domain_name, name="case sharing group", case_sharing=True, users=[cls.user.user_id])
        cls.group.save()

        load_data(
            domain_name,
            cls.user.user_id,
            "not this user",
            cls.group.get_id,
            case_opened_by=cls.user.user_id,
            case_closed_by=cls.user.user_id,
        )

        # create one case of each type so that we get the indicators where there is no data for the period
        create_cases_for_types(domain_name, ["person", "dog"])
Пример #2
0
    def testGetUsers(self):
        domain = 'group-test'
        active_user = CommCareUser.create(domain=domain, username='******', password='******')
        inactive_user = CommCareUser.create(domain=domain, username='******', password='******')
        inactive_user.is_active = False
        inactive_user.save()
        deleted_user = CommCareUser.create(domain=domain, username='******', password='******')
        deleted_user.retire()

        group = Group(domain=domain, name='group',
                      users=[active_user._id, inactive_user._id, deleted_user._id])
        group.save()

        def _check_active_users(userlist):
            self.assertEqual(len(userlist), 1)
            self.assertEqual(active_user._id, userlist[0])

        # try all the flavors of this
        _check_active_users([u._id for u in group.get_users()])
        _check_active_users(group.get_user_ids())
        _check_active_users([u._id for u in group.get_static_users()])
        _check_active_users(group.get_static_user_ids())

        def _check_all_users(userlist):
            self.assertEqual(len(userlist), 2)
            self.assertTrue(active_user._id in userlist)
            self.assertTrue(inactive_user._id in userlist)
            self.assertFalse(deleted_user._id in userlist)

        _check_all_users([u._id for u in group.get_users(is_active=False)])
        _check_all_users(group.get_user_ids(is_active=False))
        _check_all_users([u._id for u in group.get_static_users(is_active=False)])
        _check_all_users(group.get_static_user_ids(is_active=False))
    def handle(self, *args, **options):
        for domain in Domain.get_all_names():
            fields_definition = cdm.CustomDataFieldsDefinition.get_or_create(
                domain,
                'UserFields'
            )
            had_fields = bool(fields_definition.fields)

            user_ids = (CommCareUser.ids_by_domain(domain) +
                        CommCareUser.ids_by_domain(domain, is_active=False))

            existing_field_slugs = set([field.slug for field in fields_definition.fields])
            for user in iter_docs(CommCareUser.get_db(), user_ids):
                user_data = user.get('user_data', {})
                for key in user_data.keys():
                    if (key and key not in existing_field_slugs
                        and not cdm.is_system_key(key)):
                        existing_field_slugs.add(key)
                        fields_definition.fields.append(cdm.CustomDataField(
                            slug=key,
                            label=key,
                            is_required=False,
                        ))

            for field in fields_definition.fields:
                if cdm.is_system_key(field.slug):
                    fields_definition.fields.remove(field)
            # Only save a definition for domains which use custom user data
            if fields_definition.fields or had_fields:
                fields_definition.save()
            print 'finished domain "{}"'.format(domain.name)
Пример #4
0
    def setUp(self):
        super(CallCenterCaseSharingTest, self).setUp()
        self.domain = create_domain(self.domain_name)
        self.supervisor = CommCareUser.create(self.domain_name, 'supervisor@' + self.domain_name, '***')

        self.domain.call_center_config.enabled = True
        self.domain.call_center_config.case_owner_id = self.supervisor.get_id
        self.domain.call_center_config.case_type = 'cc_flw'
        self.domain.save()

        self.user = CommCareUser.create(self.domain_name, 'user@' + self.domain_name, '***')
        sync_call_center_user_case(self.user)

        self.group = Group(
            domain=self.domain_name,
            name='case sharing group',
            case_sharing=True,
            users=[self.user.user_id]
        )
        self.group.save()

        load_data(
            self.domain_name,
            self.user.user_id,
            'not this user',
            self.group.get_id,
            case_opened_by=self.user.user_id,
            case_closed_by=self.user.user_id)
Пример #5
0
 def make_mobile_worker(cls, username, domain=None):
     domain = domain or cls.domain
     user = CommCareUser(username=normalize_username(username, domain),
                         domain=domain)
     user.domain_membership = DomainMembership(domain=domain)
     UserESFake.save_doc(user._doc)
     return user
Пример #6
0
    def test_users(self):
        from corehq.apps.users.models import CommCareUser
        from corehq.apps.users.models import WebUser
        from django.contrib.auth.models import User

        expected_object_counts = Counter({User: 3})

        ccuser_1 = CommCareUser.create(
            domain=self.domain_name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        ccuser_2 = CommCareUser.create(
            domain=self.domain_name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        web_user = WebUser.create(
            domain=self.domain_name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        self.addCleanup(ccuser_1.delete)
        self.addCleanup(ccuser_2.delete)
        self.addCleanup(web_user.delete)

        self._dump_and_load(expected_object_counts)
Пример #7
0
 def setUpClass(cls):
     cls.active_user = CommCareUser.create(domain=DOMAIN, username='******', password='******')
     cls.inactive_user = CommCareUser.create(domain=DOMAIN, username='******', password='******')
     cls.inactive_user.is_active = False
     cls.inactive_user.save()
     cls.deleted_user = CommCareUser.create(domain=DOMAIN, username='******', password='******')
     cls.deleted_user.retire()
Пример #8
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()
Пример #9
0
def bootstrap_user(
    username=TEST_USER,
    domain=TEST_DOMAIN,
    phone_number=TEST_NUMBER,
    password=TEST_PASSWORD,
    backend=TEST_BACKEND,
    first_name="",
    last_name="",
    home_loc=None,
    user_data=None,
    program_id=None,
):
    user_data = user_data or {}
    user = CommCareUser.create(
        domain,
        username,
        password,
        phone_numbers=[TEST_NUMBER],
        user_data=user_data,
        first_name=first_name,
        last_name=last_name,
    )

    user.set_location(home_loc)
    dm = user.get_domain_membership(domain)
    dm.program_id = program_id
    user.save()

    user.save_verified_number(domain, phone_number, verified=True, backend_id=backend)
    return CommCareUser.wrap(user.to_json())
Пример #10
0
    def testGroupFilters(self):
        domain = 'case-export-test'
        active_user = CommCareUser.create(domain=domain, username='******', password='******')
        inactive_user = CommCareUser.create(domain=domain, username='******', password='******')
        inactive_user.is_active = False
        inactive_user.save()

        group = Group(domain=domain, name='group', users=[active_user._id, inactive_user._id])
        group.save()

        # no matter what the group should match on ownerid (but not user id)
        self.assertTrue(case_group_filter(_mock_case(group._id, 'nobody'), group))
        self.assertTrue(case_group_filter(_mock_case(group._id, active_user._id), group))
        self.assertTrue(case_group_filter(_mock_case(group._id, inactive_user._id), group))
        self.assertFalse(case_group_filter(_mock_case('nobody', group._id), group))

        # test active users count
        self.assertTrue(case_group_filter(_mock_case(active_user._id, 'nobody'), group))
        self.assertTrue(case_group_filter(_mock_case('nobody', active_user._id), group))
        self.assertTrue(case_group_filter(_mock_case(active_user._id, active_user._id), group))

        # test inactive users don't count
        self.assertFalse(case_group_filter(_mock_case(inactive_user._id, 'nobody'), group))
        self.assertFalse(case_group_filter(_mock_case('nobody', inactive_user._id), group))
        self.assertFalse(case_group_filter(_mock_case(inactive_user._id, inactive_user._id), group))

        # combinations of active and inactive should count
        self.assertTrue(case_group_filter(_mock_case(active_user._id, inactive_user._id), group))
        self.assertTrue(case_group_filter(_mock_case(inactive_user._id, active_user._id), group))

        # duh
        self.assertFalse(case_group_filter(_mock_case('nobody', 'nobody-else'), group))
Пример #11
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()
Пример #12
0
    def setUp(self):
        super(CallCenterCaseSharingTest, self).setUp()
        self.domain = create_domain(self.domain_name)
        self.supervisor = CommCareUser.create(self.domain_name, 'supervisor@' + self.domain_name, '***')

        self.domain.call_center_config.enabled = True
        self.domain.call_center_config.case_owner_id = self.supervisor.get_id
        self.domain.call_center_config.case_type = 'cc_flw'
        self.domain.save()

        self.user = CommCareUser.create(self.domain_name, 'user@' + self.domain_name, '***')
        sync_call_center_user_case(self.user)

        self.group = Group(
            domain=self.domain_name,
            name='case sharing group',
            case_sharing=True,
            users=[self.user.user_id]
        )
        self.group.save()

        load_data(
            self.domain_name,
            self.user.user_id,
            'not this user',
            self.group.get_id,
            case_opened_by=self.user.user_id,
            case_closed_by=self.user.user_id)

        # create one case of each type so that we get the indicators where there is no data for the period
        create_cases_for_types(self.domain_name, ['person', 'dog'])
Пример #13
0
 def setUpClass(cls):
     super(UserAnalyticsTest, cls).setUpClass()
     delete_all_users()
     cls.domain = create_domain('test')
     cls.active_user = CommCareUser.create(
         domain='test',
         username='******',
         password='******',
         is_active=True,
     )
     cls.active_user_2 = CommCareUser.create(
         domain='test',
         username='******',
         password='******',
         is_active=True,
     )
     cls.inactive_user = CommCareUser.create(
         domain='test',
         username='******',
         password='******',
         is_active=False
     )
     cls.web_user = WebUser.create(
         domain='test',
         username='******',
         password='******',
     )
     update_analytics_indexes()
Пример #14
0
    def testEditUserFromRegistration(self):
        """
        Edit a user via registration XML
        """
        # really this should be in the "update" test but all the infrastructure
        # for dealing with the xml payload is here.
        original_user, created = CommCareUser.create_or_update_from_xform(self.xform)
        self.assertTrue(created)
        self.assertEqual("test_reg", original_user.username.split("@")[0])
        original_django_user = original_user.get_django_user()
        original_count = User.objects.count()

        xform = self.xform
        xform.form['username'] = '******'
        xform.form['password'] = "******"
        self.xform.form['registering_phone_id'] = 'phone_edit'
        xform.form['user_data'] = {'data': [{'@key': 'user_type', '#text': 'boss'}]}
        updated_user, created = CommCareUser.create_or_update_from_xform(xform)
        self.assertFalse(created)
        # make sure they got different usernames
        self.assertEqual("a_new_username", updated_user.username.split("@")[0])
        self.assertEqual("phone_edit", updated_user.device_id)
        self.assertEqual("boss", updated_user.user_data["user_type"])

        # make sure we didn't create a new django user and updated
        # the old one correctly
        updated_django_user = updated_user.get_django_user()
        self.assertEqual(original_count, User.objects.count())
        self.assertEqual(original_django_user.pk, updated_django_user.pk)
        self.assertNotEqual(original_django_user.username, updated_django_user.username)
        self.assertNotEqual(original_django_user.password, updated_django_user.password)
Пример #15
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)
Пример #16
0
    def setUpClass(cls):
        cls.ccdomain = Domain(name='cc_user_domain')
        cls.ccdomain.save()
        cls.other_domain = Domain(name='other_domain')
        cls.other_domain.save()

        cls.ccuser_1 = CommCareUser.create(
            domain=cls.ccdomain.name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        cls.ccuser_2 = CommCareUser.create(
            domain=cls.ccdomain.name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        cls.web_user = WebUser.create(
            domain=cls.ccdomain.name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        cls.ccuser_other_domain = CommCareUser.create(
            domain=cls.other_domain.name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
Пример #17
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
Пример #18
0
    def test_sync_log(self):
        from casexml.apps.phone.models import SyncLog, SimplifiedSyncLog
        from corehq.apps.users.models import WebUser, CommCareUser
        from casexml.apps.phone.models import get_sync_log_class_by_format

        web_user = WebUser.create(
            domain=self.domain_name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        mobile_user = CommCareUser.create(
            self.domain_name, 'mobile_user1', 'secret'
        )
        other_user = CommCareUser.create(
            'other_domain', 'mobile_user2', 'secret'
        )
        self.addCleanup(other_user.delete)

        l1 = SyncLog(user_id=web_user._id)
        l1.save()
        l2 = SimplifiedSyncLog(user_id=mobile_user._id)
        l2.save()
        other_log = SyncLog(user_id=other_user._id)
        other_log.save()

        def _synclog_to_class(doc):
            if doc['doc_type'] == 'SyncLog':
                return get_sync_log_class_by_format(doc.get('log_format'))

        expected_docs = [web_user, mobile_user, l1, l2]
        not_expected_docs = [other_user, other_log]
        self._dump_and_load(expected_docs, not_expected_docs, doc_to_doc_class=_synclog_to_class)
Пример #19
0
    def __init__(self, report, case):

        try:
            self.user = CommCareUser.get_by_user_id(case["user_id"])
            if self.user is None:
                self.user = CommCareUser.get_by_user_id(case["opened_by"])
        except CouchUser.AccountTypeError:
            # if we have web users submitting forms (e.g. via cloudcare) just don't bother
            # with the rest of this data.
            self.user = None

        if self.user:
            setattr(self, "_village", get_property(self.user.user_data, "village"))
            setattr(self, "_asha_name", self.user.full_name if get_property(self.user.user_data, "role").upper() == "ASHA" else get_property(self.user.user_data, "partner_name"))
            if get_property(self.user.user_data, "role").upper() == "ASHA":
                setattr(self, "_asha_number", self.user.default_phone_number if self.user.default_phone_number else EMPTY_FIELD)
            else:
                setattr(self, "_asha_number", get_property(self.user.user_data, "partner_phone"))

            setattr(self, "_awc_code_name", "%s, %s" % (get_property(self.user.user_data, "awc-code"), get_property(self.user.user_data, "village")))
            setattr(self, "_aww_name", self.user.full_name if get_property(self.user.user_data, "role").upper() == "AWW" else get_property(self.user.user_data, "partner_name"))

            if get_property(self.user.user_data, "role").upper() == "AWW":
                setattr(self, "_aww_number", self.user.phone_numbers[0] if len(self.user.phone_numbers) > 0 else EMPTY_FIELD)
            else:
                setattr(self, "_aww_number", get_property(self.user.user_data, "partner_phone"))

        super(MCHDisplay, self).__init__(report, case)
Пример #20
0
 def setUp(self):
     self.domain = "test-domain"
     create_domain(self.domain)
     self.user = CommCareUser.create(self.domain, 'reconciliation-test', 'password')
     self.user.save()
     self.other_user = CommCareUser.create(self.domain, 'reconciliation-test-other', 'password')
     self.other_user.save()
Пример #21
0
 def _sync_location_user(self):
     if not self.location.location_id:
         return
     if self.location.location_type.has_user and not self.location.user_id:
         # make sure there's a location user
         res = list(UserES()
                    .domain(self.domain)
                    .show_inactive()
                    .term('user_location_id', self.location.location_id)
                    .values_list('_id', flat=True))
         user_id = res[0] if res else None
         if user_id:
             user = CommCareUser.get(user_id)
         else:
             user = make_location_user(self.location)
         user.is_active = True
         user.user_location_id = self.location.location_id
         user.set_location(self.location, commit=False)
         user.save()
         self.location.user_id = user._id
         self.location.save()
     elif self.location.user_id and not self.location.location_type.has_user:
         # archive the location user
         user = CommCareUser.get_by_user_id(self.location.user_id, self.domain)
         if user:
             user.is_active = False
             user.save()
         self.location.user_id = ''
         self.location.save()
Пример #22
0
    def rows(self):
        rows = []
        locations = SQLLocation.objects.filter(parent__location_id=self.config['location_id'])
        dg = []
        for date in list(rrule.rrule(rrule.MONTHLY, dtstart=self.config['startdate'],
                                     until=self.config['enddate'])):
            dg.extend(DeliveryGroups().submitting(locations, date.month))

        for child in dg:
            total_responses = 0
            total_possible = 0
            submitted, rr_value = randr_value(child.location_id, self.config['startdate'], self.config['enddate'])
            if child.is_archived and not rr_value:
                continue

            group_summaries = GroupSummary.objects.filter(
                org_summary__date__lte=self.config['startdate'],
                org_summary__location_id=child.location_id,
                title=SupplyPointStatusTypes.R_AND_R_FACILITY
            )

            for group_summary in group_summaries:
                if group_summary:
                    total_responses += group_summary.responded
                    total_possible += group_summary.total
            hist_resp_rate = rr_format_percent(total_responses, total_possible)

            url = make_url(FacilityDetailsReport, self.config['domain'],
                           '?location_id=%s&filter_by_program=%s&'
                           'datespan_type=%s&datespan_first=%s&datespan_second=%s',
                           (self.config['location_id'],
                            self.config['program'], self.config['datespan_type'],
                            self.config['datespan_first'], self.config['datespan_second']))

            contact = CommCareUser.get_db().view(
                'locations/users_by_location_id',
                startkey=[child.location_id],
                endkey=[child.location_id, {}],
                include_docs=True
            ).first()

            if contact and contact['doc']:
                contact = CommCareUser.wrap(contact['doc'])
                role = contact.user_data.get('role') or ""
                args = (contact.first_name, contact.last_name, role, contact.default_phone_number)
                contact_string = "%s %s (%s) %s" % args
            else:
                contact_string = ""

            rows.append(
                [
                    child.site_code,
                    link_format(child.name, url),
                    get_span(submitted) % (rr_value.strftime("%d %b %Y") if rr_value else "Not reported"),
                    contact_string,
                    hist_resp_rate
                ]
            )

        return rows
Пример #23
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)
Пример #24
0
def bootstrap_user(loc, username=TEST_USER, domain=TEST_DOMAIN,
                   phone_number=TEST_NUMBER, password=TEST_PASSWORD,
                   backend=TEST_BACKEND, first_name='', last_name='',
                   home_loc=None, user_data=None, language=None
                   ):
    user_data = user_data or {}
    user = CommCareUser.create(
        domain,
        username,
        password,
        phone_numbers=[phone_number],
        user_data=user_data,
        first_name=first_name,
        last_name=last_name
    )
    if language:
        user.language = language
    if home_loc == loc.site_code:
        interface = SupplyInterface(domain)
        if not interface.get_by_location(loc):
            interface.create_from_location(domain, loc)

        user.set_location(loc)

    user.save_verified_number(domain, phone_number, verified=True, backend_id=backend)
    user.save()
    return CommCareUser.wrap(user.to_json())
Пример #25
0
 def tearDown(self):
     user = CommCareUser.get_by_username('*****@*****.**')
     if user:
         user.delete()
     user = CommCareUser.get_by_username('*****@*****.**')
     if user:
         user.delete()
Пример #26
0
def bootstrap_user(username=TEST_USER, domain=TEST_DOMAIN,
                   phone_number=TEST_NUMBER, password=TEST_PASSWORD,
                   backend=TEST_BACKEND, first_name='', last_name='',
                   home_loc=None, user_data=None,
                   ):
    from corehq.apps.commtrack.helpers import make_supply_point

    user_data = user_data or {}
    user = CommCareUser.create(
        domain,
        username,
        password,
        phone_numbers=[TEST_NUMBER],
        user_data=user_data,
        first_name=first_name,
        last_name=last_name
    )

    if not SupplyPointCase.get_by_location(home_loc):
        make_supply_point(domain, home_loc)
        home_loc.save()
    user.set_location(home_loc)

    user.save_verified_number(domain, phone_number, verified=True, backend_id=backend)
    return CommCareUser.wrap(user.to_json())
Пример #27
0
    def setUpClass(cls):
        domain_name = 'cc_test_case_sharing'
        cls.domain = create_domain(domain_name)
        cls.supervisor = CommCareUser.create(domain_name, 'supervisor@' + domain_name, '***')

        cls.domain.call_center_config.enabled = True
        cls.domain.call_center_config.case_owner_id = cls.supervisor.get_id
        cls.domain.call_center_config.case_type = 'cc_flw'
        cls.domain.save()

        cls.user = CommCareUser.create(domain_name, 'user@' + domain_name, '***')
        sync_call_center_user_case(cls.user)

        cls.group = Group(
            domain=domain_name,
            name='case sharing group',
            case_sharing=True,
            users=[cls.user.user_id]
        )
        cls.group.save()

        load_data(
            domain_name,
            cls.user.user_id,
            'not this user',
            cls.group.get_id,
            case_opened_by=cls.user.user_id,
            case_closed_by=cls.user.user_id)

        # create one case of each type so that we get the indicators where there is no data for the period
        create_cases_for_types(domain_name, ['person', 'dog'])
Пример #28
0
def bootstrap_user(username=TEST_USER, domain=TEST_DOMAIN,
                   phone_number=TEST_NUMBER, password=TEST_PASSWORD,
                   backend=TEST_BACKEND, first_name='', last_name='',
                   home_loc=None, user_data=None, program_id=None
                   ):
    user_data = user_data or {}
    user = CommCareUser.create(
        domain,
        username,
        password,
        user_data=user_data,
        first_name=first_name,
        last_name=last_name
    )
    user.phone_numbers = [phone_number]
    if home_loc:
        user.set_location(home_loc)
    dm = user.get_domain_membership(domain)
    dm.program_id = program_id
    user.save()

    entry = user.get_or_create_phone_entry(phone_number)
    entry.set_two_way()
    entry.set_verified()
    entry.backend_id = backend
    entry.save()
    return CommCareUser.wrap(user.to_json())
Пример #29
0
def make_meta_block(self, instance_id=None, timestart=None, timeend=None, webuser=None):
    if timestart is None:
        timestart = datetime.utcnow()
    if timeend is None:
        timeend = datetime.utcnow()

    if webuser is None:
        if CommCareUser.get_by_username('*****@*****.**') is None:
            raise Exception("Pact importer user not created")
        webuser = CommCareUser.get_by_username('*****@*****.**')

    if instance_id is None:
        instance_id = uuid.uuid4().hex

    meta_block = """
        <meta>
            <deviceID>pact_case_importer</deviceID>
            <timeStart>%(timestart)s</timeStart>
            <timeEnd>%(timeend)s</timeEnd>
            <username>%(username)s</username>
            <userID>%(userid)s</userID>
            <instanceID>%(instance_id)s</instanceID>
        </meta>""" % {
        "username": webuser.username,
        "userid": webuser.get_id,
        "timestart": timestart.strftime('%Y-%m-%dT%H:%M:%SZ'),
        "timeend": timeend.strftime('%Y-%m-%dT%H:%M:%SZ'),
        "instance_id": instance_id,
        }
    return meta_block
Пример #30
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),
    })
Пример #31
0
def process_sms_registration(msg):
    """
    This method handles registration via sms.
    Returns True if a contact was registered, False if not.

    To have a case register itself, do the following:

        1) Select "Enable Case Registration Via SMS" in project settings, and fill in the
        associated Case Registration settings.

        2) Text in "join <domain>", where <domain> is the domain to join. If the sending
        number does not exist in the system, a case will be registered tied to that number.
        The "join" keyword can be any keyword in REGISTRATION_KEYWORDS. This is meant to
        support multiple translations.

    To have a mobile worker register itself, do the following:

        1) Select "Enable Mobile Worker Registration via SMS" in project settings.

        2) Text in "join <domain> worker <username>", where <domain> is the domain to join and <username> is the
        requested username.  If the username doesn't exist it will be created, otherwise the registration will error.
        If the username argument is not specified, the username will be the mobile number

        The "join" and "worker" keywords can be any keyword in REGISTRATION_KEYWORDS and
        REGISTRATION_MOBILE_WORKER_KEYWORDS, respectively. This is meant to support multiple
        translations.
    """
    registration_processed = False
    text_words = msg.text.upper().split()
    keyword1 = text_words[0] if len(text_words) > 0 else ""
    keyword2 = text_words[1].lower() if len(text_words) > 1 else ""
    keyword3 = text_words[2] if len(text_words) > 2 else ""
    keyword4 = text_words[3] if len(text_words) > 3 else ""
    cleaned_phone_number = strip_plus(msg.phone_number)
    if is_registration_text(msg.text) and keyword2 != "":
        domain = Domain.get_by_name(keyword2, strict=True)
        if domain is not None:
            if domain_has_privilege(domain, privileges.INBOUND_SMS):
                if keyword3 in REGISTRATION_MOBILE_WORKER_KEYWORDS and domain.sms_mobile_worker_registration_enabled:
                    if keyword4 != '':
                        username = keyword4
                    else:
                        username = cleaned_phone_number
                    try:
                        user_data = {}

                        invitation = SelfRegistrationInvitation.by_phone(msg.phone_number)
                        if invitation:
                            invitation.completed()
                            user_data = invitation.custom_user_data

                        username = process_username(username, domain)
                        password = random_password()
                        new_user = CommCareUser.create(domain.name, username, password, user_data=user_data)
                        new_user.add_phone_number(cleaned_phone_number)
                        new_user.save()

                        entry = new_user.get_or_create_phone_entry(cleaned_phone_number)
                        entry.set_two_way()
                        entry.set_verified()
                        entry.save()
                        registration_processed = True

                        if domain.enable_registration_welcome_sms_for_mobile_worker:
                            send_sms(domain.name, None, cleaned_phone_number,
                                     get_message(MSG_REGISTRATION_WELCOME_MOBILE_WORKER, domain=domain.name))
                    except ValidationError as e:
                        send_sms(domain.name, None, cleaned_phone_number, e.messages[0])

                elif domain.sms_case_registration_enabled:
                    register_sms_contact(
                        domain=domain.name,
                        case_type=domain.sms_case_registration_type,
                        case_name="unknown",
                        user_id=domain.sms_case_registration_user_id,
                        contact_phone_number=cleaned_phone_number,
                        contact_phone_number_is_verified="1",
                        owner_id=domain.sms_case_registration_owner_id,
                    )
                    registration_processed = True
                    if domain.enable_registration_welcome_sms_for_case:
                        send_sms(domain.name, None, cleaned_phone_number,
                                 get_message(MSG_REGISTRATION_WELCOME_CASE, domain=domain.name))
            msg.domain = domain.name
            msg.save()

    return registration_processed
def hard_delete_deleted_users():
    # Hard deleted the deleted users to truncate the view
    db_view = CommCareUser.get_db().view('deleted_users_by_username/view',
                                         reduce=False)
    deleted_user_ids = [row['id'] for row in db_view]
    iter_bulk_delete(CommCareUser.get_db(), deleted_user_ids)
Пример #33
0
 def create_user(username):
     username = format_username(username, cls.domain)
     return CommCareUser.create(cls.domain, username, cls.password)
Пример #34
0
 def options(self):
     return [(user._id, user.username[:user.username.index('@')]) for user in
             CommCareUser.by_domain(self.domain)]
Пример #35
0
 def tearDown(self):
     CommCareCase.set_db(self.case_orig_db)
     XFormInstance.set_db(self.form_orig_db)
     CommCareUser.set_db(self.user_orig_db)
Пример #36
0
def restore_commcare_user(request, domain, user_id):
    user = CommCareUser.get_by_user_id(user_id, domain)
    user.unretire()
    messages.success(request, "User %s and all their submissions have been restored" % user.username)
    return HttpResponseRedirect(reverse(EditCommCareUserView.urlname, args=[domain, user_id]))
Пример #37
0
    def setUpClass(cls):
        cls.domain = Domain(name=DOMAIN)
        cls.domain.save()

        cls.country = LocationType(domain=DOMAIN, name='country')
        cls.country.save()
        cls.state = LocationType(
            domain=DOMAIN,
            name='state',
            parent_type=cls.country,
        )
        cls.state.save()
        cls.city = LocationType(
            domain=DOMAIN,
            name='city',
            parent_type=cls.state,
            shares_cases=True,
        )
        cls.city.save()

        cls.usa = SQLLocation(
            domain=DOMAIN,
            name='The United States of America',
            site_code='usa',
            location_type=cls.country,
        )
        cls.usa.save()
        cls.massachusetts = SQLLocation(
            domain=DOMAIN,
            name='Massachusetts',
            site_code='massachusetts',
            location_type=cls.state,
            parent=cls.usa,
        )
        cls.massachusetts.save()
        cls.new_york = SQLLocation(
            domain=DOMAIN,
            name='New York',
            site_code='new_york',
            location_type=cls.state,
            parent=cls.usa,
        )
        cls.new_york.save()

        cls.cambridge = SQLLocation(
            domain=DOMAIN,
            name='Cambridge',
            site_code='cambridge',
            location_type=cls.city,
            parent=cls.massachusetts,
        )
        cls.cambridge.save()
        cls.somerville = SQLLocation(
            domain=DOMAIN,
            name='Somerville',
            site_code='somerville',
            location_type=cls.city,
            parent=cls.massachusetts,
        )
        cls.somerville.save()
        cls.nyc = SQLLocation(
            domain=DOMAIN,
            name='New York City',
            site_code='nyc',
            location_type=cls.city,
            parent=cls.new_york,
        )
        cls.nyc.save()

        cls.drew = CommCareUser(
            domain=DOMAIN,
            username='******',
            location_id=cls.nyc.location_id,
        )
        cls.jon = CommCareUser(
            domain=DOMAIN,
            username='******',
            location_id=cls.cambridge.location_id,
        )
        cls.nate = CommCareUser(
            domain=DOMAIN,
            username='******',
            location_id=cls.somerville.location_id,
        )
        cls.sheel = CommCareUser(
            domain=DOMAIN,
            username='******',
            location_id=cls.somerville.location_id,
            last_login=datetime.datetime.now(),
            date_joined=datetime.datetime.now(),
        )
        cls.sheel.save()
Пример #38
0
 def setUpClass(cls):
     super(GetCaseTest, cls).setUpClass()
     cls.domain = Domain(name='foo')
     cls.domain.save()
     cls.user = CommCareUser.create(cls.domain.name, 'username', 's3cr3t')
Пример #39
0
 def setUp(self):
     super(LocationsTest, self).setUp()
     self.user = CommCareUser.create(domain=self.domain, username='******', password='******')
     self.loc = make_loc('mariposa_saloon', domain=self.domain)
     self.user.set_location(self.loc)
Пример #40
0
def sync_user_cases_task(user_id):
    user = CommCareUser.get_by_user_id(user_id)
    sync_user_cases(user)
Пример #41
0
 def tearDown(self):
     CommCareUser.get_db().delete_doc(self.user._id)
     FormProcessorTestUtils.delete_all_xforms(self.domain)
     self.domain_obj.delete()
     super(UserModelTest, self).tearDown()
Пример #42
0
 def get_user(self):
     if hasattr(self, 'request') and 'chw_id' in self.request.GET:
         self._user_doc = CommCareUser.get(self.request.GET['chw_id'])
         return self._user_doc
     else:
         return None
Пример #43
0
def user_list(domain):
    #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
Пример #44
0
 def test_last_modified(self):
     lm = self.user.last_modified
     self.user.save()
     user = CommCareUser.get(self.user._id)
     self.assertGreater(user.last_modified, lm)
Пример #45
0
 def tearDown(self):
     user = CommCareUser.get(self.ccuser._id)
     user.reporting_metadata.last_syncs = []
     user.save()
     super().tearDown()
Пример #46
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)
    """
    def _create_temp_user(user_id):
        username = get_username_from_forms(domain, user_id).lower()
        temp_user = TempCommCareUser(domain, username, user_id)
        if user_filter[temp_user.filter_flag].show:
            return temp_user
        return None

    user_ids = user_ids or []
    user_ids = [_f for _f in user_ids if _f]  # remove empty strings if any
    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:
        try:
            users = []
            for id in user_ids:
                user = CommCareUser.get_by_user_id(id)
                if not user and (user_filter[HQUserType.ADMIN].show
                                 or user_filter[HQUserType.DEMO_USER].show
                                 or user_filter[HQUserType.UNKNOWN].show):
                    user = _create_temp_user(id)
                if user:
                    users.append(user)
        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 = set(get_all_user_ids_submitted(domain))
        registered_users_by_id = dict([
            (user.user_id, user) for user in CommCareUser.by_domain(domain)
        ])
        if include_inactive:
            registered_users_by_id.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_users_by_id and user_filter[
                    HQUserType.ACTIVE].show:
                user = registered_users_by_id[user_id]
                users.append(user)
            elif (user_id not in registered_users_by_id
                  and (user_filter[HQUserType.ADMIN].show
                       or user_filter[HQUserType.DEMO_USER].show
                       or user_filter[HQUserType.UNKNOWN].show)):
                user = _create_temp_user(user_id)
                if user:
                    users.append(user)
        if user_filter[HQUserType.UNKNOWN].show:
            users.append(TempCommCareUser(domain, '*', None))

        if user_filter[HQUserType.ACTIVE].show:
            # now add all the registered users who never submitted anything
            users.extend(user for id, user in registered_users_by_id.items()
                         if id not in submitted_user_ids)

    if simplified:
        return [_report_user_dict(user) for user in users]
    return users
Пример #47
0
def _run_fixture_upload(domain, workbook, replace=False, task=None):
    from corehq.apps.users.bulkupload import GroupMemoizer
    return_val = FixtureUploadResult()
    group_memoizer = GroupMemoizer(domain)
    get_location = get_memoized_location_getter(domain)
    data_types = []

    with CouchTransaction() as transaction:
        type_sheets = workbook.get_all_type_sheets()
        total_tables = len(type_sheets)
        return_val.number_of_fixtures = total_tables

        def _update_progress(table_count, item_count, items_in_table):
            if task:
                processed = table_count * 10 + (10 * item_count / items_in_table)
                DownloadBase.set_progress(task, processed, 10 * total_tables)

        for table_number, table_def in enumerate(type_sheets):
            tag = table_def.table_id
            new_data_type = FixtureDataType(
                domain=domain,
                is_global=table_def.is_global,
                tag=tag,
                fields=table_def.fields,
                item_attributes=table_def.item_attributes
            )
            try:
                tagged_fdt = FixtureDataType.fixture_tag_exists(domain, tag)
                if tagged_fdt:
                    data_type = tagged_fdt
                # support old usage with 'UID'
                elif table_def.uid:
                    data_type = FixtureDataType.get(table_def.uid)
                else:
                    data_type = new_data_type

                if replace and data_type != new_data_type:
                    data_type.recursive_delete(transaction)
                    data_type = new_data_type

                data_type.fields = table_def.fields
                data_type.item_attributes = table_def.item_attributes
                data_type.is_global = table_def.is_global
                assert data_type.doc_type == FixtureDataType._doc_type
                if data_type.domain != domain:
                    data_type = new_data_type
                    return_val.errors.append(
                        _("'%(UID)s' is not a valid UID. But the new type is created.")
                        % {'UID': table_def.uid}
                    )
                if table_def.delete:
                    data_type.recursive_delete(transaction)
                    continue
            except (ResourceNotFound, KeyError):
                data_type = new_data_type
            transaction.save(data_type)
            data_types.append(data_type)
            data_items = list(workbook.get_data_sheet(data_type.tag))
            items_in_table = len(data_items)
            for sort_key, di in enumerate(data_items):
                _update_progress(table_number, sort_key, items_in_table)
                type_fields = data_type.fields
                item_fields = {}
                for field in type_fields:
                    # if field doesn't have properties
                    if len(field.properties) == 0:
                        item_fields[field.field_name] = FieldList(
                            field_list=[FixtureItemField(
                                # using unicode here, to cast ints, and multi-language strings
                                field_value=six.text_type(di['field'][field.field_name]),
                                properties={}
                            )]
                        )
                    else:
                        field_list = []
                        field_prop_combos = di['field'][field.field_name]
                        prop_combo_len = len(field_prop_combos)
                        prop_dict = di[field.field_name]
                        for x in range(0, prop_combo_len):
                            fix_item_field = FixtureItemField(
                                field_value=six.text_type(field_prop_combos[x]),
                                properties={prop: six.text_type(prop_dict[prop][x]) for prop in prop_dict}
                            )
                            field_list.append(fix_item_field)
                        item_fields[field.field_name] = FieldList(
                            field_list=field_list
                        )

                item_attributes = di.get('property', {})
                new_data_item = FixtureDataItem(
                    domain=domain,
                    data_type_id=data_type.get_id,
                    fields=item_fields,
                    item_attributes=item_attributes,
                    sort_key=sort_key
                )
                try:
                    if di['UID'] and not replace:
                        old_data_item = FixtureDataItem.get(di['UID'])
                    else:
                        old_data_item = new_data_item
                        pass
                    old_data_item.fields = item_fields
                    old_data_item.item_attributes = item_attributes
                    if old_data_item.domain != domain \
                            or not old_data_item.data_type_id == data_type.get_id:
                        old_data_item = new_data_item
                        return_val.errors.append(
                            _("'%(UID)s' is not a valid UID. But the new item is created.")
                            % {'UID': di['UID']}
                        )
                    assert old_data_item.doc_type == FixtureDataItem._doc_type
                    if di[DELETE_HEADER] == "Y" or di[DELETE_HEADER] == "y":
                        old_data_item.recursive_delete(transaction)
                        continue
                except (ResourceNotFound, KeyError):
                    old_data_item = new_data_item
                transaction.save(old_data_item)

                old_groups = old_data_item.groups
                for group in old_groups:
                    old_data_item.remove_group(group)
                old_users = old_data_item.users
                for user in old_users:
                    old_data_item.remove_user(user)
                old_locations = old_data_item.locations
                for location in old_locations:
                    old_data_item.remove_location(location)

                for group_name in di.get('group', []):
                    group = group_memoizer.by_name(group_name)
                    if group:
                        old_data_item.add_group(group, transaction=transaction)
                    else:
                        return_val.errors.append(
                            _("Unknown group: '%(name)s'. But the row is successfully added")
                            % {'name': group_name}
                        )

                for raw_username in di.get('user', []):
                    try:
                        username = normalize_username(str(raw_username), domain)
                    except ValidationError:
                        return_val.errors.append(
                            _("Invalid username: '******'. Row is not added")
                            % {'name': raw_username}
                        )
                        continue
                    user = CommCareUser.get_by_username(username)
                    if user:
                        old_data_item.add_user(user)
                    else:
                        return_val.errors.append(
                            _("Unknown user: '******'. But the row is successfully added")
                            % {'name': raw_username}
                        )

                for name in di.get('location', []):
                    location_cache = get_location(name)
                    if location_cache.is_error:
                        return_val.errors.append(location_cache.message)
                    else:
                        old_data_item.add_location(location_cache.location,
                                                   transaction=transaction)

    clear_fixture_quickcache(data_types)
    clear_fixture_cache(domain)
    return return_val
Пример #48
0
 def create_user(username):
     return CommCareUser.create(self.domain,
                                format_username(username, self.domain),
                                password, None, None)
Пример #49
0
def _mk_user(domain):
    return CommCareUser(domain=domain,
                        domain_membership=DomainMembership(domain=domain))
Пример #50
0
 def make_user(name, location):
     user = CommCareUser.create(cls.domain, name, 'password')
     user.set_location(location)
     return user
 def setUpClass(cls):
     super(MarkLatestSubmissionTest, cls).setUpClass()
     cls.user = CommCareUser.create(cls.domain, cls.username, cls.password)
Пример #52
0
 def obj_delete(self, bundle, **kwargs):
     user = CommCareUser.get(kwargs['pk'])
     if user:
         user.retire(deleted_by=bundle.request.user, deleted_via=USER_CHANGE_VIA_API)
     return ImmediateHttpResponse(response=http.HttpAccepted())
Пример #53
0
    def handle(self):
        text = ' '.join(self.msg.text.split()[1:])
        is_district = False
        sp = ""
        msd_code = ""
        params = {}

        if text.find(self.DISTRICT_REG_DELIMITER) != -1:
            phrases = [x.strip() for x in text.split(":")]
            if len(phrases) != 2:
                self.respond(REGISTER_HELP)
                return True
            name = phrases[0]
            sp = phrases[1]
            role = Roles.DISTRICT_PHARMACIST
            message = REGISTRATION_CONFIRM_DISTRICT
            is_district = True
        else:
            names = []
            msd_codes = []
            location_regex = '^({prefs})\d+'.format(prefs='|'.join(p.lower() for p in DISTRICT_PREFIXES))
            for the_string in self.args:
                if re.match(location_regex, the_string.strip().lower()):
                    msd_codes.append(the_string.strip().lower())
                else:
                    names.append(the_string)

            name = " ".join(names)
            if len(msd_codes) != 1:
                self.respond(REGISTER_HELP)
                return True
            else:
                [msd_code] = msd_codes

            role = Roles.IN_CHARGE
            message = REGISTRATION_CONFIRM

        if is_district:
            try:
                loc = self._get_district_location(self.domain, sp)
                params['sdp_name'] = loc.name
            except SQLLocation.DoesNotExist:
                self.respond(REGISTER_UNKNOWN_DISTRICT, name=sp)
                return True
        else:
            try:
                loc = self._get_facility_location(self.domain, msd_code)
                params['sdp_name'] = loc.name
                params['msd_code'] = loc.site_code
            except SQLLocation.DoesNotExist:
                self.respond(REGISTER_UNKNOWN_CODE, msd_code=msd_code)
                return True

        split_name = name.split(' ', 2)
        first_name = ''
        last_name = ''
        if len(split_name) == 2:
            first_name, last_name = split_name
        elif split_name:
            first_name = split_name[0]

        if not self.user:
            key = u'generating ils username for %s, %s, %s' % (self.domain, first_name, last_name)
            with CriticalSection([key]):
                username = generate_username(self.domain, first_name, last_name)
                password = uuid.uuid4().hex
                self.user = CommCareUser.create(
                    self.domain,
                    username,
                    password,
                    phone_number=strip_plus(self.msg.phone_number)
                )
            self.verified_contact = self.user.get_or_create_phone_entry(self.msg.phone_number)
            self.verified_contact.set_two_way()
            self.verified_contact.set_verified()
            self.verified_contact.save()
            # As per earlier ILSGateway system, set language by default to Swahili
            self.user.language = 'sw'

        if first_name or last_name:
            self.user.first_name = first_name
            self.user.last_name = last_name
        self.user.set_location(loc)
        self.user.is_active = True
        self.user.user_data['role'] = role
        self.user.save()
        params['contact_name'] = name

        if params:
            self.respond(message, **params)
        return True
 def tearDown(self):
     user = CommCareUser.get(self.ccuser._id)
     user.reporting_metadata.last_syncs = []
     user.save()
     UserReportingMetadataStaging.objects.all().delete()
     super().tearDown()
 def setUpClass(cls):
     super(DigestOtaRestoreTest, cls).setUpClass()
     create_domain(cls.domain)
     create_domain(cls.wrong_domain)
     cls.commcare_user = CommCareUser.create(cls.domain, cls.username, cls.password)
     cls.web_user = WebUser.create(cls.domain, cls.web_username, cls.password)
Пример #56
0
def get_commcare_user(domain_name):
    user = CommCareUser.create(domain_name, 'username', 'pw', None, None)
    try:
        yield user
    finally:
        user.delete(deleted_by=None)
Пример #57
0
    def setUpClass(cls):
        super(ChatHistoryTestCase, cls).setUpClass()
        cls.domain = 'sms-chat-history-test-domain'
        cls.domain_obj = Domain(name=cls.domain)
        cls.domain_obj.save()

        cls.contact1_id = uuid.uuid4().hex
        cls.contact2_id = uuid.uuid4().hex
        cls.contact3 = CommCareUser.create(cls.domain, 'user1', '123')

        cls.chat_user = CommCareUser.create(cls.domain, 'user2', '123')
        cls.chat_user.first_name = 'Sam'
        cls.chat_user.save()

        cls.outgoing_from_system = SMS.objects.create(
            domain=cls.domain,
            direction=OUTGOING,
            date=datetime(2016, 2, 18, 0, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='Remember your appointment tomorrow',
            chat_user_id=None,
            processed=True,
            xforms_session_couch_id=None,
            invalid_survey_response=False,
        )

        cls.outgoing_not_processed = SMS.objects.create(
            domain=cls.domain,
            direction=OUTGOING,
            date=datetime(2016, 2, 18, 1, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='Remember your appointment next week',
            chat_user_id=None,
            processed=False,
            xforms_session_couch_id=None,
            invalid_survey_response=False,
        )

        cls.outgoing_from_chat = SMS.objects.create(
            domain=cls.domain,
            direction=OUTGOING,
            date=datetime(2016, 2, 18, 2, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='How are you?',
            chat_user_id=cls.chat_user.get_id,
            processed=True,
            xforms_session_couch_id=None,
            invalid_survey_response=False,
        )

        cls.incoming_not_processed = SMS.objects.create(
            domain=cls.domain,
            direction=INCOMING,
            date=datetime(2016, 2, 18, 3, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='Good',
            chat_user_id=None,
            processed=False,
            xforms_session_couch_id=None,
            invalid_survey_response=False,
        )

        cls.incoming_survey_answer1 = SMS.objects.create(
            domain=cls.domain,
            direction=INCOMING,
            date=datetime(2016, 2, 18, 4, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='x',
            chat_user_id=None,
            processed=True,
            xforms_session_couch_id='session-id',
            invalid_survey_response=True,
        )

        cls.outgoing_survey_response1 = SMS.objects.create(
            domain=cls.domain,
            direction=OUTGOING,
            date=datetime(2016, 2, 18, 5, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='Invalid Response',
            chat_user_id=None,
            processed=True,
            xforms_session_couch_id='session-id',
            invalid_survey_response=True,
        )

        cls.incoming_survey_answer2 = SMS.objects.create(
            domain=cls.domain,
            direction=INCOMING,
            date=datetime(2016, 2, 18, 6, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='1',
            chat_user_id=None,
            processed=True,
            xforms_session_couch_id='session-id',
            invalid_survey_response=False,
        )

        cls.outgoing_survey_response2 = SMS.objects.create(
            domain=cls.domain,
            direction=OUTGOING,
            date=datetime(2016, 2, 18, 7, 0),
            couch_recipient_doc_type='CommCareCase',
            couch_recipient=cls.contact1_id,
            text='Thank you for completing the survey',
            chat_user_id=None,
            processed=True,
            xforms_session_couch_id='session-id',
            invalid_survey_response=False,
        )
Пример #58
0
 def payload_doc(self, repeat_record):
     return CommCareUser.get(repeat_record.payload_id)
Пример #59
0
def create_user_cases(domain_name):
    from corehq.apps.callcenter.sync_user_case import sync_usercase
    for user in CommCareUser.by_domain(domain_name):
        sync_usercase(user)
Пример #60
0
 def user(self):
     return CommCareUser.get_by_username('{}@{}.commcarehq.org'.format(
         'hello', self.domain.name))