Skip to content
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

When creating a new Stripe customer, also create a Usage-Based Subscription for them #10630

Merged
merged 1 commit into from
Jun 14, 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
4 changes: 2 additions & 2 deletions components/dashboard/src/teams/TeamUsageBasedBilling.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default function TeamUsageBasedBilling() {
const { teams } = useContext(TeamsContext);
const location = useLocation();
const team = getCurrentTeam(location, teams);
const { showUsageBasedUI } = useContext(PaymentContext);
const { showUsageBasedUI, currency } = useContext(PaymentContext);
jankeromnes marked this conversation as resolved.
Show resolved Hide resolved
const [stripeCustomerId, setStripeCustomerId] = useState<string | undefined>();
const [isLoading, setIsLoading] = useState<boolean>(true);
const [showBillingSetupModal, setShowBillingSetupModal] = useState<boolean>(false);
Expand Down Expand Up @@ -68,7 +68,7 @@ export default function TeamUsageBasedBilling() {
(async () => {
const setupIntentId = params.get("setup_intent")!;
window.history.replaceState({}, "", window.location.pathname);
await getGitpodService().server.subscribeTeamToStripe(team.id, setupIntentId);
await getGitpodService().server.subscribeTeamToStripe(team.id, setupIntentId, currency);
const pendingCustomer = { pendingSince: Date.now() };
setPendingStripeCustomer(pendingCustomer);
window.localStorage.setItem(`pendingStripeCustomerForTeam${team.id}`, JSON.stringify(pendingCustomer));
Expand Down
3 changes: 2 additions & 1 deletion components/gitpod-protocol/src/gitpod-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
import { RemotePageMessage, RemoteTrackMessage, RemoteIdentifyMessage } from "./analytics";
import { IDEServer } from "./ide-protocol";
import { InstallationAdminSettings, TelemetryData } from "./installation-admin-protocol";
import { Currency } from "./plans";

export interface GitpodClient {
onInstanceUpdate(instance: WorkspaceInstance): void;
Expand Down Expand Up @@ -273,7 +274,7 @@ export interface GitpodServer extends JsonRpcServer<GitpodClient>, AdminServer,
getStripePublishableKey(): Promise<string>;
getStripeSetupIntentClientSecret(): Promise<string>;
findStripeCustomerIdForTeam(teamId: string): Promise<string | undefined>;
subscribeTeamToStripe(teamId: string, setupIntentId: string): Promise<void>;
subscribeTeamToStripe(teamId: string, setupIntentId: string, currency: Currency): Promise<void>;
getStripePortalUrlForTeam(teamId: string): Promise<string>;

/**
Expand Down
16 changes: 16 additions & 0 deletions components/server/ee/src/user/stripe-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { inject, injectable } from "inversify";
import Stripe from "stripe";
import { Team, User } from "@gitpod/gitpod-protocol";
import { Currency } from "@gitpod/gitpod-protocol/lib/plans";
import { Config } from "../../../src/config";

@injectable()
Expand Down Expand Up @@ -113,4 +114,19 @@ export class StripeService {
});
return session.url;
}

async createSubscriptionForCustomer(customerId: string, currency: Currency): Promise<void> {
// FIXME(janx): Use configmap.
const prices = {
EUR: "price_1LAE0AGadRXm50o3xjegX0Kd",
USD: "price_1LAE0AGadRXm50o3rKoktPiJ",
};
Comment on lines +119 to +123
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you create an issue for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure! #10655

const startOfNextMonth = new Date(new Date().toISOString().slice(0, 7) + "-01"); // First day of this month (YYYY-MM-01)
startOfNextMonth.setMonth(startOfNextMonth.getMonth() + 1); // Add one month
await this.getStripe().subscriptions.create({
customer: customerId,
items: [{ price: prices[currency] }],
billing_cycle_anchor: Math.round(startOfNextMonth.getTime() / 1000),
});
}
}
13 changes: 9 additions & 4 deletions components/server/ee/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ import {
TeamSubscriptionSlot,
TeamSubscriptionSlotResolved,
} from "@gitpod/gitpod-protocol/lib/team-subscription-protocol";
import { Plans } from "@gitpod/gitpod-protocol/lib/plans";
import { Currency, Plans } from "@gitpod/gitpod-protocol/lib/plans";
import * as pThrottle from "p-throttle";
import { formatDate } from "@gitpod/gitpod-protocol/lib/util/date-time";
import { FindUserByIdentityStrResult, UserService } from "../../../src/user/user-service";
Expand Down Expand Up @@ -1892,14 +1892,19 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
}
}

async subscribeTeamToStripe(ctx: TraceContext, teamId: string, setupIntentId: string): Promise<void> {
async subscribeTeamToStripe(
ctx: TraceContext,
teamId: string,
setupIntentId: string,
currency: Currency,
): Promise<void> {
const user = this.checkAndBlockUser("subscribeUserToStripe");
await this.ensureIsUsageBasedFeatureFlagEnabled(user);
await this.guardTeamOperation(teamId, "update");
const team = await this.teamDB.findTeamById(teamId);
try {
await this.stripeService.createCustomerForTeam(user, team!, setupIntentId);
// TODO(janx): Create a Stripe usage-based Subscription for the customer
const customer = await this.stripeService.createCustomerForTeam(user, team!, setupIntentId);
await this.stripeService.createSubscriptionForCustomer(customer.id, currency);
} catch (error) {
log.error(`Failed to subscribe team '${teamId}' to Stripe`, error);
throw new ResponseError(ErrorCodes.INTERNAL_SERVER_ERROR, `Failed to subscribe team '${teamId}' to Stripe`);
Expand Down
8 changes: 7 additions & 1 deletion components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ import { InstallationAdminTelemetryDataProvider } from "../installation-admin/te
import { LicenseEvaluator } from "@gitpod/licensor/lib";
import { Feature } from "@gitpod/licensor/lib/api";
import { getExperimentsClient } from "../experiments";
import { Currency } from "@gitpod/gitpod-protocol/lib/plans";

// shortcut
export const traceWI = (ctx: TraceContext, wi: Omit<LogContext, "userId">) => TraceContext.setOWI(ctx, wi); // userId is already taken care of in WebsocketConnectionManager
Expand Down Expand Up @@ -3042,7 +3043,12 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
async findStripeCustomerIdForTeam(ctx: TraceContext, teamId: string): Promise<string | undefined> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}
async subscribeTeamToStripe(ctx: TraceContext, teamId: string, setupIntentId: string): Promise<void> {
async subscribeTeamToStripe(
ctx: TraceContext,
teamId: string,
setupIntentId: string,
currency: Currency,
): Promise<void> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}
async getStripePortalUrlForTeam(ctx: TraceContext, teamId: string): Promise<string> {
Expand Down