Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
stripe: Add billing anchor data param to process_initial_upgrade.
Lauryn Menard3c4e1803fd2a
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.pyindex e2dfe79de34..66636027aa9 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -1816,6 +1816,7 @@ class BillingSession(ABC):complimentary_access_plan: CustomerPlan | None = None,upgrade_when_complimentary_access_plan_ends: bool = False,stripe_invoice_paid: bool = False,+ adjusted_billing_cycle_anchor: datetime | None = None,) -> None:is_self_hosted_billing = not isinstance(self, RealmBillingSession)if stripe_invoice_paid:@@ -1823,12 +1824,24 @@ class BillingSession(ABC):else:customer = self.update_or_create_stripe_customer()self.ensure_current_plan_is_upgradable(customer, plan_tier)- billing_cycle_anchor = Noneif complimentary_access_plan is not None:# Customers on a complimentary access plan don't get# an additional free trial.free_trial = False++ billing_cycle_anchor = None+ # This parameter is to support situations where the plan+ # was invoiced and paid manually through Stripe vs being+ # processed through our billing system.+ if adjusted_billing_cycle_anchor is not None:+ assert stripe_invoice_paid+ # The adjusted anchor datetime should be in the past.+ assert adjusted_billing_cycle_anchor < timezone_now()+ assert not free_trial+ assert not upgrade_when_complimentary_access_plan_ends+ billing_cycle_anchor = standardize_datetime_for_stripe(adjusted_billing_cycle_anchor)+if upgrade_when_complimentary_access_plan_ends:assert complimentary_access_plan is not Noneassert complimentary_access_plan.end_date is not None@@ -4104,6 +4117,50 @@ class BillingSession(ABC):for user in admin_realm.get_human_admin_users():internal_send_private_message(sender, user, direct_message)+ def check_can_configure_prepaid_fixed_price_plan(+ self,+ plan_tier: int,+ ) -> None:+ customer = self.get_customer()+ if customer is None:+ raise BillingError("no_customer", "No Customer object for this billing entity.")++ if customer.stripe_customer_id is None:+ raise BillingError(+ "no_stripe_id", "Customer object not linked to a Stripe customer ID."+ )++ plan = get_current_plan_by_customer(customer)+ if plan is not None and plan.is_a_paid_plan():+ raise BillingError("on_paid_plan", "Customer already has an active paid plan.")++ fixed_price_plan_offer = get_configured_fixed_price_plan_offer(customer, plan_tier)+ if fixed_price_plan_offer is None:+ raise BillingError("no_plan_offer", "No CustomerPlanOffer object for this plan tier.")++ # This function should be used when a customer's plan was invoiced+ # and paid manually through Stripe by admin staff, instead of being+ # paid and processed through the billing page by the customer.+ def initialize_prepaid_fixed_price_plan(+ self,+ plan_tier: int,+ billing_cycle_anchor: datetime | None,+ ) -> None:+ self.check_can_configure_prepaid_fixed_price_plan(plan_tier)+ customer = self.get_customer()+ complimentary_access_plan = self.get_complimentary_access_plan(customer)+ self.process_initial_upgrade(+ plan_tier=plan_tier,+ licenses=0,+ automanage_licenses=True,+ billing_schedule=CustomerPlan.BILLING_SCHEDULE_ANNUAL,+ charge_automatically=False,+ free_trial=False,+ complimentary_access_plan=complimentary_access_plan,+ stripe_invoice_paid=True,+ adjusted_billing_cycle_anchor=billing_cycle_anchor,+ )+class RealmBillingSession(BillingSession):def __init__(diff --git a/corporate/management/commands/initialize_fixed_price_plan.py b/corporate/management/commands/initialize_fixed_price_plan.pynew file mode 100644index 00000000000..dfed8a1b73e--- /dev/null+++ b/corporate/management/commands/initialize_fixed_price_plan.py@@ -0,0 +1,141 @@+from typing import Any++from django.conf import settings+from django.core.management.base import CommandError, CommandParser+from typing_extensions import override++from zerver.lib.management import ZulipBaseCommand+from zerver.lib.timestamp import timestamp_to_datetime+from zerver.models.realms import Realm+from zilencer.models import RemoteRealm, RemoteZulipServer++if settings.BILLING_ENABLED:+ from corporate.lib.stripe import (+ BillingError,+ BillingSession,+ RealmBillingSession,+ RemoteRealmBillingSession,+ RemoteServerBillingSession,+ get_configured_fixed_price_plan_offer,+ )+ from corporate.models.plans import CustomerPlan+++class Command(ZulipBaseCommand):+ help = """Initialize a paid fixed-price plan for a billing customer (Realm, RemoteRealm or RemoteZulipServer)."""++ @override+ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument(+ "--plan-tier",+ dest="plan_tier",+ type=int,+ required=True,+ help="The CustomerPlan tier for the fixed-price plan.",+ )+ parser.add_argument(+ "--billing-anchor",+ dest="billing_cycle_anchor",+ type=float,+ required=False,+ help="Adjusted billing cycle anchor timestamp. Must be in the past.",+ )+ parser.add_argument(+ "--remote-server",+ dest="remote_server_uuid",+ required=False,+ help="The UUID of the registered remote Zulip server to modify.",+ )+ parser.add_argument(+ "--remote-realm",+ dest="remote_realm_uuid",+ required=False,+ help="The UUID of the remote realm to modify.",+ )+ self.add_realm_args(parser)+ parser.add_argument(+ "--dry-run",+ dest="dry_run",+ action="store_true",+ required=False,+ help="Check for errors before initializing paid fixed-price plan.",+ )++ @override+ def handle(self, *args: Any, **options: Any) -> None:+ if not settings.BILLING_ENABLED:+ raise CommandError("Billing system not enabled.")++ plan_tier = options["plan_tier"]+ if plan_tier not in CustomerPlan.PAID_PLAN_TIERS:+ raise CommandError("Invalid tier for paid plan.")++ billing_cycle_anchor = None+ if options["billing_cycle_anchor"]:+ anchor_timestamp = options["billing_cycle_anchor"]+ billing_cycle_anchor = timestamp_to_datetime(anchor_timestamp)++ realm: Realm | None = None+ remote_realm: RemoteRealm | None = None+ remote_server: RemoteZulipServer | None = None+ billing_session: BillingSession | None = None+ if options["realm_id"]:+ realm = self.get_realm(options)+ if realm is None:+ raise CommandError("No realm found.")+ billing_session = RealmBillingSession(user=None, realm=realm)+ elif options["remote_realm_uuid"]:+ remote_realm_uuid = options["remote_realm_uuid"]+ try:+ remote_realm = RemoteRealm.objects.get(uuid=remote_realm_uuid)+ billing_session = RemoteRealmBillingSession(remote_realm=remote_realm)+ except RemoteRealm.DoesNotExist:+ raise CommandError(+ "There is no remote realm with uuid '{}'. Aborting.".format(+ options["remote_realm_uuid"]+ )+ )+ elif options["remote_server_uuid"]:+ remote_server_uuid = options["remote_server_uuid"]+ try:+ remote_server = RemoteZulipServer.objects.get(uuid=remote_server_uuid)+ billing_session = RemoteServerBillingSession(remote_server=remote_server)+ except RemoteZulipServer.DoesNotExist:+ raise CommandError(+ "There is no remote server with uuid '{}'. Aborting.".format(+ options["remote_server_uuid"]+ )+ )++ if realm is None and remote_realm is None and remote_server is None:+ raise CommandError(+ "No billing entity (Realm, RemoteRealm or RemoteZulipServer) specified."+ )++ assert billing_session is not None+ if options["dry_run"]:+ try:+ billing_session.check_can_configure_prepaid_fixed_price_plan(plan_tier)+ customer = billing_session.get_customer()+ assert customer is not None+ fixed_price_plan_offer = get_configured_fixed_price_plan_offer(customer, plan_tier)+ assert fixed_price_plan_offer is not None+ anchor_date_string = (+ billing_cycle_anchor.strftime("%B %d, %Y") if billing_cycle_anchor else "today"+ )+ print(+ f"Will initialize {fixed_price_plan_offer} with anchor date of {anchor_date_string}."+ )+ return+ except BillingError as e:+ raise CommandError(e.msg)+ except AssertionError as e:+ raise CommandError(e)+ else:+ try:+ billing_session.initialize_prepaid_fixed_price_plan(plan_tier, billing_cycle_anchor)+ print("Done! Check support panel for customer to review active fixed-price plan.")+ except BillingError as e:+ raise CommandError(e.msg)+ except AssertionError as e:+ raise CommandError(e)diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 0342a192c26..8cd59354df2 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -5953,6 +5953,253 @@ class BillingHelpersTest(ZulipTestCase):],)+ def test_initialize_fixed_price_plan_realm(self) -> None:+ billing_cycle_anchor = datetime(2012, 1, 1, 1, 1, 1, tzinfo=timezone.utc)+ realm = get_realm("zulip")++ # Requires a Customer object for the billing entity.+ billing_session = RealmBillingSession(None, realm)+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_customer",+ billing_context.exception.error_description,+ )++ # Requires that the Customer object is linked to a+ # customer ID in Stripe.+ billing_session.update_or_create_customer()+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_stripe_id",+ billing_context.exception.error_description,+ )++ # Requires a fixed price plan offer to be configured+ # for the customer.+ customer = billing_session.get_customer()+ assert customer is not None+ customer.stripe_customer_id = "cus_123"+ customer.save(update_fields=["stripe_customer_id"])+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_plan_offer",+ billing_context.exception.error_description,+ )++ billing_session.set_required_plan_tier(CustomerPlan.TIER_CLOUD_STANDARD)+ billing_session.configure_fixed_price_plan(1000, None)+ self.assertEqual(realm.plan_type, Realm.PLAN_TYPE_SELF_HOSTED)+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(realm.plan_type, Realm.PLAN_TYPE_STANDARD)+ plan = CustomerPlan.objects.first()+ assert plan is not None+ self.assertEqual(plan.fixed_price, 100000)+ self.assertEqual(plan.billing_cycle_anchor, billing_cycle_anchor)+ license_ledger = LicenseLedger.objects.filter(plan=plan, is_renewal=True).last()+ assert license_ledger is not None+ self.assertEqual(license_ledger.event_time, billing_cycle_anchor)++ # Confirm that if there is an active paid plan for the+ # customer, a new plan can not be initialized.+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "on_paid_plan",+ billing_context.exception.error_description,+ )++ def test_initialize_fixed_price_plan_remote_realm(self) -> None:+ billing_cycle_anchor = datetime(2012, 1, 1, 1, 1, 1, tzinfo=timezone.utc)+ server_uuid = str(uuid.uuid4())+ remote_server = RemoteZulipServer.objects.create(+ uuid=server_uuid,+ api_key="magic_secret_api_key",+ hostname="demo.example.com",+ contact_email="[email protected]",+ )+ realm_uuid = str(uuid.uuid4())+ remote_realm = RemoteRealm.objects.create(+ server=remote_server,+ uuid=realm_uuid,+ uuid_owner_secret="dummy-owner-secret",+ host="dummy-hostname",+ realm_date_created=timezone_now(),+ )++ # Requires a Customer object for the billing entity.+ billing_session = RemoteRealmBillingSession(remote_realm)+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_SELF_HOSTED_BASIC,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_customer",+ billing_context.exception.error_description,+ )++ # Requires that the Customer object is linked to a+ # customer ID in Stripe.+ billing_session.update_or_create_customer()+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_stripe_id",+ billing_context.exception.error_description,+ )++ # Requires a fixed price plan offer to be configured+ # for the customer.+ customer = billing_session.get_customer()+ assert customer is not None+ customer.stripe_customer_id = "cus_123"+ customer.save(update_fields=["stripe_customer_id"])+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_plan_offer",+ billing_context.exception.error_description,+ )++ billing_session.set_required_plan_tier(CustomerPlan.TIER_SELF_HOSTED_BASIC)+ billing_session.configure_fixed_price_plan(1200, None)+ self.assertEqual(remote_realm.plan_type, RemoteRealm.PLAN_TYPE_SELF_MANAGED)+ with mock.patch(+ "corporate.lib.stripe.RemoteRealmBillingSession.current_count_for_billed_licenses",+ return_value=60,+ ):+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_SELF_HOSTED_BASIC,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(remote_realm.plan_type, RemoteRealm.PLAN_TYPE_BASIC)+ plan = CustomerPlan.objects.first()+ assert plan is not None+ self.assertEqual(plan.fixed_price, 120000)+ self.assertEqual(plan.billing_cycle_anchor, billing_cycle_anchor)+ license_ledger = LicenseLedger.objects.filter(plan=plan, is_renewal=True).last()+ assert license_ledger is not None+ self.assertEqual(license_ledger.event_time, billing_cycle_anchor)++ # Confirm that if there is an active paid plan for the+ # customer, a new plan can not be initialized.+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "on_paid_plan",+ billing_context.exception.error_description,+ )++ def test_initialize_fixed_price_plan_remote_server(self) -> None:+ billing_cycle_anchor = datetime(2012, 1, 1, 1, 1, 1, tzinfo=timezone.utc)+ server_uuid = str(uuid.uuid4())+ remote_server = RemoteZulipServer.objects.create(+ uuid=server_uuid,+ api_key="magic_secret_api_key",+ hostname="demo.example.com",+ contact_email="[email protected]",+ )++ # Requires a Customer object for the billing entity.+ billing_session = RemoteServerBillingSession(remote_server)+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_SELF_HOSTED_BASIC,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_customer",+ billing_context.exception.error_description,+ )++ # Requires that the Customer object is linked to a+ # customer ID in Stripe.+ billing_session.update_or_create_customer()+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_stripe_id",+ billing_context.exception.error_description,+ )++ # Requires a fixed price plan offer to be configured+ # for the customer.+ customer = billing_session.get_customer()+ assert customer is not None+ customer.stripe_customer_id = "cus_123"+ customer.save(update_fields=["stripe_customer_id"])+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "no_plan_offer",+ billing_context.exception.error_description,+ )++ billing_session.set_required_plan_tier(CustomerPlan.TIER_SELF_HOSTED_BASIC)+ billing_session.configure_fixed_price_plan(1200, None)+ self.assertEqual(remote_server.plan_type, RemoteRealm.PLAN_TYPE_SELF_MANAGED)+ with mock.patch(+ "corporate.lib.stripe.RemoteServerBillingSession.current_count_for_billed_licenses",+ return_value=60,+ ):+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_SELF_HOSTED_BASIC,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(remote_server.plan_type, RemoteRealm.PLAN_TYPE_BASIC)+ plan = CustomerPlan.objects.first()+ assert plan is not None+ self.assertEqual(plan.fixed_price, 120000)+ self.assertEqual(plan.billing_cycle_anchor, billing_cycle_anchor)+ license_ledger = LicenseLedger.objects.filter(plan=plan, is_renewal=True).last()+ assert license_ledger is not None+ self.assertEqual(license_ledger.event_time, billing_cycle_anchor)++ # Confirm that if there is an active paid plan for the+ # customer, a new plan can not be initialized.+ with self.assertRaises(BillingError) as billing_context:+ billing_session.initialize_prepaid_fixed_price_plan(+ plan_tier=CustomerPlan.TIER_CLOUD_STANDARD,+ billing_cycle_anchor=billing_cycle_anchor,+ )+ self.assertEqual(+ "on_paid_plan",+ billing_context.exception.error_description,+ )+class LicenseLedgerTest(StripeTestCase):def test_add_plan_renewal_if_needed(self) -> None: