Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
corporate: Move invoice_plan to BillingSession abstract class.
Lauryn Menard4eea4d471792
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.pyindex ec810179bb2..28a741f26d2 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -467,6 +467,12 @@ def stripe_get_customer(stripe_customer_id: str) -> stripe.Customer:)+class PriceArgs(TypedDict, total=False):+ amount: int+ unit_amount: int+ quantity: int++@dataclassclass StripeCustomerData:description: str@@ -1674,6 +1680,115 @@ class BillingSession(ABC):licenses_at_next_renewal=licenses_for_new_plan,)+ def invoice_plan(self, plan: CustomerPlan, event_time: datetime) -> None:+ if plan.invoicing_status == CustomerPlan.INVOICING_STATUS_STARTED:+ raise NotImplementedError(+ "Plan with invoicing_status==STARTED needs manual resolution."+ )+ if not plan.customer.stripe_customer_id:+ raise BillingError(+ f"Customer has a paid plan without a Stripe customer ID: {plan.customer!s}"+ )++ # Updating a CustomerPlan with a status to switch the plan tier,+ # is done via switch_plan_tier, so we do not need to make end of+ # cycle updates for that case.+ if plan.status is not CustomerPlan.SWITCH_PLAN_TIER_NOW:+ self.make_end_of_cycle_updates_if_needed(plan, event_time)++ if plan.invoicing_status == CustomerPlan.INVOICING_STATUS_INITIAL_INVOICE_TO_BE_SENT:+ invoiced_through_id = -1+ licenses_base = None+ else:+ assert plan.invoiced_through is not None+ licenses_base = plan.invoiced_through.licenses+ invoiced_through_id = plan.invoiced_through.id++ invoice_item_created = False+ for ledger_entry in LicenseLedger.objects.filter(+ plan=plan, id__gt=invoiced_through_id, event_time__lte=event_time+ ).order_by("id"):+ price_args: PriceArgs = {}+ if ledger_entry.is_renewal:+ if plan.fixed_price is not None:+ price_args = {"amount": plan.fixed_price}+ else:+ assert plan.price_per_license is not None # needed for mypy+ price_args = {+ "unit_amount": plan.price_per_license,+ "quantity": ledger_entry.licenses,+ }+ description = f"{plan.name} - renewal"+ elif licenses_base is not None and ledger_entry.licenses != licenses_base:+ assert plan.price_per_license+ last_ledger_entry_renewal = (+ LicenseLedger.objects.filter(+ plan=plan, is_renewal=True, event_time__lte=ledger_entry.event_time+ )+ .order_by("-id")+ .first()+ )+ assert last_ledger_entry_renewal is not None+ last_renewal = last_ledger_entry_renewal.event_time+ billing_period_end = start_of_next_billing_cycle(plan, ledger_entry.event_time)+ plan_renewal_or_end_date = get_plan_renewal_or_end_date(+ plan, ledger_entry.event_time+ )+ proration_fraction = (plan_renewal_or_end_date - ledger_entry.event_time) / (+ billing_period_end - last_renewal+ )+ price_args = {+ "unit_amount": int(plan.price_per_license * proration_fraction + 0.5),+ "quantity": ledger_entry.licenses - licenses_base,+ }+ description = "Additional license ({} - {})".format(+ ledger_entry.event_time.strftime("%b %-d, %Y"),+ plan_renewal_or_end_date.strftime("%b %-d, %Y"),+ )++ if price_args:+ plan.invoiced_through = ledger_entry+ plan.invoicing_status = CustomerPlan.INVOICING_STATUS_STARTED+ plan.save(update_fields=["invoicing_status", "invoiced_through"])+ stripe.InvoiceItem.create(+ currency="usd",+ customer=plan.customer.stripe_customer_id,+ description=description,+ discountable=False,+ period={+ "start": datetime_to_timestamp(ledger_entry.event_time),+ "end": datetime_to_timestamp(+ get_plan_renewal_or_end_date(plan, ledger_entry.event_time)+ ),+ },+ idempotency_key=get_idempotency_key(ledger_entry),+ **price_args,+ )+ invoice_item_created = True+ plan.invoiced_through = ledger_entry+ plan.invoicing_status = CustomerPlan.INVOICING_STATUS_DONE+ plan.save(update_fields=["invoicing_status", "invoiced_through"])+ licenses_base = ledger_entry.licenses++ if invoice_item_created:+ if plan.charge_automatically:+ collection_method = "charge_automatically"+ days_until_due = None+ else:+ collection_method = "send_invoice"+ days_until_due = DEFAULT_INVOICE_DAYS_UNTIL_DUE+ stripe_invoice = stripe.Invoice.create(+ auto_advance=True,+ collection_method=collection_method,+ customer=plan.customer.stripe_customer_id,+ days_until_due=days_until_due,+ statement_descriptor=plan.name,+ )+ stripe.Invoice.finalize_invoice(stripe_invoice)++ plan.next_invoice_date = next_invoice_date(plan)+ plan.save(update_fields=["next_invoice_date"])+def do_change_plan_to_new_tier(self, new_plan_tier: int) -> None:customer = self.get_customer()assert customer is not None@@ -1706,10 +1821,10 @@ class BillingSession(ABC):description="Credit from early termination of active plan",)self.switch_plan_tier(current_plan, new_plan_tier)- invoice_plan(current_plan, plan_switch_time)+ self.invoice_plan(current_plan, plan_switch_time)new_plan = get_current_plan_by_customer(customer)assert new_plan is not None # for mypy- invoice_plan(new_plan, plan_switch_time)+ self.invoice_plan(new_plan, plan_switch_time)def get_event_status(self, event_status_request: EventStatusRequest) -> Dict[str, Any]:customer = self.get_customer()@@ -2832,127 +2947,13 @@ def get_plan_renewal_or_end_date(plan: CustomerPlan, event_time: datetime) -> dareturn billing_period_end-class PriceArgs(TypedDict, total=False):- amount: int- unit_amount: int- quantity: int---def invoice_plan(plan: CustomerPlan, event_time: datetime) -> None:- if plan.invoicing_status == CustomerPlan.INVOICING_STATUS_STARTED:- raise NotImplementedError("Plan with invoicing_status==STARTED needs manual resolution.")- if not plan.customer.stripe_customer_id:- assert plan.customer.realm is not None- raise BillingError(- f"Realm {plan.customer.realm.string_id} has a paid plan without a Stripe customer."- )-- realm = plan.customer.realm- billing_session = RealmBillingSession(user=None, realm=realm)-- # Updating a CustomerPlan with a status to switch the plan tier,- # is done via switch_plan_tier, so we do not need to make end of- # cycle updates for that case.- if plan.status is not CustomerPlan.SWITCH_PLAN_TIER_NOW:- billing_session.make_end_of_cycle_updates_if_needed(plan, event_time)-- if plan.invoicing_status == CustomerPlan.INVOICING_STATUS_INITIAL_INVOICE_TO_BE_SENT:- invoiced_through_id = -1- licenses_base = None- else:- assert plan.invoiced_through is not None- licenses_base = plan.invoiced_through.licenses- invoiced_through_id = plan.invoiced_through.id-- invoice_item_created = False- for ledger_entry in LicenseLedger.objects.filter(- plan=plan, id__gt=invoiced_through_id, event_time__lte=event_time- ).order_by("id"):- price_args: PriceArgs = {}- if ledger_entry.is_renewal:- if plan.fixed_price is not None:- price_args = {"amount": plan.fixed_price}- else:- assert plan.price_per_license is not None # needed for mypy- price_args = {- "unit_amount": plan.price_per_license,- "quantity": ledger_entry.licenses,- }- description = f"{plan.name} - renewal"- elif licenses_base is not None and ledger_entry.licenses != licenses_base:- assert plan.price_per_license- last_ledger_entry_renewal = (- LicenseLedger.objects.filter(- plan=plan, is_renewal=True, event_time__lte=ledger_entry.event_time- )- .order_by("-id")- .first()- )- assert last_ledger_entry_renewal is not None- last_renewal = last_ledger_entry_renewal.event_time- billing_period_end = start_of_next_billing_cycle(plan, ledger_entry.event_time)- plan_renewal_or_end_date = get_plan_renewal_or_end_date(plan, ledger_entry.event_time)- proration_fraction = (plan_renewal_or_end_date - ledger_entry.event_time) / (- billing_period_end - last_renewal- )- price_args = {- "unit_amount": int(plan.price_per_license * proration_fraction + 0.5),- "quantity": ledger_entry.licenses - licenses_base,- }- description = "Additional license ({} - {})".format(- ledger_entry.event_time.strftime("%b %-d, %Y"),- plan_renewal_or_end_date.strftime("%b %-d, %Y"),- )-- if price_args:- plan.invoiced_through = ledger_entry- plan.invoicing_status = CustomerPlan.INVOICING_STATUS_STARTED- plan.save(update_fields=["invoicing_status", "invoiced_through"])- stripe.InvoiceItem.create(- currency="usd",- customer=plan.customer.stripe_customer_id,- description=description,- discountable=False,- period={- "start": datetime_to_timestamp(ledger_entry.event_time),- "end": datetime_to_timestamp(- get_plan_renewal_or_end_date(plan, ledger_entry.event_time)- ),- },- idempotency_key=get_idempotency_key(ledger_entry),- **price_args,- )- invoice_item_created = True- plan.invoiced_through = ledger_entry- plan.invoicing_status = CustomerPlan.INVOICING_STATUS_DONE- plan.save(update_fields=["invoicing_status", "invoiced_through"])- licenses_base = ledger_entry.licenses-- if invoice_item_created:- if plan.charge_automatically:- collection_method = "charge_automatically"- days_until_due = None- else:- collection_method = "send_invoice"- days_until_due = DEFAULT_INVOICE_DAYS_UNTIL_DUE- stripe_invoice = stripe.Invoice.create(- auto_advance=True,- collection_method=collection_method,- customer=plan.customer.stripe_customer_id,- days_until_due=days_until_due,- statement_descriptor=plan.name,- )- stripe.Invoice.finalize_invoice(stripe_invoice)-- plan.next_invoice_date = next_invoice_date(plan)- plan.save(update_fields=["next_invoice_date"])--def invoice_plans_as_needed(event_time: Optional[datetime] = None) -> None:if event_time is None: # nocoverageevent_time = timezone_now()+ # TODO: Add RemoteRealmBillingSession and RemoteServerBillingSession cases.for plan in CustomerPlan.objects.filter(next_invoice_date__lte=event_time):- invoice_plan(plan, event_time)+ if plan.customer.realm is not None:+ RealmBillingSession(realm=plan.customer.realm).invoice_plan(plan, event_time)def is_realm_on_free_trial(realm: Realm) -> bool:diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 13408a66824..baf757c83b1 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -60,7 +60,6 @@ from corporate.lib.stripe import (get_latest_seat_count,get_plan_renewal_or_end_date,get_price_per_license,- invoice_plan,invoice_plans_as_needed,is_free_trial_offer_enabled,is_realm_on_free_trial,@@ -1349,7 +1348,7 @@ class StripeTest(StripeTestCase):]:self.assert_in_response(substring, response)- with patch("corporate.lib.stripe.invoice_plan") as mocked:+ with patch("corporate.lib.stripe.BillingSession.invoice_plan") as mocked:invoice_plans_as_needed(self.next_month)mocked.assert_not_called()mocked.reset_mock()@@ -2596,7 +2595,7 @@ class StripeTest(StripeTestCase):for key, value in annual_plan_invoice_item_params.items():self.assertEqual(invoice_item[key], value)- with patch("corporate.lib.stripe.invoice_plan") as m:+ with patch("corporate.lib.stripe.BillingSession.invoice_plan") as m:invoice_plans_as_needed(add_months(self.now, 2))m.assert_not_called()@@ -3018,12 +3017,12 @@ class StripeTest(StripeTestCase):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:+ with patch("corporate.lib.stripe.BillingSession.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:+ with patch("corporate.lib.stripe.BillingSession.invoice_plan") as mocked:invoice_plans_as_needed(self.next_year)mocked.assert_not_called()@@ -3128,12 +3127,12 @@ class StripeTest(StripeTestCase):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:+ with patch("corporate.lib.stripe.BillingSession.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:+ with patch("corporate.lib.stripe.BillingSession.invoice_plan") as mocked:invoice_plans_as_needed(self.next_year)mocked.assert_not_called()@@ -3567,12 +3566,12 @@ class StripeTest(StripeTestCase):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:+ with patch("corporate.lib.stripe.BillingSession.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:+ with patch("corporate.lib.stripe.BillingSession.invoice_plan") as mocked:invoice_plans_as_needed(self.next_year)mocked.assert_not_called()@@ -4830,27 +4829,32 @@ class LicenseLedgerTest(StripeTestCase):class InvoiceTest(StripeTestCase):def test_invoicing_status_is_started(self) -> None:+ # local_upgrade uses hamlet as user, therefore realm is zulip.self.local_upgrade(self.seat_count, True, CustomerPlan.BILLING_SCHEDULE_ANNUAL, True, False)plan = CustomerPlan.objects.first()assert plan is not Noneplan.invoicing_status = CustomerPlan.INVOICING_STATUS_STARTEDplan.save(update_fields=["invoicing_status"])with self.assertRaises(NotImplementedError):- invoice_plan(assert_is_not_none(CustomerPlan.objects.first()), self.now)+ billing_session = RealmBillingSession(realm=get_realm("zulip"))+ billing_session.invoice_plan(assert_is_not_none(CustomerPlan.objects.first()), self.now)def test_invoice_plan_without_stripe_customer(self) -> None:+ # local_upgrade uses hamlet as user, therefore realm is zulip.+ realm = get_realm("zulip")self.local_upgrade(self.seat_count, True, CustomerPlan.BILLING_SCHEDULE_ANNUAL, False, False)- plan = get_current_plan_by_realm(get_realm("zulip"))+ plan = get_current_plan_by_realm(realm)assert plan is not Noneplan.customer.stripe_customer_id = Noneplan.customer.save(update_fields=["stripe_customer_id"])with self.assertRaises(BillingError) as context:- invoice_plan(plan, timezone_now())+ billing_session = RealmBillingSession(realm=realm)+ billing_session.invoice_plan(plan, timezone_now())self.assertRegex(context.exception.error_description,- "Realm zulip has a paid plan without a Stripe customer",+ "Customer has a paid plan without a Stripe customer ID:",)@mock_stripe()@@ -4876,7 +4880,8 @@ class InvoiceTest(StripeTestCase):update_license_ledger_if_needed(get_realm("zulip"), self.now + timedelta(days=500))plan = CustomerPlan.objects.first()assert plan is not None- invoice_plan(plan, self.now + timedelta(days=400))+ billing_session = RealmBillingSession(realm=user.realm)+ billing_session.invoice_plan(plan, self.now + timedelta(days=400))stripe_customer_id = plan.customer.stripe_customer_idassert stripe_customer_id is not None[invoice0, invoice1] = iter(stripe.Invoice.list(customer=stripe_customer_id))@@ -4931,7 +4936,8 @@ class InvoiceTest(StripeTestCase):plan.fixed_price = 100plan.price_per_license = 0plan.save(update_fields=["fixed_price", "price_per_license"])- invoice_plan(plan, self.next_year)+ billing_session = RealmBillingSession(realm=user.realm)+ billing_session.invoice_plan(plan, self.next_year)stripe_customer_id = plan.customer.stripe_customer_idassert stripe_customer_id is not None[invoice0, invoice1] = iter(stripe.Invoice.list(customer=stripe_customer_id))@@ -4951,6 +4957,7 @@ class InvoiceTest(StripeTestCase):self.assertEqual(item.get(key), value)def test_no_invoice_needed(self) -> None:+ # local_upgrade uses hamlet as user, therefore realm is zulip.with time_machine.travel(self.now, tick=False):self.local_upgrade(self.seat_count, True, CustomerPlan.BILLING_SCHEDULE_ANNUAL, True, False@@ -4959,7 +4966,9 @@ class InvoiceTest(StripeTestCase):assert plan is not Noneself.assertEqual(plan.next_invoice_date, self.next_month)# Test this doesn't make any calls to stripe.Invoice or stripe.InvoiceItem- invoice_plan(plan, self.next_month)+ assert plan.customer.realm is not None+ billing_session = RealmBillingSession(realm=plan.customer.realm)+ billing_session.invoice_plan(plan, self.next_month)plan = CustomerPlan.objects.first()# Test that we still update next_invoice_dateassert plan is not None@@ -4974,7 +4983,7 @@ class InvoiceTest(StripeTestCase):assert plan is not Noneself.assertEqual(plan.next_invoice_date, self.next_month)# Test nothing needed to be done- with patch("corporate.lib.stripe.invoice_plan") as mocked:+ with patch("corporate.lib.stripe.BillingSession.invoice_plan") as mocked:invoice_plans_as_needed(self.next_month - timedelta(days=1))mocked.assert_not_called()# Test something needing to be done