-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathbilling-mode.ts
202 lines (181 loc) · 8.86 KB
/
billing-mode.ts
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
/**
* Copyright (c) 2022 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License-AGPL.txt in the project root for license information.
*/
import { inject, injectable } from "inversify";
import { Team, User } from "@gitpod/gitpod-protocol";
import { ConfigCatClientFactory } from "@gitpod/gitpod-protocol/lib/experiments/configcat-server";
import { SubscriptionService } from "@gitpod/gitpod-payment-endpoint/lib/accounting";
import { Subscription } from "@gitpod/gitpod-protocol/lib/accounting-protocol";
import { Config } from "../../../src/config";
import { StripeService } from "../user/stripe-service";
import { BillingMode } from "@gitpod/gitpod-protocol/lib/billing-mode";
import { TeamDB, TeamSubscription2DB, TeamSubscriptionDB, UserDB } from "@gitpod/gitpod-db/lib";
import { Plans } from "@gitpod/gitpod-protocol/lib/plans";
import { AttributionId } from "@gitpod/gitpod-protocol/lib/attribution";
import { TeamSubscription, TeamSubscription2 } from "@gitpod/gitpod-protocol/lib/team-subscription-protocol";
export const BillingModes = Symbol("BillingModes");
export interface BillingModes {
getBillingMode(attributionId: AttributionId, now: Date): Promise<BillingMode>;
getBillingModeForUser(user: User, now: Date): Promise<BillingMode>;
getBillingModeForTeam(team: Team, now: Date): Promise<BillingMode>;
}
/**
*
* Some rules for how we decide about BillingMode someone is in:
* - Teams: Do they have either:
* - Chargebee subscription => cb
* - UBB (& maybe Stripe subscription): => ubb
* - Users: Do they have either:
* - personal Chargebee subscription => cb
* - personal Stripe Subscription => ubb
* - at least one Stripe Team seat => ubb
*/
@injectable()
export class BillingModesImpl implements BillingModes {
@inject(Config) protected readonly config: Config;
@inject(ConfigCatClientFactory) protected readonly configCatClientFactory: ConfigCatClientFactory;
@inject(SubscriptionService) protected readonly subscriptionSvc: SubscriptionService;
@inject(StripeService) protected readonly stripeService: StripeService;
@inject(TeamSubscriptionDB) protected readonly teamSubscriptionDb: TeamSubscriptionDB;
@inject(TeamSubscription2DB) protected readonly teamSubscription2Db: TeamSubscription2DB;
@inject(TeamDB) protected readonly teamDB: TeamDB;
@inject(UserDB) protected readonly userDB: UserDB;
public async getBillingMode(attributionId: AttributionId, now: Date): Promise<BillingMode> {
switch (attributionId.kind) {
case "team":
const team = await this.teamDB.findTeamById(attributionId.teamId);
if (!team) {
throw new Error(`Cannot find team with id '${attributionId.teamId}'!`);
}
return this.getBillingModeForTeam(team, now);
case "user":
const user = await this.userDB.findUserById(attributionId.userId);
if (!user) {
throw new Error(`Cannot find user with id '${attributionId.userId}'!`);
}
return this.getBillingModeForUser(user, now);
}
}
async getBillingModeForUser(user: User, now: Date): Promise<BillingMode> {
if (!this.config.enablePayment) {
// Payment is not enabled. E.g. Self-Hosted.
return { mode: "none" };
}
// Is Usage Based Billing enabled for this user or not?
const teams = await this.teamDB.findTeamsByUser(user.id);
const isUsageBasedBillingEnabled = await this.configCatClientFactory().getValueAsync(
"isUsageBasedBillingEnabled",
false,
{
user,
teams,
},
);
// 1. UBB enabled?
if (!isUsageBasedBillingEnabled) {
// UBB is not enabled: definitely chargebee
return { mode: "chargebee" };
}
// 2. Any personal subscriptions?
// Chargebee takes precedence
function isTeamSubscription(s: Subscription): boolean {
return !!Plans.getById(s.planId)?.team;
}
const cbSubscriptions = await this.subscriptionSvc.getActivePaidSubscription(user.id, now);
const cbTeamSubscriptions = cbSubscriptions.filter((s) => isTeamSubscription(s));
const cbPersonalSubscriptions = cbSubscriptions.filter(
(s) => !isTeamSubscription(s) && s.planId !== Plans.FREE_OPEN_SOURCE.chargebeeId,
);
const cbOwnedTeamSubscriptions = (
await this.teamSubscriptionDb.findTeamSubscriptions({ userId: user.id })
).filter((ts) => TeamSubscription.isActive(ts, now.toISOString()));
let canUpgradeToUBB = false;
if (cbPersonalSubscriptions.length > 0) {
if (cbPersonalSubscriptions.every((s) => Subscription.isCancelled(s, now.toISOString()))) {
// The user has one or more paid subscriptions, but all of them have already been cancelled
canUpgradeToUBB = true;
} else {
// The user has at least one paid personal subscription
return {
mode: "chargebee",
};
}
}
// Stripe: Active personal subsciption?
let hasUbbPersonal = false;
const subscriptionId = await this.stripeService.findUncancelledSubscriptionByAttributionId(
AttributionId.render({ kind: "user", userId: user.id }),
);
if (subscriptionId) {
hasUbbPersonal = true;
}
// 3. Check team memberships/plans
// UBB overrides wins if there is _any_. But if there is none, use the existing Chargebee subscription.
const teamsModes = await Promise.all(teams.map((t) => this.getBillingModeForTeam(t, now)));
const hasUbbPaidTeam = teamsModes.some((tm) => tm.mode === "usage-based" && !!tm.paid);
const hasCbTeam = teamsModes.some((tm) => tm.mode === "chargebee");
const hasCbTeamSeat = cbTeamSubscriptions.length > 0;
const hasCbTeamSubscription = cbOwnedTeamSubscriptions.length > 0;
function usageBased() {
const result: BillingMode = { mode: "usage-based" };
if (hasCbTeam) {
result.hasChargebeeTeamPlan = true;
}
if (hasCbTeamSeat || hasCbTeamSubscription) {
result.hasChargebeeTeamSubscription = true;
}
return result;
}
if (hasUbbPaidTeam || hasUbbPersonal) {
// UBB is greedy: once a user has at least a paid team membership, they should benefit from it!
return usageBased();
}
if (hasCbTeam || hasCbTeamSeat || canUpgradeToUBB) {
// TODO(gpl): Q: How to test the free-tier, then? A: Make sure you have no CB seats anymore
// For that we could add a new field here, which lists all seats that are "blocking" you, and display them in the UI somewhere.
return { mode: "chargebee", canUpgradeToUBB: true }; // UBB is enabled, but no seat nor subscription yet.
}
// UBB free tier
return usageBased();
}
async getBillingModeForTeam(team: Team, _now: Date): Promise<BillingMode> {
if (!this.config.enablePayment) {
// Payment is not enabled. E.g. Self-Hosted.
return { mode: "none" };
}
const now = _now.toISOString();
// Is Usage Based Billing enabled for this team?
const isUsageBasedBillingEnabled = await this.configCatClientFactory().getValueAsync(
"isUsageBasedBillingEnabled",
false,
{
teamId: team.id,
teamName: team.name,
},
);
// 1. UBB enabled?
if (!isUsageBasedBillingEnabled) {
return { mode: "chargebee" };
}
// 2. Any Chargbee TeamSubscription2 (old Team Subscriptions are not relevant here, as they are not associated with a team)
const teamSubscription = await this.teamSubscription2Db.findForTeam(team.id, now);
if (teamSubscription && TeamSubscription2.isActive(teamSubscription, now)) {
if (TeamSubscription2.isCancelled(teamSubscription, now)) {
// The team has a paid subscription, but it's already cancelled, and UBB enabled
return { mode: "chargebee", canUpgradeToUBB: true };
}
return { mode: "chargebee" };
}
// 3. Now we're usage-based. We only have to figure out whether we have a plan yet or not.
const result: BillingMode = { mode: "usage-based" };
const subscriptionId = await this.stripeService.findUncancelledSubscriptionByAttributionId(
AttributionId.render({ kind: "team", teamId: team.id }),
);
if (subscriptionId) {
result.paid = true;
}
return result;
}
}