Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

stripe: Add 'get_billing_page_context' method to 'BillingSession'.

Prakhar Pratyush135d7c03cc04
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py
index b8906206851..d8a1d00bb75 100644
--- a/corporate/lib/stripe.py
+++ b/corporate/lib/stripe.py
@@ -62,6 +62,16 @@ VALID_BILLING_MODALITY_VALUES = ["send_invoice", "charge_automatically"]
VALID_BILLING_SCHEDULE_VALUES = ["annual", "monthly"]
VALID_LICENSE_MANAGEMENT_VALUES = ["automatic", "manual"]
+CARD_CAPITALIZATION = {
+ "amex": "American Express",
+ "diners": "Diners Club",
+ "discover": "Discover",
+ "jcb": "JCB",
+ "mastercard": "Mastercard",
+ "unionpay": "UnionPay",
+ "visa": "Visa",
+}
+
# The version of Stripe API the billing system supports.
STRIPE_API_VERSION = "2020-08-27"
@@ -252,14 +262,18 @@ def next_invoice_date(plan: CustomerPlan) -> Optional[datetime]:
return dt
-def renewal_amount(plan: CustomerPlan, event_time: datetime) -> int: # nocoverage: TODO
+def renewal_amount(
+ plan: CustomerPlan, event_time: datetime, last_ledger_entry: Optional[LicenseLedger] = None
+) -> int: # nocoverage: TODO
if plan.fixed_price is not None:
return plan.fixed_price
- realm = plan.customer.realm
- billing_session = RealmBillingSession(user=None, realm=realm)
- new_plan, last_ledger_entry = billing_session.make_end_of_cycle_updates_if_needed(
- plan, event_time
- )
+ new_plan = None
+ if last_ledger_entry is None:
+ realm = plan.customer.realm
+ billing_session = RealmBillingSession(user=None, realm=realm)
+ new_plan, last_ledger_entry = billing_session.make_end_of_cycle_updates_if_needed(
+ plan, event_time
+ )
if last_ledger_entry is None:
return 0
if last_ledger_entry.licenses_at_next_renewal is None:
@@ -280,6 +294,32 @@ def cents_to_dollar_string(cents: int) -> str:
return f"{cents / 100.:,.2f}"
+# Should only be called if the customer is being charged automatically
+def payment_method_string(stripe_customer: stripe.Customer) -> str:
+ assert stripe_customer.invoice_settings is not None
+ default_payment_method = stripe_customer.invoice_settings.default_payment_method
+ if default_payment_method is None:
+ return _("No payment method on file.")
+
+ assert isinstance(default_payment_method, stripe.PaymentMethod)
+ if default_payment_method.type == "card":
+ assert default_payment_method.card is not None
+ brand_name = default_payment_method.card.brand
+ if brand_name in CARD_CAPITALIZATION:
+ brand_name = CARD_CAPITALIZATION[default_payment_method.card.brand]
+ return _("{brand} ending in {last4}").format(
+ brand=brand_name,
+ last4=default_payment_method.card.last4,
+ )
+ # There might be one-off stuff we do for a particular customer that
+ # would land them here. E.g. by default we don't support ACH for
+ # automatic payments, but in theory we could add it for a customer via
+ # the Stripe dashboard.
+ return _("Unknown payment method. Please contact {email}.").format(
+ email=settings.ZULIP_ADMINISTRATOR,
+ ) # nocoverage
+
+
class BillingError(JsonableError):
data_fields = ["error_description"]
# error messages
@@ -969,6 +1009,81 @@ class BillingSession(ABC):
return None, None
return None, last_ledger_entry
+ def get_billing_page_context(self) -> Dict[str, Any]:
+ customer = self.get_customer()
+ assert customer is not None
+ plan = get_current_plan_by_customer(customer)
+ context: Dict[str, Any] = {}
+ if plan is not None:
+ now = timezone_now()
+ new_plan, last_ledger_entry = self.make_end_of_cycle_updates_if_needed(plan, now)
+ if last_ledger_entry is not None:
+ if new_plan is not None: # nocoverage
+ plan = new_plan
+ assert plan is not None # for mypy
+ downgrade_at_end_of_cycle = plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE
+ switch_to_annual_at_end_of_cycle = (
+ plan.status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE
+ )
+ licenses = last_ledger_entry.licenses
+ licenses_at_next_renewal = last_ledger_entry.licenses_at_next_renewal
+ seat_count = self.current_count_for_billed_licenses()
+
+ # Should do this in JavaScript, using the user's time zone
+ if plan.is_free_trial():
+ assert plan.next_invoice_date is not None
+ renewal_date = "{dt:%B} {dt.day}, {dt.year}".format(dt=plan.next_invoice_date)
+ else:
+ renewal_date = "{dt:%B} {dt.day}, {dt.year}".format(
+ dt=start_of_next_billing_cycle(plan, now)
+ )
+
+ renewal_cents = renewal_amount(plan, now, last_ledger_entry)
+ charge_automatically = plan.charge_automatically
+ assert customer.stripe_customer_id is not None # for mypy
+ stripe_customer = stripe_get_customer(customer.stripe_customer_id)
+ if charge_automatically:
+ payment_method = payment_method_string(stripe_customer)
+ else:
+ payment_method = "Billed by invoice"
+
+ fixed_price = (
+ cents_to_dollar_string(plan.fixed_price)
+ if plan.fixed_price is not None
+ else None
+ )
+
+ billing_frequency = CustomerPlan.BILLING_SCHEDULES[plan.billing_schedule]
+
+ if plan.price_per_license is None:
+ price_per_license = ""
+ elif billing_frequency == "Annual":
+ price_per_license = format_money(plan.price_per_license / 12)
+ else:
+ price_per_license = format_money(plan.price_per_license)
+
+ context = {
+ "plan_name": plan.name,
+ "has_active_plan": True,
+ "free_trial": plan.is_free_trial(),
+ "downgrade_at_end_of_cycle": downgrade_at_end_of_cycle,
+ "automanage_licenses": plan.automanage_licenses,
+ "switch_to_annual_at_end_of_cycle": switch_to_annual_at_end_of_cycle,
+ "licenses": licenses,
+ "licenses_at_next_renewal": licenses_at_next_renewal,
+ "seat_count": seat_count,
+ "renewal_date": renewal_date,
+ "renewal_amount": cents_to_dollar_string(renewal_cents),
+ "payment_method": payment_method,
+ "charge_automatically": charge_automatically,
+ "stripe_email": stripe_customer.email,
+ "CustomerPlan": CustomerPlan,
+ "billing_frequency": billing_frequency,
+ "fixed_price": fixed_price,
+ "price_per_license": price_per_license,
+ }
+ return context
+
class RealmBillingSession(BillingSession):
def __init__(self, user: Optional[UserProfile] = None, realm: Optional[Realm] = None) -> None:
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index 66d9739c3e0..40ef8cd2d81 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -839,7 +839,7 @@ class StripeTest(StripeTestCase):
self.assertEqual("/billing/", response["Location"])
# Check /billing/ has the correct information
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_not_in_success_response(["Pay annually"], response)
for substring in [
@@ -974,7 +974,7 @@ class StripeTest(StripeTestCase):
self.assertEqual("/billing/", response["Location"])
# Check /billing/ has the correct information
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_not_in_success_response(["Pay annually", "Update card"], response)
for substring in [
@@ -1093,7 +1093,7 @@ class StripeTest(StripeTestCase):
self.assertEqual(realm.plan_type, Realm.PLAN_TYPE_STANDARD)
self.assertEqual(realm.max_invites, Realm.INVITES_STANDARD_REALM_DAILY_MAX)
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_not_in_success_response(["Pay annually"], response)
for substring in [
@@ -1111,7 +1111,7 @@ class StripeTest(StripeTestCase):
self.assert_in_response(substring, response)
self.assert_not_in_success_response(["Go to your Zulip organization"], response)
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/", {"onboarding": "true"})
self.assert_in_success_response(["Go to your Zulip organization"], response)
@@ -1214,7 +1214,7 @@ class StripeTest(StripeTestCase):
plan.fixed_price = 127
plan.price_per_license = None
plan.save(update_fields=["fixed_price", "price_per_license"])
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_in_success_response(["$1.27"], response)
# Don't show price breakdown
@@ -1371,7 +1371,7 @@ class StripeTest(StripeTestCase):
self.assertEqual(realm.plan_type, Realm.PLAN_TYPE_STANDARD)
self.assertEqual(realm.max_invites, Realm.INVITES_STANDARD_REALM_DAILY_MAX)
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_not_in_success_response(["Pay annually"], response)
for substring in [
@@ -2643,14 +2643,12 @@ class StripeTest(StripeTestCase):
self.assertEqual(plan.licenses(), self.seat_count)
self.assertEqual(plan.licenses_at_next_renewal(), None)
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ 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.views.billing_page.stripe_get_customer", return_value=mock_customer
- ):
+ with patch("corporate.lib.stripe.stripe_get_customer", return_value=mock_customer):
response = self.client_get("/billing/")
self.assert_in_success_response(
[
@@ -2756,7 +2754,7 @@ class StripeTest(StripeTestCase):
self.assert_json_success(response)
monthly_plan.refresh_from_db()
self.assertEqual(monthly_plan.status, CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE)
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_in_success_response(
["Your plan will switch to annual billing on February 2, 2012"], response
@@ -2946,7 +2944,7 @@ class StripeTest(StripeTestCase):
self.assert_json_success(response)
monthly_plan.refresh_from_db()
self.assertEqual(monthly_plan.status, CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE)
- with patch("corporate.views.billing_page.timezone_now", return_value=self.now):
+ with patch("corporate.lib.stripe.timezone_now", return_value=self.now):
response = self.client_get("/billing/")
self.assert_in_success_response(
["Your plan will switch to annual billing on February 2, 2012"], response
diff --git a/corporate/views/billing_page.py b/corporate/views/billing_page.py
index 92f266d5859..29b968808ef 100644
--- a/corporate/views/billing_page.py
+++ b/corporate/views/billing_page.py
@@ -1,8 +1,6 @@
import logging
from typing import Any, Dict, Optional
-import stripe
-from django.conf import settings
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
@@ -11,24 +9,14 @@ from django.utils.translation import gettext as _
from corporate.lib.stripe import (
RealmBillingSession,
- cents_to_dollar_string,
do_change_plan_status,
downgrade_at_the_end_of_billing_cycle,
downgrade_now_without_creating_additional_invoices,
- format_money,
get_latest_seat_count,
- renewal_amount,
- start_of_next_billing_cycle,
- stripe_get_customer,
update_license_ledger_for_manual_plan,
validate_licenses,
)
-from corporate.models import (
- CustomerPlan,
- get_current_plan_by_customer,
- get_current_plan_by_realm,
- get_customer_by_realm,
-)
+from corporate.models import CustomerPlan, get_current_plan_by_realm, get_customer_by_realm
from zerver.decorator import require_billing_access, zulip_login_required
from zerver.lib.exceptions import JsonableError
from zerver.lib.request import REQ, has_request_variables
@@ -38,42 +26,6 @@ from zerver.models import Realm, UserProfile
billing_logger = logging.getLogger("corporate.stripe")
-CARD_CAPITALIZATION = {
- "amex": "American Express",
- "diners": "Diners Club",
- "discover": "Discover",
- "jcb": "JCB",
- "mastercard": "Mastercard",
- "unionpay": "UnionPay",
- "visa": "Visa",
-}
-
-
-# Should only be called if the customer is being charged automatically
-def payment_method_string(stripe_customer: stripe.Customer) -> str:
- assert stripe_customer.invoice_settings is not None
- default_payment_method = stripe_customer.invoice_settings.default_payment_method
- if default_payment_method is None:
- return _("No payment method on file.")
-
- assert isinstance(default_payment_method, stripe.PaymentMethod)
- if default_payment_method.type == "card":
- assert default_payment_method.card is not None
- brand_name = default_payment_method.card.brand
- if brand_name in CARD_CAPITALIZATION:
- brand_name = CARD_CAPITALIZATION[default_payment_method.card.brand]
- return _("{brand} ending in {last4}").format(
- brand=brand_name,
- last4=default_payment_method.card.last4,
- )
- # There might be one-off stuff we do for a particular customer that
- # would land them here. E.g. by default we don't support ACH for
- # automatic payments, but in theory we could add it for a customer via
- # the Stripe dashboard.
- return _("Unknown payment method. Please contact {email}.").format(
- email=settings.ZULIP_ADMINISTRATOR,
- ) # nocoverage
-
def add_sponsorship_info_to_context(context: Dict[str, Any], user_profile: UserProfile) -> None:
def key_helper(d: Any) -> int:
@@ -159,77 +111,11 @@ def billing_home(
return HttpResponseRedirect(reverse(initial_upgrade))
- plan = get_current_plan_by_customer(customer)
- if plan is not None:
- now = timezone_now()
- realm = plan.customer.realm
- billing_session = RealmBillingSession(user=None, realm=realm)
- new_plan, last_ledger_entry = billing_session.make_end_of_cycle_updates_if_needed(plan, now)
- if last_ledger_entry is not None:
- if new_plan is not None: # nocoverage
- plan = new_plan
- assert plan is not None # for mypy
- downgrade_at_end_of_cycle = plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE
- switch_to_annual_at_end_of_cycle = (
- plan.status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE
- )
- licenses = last_ledger_entry.licenses
- licenses_at_next_renewal = last_ledger_entry.licenses_at_next_renewal
- seat_count = get_latest_seat_count(user.realm)
-
- # Should do this in JavaScript, using the user's time zone
- if plan.is_free_trial():
- assert plan.next_invoice_date is not None
- renewal_date = "{dt:%B} {dt.day}, {dt.year}".format(dt=plan.next_invoice_date)
- else:
- renewal_date = "{dt:%B} {dt.day}, {dt.year}".format(
- dt=start_of_next_billing_cycle(plan, now)
- )
-
- renewal_cents = renewal_amount(plan, now)
- charge_automatically = plan.charge_automatically
- assert customer.stripe_customer_id is not None # for mypy
- stripe_customer = stripe_get_customer(customer.stripe_customer_id)
- if charge_automatically:
- payment_method = payment_method_string(stripe_customer)
- else:
- payment_method = "Billed by invoice"
-
- fixed_price = (
- cents_to_dollar_string(plan.fixed_price) if plan.fixed_price is not None else None
- )
-
- billing_frequency = CustomerPlan.BILLING_SCHEDULES[plan.billing_schedule]
-
- if plan.price_per_license is None:
- price_per_license = ""
- elif billing_frequency == "Annual":
- price_per_license = format_money(plan.price_per_license / 12)
- else:
- price_per_license = format_money(plan.price_per_license)
-
- context.update(
- plan_name=plan.name,
- has_active_plan=True,
- free_trial=plan.is_free_trial(),
- downgrade_at_end_of_cycle=downgrade_at_end_of_cycle,
- automanage_licenses=plan.automanage_licenses,
- switch_to_annual_at_end_of_cycle=switch_to_annual_at_end_of_cycle,
- licenses=licenses,
- licenses_at_next_renewal=licenses_at_next_renewal,
- seat_count=seat_count,
- renewal_date=renewal_date,
- renewal_amount=cents_to_dollar_string(renewal_cents),
- payment_method=payment_method,
- charge_automatically=charge_automatically,
- stripe_email=stripe_customer.email,
- CustomerPlan=CustomerPlan,
- onboarding=onboarding,
- billing_frequency=billing_frequency,
- fixed_price=fixed_price,
- price_per_license=price_per_license,
- success_message=success_message,
- )
+ billing_session = RealmBillingSession(user=None, realm=user.realm)
+ main_context = billing_session.get_billing_page_context()
+ if main_context:
+ context.update(main_context)
+ context.update({"onboarding": onboarding, "success_message": success_message})
return render(request, "corporate/billing.html", context=context)