-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
stripe.py
4657 lines (4094 loc) · 190 KB
/
stripe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import math
import os
import secrets
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from enum import Enum
from functools import wraps
from typing import Any, Callable, Dict, Generator, Optional, Tuple, TypedDict, TypeVar, Union
from urllib.parse import urlencode, urljoin
import stripe
from django import forms
from django.conf import settings
from django.core import signing
from django.core.signing import Signer
from django.db import transaction
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils.timezone import now as timezone_now
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
from django.utils.translation import override as override_language
from typing_extensions import ParamSpec, override
from corporate.models import (
Customer,
CustomerPlan,
LicenseLedger,
PaymentIntent,
Session,
SponsoredPlanTypes,
ZulipSponsorshipRequest,
get_current_plan_by_customer,
get_current_plan_by_realm,
get_customer_by_realm,
get_customer_by_remote_realm,
get_customer_by_remote_server,
)
from zerver.lib.exceptions import JsonableError
from zerver.lib.logging_util import log_to_file
from zerver.lib.send_email import (
FromAddress,
send_email,
send_email_to_billing_admins_and_realm_owners,
)
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
from zerver.lib.url_encoding import append_url_query_string
from zerver.lib.utils import assert_is_not_none
from zerver.models import Realm, RealmAuditLog, UserProfile
from zerver.models.realms import get_org_type_display_name, get_realm
from zerver.models.users import get_system_bot
from zilencer.lib.remote_counts import MissingDataError
from zilencer.models import (
RemoteRealm,
RemoteRealmAuditLog,
RemoteRealmBillingUser,
RemoteServerBillingUser,
RemoteZulipServer,
RemoteZulipServerAuditLog,
get_remote_realm_guest_and_non_guest_count,
get_remote_server_guest_and_non_guest_count,
has_stale_audit_log,
)
from zproject.config import get_secret
stripe.api_key = get_secret("stripe_secret_key")
BILLING_LOG_PATH = os.path.join(
"/var/log/zulip" if not settings.DEVELOPMENT else settings.DEVELOPMENT_LOG_DIRECTORY,
"billing.log",
)
billing_logger = logging.getLogger("corporate.stripe")
log_to_file(billing_logger, BILLING_LOG_PATH)
log_to_file(logging.getLogger("stripe"), BILLING_LOG_PATH)
ParamT = ParamSpec("ParamT")
ReturnT = TypeVar("ReturnT")
BILLING_SUPPORT_EMAIL = "sales@zulip.com"
MIN_INVOICED_LICENSES = 30
MAX_INVOICED_LICENSES = 1000
DEFAULT_INVOICE_DAYS_UNTIL_DUE = 30
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"
stripe.api_version = STRIPE_API_VERSION
# This function imitates the behavior of the format_money in billing/helpers.ts
def format_money(cents: float) -> str:
# allow for small floating point errors
cents = math.ceil(cents - 0.001)
if cents % 100 == 0:
precision = 0
else:
precision = 2
dollars = cents / 100
# Format the number as a string with the correct number of decimal places
return f"{dollars:.{precision}f}"
def format_discount_percentage(discount: Optional[Decimal]) -> Optional[str]:
if type(discount) is not Decimal or discount == Decimal(0):
return None
# This will look good for any custom discounts that we apply.
if discount * 100 % 100 == 0:
precision = 0
else:
precision = 2 # nocoverage
return f"{discount:.{precision}f}"
def get_latest_seat_count(realm: Realm) -> int:
return get_seat_count(realm, extra_non_guests_count=0, extra_guests_count=0)
def get_seat_count(
realm: Realm, extra_non_guests_count: int = 0, extra_guests_count: int = 0
) -> int:
non_guests = (
UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False)
.exclude(role=UserProfile.ROLE_GUEST)
.count()
) + extra_non_guests_count
# This guest count calculation should match the similar query in render_stats().
guests = (
UserProfile.objects.filter(
realm=realm, is_active=True, is_bot=False, role=UserProfile.ROLE_GUEST
).count()
+ extra_guests_count
)
# This formula achieves the pricing of the first 5*N guests
# being free of charge (where N is the number of non-guests in the organization)
# and each consecutive one being worth 1/5 the non-guest price.
return max(non_guests, math.ceil(guests / 5))
def sign_string(string: str) -> Tuple[str, str]:
salt = secrets.token_hex(32)
signer = Signer(salt=salt)
return signer.sign(string), salt
def unsign_string(signed_string: str, salt: str) -> str:
signer = Signer(salt=salt)
return signer.unsign(signed_string)
def unsign_seat_count(signed_seat_count: str, salt: str) -> int:
try:
return int(unsign_string(signed_seat_count, salt))
except signing.BadSignature:
raise BillingError("tampered seat count")
def validate_licenses(
charge_automatically: bool,
licenses: Optional[int],
seat_count: int,
exempt_from_license_number_check: bool,
min_licenses_for_plan: int,
) -> None:
min_licenses = max(seat_count, min_licenses_for_plan)
max_licenses = None
if not charge_automatically:
min_licenses = max(seat_count, MIN_INVOICED_LICENSES)
max_licenses = MAX_INVOICED_LICENSES
if licenses is None or (not exempt_from_license_number_check and licenses < min_licenses):
raise BillingError(
"not enough licenses",
_(
"You must purchase licenses for all active users in your organization (minimum {min_licenses})."
).format(min_licenses=min_licenses),
)
if max_licenses is not None and licenses > max_licenses:
message = _(
"Invoices with more than {max_licenses} licenses can't be processed from this page. To"
" complete the upgrade, please contact {email}."
).format(max_licenses=max_licenses, email=settings.ZULIP_ADMINISTRATOR)
raise BillingError("too many licenses", message)
def check_upgrade_parameters(
billing_modality: str,
schedule: str,
license_management: Optional[str],
licenses: Optional[int],
seat_count: int,
exempt_from_license_number_check: bool,
min_licenses_for_plan: int,
) -> None:
if billing_modality not in VALID_BILLING_MODALITY_VALUES: # nocoverage
raise BillingError("unknown billing_modality", "")
if schedule not in VALID_BILLING_SCHEDULE_VALUES: # nocoverage
raise BillingError("unknown schedule")
if license_management not in VALID_LICENSE_MANAGEMENT_VALUES: # nocoverage
raise BillingError("unknown license_management")
validate_licenses(
billing_modality == "charge_automatically",
licenses,
seat_count,
exempt_from_license_number_check,
min_licenses_for_plan,
)
# Be extremely careful changing this function. Historical billing periods
# are not stored anywhere, and are just computed on the fly using this
# function. Any change you make here should return the same value (or be
# within a few seconds) for basically any value from when the billing system
# went online to within a year from now.
def add_months(dt: datetime, months: int) -> datetime:
assert months >= 0
# It's fine that the max day in Feb is 28 for leap years.
MAX_DAY_FOR_MONTH = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
year = dt.year
month = dt.month + months
while month > 12:
year += 1
month -= 12
day = min(dt.day, MAX_DAY_FOR_MONTH[month])
# datetimes don't support leap seconds, so don't need to worry about those
return dt.replace(year=year, month=month, day=day)
def next_month(billing_cycle_anchor: datetime, dt: datetime) -> datetime:
estimated_months = round((dt - billing_cycle_anchor).days * 12.0 / 365)
for months in range(max(estimated_months - 1, 0), estimated_months + 2):
proposed_next_month = add_months(billing_cycle_anchor, months)
if 20 < (proposed_next_month - dt).days < 40:
return proposed_next_month
raise AssertionError(
"Something wrong in next_month calculation with "
f"billing_cycle_anchor: {billing_cycle_anchor}, dt: {dt}"
)
def start_of_next_billing_cycle(plan: CustomerPlan, event_time: datetime) -> datetime:
months_per_period = {
CustomerPlan.BILLING_SCHEDULE_ANNUAL: 12,
CustomerPlan.BILLING_SCHEDULE_MONTHLY: 1,
}[plan.billing_schedule]
periods = 1
dt = plan.billing_cycle_anchor
while dt <= event_time:
dt = add_months(plan.billing_cycle_anchor, months_per_period * periods)
periods += 1
return dt
def next_invoice_date(plan: CustomerPlan) -> Optional[datetime]:
if plan.status == CustomerPlan.ENDED:
return None
assert plan.next_invoice_date is not None # for mypy
months_per_period = {
CustomerPlan.BILLING_SCHEDULE_ANNUAL: 12,
CustomerPlan.BILLING_SCHEDULE_MONTHLY: 1,
}[plan.billing_schedule]
if plan.automanage_licenses:
months_per_period = 1
periods = 1
dt = plan.billing_cycle_anchor
while dt <= plan.next_invoice_date:
dt = add_months(plan.billing_cycle_anchor, months_per_period * periods)
periods += 1
return dt
def get_amount_to_credit_for_plan_tier_change(
current_plan: CustomerPlan, plan_change_date: datetime
) -> int:
last_renewal_ledger = (
LicenseLedger.objects.filter(is_renewal=True, plan=current_plan).order_by("id").last()
)
assert last_renewal_ledger is not None
assert current_plan.price_per_license is not None
next_renewal_date = start_of_next_billing_cycle(current_plan, plan_change_date)
last_renewal_amount = last_renewal_ledger.licenses * current_plan.price_per_license
last_renewal_date = last_renewal_ledger.event_time
prorated_fraction = 1 - (plan_change_date - last_renewal_date) / (
next_renewal_date - last_renewal_date
)
amount_to_credit_back = math.ceil(last_renewal_amount * prorated_fraction)
return amount_to_credit_back
def get_idempotency_key(ledger_entry: LicenseLedger) -> Optional[str]:
if settings.TEST_SUITE:
return None
return f"ledger_entry:{ledger_entry.id}" # nocoverage
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
def build_support_url(support_view: str, query_text: str) -> str:
support_realm_url = get_realm(settings.STAFF_SUBDOMAIN).uri
support_url = urljoin(support_realm_url, reverse(support_view))
query = urlencode({"q": query_text})
support_url = append_url_query_string(support_url, query)
return support_url
class BillingError(JsonableError):
data_fields = ["error_description"]
# error messages
CONTACT_SUPPORT = gettext_lazy("Something went wrong. Please contact {email}.")
TRY_RELOADING = gettext_lazy("Something went wrong. Please reload the page.")
# description is used only for tests
def __init__(self, description: str, message: Optional[str] = None) -> None:
self.error_description = description
if message is None:
message = BillingError.CONTACT_SUPPORT.format(email=settings.ZULIP_ADMINISTRATOR)
super().__init__(message)
class LicenseLimitError(Exception):
pass
class StripeCardError(BillingError):
pass
class StripeConnectionError(BillingError):
pass
class ServerDeactivateWithExistingPlanError(BillingError): # nocoverage
def __init__(self) -> None:
super().__init__(
"server deactivation with existing plan",
"",
)
class UpgradeWithExistingPlanError(BillingError):
def __init__(self) -> None:
super().__init__(
"subscribing with existing subscription",
"The organization is already subscribed to a plan. Please reload the billing page.",
)
class InvalidPlanUpgradeError(BillingError): # nocoverage
def __init__(self, message: str) -> None:
super().__init__(
"invalid plan upgrade",
message,
)
class InvalidBillingScheduleError(Exception):
def __init__(self, billing_schedule: int) -> None:
self.message = f"Unknown billing_schedule: {billing_schedule}"
super().__init__(self.message)
class InvalidTierError(Exception):
def __init__(self, tier: int) -> None:
self.message = f"Unknown tier: {tier}"
super().__init__(self.message)
class SupportRequestError(BillingError):
def __init__(self, message: str) -> None:
super().__init__(
"invalid support request",
message,
)
def catch_stripe_errors(func: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]:
@wraps(func)
def wrapped(*args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT:
try:
return func(*args, **kwargs)
# See https://stripe.com/docs/api/python#error_handling, though
# https://stripe.com/docs/api/ruby#error_handling suggests there are additional fields, and
# https://stripe.com/docs/error-codes gives a more detailed set of error codes
except stripe.error.StripeError as e:
assert isinstance(e.json_body, dict)
err = e.json_body.get("error", {})
if isinstance(e, stripe.error.CardError):
billing_logger.info(
"Stripe card error: %s %s %s %s",
e.http_status,
err.get("type"),
err.get("code"),
err.get("param"),
)
# TODO: Look into i18n for this
raise StripeCardError("card error", err.get("message"))
billing_logger.error(
"Stripe error: %s %s %s %s",
e.http_status,
err.get("type"),
err.get("code"),
err.get("param"),
)
if isinstance(
e, (stripe.error.RateLimitError, stripe.error.APIConnectionError)
): # nocoverage TODO
raise StripeConnectionError(
"stripe connection error",
_("Something went wrong. Please wait a few seconds and try again."),
)
raise BillingError("other stripe error")
return wrapped
@catch_stripe_errors
def stripe_get_customer(stripe_customer_id: str) -> stripe.Customer:
return stripe.Customer.retrieve(
stripe_customer_id, expand=["invoice_settings", "invoice_settings.default_payment_method"]
)
def sponsorship_org_type_key_helper(d: Any) -> int:
return d[1]["display_order"]
class PriceArgs(TypedDict, total=False):
amount: int
unit_amount: int
quantity: int
@dataclass
class StripeCustomerData:
description: str
email: str
metadata: Dict[str, Any]
@dataclass
class StripePaymentIntentData:
amount: int
description: str
plan_name: str
email: str
@dataclass
class UpgradeRequest:
billing_modality: str
schedule: str
signed_seat_count: str
salt: str
license_management: Optional[str]
licenses: Optional[int]
tier: int
remote_server_plan_start_date: Optional[str]
@dataclass
class InitialUpgradeRequest:
manual_license_management: bool
tier: int
success_message: str = ""
@dataclass
class UpdatePlanRequest:
status: Optional[int]
licenses: Optional[int]
licenses_at_next_renewal: Optional[int]
schedule: Optional[int]
@dataclass
class EventStatusRequest:
stripe_session_id: Optional[str]
stripe_payment_intent_id: Optional[str]
class SupportType(Enum):
approve_sponsorship = 1
update_sponsorship_status = 2
attach_discount = 3
update_billing_modality = 4
modify_plan = 5
update_minimum_licenses = 6
update_plan_end_date = 7
update_required_plan_tier = 8
class SupportViewRequest(TypedDict, total=False):
support_type: SupportType
sponsorship_status: Optional[bool]
discount: Optional[Decimal]
billing_modality: Optional[str]
plan_modification: Optional[str]
new_plan_tier: Optional[int]
minimum_licenses: Optional[int]
plan_end_date: Optional[str]
required_plan_tier: Optional[int]
class AuditLogEventType(Enum):
STRIPE_CUSTOMER_CREATED = 1
STRIPE_CARD_CHANGED = 2
CUSTOMER_PLAN_CREATED = 3
DISCOUNT_CHANGED = 4
SPONSORSHIP_APPROVED = 5
SPONSORSHIP_PENDING_STATUS_CHANGED = 6
BILLING_MODALITY_CHANGED = 7
CUSTOMER_SWITCHED_FROM_MONTHLY_TO_ANNUAL_PLAN = 8
CUSTOMER_SWITCHED_FROM_ANNUAL_TO_MONTHLY_PLAN = 9
BILLING_ENTITY_PLAN_TYPE_CHANGED = 10
CUSTOMER_PROPERTY_CHANGED = 11
CUSTOMER_PLAN_PROPERTY_CHANGED = 12
class PlanTierChangeType(Enum):
INVALID = 1
UPGRADE = 2
DOWNGRADE = 3
class BillingSessionAuditLogEventError(Exception):
def __init__(self, event_type: AuditLogEventType) -> None:
self.message = f"Unknown audit log event type: {event_type}"
super().__init__(self.message)
class UpgradePageParams(TypedDict):
annual_price: int
demo_organization_scheduled_deletion_date: Optional[datetime]
monthly_price: int
seat_count: int
billing_base_url: str
tier: int
flat_discount: int
flat_discounted_months: int
class UpgradePageSessionTypeSpecificContext(TypedDict):
customer_name: str
email: str
is_demo_organization: bool
demo_organization_scheduled_deletion_date: Optional[datetime]
is_self_hosting: bool
class SponsorshipApplicantInfo(TypedDict):
name: str
role: str
email: str
class SponsorshipRequestSessionSpecificContext(TypedDict):
# We don't store UserProfile for remote realms.
realm_user: Optional[UserProfile]
user_info: SponsorshipApplicantInfo
# TODO: Call this what we end up calling it for /support page.
realm_string_id: str
class UpgradePageContext(TypedDict):
customer_name: str
default_invoice_days_until_due: int
discount_percent: Optional[str]
email: str
exempt_from_license_number_check: bool
free_trial_days: Optional[int]
free_trial_end_date: Optional[str]
is_demo_organization: bool
manual_license_management: bool
using_min_licenses_for_plan: bool
min_licenses_for_plan: int
page_params: UpgradePageParams
payment_method: Optional[str]
plan: str
remote_server_legacy_plan_end_date: Optional[str]
salt: str
seat_count: int
signed_seat_count: str
success_message: str
is_sponsorship_pending: bool
sponsorship_plan_name: str
class SponsorshipRequestForm(forms.Form):
website = forms.URLField(max_length=ZulipSponsorshipRequest.MAX_ORG_URL_LENGTH, required=False)
organization_type = forms.IntegerField()
description = forms.CharField(widget=forms.Textarea)
expected_total_users = forms.CharField(widget=forms.Textarea)
paid_users_count = forms.CharField(widget=forms.Textarea)
paid_users_description = forms.CharField(widget=forms.Textarea, required=False)
requested_plan = forms.ChoiceField(
choices=[(plan.value, plan.name) for plan in SponsoredPlanTypes], required=False
)
class BillingSession(ABC):
@property
@abstractmethod
def billing_entity_display_name(self) -> str:
pass
@property
@abstractmethod
def billing_session_url(self) -> str:
pass
@property
@abstractmethod
def billing_base_url(self) -> str:
pass
@abstractmethod
def support_url(self) -> str:
pass
@abstractmethod
def get_customer(self) -> Optional[Customer]:
pass
@abstractmethod
def get_email(self) -> str:
pass
@abstractmethod
def current_count_for_billed_licenses(self, event_time: datetime = timezone_now()) -> int:
pass
@abstractmethod
def get_audit_log_event(self, event_type: AuditLogEventType) -> int:
pass
@abstractmethod
def write_to_audit_log(
self,
event_type: AuditLogEventType,
event_time: datetime,
*,
background_update: bool = False,
extra_data: Optional[Dict[str, Any]] = None,
) -> None:
pass
@abstractmethod
def get_data_for_stripe_customer(self) -> StripeCustomerData:
pass
@abstractmethod
def update_data_for_checkout_session_and_payment_intent(
self, metadata: Dict[str, Any]
) -> Dict[str, Any]:
pass
def get_data_for_stripe_payment_intent(
self,
customer: Customer,
price_per_license: int,
licenses: int,
plan_tier: int,
billing_schedule: int,
email: str,
) -> StripePaymentIntentData:
if hasattr(self, "support_session") and self.support_session: # nocoverage
raise BillingError(
"invalid support session",
"Support requests do not set any stripe billing information.",
)
amount = price_per_license * licenses
plan_name = CustomerPlan.name_from_tier(plan_tier)
description = f"Upgrade to {plan_name}, ${price_per_license/100} x {licenses}"
if customer.flat_discounted_months > 0:
num_months = 12 if billing_schedule == CustomerPlan.BILLING_SCHEDULE_ANNUAL else 1
flat_discounted_months = min(customer.flat_discounted_months, num_months)
amount -= customer.flat_discount * flat_discounted_months
description += f" - ${customer.flat_discount/100} x {flat_discounted_months}"
return StripePaymentIntentData(
amount=amount,
description=description,
plan_name=plan_name,
email=email,
)
@abstractmethod
def update_or_create_customer(
self, stripe_customer_id: Optional[str] = None, *, defaults: Optional[Dict[str, Any]] = None
) -> Customer:
pass
@abstractmethod
def do_change_plan_type(
self, *, tier: Optional[int], is_sponsored: bool = False, background_update: bool = False
) -> None:
pass
@abstractmethod
def process_downgrade(self, plan: CustomerPlan, background_update: bool = False) -> None:
pass
@abstractmethod
def approve_sponsorship(self) -> str:
pass
@abstractmethod
def is_sponsored(self) -> bool:
pass
@abstractmethod
def get_sponsorship_request_session_specific_context(
self,
) -> SponsorshipRequestSessionSpecificContext:
pass
@abstractmethod
def save_org_type_from_request_sponsorship_session(self, org_type: int) -> None:
pass
@abstractmethod
def get_upgrade_page_session_type_specific_context(
self,
) -> UpgradePageSessionTypeSpecificContext:
pass
@abstractmethod
def check_plan_tier_is_billable(self, plan_tier: int) -> bool:
pass
@abstractmethod
def get_type_of_plan_tier_change(
self, current_plan_tier: int, new_plan_tier: int
) -> PlanTierChangeType:
pass
@abstractmethod
def has_billing_access(self) -> bool:
pass
@abstractmethod
def on_paid_plan(self) -> bool:
pass
@abstractmethod
def add_sponsorship_info_to_context(self, context: Dict[str, Any]) -> None:
pass
@abstractmethod
def get_metadata_for_stripe_update_card(self) -> Dict[str, Any]:
pass
@abstractmethod
def sync_license_ledger_if_needed(self) -> None:
# Updates the license ledger based on RemoteRealmAuditLog
# entries.
#
# Supports backfilling entries from weeks if the past if
# needed when we receive audit logs, making any end-of-cycle
# updates that happen to be scheduled inside the interval that
# we are processing.
#
# But this support is fragile, in that it does not handle the
# possibility that some other code path changed or ended the
# customer's current plan at some point after
# last_ledger.event_time but before the event times for the
# audit logs we will be processing.
pass
def is_sponsored_or_pending(self, customer: Optional[Customer]) -> bool:
if (customer is not None and customer.sponsorship_pending) or self.is_sponsored():
return True
return False
def get_remote_server_legacy_plan(
self, customer: Optional[Customer], status: int = CustomerPlan.ACTIVE
) -> Optional[CustomerPlan]:
# status = CustomerPlan.ACTIVE means that the legacy plan is not scheduled for an upgrade.
# status = CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END means that the legacy plan is scheduled for an upgrade.
if customer is None:
return None
return CustomerPlan.objects.filter(
customer=customer,
tier=CustomerPlan.TIER_SELF_HOSTED_LEGACY,
status=status,
next_invoice_date=None,
).first()
def get_formatted_remote_server_legacy_plan_end_date(
self, customer: Optional[Customer], status: int = CustomerPlan.ACTIVE
) -> Optional[str]: # nocoverage
plan = self.get_remote_server_legacy_plan(customer, status)
if plan is None:
return None
assert plan.end_date is not None
return plan.end_date.strftime("%B %d, %Y")
def get_legacy_remote_server_next_plan(self, customer: Customer) -> Optional[CustomerPlan]:
legacy_plan = self.get_remote_server_legacy_plan(
customer, CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END
)
if legacy_plan is None:
return None
# This also asserts that such a plan should exist.
assert legacy_plan.end_date is not None
return CustomerPlan.objects.get(
customer=customer,
billing_cycle_anchor=legacy_plan.end_date,
status=CustomerPlan.NEVER_STARTED,
)
def get_legacy_remote_server_next_plan_name(self, customer: Customer) -> Optional[str]:
next_plan = self.get_legacy_remote_server_next_plan(customer)
if next_plan is None:
return None
return next_plan.name
@catch_stripe_errors
def create_stripe_customer(self) -> Customer:
stripe_customer_data = self.get_data_for_stripe_customer()
stripe_customer = stripe.Customer.create(
description=stripe_customer_data.description,
email=stripe_customer_data.email,
metadata=stripe_customer_data.metadata,
)
event_time = timestamp_to_datetime(stripe_customer.created)
with transaction.atomic():
self.write_to_audit_log(AuditLogEventType.STRIPE_CUSTOMER_CREATED, event_time)
customer = self.update_or_create_customer(stripe_customer.id)
return customer
@catch_stripe_errors
def replace_payment_method(
self, stripe_customer_id: str, payment_method: str, pay_invoices: bool = False
) -> None:
stripe.Customer.modify(
stripe_customer_id, invoice_settings={"default_payment_method": payment_method}
)
self.write_to_audit_log(AuditLogEventType.STRIPE_CARD_CHANGED, timezone_now())
if pay_invoices:
for stripe_invoice in stripe.Invoice.list(
collection_method="charge_automatically",
customer=stripe_customer_id,
status="open",
):
# The stripe customer with the associated ID will get either a receipt
# or a "failed payment" email, but the in-app messaging could be clearer
# here (e.g. it could explicitly tell the user that there were payment(s)
# and that they succeeded or failed). Worth fixing if we notice that a
# lot of cards end up failing at this step.
stripe.Invoice.pay(stripe_invoice)
# Returns Customer instead of stripe_customer so that we don't make a Stripe
# API call if there's nothing to update
@catch_stripe_errors
def update_or_create_stripe_customer(self, payment_method: Optional[str] = None) -> Customer:
customer = self.get_customer()
if customer is None or customer.stripe_customer_id is None:
# A stripe.PaymentMethod should be attached to a stripe.Customer via
# a stripe.SetupIntent or stripe.PaymentIntent. Here we just want to
# create a new stripe.Customer.
assert payment_method is None
# We could do a better job of handling race conditions here, but if two
# people try to upgrade at exactly the same time, the main bad thing that
# will happen is that we will create an extra stripe.Customer that we can
# delete or ignore.
return self.create_stripe_customer()
if payment_method is not None:
self.replace_payment_method(customer.stripe_customer_id, payment_method, True)
return customer
def create_stripe_payment_intent(
self, price_per_license: int, licenses: int, metadata: Dict[str, Any]
) -> str:
# NOTE: This charges users immediately.
customer = self.get_customer()
assert customer is not None and customer.stripe_customer_id is not None
payment_intent_data = self.get_data_for_stripe_payment_intent(
customer,
price_per_license,
licenses,
metadata["plan_tier"],
metadata["billing_schedule"],
self.get_email(),
)
# Ensure customers have a default payment method set.
stripe_customer = stripe_get_customer(customer.stripe_customer_id)
if not stripe_customer_has_credit_card_as_default_payment_method(stripe_customer):
raise BillingError(
"no payment method",
"Please add a credit card before upgrading.",
)
assert stripe_customer.invoice_settings is not None
assert stripe_customer.invoice_settings.default_payment_method is not None
try:
# Try to charge user immediately, and if that fails, we inform the user about the failure.
stripe_payment_intent = stripe.PaymentIntent.create(
amount=payment_intent_data.amount,
currency="usd",
customer=customer.stripe_customer_id,
description=payment_intent_data.description,
receipt_email=payment_intent_data.email,
confirm=True,
statement_descriptor=payment_intent_data.plan_name,
metadata=metadata,
off_session=True,
payment_method=stripe_customer.invoice_settings.default_payment_method,
)
except stripe.error.CardError as e:
raise StripeCardError("card error", e.user_message)
PaymentIntent.objects.create(
customer=customer,
stripe_payment_intent_id=stripe_payment_intent.id,
status=PaymentIntent.get_status_integer_from_status_text(stripe_payment_intent.status),
)
return stripe_payment_intent.id
def create_card_update_session_for_upgrade(
self,
manual_license_management: bool,
tier: int,
) -> Dict[str, Any]:
metadata = self.get_metadata_for_stripe_update_card()
customer = self.update_or_create_stripe_customer()