def setUp(self):
        super(TestDeleteDomain, self).setUp()
        self.domain = Domain(name="test", is_active=True)
        self.domain.save()
        self.domain.convert_to_commtrack()
        self.current_subscription = Subscription.new_domain_subscription(
            BillingAccount.get_or_create_account_by_domain(self.domain.name, created_by='tests')[0],
            self.domain.name,
            DefaultProductPlan.get_default_plan_version(SoftwarePlanEdition.ADVANCED),
            date_start=date.today() - relativedelta(days=1),
        )

        self.domain2 = Domain(name="test2", is_active=True)
        self.domain2.save()
        self.domain2.convert_to_commtrack()

        LocationType.objects.create(
            domain='test',
            name='facility',
        )
        LocationType.objects.create(
            domain='test2',
            name='facility',
        )
        LocationType.objects.create(
            domain='test',
            name='facility2',
        )
        LocationType.objects.create(
            domain='test2',
            name='facility2',
        )
    def handle(self, *args, **options):
        domains = Domain.get_all()
        seen = set([])
        dups = set([])
        for domain in domains:
            if domain.name in seen:
                dups.add(domain.name)
            else:
                seen.add(domain.name)

        if not dups:
            self.stdout.write('Found no duplicate domains\n')

        for domain in list(dups):
            real_dom = Domain.get_by_name(domain)
            total_doms = Domain.view("domain/domains",
                key=domain,
                reduce=False,
                include_docs=True,
            ).all()
            fake_doms = [d for d in total_doms if d.get_id != real_dom.get_id]

            self.stdout.write('Found Dup: %s\n' % domain)
            self.stdout.write(" -- _id of correct domain: %s\n" % real_dom.get_id)
            self.stdout.write(" -- ids of duplicate domains: %s\n" % [d.get_id for d in fake_doms])

            for dom in fake_doms:
                dom.doc_type = 'Domain-DUPLICATE'
                dom.save()
Exemple #3
0
class TestCaseListFilter(TestCase):
    def setUp(self):
        self.subject = CaseListFilter
        self.domain = Domain(name='test', is_active=True)
        self.domain.save()
        self.location_type = LocationType.objects.create(domain=self.domain.name, name='testtype')
        self.user_assigned_locations = [
            make_loc('root', domain=self.domain.name, type=self.location_type).sql_location
        ]
        self.request = RequestFactory()
        self.request.couch_user = WebUser()
        self.request.domain = self.domain

    @patch('corehq.apps.users.models.WebUser.get_sql_locations')
    def test_default_selections_for_full_access(self, assigned_locations_patch):
        self.request.can_access_all_locations = True
        self.request.project = self.domain
        emwf = self.subject(self.request)
        default_selections = emwf.get_default_selections()
        self.assertEqual(default_selections, emwf.default_selections)
        assert not assigned_locations_patch.called

    @patch('corehq.apps.users.models.WebUser.get_sql_locations')
    def test_default_selections_for_restricted_access(self, assigned_locations_patch):
        self.request.can_access_all_locations = False
        self.request.project = self.domain
        emwf = self.subject(self.request)
        emwf.get_default_selections()
        assert assigned_locations_patch.called
class OtaV3RestoreTest(TestCase):
    """Tests OTA Restore v3"""

    def setUp(self):
        self.domain = 'dummy-project'
        self.project = Domain(name=self.domain)
        self.project.save()
        delete_all_cases()
        delete_all_sync_logs()
        delete_all_users()

    def tearDown(self):
        self.project.delete()

    def testUserRestoreWithCase(self):
        restore_user = create_restore_user(domain=self.domain)
        case_id = 'my-case-id'
        device = MockDevice(self.project, restore_user)
        device.change_cases(CaseBlock(
            create=True,
            case_id=case_id,
            user_id=restore_user.user_id,
            owner_id=restore_user.user_id,
            case_type='test-case-type',
            update={'external_id': 'someexternal'},
        ))
        self.assertIn(case_id, device.sync().cases)
Exemple #5
0
def create_user_and_domain(username='******', 
                           password='******',
                           domain_name='mockdomain'):
    """Creates a domain 'mockdomain' and a web user with name/pw 
       'brian'/'test'.  Returns these two objects in a tuple 
       as (domain, user).  The parameters are configurable."""
    try:
        domain = Domain.get_by_name(domain_name)
        print "WARNING: tried to create domain %s but it already exists!" % domain_name
        print "Are all your tests cleaning up properly?"
    except Domain.DoesNotExist:
        # this is the normal case
        domain = Domain(name=domain_name, is_active=True)
        domain.save()
    
    try:
        user = User.objects.get(username=username)
        print "WARNING: tried to create user %s but it already exists!" % username
        print "Are all your tests cleaning up properly?"
        # update the pw anyway
        user.password = _get_salted_pw(password)
        user.save()
    except User.DoesNotExist:
        user = User()
        user.username = username
        # here, we mimic what the django auth system does
        # only we specify the salt to be 12345
        user.password = _get_salted_pw(password)
        
        user.save()
        
    return (user, domain)
Exemple #6
0
def redirect_to_default(req, domain=None):
    if not req.user.is_authenticated():
        if domain != None:
            url = reverse('domain_login', args=[domain])
        else:
            # this actually gets hijacked by the static site, but is necessary
            url = reverse('corehq.apps.hqwebapp.views.landing_page')
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)
        if 0 == len(domains) and not req.user.is_superuser:
            return redirect('registration_domain')
        elif 1 == len(domains):
            if domains[0]:
                domain = domains[0].name
                if req.couch_user.is_commcare_user():
                    if not is_mobile_worker_with_report_access(
                            req.couch_user, domain):
                        url = reverse("cloudcare_main", args=[domain, ""])
                    else:
                        url = reverse("saved_reports", args=[domain])
                elif req.couch_user.can_view_reports(domain) or req.couch_user.get_viewable_reports(domain):
                    url = reverse('corehq.apps.reports.views.default', args=[domain])
                else:
                    url = reverse('corehq.apps.app_manager.views.default', args=[domain])
            else:
                raise Http404
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Exemple #7
0
    def setUp(self):
        super(BaseReminderTestCase, self).setUp()
        self.domain_obj = Domain(name="test")
        self.domain_obj.save()
        # Prevent resource conflict
        self.domain_obj = Domain.get(self.domain_obj._id)

        self.account, _ = BillingAccount.get_or_create_account_by_domain(
            self.domain_obj.name,
            created_by="tests"
        )
        advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain(
            self.domain_obj, edition=SoftwarePlanEdition.ADVANCED)
        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain_obj.name,
            advanced_plan_version
        )
        self.subscription.is_active = True
        self.subscription.save()

        self.sms_backend = TestSMSBackend(named="MOBILE_BACKEND_TEST", is_global=True)
        self.sms_backend.save()

        self.sms_backend_mapping = BackendMapping(is_global=True,prefix="*",backend_id=self.sms_backend._id)
        self.sms_backend_mapping.save()
Exemple #8
0
class UpdateTestCase(TestCase):

    def setUp(self):
        super(UpdateTestCase, self).setUp()
        delete_all_users()
        self.username = "******"
        password = "******"
        self.domain = Domain(name='my-domain')
        self.domain.save()
        self.couch_user = CommCareUser.create(self.domain.name, self.username, password)
        self.couch_user.save()
        
    def testAddRemovePhoneNumbers(self):
        """ 
        test that a basic couch user gets created properly after 
        saving a django user programmatically
        """
        self.couch_user.add_phone_number('123123123')
        self.assertEqual(self.couch_user.phone_numbers, ['123123123'])
        self.couch_user.add_phone_number('321321321')
        self.assertEqual(self.couch_user.phone_numbers, ['123123123', '321321321'])

    def testChangeUsername(self):
        new_username = '******'
        self.assertEqual(CouchUser.get_by_username(self.username).user_id, self.couch_user.user_id)
        self.assertEqual(User.objects.filter(username=self.username).count(), 1)
        self.couch_user.change_username(new_username)
        self.assertEqual(CouchUser.get_by_username(self.username), None)
        self.assertEqual(CouchUser.get_by_username(new_username).user_id, self.couch_user.user_id)
        self.assertEqual(self.couch_user.get_django_user().username, new_username)
        self.assertEqual(User.objects.filter(username=new_username).count(), 1)
        self.assertEqual(User.objects.get(username=new_username).id, self.couch_user.get_django_user().id)
        self.assertEqual(User.objects.filter(username=self.username).count(), 0)
def arbitrary_domain():
    domain = Domain(
        name=data_gen.arbitrary_unique_name()[:20],
        is_active=True,
    )
    domain.save()
    return domain
Exemple #10
0
    def create_domain(self, domain):
        domain_obj = Domain(name=domain)
        domain_obj.use_default_sms_response = True
        domain_obj.default_sms_response = "Default SMS Response"
        domain_obj.save()

        # I tried making this class inherit from BaseSMSTest, but somehow
        # the multiple inheritance was causing the postgres connection to
        # get in a weird state where it wasn't commiting any changes. So
        # for now, keeping this subscription setup code as is.
        generator.instantiate_accounting_for_tests()
        self.account = BillingAccount.get_or_create_account_by_domain(
            domain_obj.name,
            created_by="automated-test",
        )[0]
        plan = DefaultProductPlan.get_default_plan_by_domain(
            domain_obj, edition=SoftwarePlanEdition.ADVANCED
        )
        self.subscription = Subscription.new_domain_subscription(
            self.account,
            domain_obj.name,
            plan
        )
        self.subscription.is_active = True
        self.subscription.save()
        return domain_obj
def domains_for_user(request, selected_domain=None):
    lst = list()
    lst.append('<ul class="dropdown-menu nav-list dropdown-orange">')
    new_domain_url = reverse("registration_domain")
    if selected_domain == 'public':
        # viewing the public domain with a different db, so the user's domains can't readily be accessed.
        lst.append('<li><a href="%s">Back to My Projects...</a></li>' % reverse("domain_select"))
        lst.append('<li class="divider"></li>')
    else:
        try:
            domain_list = Domain.active_for_user(request.couch_user)
        except Exception:
            if settings.DEBUG:
                raise
            else:
                domain_list = Domain.active_for_user(request.user)
                notify_exception(request)

        if len(domain_list) > 0:
            lst.append('<li class="nav-header">My Projects</li>')
            for domain in domain_list:
                default_url = reverse("domain_homepage", args=[domain.name])
                lst.append('<li><a href="%s">%s</a></li>' % (default_url, domain.long_display_name()))
        else:
            lst.append('<li class="nav-header">No Projects</li>')
    lst.append('<li class="divider"></li>')
    lst.append('<li><a href="%s">New Project...</a></li>' % new_domain_url)
    lst.append('<li><a href="%s">CommCare Exchange...</a></li>' % reverse("appstore"))
    lst.append("</ul>")

    return "".join(lst)
 def setUp(self):
     self.domain = Domain(name="test", is_active=True)
     self.domain.save()
     self.domain.convert_to_commtrack()
     self.domain2 = Domain(name="test2", is_active=True)
     self.domain2.save()
     self.domain2.convert_to_commtrack()
     LocationType.objects.create(
         domain='test',
         name='facility',
     )
     LocationType.objects.create(
         domain='test2',
         name='facility',
     )
     LocationType.objects.create(
         domain='test',
         name='facility2',
     )
     LocationType.objects.create(
         domain='test2',
         name='facility2',
     )
     for i in xrange(2):
         self._create_data('test', i)
         self._create_data('test2', i)
    def handle(self, *args, **options):
        if options.get('domain'):
            domains = [Domain.get_by_name(options.get('domain'))]
        else:
            domains = Domain.get_all()

        since = options.get('since')
        seen_since = False
        for d in domains:
            if since and not seen_since:
                if d.name == since:
                    seen_since = True
                else:
                    continue

            if d.name in DOMS_TO_IGNORE:
                continue
            try:
                for app in d.full_applications():
                    try:
                        if app.is_remote_app():
                            continue
                        for _, m in app.get_media_objects():
                            if app.domain not in m.valid_domains:
                                m.valid_domains.append(app.domain)
                                self.stdout.write("adding domain %s to media file %s" % (app.domain, m._id))
                                m.save()
                    except Exception as e:
                        self.stdout.write("Error in app %s-%s: %s" % (app.domain, app._id, e))
            except Exception as e:
                self.stdout.write("Error in domain %s: %s" % (d.name, e))
Exemple #14
0
def redirect_to_default(req, domain=None):
    if not req.user.is_authenticated():
        if domain != None:
            url = reverse('domain_login', args=[domain])
        else:
            try:
                from corehq.apps.prelogin.views import HomePublicView
                url = reverse(HomePublicView.urlname)
            except ImportError:
                # this happens when the prelogin app is not included.
                url = reverse('landing_page')
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)
        if 0 == len(domains) and not req.user.is_superuser:
            return redirect('registration_domain', domain_type=get_domain_type(None, req))
        elif 1 == len(domains):
            if domains[0]:
                domain = domains[0].name

                if (req.couch_user.is_commcare_user()
                    and not is_mobile_worker_with_report_access(
                        req.couch_user, domain)):
                    url = reverse("cloudcare_main", args=[domain, ""])
                else:
                    url = reverse('dashboard_default', args=[domain])

            else:
                raise Http404
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Exemple #15
0
def appstore(request, template="appstore/appstore_base.html", sort_by=None):
    page = int(request.GET.get('page', 1))
    include_unapproved = (request.user.is_superuser and request.GET.get('unapproved', False))
    if not sort_by:
        results = Domain.published_snapshots(include_unapproved=include_unapproved, page=page, per_page=PER_PAGE)
        more_pages = page * PER_PAGE < results.total_rows and len(results) == PER_PAGE # hacky way to deal with approved vs unapproved
    else:
        total_results = Domain.published_snapshots(include_unapproved=include_unapproved)
        if sort_by == 'best':
            results = Domain.popular_sort(total_results, page)
            #more_pages = page * PER_PAGE < total_results and page <= 10
        elif sort_by == 'hits':
            results = Domain.hit_sort(total_results, page)
            #more_pages = page * PER_PAGE < len(total_results) and page <= 10
        more_pages = page * PER_PAGE < total_results.total_rows and len(results) == PER_PAGE # hacky way to deal with approved vs unapproved
    average_ratings = list()
    for result in results:
        average_ratings.append([result.name, Review.get_average_rating_by_app(result.original_doc)])

    return render_to_response(request, template, _appstore_context({
        'apps': results,
        'average_ratings': average_ratings,
        'page': page,
        'prev_page': (page-1),
        'next_page': (page+1),
        'more_pages': more_pages,
        'sort_by': sort_by,
        'include_unapproved': include_unapproved
    }))
    def setUp(self):
        self.domain = Domain(name="test", is_active=True)
        self.domain.save()
        self.domain2 = Domain(name="test2", is_active=True)
        self.domain2.save()

        StockDataCheckpoint.objects.create(
            domain='test',
            api='test',
            limit=100,
            offset=0
        )

        StockDataCheckpoint.objects.create(
            domain='test2',
            api='test',
            limit=100,
            offset=0
        )

        MigrationCheckpoint.objects.create(
            domain='test',
            api='test',
            limit=100,
            offset=0
        )

        MigrationCheckpoint.objects.create(
            domain='test2',
            api='test',
            limit=100,
            offset=0
        )
Exemple #17
0
class TestDomainViews(TestCase):
    def setUp(self):
        self.client = Client()

        self.domain = Domain(name="fandago", is_active=True)
        self.domain.save()

        self.username = '******'
        self.password = '******'
        self.user = WebUser.create(self.domain.name, self.username, self.password)
        self.user.set_role(self.domain.name, 'admin')
        self.user.save()

    def tearDown(self):
        self.user.delete()
        self.domain.delete()
        
    def test_add_repeater(self):
        forwarding_url = 'https://example.com/forwarding'

        self.client.login(username=self.username, password=self.password)

        post_url = reverse('add_repeater', kwargs={'domain': self.domain.name, 'repeater_type': 'AppStructureRepeater'})
        response = self.client.post(post_url, {'url': forwarding_url}, follow=True)
        self.assertEqual(response.status_code, 200)

        self.client.logout()
        
        app_structure_repeaters = AppStructureRepeater.by_domain(self.domain.name)
        self.assertEqual(len(app_structure_repeaters), 1)

        for app_structure_repeater in app_structure_repeaters:
            app_structure_repeater.delete()
Exemple #18
0
    def get_billable_domains(cls):
        marked_domains = SMSBillable.get_db().view('hqbilling/domains_marked_for_billing', reduce=False).all()

        prev_month, _ = HQMonthlyBill.get_default_start_end()

        recent = SMSBillable.get_db().view('hqbilling/domains_with_billables',
                                           startkey=[prev_month.year, prev_month.month],
                                           group=True,
                                           group_level=3).all()
        
        recent_counts = defaultdict(int)
        for r in recent:
            recent_counts[r['key'][-1]] += r['value']
        for m in marked_domains:
            if m['key'] not in recent_counts.keys():
                recent_counts[m['key']] = 0

        all_time = SMSBillable.get_db().view('hqbilling/domains_with_billables',
                                             group=True,
                                             group_level=3).all()
        all_time_counts = defaultdict(int)
        for a in all_time:
            if a['key'][-1] not in recent_counts.keys():
                all_time_counts[a['key'][-1]] += a['value']

        sorted_recent = sorted(recent_counts.iteritems(), key=operator.itemgetter(1), reverse=True)
        sorted_all_time = sorted(all_time_counts.iteritems(), key=operator.itemgetter(1), reverse=True)

        return [Domain.get_by_name(r[0]) for r in sorted_recent if r[0]] + \
               [Domain.get_by_name(a[0]) for a in sorted_all_time if a[0]]
class DomainCalculatedPropertiesTest(TestCase):

    @classmethod
    def setUpClass(cls):
        super(DomainCalculatedPropertiesTest, cls).setUpClass()
        cls.es = [{
            'info': i,
            'instance': get_es_new(),
        } for i in [CASE_INDEX_INFO, SMS_INDEX_INFO, XFORM_INDEX_INFO]]

    def setUp(self):
        self.domain = Domain(name='test-b9289e19d819')
        self.domain.save()
        for es in self.es:
            ensure_index_deleted(es['info'].index)
            initialize_index_and_mapping(es['instance'], es['info'])

    def tearDown(self):
        self.domain.delete()

    def test_sanity(self):
        all_stats = all_domain_stats()
        props = calced_props(self.domain, self.domain._id, all_stats)
        self.assertFalse(props['cp_has_app'])
        # ensure serializable
        json.dumps(props)
Exemple #20
0
def tearDownModule():
    if settings.USE_PARTITIONED_DATABASE:
        return

    _call_center_domain_mock = mock.patch(
        'corehq.apps.callcenter.data_source.call_center_data_source_configuration_provider'
    )
    _call_center_domain_mock.start()
    with override_settings(SERVER_ENVIRONMENT='icds'):
        configs = StaticDataSourceConfiguration.by_domain('icds-cas')
        adapters = [get_indicator_adapter(config) for config in configs]
        for adapter in adapters:
            if adapter.config.table_id == 'static-child_health_cases':
                # hack because this is in a migration
                adapter.clear_table()
                continue
            adapter.drop_table()

        engine = connection_manager.get_engine(ICDS_UCR_ENGINE_ID)
        with engine.begin() as connection:
            metadata = sqlalchemy.MetaData(bind=engine)
            metadata.reflect(bind=engine, extend_existing=True)
            table = metadata.tables['ucr_table_name_mapping']
            delete = table.delete()
            connection.execute(delete)
    LocationType.objects.filter(domain='icds-cas').delete()
    SQLLocation.objects.filter(domain='icds-cas').delete()

    Domain.get_by_name('icds-cas').delete()
    _call_center_domain_mock.stop()
Exemple #21
0
class TestSubscriptionChangeResourceConflict(BaseAccountingTest):

    def setUp(self):
        self.domain_name = 'test-domain-changes'
        self.domain = Domain(
            name=self.domain_name,
            is_active=True,
            description='spam',
        )
        self.domain.save()

    def test_domain_changes(self):
        role = Mock()
        role.memberships_granted.all.return_value = []
        version = Mock()
        version.role.get_cached_role.return_value = role
        handler = DomainDowngradeActionHandler(
            self.domain, new_plan_version=version, changed_privs=REPORT_BUILDER_ADD_ON_PRIVS
        )

        conflicting_domain = Domain.get_by_name(self.domain_name)
        conflicting_domain.description = 'eggs'
        conflicting_domain.save()

        get_by_name_func = Domain.get_by_name
        with patch('corehq.apps.accounting.subscription_changes.Domain') as Domain_patch:
            Domain_patch.get_by_name.side_effect = lambda name: get_by_name_func(name)
            handler.get_response()
            Domain_patch.get_by_name.assert_called_with(self.domain_name)
Exemple #22
0
 def d_results(self):
     hits = self.results.get('hits', {}).get('hits', [])
     hits = deduplicate(hits)
     d_results = []
     for res in hits:
         try:
             domain = Domain.wrap(res['_source'])
             if domain.copied_from is not None:
                 # this avoids putting in snapshots in the list where the
                 # copied_from domain has been deleted.
                 d_results.append(domain)
         except CopiedFromDeletedException as e:
             notify_exception(
                 self.request,
                 message=(
                     "Fetched Exchange Snapshot Error: {}. "
                     "The problem snapshot id: {}".format(
                         e.message, res['_source']['_id'])
                 )
             )
     if self.sort_by == 'newest':
         pass
     else:
         d_results = Domain.hit_sort(d_results)
     return d_results
def domains_for_user(request, selected_domain=None):
    """
    Generate pulldown menu for domains.
    Cache the entire string alongside the couch_user's doc_id that can get invalidated when
    the user doc updates via save.
    """
    domain_list = []
    if selected_domain != 'public':
        cached_domains = cache_core.get_cached_prop(request.couch_user.get_id, 'domain_list')
        if cached_domains:
            domain_list = [Domain.wrap(x) for x in cached_domains]
        else:
            try:
                domain_list = Domain.active_for_user(request.couch_user)
                cache_core.cache_doc_prop(request.couch_user.get_id, 'domain_list', [x.to_json() for x in domain_list])
            except Exception:
                if settings.DEBUG:
                    raise
                else:
                    domain_list = Domain.active_for_user(request.user)
                    notify_exception(request)
    domain_list = [dict(
        url=reverse('domain_homepage', args=[d.name]),
        name=d.long_display_name()
    ) for d in domain_list]
    context = {
        'is_public': selected_domain == 'public',
        'domain_list': domain_list,
        'current_domain': selected_domain,
    }
    template = {
        style_utils.BOOTSTRAP_2: 'hqwebapp/partials/domain_list_dropdown.html',
        style_utils.BOOTSTRAP_3: 'style/includes/domain_list_dropdown.html',
    }[style_utils.bootstrap_version(request)]
    return mark_safe(render_to_string(template, context))
Exemple #24
0
 def setUp(self):
     super(LoadBalancingAndRateLimitingTestCase, self).setUp()
     self.domain = 'load-balance-rate-limit'
     self.domain_obj = Domain(name=self.domain)
     self.domain_obj.save()
     self.create_account_and_subscription(self.domain)
     self.domain_obj = Domain.get(self.domain_obj.get_id)
Exemple #25
0
class TestSubscription(BaseAccountingTest):

    def setUp(self):
        super(TestSubscription, self).setUp()
        self.billing_contact = generator.arbitrary_web_user()
        self.dimagi_user = generator.arbitrary_web_user(is_dimagi=True)
        self.domain = Domain(name='test')
        self.domain.save()
        self.currency = generator.init_default_currency()
        self.account = generator.billing_account(self.dimagi_user, self.billing_contact)
        self.subscription, self.subscription_length = generator.generate_domain_subscription_from_date(
            datetime.date.today(), self.account, self.domain.name
        )

    def test_creation(self):
        self.assertIsNotNone(self.subscription)

    def test_no_activation(self):
        tasks.activate_subscriptions(based_on_date=self.subscription.date_start - datetime.timedelta(30))
        subscription = Subscription.objects.get(id=self.subscription.id)
        self.assertFalse(subscription.is_active)

    def test_activation(self):
        tasks.activate_subscriptions(based_on_date=self.subscription.date_start)
        subscription = Subscription.objects.get(id=self.subscription.id)
        self.assertTrue(subscription.is_active)

    def test_no_deactivation(self):
        tasks.activate_subscriptions(based_on_date=self.subscription.date_start)
        tasks.deactivate_subscriptions(based_on_date=self.subscription.date_end - datetime.timedelta(30))
        subscription = Subscription.objects.get(id=self.subscription.id)
        self.assertTrue(subscription.is_active)

    def test_deactivation(self):
        tasks.deactivate_subscriptions(based_on_date=self.subscription.date_end)
        subscription = Subscription.objects.get(id=self.subscription.id)
        self.assertFalse(subscription.is_active)

    def test_deletions(self):
        self.assertRaises(models.ProtectedError, self.account.delete)
        self.assertRaises(models.ProtectedError, self.subscription.plan_version.delete)
        self.assertRaises(models.ProtectedError, self.subscription.subscriber.delete)

    def test_is_hidden_to_ops(self):
        self.subscription.is_hidden_to_ops = True
        self.subscription.save()
        self.assertEqual(0, len(Subscription.objects.filter(id=self.subscription.id)))

        self.subscription.is_hidden_to_ops = False
        self.subscription.save()
        self.assertEqual(1, len(Subscription.objects.filter(id=self.subscription.id)))

    def tearDown(self):
        self.billing_contact.delete()
        self.dimagi_user.delete()
        self.domain.delete()

        generator.delete_all_subscriptions()
        generator.delete_all_accounts()
        super(TestSubscription, self).tearDown()
Exemple #26
0
def run():
    from django.contrib.sites.models import Site

    django_site_1 = Site.objects.all()[0]
    django_site_1.domain = u'localhost:8000'
    django_site_1.name = u'localhost:8000'
    django_site_1.save()

    from corehq.apps.domain.models import Domain

    domain_domain_1 = Domain()
    domain_domain_1.name = u'test'
    domain_domain_1.is_active = True
    domain_domain_1.save()

    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u'admin'
    auth_user_1.first_name = u''
    auth_user_1.last_name = u''
    auth_user_1.email = u'*****@*****.**'
    auth_user_1.password = u'sha1$f8d4b$b6d2f6431c423687c227ad261caa46faaf16917d'
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.last_login = datetime.datetime(2010, 9, 10, 14, 40, 30, 501416)
    auth_user_1.date_joined = datetime.datetime(2010, 9, 10, 14, 37, 22, 677987)
    auth_user_1.save()

    auth_user_2 = User()
    auth_user_2.username = u'test'
    auth_user_2.first_name = u'test'
    auth_user_2.last_name = u'test'
    auth_user_2.email = u'*****@*****.**'
    auth_user_2.password = u'sha1$f09cf$551ac80804020ad3e1d9943a583ee1ea52284797'
    auth_user_2.is_staff = False
    auth_user_2.is_active = True
    auth_user_2.is_superuser = False
    auth_user_2.last_login = datetime.datetime(2010, 9, 10, 14, 40, 53, 818764)
    auth_user_2.date_joined = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    auth_user_2.save()

    couch_user = auth_user_2.get_profile().get_couch_user()
    couch_user.add_domain_membership(domain_domain_1.name)
    couch_user.save()

    from corehq.apps.domain.models import RegistrationRequest

    domain_registration_request_1 = RegistrationRequest()
    domain_registration_request_1.tos_confirmed = True
    domain_registration_request_1.request_time = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    domain_registration_request_1.request_ip = '127.0.0.1'
    domain_registration_request_1.activation_guid = u'368ce6b8bd1311df932c5cff350164a3'
    domain_registration_request_1.confirm_time = datetime.datetime(2010, 9, 10, 14, 40, 25, 219783)
    domain_registration_request_1.confirm_ip = '127.0.0.1'
    domain_registration_request_1.domain = domain_domain_1
    domain_registration_request_1.new_user = auth_user_2
    domain_registration_request_1.requesting_user = None
    domain_registration_request_1.save()
Exemple #27
0
def purge_locations(domain):
    """
    Delete all location data associated with <domain>.

    This means Locations, SQLLocations, LocationTypes, and anything which
    has a ForeignKey relationship to SQLLocation (as of 2015-03-02, this
    includes only StockStates and some custom stuff).
    """
    location_ids = set([r['id'] for r in Location.get_db().view(
        'locations/by_type',
        reduce=False,
        startkey=[domain],
        endkey=[domain, {}],
    ).all()])
    iter_bulk_delete(Location.get_db(), location_ids)

    for loc in SQLLocation.objects.filter(domain=domain).iterator():
        if loc.supply_point_id:
            case = CommCareCase.get(loc.supply_point_id)
            case.delete()
        loc.delete()

    db = Domain.get_db()
    domain_obj = Domain.get_by_name(domain)  # cached lookup is fast but stale
    domain_json = db.get(domain_obj._id)  # get latest raw, unwrapped doc
    domain_json.pop('obsolete_location_types', None)
    domain_json.pop('location_types', None)
    db.save_doc(domain_json)
class OtaV3RestoreTest(TestCase):
    """Tests OTA Restore v3"""

    def setUp(self):
        self.domain = 'dummy-project'
        self.project = Domain(name=self.domain)
        self.project.save()
        delete_all_cases()
        delete_all_sync_logs()
        delete_all_users()

    def tearDown(self):
        self.project.delete()

    def testUserRestoreWithCase(self):
        restore_user = create_restore_user(domain=self.domain)
        expected_case_block = CaseBlock(
            create=True,
            case_id='my-case-id',
            user_id=restore_user.user_id,
            owner_id=restore_user.user_id,
            case_type='test-case-type',
            update={'external_id': 'someexternal'},
        )
        _, [case] = post_case_blocks([expected_case_block.as_xml()], {'domain': self.domain})

        assert_user_has_case(self, restore_user, case.case_id)
Exemple #29
0
    def get_reports(self, domain=None):
        attr_name = self.map_name
        from corehq import reports
        if domain:
            project = Domain.get_by_name(domain)
        else:
            project = None

        def process(reports):
            if project and callable(reports):
                reports = reports(project)
            return tuple(reports)

        corehq_reports = process(getattr(reports, attr_name, ()))

        module_name = get_domain_module_map().get(domain)
        if module_name is None:
            custom_reports = ()
        else:
            module = __import__(module_name, fromlist=['reports'])
            if hasattr(module, 'reports'):
                reports = getattr(module, 'reports')
                custom_reports = process(getattr(reports, attr_name, ()))
            else:
                custom_reports = ()

            # soon to be removed
            if not custom_reports:
                domain_module = Domain.get_module_by_name(domain)
                custom_reports = process(getattr(domain_module, attr_name, ()))

        return corehq_reports + custom_reports
Exemple #30
0
def orgs_team_members(request, org, team_id, template="orgs/orgs_team_members.html"):
    #organization and teams
    organization = Organization.get_by_name(org)
    teams = Team.get_by_org(org)
    current_domains = Domain.get_by_organization(org)

    #check that the team exists
    team = Team.get(team_id)
    if team is None:
        raise Http404("Group %s does not exist" % team_id)

    #inspect the members of the team
    member_ids = team.get_member_ids()
    members = WebUser.view("_all_docs", keys=member_ids, include_docs=True).all()
    members.sort(key=lambda user: user.username)

    #inspect the domains of the team
    domain_names = team.get_domains()
    domains = list()
    for name in domain_names:
        domains.append([Domain.get_by_name(name), team.role_label(domain=name)])

    all_org_domains = Domain.get_by_organization(org)
    non_domains = [domain for domain in all_org_domains if domain.name not in domain_names]

    all_org_member_ids = organization.members
    all_org_members = WebUser.view("_all_docs", keys=all_org_member_ids, include_docs=True).all()
    non_members = [member for member in all_org_members if member.user_id not in member_ids]

    vals = dict(org=organization, team=team, teams=teams, members=members, nonmembers=non_members, domains=current_domains, team_domains=domains, team_nondomains=non_domains)
    return render_to_response(request, template, vals)
Exemple #31
0
def process_sms(queued_sms_pk):
    """
    queued_sms_pk - pk of a QueuedSMS entry
    """
    utcnow = get_utcnow()
    # Prevent more than one task from processing this SMS, just in case
    # the message got enqueued twice.
    message_lock = get_lock("sms-queue-processing-%s" % queued_sms_pk)

    if message_lock.acquire(blocking=False):
        try:
            msg = QueuedSMS.objects.get(pk=queued_sms_pk)
        except QueuedSMS.DoesNotExist:
            # The message was already processed and removed from the queue
            release_lock(message_lock, True)
            return

        if message_is_stale(msg, utcnow):
            msg.set_system_error(SMS.ERROR_MESSAGE_IS_STALE)
            remove_from_queue(msg)
            release_lock(message_lock, True)
            return

        outbound_counter = None
        if msg.direction == OUTGOING:
            domain_object = Domain.get_by_name(
                msg.domain) if msg.domain else None

            if domain_object and handle_domain_specific_delays(
                    msg, domain_object, utcnow):
                release_lock(message_lock, True)
                return

            outbound_counter = OutboundDailyCounter(domain_object)
            if not outbound_counter.can_send_outbound_sms(msg):
                release_lock(message_lock, True)
                return

        requeue = False
        # Process inbound SMS from a single contact one at a time
        recipient_block = msg.direction == INCOMING

        # We check datetime_to_process against utcnow plus a small amount
        # of time because timestamps can differ between machines which
        # can cause us to miss sending the message the first time and
        # result in an unnecessary delay.
        if (isinstance(msg.processed, bool) and not msg.processed
                and not msg.error and msg.datetime_to_process <
            (utcnow + timedelta(seconds=10))):
            if recipient_block:
                recipient_lock = get_lock("sms-queue-recipient-phone-%s" %
                                          msg.phone_number)
                recipient_lock.acquire(blocking=True)

            if msg.direction == OUTGOING:
                if (msg.domain and msg.couch_recipient_doc_type
                        and msg.couch_recipient and not is_contact_active(
                            msg.domain, msg.couch_recipient_doc_type,
                            msg.couch_recipient)):
                    msg.set_system_error(SMS.ERROR_CONTACT_IS_INACTIVE)
                    remove_from_queue(msg)
                else:
                    requeue = handle_outgoing(msg)
            elif msg.direction == INCOMING:
                try:
                    handle_incoming(msg)
                except DelayProcessing:
                    process_sms.apply_async([queued_sms_pk], countdown=60)
                    if recipient_block:
                        release_lock(recipient_lock, True)
                    release_lock(message_lock, True)
            else:
                msg.set_system_error(SMS.ERROR_INVALID_DIRECTION)
                remove_from_queue(msg)

            if recipient_block:
                release_lock(recipient_lock, True)

        release_lock(message_lock, True)
        if requeue:
            if outbound_counter:
                outbound_counter.decrement()
            send_to_sms_queue(msg)
Exemple #32
0
 def setUpClass(cls):
     super(LocationFixtureSyncSettingsTest, cls).setUpClass()
     cls.domain_obj = Domain(name=uuid.uuid4().hex)
     cls.domain_obj.save()
Exemple #33
0
 def setUpClass(cls):
     delete_all_docs_by_doc_type(Domain.get_db(),
                                 ['Domain', 'Domain-Deleted'])
     super(TestDomainStagingTable, cls).setUpClass()
Exemple #34
0
    def handle(self, *args, **options):
        if len(args) not in [2, 3]:
            raise CommandError('Usage is copy_domain %s' % self.args)
        self.exclude_dbs = (
            # these have data we don't want to copy
            'receiverwrapper', 'auditcare', 'fluff-bihar', 'fluff-opm',
            'fluff-mc', 'fluff-cvsu', 'mvp-indicators', 'm4change',
            # todo: missing domain/docs, but probably want to add back
            'meta',
        )
        self.source_couch = source_couch = CouchConfig(args[0])
        domain = args[1].strip()
        simulate = options['simulate']
        exclude_attachments = options['exclude_attachments']
        self.run_multi_process = options['run_multi_process']

        since = json_format_date(iso_string_to_date(options['since'])) if options['since'] else None

        if options['list_types']:
            for sourcedb_name, sourcedb in self.iter_source_dbs():
                self.list_types(sourcedb, domain, since)
            sys.exit(0)

        if simulate:
            print "\nSimulated run, no data will be copied.\n"

        if options['postgres_db'] and options['postgres_password']:
            settings.DATABASES[options['postgres_db']]['PASSWORD'] = options['postgres_password']

        self.targetdb = CouchConfig(args[2]) if len(args) == 3 else CouchConfig()

        try:
            domain_doc = Domain.get_by_name(domain)
        except ResourceNotFound:
            domain_doc = None

        if domain_doc is None:
            self.copy_domain(source_couch, domain)

        if options['doc_types']:
            doc_types = options['doc_types'].split(',')
            for doc_type in doc_types:
                sourcedb = source_couch.get_db_for_doc_type(doc_type)
                startkey = [x for x in [domain, doc_type, since] if x is not None]
                endkey = [x for x in [domain, doc_type, {}] if x is not None]
                self.copy_docs(sourcedb, domain, simulate, startkey, endkey, doc_type=doc_type, since=since,
                               postgres_db=options['postgres_db'], exclude_attachments=exclude_attachments)
        elif options['id_file']:
            path = options['id_file']
            if not os.path.isfile(path):
                print "Path '%s' does not exist or is not a file" % path
                sys.exit(1)

            with open(path) as input:
                doc_ids = [line.rstrip('\n') for line in input]

            if not doc_ids:
                print "Path '%s' does not contain any document ID's" % path
                sys.exit(1)

            for sourcedb_name, sourcedb in self.iter_source_dbs():
                self.copy_docs(sourcedb, domain, simulate, doc_ids=doc_ids, postgres_db=options['postgres_db'],
                               exclude_attachments=exclude_attachments)
        else:
            startkey = [domain]
            endkey = [domain, {}]
            exclude_types = DEFAULT_EXCLUDE_TYPES + options['doc_types_exclude'].split(',')
            for sourcedb_name, sourcedb in self.iter_source_dbs():
                self.copy_docs(sourcedb, domain, simulate, startkey, endkey, exclude_types=exclude_types,
                               postgres_db=options['postgres_db'], exclude_attachments=exclude_attachments)
Exemple #35
0
def load_domain(req, domain):
    domain_name = normalize_domain_name(domain)
    domain = Domain.get_by_name(domain_name)
    req.project = domain
    return domain_name, domain
Exemple #36
0
 def options(self):
     if hasattr(Domain, 'categories'):
         available_categories = [(d.replace(' ', '+'), d) for d in Domain.categories()]
     else:
         available_categories = []
     return available_categories
Exemple #37
0
 def options(self):
     if hasattr(Domain, 'regions'):
         available_regions = [(d.replace(' ', '+'), d) for d in Domain.regions()]
     else:
         available_regions = []
     return available_regions
Exemple #38
0
class TestUserBulkUpload(TestCase, DomainSubscriptionMixin):
    def setUp(self):
        super(TestUserBulkUpload, self).setUp()
        delete_all_users()
        self.domain_name = 'mydomain'
        self.domain = Domain(name=self.domain_name)
        self.domain.save()
        self.user_specs = [{
            u'username': u'hello',
            u'user_id': u'should not update',
            u'name': u'Another One', u'language': None,
            u'is_active': u'True',
            u'phone-number': u'23424123',
            u'password': 123,
            u'email': None
        }]

        permissions = Permissions(edit_apps=True, view_reports=True)
        self.role = UserRole.get_or_create_with_permissions(self.domain.name, permissions, 'edit-apps')

    def tearDown(self):
        self.role.delete()
        self.domain.delete()
        super(TestUserBulkUpload, self).tearDown()

    @property
    def user(self):
        return CommCareUser.get_by_username('{}@{}.commcarehq.org'.format(
            self.user_specs[0]['username'],
            self.domain.name))

    def test_upload_with_user_id(self):
        bulk_upload_async(
            self.domain.name,
            list(self.user_specs),
            list([]),
        )

        self.assertNotEqual(self.user_specs[0]['user_id'], self.user._id)
        self.assertEqual(self.user_specs[0]['phone-number'], self.user.phone_number)
        self.assertEqual(self.user_specs[0]['name'], self.user.name)

    @patch('corehq.apps.users.bulkupload.domain_has_privilege', lambda x, y: True)
    def test_location_not_list(self):
        self.setup_locations()
        updated_user_spec = deepcopy(self.user_specs[0])

        # location_code can also just be string instead of array for single location assignmentss
        updated_user_spec["location_code"] = self.loc1.site_code
        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        self.assertEqual(self.user.location_id, self.loc1._id)
        self.assertEqual(self.user.location_id, self.user.user_data.get('commcare_location_id'))
        # multiple locations
        self.assertListEqual([self.loc1._id], self.user.assigned_location_ids)

    @patch('corehq.apps.users.bulkupload.domain_has_privilege', lambda x, y: True)
    def test_location_unknown_site_code(self):
        self.setup_locations()
        updated_user_spec = deepcopy(self.user_specs[0])
        updated_user_spec["location_code"] = ['unknownsite']

        # location_code should be an array of multiple excel columns
        # with self.assertRaises(UserUploadError):
        result = create_or_update_users_and_groups(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        self.assertEqual(len(result["rows"]), 1)

    @patch('corehq.apps.users.bulkupload.domain_has_privilege', lambda x, y: True)
    def test_location_add(self):
        self.setup_locations()
        updated_user_spec = deepcopy(self.user_specs[0])

        updated_user_spec["location_code"] = [a.site_code for a in [self.loc1, self.loc2]]
        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        # first location should be primary location
        self.assertEqual(self.user.location_id, self.loc1._id)
        self.assertEqual(self.user.location_id, self.user.user_data.get('commcare_location_id'))
        # multiple locations
        self.assertListEqual([l._id for l in [self.loc1, self.loc2]], self.user.assigned_location_ids)
        # non-primary location
        self.assertTrue(self.loc2._id in self.user.user_data.get('commcare_location_ids'))

    @patch('corehq.apps.users.bulkupload.domain_has_privilege', lambda x, y: True)
    def test_location_remove(self):
        self.setup_locations()
        updated_user_spec = deepcopy(self.user_specs[0])
        # first assign both locations
        updated_user_spec["location_code"] = [a.site_code for a in [self.loc1, self.loc2]]
        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )

        # deassign all locations
        updated_user_spec["location_code"] = []
        updated_user_spec["user_id"] = self.user._id
        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )

        # user should have no locations
        self.assertEqual(self.user.location_id, None)
        self.assertEqual(self.user.user_data.get('commcare_location_id'), None)
        self.assertListEqual(self.user.assigned_location_ids, [])

    @patch('corehq.apps.users.bulkupload.domain_has_privilege', lambda x, y: True)
    def test_primary_location_replace(self):
        self.setup_locations()
        updated_user_spec = deepcopy(self.user_specs[0])

        # first assign to loc1
        updated_user_spec["location_code"] = [a.site_code for a in [self.loc1, self.loc2]]
        create_or_update_users_and_groups(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )

        # user's primary location should be loc1
        self.assertEqual(self.user.location_id, self.loc1._id)
        self.assertEqual(self.user.user_data.get('commcare_location_id'), self.loc1._id)
        self.assertEqual(self.user.user_data.get('commcare_location_ids'), " ".join([self.loc1._id, self.loc2._id]))
        self.assertListEqual(self.user.assigned_location_ids, [self.loc1._id, self.loc2._id])

        # reassign to loc2
        updated_user_spec["location_code"] = [self.loc2.site_code]
        updated_user_spec["user_id"] = self.user._id
        create_or_update_users_and_groups(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )

        # user's location should now be loc2
        self.assertEqual(self.user.location_id, self.loc2._id)
        self.assertEqual(self.user.user_data.get('commcare_location_ids'), self.loc2._id)
        self.assertEqual(self.user.user_data.get('commcare_location_id'), self.loc2._id)
        self.assertListEqual(self.user.assigned_location_ids, [self.loc2._id])

    @patch('corehq.apps.users.bulkupload.domain_has_privilege', lambda x, y: True)
    def test_location_replace(self):
        self.setup_locations()
        updated_user_spec = deepcopy(self.user_specs[0])

        # first assign to loc1
        updated_user_spec["location_code"] = [self.loc1.site_code]
        create_or_update_users_and_groups(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )

        # reassign to loc2
        updated_user_spec["location_code"] = [self.loc2.site_code]
        updated_user_spec["user_id"] = self.user._id
        create_or_update_users_and_groups(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )

        # user's location should now be loc2
        self.assertEqual(self.user.location_id, self.loc2._id)
        self.assertEqual(self.user.user_data.get('commcare_location_id'), self.loc2._id)
        self.assertListEqual(self.user.assigned_location_ids, [self.loc2._id])

    def setup_locations(self):
        self.loc1 = make_loc('loc1', type='state', domain=self.domain_name)
        self.loc2 = make_loc('loc2', type='state', domain=self.domain_name)

    def test_numeric_user_name(self):
        """
        Test that bulk upload doesn't choke if the user's name is a number
        """
        updated_user_spec = deepcopy(self.user_specs[0])
        updated_user_spec["name"] = 1234

        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        self.assertEqual(self.user.full_name, "1234")

    def test_empty_user_name(self):
        """
        This test confirms that a name of None doesn't set the users name to
        "None" or anything like that.
        """
        updated_user_spec = deepcopy(self.user_specs[0])
        updated_user_spec["name"] = None

        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        self.assertEqual(self.user.full_name, "")

    def test_upper_case_email(self):
        """
        Ensure that bulk upload throws a proper error when the email has caps in it
        """
        updated_user_spec = deepcopy(self.user_specs[0])
        updated_user_spec["email"] = '*****@*****.**'

        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        self.assertEqual(self.user.email, updated_user_spec['email'].lower())

    def test_set_role(self):
        updated_user_spec = deepcopy(self.user_specs[0])
        updated_user_spec["role"] = self.role.name

        bulk_upload_async(
            self.domain.name,
            list([updated_user_spec]),
            list([]),
        )
        self.assertEqual(self.user.get_role(self.domain_name).name, updated_user_spec['role'])
Exemple #39
0
 def project(self):
     return Domain.get_by_name(self.domain)
 def _setup_domain_user(cls):
     cls.domain = Domain(name=cls.DOMAIN_NAME)
     cls.domain.save()
     cls.user = CommCareUser.create(cls.DOMAIN_NAME, cls.USERNAME, '*****')
     cls.user.save()
     cls.user_id = cls.user._id
 def get_domain(self):
     return Domain.get_by_name(self.domain)
Exemple #42
0
def generate_invoices(based_on_date=None):
    """
    Generates all invoices for the past month.
    """
    today = based_on_date or datetime.date.today()
    invoice_start, invoice_end = get_previous_month_date_range(today)
    log_accounting_info(
        "Starting up invoices for %(start)s - %(end)s" % {
            'start': invoice_start.strftime(USER_DATE_FORMAT),
            'end': invoice_end.strftime(USER_DATE_FORMAT),
        })
    all_domain_ids = [d['id'] for d in Domain.get_all(include_docs=False)]
    for domain_doc in iter_docs(Domain.get_db(), all_domain_ids):
        domain = Domain.wrap(domain_doc)
        if not domain.is_active:
            continue
        try:
            invoice_factory = DomainInvoiceFactory(invoice_start, invoice_end,
                                                   domain)
            invoice_factory.create_invoices()
            log_accounting_info("Sent invoices for domain %s" % domain.name)
        except CreditLineError as e:
            log_accounting_error(
                "There was an error utilizing credits for "
                "domain %s: %s" % (domain.name, e),
                show_stack_trace=True,
            )
        except InvoiceError as e:
            log_accounting_error(
                "Could not create invoice for domain %s: %s" %
                (domain.name, e),
                show_stack_trace=True,
            )
        except Exception as e:
            log_accounting_error(
                "Error occurred while creating invoice for "
                "domain %s: %s" % (domain.name, e),
                show_stack_trace=True,
            )
    all_customer_billing_accounts = BillingAccount.objects.filter(
        is_customer_billing_account=True)
    for account in all_customer_billing_accounts:
        try:
            if account.invoicing_plan == InvoicingPlan.QUARTERLY:
                customer_invoice_start = invoice_start - relativedelta(
                    months=2)
            elif account.invoicing_plan == InvoicingPlan.YEARLY:
                customer_invoice_start = invoice_start - relativedelta(
                    months=11)
            else:
                customer_invoice_start = invoice_start
            invoice_factory = CustomerAccountInvoiceFactory(
                account=account,
                date_start=customer_invoice_start,
                date_end=invoice_end)
            invoice_factory.create_invoice()
        except CreditLineError as e:
            log_accounting_error(
                "There was an error utilizing credits for "
                "domain %s: %s" % (domain.name, e),
                show_stack_trace=True,
            )
        except InvoiceError as e:
            log_accounting_error(
                "Could not create invoice for domain %s: %s" %
                (domain.name, e),
                show_stack_trace=True,
            )
        except Exception as e:
            log_accounting_error(
                "Error occurred while creating invoice for "
                "domain %s: %s" % (domain.name, e),
                show_stack_trace=True,
            )

    if not settings.UNIT_TESTING:
        _invoicing_complete_soft_assert(False, "Invoicing is complete!")
Exemple #43
0
 def odata_feed_limit(self):
     domain_object = Domain.get_by_name(self.domain)
     return domain_object.odata_feed_limit or settings.DEFAULT_ODATA_FEED_LIMIT
Exemple #44
0
def logo(request, domain):
    logo = Domain.get_by_name(domain).get_custom_logo()
    if logo is None:
        raise Http404()

    return HttpResponse(logo[0], content_type=logo[1])
Exemple #45
0
class TestSubscriptionForm(BaseAccountingTest):
    def setUp(self):
        super(TestSubscriptionForm, self).setUp()

        self.domain = Domain(name="test-sub-form", is_active=True)
        self.domain.save()
        self.domain2 = Domain(name="test-sub-form-2", is_active=True)
        self.domain2.save()

        self.web_user = WebUser.create(
            self.domain.name, generator.create_arbitrary_web_user_name(),
            'testpwd')

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.web_user.username)[0]
        self.account.save()
        self.customer_account = BillingAccount.get_or_create_account_by_domain(
            self.domain2.name, created_by=self.web_user.username)[0]
        self.customer_account.is_customer_billing_account = True
        self.customer_account.save()

        self.plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.ADVANCED)
        self.customer_plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.ADVANCED)
        self.customer_plan.plan.is_customer_software_plan = True

    def tearDown(self):
        super(TestSubscriptionForm, self).tearDown()

    def test_regular_plan_not_added_to_customer_account(self):
        subscription = Subscription.new_domain_subscription(
            domain=self.domain.name,
            plan_version=self.plan,
            account=self.account)
        subscription_form = SubscriptionForm(
            subscription=subscription,
            account_id=self.account.id,
            web_user=self.web_user,
        )
        subscription_form.cleaned_data = {
            'active_accounts': self.customer_account.id,
            'start_date': datetime.date.today(),
            'end_date': None,
            'do_not_invoice': None,
            'no_invoice_reason': None,
            'do_not_email_invoice': None,
            'do_not_email_reminder': None,
            'auto_generate_credits': None,
            'skip_invoicing_if_no_feature_charges': None,
            'salesforce_contract_id': None,
            'service_type': None,
            'pro_bono_status': None,
            'funding_source': None,
            'skip_auto_downgrade': None,
            'skip_auto_downgrade_reason': None
        }

        self.assertRaises(ValidationError,
                          lambda: subscription_form.clean_active_accounts())

    def test_customer_plan_not_added_to_regular_account(self):
        subscription = Subscription.new_domain_subscription(
            domain=self.domain.name,
            plan_version=self.customer_plan,
            account=self.customer_account)
        subscription_form = SubscriptionForm(
            subscription=subscription,
            account_id=self.customer_plan.id,
            web_user=self.web_user,
        )
        subscription_form.cleaned_data = {
            'active_accounts': self.account.id,
            'start_date': datetime.date.today(),
            'end_date': None,
            'do_not_invoice': None,
            'no_invoice_reason': None,
            'do_not_email_invoice': None,
            'do_not_email_reminder': None,
            'auto_generate_credits': None,
            'skip_invoicing_if_no_feature_charges': None,
            'salesforce_contract_id': None,
            'service_type': None,
            'pro_bono_status': None,
            'funding_source': None,
            'skip_auto_downgrade': None,
            'skip_auto_downgrade_reason': None
        }

        self.assertRaises(ValidationError,
                          lambda: subscription_form.clean_active_accounts())
class TestUserRoleSubscriptionChanges(BaseAccountingTest):
    def setUp(self):
        super(TestUserRoleSubscriptionChanges, self).setUp()
        self.domain = Domain(
            name="test-sub-changes",
            is_active=True,
        )
        self.domain.save()
        UserRole.init_domain_with_presets(self.domain.name)
        self.user_roles = UserRole.by_domain(self.domain.name)
        self.custom_role = UserRole.get_or_create_with_permissions(
            self.domain.name, Permissions(edit_apps=True, edit_web_users=True),
            "Custom Role")
        self.custom_role.save()
        self.read_only_role = UserRole.get_read_only_role_by_domain(
            self.domain.name)

        self.admin_user = generator.arbitrary_web_user()
        self.admin_user.add_domain_membership(self.domain.name, is_admin=True)
        self.admin_user.save()

        self.web_users = []
        self.commcare_users = []
        for role in [self.custom_role] + self.user_roles:
            web_user = generator.arbitrary_web_user()
            web_user.add_domain_membership(self.domain.name,
                                           role_id=role.get_id)
            web_user.save()
            self.web_users.append(web_user)

            commcare_user = generator.arbitrary_commcare_user(
                domain=self.domain.name)
            commcare_user.set_role(self.domain.name, role.get_qualified_id())
            commcare_user.save()
            self.commcare_users.append(commcare_user)

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]
        self.advanced_plan = DefaultProductPlan.get_default_plan(
            edition=SoftwarePlanEdition.ADVANCED)

    def test_cancellation(self):
        subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.advanced_plan,
            web_user=self.admin_user.username)
        self._change_std_roles()
        subscription.cancel_subscription(web_user=self.admin_user.username)

        custom_role = UserRole.get(self.custom_role.get_id)
        self.assertTrue(custom_role.is_archived)

        # disable this part of the test until we improve the UX for notifying
        # downgraded users of their privilege changes
        # custom_web_user = WebUser.get(self.web_users[0].get_id)
        # custom_commcare_user = CommCareUser.get(self.commcare_users[0].get_id)
        # self.assertEqual(
        #     custom_web_user.get_domain_membership(self.domain.name).role_id,
        #     self.read_only_role.get_id
        # )
        # self.assertIsNone(
        #     custom_commcare_user.get_domain_membership(self.domain.name).role_id
        # )

        self._assertInitialRoles()
        self._assertStdUsers()

    def test_resubscription(self):
        subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.advanced_plan,
            web_user=self.admin_user.username)
        self._change_std_roles()
        subscription.cancel_subscription(web_user=self.admin_user.username)
        custom_role = UserRole.get(self.custom_role.get_id)
        self.assertTrue(custom_role.is_archived)
        subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.advanced_plan,
            web_user=self.admin_user.username)
        custom_role = UserRole.get(self.custom_role.get_id)
        self.assertFalse(custom_role.is_archived)

        # disable this part of the test until we improve the UX for notifying
        # downgraded users of their privilege changes
        # custom_web_user = WebUser.get(self.web_users[0].get_id)
        # custom_commcare_user = CommCareUser.get(self.commcare_users[0].get_id)
        # self.assertEqual(
        #     custom_web_user.get_domain_membership(self.domain.name).role_id,
        #     self.read_only_role.get_id
        # )
        # self.assertIsNone(
        #     custom_commcare_user.get_domain_membership(self.domain.name).role_id
        # )

        self._assertInitialRoles()
        self._assertStdUsers()
        subscription.cancel_subscription(web_user=self.admin_user.username)

    def _change_std_roles(self):
        for u in self.user_roles:
            user_role = UserRole.get(u.get_id)
            user_role.permissions = Permissions(view_reports=True,
                                                edit_commcare_users=True,
                                                edit_apps=True,
                                                edit_data=True)
            user_role.save()

    def _assertInitialRoles(self):
        for u in self.user_roles:
            user_role = UserRole.get(u.get_id)
            self.assertEqual(user_role.permissions,
                             UserRolePresets.get_permissions(user_role.name))

    def _assertStdUsers(self):
        for ind, wu in enumerate(self.web_users[1:]):
            web_user = WebUser.get(wu.get_id)
            self.assertEqual(
                web_user.get_domain_membership(self.domain.name).role_id,
                self.user_roles[ind].get_id)

        for ind, cc in enumerate(self.commcare_users[1:]):
            commcare_user = CommCareUser.get(cc.get_id)
            self.assertEqual(
                commcare_user.get_domain_membership(self.domain.name).role_id,
                self.user_roles[ind].get_id)

    def tearDown(self):
        self.domain.delete()
        self.admin_user.delete()
        generator.delete_all_subscriptions()
        generator.delete_all_accounts()
        super(TestUserRoleSubscriptionChanges, self).tearDown()
Exemple #47
0
 def _user_requires_secure_session(couch_user):
     return couch_user and any(
         Domain.is_secure_session_required(domain)
         for domain in couch_user.get_domains())
Exemple #48
0
class TestFixtureStatus(TestCase):
    def setUp(self):
        self._delete_everything()
        self.username = "******"
        password = "******"
        self.domain = Domain(name='my-domain')
        self.domain.save()
        self.couch_user = CommCareUser.create(self.domain.name, self.username,
                                              password)
        self.couch_user.save()

    def tearDown(self):
        self._delete_everything()

    def _delete_everything(self):
        delete_all_users()
        UserFixtureStatus.objects.all().delete()

    def test_get_statuses(self):
        no_status = {
            UserFixtureType.CHOICES[0][0]:
            UserFixtureStatus.DEFAULT_LAST_MODIFIED
        }
        self.assertEqual(get_fixture_statuses(self.couch_user._id), no_status)

        now = datetime.utcnow()
        UserFixtureStatus(
            user_id=self.couch_user._id,
            fixture_type=UserFixtureType.CHOICES[0][0],
            last_modified=now,
        ).save()
        expected_status = {UserFixtureType.CHOICES[0][0]: now}
        self.assertEqual(get_fixture_statuses(self.couch_user._id),
                         expected_status)

    def test_get_status(self):
        now = datetime.utcnow()
        couch_user = CommCareUser.get_by_username(self.username)
        UserFixtureStatus(
            user_id=self.couch_user._id,
            fixture_type=UserFixtureType.CHOICES[0][0],
            last_modified=now,
        ).save()

        self.assertEqual(self.couch_user.fixture_status("fake_status"),
                         UserFixtureStatus.DEFAULT_LAST_MODIFIED)
        self.assertEqual(
            couch_user.fixture_status(UserFixtureType.CHOICES[0][0]), now)

    def test_update_status_set_location(self):
        fake_location = MagicMock()
        fake_location.location_id = "the_depths_of_khazad_dum"
        fake_location.group_id = "the_depths_of_khazad_dum"
        self.assertEqual(UserFixtureStatus.objects.all().count(), 0)

        self.couch_user.set_location(fake_location)

        self.assertEqual(UserFixtureStatus.objects.all().count(), 1)
        user_fixture_status = UserFixtureStatus.objects.first()

        self.assertEqual(user_fixture_status.user_id, self.couch_user._id)
        self.assertEqual(user_fixture_status.fixture_type,
                         UserFixtureType.LOCATION)

    def test_update_status_unset_location(self):
        fake_location = MagicMock()
        fake_location.location_id = "the_mines_of_moria"
        fake_location.group_id = "the_mines_of_moria"
        self.couch_user.set_location(fake_location)
        previously_updated_time = UserFixtureStatus.objects.get(
            user_id=self.couch_user._id).last_modified

        self.couch_user.unset_location()

        new_updated_time = UserFixtureStatus.objects.get(
            user_id=self.couch_user._id).last_modified
        self.assertTrue(new_updated_time > previously_updated_time)

    def test_update_status_reset_location(self):
        fake_location = MagicMock()
        fake_location.location_id = "misty_mountains"
        fake_location.group_id = "misty_mountains"
        self.couch_user.set_location(fake_location)
        previously_updated_time = UserFixtureStatus.objects.get(
            user_id=self.couch_user._id).last_modified

        fake_location.location_id = "lonely_mountain"
        fake_location.group_id = "lonely_mountain"
        self.couch_user.set_location(fake_location)

        new_updated_time = UserFixtureStatus.objects.get(
            user_id=self.couch_user._id).last_modified
        self.assertTrue(new_updated_time > previously_updated_time)
Exemple #49
0
 def test_failure(self):
     name = "ab"
     self.add_domain(name)
     with self.assertRaises(NameUnavailableException):
         Domain.generate_name(name, 1)
def setUpModule():
    if isinstance(Domain.get_db(), Mock):
        # needed to skip setUp for javascript tests thread on Travis
        return

    _call_center_domain_mock = mock.patch(
        'corehq.apps.callcenter.data_source.call_center_data_source_configuration_provider'
    )
    _call_center_domain_mock.start()

    domain = create_domain('test-pna')
    region_location_type = LocationType.objects.create(
        domain='test-pna',
        name='R\u00e9gion',
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='Region Test',
        location_id='8cde73411ddc4488a7f913c99499ead4',
        location_type=region_location_type
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='PASSY',
        location_id='1991b4dfe166335e342f28134b85fcac',
        location_type=region_location_type
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='r1',
        location_id='0682630532ff25717176320482ff1028',
        location_type=region_location_type
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='r2',
        location_id='582c5d65a307baa7a38e7b5e651fd5fc',
        location_type=region_location_type
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='r3',
        location_id='bd0395ba4a4fbd38c90765bd04208a8f',
        location_type=region_location_type
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='r4',
        location_id='6ed1f958fccd1b8202e8e30851a2b326',
        location_type=region_location_type
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='r5',
        location_id='1991b4dfe166335e342f28134b85f516',
        location_type=region_location_type
    )

    district_location_type = LocationType.objects.create(
        domain='test-pna',
        name='District',
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='District Test',
        location_id='3db74fac2bad4e708e2b03800cc5ab73',
        location_type=district_location_type
    )

    pps_location_type = LocationType.objects.create(
        domain='test-pna',
        name='PPS',
    )

    SQLLocation.objects.create(
        domain='test-pna',
        name='P2',
        location_id='ccf4430f5c3f493797486d6ce1c39682',
        location_type=pps_location_type
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Collier',
        code='product1',
        product_id='product1'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='CU',
        code='product2',
        product_id='product2'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Depo-Provera',
        code='product3',
        product_id='product3'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='DIU',
        code='product4',
        product_id='product4'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Jadelle',
        code='product5',
        product_id='product5'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Microgynon/Lof.',
        code='product6',
        product_id='product6'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Microlut/Ovrette',
        code='product7',
        product_id='product7'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Preservatif Feminin',
        code='product8',
        product_id='product8'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Preservatif Masculin',
        code='product9',
        product_id='product9'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Sayana Press',
        code='product10',
        product_id='product10'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='IMPLANON',
        code='product11',
        product_id='product11'
    )

    SQLProduct.objects.create(
        domain='test-pna',
        name='Product 7',
        code='p7',
        product_id='p7'
    )

    with override_settings(SERVER_ENVIRONMENT='production'):

        configs = StaticDataSourceConfiguration.by_domain(domain.name)
        adapters = [get_indicator_adapter(config) for config in configs]

        for adapter in adapters:
            adapter.build_table()

        engine = connection_manager.get_engine(UCR_ENGINE_ID)
        metadata = sqlalchemy.MetaData(bind=engine)
        metadata.reflect(bind=engine, extend_existing=True)
        path = os.path.join(os.path.dirname(__file__), 'fixtures')
        for file_name in os.listdir(path):
            with open(os.path.join(path, file_name), encoding='utf-8') as f:
                table_name = get_table_name(domain.name, file_name[:-4])
                table = metadata.tables[table_name]
                postgres_copy.copy_from(f, table, engine, format=b'csv', null=b'', header=True)
    _call_center_domain_mock.stop()
Exemple #51
0
 def add_domain(self, name):
     domain = Domain(name=name)
     domain.save()
     self.domains.append(domain)
Exemple #52
0
 def test_conflict(self):
     name = "fandango"
     self.add_domain(name)
     self.assertEquals(Domain.generate_name(name), name + "-1")
Exemple #53
0
class TestDomainViews(TestCase):
    def setUp(self):
        self.client = Client()

        self.domain = Domain(name="fandago", is_active=True)
        self.domain.save()

        self.username = '******'
        self.password = '******'
        self.user = WebUser.create(self.domain.name,
                                   self.username,
                                   self.password,
                                   is_admin=True)
        self.user.eula.signed = True
        self.user.save()

        self.app = Application.new_app(domain="fandago", name="cheeto")
        self.app.save()

    def tearDown(self):
        self.user.delete()
        self.domain.delete()

    def test_allow_domain_requests(self):
        self.client.login(username=self.username, password=self.password)

        public_domain = Domain(name="public", is_active=True)
        public_domain.allow_domain_requests = True
        public_domain.save()

        response = self.client.get(reverse("domain_homepage",
                                           args=[public_domain.name]),
                                   follow=True)
        self.assertEqual(response.status_code, 200)

        public_domain.delete()

    def test_disallow_domain_requests(self):
        self.client.login(username=self.username, password=self.password)

        private_domain = Domain(name="private", is_active=True)
        private_domain.save()

        response = self.client.get(reverse("domain_homepage",
                                           args=[private_domain.name]),
                                   follow=True)
        self.assertEqual(response.status_code, 404)

        private_domain.delete()

    def test_add_repeater(self):
        forwarding_url = 'https://example.com/forwarding'

        self.client.login(username=self.username, password=self.password)

        post_url = reverse('add_repeater',
                           kwargs={
                               'domain': self.domain.name,
                               'repeater_type': 'AppStructureRepeater'
                           })
        response = self.client.post(post_url, {'url': forwarding_url},
                                    follow=True)
        self.assertEqual(response.status_code, 200)

        self.client.logout()

        app_structure_repeaters = AppStructureRepeater.by_domain(
            self.domain.name)
        self.assertEqual(len(app_structure_repeaters), 1)

        for app_structure_repeater in app_structure_repeaters:
            app_structure_repeater.delete()

    def delete_domain_snapshots(self):
        for snap in self.domain.snapshots():
            snap.delete()

    @teardown(delete_domain_snapshots)
    def test_exchange_snapshot_view(self):
        """
        Tests creating a new exchange snapshot and then creating another snapshot
        """

        self.client.login(username=self.username, password=self.password)
        app_publish = "{}-publish".format(self.app._id)
        filename = 'file.txt'

        data = {
            'title': 'Title',
            'short_description': 'Description',
            'description': 'Description',
            'project_type': 'MCH',
            'license': 'cc',
            'documentation_file': SimpleUploadedFile(filename, b'contents'),
            'publish_on_submit': 'yes',
            'cda_confirmed': True,
            app_publish: True,
        }

        response = self.client.post(reverse(
            CreateNewExchangeSnapshotView.urlname, args=[self.domain.name]),
                                    data,
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        published = self.domain.published_snapshot()
        self.assertIsNotNone(published)

        self.assertEqual(published.title, data['title'])
        self.assertEqual(published.documentation_file_path, filename)

        # Should keep documentation file when old_documentation_file is specified
        del data['documentation_file']
        data['old_documentation_file'] = True

        response = self.client.post(reverse(
            CreateNewExchangeSnapshotView.urlname, args=[self.domain.name]),
                                    data,
                                    follow=True)
        self.domain = Domain.get(self.domain._id)
        self.assertEqual(response.status_code, 200)
        snapshots = list(self.domain.snapshots())
        self.assertEqual(len(snapshots), 2)
        self.assertEqual(snapshots[0].documentation_file_path, filename)
        self.assertEqual(snapshots[1].documentation_file_path, filename)
Exemple #54
0
def get_all_report_configs():
    all_domains = Domain.get_all()
    for domain in all_domains:
        for report_config in get_report_configs_for_domain(domain.name):
            yield report_config
Exemple #55
0
 def test_should_sync_hierarchical_format_default(self):
     self.assertEqual(False, should_sync_hierarchical_fixture(Domain()))
class RegistrationTestCase(BaseSMSTest):

    def setUp(self):
        super(RegistrationTestCase, self).setUp()

        self.domain = 'sms-reg-test-domain'
        self.domain_obj = Domain(name=self.domain)
        self.domain_obj.save()

        self.create_account_and_subscription(self.domain)
        self.domain_obj = Domain.get(self.domain_obj.get_id)

        self.backend = SQLTestSMSBackend.objects.create(
            name='BACKEND',
            is_global=False,
            domain=self.domain,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        SQLMobileBackendMapping.set_default_domain_backend(self.domain, self.backend)

        self.app_id = 'app_id'

        self.default_user_data = {'commcare_project': self.domain}

    def tearDown(self):
        delete_domain_phone_numbers(self.domain)
        SelfRegistrationInvitation.objects.filter(domain=self.domain).delete()
        SQLMobileBackendMapping.unset_default_domain_backend(self.domain)
        self.backend.delete()
        self.domain_obj.delete()

        super(RegistrationTestCase, self).tearDown()

    def _get_last_sms(self, count=1, direction=None, phone_number=None):
        result = SMS.objects.filter(domain=self.domain)
        if direction:
            result = result.filter(direction=direction)

        if phone_number:
            result = result.filter(phone_number=phone_number)

        result = result.order_by('-date')
        result = list(result[:count])
        self.assertEqual(len(result), count)
        return result

    def assertLastOutgoingSMS(self, phone_number, expected_texts):
        result = self._get_last_sms(
            count=len(expected_texts),
            direction=OUTGOING,
            phone_number=phone_number
        )
        actual_texts = set([sms.text for sms in result])
        self.assertEqual(actual_texts, set(expected_texts))

    def _get_sms_registration_invitation(self):
        # implicitly assert there is only one of these
        return SelfRegistrationInvitation.objects.get(domain=self.domain)

    def assertRegistrationInvitation(self, **kwargs):
        invite = self._get_sms_registration_invitation()

        for name, value in kwargs.items():
            self.assertEqual(getattr(invite, name), value)

    def test_sms_registration(self):
        formatted_username = format_username('tester', self.domain)

        # Test without mobile worker registration enabled
        incoming('+9991234567', 'JOIN {} WORKER tester'.format(self.domain), self.backend.hq_api_id)
        self.assertIsNone(CommCareUser.get_by_username(formatted_username))

        # Test with mobile worker registration enabled
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.save()

        incoming('+9991234567', 'JOIN {} WORKER tester'.format(self.domain), self.backend.hq_api_id)
        self.assertIsNotNone(CommCareUser.get_by_username(formatted_username))

        # Test a duplicate registration
        prev_num_users = num_mobile_users(self.domain)
        incoming('+9991234568', 'JOIN {} WORKER tester'.format(self.domain), self.backend.hq_api_id)
        current_num_users = num_mobile_users(self.domain)
        self.assertEqual(prev_num_users, current_num_users)

    def test_other_registration_from_invite(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        user_data = {'abc': 'def'}

        # Initiate Registration Workflow
        SelfRegistrationInvitation.initiate_workflow(
            self.domain,
            [SelfRegistrationUserInfo('999123', user_data)],
            app_id=self.app_id,
        )

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=None,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_MOBILE_WORKER_INVITATION_START]])

        # Choose phone type 'other'
        incoming('+999123', '2', self.backend.hq_api_id)

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=SelfRegistrationInvitation.PHONE_TYPE_OTHER,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_MOBILE_WORKER_JAVA_INVITATION].format(self.domain)])

        # Register over SMS
        incoming('+999123', 'JOIN {} WORKER test'.format(self.domain), self.backend.hq_api_id)
        user = CommCareUser.get_by_username(format_username('test', self.domain))
        self.assertIsNotNone(user)
        self.assertEqual(user.user_data, dict(self.default_user_data, **user_data))
        self.assertEqual(PhoneNumber.by_phone('999123').owner_id, user.get_id)

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_REGISTRATION_WELCOME_MOBILE_WORKER]])

        self.assertRegistrationInvitation(
            status=SelfRegistrationInvitation.STATUS_REGISTERED,
        )

    def test_android_registration_from_invite(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        user_data = {'abc': 'def'}

        # Initiate Registration Workflow
        SelfRegistrationInvitation.initiate_workflow(
            self.domain,
            [SelfRegistrationUserInfo('999123', user_data)],
            app_id=self.app_id,
        )

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=None,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_MOBILE_WORKER_INVITATION_START]])

        # Choose phone type 'android'
        with patch('corehq.apps.sms.models.SelfRegistrationInvitation.odk_url') as mock_odk_url, \
                patch.object(SelfRegistrationInvitation, 'get_user_registration_url', return_value=DUMMY_REGISTRATION_URL), \
                patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            mock_odk_url.__get__ = Mock(return_value=DUMMY_APP_ODK_URL)
            incoming('+999123', '1', self.backend.hq_api_id)

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=SelfRegistrationInvitation.PHONE_TYPE_ANDROID,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [
            _MESSAGES[MSG_MOBILE_WORKER_ANDROID_INVITATION].format(DUMMY_REGISTRATION_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])

        invite = self._get_sms_registration_invitation()
        c = Client()
        response = c.post('/a/{}/settings/users/commcare/register/{}/'.format(self.domain, invite.token), {
            'username': '******',
            'password': '******',
            'password2': 'abc',
            'email': '*****@*****.**',
        })
        self.assertEqual(response.status_code, 200)

        user = CommCareUser.get_by_username(format_username('new_user', self.domain))
        self.assertIsNotNone(user)
        self.assertEqual(user.user_data, dict(self.default_user_data, **user_data))
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(PhoneNumber.by_phone('999123').owner_id, user.get_id)

        self.assertRegistrationInvitation(
            status=SelfRegistrationInvitation.STATUS_REGISTERED,
        )

    def test_android_only_registration_from_invite(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        # Initiate Registration Workflow
        with patch('corehq.apps.sms.models.SelfRegistrationInvitation.odk_url') as mock_odk_url, \
                patch.object(SelfRegistrationInvitation, 'get_user_registration_url', return_value=DUMMY_REGISTRATION_URL), \
                patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            mock_odk_url.__get__ = Mock(return_value=DUMMY_APP_ODK_URL)
            SelfRegistrationInvitation.initiate_workflow(
                self.domain,
                [SelfRegistrationUserInfo('999123')],
                app_id=self.app_id,
                android_only=True,
            )

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=SelfRegistrationInvitation.PHONE_TYPE_ANDROID,
            android_only=True,
            require_email=False,
            custom_user_data={},
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [
            _MESSAGES[MSG_MOBILE_WORKER_ANDROID_INVITATION].format(DUMMY_REGISTRATION_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])

        invite = self._get_sms_registration_invitation()
        c = Client()
        response = c.post('/a/{}/settings/users/commcare/register/{}/'.format(self.domain, invite.token), {
            'username': '******',
            'password': '******',
            'password2': 'abc',
            'email': '*****@*****.**',
        })
        self.assertEqual(response.status_code, 200)

        user = CommCareUser.get_by_username(format_username('new_user', self.domain))
        self.assertIsNotNone(user)
        self.assertEqual(user.user_data, self.default_user_data)
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(PhoneNumber.by_phone('999123').owner_id, user.get_id)

        self.assertRegistrationInvitation(
            status=SelfRegistrationInvitation.STATUS_REGISTERED,
        )

    def test_custom_message_for_normal_workflow(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        # Initiate Registration Workflow
        SelfRegistrationInvitation.initiate_workflow(
            self.domain,
            [SelfRegistrationUserInfo('999123')],
            app_id=self.app_id,
            custom_first_message='Custom Message',
        )

        self.assertLastOutgoingSMS('+999123', ['Custom Message'])

    def test_custom_message_for_android_only_workflow(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        # Initiate Registration Workflow
        with patch('corehq.apps.sms.models.SelfRegistrationInvitation.odk_url') as mock_odk_url, \
                patch.object(SelfRegistrationInvitation, 'get_user_registration_url', return_value=DUMMY_REGISTRATION_URL), \
                patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            mock_odk_url.__get__ = Mock(return_value=DUMMY_APP_ODK_URL)
            SelfRegistrationInvitation.initiate_workflow(
                self.domain,
                [SelfRegistrationUserInfo('999123')],
                app_id=self.app_id,
                android_only=True,
                custom_first_message='Sign up here: {}',
            )

        self.assertLastOutgoingSMS('+999123', [
            'Sign up here: {}'.format(DUMMY_REGISTRATION_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])

    def test_resend_install_link(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        with patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            success_numbers, invalid_format_numbers, error_numbers = SelfRegistrationInvitation.send_install_link(
                self.domain,
                [SelfRegistrationUserInfo('999123')],
                self.app_id
            )
            self.assertEqual(success_numbers, ['999123'])
            self.assertEqual(invalid_format_numbers, [])
            self.assertEqual(error_numbers, [])

        self.assertLastOutgoingSMS('+999123', [
            _MESSAGES[MSG_REGISTRATION_INSTALL_COMMCARE].format(GOOGLE_PLAY_STORE_COMMCARE_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])

    def test_resend_install_link_with_custom_message(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        with patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            success_numbers, invalid_format_numbers, error_numbers = SelfRegistrationInvitation.send_install_link(
                self.domain,
                [SelfRegistrationUserInfo('999123')],
                self.app_id,
                custom_message='Click here to reinstall CommCare: {}'
            )
            self.assertEqual(success_numbers, ['999123'])
            self.assertEqual(invalid_format_numbers, [])
            self.assertEqual(error_numbers, [])

        self.assertLastOutgoingSMS('+999123', [
            'Click here to reinstall CommCare: {}'.format(GOOGLE_PLAY_STORE_COMMCARE_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])
Exemple #57
0
 def domain_obj(self, domain_name):
     return Domain.get_by_name(domain_name)
Exemple #58
0
 def test_should_sync_flat_format_default(self):
     self.assertEqual(True, should_sync_flat_fixture(Domain()))
def commit_migration(domain_name):
    domain = Domain.get_by_name(domain_name)
    domain.use_sql_backend = True
    domain.save()
    clear_local_domain_sql_backend_override(domain_name)
    assert should_use_sql_backend(domain_name)
Exemple #60
0
def import_app(request, domain):
    template = "app_manager/import_app.html"
    if request.method == "POST":
        clear_app_cache(request, domain)
        name = request.POST.get('name')
        file = request.FILES.get('source_file')

        valid_request = True
        if not name:
            messages.error(
                request,
                _("You must submit a name for the application you are importing."
                  ))
            valid_request = False
        if not file:
            messages.error(request, _("You must upload the app source file."))
            valid_request = False

        try:
            if valid_request:
                source = json.load(file)
        except json.decoder.JSONDecodeError:
            messages.error(request,
                           _("The file uploaded is an invalid JSON file"))
            valid_request = False

        if not valid_request:
            return render(request, template, {'domain': domain})

        assert (source is not None)
        app = import_app_util(source, domain, {'name': name}, request=request)

        return back_to_main(request, domain, app_id=app._id)
    else:
        app_id = request.GET.get('app')
        redirect_domain = request.GET.get('domain') or None
        if redirect_domain is not None:
            redirect_domain = redirect_domain.lower()
            if Domain.get_by_name(redirect_domain):
                return HttpResponseRedirect(
                    reverse('import_app', args=[redirect_domain]) +
                    "?app={app_id}".format(app_id=app_id))
            else:
                if redirect_domain:
                    messages.error(
                        request, "We can't find a project called \"%s\"." %
                        redirect_domain)
                else:
                    messages.error(request, "You left the project name blank.")
                return HttpResponseRedirect(
                    request.META.get('HTTP_REFERER', request.path))

        if app_id:
            app = get_app(None, app_id)
            assert (app.get_doc_type() in ('Application', 'RemoteApp'))
            assert (request.couch_user.is_member_of(app.domain))
        else:
            app = None

        return render(request, template, {
            'domain': domain,
            'app': app,
        })