Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
remote-support: Add ability to set a required plan tier for customer.
Lauryn Menarda5f2883a757f
diff --git a/analytics/views/support.py b/analytics/views/support.pyindex b70c08d1369..2ab8b60377c 100644--- a/analytics/views/support.py+++ b/analytics/views/support.py@@ -1,4 +1,5 @@from contextlib import suppress+from dataclasses import dataclassfrom datetime import timedeltafrom decimal import Decimalfrom typing import Any, Dict, Iterable, List, Optional, Union@@ -140,6 +141,27 @@ def get_confirmations(return confirmation_dicts+@dataclass+class PlanTierOption:+ name: str+ value: int+++def get_remote_plan_tier_options() -> List[PlanTierOption]:+ remote_plan_tiers = [+ PlanTierOption("None", 0),+ PlanTierOption(+ CustomerPlan.name_from_tier(CustomerPlan.TIER_SELF_HOSTED_BASIC),+ CustomerPlan.TIER_SELF_HOSTED_BASIC,+ ),+ PlanTierOption(+ CustomerPlan.name_from_tier(CustomerPlan.TIER_SELF_HOSTED_BUSINESS),+ CustomerPlan.TIER_SELF_HOSTED_BUSINESS,+ ),+ ]+ return remote_plan_tiers++VALID_MODIFY_PLAN_METHODS = ["downgrade_at_billing_cycle_end","downgrade_now_without_additional_licenses",@@ -417,6 +439,7 @@ def remote_servers_support(remote_realm_id: Optional[int] = REQ(default=None, converter=to_non_negative_int),discount: Optional[Decimal] = REQ(default=None, converter=to_decimal),minimum_licenses: Optional[int] = REQ(default=None, converter=to_non_negative_int),+ required_plan_tier: Optional[int] = REQ(default=None, converter=to_non_negative_int),sponsorship_pending: Optional[bool] = REQ(default=None, json_validator=check_bool),approve_sponsorship: bool = REQ(default=False, json_validator=check_bool),billing_modality: Optional[str] = REQ(@@ -472,6 +495,11 @@ def remote_servers_support(support_type=SupportType.update_minimum_licenses,minimum_licenses=minimum_licenses,)+ elif required_plan_tier is not None:+ support_view_request = SupportViewRequest(+ support_type=SupportType.update_required_plan_tier,+ required_plan_tier=required_plan_tier,+ )elif billing_modality is not None:support_view_request = SupportViewRequest(support_type=SupportType.update_billing_modality,@@ -555,6 +583,7 @@ def remote_servers_support(context["format_discount"] = format_discount_percentagecontext["dollar_amount"] = cents_to_dollar_stringcontext["server_analytics_link"] = remote_installation_stats_link+ context["REMOTE_PLAN_TIERS"] = get_remote_plan_tier_options()context["SPONSORED_PLAN_TYPE"] = RemoteZulipServer.PLAN_TYPE_COMMUNITYreturn render(diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.pyindex 9cdf4da1056..f093fd18b2a 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -554,6 +554,7 @@ class SupportType(Enum):modify_plan = 5update_minimum_licenses = 6update_plan_end_date = 7+ update_required_plan_tier = 8class SupportViewRequest(TypedDict, total=False):@@ -565,6 +566,7 @@ class SupportViewRequest(TypedDict, total=False):new_plan_tier: Optional[int]minimum_licenses: Optional[int]plan_end_date: Optional[str]+ required_plan_tier: Optional[int]class AuditLogEventType(Enum):@@ -792,6 +794,10 @@ class BillingSession(ABC):) -> UpgradePageSessionTypeSpecificContext:pass+ @abstractmethod+ def check_plan_tier_is_billable(self, plan_tier: int) -> bool:+ pass+@abstractmethoddef get_type_of_plan_tier_change(self, current_plan_tier: int, new_plan_tier: int@@ -1131,6 +1137,39 @@ class BillingSession(ABC):previous_minimum_license_count = 0return f"Minimum licenses for {self.billing_entity_display_name} changed to {new_minimum_license_count} from {previous_minimum_license_count}."+ def set_required_plan_tier(self, required_plan_tier: int) -> str:+ previous_required_plan_tier = None+ new_plan_tier = None+ if required_plan_tier != 0:+ new_plan_tier = required_plan_tier+ customer = self.get_customer()++ if new_plan_tier is not None and not self.check_plan_tier_is_billable(required_plan_tier):+ raise SupportRequestError(f"Invalid plan tier for {self.billing_entity_display_name}.")++ if customer is not None:+ previous_required_plan_tier = customer.required_plan_tier+ customer.required_plan_tier = new_plan_tier+ customer.save(update_fields=["required_plan_tier"])+ else:+ customer = self.update_or_create_customer(+ defaults={"required_plan_tier": new_plan_tier}+ )++ self.write_to_audit_log(+ event_type=AuditLogEventType.CUSTOMER_PROPERTY_CHANGED,+ event_time=timezone_now(),+ extra_data={+ "old_value": previous_required_plan_tier,+ "new_value": new_plan_tier,+ "property": "required_plan_tier",+ },+ )+ plan_tier_name = "None"+ if new_plan_tier is not None:+ plan_tier_name = CustomerPlan.name_from_tier(new_plan_tier)+ return f"Required plan tier for {self.billing_entity_display_name} set to {plan_tier_name}."+def update_customer_sponsorship_status(self, sponsorship_pending: bool) -> str:customer = self.get_customer()if customer is None:@@ -2718,6 +2757,10 @@ class BillingSession(ABC):assert support_request["minimum_licenses"] is not Nonenew_minimum_license_count = support_request["minimum_licenses"]success_message = self.update_customer_minimum_licenses(new_minimum_license_count)+ elif support_type == SupportType.update_required_plan_tier:+ required_plan_tier = support_request.get("required_plan_tier")+ assert required_plan_tier is not None+ success_message = self.set_required_plan_tier(required_plan_tier)elif support_type == SupportType.update_billing_modality:assert support_request["billing_modality"] is not Noneassert support_request["billing_modality"] in VALID_BILLING_MODALITY_VALUES@@ -3239,6 +3282,16 @@ class RealmBillingSession(BillingSession):is_self_hosting=False,)+ @override+ def check_plan_tier_is_billable(self, plan_tier: int) -> bool:+ implemented_plan_tiers = [+ CustomerPlan.TIER_CLOUD_STANDARD,+ CustomerPlan.TIER_CLOUD_PLUS,+ ]+ if plan_tier in implemented_plan_tiers:+ return True+ return False+@overridedef get_type_of_plan_tier_change(self, current_plan_tier: int, new_plan_tier: int@@ -3630,6 +3683,16 @@ class RemoteRealmBillingSession(BillingSession):plan.status = CustomerPlan.ENDEDplan.save(update_fields=["status"])+ @override+ def check_plan_tier_is_billable(self, plan_tier: int) -> bool: # nocoverage+ implemented_plan_tiers = [+ CustomerPlan.TIER_SELF_HOSTED_BASIC,+ CustomerPlan.TIER_SELF_HOSTED_BUSINESS,+ ]+ if plan_tier in implemented_plan_tiers:+ return True+ return False+@overridedef get_type_of_plan_tier_change(self, current_plan_tier: int, new_plan_tier: int@@ -4044,6 +4107,16 @@ class RemoteServerBillingSession(BillingSession):is_self_hosting=True,)+ @override+ def check_plan_tier_is_billable(self, plan_tier: int) -> bool: # nocoverage+ implemented_plan_tiers = [+ CustomerPlan.TIER_SELF_HOSTED_BASIC,+ CustomerPlan.TIER_SELF_HOSTED_BUSINESS,+ ]+ if plan_tier in implemented_plan_tiers:+ return True+ return False+@overridedef get_type_of_plan_tier_change(self, current_plan_tier: int, new_plan_tier: intdiff --git a/corporate/lib/support.py b/corporate/lib/support.pyindex 5286564548c..a579678bedb 100644--- a/corporate/lib/support.py+++ b/corporate/lib/support.py@@ -49,6 +49,7 @@ class SponsorshipData:sponsorship_pending: bool = Falsedefault_discount: Optional[Decimal] = Noneminimum_licenses: Optional[int] = None+ required_plan_tier: Optional[int] = Nonelatest_sponsorship_request: Optional[SponsorshipRequestDict] = None@@ -102,6 +103,7 @@ def get_customer_sponsorship_data(customer: Customer) -> SponsorshipData:pending = customer.sponsorship_pendingdiscount = customer.default_discountlicenses = customer.minimum_licenses+ plan_tier = customer.required_plan_tiersponsorship_request = Noneif pending:last_sponsorship_request = (@@ -130,6 +132,7 @@ def get_customer_sponsorship_data(customer: Customer) -> SponsorshipData:sponsorship_pending=pending,default_discount=discount,minimum_licenses=licenses,+ required_plan_tier=plan_tier,latest_sponsorship_request=sponsorship_request,)diff --git a/corporate/models.py b/corporate/models.pyindex f4171a57f6c..13911e78f9b 100644--- a/corporate/models.py+++ b/corporate/models.py@@ -65,7 +65,7 @@ class Customer(models.Model):def get_discount_for_plan_tier(self, plan_tier: int) -> Optional[Decimal]:if self.required_plan_tier is None or self.required_plan_tier == plan_tier:return self.default_discount- return None # nocoverage+ return Nonedef get_customer_by_realm(realm: Realm) -> Optional[Customer]:diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 8ea01ca43c1..8c7b75cb15e 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -5447,6 +5447,77 @@ class TestSupportBillingHelpers(StripeTestCase):):billing_session.process_support_view_request(support_view_request)+ def test_set_required_plan_tier(self) -> None:+ valid_plan_tier = CustomerPlan.TIER_CLOUD_STANDARD+ support_view_request = SupportViewRequest(+ support_type=SupportType.update_required_plan_tier,+ required_plan_tier=valid_plan_tier,+ )+ support_admin = self.example_user("iago")+ user = self.example_user("hamlet")+ billing_session = RealmBillingSession(support_admin, realm=user.realm, support_session=True)+ customer = billing_session.get_customer()+ assert customer is None++ # Set valid plan tier - creates Customer object+ message = billing_session.process_support_view_request(support_view_request)+ self.assertEqual("Required plan tier for zulip set to Zulip Cloud Standard.", message)+ realm_audit_log = RealmAuditLog.objects.filter(+ event_type=RealmAuditLog.CUSTOMER_PROPERTY_CHANGED+ ).last()+ assert realm_audit_log is not None+ expected_extra_data = {+ "old_value": None,+ "new_value": valid_plan_tier,+ "property": "required_plan_tier",+ }+ self.assertEqual(realm_audit_log.extra_data, expected_extra_data)+ customer = billing_session.get_customer()+ assert customer is not None+ self.assertEqual(customer.required_plan_tier, valid_plan_tier)+ self.assertEqual(customer.default_discount, None)++ # Check that discount is only applied to set plan tier+ billing_session.attach_discount_to_customer(Decimal(50))+ customer.refresh_from_db()+ self.assertEqual(customer.default_discount, Decimal(50))+ discount_for_standard_plan = customer.get_discount_for_plan_tier(valid_plan_tier)+ self.assertEqual(discount_for_standard_plan, customer.default_discount)+ discount_for_plus_plan = customer.get_discount_for_plan_tier(CustomerPlan.TIER_CLOUD_PLUS)+ self.assertEqual(discount_for_plus_plan, None)++ # Try to set invalid plan tier+ invalid_plan_tier = CustomerPlan.TIER_SELF_HOSTED_BASE+ support_view_request = SupportViewRequest(+ support_type=SupportType.update_required_plan_tier,+ required_plan_tier=invalid_plan_tier,+ )+ with self.assertRaisesRegex(SupportRequestError, "Invalid plan tier for zulip."):+ billing_session.process_support_view_request(support_view_request)++ # Set plan tier to None and check that discount is applied to all plan tiers+ support_view_request = SupportViewRequest(+ support_type=SupportType.update_required_plan_tier, required_plan_tier=0+ )+ message = billing_session.process_support_view_request(support_view_request)+ self.assertEqual("Required plan tier for zulip set to None.", message)+ customer.refresh_from_db()+ self.assertIsNone(customer.required_plan_tier)+ discount_for_standard_plan = customer.get_discount_for_plan_tier(valid_plan_tier)+ self.assertEqual(discount_for_standard_plan, customer.default_discount)+ discount_for_plus_plan = customer.get_discount_for_plan_tier(CustomerPlan.TIER_CLOUD_PLUS)+ self.assertEqual(discount_for_plus_plan, customer.default_discount)+ realm_audit_log = RealmAuditLog.objects.filter(+ event_type=RealmAuditLog.CUSTOMER_PROPERTY_CHANGED+ ).last()+ assert realm_audit_log is not None+ expected_extra_data = {+ "old_value": valid_plan_tier,+ "new_value": None,+ "property": "required_plan_tier",+ }+ self.assertEqual(realm_audit_log.extra_data, expected_extra_data)+def test_approve_realm_sponsorship(self) -> None:realm = get_realm("zulip")self.assertNotEqual(realm.plan_type, Realm.PLAN_TYPE_STANDARD_FREE)diff --git a/templates/analytics/sponsorship_forms_support.html b/templates/analytics/sponsorship_forms_support.htmlindex 9f525cab037..628364e8943 100644--- a/templates/analytics/sponsorship_forms_support.html+++ b/templates/analytics/sponsorship_forms_support.html@@ -21,7 +21,9 @@{% endif %}<form method="POST" class="remote-form">- <b>Discount</b>:<br />+ <b>Discount percentage</b>:<br />+ <i>Updates will change pre-existing plans and scheduled upgrades.</i><br />+ <i>Any prorated licenses for the current billing cycle will be billed at the updated discounted rate.</i><br />{{ csrf_input }}<input type="hidden" name="{{ remote_type }}" value="{{ remote_id }}" />{% if has_fixed_price %}@@ -43,6 +45,22 @@</form>{% endif %}+<form method="POST" class="remote-form">+ <b>Required plan tier for discounts and fixed prices</b>:<br />+ <i>Updates will not change any pre-existing plans or scheduled upgrades.</i><br />+ {{ csrf_input }}+ <input type="hidden" name="{{ remote_type }}" value="{{ remote_id }}" />+ <select name="required_plan_tier">+ {% for plan_tier in REMOTE_PLAN_TIERS %}+ {% if sponsorship_data.required_plan_tier == plan_tier.value %}+ <option value="{{ plan_tier.value }}" selected>{{ plan_tier.name }}</option>+ {% else %}+ <option value="{{ plan_tier.value }}">{{ plan_tier.name }}</option>+ {% endif %}+ {% endfor %}+ </select>+ <button type="submit" class="btn btn-default support-submit-button">Update</button>+</form>{% if sponsorship_data.sponsorship_pending %}<div class="">