-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathstripe.py
5159 lines (4542 loc) · 213 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,
Literal,
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,
CustomerPlanOffer,
Invoice,
LicenseLedger,
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 = 15
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 get_amount_due_fixed_price_plan(fixed_price: int, billing_schedule: int) -> int:
amount_due = fixed_price
if billing_schedule == CustomerPlan.BILLING_SCHEDULE_MONTHLY:
amount_due = int(float(format_money(fixed_price / 12)) * 100)
return amount_due
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
# max / min license check for invoiced plans is disabled in production right now.
# Logic and tests are kept in case we decide to enable it in future.
if settings.TEST_SUITE and 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 = 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
def get_configured_fixed_price_plan_offer(
customer: Customer, plan_tier: int
) -> Optional[CustomerPlanOffer]:
"""
Fixed price plan offer configured via /support which the
customer is yet to buy or schedule a purchase.
"""
if plan_tier == customer.required_plan_tier:
return CustomerPlanOffer.objects.filter(
customer=customer,
tier=plan_tier,
fixed_price__isnull=False,
status=CustomerPlanOffer.CONFIGURED,
).first()
return None
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.StripeError as e:
assert isinstance(e.json_body, dict)
err = e.json_body.get("error", {})
if isinstance(e, stripe.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.RateLimitError, stripe.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 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
billing_modality: str
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_invoice_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
configure_fixed_price_plan = 9
delete_fixed_price_next_plan = 10
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]
fixed_price: Optional[int]
sent_invoice_id: Optional[str]
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)
# Sync this with upgrade_params_schema in base_page_params.ts.
class UpgradePageParams(TypedDict):
page_type: Literal["upgrade"]
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
fixed_price: Optional[int]
setup_payment_by_invoice: bool
free_trial_days: Optional[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
discount_percent: Optional[str]
email: str
exempt_from_license_number_check: bool
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
fixed_price_plan: bool
pay_by_invoice_payments_page: Optional[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
scheduled_upgrade_invoice_amount_due: Optional[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_invoice_payment(
self, metadata: Dict[str, Any]
) -> Dict[str, Any]:
pass
@abstractmethod
def org_name(self) -> str:
pass
def is_legacy_customer(self) -> bool:
if isinstance(self, RealmBillingSession):
return False
customers_to_check = []
if isinstance(self, RemoteRealmBillingSession):
customer = self.get_customer()
if customer is not None:
customers_to_check.append(customer)
# Also, check if server for a remote realm was ever on a legacy plan.
# We don't migrate ENDED legacy plans from server to remote realm, so we can end
# in this state if the first time they registered with us was after the legacy plan.
server_customer = get_customer_by_remote_server(self.remote_realm.server)
if server_customer is not None:
customers_to_check.append(server_customer)
if isinstance(self, RemoteServerBillingSession):
customer = self.get_customer()
if customer is not None:
customers_to_check.append(customer)
return CustomerPlan.objects.filter(
customer__in=customers_to_check, tier=CustomerPlan.TIER_SELF_HOSTED_LEGACY
).exists()
def get_past_invoices_session_url(self) -> str:
headline = "List of past invoices"
customer = self.get_customer()
assert customer is not None and customer.stripe_customer_id is not None
# Check if customer has any $0 invoices.
if stripe.Invoice.list(
customer=customer.stripe_customer_id,
limit=1,
status="paid",
total=0,
).data: # nocoverage
# These are payment for upgrades which were paid directly by the customer and then we
# created an invoice for them resulting in `$0` invoices since there was no amount due.
headline += " ($0 invoices include payment)"
configuration = stripe.billing_portal.Configuration.create(
business_profile={
"headline": headline,
},
features={
"invoice_history": {"enabled": True},
},
)
return stripe.billing_portal.Session.create(
customer=customer.stripe_customer_id,
configuration=configuration.id,
return_url=f"{self.billing_session_url}/billing/",
).url
def get_stripe_customer_portal_url(
self,
return_to_billing_page: bool,
manual_license_management: bool,
tier: Optional[int] = None,
setup_payment_by_invoice: bool = False,
) -> str:
customer = self.get_customer()
if setup_payment_by_invoice and (
customer is None or customer.stripe_customer_id is None
): # nocoverage
customer = self.create_stripe_customer()
assert customer is not None and customer.stripe_customer_id is not None
if return_to_billing_page:
return_url = f"{self.billing_session_url}/billing/"
else:
assert tier is not None
base_return_url = f"{self.billing_session_url}/upgrade/"
params = {
"manual_license_management": str(manual_license_management).lower(),
"tier": str(tier),
"setup_payment_by_invoice": str(setup_payment_by_invoice).lower(),
}
return_url = f"{base_return_url}?{urlencode(params)}"
configuration = stripe.billing_portal.Configuration.create(
business_profile={
"headline": "Invoice and receipt billing information",
},
features={"customer_update": {"enabled": True, "allowed_updates": ["address", "name"]}},
)
return stripe.billing_portal.Session.create(
customer=customer.stripe_customer_id,
configuration=configuration.id,
return_url=return_url,
).url
def generate_invoice_for_upgrade(
self,
customer: Customer,
price_per_license: Optional[int],
fixed_price: Optional[int],
licenses: int,
plan_tier: int,
billing_schedule: int,
charge_automatically: bool,
license_management: Optional[str] = None,
) -> stripe.Invoice:
plan_name = CustomerPlan.name_from_tier(plan_tier)
assert price_per_license is None or fixed_price is None
price_args: PriceArgs = {}
if fixed_price is None:
assert price_per_license is not None
price_args = {
"quantity": licenses,
"unit_amount": price_per_license,
}
else:
assert fixed_price is not None
amount_due = get_amount_due_fixed_price_plan(fixed_price, billing_schedule)
price_args = {"amount": amount_due}
stripe.InvoiceItem.create(
currency="usd",
customer=customer.stripe_customer_id,
description=plan_name,
discountable=False,
**price_args,
)
if fixed_price is None and 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)
discount = customer.flat_discount * flat_discounted_months
customer.flat_discounted_months -= flat_discounted_months
customer.save(update_fields=["flat_discounted_months"])
stripe.InvoiceItem.create(
currency="usd",
customer=customer.stripe_customer_id,
description=f"${cents_to_dollar_string(customer.flat_discount)}/month new customer discount",
# Negative value to apply discount.
amount=(-1 * discount),
)
if charge_automatically:
collection_method = "charge_automatically"
days_until_due = None
else:
collection_method = "send_invoice"
# days_until_due is required for `send_invoice` collection method. Since this is an invoice
# for upgrade, the due date is irrelevant since customer will upgrade once they pay the invoice
# regardless of the due date. Using `1` shows `Due today / tomorrow` which seems nice.
days_until_due = 1
metadata = {
"plan_tier": plan_tier,
"billing_schedule": billing_schedule,
"licenses": licenses,
"license_management": license_management,
}
if hasattr(self, "user"):
metadata["user_id"] = self.user.id
# We only need to email customer about open invoice for manual billing.
# If automatic charge fails, we simply void the invoice.
# https://stripe.com/docs/invoicing/integration/automatic-advancement-collection
auto_advance = not charge_automatically
stripe_invoice = stripe.Invoice.create(
auto_advance=auto_advance,
collection_method=collection_method,
customer=customer.stripe_customer_id,
days_until_due=days_until_due,
statement_descriptor=plan_name,
metadata=metadata,
)
stripe.Invoice.finalize_invoice(stripe_invoice)
return stripe_invoice
@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