def test_new_susbscription_in_future(self):
        """
        Test covers issue that came up with commcare-hq/PR#3725.
        """
        today = datetime.date.today()
        in_30_days = today + datetime.timedelta(days=30)
        week_after_30 = in_30_days + datetime.timedelta(days=7)
        next_year = week_after_30 + datetime.timedelta(days=400)

        # mimic domain signing up for trial
        trial_subscription = Subscription.new_domain_subscription(
            self.account, self.domain.name, self.advanced_plan,
            date_end=in_30_days,
            adjustment_method=SubscriptionAdjustmentMethod.TRIAL,
            is_trial=True,
        )
        trial_subscription.is_active = True
        trial_subscription.save()

        subscription = Subscription.new_domain_subscription(
            self.account2, self.domain.name, self.standard_plan,
            web_user=self.admin_user_name,
            date_start=week_after_30, date_end=next_year,
        )

        final_sub = Subscription.visible_objects.get(pk=subscription.id)

        self.assertEqual(final_sub.date_start, week_after_30)
        self.assertEqual(final_sub.date_end, next_year)
    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)
Example #3
0
def generate_domain_subscription_from_date(date_start, billing_account, domain,
                                           min_num_months=None, is_immediately_active=False,
                                           delay_invoicing_until=None, save=True):
    # make sure the first month is never a full month (for testing)
    date_start = date_start.replace(day=max(2, date_start.day))

    subscription_length = random.randint(min_num_months or 3, 25)
    date_end_year, date_end_month = add_months(date_start.year, date_start.month, subscription_length)
    date_end_last_day = calendar.monthrange(date_end_year, date_end_month)[1]

    # make sure that the last month is never a full month (for testing)
    date_end = datetime.date(date_end_year, date_end_month, min(date_end_last_day - 1, date_start.day + 1))

    subscriber, _ = Subscriber.objects.get_or_create(domain=domain, organization=None)
    subscription = Subscription(
        account=billing_account,
        plan_version=arbitrary_subscribable_plan(),
        subscriber=subscriber,
        salesforce_contract_id=data_gen.arbitrary_unique_name("SFC")[:80],
        date_start=date_start,
        date_end=date_end,
        is_active=is_immediately_active,
        date_delay_invoicing=delay_invoicing_until,
    )
    if save:
        subscription.save()
    return subscription, subscription_length
Example #4
0
    def test_preexisting_past_subscription(self):
        past_subscription_end_date = self.from_date - timedelta(days=10)
        past_subscription_start_date = past_subscription_end_date - timedelta(days=5)
        plan_version = self._random_plan_version
        Subscription.new_domain_subscription(
            self._preexisting_subscription_account,
            self.domain.name,
            plan_version,
            date_start=past_subscription_start_date,
            date_end=past_subscription_end_date,
        )

        self._assign_community_subscriptions()

        self.assertEqual(Subscription.objects.count(), 2)
        self.assertFalse(Subscription.objects.exclude(subscriber__domain=self.domain.name).exists())
        self.assertIsNotNone(Subscription.objects.get(
            date_start=self.from_date,
            date_end=None,
            plan_version=self._most_recently_created_community_plan_version,
            skip_invoicing_if_no_feature_charges=True,
        ))
        self.assertIsNotNone(Subscription.objects.get(
            date_start=past_subscription_start_date,
            date_end=past_subscription_end_date,
            plan_version=plan_version,
        ))
Example #5
0
 def ensure_full_coverage(self, subscriptions):
     plan_version = DefaultProductPlan.get_default_plan_by_domain(
         self.domain, edition=SoftwarePlanEdition.COMMUNITY
     ).plan.get_version()
     if not plan_version.feature_charges_exist_for_domain(self.domain):
         return
     community_ranges = self.get_community_ranges(subscriptions)
     if not community_ranges:
         return
     do_not_invoice = any([s.do_not_invoice for s in subscriptions])
     account = BillingAccount.get_or_create_account_by_domain(
         self.domain.name, created_by=self.__class__.__name__,
         created_by_invoicing=True)[0]
     if account.date_confirmed_extra_charges is None:
         if self.domain.is_active:
             subject = "[%s] Invoice Generation Issue" % self.domain.name
             email_content = render_to_string(
                 'accounting/invoice_error_email.html', {
                     'project': self.domain.name,
                     'error_msg': "This project is incurring charges on their "
                                  "Community subscription, but they haven't "
                                  "agreed to the charges yet. Someone should "
                                  "follow up with this project to see if everything "
                                  "is configured correctly or if communication "
                                  "needs to happen between Dimagi and the project's"
                                  "admins. For now, the invoices generated are "
                                  "marked as Do Not Invoice.",
                 }
             )
             send_HTML_email(
                 subject, settings.BILLING_EMAIL, email_content,
                 email_from="Dimagi Billing Bot <%s>" % settings.DEFAULT_FROM_EMAIL
             )
         do_not_invoice = True
     if not BillingContactInfo.objects.filter(account=account).exists():
         # No contact information exists for this account.
         # This shouldn't happen, but if it does, we can't continue
         # with the invoice generation.
         raise BillingContactInfoError(
             "Project %s has incurred charges, but does not have their "
             "Billing Contact Info filled out. Someone should follow up "
             "on this." % self.domain.name
         )
     # First check to make sure none of the existing subscriptions is set
     # to do not invoice. Let's be on the safe side and not send a
     # community invoice out, if that's the case.
     for c in community_ranges:
         # create a new community subscription for each
         # date range that the domain did not have a subscription
         community_subscription = Subscription(
             account=account,
             plan_version=plan_version,
             subscriber=self.subscriber,
             date_start=c[0],
             date_end=c[1],
             do_not_invoice=do_not_invoice,
         )
         community_subscription.save()
         subscriptions.append(community_subscription)
 def test_exceeding_max_domains_prevents_new_domains(self):
     self.advanced_plan.plan.max_domains = 1
     Subscription.new_domain_subscription(
         self.account, self.domain.name, self.advanced_plan
     )
     self.assertRaises(NewSubscriptionError, lambda: Subscription.new_domain_subscription(
         self.account, self.domain2.name, self.advanced_plan
     ))
    def test_change_plan_blocks_on_max_domains(self):
        Subscription.new_domain_subscription(
            self.account, self.domain.name, self.advanced_plan
        )

        sub2 = Subscription.new_domain_subscription(
            self.account, self.domain2.name, self.community_plan
        )
        self.assertRaises(SubscriptionAdjustmentError, lambda: sub2.change_plan(self.advanced_plan))
 def test_next_subscription_filter_no_end_date(self):
     next_subscription = Subscription(
         account=self.subscription.account,
         plan_version=self.subscription.plan_version,
         subscriber=self.subscription.subscriber,
         date_start=self.subscription.date_end,
         date_end=None,
     )
     next_subscription.save()
     self.assertEqual(next_subscription, self.subscription.next_subscription)
 def test_full_coverage(self):
     some_plan = generator.subscribable_plan_version()
     Subscription.new_domain_subscription(
         self.account, self.domain.name, some_plan,
         date_start=self.invoice_start,
         date_end=self.invoice_end + datetime.timedelta(days=1),
     )
     subscriptions = self.invoice_factory._get_subscriptions()
     community_ranges = self.invoice_factory._get_community_ranges(subscriptions)
     self.assertEqual(len(community_ranges), 0)
Example #10
0
    def test_transfers(self):
        advanced_plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.ADVANCED
        )
        standard_plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.STANDARD
        )
        first_sub = Subscription.new_domain_subscription(
            self.account, self.domain.name, advanced_plan,
            date_start=datetime.date.today() - relativedelta(days=1),
        )

        product_credit = CreditLine.add_credit(
            self.product_credit_amt, subscription=first_sub,
            is_product=True,
        )
        feature_credit = CreditLine.add_credit(
            self.feature_credit_amt, subscription=first_sub,
            feature_type=FeatureType.USER,
        )
        subscription_credit = CreditLine.add_credit(
            self.subscription_credit_amt, subscription=first_sub,
        )
        original_credits = [
            product_credit, feature_credit, subscription_credit,
        ]

        second_sub = first_sub.change_plan(standard_plan)

        second_credits = self._ensure_transfer(original_credits)
        for credit_line in second_credits:
            self.assertEqual(credit_line.subscription.pk, second_sub.pk)

        second_sub.date_end = datetime.date.today() + datetime.timedelta(days=5)
        second_sub.save()
        third_sub = second_sub.renew_subscription()
        deactivate_subscriptions(second_sub.date_end)
        third_sub = Subscription.visible_objects.get(id=third_sub.id)

        third_credits = self._ensure_transfer(second_credits)
        for credit_line in third_credits:
            self.assertEqual(credit_line.subscription.pk, third_sub.pk)

        third_sub.date_end = third_sub.date_start + relativedelta(days=1)
        third_sub.save()
        Subscription.new_domain_subscription(
            self.other_account, self.domain, DefaultProductPlan.get_default_plan_version(),
            date_start=third_sub.date_end,
        )
        deactivate_subscriptions(third_sub.date_end)

        account_credits = self._ensure_transfer(third_credits)
        for credit_line in account_credits:
            self.assertIsNone(credit_line.subscription)
            self.assertEqual(credit_line.account.pk, self.account.pk)
 def make_new_enterprise_subscription(self, domain):
     account, _ = BillingAccount.get_or_create_account_by_domain(
         domain.name,
         account_type=BillingAccountType.CONTRACT,
         created_by="management command",
     )
     Subscription.new_domain_subscription(
         account,
         domain.name,
         self.enterprise_plan_version,
     )
Example #12
0
def generate_domain_subscription(account, domain, date_start, date_end,
                                 plan_version=None, service_type=SubscriptionType.NOT_SET):
    subscriber, _ = Subscriber.objects.get_or_create(domain=domain.name)
    subscription = Subscription(
        account=account,
        plan_version=plan_version or subscribable_plan_version(),
        subscriber=subscriber,
        date_start=date_start,
        date_end=date_end,
        service_type=service_type,
    )
    subscription.save()
    return subscription
Example #13
0
 def subscription(self):
     """
     If we're arriving here, it's because there wasn't a subscription for the period of this invoice,
     so let's create one.
     """
     subscriber, _ = Subscriber.objects.get_or_create(domain=self.domain.name)
     subscription = Subscription(
         account=self.account,
         subscriber=subscriber,
         plan_version=self.software_plan_version,
         date_start=self.date_start,
         date_end=self.date_end,
     )
     subscription.save()
     return subscription
    def test_app_icon_permissions(self):
        LOGO_HOME = u'hq_logo_android_home'
        LOGO_LOGIN = u'hq_logo_android_login'

        advanced_sub = Subscription.new_domain_subscription(
            self.account, self.domain.name, self.advanced_plan,
            web_user=self.admin_user.username
        )
        with open(os.path.join(os.path.dirname(__file__), 'data', 'app-commcare-icon-standard.json')) as f:
            standard_source = json.load(f)
        with open(os.path.join(os.path.dirname(__file__), 'data', 'app-commcare-icon-build.json')) as f:
            build_source = json.load(f)

        app_standard = Application.wrap(standard_source)
        app_standard.save()
        self.assertEqual(self.domain.name, app_standard.domain)

        app_build = Application.wrap(build_source)
        app_build.save()
        self.assertEqual(self.domain.name, app_build.domain)

        self.assertTrue(LOGO_HOME in app_standard.logo_refs.keys())
        self.assertTrue(LOGO_LOGIN in app_standard.logo_refs.keys())
        self.assertTrue(LOGO_HOME in app_build.logo_refs.keys())
        self.assertTrue(LOGO_LOGIN in app_build.logo_refs.keys())

        advanced_sub.cancel_subscription(web_user=self.admin_user.username)

        app_standard = Application.get(app_standard._id)
        app_build = Application.get(app_build._id)

        self.assertFalse(LOGO_HOME in app_standard.logo_refs.keys())
        self.assertFalse(LOGO_LOGIN in app_standard.logo_refs.keys())
        self.assertFalse(LOGO_HOME in app_build.logo_refs.keys())
        self.assertFalse(LOGO_LOGIN in app_build.logo_refs.keys())

        Subscription.new_domain_subscription(
            self.account, self.domain.name, self.advanced_plan,
            web_user=self.admin_user.username
        )

        app_standard = Application.get(app_standard._id)
        app_build = Application.get(app_build._id)

        self.assertTrue(LOGO_HOME in app_standard.logo_refs.keys())
        self.assertTrue(LOGO_LOGIN in app_standard.logo_refs.keys())
        self.assertTrue(LOGO_HOME in app_build.logo_refs.keys())
        self.assertTrue(LOGO_LOGIN in app_build.logo_refs.keys())
Example #15
0
    def save(self, commit=True):
        try:
            billing_contact_info = super(BillingAccountInfoForm, self).save(commit=False)
            billing_contact_info.account = self.account
            billing_contact_info.save()

            billing_admins = self.cleaned_data['billing_admins']
            for admin in billing_admins:
                if not self.account.billing_admins.filter(web_user=admin.web_user).exists():
                    self.account.billing_admins.add(admin)
            self.account.save()
            if self.current_subscription is not None:
                if self.plan_version.plan.edition == SoftwarePlanEdition.COMMUNITY:
                    self.current_subscription.cancel_subscription(adjustment_method=SubscriptionAdjustmentMethod.USER,
                                                                  web_user=self.creating_user)
                else:
                    subscription = self.current_subscription.change_plan(
                        self.plan_version, web_user=self.creating_user, adjustment_method=SubscriptionAdjustmentMethod.USER
                    )
                    subscription.is_active = True
                    subscription.save()
            else:
                subscription = Subscription.new_domain_subscription(
                    self.account, self.domain, self.plan_version,
                    web_user=self.creating_user, adjustment_method=SubscriptionAdjustmentMethod.USER
                )
                subscription.is_active = True
                subscription.save()
            return True
        except Exception:
            logger.exception("There was an error subscribing the domain '%s' to plan '%s'. "
                             "Go quickly!" % (self.domain, self.plan_version.plan.name))
        return False
Example #16
0
    def setUp(self):
        super(OptTestCase, self).setUp()
        self.domain = "opt-test"

        self.domain_obj = Domain(name=self.domain)
        self.domain_obj.save()

        generator.instantiate_accounting_for_tests()
        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain_obj.name,
            created_by="automated-test",
        )[0]
        plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain_obj, edition=SoftwarePlanEdition.ADVANCED
        )
        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain_obj.name,
            plan
        )
        self.subscription.is_active = True
        self.subscription.save()

        self.backend = TestSMSBackend(is_global=True)
        self.backend.save()

        self.backend_mapping = BackendMapping(
            is_global=True,
            prefix="*",
            backend_id=self.backend._id,
        )
        self.backend_mapping.save()
Example #17
0
    def test_transfers(self):
        advanced_plan = DefaultProductPlan.get_default_plan_by_domain(self.domain, edition=SoftwarePlanEdition.ADVANCED)
        standard_plan = DefaultProductPlan.get_default_plan_by_domain(self.domain, edition=SoftwarePlanEdition.STANDARD)
        first_sub = Subscription.new_domain_subscription(self.account, self.domain, advanced_plan)

        product_credit = CreditLine.add_credit(
            self.product_credit_amt, subscription=first_sub, product_type=SoftwareProductType.COMMCARE
        )
        feature_credit = CreditLine.add_credit(
            self.feature_credit_amt, subscription=first_sub, feature_type=FeatureType.USER
        )
        subscription_credit = CreditLine.add_credit(self.subscription_credit_amt, subscription=first_sub)
        original_credits = [product_credit, feature_credit, subscription_credit]

        second_sub = first_sub.change_plan(standard_plan)

        second_credits = self._ensure_transfer(original_credits)
        for credit_line in second_credits:
            self.assertEqual(credit_line.subscription.pk, second_sub.pk)

        second_sub.date_end = datetime.date.today() + datetime.timedelta(days=5)
        second_sub.save()

        third_sub = second_sub.renew_subscription()
        third_credits = self._ensure_transfer(second_credits)
        for credit_line in third_credits:
            self.assertEqual(credit_line.subscription.pk, third_sub.pk)

        third_sub.cancel_subscription()
        account_credits = self._ensure_transfer(third_credits)
        for credit_line in account_credits:
            self.assertIsNone(credit_line.subscription)
            self.assertEqual(credit_line.account.pk, self.account.pk)
 def _change_to_probono(self, domain_name, pro_bono_status):
     subscription = Subscription.get_active_subscription_by_domain(domain_name)
     subscription.update_subscription(
         pro_bono_status=pro_bono_status,
         date_start=datetime.date.today() - datetime.timedelta(days=1),
         date_end=datetime.date.today() + datetime.timedelta(days=5)
     )
 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
Example #20
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
Example #21
0
def create_30_day_trial(domain_obj):
    from corehq.apps.accounting.models import (
        DefaultProductPlan,
        SoftwarePlanEdition,
        BillingAccount,
        Currency,
        BillingAccountType,
        Subscription,
        SubscriptionAdjustmentMethod,
    )
    # Create a 30 Day Trial subscription to the Advanced Plan
    advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain(
        domain_obj, edition=SoftwarePlanEdition.ADVANCED, is_trial=True
    )
    expiration_date = date.today() + timedelta(days=30)
    trial_account = BillingAccount.objects.get_or_create(
        name="Trial Account for %s" % domain_obj.name,
        currency=Currency.get_default(),
        created_by_domain=domain_obj.name,
        account_type=BillingAccountType.TRIAL,
    )[0]
    trial_subscription = Subscription.new_domain_subscription(
        trial_account, domain_obj.name, advanced_plan_version,
        date_end=expiration_date,
        adjustment_method=SubscriptionAdjustmentMethod.TRIAL,
        is_trial=True,
    )
    trial_subscription.is_active = True
    trial_subscription.save()
Example #22
0
def assign_explicit_community_subscription(domain_name, start_date, method, account=None, web_user=None):
    future_subscriptions = Subscription.visible_objects.filter(
        date_start__gt=start_date,
        subscriber__domain=domain_name,
    )
    if future_subscriptions.exists():
        end_date = future_subscriptions.earliest('date_start').date_start
    else:
        end_date = None

    if account is None:
        account = BillingAccount.get_or_create_account_by_domain(
            domain_name,
            created_by='assign_explicit_community_subscriptions',
            entry_point=EntryPoint.SELF_STARTED,
        )[0]

    return Subscription.new_domain_subscription(
        account=account,
        domain=domain_name,
        plan_version=DefaultProductPlan.get_default_plan_version(),
        date_start=start_date,
        date_end=end_date,
        skip_invoicing_if_no_feature_charges=True,
        adjustment_method=method,
        internal_change=True,
        service_type=SubscriptionType.PRODUCT,
        web_user=web_user,
    )
Example #23
0
def run_downgrade_process(today=None):
    today = today or datetime.date.today()

    for domain, oldest_unpaid_invoice, total in _get_domains_with_invoices_over_threshold(today):
        current_subscription = Subscription.get_active_subscription_by_domain(domain)
        if _is_subscription_eligible_for_downgrade_process(current_subscription):
            _apply_downgrade_process(current_subscription, oldest_unpaid_invoice, total, today)
Example #24
0
    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 _change_to_extended_trial(self, domain_name):
     subscription = Subscription.get_active_subscription_by_domain(domain_name)
     subscription.update_subscription(
         service_type=SubscriptionType.EXTENDED_TRIAL,
         date_start=datetime.date.today() - datetime.timedelta(days=1),
         date_end=datetime.date.today() + datetime.timedelta(days=5)
     )
    def test_update_billing_account_entry_point_contracted(self):
        contracted_subscription = Subscription.new_domain_subscription(
            self.account, self.domain.name, self.advanced_plan,
            web_user=self.admin_user_name, service_type=SubscriptionType.IMPLEMENTATION
        )

        self.assertNotEqual(contracted_subscription.account.entry_point, EntryPoint.SELF_STARTED)
Example #27
0
def assign_explicit_community_subscription(domain_name, start_date):
    future_subscriptions = Subscription.objects.filter(
        CONSISTENT_DATES_CHECK
    ).filter(
        date_start__gt=start_date,
        subscriber__domain=domain_name,
    )
    if future_subscriptions.exists():
        end_date = future_subscriptions.latest('date_start').date_start
    else:
        end_date = None

    return Subscription.new_domain_subscription(
        account=BillingAccount.get_or_create_account_by_domain(
            domain_name,
            created_by='assign_explicit_community_subscriptions',
            entry_point=EntryPoint.SELF_STARTED,
        )[0],
        domain=domain_name,
        plan_version=DefaultProductPlan.get_default_plan_version(),
        date_start=start_date,
        date_end=end_date,
        skip_invoicing_if_no_feature_charges=True,
        adjustment_method=SubscriptionAdjustmentMethod.TASK,
        internal_change=True,
        service_type=SubscriptionType.PRODUCT,
    )
    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()
Example #29
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()
Example #30
0
    def save(self, commit=True):
        account_save_success = super(ConfirmNewSubscriptionForm, self).save(commit=False)
        if not account_save_success:
            return False

        try:
            if self.current_subscription is not None:
                if self.plan_version.plan.edition == SoftwarePlanEdition.COMMUNITY:
                    self.current_subscription.cancel_subscription(adjustment_method=SubscriptionAdjustmentMethod.USER,
                                                                  web_user=self.creating_user)
                else:
                    subscription = self.current_subscription.change_plan(
                        self.plan_version, web_user=self.creating_user, adjustment_method=SubscriptionAdjustmentMethod.USER
                    )
                    subscription.is_active = True
                    subscription.save()
            else:
                subscription = Subscription.new_domain_subscription(
                    self.account, self.domain, self.plan_version,
                    web_user=self.creating_user,
                    adjustment_method=SubscriptionAdjustmentMethod.USER)
                subscription.is_active = True
                if subscription.plan_version.plan.edition == SoftwarePlanEdition.ENTERPRISE:
                    # this point can only be reached if the initiating user was a superuser
                    subscription.do_not_invoice = True
                subscription.save()
            return True
        except Exception:
            logger.exception("There was an error subscribing the domain '%s' to plan '%s'. "
                             "Go quickly!" % (self.domain, self.plan_version.plan.name))
        return False
Example #31
0
def domain_is_on_trial(domain_name):
    from corehq.apps.accounting.models import Subscription
    subscription = Subscription.get_active_subscription_by_domain(domain_name)
    return subscription and subscription.is_trial
Example #32
0
    def setUpClass(cls):
        super().setUpClass()

        plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.ADVANCED)

        cls.blocked_account = generator.billing_account(
            '*****@*****.**', '*****@*****.**')
        cls.blocked_account.block_hubspot_data_for_all_users = True
        cls.blocked_account.save()

        # this is one domain linked to the billing account that blocks hubspot
        cls.blocked_domain = create_domain('block-domain-hubspot')
        first_blocked_sub = Subscription.new_domain_subscription(
            cls.blocked_account, cls.blocked_domain.name, plan)
        first_blocked_sub.is_active = True
        first_blocked_sub.save()

        # this is another domain linked to the billing account that blocks hubspot
        cls.second_blocked_domain = create_domain('block-domain-hubspot-002')
        second_blocked_sub = Subscription.new_domain_subscription(
            cls.blocked_account, cls.second_blocked_domain.name, plan)
        second_blocked_sub.is_active = True
        second_blocked_sub.save()

        # this domain is not linked to an account that is blocking hubspot
        cls.allowed_domain = create_domain('allow-domain-hubspot')
        allowed_account = generator.billing_account('*****@*****.**',
                                                    '*****@*****.**')
        allowed_sub = Subscription.new_domain_subscription(
            allowed_account, cls.allowed_domain.name, plan)
        allowed_sub.is_active = True
        allowed_sub.save()

        cls.allowed_user = WebUser.create(cls.allowed_domain.name,
                                          '*****@*****.**', '*****', None,
                                          None)
        cls.allowed_user.save()

        cls.blocked_user = WebUser.create(cls.blocked_domain.name,
                                          '*****@*****.**', '*****', None,
                                          None)
        cls.blocked_user.save()
        cls.blocked_couch_user = CouchUser.get_by_username(
            cls.blocked_user.username)

        cls.second_blocked_user = WebUser.create(
            cls.second_blocked_domain.name, '*****@*****.**', '*****',
            None, None)
        cls.second_blocked_user.save()
        cls.second_blocked_couch_user = CouchUser.get_by_username(
            cls.second_blocked_user.username)

        cls.blocked_invitation_user = WebUser.create(
            cls.blocked_domain.name, '*****@*****.**',
            '*****', None, None)
        invite_to_blocked_domain = Invitation(
            email=cls.blocked_invitation_user.username,
            is_accepted=True,
            domain=cls.blocked_domain.name,
            invited_on=datetime.now(),
            invited_by="*****@*****.**",
        )
        invite_to_blocked_domain.save()

        cls.blocked_commcare_user = CommCareUser.create(
            cls.blocked_domain.name, 'testuser', '****', None, None)
        cls.blocked_commcare_user.save()
Example #33
0
def is_domain_enterprise(domain):
    subscription = Subscription.get_active_subscription_by_domain(domain)
    try:
        return subscription.plan_version.plan.edition == SoftwarePlanEdition.ENTERPRISE
    except AttributeError:
        return False
Example #34
0
 def update_subscription(self, plan):
     current_subscription = Subscription.get_active_subscription_by_domain(
         self.domain)
     if current_subscription.plan_version.plan.edition != plan:
         current_subscription.change_plan(
             DefaultProductPlan.get_default_plan_version(plan))
Example #35
0
def get_subscription_info(domain):
    subscription = Subscription.get_active_subscription_by_domain(domain)
    if subscription:
        return subscription.service_type, subscription.plan_version.plan.name
    return None, None
Example #36
0
    def setUp(self):
        super(BackendTestCase, self).setUp()

        self.domain = "test-domain"
        self.domain2 = "test-domain2"

        self.site, self.site_created = self.get_or_create_site()

        self.domain_obj = Domain(name=self.domain)
        self.domain_obj.save()

        generator.instantiate_accounting_for_tests()
        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain_obj.name,
            created_by="automated-test",
        )[0]
        plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain_obj, edition=SoftwarePlanEdition.ADVANCED)
        self.subscription = Subscription.new_domain_subscription(
            self.account, self.domain_obj.name, plan)
        self.subscription.is_active = True
        self.subscription.save()
        self.domain_obj = Domain.get(
            self.domain_obj._id)  # Prevent resource conflict

        self.backend1 = TestCaseBackend(name="BACKEND1", is_global=True)
        self.backend1.save()

        self.backend2 = TestCaseBackend(name="BACKEND2", is_global=True)
        self.backend2.save()

        self.backend3 = TestCaseBackend(name="BACKEND3", is_global=True)
        self.backend3.save()

        self.backend4 = TestCaseBackend(name="BACKEND4", is_global=True)
        self.backend4.save()

        self.backend5 = TestCaseBackend(name="BACKEND5",
                                        domain=self.domain,
                                        is_global=False,
                                        authorized_domains=[])
        self.backend5.save()

        self.backend6 = TestCaseBackend(name="BACKEND6",
                                        domain=self.domain2,
                                        is_global=False,
                                        authorized_domains=[self.domain])
        self.backend6.save()

        self.backend7 = TestCaseBackend(name="BACKEND7",
                                        domain=self.domain2,
                                        is_global=False,
                                        authorized_domains=[])
        self.backend7.save()

        self.backend8 = TestCaseBackend(name="BACKEND",
                                        domain=self.domain,
                                        is_global=False,
                                        authorized_domains=[])
        self.backend8.save()

        self.backend9 = TestCaseBackend(name="BACKEND",
                                        domain=self.domain2,
                                        is_global=False,
                                        authorized_domains=[self.domain])
        self.backend9.save()

        self.backend10 = TestCaseBackend(name="BACKEND", is_global=True)
        self.backend10.save()

        self.backend_mapping1 = BackendMapping(is_global=True,
                                               prefix="*",
                                               backend_id=self.backend1._id)
        self.backend_mapping1.save()

        self.backend_mapping2 = BackendMapping(is_global=True,
                                               prefix="1",
                                               backend_id=self.backend2._id)
        self.backend_mapping2.save()

        self.backend_mapping3 = BackendMapping(is_global=True,
                                               prefix="91",
                                               backend_id=self.backend3._id)
        self.backend_mapping3.save()

        self.backend_mapping4 = BackendMapping(is_global=True,
                                               prefix="265",
                                               backend_id=self.backend4._id)
        self.backend_mapping4.save()

        self.backend_mapping5 = BackendMapping(is_global=True,
                                               prefix="256",
                                               backend_id=self.backend5._id)
        self.backend_mapping5.save()

        self.backend_mapping6 = BackendMapping(is_global=True,
                                               prefix="25670",
                                               backend_id=self.backend6._id)
        self.backend_mapping6.save()

        self.backend_mapping7 = BackendMapping(is_global=True,
                                               prefix="25675",
                                               backend_id=self.backend7._id)
        self.backend_mapping7.save()

        self.case = CommCareCase(domain=self.domain)
        self.case.set_case_property("contact_phone_number", "15551234567")
        self.case.set_case_property("contact_phone_number_is_verified", "1")
        self.case.save()

        self.contact = CommConnectCase.wrap(self.case.to_json())

        settings.SMS_LOADED_BACKENDS.append(
            "corehq.apps.sms.tests.TestCaseBackend")
Example #37
0
def domain_is_on_trial(domain):
    from corehq.apps.accounting.models import Subscription
    subscription = Subscription.get_subscribed_plan_by_domain(domain)[1]
    return subscription.is_trial
Example #38
0
 def test_non_trial_with_previous(self):
     self._run_test(Subscription(is_trial=False),
                    Subscription(is_trial=False), True)
     self._run_test(Subscription(is_trial=True),
                    Subscription(is_trial=False), True)
 def test_update_billing_account_entry_point_self_serve(self):
     self_serve_subscription = Subscription.new_domain_subscription(
         self.account, self.domain.name, self.advanced_plan,
         web_user=self.admin_user_name, service_type=SubscriptionType.PRODUCT
     )
     self.assertEqual(self_serve_subscription.account.entry_point, EntryPoint.SELF_STARTED)
 def test_regular_plan_not_added_to_customer_account(self):
     self.account.is_customer_billing_account = True
     self.assertRaises(
         NewSubscriptionError, lambda: Subscription.new_domain_subscription(
             self.account, self.domain.name, self.advanced_plan))
Example #41
0
 def _setup_accounting(cls):
     cls.account, _ = BillingAccount.get_or_create_account_by_domain(cls.domain.name, created_by='')
     plan_version = DefaultProductPlan.get_default_plan_version(SoftwarePlanEdition.STANDARD)
     cls.subscription = Subscription.new_domain_subscription(cls.account, cls.domain.name, plan_version)
Example #42
0
def request_new_domain(request, form, org, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    commtrack_enabled = domain_type == 'commtrack'

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(
        name=form.cleaned_data['domain_name'],
        is_active=False,
        date_created=datetime.utcnow(),
        commtrack_enabled=commtrack_enabled,
        creating_user=current_user.username,
        secure_submissions=True,
    )

    if form.cleaned_data.get('domain_timezone'):
        new_domain.default_timezone = form.cleaned_data['domain_timezone']

    if org:
        new_domain.organization = org
        new_domain.hr_name = request.POST.get('domain_hrname', None) or new_domain.name

    if not new_user:
        new_domain.is_active = True

    # ensure no duplicate domain documents get created on cloudant
    new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save() # we need to get the name from the _id

    # Create a 30 Day Trial subscription to the Advanced Plan
    advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain(
        new_domain, edition=SoftwarePlanEdition.ADVANCED, is_trial=True
    )
    expiration_date = date.today() + timedelta(days=30)
    trial_account = BillingAccount.objects.get_or_create(
        name="Trial Account for %s" % new_domain.name,
        currency=Currency.get_default(),
        created_by_domain=new_domain.name,
        account_type=BillingAccountType.TRIAL,
    )[0]
    trial_subscription = Subscription.new_domain_subscription(
        trial_account, new_domain.name, advanced_plan_version,
        date_end=expiration_date,
        adjustment_method=SubscriptionAdjustmentMethod.TRIAL,
        is_trial=True,
    )
    trial_subscription.is_active = True
    trial_subscription.save()

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
Example #43
0
 def test_non_trial_with_no_previous(self):
     self._run_test(None, Subscription(is_trial=False), False)
    def setUpClass(cls):
        cls.domain = initial_bootstrap(TEST_DOMAIN)
        db = get_db()
        if db.doc_exist(DOMAIN_MODULE_KEY):
            module_config = db.open_doc(DOMAIN_MODULE_KEY)
            module_map = module_config.get('module_map')
            if module_map:
                module_map[TEST_DOMAIN] = 'custom.ewsghana'
            else:
                module_config['module_map'][TEST_DOMAIN] = 'custom.ewsghana'
        else:
            module_config = db.save_doc({
                '_id': DOMAIN_MODULE_KEY,
                'module_map': {
                    'ewsghana-test-input-stock': 'custom.ewsghana'
                }
            })
        db.save_doc(module_config)
        generator.instantiate_accounting_for_tests()
        account = BillingAccount.get_or_create_account_by_domain(
            cls.domain.name,
            created_by="automated-test",
        )[0]
        plan = DefaultProductPlan.get_default_plan_by_domain(
            cls.domain, edition=SoftwarePlanEdition.ENTERPRISE)
        subscription = Subscription.new_domain_subscription(
            account, cls.domain.name, plan)
        subscription.is_active = True
        subscription.save()
        cls.endpoint = MockEndpoint('http://test-api.com/', 'dummy', 'dummy')
        cls.api_object = EWSApi(TEST_DOMAIN, cls.endpoint)
        cls.api_object.prepare_commtrack_config()
        cls.api_object.prepare_custom_fields()
        cls.datapath = os.path.join(os.path.dirname(__file__), 'data')

        with open(os.path.join(cls.datapath, 'sample_products.json')) as f:
            for p in json.loads(f.read()):
                cls.api_object.product_sync(Product(p))

        with open(os.path.join(cls.datapath, 'sample_locations.json')) as f:
            for loc in json.loads(f.read()):
                cls.api_object.location_sync(Location(loc))

        cls.test_facility3 = SQLLocation.objects.get(domain=TEST_DOMAIN,
                                                     site_code='tsactive')
        cls.testregion2 = SQLLocation.objects.get(domain=TEST_DOMAIN,
                                                  site_code='testregion2')
        cls.rsp = SQLLocation.objects.get(domain=TEST_DOMAIN, site_code='rsp')
        cls.test_district = SQLLocation.objects.get(domain=TEST_DOMAIN,
                                                    site_code='testdistrict')

        cls.username1 = 'ews_user1'
        cls.password1 = 'dummy'
        cls.web_user1 = WebUser.create(TEST_DOMAIN, cls.username1,
                                       cls.password1)

        cls.web_user1.eula.signed = True
        cls.web_user1.save()

        cls.username2 = 'ews_user2'
        cls.password2 = 'dummy'
        cls.web_user2 = WebUser.create(TEST_DOMAIN, cls.username2,
                                       cls.password2)
        cls.web_user2.get_domain_membership(
            TEST_DOMAIN).location_id = cls.test_facility3.location_id

        cls.web_user2.eula.signed = True
        cls.web_user2.save()

        cls.username3 = 'ews_user3'
        cls.password3 = 'dummy'
        cls.web_user3 = WebUser.create(TEST_DOMAIN, cls.username3,
                                       cls.password3)
        cls.web_user3.get_domain_membership(
            TEST_DOMAIN).location_id = cls.testregion2.location_id

        cls.web_user3.eula.signed = True
        cls.web_user3.save()

        cls.username4 = 'ews_user4'
        cls.password4 = 'dummy'
        cls.web_user4 = WebUser.create(TEST_DOMAIN, cls.username4,
                                       cls.password4)
        cls.web_user4.get_domain_membership(
            TEST_DOMAIN).location_id = cls.rsp.location_id

        cls.web_user4.eula.signed = True
        cls.web_user4.save()

        cls.username5 = 'ews_user5'
        cls.password5 = 'dummy'
        cls.web_user5 = WebUser.create(TEST_DOMAIN, cls.username5,
                                       cls.password5)
        domain_membership = cls.web_user5.get_domain_membership(TEST_DOMAIN)
        domain_membership.location_id = cls.test_district.location_id
        domain_membership.role_id = UserRole.get_read_only_role_by_domain(
            cls.domain.name).get_id

        cls.web_user5.eula.signed = True
        cls.web_user5.save()

        cls.ad = SQLProduct.objects.get(domain=TEST_DOMAIN, code='ad')
        cls.al = SQLProduct.objects.get(domain=TEST_DOMAIN, code='al')

        cls.client = Client()
Example #45
0
    def setUpClass(cls):
        super().setUpClass()

        cls.domain1, subscriber1 = generator.arbitrary_domain_and_subscriber()
        cls.domain2, subscriber2 = generator.arbitrary_domain_and_subscriber()
        cls.admin_web_user = generator.create_arbitrary_web_user_name()

        account = generator.billing_account(cls.admin_web_user,
                                            cls.admin_web_user)
        account.is_customer_billing_account = True
        account.save()

        enterprise_plan = SoftwarePlan.objects.create(
            name="Helping Earth INGO Enterprise Plan",
            description="Enterprise plan for Helping Earth",
            edition=SoftwarePlanEdition.ENTERPRISE,
            visibility=SoftwarePlanVisibility.INTERNAL,
            is_customer_software_plan=True,
        )

        first_product_rate = SoftwareProductRate.objects.create(
            monthly_fee=3000, name="HQ Enterprise")
        cls.first_version = SoftwarePlanVersion.objects.create(
            plan=enterprise_plan,
            role=Role.objects.first(),
            product_rate=first_product_rate)
        cls.first_version.save()

        today = datetime.date.today()
        two_months_ago = today - datetime.timedelta(days=60)
        next_month = today + datetime.timedelta(days=30)

        subscription1 = Subscription(
            account=account,
            plan_version=cls.first_version,
            subscriber=subscriber1,
            date_start=two_months_ago,
            date_end=None,
            service_type=SubscriptionType.IMPLEMENTATION,
        )
        subscription1.is_active = True
        subscription1.save()

        subscription2 = Subscription(
            account=account,
            plan_version=cls.first_version,
            subscriber=subscriber2,
            date_start=two_months_ago,
            date_end=next_month,
            service_type=SubscriptionType.IMPLEMENTATION,
        )
        subscription2.is_active = True
        subscription2.save()

        new_product_rate = SoftwareProductRate.objects.create(
            monthly_fee=5000, name="HQ Enterprise")
        cls.newest_version = SoftwarePlanVersion.objects.create(
            plan=enterprise_plan,
            role=Role.objects.first(),
            product_rate=new_product_rate)
        cls.newest_version.save()
Example #46
0
    def test_transfers(self):
        advanced_plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.ADVANCED)
        standard_plan = DefaultProductPlan.get_default_plan_version(
            edition=SoftwarePlanEdition.STANDARD)
        first_sub = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            advanced_plan,
            date_start=datetime.date.today() - relativedelta(days=1),
        )

        product_credit = CreditLine.add_credit(
            self.product_credit_amt,
            subscription=first_sub,
            is_product=True,
        )
        feature_credit = CreditLine.add_credit(
            self.feature_credit_amt,
            subscription=first_sub,
            feature_type=FeatureType.USER,
        )
        subscription_credit = CreditLine.add_credit(
            self.subscription_credit_amt,
            subscription=first_sub,
        )
        original_credits = [
            product_credit,
            feature_credit,
            subscription_credit,
        ]

        second_sub = first_sub.change_plan(standard_plan)

        second_credits = self._ensure_transfer(original_credits)
        for credit_line in second_credits:
            self.assertEqual(credit_line.subscription.pk, second_sub.pk)

        second_sub.date_end = datetime.date.today() + datetime.timedelta(
            days=5)
        second_sub.save()
        third_sub = second_sub.renew_subscription()
        deactivate_subscriptions(second_sub.date_end)
        third_sub = Subscription.visible_objects.get(id=third_sub.id)

        third_credits = self._ensure_transfer(second_credits)
        for credit_line in third_credits:
            self.assertEqual(credit_line.subscription.pk, third_sub.pk)

        third_sub.date_end = third_sub.date_start + relativedelta(days=1)
        third_sub.save()
        Subscription.new_domain_subscription(
            self.other_account,
            self.domain,
            DefaultProductPlan.get_default_plan_version(),
            date_start=third_sub.date_end,
        )
        deactivate_subscriptions(third_sub.date_end)

        account_credits = self._ensure_transfer(third_credits)
        for credit_line in account_credits:
            self.assertIsNone(credit_line.subscription)
            self.assertEqual(credit_line.account.pk, self.account.pk)
Example #47
0
    def post(self, req, *args, **kwargs):
        report = dict([(key, req.POST.get(key, '')) for key in (
            'subject',
            'username',
            'domain',
            'url',
            'message',
            'app_id',
            'cc',
            'email',
            '500traceback',
            'sentry_id',
        )])

        try:
            couch_user = req.couch_user
            full_name = couch_user.full_name
            if couch_user.is_commcare_user():
                email = report['email']
            else:
                email = couch_user.get_email()
        except Exception:
            full_name = None
            email = report['email']
        report['full_name'] = full_name
        report['email'] = email or report['username']

        if report['domain']:
            domain = report['domain']
        elif len(couch_user.domains) == 1:
            # This isn't a domain page, but the user has only one domain, so let's use that
            domain = couch_user.domains[0]
        else:
            domain = "<no domain>"

        message = ("username: {username}\n"
                   "full name: {full_name}\n"
                   "domain: {domain}\n"
                   "url: {url}\n").format(**report)

        domain_object = Domain.get_by_name(
            domain) if report['domain'] else None
        debug_context = {
            'datetime':
            datetime.utcnow(),
            'self_started':
            '<unknown>',
            'scale_backend':
            '<unknown>',
            'has_handoff_info':
            '<unknown>',
            'project_description':
            '<unknown>',
            'sentry_error':
            '{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL', ''),
                          report['sentry_id'])
        }
        if domain_object:
            current_project_description = domain_object.project_description if domain_object else None
            new_project_description = req.POST.get('project_description')
            if (domain_object and req.couch_user.is_domain_admin(domain=domain)
                    and new_project_description and
                    current_project_description != new_project_description):
                domain_object.project_description = new_project_description
                domain_object.save()

            message += (("software plan: {software_plan}\n").format(
                software_plan=Subscription.get_subscribed_plan_by_domain(
                    domain), ))

            debug_context.update({
                'self_started':
                domain_object.internal.self_started,
                'scale_backend':
                should_use_sql_backend(domain),
                'has_handoff_info':
                bool(domain_object.internal.partner_contact),
                'project_description':
                domain_object.project_description,
            })

        subject = '{subject} ({domain})'.format(subject=report['subject'],
                                                domain=domain)
        cc = [el for el in report['cc'].strip().split(",") if el]

        if full_name and not any([c in full_name for c in '<>"']):
            reply_to = '"{full_name}" <{email}>'.format(**report)
        else:
            reply_to = report['email']

        # if the person looks like a commcare user, fogbugz can't reply
        # to their email, so just use the default
        if settings.HQ_ACCOUNT_ROOT in reply_to:
            reply_to = settings.SERVER_EMAIL

        message += "Message:\n\n{message}\n".format(message=report['message'])
        if req.POST.get('five-hundred-report'):
            extra_message = (
                "This message was reported from a 500 error page! "
                "Please fix this ASAP (as if you wouldn't anyway)...")
            extra_debug_info = (
                "datetime: {datetime}\n"
                "Is self start: {self_started}\n"
                "Is scale backend: {scale_backend}\n"
                "Has Support Hand-off Info: {has_handoff_info}\n"
                "Project description: {project_description}\n"
                "Sentry Error: {sentry_error}\n").format(**debug_context)
            traceback_info = cache.cache.get(
                report['500traceback']) or 'No traceback info available'
            cache.cache.delete(report['500traceback'])
            message = "\n\n".join(
                [message, extra_debug_info, extra_message, traceback_info])

        email = EmailMessage(subject=subject,
                             body=message,
                             to=self.recipients,
                             headers={'Reply-To': reply_to},
                             cc=cc)

        uploaded_file = req.FILES.get('report_issue')
        if uploaded_file:
            filename = uploaded_file.name
            content = uploaded_file.read()
            email.attach(filename=filename, content=content)

        # only fake the from email if it's an @dimagi.com account
        is_icds_env = settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS
        if re.search(r'@dimagi\.com$', report['username']) and not is_icds_env:
            email.from_email = report['username']
        else:
            email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

        email.send(fail_silently=False)

        if req.POST.get('five-hundred-report'):
            messages.success(
                req,
                "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
            )
            return HttpResponseRedirect(reverse('homepage'))

        return HttpResponse()
Example #48
0
 def test_get_active_domains_for_account(self):
     tasks.activate_subscriptions(
         based_on_date=self.subscription.date_start)
     test_domains = ['test']
     domains = Subscription.get_active_domains_for_account(self.account)
     self.assertEqual(list(domains), test_domains)
    def handle(self, *args, **options):
        if len(args) != 1:
            print "Invalid arguments: %s" % str(args)
            return

        completed = 0
        total = 0
        filename = args[0]
        with open(filename) as f:
            reader = csv.reader(f)
            reader.next()
            for row in reader:
                total = total + 1
                domain = row[0]
                plan_version, subscription = Subscription.get_subscribed_plan_by_domain(
                    domain)
                if subscription is None:
                    print "Could not find Subscription for %s" % domain

                account = BillingAccount.get_account_by_domain(domain)
                if account is None:
                    print "Could not find BillingAccount for %s" % domain

                if account is not None and subscription is not None:
                    '''
                    service_type = self.normalize(row[1])  # self service, contracted, or not set
                    if service_type == "selfservice":
                        #print "%s service_type => SELF_SERVICE" % domain
                        subscription.service_type = SubscriptionType.SELF_SERVICE
                    elif service_type == "contracted":
                        #print "%s service_type => CONTRACTED" % domain
                        subscription.service_type = SubscriptionType.CONTRACTED
                    elif service_type == "notset":
                        #print "%s service_type => NOT_SET" % domain
                        subscription.service_type = SubscriptionType.NOT_SET
                    else:
                        pass
                        #print "Skipping service type for %s" % domain

                    entry_point = self.normalize(row[2])  # yes if self starter, might be missing
                    if entry_point == "yes":
                        #print "%s entry_point => SELF_STARTED" % domain
                        account.entry_point = EntryPoint.SELF_STARTED
                    elif entry_point == "no":
                        #print "%s entry_point => CONTRACTED" % domain
                        account.entry_point = EntryPoint.CONTRACTED
                    else:
                        #print "Skipping entry point for %s" % domain
                        pass
                    '''

                    pro_bono_status = self.normalize(row[3])  # yes/no
                    if pro_bono_status == "yes":
                        #print "%s pro_bono_status => YES" % domain
                        subscription.pro_bono_status = ProBonoStatus.YES
                    elif pro_bono_status == "discounted":
                        #print "%s pro_bono_status => DISCOUNTED" % domain
                        subscription.pro_bono_status = ProBonoStatus.DISCOUNTED
                    else:
                        #print "%s pro_bono_status => NO" % domain
                        subscription.pro_bono_status = ProBonoStatus.NO
                    '''print "setting %s's service_type=%s, entry_point=%s, pro_bono=%s" % (
                        domain, subscription.service_type, account.entry_point, subscription.pro_bono_status
                    )'''

                    subscription.save()
                    account.save()
                    completed = completed + 1

        print "Completed %i of %i domains" % (completed, total)
Example #50
0
 def options(self):
     account = BillingAccount.get_account_by_domain(self.request.domain)
     return clean_options([
         (domain, domain)
         for domain in Subscription.get_active_domains_for_account(account)
     ])
Example #51
0
def get_overdue_invoice(domain_name):
    current_subscription = Subscription.get_active_subscription_by_domain(domain_name)
    if current_subscription and is_subscription_eligible_for_downgrade_process(current_subscription):
        overdue_invoice, _ = get_oldest_unpaid_invoice_over_threshold(date.today(), domain_name)
        return overdue_invoice
 def _subscribe_to_advanced(self):
     return Subscription.new_domain_subscription(
         self.account,
         self.project.name,
         self.advanced_plan,
         web_user=self.admin_username)
Example #53
0
def get_subscription_properties_by_user(couch_user):
    def _is_paying_subscription(subscription, plan_version):
        NON_PAYING_SERVICE_TYPES = [
            SubscriptionType.TRIAL,
            SubscriptionType.EXTENDED_TRIAL,
            SubscriptionType.SANDBOX,
            SubscriptionType.INTERNAL,
        ]

        NON_PAYING_PRO_BONO_STATUSES = [
            ProBonoStatus.YES,
            ProBonoStatus.DISCOUNTED,
        ]
        return (plan_version.plan.visibility != SoftwarePlanVisibility.TRIAL
                and subscription.service_type not in NON_PAYING_SERVICE_TYPES
                and subscription.pro_bono_status
                not in NON_PAYING_PRO_BONO_STATUSES
                and plan_version.plan.edition != SoftwarePlanEdition.COMMUNITY)

    # Note: using "yes" and "no" instead of True and False because spec calls
    # for using these values. (True is just converted to "True" in KISSmetrics)
    all_subscriptions = []
    paying_subscribed_editions = []
    subscribed_editions = []
    for domain_name in couch_user.domains:
        subscription = Subscription.get_active_subscription_by_domain(
            domain_name)
        plan_version = (subscription.plan_version if subscription is not None
                        else DefaultProductPlan.get_default_plan_version())
        subscribed_editions.append(plan_version.plan.edition)
        if subscription is not None:
            all_subscriptions.append(subscription)
        if subscription is not None and _is_paying_subscription(
                subscription, plan_version):
            paying_subscribed_editions.append(plan_version.plan.edition)

    def _is_one_of_editions(edition):
        return 'yes' if edition in subscribed_editions else 'no'

    def _is_a_pro_bono_status(status):
        return 'yes' if status in [
            s.pro_bono_status for s in all_subscriptions
        ] else 'no'

    def _is_on_extended_trial():
        service_types = [s.service_type for s in all_subscriptions]
        return 'yes' if SubscriptionType.EXTENDED_TRIAL in service_types else 'no'

    def _max_edition():
        for edition in paying_subscribed_editions:
            assert edition in [e[0] for e in SoftwarePlanEdition.CHOICES]

        return max(
            paying_subscribed_editions) if paying_subscribed_editions else ''

    env = get_instance_string()

    return {
        '{}is_on_community_plan'.format(env):
        _is_one_of_editions(SoftwarePlanEdition.COMMUNITY),
        '{}is_on_standard_plan'.format(env):
        _is_one_of_editions(SoftwarePlanEdition.STANDARD),
        '{}is_on_pro_plan'.format(env):
        _is_one_of_editions(SoftwarePlanEdition.PRO),
        '{}is_on_pro_bono_plan'.format(env):
        _is_a_pro_bono_status(ProBonoStatus.YES),
        '{}is_on_discounted_plan'.format(env):
        _is_a_pro_bono_status(ProBonoStatus.DISCOUNTED),
        '{}is_on_extended_trial_plan'.format(env):
        _is_on_extended_trial(),
        '{}max_edition_of_paying_plan'.format(env):
        _max_edition()
    }
Example #54
0
 def plan_name(self):
     plan_version, _ = Subscription.get_subscribed_plan_by_domain(
         self.domain)
     return plan_version.plan.name