Skip to content

Allow teams to cancel and renew their usage-based subscription in Stripe #10890

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 42 additions & 39 deletions components/dashboard/src/teams/TeamUsageBasedBilling.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,30 @@ import { PaymentContext } from "../payment-context";
import { getGitpodService } from "../service/service";
import { ThemeContext } from "../theme-context";

type PendingStripeCustomer = { pendingSince: number };
type PendingStripeSubscription = { pendingSince: number };

export default function TeamUsageBasedBilling() {
const { teams } = useContext(TeamsContext);
const location = useLocation();
const team = getCurrentTeam(location, teams);
const { showUsageBasedUI, currency } = useContext(PaymentContext);
const [stripeCustomerId, setStripeCustomerId] = useState<string | undefined>();
const [stripeSubscriptionId, setStripeSubscriptionId] = useState<string | undefined>();
const [isLoading, setIsLoading] = useState<boolean>(true);
const [showBillingSetupModal, setShowBillingSetupModal] = useState<boolean>(false);
const [pendingStripeCustomer, setPendingStripeCustomer] = useState<PendingStripeCustomer | undefined>();
const [pollStripeCustomerTimeout, setPollStripeCustomerTimeout] = useState<NodeJS.Timeout | undefined>();
const [pendingStripeSubscription, setPendingStripeSubscription] = useState<PendingStripeSubscription | undefined>();
const [pollStripeSubscriptionTimeout, setPollStripeSubscriptionTimeout] = useState<NodeJS.Timeout | undefined>();
const [stripePortalUrl, setStripePortalUrl] = useState<string | undefined>();

useEffect(() => {
if (!team) {
return;
}
(async () => {
setStripeCustomerId(undefined);
setStripeSubscriptionId(undefined);
setIsLoading(true);
try {
const customerId = await getGitpodService().server.findStripeCustomerIdForTeam(team.id);
setStripeCustomerId(customerId);
const subscriptionId = await getGitpodService().server.findStripeSubscriptionIdForTeam(team.id);
setStripeSubscriptionId(subscriptionId);
} catch (error) {
console.error(error);
} finally {
Expand All @@ -48,14 +48,14 @@ export default function TeamUsageBasedBilling() {
}, [team]);

useEffect(() => {
if (!team || !stripeCustomerId) {
if (!team || !stripeSubscriptionId) {
return;
}
(async () => {
const portalUrl = await getGitpodService().server.getStripePortalUrlForTeam(team.id);
setStripePortalUrl(portalUrl);
})();
}, [team, stripeCustomerId]);
}, [team, stripeSubscriptionId]);

useEffect(() => {
if (!team) {
Expand All @@ -69,60 +69,63 @@ export default function TeamUsageBasedBilling() {
const setupIntentId = params.get("setup_intent")!;
window.history.replaceState({}, "", window.location.pathname);
await getGitpodService().server.subscribeTeamToStripe(team.id, setupIntentId, currency);
const pendingCustomer = { pendingSince: Date.now() };
setPendingStripeCustomer(pendingCustomer);
window.localStorage.setItem(`pendingStripeCustomerForTeam${team.id}`, JSON.stringify(pendingCustomer));
const pendingSubscription = { pendingSince: Date.now() };
setPendingStripeSubscription(pendingSubscription);
window.localStorage.setItem(
`pendingStripeSubscriptionForTeam${team.id}`,
JSON.stringify(pendingSubscription),
);
})();
}, [location.search, team]);

useEffect(() => {
setPendingStripeCustomer(undefined);
setPendingStripeSubscription(undefined);
if (!team) {
return;
}
try {
const pendingStripeCustomer = window.localStorage.getItem(`pendingStripeCustomerForTeam${team.id}`);
if (!pendingStripeCustomer) {
const pendingStripeSubscription = window.localStorage.getItem(`pendingStripeSubscriptionForTeam${team.id}`);
if (!pendingStripeSubscription) {
return;
}
const pending = JSON.parse(pendingStripeCustomer);
setPendingStripeCustomer(pending);
const pending = JSON.parse(pendingStripeSubscription);
setPendingStripeSubscription(pending);
} catch (error) {
console.error("Could not load pending stripe customer", team.id, error);
console.error("Could not load pending stripe subscription", team.id, error);
}
}, [team]);

useEffect(() => {
if (!pendingStripeCustomer || !team) {
if (!pendingStripeSubscription || !team) {
return;
}
if (!!stripeCustomerId) {
if (!!stripeSubscriptionId) {
// The upgrade was successful!
window.localStorage.removeItem(`pendingStripeCustomerForTeam${team.id}`);
clearTimeout(pollStripeCustomerTimeout!);
setPendingStripeCustomer(undefined);
window.localStorage.removeItem(`pendingStripeSubscriptionForTeam${team.id}`);
clearTimeout(pollStripeSubscriptionTimeout!);
setPendingStripeSubscription(undefined);
return;
}
if (pendingStripeCustomer.pendingSince + 1000 * 60 * 5 < Date.now()) {
// Pending Stripe customer expires after 5 minutes
window.localStorage.removeItem(`pendingStripeCustomerForTeam${team.id}`);
clearTimeout(pollStripeCustomerTimeout!);
setPendingStripeCustomer(undefined);
if (pendingStripeSubscription.pendingSince + 1000 * 60 * 5 < Date.now()) {
// Pending Stripe subscription expires after 5 minutes
window.localStorage.removeItem(`pendingStripeSubscriptionForTeam${team.id}`);
clearTimeout(pollStripeSubscriptionTimeout!);
setPendingStripeSubscription(undefined);
return;
}
if (!pollStripeCustomerTimeout) {
// Refresh Stripe customer in 5 seconds in order to poll for upgrade confirmation
if (!pollStripeSubscriptionTimeout) {
// Refresh Stripe subscription in 5 seconds in order to poll for upgrade confirmation
const timeout = setTimeout(async () => {
const customerId = await getGitpodService().server.findStripeCustomerIdForTeam(team.id);
setStripeCustomerId(customerId);
setPollStripeCustomerTimeout(undefined);
const subscriptionId = await getGitpodService().server.findStripeSubscriptionIdForTeam(team.id);
setStripeSubscriptionId(subscriptionId);
setPollStripeSubscriptionTimeout(undefined);
}, 5000);
setPollStripeCustomerTimeout(timeout);
setPollStripeSubscriptionTimeout(timeout);
}
return function cleanup() {
clearTimeout(pollStripeCustomerTimeout!);
clearTimeout(pollStripeSubscriptionTimeout!);
};
}, [pendingStripeCustomer, pollStripeCustomerTimeout, stripeCustomerId, team]);
}, [pendingStripeSubscription, pollStripeSubscriptionTimeout, stripeSubscriptionId, team]);

if (!showUsageBasedUI) {
return <></>;
Expand All @@ -135,12 +138,12 @@ export default function TeamUsageBasedBilling() {
<div className="max-w-xl">
<div className="mt-4 h-32 p-4 flex flex-col rounded-xl bg-gray-100 dark:bg-gray-800">
<div className="uppercase text-sm text-gray-400 dark:text-gray-500">Billing</div>
{(isLoading || pendingStripeCustomer) && (
{(isLoading || pendingStripeSubscription) && (
<>
<Spinner className="m-2 h-5 w-5 animate-spin" />
</>
)}
{!isLoading && !pendingStripeCustomer && !stripeCustomerId && (
{!isLoading && !pendingStripeSubscription && !stripeSubscriptionId && (
<>
<div className="text-xl font-semibold flex-grow text-gray-600 dark:text-gray-400">
Inactive
Expand All @@ -150,7 +153,7 @@ export default function TeamUsageBasedBilling() {
</button>
</>
)}
{!isLoading && !pendingStripeCustomer && !!stripeCustomerId && (
{!isLoading && !pendingStripeSubscription && !!stripeSubscriptionId && (
<>
<div className="text-xl font-semibold flex-grow text-gray-600 dark:text-gray-400">
Active
Expand Down
2 changes: 1 addition & 1 deletion components/gitpod-protocol/src/gitpod-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ export interface GitpodServer extends JsonRpcServer<GitpodClient>, AdminServer,

getStripePublishableKey(): Promise<string>;
getStripeSetupIntentClientSecret(): Promise<string>;
findStripeCustomerIdForTeam(teamId: string): Promise<string | undefined>;
findStripeSubscriptionIdForTeam(teamId: string): Promise<string | undefined>;
subscribeTeamToStripe(teamId: string, setupIntentId: string, currency: Currency): Promise<void>;
getStripePortalUrlForTeam(teamId: string): Promise<string>;

Expand Down
10 changes: 10 additions & 0 deletions components/server/ee/src/user/stripe-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ export class StripeService {
return session.url;
}

async findUncancelledSubscriptionByCustomer(customerId: string): Promise<Stripe.Subscription | undefined> {
const result = await this.getStripe().subscriptions.list({
customer: customerId,
});
if (result.data.length > 1) {
throw new Error(`Stripe customer '${customerId}') has more than one subscription!`);
}
return result.data[0];
}

async createSubscriptionForCustomer(customerId: string, currency: Currency): Promise<void> {
const priceId = this.config?.stripeConfig?.usageProductPriceIds[currency];
if (!priceId) {
Expand Down
19 changes: 13 additions & 6 deletions components/server/ee/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1904,18 +1904,22 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
}
}

async findStripeCustomerIdForTeam(ctx: TraceContext, teamId: string): Promise<string | undefined> {
const user = this.checkAndBlockUser("findStripeCustomerIdForTeam");
async findStripeSubscriptionIdForTeam(ctx: TraceContext, teamId: string): Promise<string | undefined> {
const user = this.checkAndBlockUser("findStripeSubscriptionIdForTeam");
await this.ensureIsUsageBasedFeatureFlagEnabled(user);
await this.guardTeamOperation(teamId, "update");
try {
const customer = await this.stripeService.findCustomerByTeamId(teamId);
return customer?.id || undefined;
if (!customer?.id) {
return undefined;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As in another PR, I think this should be returning NotFound and the client handling not found as No subscription exists.

Copy link
Contributor Author

@jankeromnes jankeromnes Jun 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Until now, I think we've had our API return something | undefined for such findSomething methods.

We could change this pattern to introduce 404 errors instead, but then maybe it would make sense to change all these methods?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Up to you. I'd mostly suggest we do this opportunistically on apis we work on as part of features.

Copy link
Contributor Author

@jankeromnes jankeromnes Jun 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up issue: #10892

}
const subscription = await this.stripeService.findUncancelledSubscriptionByCustomer(customer.id);
return subscription?.id;
} catch (error) {
log.error(`Failed to get Stripe Customer ID for team '${teamId}'`, error);
log.error(`Failed to get Stripe Subscription ID for team '${teamId}'`, error);
throw new ResponseError(
ErrorCodes.INTERNAL_SERVER_ERROR,
`Failed to get Stripe Customer ID for team '${teamId}'`,
`Failed to get Stripe Subscription ID for team '${teamId}'`,
);
}
}
Expand All @@ -1931,7 +1935,10 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
await this.guardTeamOperation(teamId, "update");
const team = await this.teamDB.findTeamById(teamId);
try {
const customer = await this.stripeService.createCustomerForTeam(user, team!, setupIntentId);
let customer = await this.stripeService.findCustomerByTeamId(team!.id);
if (!customer) {
customer = await this.stripeService.createCustomerForTeam(user, team!, setupIntentId);
}
Comment on lines +1938 to +1941
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems it is possible for 2 parallel requests to subscribeTeamToStripe to succeed and create 2 different subscriptions. Is this somehow transactional on the Stripe side?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for identifying this pre-existing problem! I don't think it can realistically happen, but I'm happy to open a follow-up issue about this if it seems important. 💡

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to solve in this PR. I would like an issue for this however. In the least, the Billing Controller (when listing subscriptions for a team) need to tell us there were more than 1 for a given TeamID so we can fix it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The controller already handles this case - https://github.com/gitpod-io/gitpod/pull/10854/files#diff-1f1047abea4ed15decb31dfdf94d84646a601fbacd5462dcef20f7f8b4de33dbR54 it will ignore any with multiple subscriptions and logs an error.

await this.stripeService.createSubscriptionForCustomer(customer.id, currency);
} catch (error) {
log.error(`Failed to subscribe team '${teamId}' to Stripe`, error);
Expand Down
2 changes: 1 addition & 1 deletion components/server/src/auth/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function getConfig(config: RateLimiterConfig): RateLimiterConfig {
tsReassignSlot: { group: "default", points: 1 },
getStripePublishableKey: { group: "default", points: 1 },
getStripeSetupIntentClientSecret: { group: "default", points: 1 },
findStripeCustomerIdForTeam: { group: "default", points: 1 },
findStripeSubscriptionIdForTeam: { group: "default", points: 1 },
subscribeTeamToStripe: { group: "default", points: 1 },
getStripePortalUrlForTeam: { group: "default", points: 1 },
trackEvent: { group: "default", points: 1 },
Expand Down
2 changes: 1 addition & 1 deletion components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3048,7 +3048,7 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
async getStripeSetupIntentClientSecret(ctx: TraceContext): Promise<string> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}
async findStripeCustomerIdForTeam(ctx: TraceContext, teamId: string): Promise<string | undefined> {
async findStripeSubscriptionIdForTeam(ctx: TraceContext, teamId: string): Promise<string | undefined> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}
async subscribeTeamToStripe(
Expand Down