def setUp(self):
        super(TestNewDomainSubscription, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

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

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

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]
        self.account2 = BillingAccount.get_or_create_account_by_domain(
            self.domain2.name, created_by=self.admin_user.username)[0]
        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)
        self.advanced_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.ADVANCED)
Ejemplo n.º 2
0
def product_fixture_generator(user, version, last_sync):
    if not user.domain:
        return []
    domain = Domain.get_by_name(user.domain)
    if not domain or not Domain.get_by_name(user.domain).commtrack_enabled:
        return []

    root = ElementTree.Element('fixture',
                               attrib={'id': 'commtrack:products',
                                       'user_id': user.user_id})
    products = ElementTree.Element('products')
    root.append(products)
    for product_data in Product.by_domain(user.domain):
        product = (ElementTree.Element('product',
                                       {'id': product_data.get_id}))
        products.append(product)
        product_fields = ['name',
                          'unit',
                          'code',
                          'description',
                          'category',
                          'program_id',
                          'cost']
        for product_field in product_fields:
            field = ElementTree.Element(product_field)
            field.text = unicode(getattr(product_data, product_field) or '')
            product.append(field)

    return [root]
Ejemplo n.º 3
0
def _copy(config):
    # unfortunately the only couch view we have for this needs to go by domain
    # will be a bit slow
    database = Domain.get_db()
    assert database.uri == config.source_db.uri, 'can only use "copy" with the main HQ DB as the source'
    domain_names = Domain.get_all_names()
    for domain in domain_names:
        for doc_type in config.doc_types:
            ids_of_this_type = [row['id'] for row in database.view(
                'domain/docs',
                startkey=[domain, doc_type],
                endkey=[domain, doc_type, {}],
                reduce=False,
                include_docs=False,
            )]
            if ids_of_this_type:
                new_revs = dict([
                    (row['id'], row['value']['rev'])
                    for row in config.dest_db.view('_all_docs', keys=ids_of_this_type, include_docs=False)
                    if 'error' not in row
                ])
                for id_group in chunked(ids_of_this_type, 500):
                    docs = get_docs(database, id_group)
                    for doc in docs:
                        if doc['_id'] in new_revs:
                            doc['_rev'] = new_revs[doc['_id']]
                    config.dest_db.bulk_save(docs)

            print 'copied {} {}s from {}'.format(len(ids_of_this_type), doc_type, domain)
    print 'copy docs complete'
Ejemplo n.º 4
0
    def setUp(self):
        super(TestRenewSubscriptions, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

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

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]

        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)

        today = datetime.date.today()
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=1)

        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.standard_plan,
            web_user=self.admin_user.username,
            date_start=yesterday,
            date_end=tomorrow,
        )

        self.subscription.save()
Ejemplo n.º 5
0
    def setUp(self):
        super(TestNewDomainSubscription, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

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

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

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]
        self.account2 = BillingAccount.get_or_create_account_by_domain(
            self.domain2.name, created_by=self.admin_user.username)[0]
        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)
        self.advanced_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.ADVANCED)
    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))
Ejemplo n.º 7
0
    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))
Ejemplo n.º 8
0
    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
        )
class TestRenewSubscriptions(BaseAccountingTest):

    def setUp(self):
        super(TestRenewSubscriptions, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

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

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]

        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)

        today = datetime.date.today()
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=1)

        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.standard_plan,
            web_user=self.admin_user.username,
            date_start=yesterday,
            date_end=tomorrow,
        )

        self.subscription.save()

    def test_simple_renewal(self):
        today = datetime.date.today()
        new_end_date = today + datetime.timedelta(days=9)

        renewed_subscription = self.subscription.renew_subscription(
            date_end=new_end_date
        )

        self.assertEqual(renewed_subscription.date_end, new_end_date)
        self.assertEqual(renewed_subscription.date_start, self.subscription.date_end)
        self.assertEqual(renewed_subscription.plan_version, self.subscription.plan_version)

    def test_change_plan_on_renewal(self):
        today = datetime.date.today()
        new_end_date = today + datetime.timedelta(days=9)
        new_edition = SoftwarePlanEdition.ADVANCED
        new_plan = DefaultProductPlan.get_default_plan_by_domain(self.domain.name, new_edition)

        renewed_subscription = self.subscription.renew_subscription(
            date_end=new_end_date,
            new_version=new_plan
        )

        self.assertEqual(renewed_subscription.plan_version, new_plan)
Ejemplo n.º 10
0
class TestRenewSubscriptions(BaseAccountingTest):
    def setUp(self):
        super(TestRenewSubscriptions, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

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

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]

        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)

        today = datetime.date.today()
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=1)

        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.standard_plan,
            web_user=self.admin_user.username,
            date_start=yesterday,
            date_end=tomorrow,
        )

        self.subscription.save()

    def test_simple_renewal(self):
        today = datetime.date.today()
        new_end_date = today + datetime.timedelta(days=9)

        renewed_subscription = self.subscription.renew_subscription(
            date_end=new_end_date)

        self.assertEqual(renewed_subscription.date_end, new_end_date)
        self.assertEqual(renewed_subscription.date_start,
                         self.subscription.date_end)
        self.assertEqual(renewed_subscription.plan_version,
                         self.subscription.plan_version)

    def test_change_plan_on_renewal(self):
        today = datetime.date.today()
        new_end_date = today + datetime.timedelta(days=9)
        new_edition = SoftwarePlanEdition.ADVANCED
        new_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, new_edition)

        renewed_subscription = self.subscription.renew_subscription(
            date_end=new_end_date, new_version=new_plan)

        self.assertEqual(renewed_subscription.plan_version, new_plan)
Ejemplo n.º 11
0
 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
     )
Ejemplo n.º 12
0
 def tearDownClass(cls):
     MobileBackend.load_by_name(TEST_DOMAIN, TEST_BACKEND).delete()
     CommCareUser.get_by_username('stella').delete()
     CommCareUser.get_by_username('super').delete()
     delete_all_locations()
     LocationType.objects.all().delete()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
     SQLProduct.objects.all().delete()
     EWSGhanaConfig.for_domain(TEST_DOMAIN).delete()
     DocDomainMapping.objects.all().delete()
     generator.delete_all_subscriptions()
     Domain.get_by_name(TEST_DOMAIN).delete()
Ejemplo n.º 13
0
 def tearDownClass(cls):
     MobileBackend.load_by_name(TEST_DOMAIN, TEST_BACKEND).delete()
     CommCareUser.get_by_username('stella').delete()
     CommCareUser.get_by_username('super').delete()
     delete_all_locations()
     LocationType.objects.all().delete()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
     SQLProduct.objects.all().delete()
     EWSGhanaConfig.for_domain(TEST_DOMAIN).delete()
     DocDomainMapping.objects.all().delete()
     generator.delete_all_subscriptions()
     Domain.get_by_name(TEST_DOMAIN).delete()
Ejemplo n.º 14
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 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()
Ejemplo n.º 15
0
def stock_data_submission(sender, cases, endpoint=None, **kwargs):
    project = Domain.get_by_name(cases[0].domain)

    if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:

        if endpoint is None:
            endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config)

        # get agentCode and programCode - I assume all cases are part of the same program
        agentCode = (cases[0].get_supply_point_case()).location.site_code
        programCode = Program.get(cases[0].get_product().program_id).code

        products = []
        for case in cases:
            product = case.get_product()

            product_json = {'productCode': product.code}
            product_json['stockInHand'] = int(case.get_default_value())

            products.append(product_json)

        stock_data = {  'agentCode': agentCode,
                        'programCode': programCode,
                        'products': products
        }
        response = sync_stock_data_to_openlmis(submission=stock_data, openlmis_endpoint=endpoint)

        if response['requisitionId'] is not None:
            for case in cases:
                case.external_id = response['requisitionId']
                case.save()

            cases, send_notification = sync_requisition_from_openlmis(project.name, response['requisitionId'], endpoint)
            if send_notification:
                send_notifications(xform=None, cases=cases)
Ejemplo n.º 16
0
def stock_data_submission(sender, cases, endpoint=None, **kwargs):
    project = Domain.get_by_name(cases[0].domain)

    if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:

        if endpoint is None:
            endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config)

        # get agentCode and programCode - I assume all cases are part of the same program
        agentCode = (cases[0].get_supply_point_case()).location.site_code
        programCode = Program.get(cases[0].get_product().program_id).code

        products = []
        for case in cases:
            product = case.get_product()

            product_json = {'productCode': product.code}
            product_json['stockInHand'] = int(case.get_default_value())

            products.append(product_json)

        stock_data = {  'agentCode': agentCode,
                        'programCode': programCode,
                        'products': products
        }
        response = sync_stock_data_to_openlmis(submission=stock_data, openlmis_endpoint=endpoint)

        if response['requisitionId'] is not None:
            for case in cases:
                case.external_id = response['requisitionId']
                case.save()

            cases, send_notification = sync_requisition_from_openlmis(project.name, response['requisitionId'], endpoint)
            if send_notification:
                send_notifications(xform=None, cases=cases)
Ejemplo n.º 17
0
def location_restriction_for_users(request, domain):
    project = Domain.get_by_name(domain)
    if "restrict_users" in request.POST:
        project.location_restriction_for_users = json.loads(
            request.POST["restrict_users"])
    project.save()
    return HttpResponse()
    def setUp(self):
        super(TestRenewSubscriptions, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

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

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]

        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)

        today = datetime.date.today()
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=1)

        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.standard_plan,
            web_user=self.admin_user.username,
            date_start=yesterday,
            date_end=tomorrow,
        )

        self.subscription.save()
Ejemplo n.º 19
0
def update_careplan_config(config, parent_app_id, application):
    app_props = config.app_configs.get(parent_app_id, CareplanAppProperties())
    app_props.latest_release = application.get_id
    for module in application.get_modules():
        if isinstance(module, CareplanModule):
            app_props.name = module.default_name()
            app_props.case_type = module.case_type
            app_props.goal_conf = {
                "edit_module_id":
                module.id,
                "edit_form_id":
                module.get_form_by_type(CAREPLAN_GOAL, 'update').id,
                "create_module_id":
                module.id,
                "create_form_id":
                module.get_form_by_type(CAREPLAN_GOAL, 'create').id,
            }
            app_props.task_conf = {
                "edit_module_id":
                module.id,
                "edit_form_id":
                module.get_form_by_type(CAREPLAN_TASK, 'update').id,
                "create_module_id":
                module.id,
                "create_form_id":
                module.get_form_by_type(CAREPLAN_TASK, 'create').id,
            }
            break
    config.app_configs[parent_app_id] = app_props
    config.save()
    domain = Domain.get_by_name(application.domain)
    if not domain.has_careplan:
        domain.has_careplan = True
        domain.save()
Ejemplo n.º 20
0
def update_careplan_config(config, parent_app_id, application):
        app_props = config.app_configs.get(parent_app_id, CareplanAppProperties())
        app_props.latest_release = application.get_id
        for module in application.get_modules():
            if isinstance(module, CareplanModule):
                app_props.name = module.default_name()
                app_props.case_type = module.case_type
                app_props.goal_conf = {
                    "edit_module_id": module.id,
                    "edit_form_id": module.get_form_by_type(CAREPLAN_GOAL, 'update').id,
                    "create_module_id": module.id,
                    "create_form_id": module.get_form_by_type(CAREPLAN_GOAL, 'create').id,
                }
                app_props.task_conf = {
                    "edit_module_id": module.id,
                    "edit_form_id": module.get_form_by_type(CAREPLAN_TASK, 'update').id,
                    "create_module_id": module.id,
                    "create_form_id": module.get_form_by_type(CAREPLAN_TASK, 'create').id,
                }
                break
        config.app_configs[parent_app_id] = app_props
        config.save()
        domain = Domain.get_by_name(application.domain)
        if not domain.has_careplan:
            domain.has_careplan = True
            domain.save()
Ejemplo n.º 21
0
    def handle(self, *args, **options):
        domain = args[0]
        db = Domain.get_db()
        doc_ids = [
            r['id'] for r in db.view(
                'domain/docs',
                startkey=[domain, 'RepeatRecord'],
                endkey=[domain, 'RepeatRecord', {}],
                reduce=False,
            )
        ]
        count = len(doc_ids)
        print 'found %s doc ids' % count
        latest = datetime.min
        latest_doc = None
        for i, doc in enumerate(iter_docs(db, doc_ids)):
            wrapped = RepeatRecord.wrap(doc)
            if i % 100 == 0:
                print 'checked %s / %s' % (i, count)
            if wrapped.last_checked and wrapped.last_checked > latest:
                latest = wrapped.last_checked
                latest_doc = wrapped
                print 'new latest: %s' % latest

        if latest_doc:
            print 'latest repeater date is %s' % latest
            print 'latest repeater is %s' % latest_doc._id
        else:
            print 'no relevant repeaters found'
 def handle(self, *args, **options):
     if len(args) != 1:
         print "Invalid arguments: %s" % str(args)
         return
     domain = Domain.get_by_name(args[0])
     if not domain:
         print "Invalid domain name: %s" % args[0]
         return
     account, _ = BillingAccount.get_or_create_account_by_domain(
         domain.name,
         account_type=BillingAccountType.CONTRACT,
         created_by="management command",
     )
     enterprise_plan_version = SoftwarePlanVersion.objects.filter(
         plan__edition=SoftwarePlanEdition.ENTERPRISE
     )[0]
     try:
         subscription = Subscription.new_domain_subscription(
             account,
             domain.name,
             enterprise_plan_version
         )
     except NewSubscriptionError as e:
         print e.message
         return
     subscription.is_active = True
     subscription.save()
     print 'Domain %s has been upgraded to enterprise level.' % domain.name
Ejemplo n.º 23
0
    def filter_context(self):
        api_root = reverse('api_dispatch_list', kwargs={'domain': self.domain,
                                                        'resource_name': 'location',
                                                        'api_name': 'v0.3'})
        selected_loc_id = self.request.GET.get('location_id')
        user = CouchUser.get_by_username(unicode(self.request.user))
        domain = Domain.get_by_name(self.domain)

        context = {}
        location_id = None

        domain_membership = user.get_domain_membership(self.domain)
        if domain_membership:
            location_id = domain_membership.location_id

        if not selected_loc_id and location_id and domain.commtrack_enabled:
            selected_loc_id = location_id
            if domain.location_restriction_for_users:
                context.update({'restriction': domain.location_restriction_for_users})

        context.update({
            'api_root': api_root,
            'control_name': self.label, # todo: cleanup, don't follow this structure
            'control_slug': self.slug, # todo: cleanup, don't follow this structure
            'loc_id': selected_loc_id,
            'locations': json.dumps(load_locs_json(self.domain, selected_loc_id)),
            'hierarchy': location_hierarchy_config(self.domain)
        })

        return context
Ejemplo n.º 24
0
 def handle(self, *args, **options):
     billables_created = 0
     for domain in Domain.get_all():
         key = [domain.name, 'SMSLog']
         start_date = [datetime.datetime(2014, 1, 1).isoformat()]
         end_date = [datetime.datetime(2014, 1, 24).isoformat()]
         sms_docs = SMSLog.get_db().view('sms/by_domain',
                                         reduce=False,
                                         startkey=key + start_date,
                                         endkey=key + end_date + [{}])
         for sms_doc in sms_docs:
             sms_log = SMSLog.get(sms_doc['id'])
             try:
                 if sms_log.phone_number is not None:
                     parse_phone_number(sms_log.phone_number)
             except PhoneNumberParseException:
                 billables = SmsBillable.objects.filter(log_id=sms_log._id)
                 if len(billables) == 0:
                     SmsBillable.create(sms_log)
                     billables_created += 1
                     print 'created SmsBillable for invalid number %s in domain %s, id=%s'\
                           % (sms_log.phone_number, domain.name, sms_log._id)
                 elif len(billables) > 1:
                     print "Warning: >1 SmsBillable exists for SMSLog with id=%" % sms_log._id
     print 'Number of SmsBillables created: %d' % billables_created
     print 'Completed retrobilling.'
Ejemplo n.º 25
0
def enable_usercase(domain_name):
    with CriticalSection(['enable_usercase_' + domain_name]):
        domain = Domain.get_by_name(domain_name, strict=True)
        if not domain.usercase_enabled:
            domain.usercase_enabled = True
            domain.save()
            create_user_cases.delay(domain_name)
Ejemplo n.º 26
0
def get_settings_values(app):
    try:
        profile = app.profile
    except AttributeError:
        profile = {}
    hq_settings = dict([(attr, app[attr]) for attr in app.properties()
                        if not hasattr(app[attr], 'pop')])
    if getattr(app, 'use_custom_suite', False):
        hq_settings.update(
            {'custom_suite': getattr(app, 'custom_suite', None)})

    hq_settings['build_spec'] = app.build_spec.to_string()
    # the admin_password hash shouldn't be sent to the client
    hq_settings.pop('admin_password', None)

    domain = Domain.get_by_name(app.domain)
    return {
        'properties': profile.get('properties', {}),
        'features': profile.get('features', {}),
        'hq': hq_settings,
        '$parent': {
            'doc_type': app.get_doc_type(),
            '_id': app.get_id,
            'domain': app.domain,
            'commtrack_enabled': domain.commtrack_enabled,
        }
    }
    def handle(self, *args, **options):
        num_sms = 0

        start_datetime = datetime.datetime(*str_to_int_tuple(args[0:6]))
        end_datetime = datetime.datetime(*str_to_int_tuple(args[6:12]))

        for domain in Domain.get_all():
            key = [domain.name, 'SMSLog']
            sms_docs = SMSLog.get_db().view('sms/by_domain',
                                            reduce=False,
                                            startkey=key + [start_datetime.isoformat()],
                                            endkey=key + [end_datetime.isoformat(), {}],
            )

            for sms_doc in sms_docs:
                sms_log = SMSLog.get(sms_doc['id'])
                if options.get('create', False):
                    SmsBillable.create(sms_log)
                    print 'Created billable for SMSLog %s in domain %s from %s' \
                          % (sms_doc['id'], domain.name, sms_log.date)
                else:
                    print 'Found SMSLog %s in domain %s from %s' \
                          % (sms_doc['id'], domain.name, sms_log.date)
                num_sms += 1

        print 'Number of SMSs in datetime range: %d' % num_sms
Ejemplo n.º 28
0
 def invite(self, invitation, user):
     project = Domain.get_by_name(self.domain)
     user.add_domain_membership(domain=self.domain)
     user.set_role(self.domain, invitation.role)
     if project.commtrack_enabled and not project.location_restriction_for_users:
         user.location_id = invitation.supply_point
     user.save()
Ejemplo n.º 29
0
    def __init__(self,
                 domain,
                 new_plan_version,
                 changed_privs,
                 verbose=False,
                 date_start=None,
                 web_user=None):
        self.web_user = web_user
        self.verbose = verbose
        self.date_start = date_start or datetime.date.today()
        if isinstance(changed_privs, set):
            changed_privs = list(changed_privs)
        if not isinstance(domain, Domain):
            domain = Domain.get_by_name(domain)
        self.domain = domain

        # plan dependent privilege
        changed_privs.append(privileges.MOBILE_WORKER_CREATION)

        # check to make sure that no subscriptions are scheduled to
        # start in the future
        changed_privs.append(LATER_SUBSCRIPTION_NOTIFICATION)

        self.privileges = filter(lambda x: x in self.supported_privileges,
                                 changed_privs)
        self.new_plan_version = new_plan_version
Ejemplo n.º 30
0
def get_settings_values(app):
    try:
        profile = app.profile
    except AttributeError:
        profile = {}
    hq_settings = dict([
        (attr, app[attr])
        for attr in app.properties() if not hasattr(app[attr], 'pop')
    ])
    if getattr(app, 'use_custom_suite', False):
        hq_settings.update({'custom_suite': getattr(app, 'custom_suite', None)})

    hq_settings['build_spec'] = app.build_spec.to_string()
    # the admin_password hash shouldn't be sent to the client
    hq_settings.pop('admin_password', None)

    domain = Domain.get_by_name(app.domain)
    return {
        'properties': profile.get('properties', {}),
        'features': profile.get('features', {}),
        'hq': hq_settings,
        '$parent': {
            'doc_type': app.get_doc_type(),
            '_id': app.get_id,
            'domain': app.domain,
            'commtrack_enabled': domain.commtrack_enabled,
        }
    }
Ejemplo n.º 31
0
 def options(self):
     return clean_options(
         [
             (domain.name, domain.name)
             for domain in Domain.get_all()
         ]
     )
Ejemplo n.º 32
0
class TestBillingRecord(BaseAccountingTest):

    def setUp(self):
        super(TestBillingRecord, 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.invoice_start, self.invoice_end = get_previous_month_date_range()
        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
        )
        self.invoice = Invoice(
            subscription=self.subscription,
            date_start=self.invoice_start,
            date_end=self.invoice_end,
            is_hidden=False,
        )
        self.billing_record = BillingRecord(invoice=self.invoice)

    def test_should_send_email(self):
        self.assertTrue(self.billing_record.should_send_email)

    def test_should_send_email_contracted(self):
        self.subscription.service_type = SubscriptionType.CONTRACTED
        self.assertFalse(self.billing_record.should_send_email)

        self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD - 1)
        self.assertFalse(self.billing_record.should_send_email)

        self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD + 1)
        self.assertTrue(self.billing_record.should_send_email)

    def test_should_send_email_autogenerate_credits(self):
        self.subscription.auto_generate_credits = True
        self.assertFalse(self.billing_record.should_send_email)

        self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD + 1)
        self.assertTrue(self.billing_record.should_send_email)

    def test_should_send_email_hidden(self):
        self.assertTrue(self.billing_record.should_send_email)

        self.invoice.is_hidden = True
        self.assertFalse(self.billing_record.should_send_email)
Ejemplo n.º 33
0
def can_edit_form_location(domain, user, form):
    if not toggles.RESTRICT_FORM_EDIT_BY_LOCATION.enabled(domain):
        return True

    location = get_xform_location(form)
    if not location:
        return True
    return user_can_edit_location(user, location, Domain.get_by_name(domain))
Ejemplo n.º 34
0
 def setUpClass(cls):
     cls.domain = Domain(name='foo')
     cls.domain.save()
     cls.user = CommCareUser.create(cls.domain.name, 'somebody', 'password')
     cls.user_id = cls.user._id
     cls.factory = CaseFactory(domain='foo',
                               case_defaults={'owner_id': cls.user_id})
     ENABLE_LOADTEST_USERS.set('foo', True, namespace='domain')
Ejemplo n.º 35
0
    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()
        self.locations = {}
        LocationType.objects.create(
            domain='test',
            name='facility',
        )
        LocationType.objects.create(
            domain='test2',
            name='facility',
        )

        self._create_data('test')
        self._create_data('test2')
Ejemplo n.º 36
0
def confirm_delivery(sender, requisitions, **kwargs):
    if requisitions and requisitions[
            0].requisition_status == RequisitionStatus.RECEIVED:
        project = Domain.get_by_name(requisitions[0].domain)
        if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:
            endpoint = OpenLMISEndpoint.from_config(
                project.commtrack_settings.openlmis_config)
            delivery_update(requisitions, endpoint)
Ejemplo n.º 37
0
    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()
        self.locations = {}
        LocationType.objects.create(
            domain='test',
            name='facility',
        )
        LocationType.objects.create(
            domain='test2',
            name='facility',
        )

        self._create_data('test')
        self._create_data('test2')
Ejemplo n.º 38
0
def approve_requisitions(sender, requisitions, **kwargs):
    if requisitions and requisitions[
            0].requisition_status == RequisitionStatus.APPROVED:
        project = Domain.get_by_name(requisitions[0].domain)
        if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:
            endpoint = OpenLMISEndpoint.from_config(
                project.commtrack_settings.openlmis_config)
            approve_requisition(requisitions, endpoint)
Ejemplo n.º 39
0
 def get_locations(self):
     location_types = [
         location_type.name
         for location_type in Domain.get_by_name(self.domain).location_types
         if location_type.administrative
     ]
     return SQLLocation.objects.filter(parent__location_id=self.config['location_id'],
                                       location_type__name__in=location_types, is_archived=False)
Ejemplo n.º 40
0
def location_restriction_for_users(request, domain):
    if not toggles.RESTRICT_WEB_USERS_BY_LOCATION.enabled(request.domain):
        raise Http403()
    project = Domain.get_by_name(domain)
    if "restrict_users" in request.POST:
        project.location_restriction_for_users = json.loads(request.POST["restrict_users"])
    project.save()
    return HttpResponse()
Ejemplo n.º 41
0
 def invite(self, invitation, user):
     project = Domain.get_by_name(self.domain)
     user.add_domain_membership(domain=self.domain)
     user.set_role(self.domain, invitation.role)
     if project.commtrack_enabled and not project.location_restriction_for_users:
         user.get_domain_membership(self.domain).location_id = invitation.supply_point
         user.get_domain_membership(self.domain).program_id = invitation.program
     user.save()
Ejemplo n.º 42
0
 def facilities(self, **kwargs):
     reporting_types = [
         loc_type.name for loc_type in Domain.get_by_name(self.config['domain']).location_types
         if not loc_type.administrative
     ]
     return SQLLocation.objects.filter(domain=self.domain,
                                       location_type__in=reporting_types,
                                       **kwargs)
Ejemplo n.º 43
0
 def get_locations(self):
     location_types = [
         loc_type.name for loc_type in filter(lambda loc_type: loc_type.administrative,
                                              Domain.get_by_name(self.config['domain']).location_types
                                              )
     ]
     return SQLLocation.objects.filter(parent__location_id=self.config['location_id'],
                                       location_type__in=location_types)
Ejemplo n.º 44
0
def supply_point_updated(sender, supply_point, created, **kwargs):
    project = Domain.get_by_name(supply_point.domain)
    if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:
        # check if supply_point is of 'chw type'
        if supply_point.location and supply_point.location.location_type == "chw":
            #check if supply_point is linked to an OpenLMIS facility
            if supply_point.location.lineage and len(supply_point.location.lineage) > 0:
                endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config)
                sync_supply_point_to_openlmis(supply_point, endpoint, created)
Ejemplo n.º 45
0
def careplan_removed(domain_name, config, app_id):
    if config and app_id in config.app_configs:
        del config.app_configs[app_id]
        config.save()

        if not config.app_configs:
            domain = Domain.get_by_name(domain_name)
            domain.has_careplan = False
            domain.save()
Ejemplo n.º 46
0
def careplan_removed(domain_name, config, app_id):
    if config and app_id in config.app_configs:
        del config.app_configs[app_id]
        config.save()

        if not config.app_configs:
            domain = Domain.get_by_name(domain_name)
            domain.has_careplan = False
            domain.save()
Ejemplo n.º 47
0
 def domain_response(self):
     domain_names = [
         domain['key'] for domain in Domain.get_all(include_docs=False)
     ]
     if self.search_string:
         domain_names = filter(
             lambda x: x.lower().startswith(self.search_string.lower()),
             domain_names)
     return [(d, d) for d in domain_names]
Ejemplo n.º 48
0
 def subscribed_domains(self):
     if self.subscription.subscriber.organization is None and self.subscription.subscriber.domain is None:
         raise LineItemError(
             "No domain or organization could be obtained as the subscriber."
         )
     if self.subscription.subscriber.organization is not None:
         return Domain.get_by_organization(
             self.subscription.subscriber.organization)
     return [self.subscription.subscriber.domain]
Ejemplo n.º 49
0
def supply_point_updated(sender, supply_point, created, **kwargs):
    project = Domain.get_by_name(supply_point.domain)
    if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:
        # check if supply_point is of 'chw type'
        if supply_point.location and supply_point.location.location_type == "chw":
            #check if supply_point is linked to an OpenLMIS facility
            if supply_point.location.lineage and len(supply_point.location.lineage) > 0:
                endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config)
                sync_supply_point_to_openlmis(supply_point, endpoint, created)
Ejemplo n.º 50
0
def location_restriction_for_users(request, domain):
    if not toggles.RESTRICT_WEB_USERS_BY_LOCATION.enabled(request.domain):
        raise Http403()
    project = Domain.get_by_name(domain)
    if "restrict_users" in request.POST:
        project.location_restriction_for_users = json.loads(
            request.POST["restrict_users"])
    project.save()
    return HttpResponse()
Ejemplo n.º 51
0
 def _create_location_type_if_not_exists(self, supply_point, location):
     domain = Domain.get_by_name(self.domain)
     if not filter(lambda l: l.name == supply_point.type, domain.location_types):
         domain.location_types.append(LocationType(
             name=supply_point.type,
             allowed_parents=[location.location_type],
             administrative=False
         ))
         domain.save()
Ejemplo n.º 52
0
    def handle(self, doc_types, *args, **options):

        input = raw_input('\n'.join([
            '\n\nReally delete documents of the following types: {}?',
            'This operation is not reversible. Enter a number N to delete the first '
            'N found, or type "delete all" to delete everything.',
            '',
        ]).format(doc_types))
        if input == 'delete all':
            remaining = None
        else:
            try:
                remaining = int(input)
            except ValueError:
                print 'aborting'
                sys.exit()

        doc_types = doc_types.split(',')
        deleted = 0

        # unfortunately the only couch view we have for this needs to go by domain
        # will be a bit slow
        domain_names = Domain.get_all_names()
        database = Domain.get_db()
        for domain in domain_names:
            for doc_type in doc_types:
                docs = [row['doc'] for row in database.view(
                    'domain/docs',
                    startkey=[domain, doc_type],
                    endkey=[domain, doc_type, {}],
                    reduce=False,
                    include_docs=True,
                )][:remaining]
                if docs:
                    count = len(docs)
                    print 'deleting {} {}s from {}'.format(count, doc_type, domain)
                    database.delete_docs(docs)
                    deleted += count
                    if remaining is not None:
                        remaining -= count
                        if remaining <= 0:
                            return

        print 'successfully deleted {} documents'.format(deleted)
Ejemplo n.º 53
0
 def setUp(self):
     super(TestBillingRecord, 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.invoice_start, self.invoice_end = get_previous_month_date_range()
     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
     )
     self.invoice = Invoice(
         subscription=self.subscription,
         date_start=self.invoice_start,
         date_end=self.invoice_end,
         is_hidden=False,
     )
     self.billing_record = BillingRecord(invoice=self.invoice)