Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
billing: Add UniqueConstraint for plan offers and never-started plans.
Lauryn Menard249625685845
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.pyindex fd20a7bd8f2..bfc9b338ceb 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -17,7 +17,7 @@ from django import formsfrom django.conf import settingsfrom django.core import signingfrom django.core.signing import Signer-from django.db import transaction+from django.db import IntegrityError, transactionfrom django.http import HttpRequest, HttpResponsefrom django.shortcuts import renderfrom django.urls import reverse@@ -1632,28 +1632,40 @@ class BillingSession(ABC):f"New plan for {self.billing_entity_display_name} cannot be scheduled until all the invoices of the current plan are processed.")- self.create_customer_plan(- customer=customer,- tier=customer.required_plan_tier,- anchor_date=current_plan.end_date,- billing_schedule=current_plan.billing_schedule,- charge_automatically=current_plan.charge_automatically,- # Manual license management is not available for fixed-price plans.- automanage_licenses=True,- next_invoice_date=current_plan.end_date,- status=CustomerPlan.NEVER_STARTED,- invoicing_status=CustomerPlan.INVOICING_STATUS_INITIAL_INVOICE_TO_BE_SENT,- fixed_price=fixed_price_cents,- price_per_license=None,- end_date=add_months(- current_plan.end_date, CustomerPlan.FIXED_PRICE_PLAN_DURATION_MONTHS- ),- )+ with transaction.atomic(durable=True):+ try:+ # There is a unique constraint on the database so that each Customer+ # can only be associated with one CustomerPlan with a status of+ # NEVER_STARTED at a time, so we try to create the plan before+ # making any updates to the current plan.+ self.create_customer_plan(+ customer=customer,+ tier=customer.required_plan_tier,+ anchor_date=current_plan.end_date,+ billing_schedule=current_plan.billing_schedule,+ charge_automatically=current_plan.charge_automatically,+ # Manual license management is not available for fixed-price plans.+ automanage_licenses=True,+ next_invoice_date=current_plan.end_date,+ status=CustomerPlan.NEVER_STARTED,+ invoicing_status=CustomerPlan.INVOICING_STATUS_INITIAL_INVOICE_TO_BE_SENT,+ fixed_price=fixed_price_cents,+ price_per_license=None,+ end_date=add_months(+ current_plan.end_date, CustomerPlan.FIXED_PRICE_PLAN_DURATION_MONTHS+ ),+ )- current_plan.status = CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END- current_plan.next_invoice_date = current_plan.end_date- current_plan.save(update_fields=["status", "next_invoice_date"])- return f"Fixed price {required_plan_tier_name} plan scheduled to start on {current_plan.end_date.date()}."+ current_plan.status = CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END+ current_plan.next_invoice_date = current_plan.end_date+ current_plan.save(update_fields=["status", "next_invoice_date"])+ return f"Fixed price {required_plan_tier_name} plan scheduled to start on {current_plan.end_date.date()}."+ except IntegrityError:+ raise SupportRequestError(+ "Customer already has a fixed-price plan renewal scheduled."+ )+ except Exception as e: # nocoverage+ raise SupportRequestError(str(e))# TODO: Use normal 'pay by invoice' flow for fixed-price plan offers,# which requires handling automated license management for these plan@@ -1682,27 +1694,40 @@ class BillingSession(ABC):except Exception as e:raise SupportRequestError(str(e))- if customer.stripe_customer_id is None:- # Note this is an exception to our normal support panel actions,- # which do not set any stripe billing information. Since these- # invoices are manually created first in stripe, it's important- # for our billing page to have our Customer object correctly- # linked to the customer in stripe.- self.link_stripe_customer_id(str(invoice_customer_id))-- Invoice.objects.create(- customer=customer,- stripe_invoice_id=sent_invoice_id,- status=Invoice.SENT,- )+ with transaction.atomic(durable=True):+ try:+ # There is a unique constraint on the database so that each Customer+ # can only be associated with one CustomerPlanOffer with a status of+ # CONFIGURED at a time, so we try to create the plan offer before+ # making any other database and Stripe updates.+ self.create_customer_plan_offer(+ customer=customer,+ fixed_price=fixed_price_cents,+ tier=customer.required_plan_tier,+ sent_invoice_id=sent_invoice_id,+ )- self.create_customer_plan_offer(- customer=customer,- fixed_price=fixed_price_cents,- tier=customer.required_plan_tier,- sent_invoice_id=sent_invoice_id,- )- return f"Customer can now buy a fixed price {required_plan_tier_name} plan."+ if sent_invoice_id is not None:+ if customer.stripe_customer_id is None:+ # Note this is an exception to our normal support panel actions,+ # which do not set any stripe billing information. Since these+ # invoices are manually created first in stripe, it's important+ # for our billing page to have our Customer object correctly+ # linked to the customer in stripe.+ self.link_stripe_customer_id(str(invoice_customer_id))++ Invoice.objects.create(+ customer=customer,+ stripe_invoice_id=sent_invoice_id,+ status=Invoice.SENT,+ )+ return f"Customer can now buy a fixed price {required_plan_tier_name} plan."+ except IntegrityError:+ raise SupportRequestError(+ "Customer already has a configured fixed-price plan offer."+ )+ except Exception as e: # nocoverage+ raise SupportRequestError(str(e))def delete_fixed_price_plan(self) -> str:customer = self.get_customer()diff --git a/corporate/migrations/0047_customerplan_unique_never_started_plan_customer_and_more.py b/corporate/migrations/0047_customerplan_unique_never_started_plan_customer_and_more.pynew file mode 100644index 00000000000..78905d7d7ce--- /dev/null+++ b/corporate/migrations/0047_customerplan_unique_never_started_plan_customer_and_more.py@@ -0,0 +1,33 @@+# Generated by Django 5.2.14 on 2026-05-19 13:59++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("corporate", "0046_rename_customerplan_invoice_overdue_email_sent"),+ ]++ # CustomerPlanOffer and CustomerPlan status field values+ # that we are setting to be unique for each Customer.+ CONFIGURED = 1+ NEVER_STARTED = 12++ operations = [+ migrations.AddConstraint(+ model_name="customerplan",+ constraint=models.UniqueConstraint(+ condition=models.Q(("status", NEVER_STARTED)),+ fields=("customer",),+ name="unique_never_started_plan_customer",+ ),+ ),+ migrations.AddConstraint(+ model_name="customerplanoffer",+ constraint=models.UniqueConstraint(+ condition=models.Q(("status", CONFIGURED)),+ fields=("customer",),+ name="unique_configured_plan_offer_customer",+ ),+ ),+ ]diff --git a/corporate/models/plans.py b/corporate/models/plans.pyindex dad39b21d3d..45bcf809628 100644--- a/corporate/models/plans.py+++ b/corporate/models/plans.py@@ -1,5 +1,5 @@from django.db import models-from django.db.models import CASCADE+from django.db.models import CASCADE, Qfrom typing_extensions import overridefrom corporate.models.customers import Customer, get_customer_by_realm@@ -45,6 +45,16 @@ class CustomerPlanOffer(AbstractCustomerPlan):# ID of invoice sent when chose to 'Pay by invoice'.sent_invoice_id = models.CharField(max_length=255, null=True)+ class Meta:+ # Enforce that each customer has only one CONFIGURED plan offer at a time.+ constraints = [+ models.UniqueConstraint(+ fields=["customer"],+ condition=Q(status=1), # CustomerPlanOffer.CONFIGURED+ name="unique_configured_plan_offer_customer",+ )+ ]+@overridedef __str__(self) -> str:return f"{self.name} for {self.customer!r} (status: {self.get_plan_status_as_text()})"@@ -185,6 +195,16 @@ class CustomerPlan(AbstractCustomerPlan):# TODO maybe override setattr to ensure billing_cycle_anchor, etc# are immutable.+ class Meta:+ # Enforce that each customer has only one NEVER_STARTED plan at a time.+ constraints = [+ models.UniqueConstraint(+ fields=["customer"],+ condition=Q(status=12), # CustomerPlan.NEVER_STARTED+ name="unique_never_started_plan_customer",+ )+ ]+@overridedef __str__(self) -> str:return f"{self.name} for {self.customer!r} (status: {self.get_plan_status_as_text()})"diff --git a/corporate/tests/test_support_views.py b/corporate/tests/test_support_views.pyindex 2c4be9cc3e5..d3d8ee20018 100644--- a/corporate/tests/test_support_views.py+++ b/corporate/tests/test_support_views.py@@ -1658,6 +1658,19 @@ class TestSupportEndpoint(ZulipTestCase):self.assertEqual(plan_offer.fixed_price, 36000)self.assertIsNone(plan_offer.sent_invoice_id)+ # Trying to schedule a second fixed-price plan renewal fails.+ result = self.client_post(+ "/activity/support", {"realm_id": f"{lear_realm.id}", "fixed_price": 500}+ )+ self.assert_in_success_response(+ ["Customer already has a configured fixed-price plan offer."],+ result,+ )+ customer.refresh_from_db()+ plan_offer = get_configured_fixed_price_plan_offer(customer, customer.required_plan_tier)+ assert plan_offer is not None+ self.assertEqual(plan_offer.fixed_price, 36000)+# Test deleting the fixed-price plan offer via support.result = self.client_post("/activity/support",@@ -1816,6 +1829,19 @@ class TestSupportEndpoint(ZulipTestCase):self.assertEqual(next_plan.charge_automatically, plan.charge_automatically)self.assertTrue(next_plan.automanage_licenses)+ # Trying to schedule a second fixed-price plan renewal fails.+ result = self.client_post(+ "/activity/support", {"realm_id": f"{lear_realm.id}", "fixed_price": 500}+ )+ self.assert_in_success_response(+ ["Customer already has a fixed-price plan renewal scheduled."],+ result,+ )+ plan.refresh_from_db()+ next_plan = billing_session.get_next_plan(plan)+ assert next_plan is not None+ self.assertEqual(next_plan.fixed_price, 36000)+# Test deleting the fixed-price next plan via support.with (self.assertLogs("corporate.stripe", "INFO") as m,