Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
billing: Downgrade realm at the end of free trial.
Aman Agrawalfe1a40279c2e
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.pyindex ed3423b98c0..3f23cecd22f 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -1047,7 +1047,10 @@ class BillingSession(ABC):assert last_ledger_renewal is not Nonelast_renewal = last_ledger_renewal.event_time- if plan.is_free_trial():+ if plan.status in (+ CustomerPlan.FREE_TRIAL,+ CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL,+ ):assert plan.next_invoice_date is not Nonenext_billing_cycle = plan.next_invoice_dateelse:@@ -1172,6 +1175,9 @@ class BillingSession(ABC):)return new_plan, new_plan_ledger_entry+ if plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL:+ self.downgrade_now_without_creating_additional_invoices(plan)+if plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE:self.process_downgrade(plan)return None, None@@ -1190,6 +1196,9 @@ class BillingSession(ABC):plan = new_planassert plan is not None # for mypydowngrade_at_end_of_cycle = plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE+ downgrade_at_end_of_free_trial = (+ plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL+ )switch_to_annual_at_end_of_cycle = (plan.status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE)@@ -1202,7 +1211,7 @@ class BillingSession(ABC):seat_count = self.current_count_for_billed_licenses()# Should do this in JavaScript, using the user's time zone- if plan.is_free_trial():+ if plan.is_free_trial() or downgrade_at_end_of_free_trial:assert plan.next_invoice_date is not Nonerenewal_date = "{dt:%B} {dt.day}, {dt.year}".format(dt=plan.next_invoice_date)else:@@ -1252,6 +1261,7 @@ class BillingSession(ABC):"has_active_plan": True,"free_trial": plan.is_free_trial(),"downgrade_at_end_of_cycle": downgrade_at_end_of_cycle,+ "downgrade_at_end_of_free_trial": downgrade_at_end_of_free_trial,"automanage_licenses": plan.automanage_licenses,"switch_to_annual_at_end_of_cycle": switch_to_annual_at_end_of_cycle,"switch_to_monthly_at_end_of_cycle": switch_to_monthly_at_end_of_cycle,@@ -1407,8 +1417,15 @@ class BillingSession(ABC):assert plan.fixed_price is Nonedo_change_plan_status(plan, status)elif status == CustomerPlan.ENDED:+ # Not used right now on billing page but kept in case we need it.assert plan.is_free_trial()self.downgrade_now_without_creating_additional_invoices(plan=plan)+ elif status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL:+ assert plan.is_free_trial()+ do_change_plan_status(plan, status)+ elif status == CustomerPlan.FREE_TRIAL:+ assert plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL+ do_change_plan_status(plan, status)returnlicenses = update_plan_request.licensesdiff --git a/corporate/models.py b/corporate/models.pyindex 59588f6233f..b24be24992e 100644--- a/corporate/models.py+++ b/corporate/models.py@@ -267,6 +267,7 @@ class CustomerPlan(models.Model):SWITCH_TO_ANNUAL_AT_END_OF_CYCLE = 4SWITCH_PLAN_TIER_NOW = 5SWITCH_TO_MONTHLY_AT_END_OF_CYCLE = 6+ DOWNGRADE_AT_END_OF_FREE_TRIAL = 7# "Live" plans should have a value < LIVE_STATUS_THRESHOLD.# There should be at most one live plan per customer.LIVE_STATUS_THRESHOLD = 10@@ -292,6 +293,7 @@ class CustomerPlan(models.Model):self.FREE_TRIAL: "Free trial",self.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE: "Scheduled for switch to annual at end of cycle",self.SWITCH_TO_MONTHLY_AT_END_OF_CYCLE: "Scheduled for switch to monthly at end of cycle",+ self.DOWNGRADE_AT_END_OF_FREE_TRIAL: "Scheduled for downgrade at end of free trial",self.ENDED: "Ended",self.NEVER_STARTED: "Never started",}[self.status]@@ -302,7 +304,10 @@ class CustomerPlan(models.Model):return ledger_entry.licensesdef licenses_at_next_renewal(self) -> Optional[int]:- if self.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE:+ if self.status in (+ CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE,+ CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL,+ ):return Noneledger_entry = LicenseLedger.objects.filter(plan=self).order_by("id").last()assert ledger_entry is not Nonediff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 8a36bf7d3c3..421546fa82e 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -2839,7 +2839,7 @@ class StripeTest(StripeTestCase):self.assertIsNone(plan.next_invoice_date)self.assertEqual(plan.status, CustomerPlan.ENDED)- def test_downgrade_free_trial(self) -> None:+ def test_end_free_trial(self) -> None:user = self.example_user("hamlet")free_trial_end_date = self.now + timedelta(days=60)@@ -2887,6 +2887,172 @@ class StripeTest(StripeTestCase):invoice_plans_as_needed(self.next_year)mocked.assert_not_called()+ def test_downgrade_at_end_of_free_trial(self) -> None:+ user = self.example_user("hamlet")+ self.login_user(user)++ free_trial_end_date = self.now + timedelta(days=60)+ with self.settings(FREE_TRIAL_DAYS=60):+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):+ self.local_upgrade(self.seat_count, True, CustomerPlan.ANNUAL, False, True)+ plan = get_current_plan_by_realm(user.realm)+ assert plan is not None+ self.assertEqual(plan.next_invoice_date, free_trial_end_date)+ self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD)+ self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL)+ self.assertEqual(plan.licenses(), self.seat_count)+ self.assertEqual(plan.licenses_at_next_renewal(), self.seat_count)++ # Schedule downgrade+ with self.assertLogs("corporate.stripe", "INFO") as m:+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):+ response = self.client_patch(+ "/json/billing/plan",+ {"status": CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL},+ )+ stripe_customer_id = Customer.objects.get(realm=user.realm).id+ new_plan = get_current_plan_by_realm(user.realm)+ assert new_plan is not None+ expected_log = f"INFO:corporate.stripe:Change plan status: Customer.id: {stripe_customer_id}, CustomerPlan.id: {new_plan.id}, status: {CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL}"+ self.assertEqual(m.output[0], expected_log)+ self.assert_json_success(response)+ plan.refresh_from_db()+ self.assertEqual(plan.next_invoice_date, free_trial_end_date)+ self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD)+ self.assertEqual(plan.status, CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL)+ self.assertEqual(plan.licenses(), self.seat_count)+ self.assertEqual(plan.licenses_at_next_renewal(), None)++ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):+ mock_customer = Mock(email=user.delivery_email)+ mock_customer.invoice_settings.default_payment_method = Mock(+ spec=stripe.PaymentMethod, type=Mock()+ )+ with patch("corporate.lib.stripe.stripe_get_customer", return_value=mock_customer):+ response = self.client_get("/billing/")+ self.assert_in_success_response(+ [+ "Your organization will be downgraded to <strong>Zulip Cloud Free</strong> at the end of the free trial",+ "<strong>March 2, 2012</strong>",+ ],+ response,+ )++ # Verify that we still write LicenseLedger rows during the remaining+ # part of the cycle+ with patch("corporate.lib.stripe.get_latest_seat_count", return_value=20):+ update_license_ledger_if_needed(user.realm, self.now)+ self.assertEqual(+ LicenseLedger.objects.order_by("-id")+ .values_list("licenses", "licenses_at_next_renewal")+ .first(),+ (20, 20),+ )++ # Verify that we don't invoice them for the additional users during free trial.+ from stripe import Invoice++ Invoice.create = lambda **args: None # type: ignore[assignment] # cleaner than mocking+ Invoice.finalize_invoice = lambda *args: None # type: ignore[assignment] # cleaner than mocking+ with patch("stripe.InvoiceItem.create") as mocked:+ invoice_plans_as_needed(self.next_month)+ mocked.assert_not_called()++ # Check that we downgrade properly if the cycle is over+ with patch("corporate.lib.stripe.get_latest_seat_count", return_value=30):+ update_license_ledger_if_needed(user.realm, free_trial_end_date)+ plan = CustomerPlan.objects.first()+ assert plan is not None+ self.assertIsNone(plan.next_invoice_date)+ self.assertEqual(plan.status, CustomerPlan.ENDED)+ self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_LIMITED)+ self.assertEqual(+ LicenseLedger.objects.order_by("-id")+ .values_list("licenses", "licenses_at_next_renewal")+ .first(),+ (20, 20),+ )++ # Verify that we don't write LicenseLedger rows once we've downgraded+ with patch("corporate.lib.stripe.get_latest_seat_count", return_value=40):+ update_license_ledger_if_needed(user.realm, self.next_year)+ self.assertEqual(+ LicenseLedger.objects.order_by("-id")+ .values_list("licenses", "licenses_at_next_renewal")+ .first(),+ (20, 20),+ )++ self.login_user(user)+ response = self.client_get("/billing/")+ self.assertEqual(response.status_code, 302)+ self.assertEqual("/plans/", response["Location"])++ # The extra users added in the final month are not charged+ with patch("corporate.lib.stripe.invoice_plan") as mocked:+ invoice_plans_as_needed(self.next_month)+ mocked.assert_not_called()++ # The plan is not renewed after an year+ with patch("corporate.lib.stripe.invoice_plan") as mocked:+ invoice_plans_as_needed(self.next_year)+ mocked.assert_not_called()++ def test_cancel_downgrade_at_end_of_free_trial(self) -> None:+ user = self.example_user("hamlet")+ self.login_user(user)++ free_trial_end_date = self.now + timedelta(days=60)+ with self.settings(FREE_TRIAL_DAYS=60):+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):+ self.local_upgrade(self.seat_count, True, CustomerPlan.ANNUAL, False, True)+ plan = get_current_plan_by_realm(user.realm)+ assert plan is not None+ self.assertEqual(plan.next_invoice_date, free_trial_end_date)+ self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD)+ self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL)+ self.assertEqual(plan.licenses(), self.seat_count)+ self.assertEqual(plan.licenses_at_next_renewal(), self.seat_count)++ # Schedule downgrade+ with self.assertLogs("corporate.stripe", "INFO") as m:+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):+ response = self.client_patch(+ "/json/billing/plan",+ {"status": CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL},+ )+ stripe_customer_id = Customer.objects.get(realm=user.realm).id+ new_plan = get_current_plan_by_realm(user.realm)+ assert new_plan is not None+ expected_log = f"INFO:corporate.stripe:Change plan status: Customer.id: {stripe_customer_id}, CustomerPlan.id: {new_plan.id}, status: {CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL}"+ self.assertEqual(m.output[0], expected_log)+ self.assert_json_success(response)+ plan.refresh_from_db()+ self.assertEqual(plan.next_invoice_date, free_trial_end_date)+ self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD)+ self.assertEqual(plan.status, CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL)+ self.assertEqual(plan.licenses(), self.seat_count)+ self.assertEqual(plan.licenses_at_next_renewal(), None)++ # Cancel downgrade+ with self.assertLogs("corporate.stripe", "INFO") as m:+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):+ response = self.client_patch(+ "/json/billing/plan", {"status": CustomerPlan.FREE_TRIAL}+ )+ stripe_customer_id = Customer.objects.get(realm=user.realm).id+ new_plan = get_current_plan_by_realm(user.realm)+ assert new_plan is not None+ expected_log = f"INFO:corporate.stripe:Change plan status: Customer.id: {stripe_customer_id}, CustomerPlan.id: {new_plan.id}, status: {CustomerPlan.FREE_TRIAL}"+ self.assertEqual(m.output[0], expected_log)+ self.assert_json_success(response)+ plan.refresh_from_db()+ self.assertEqual(plan.next_invoice_date, free_trial_end_date)+ self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD)+ self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL)+ self.assertEqual(plan.licenses(), self.seat_count)+ self.assertEqual(plan.licenses_at_next_renewal(), self.seat_count)+def test_reupgrade_by_billing_admin_after_downgrade(self) -> None:user = self.example_user("hamlet")diff --git a/corporate/views/billing_page.py b/corporate/views/billing_page.pyindex d0aee6691ff..41bd4f70259 100644--- a/corporate/views/billing_page.py+++ b/corporate/views/billing_page.py@@ -99,6 +99,8 @@ def update_plan(CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE,CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE,CustomerPlan.SWITCH_TO_MONTHLY_AT_END_OF_CYCLE,+ CustomerPlan.FREE_TRIAL,+ CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL,CustomerPlan.ENDED,]),diff --git a/templates/corporate/billing.html b/templates/corporate/billing.htmlindex a47d6a5d649..7816ce1dbe4 100644--- a/templates/corporate/billing.html+++ b/templates/corporate/billing.html@@ -27,7 +27,7 @@<div class="input-box billing-page-field no-validation"><label for="org-current-plan" class="inline-block label-title">Your plan</label><div id="org-current-plan" class="not-editable-realm-field">- {% if free_trial %}+ {% if free_trial or downgrade_at_end_of_free_trial %}{{ plan_name }} <i>(free trial)</i>{% else %}{{ plan_name }}@@ -41,7 +41,7 @@{%if switch_to_monthly_at_end_of_cycle %}data-switch-to-monthly-eoc="true"{% endif %}{%if switch_to_annual_at_end_of_cycle %}data-switch-to-annual-eoc="true"{% endif %}><label for="org-billing-frequency">Billing frequency</label>- {% if free_trial or downgrade_at_end_of_cycle %}+ {% if free_trial or downgrade_at_end_of_free_trial or downgrade_at_end_of_cycle %}<div class="not-editable-realm-field">{{ billing_frequency }}</div>@@ -149,6 +149,10 @@Your organization will be downgraded to <strong>Zulip Cloud Free</strong> at the end of the current billingperiod (<strong>{{ renewal_date }}</strong>). You will lose access to unlimited search history and<a href="/plans/">other features</a> of your current plan.+ {% elif downgrade_at_end_of_free_trial %}+ Your organization will be downgraded to <strong>Zulip Cloud Free</strong> at the end of the free trial+ (<strong>{{ renewal_date }}</strong>). You will lose access to unlimited search history and+ <a href="/plans/">other features</a> of your current plan.{% else %}{% if charge_automatically %}Your plan will automatically renew on <strong>{{ renewal_date }}</strong>.@@ -186,17 +190,23 @@</div><div id="planchange-error" class="alert alert-danger"></div><div id="planchange-input-section">- {% if free_trial %}+ {% if free_trial and not downgrade_at_end_of_free_trial %}<div class="end-free-trial plan-toggle-action input-box billing-page-field no-validation" id="end-free-trial"><button class="end-free-trial-button plan-toggle-action-button">- <span class="billing-button-text">End free trial</span>+ <span class="billing-button-text">Cancel plan</span><object class="loader billing-button-loader" type="image/svg+xml" data="{{ static('images/loading/loader-white.svg') }}"></object></button></div>- {% elif downgrade_at_end_of_cycle %}+ {% elif downgrade_at_end_of_cycle or downgrade_at_end_of_free_trial %}<div class="reactivate-current-plan plan-toggle-action input-box billing-page-field no-validation" id="reactivate-subscription"><button class="reactivate-current-plan-button plan-toggle-action-button">- <span class="billing-button-text">Reactivate subscription</span>+ <span class="billing-button-text">+ {% if downgrade_at_end_of_free_trial %}+ Cancel downgrade+ {% else %}+ Reactivate subscription+ {% endif %}+ </span><object class="loader billing-button-loader" type="image/svg+xml" data="{{ static('images/loading/loader-white.svg') }}"></object></button></div>@@ -211,7 +221,9 @@</div><form id="planchange-form">{% if free_trial %}- <input name="status" type="hidden" value="{{ CustomerPlan.ENDED }}" />+ <input name="status" type="hidden" value="{{ CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL }}" />+ {% elif downgrade_at_end_of_free_trial %}+ <input name="status" type="hidden" value="{{ CustomerPlan.FREE_TRIAL }}" />{% elif downgrade_at_end_of_cycle %}<input name="status" type="hidden" value="{{ CustomerPlan.ACTIVE }}" />{% else %}@@ -253,13 +265,16 @@</header><main class="modal__content"><p>- Are you sure you want to end free trial and downgrade plan to <strong>Zulip Free</strong>?+ Your organization will be downgraded to <strong>Zulip Cloud Free</strong> at the end of the free trial+ ({{ renewal_date }}). You will lose access to unlimited search history and+ <a href="/plans/">other features</a>+ of your current plan. Are you sure you want to continue?</p></main><footer class="modal__footer"><button class="modal__btn dialog_exit_button" aria-label="{{ '(Close this dialog window)' }}" data-micromodal-close>{{ _('Cancel') }}</button><button class="modal__btn dialog_submit_button">- <span>{{ _('Confirm') }}</span>+ <span>{{ _('Downgrade') }}</span></button></footer></div>diff --git a/web/styles/portico/billing.css b/web/styles/portico/billing.cssindex 172d55ba97c..9987f5c9b40 100644--- a/web/styles/portico/billing.css+++ b/web/styles/portico/billing.css@@ -551,9 +551,7 @@ input[name="licenses"] {text-align: center;}-#confirm-licenses-modal-decrease,-#confirm-licenses-modal-increase,-#confirm-cancel-subscription-modal {+.micromodal {.modal__title {font-weight: 600;}