Scheduling infrastructure for absolutely everyone.
feat: add free platform plan (#17581)
Morgan6889592d4f65
diff --git a/apps/api/v2/src/modules/billing/billing.processor.ts b/apps/api/v2/src/modules/billing/billing.processor.tsindex 68074711a66..f432998051b 100644--- a/apps/api/v2/src/modules/billing/billing.processor.ts+++ b/apps/api/v2/src/modules/billing/billing.processor.ts@@ -46,9 +46,9 @@ export class BillingProcessor {return;}- const stripeSubscription = await this.stripeService.stripe.subscriptions.retrieve(- billingSubscription.subscriptionId- );+ const stripeSubscription = await this.stripeService+ .getStripe()+ .subscriptions.retrieve(billingSubscription.subscriptionId);if (!stripeSubscription?.id) {this.logger.error(`Failed to retrieve stripe subscription (${billingSubscription.subscriptionId})`, {teamId,@@ -69,7 +69,7 @@ export class BillingProcessor {return;}- await this.stripeService.stripe.subscriptionItems.createUsageRecord(meteredItem.id, {+ await this.stripeService.getStripe().subscriptionItems.createUsageRecord(meteredItem.id, {action: "increment",quantity: 1,timestamp: "now",diff --git a/apps/api/v2/src/modules/billing/billing.repository.ts b/apps/api/v2/src/modules/billing/billing.repository.tsindex 656e07b61a0..87fc4eb63f1 100644--- a/apps/api/v2/src/modules/billing/billing.repository.ts+++ b/apps/api/v2/src/modules/billing/billing.repository.ts@@ -1,10 +1,11 @@import { PlatformPlan } from "@/modules/billing/types";import { PrismaReadService } from "@/modules/prisma/prisma-read.service";import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";-import { Injectable } from "@nestjs/common";+import { Injectable, Logger } from "@nestjs/common";@Injectable()export class BillingRepository {+ private readonly logger = new Logger("BillingRepository");constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}getBillingForTeam = (teamId: number) =>@@ -30,6 +31,35 @@ export class BillingRepository {billingCycleEnd: billingEnd,subscriptionId,plan: plan.toString(),+ overdue: false,+ },+ });+ }++ async updateBillingOverdue(subId: string, cusId: string, overdue: boolean) {+ try {+ return this.dbWrite.prisma.platformBilling.update({+ where: {+ subscriptionId: subId,+ customerId: cusId,+ },+ data: {+ overdue,+ },+ });+ } catch (err) {+ this.logger.error("Could not update billing overdue", {+ subId,+ cusId,+ err,+ });+ }+ }++ async deleteBilling(id: number) {+ return this.dbWrite.prisma.platformBilling.delete({+ where: {+ id,},});}diff --git a/apps/api/v2/src/modules/billing/controllers/billing.controller.e2e-spec.ts b/apps/api/v2/src/modules/billing/controllers/billing.controller.e2e-spec.tsnew file mode 100644index 00000000000..db83acd38e7--- /dev/null+++ b/apps/api/v2/src/modules/billing/controllers/billing.controller.e2e-spec.ts@@ -0,0 +1,211 @@+import { bootstrap } from "@/app";+import { AppModule } from "@/app.module";+import { PrismaModule } from "@/modules/prisma/prisma.module";+import { StripeService } from "@/modules/stripe/stripe.service";+import { TokensModule } from "@/modules/tokens/tokens.module";+import { UsersModule } from "@/modules/users/users.module";+import { UserWithProfile } from "@/modules/users/users.repository";+import { INestApplication } from "@nestjs/common";+import { NestExpressApplication } from "@nestjs/platform-express";+import { Test } from "@nestjs/testing";+import Stripe from "stripe";+import * as request from "supertest";+import { PlatformBillingRepositoryFixture } from "test/fixtures/repository/billing.repository.fixture";+import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";+import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";+import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";+import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";+import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";+import { withApiAuth } from "test/utils/withApiAuth";++import { Team, PlatformOAuthClient, PlatformBilling } from "@calcom/prisma/client";++describe("Platform Billing Controller (e2e)", () => {+ let app: INestApplication;+ const userEmail = "[email protected]";+ let user: UserWithProfile;+ let billing: PlatformBilling;+ let userRepositoryFixture: UserRepositoryFixture;+ let organizationsRepositoryFixture: OrganizationRepositoryFixture;+ let profileRepositoryFixture: ProfileRepositoryFixture;+ let membershipsRepositoryFixture: MembershipRepositoryFixture;+ let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;+ let oAuthClient: PlatformOAuthClient;+ let platformBillingRepositoryFixture: PlatformBillingRepositoryFixture;+ let organization: Team;++ beforeAll(async () => {+ const moduleRef = await withApiAuth(+ userEmail,+ Test.createTestingModule({+ imports: [AppModule, PrismaModule, UsersModule, TokensModule],+ })+ ).compile();+ userRepositoryFixture = new UserRepositoryFixture(moduleRef);+ organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);+ profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);+ oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);+ membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);+ platformBillingRepositoryFixture = new PlatformBillingRepositoryFixture(moduleRef);+ organization = await organizationsRepositoryFixture.create({ name: "platform billing" });++ user = await userRepositoryFixture.create({+ email: userEmail,+ username: userEmail,+ });++ await profileRepositoryFixture.create({+ uid: `usr-${user.id}`,+ username: userEmail,+ organization: {+ connect: {+ id: organization.id,+ },+ },+ user: {+ connect: {+ id: user.id,+ },+ },+ });+ await membershipsRepositoryFixture.create({+ role: "OWNER",+ team: { connect: { id: organization.id } },+ user: { connect: { id: user.id } },+ accepted: true,+ });++ billing = await platformBillingRepositoryFixture.create(organization.id);++ app = moduleRef.createNestApplication();+ bootstrap(app as NestExpressApplication);++ await app.init();+ });++ afterAll(async () => {+ userRepositoryFixture.deleteByEmail(user.email);+ await app.close();+ });++ it("/billing/webhook (POST) should set billing free plan for org", () => {+ jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(+ () =>+ ({+ webhooks: {+ constructEventAsync: async () => {+ return {+ type: "checkout.session.completed",+ data: {+ object: {+ metadata: {+ teamId: organization.id,+ plan: "FREE",+ },+ mode: "subscription",+ },+ },+ };+ },+ },+ } as unknown as Stripe)+ );++ return request(app.getHttpServer())+ .post("/v2/billing/webhook")+ .expect(200)+ .then(async (res) => {+ const billing = await platformBillingRepositoryFixture.get(organization.id);+ expect(billing?.plan).toEqual("FREE");+ });+ });+ it("/billing/webhook (POST) failed payment should set billing free plan to overdue", () => {+ jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(+ () =>+ ({+ webhooks: {+ constructEventAsync: async () => {+ return {+ type: "invoice.payment_failed",+ data: {+ object: {+ customer: billing?.customerId,+ subscription: billing?.subscriptionId,+ },+ },+ };+ },+ },+ } as unknown as Stripe)+ );++ return request(app.getHttpServer())+ .post("/v2/billing/webhook")+ .expect(200)+ .then(async (res) => {+ const billing = await platformBillingRepositoryFixture.get(organization.id);+ expect(billing?.overdue).toEqual(true);+ });+ });++ it("/billing/webhook (POST) success payment should set billing free plan to not overdue", () => {+ jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(+ () =>+ ({+ webhooks: {+ constructEventAsync: async () => {+ return {+ type: "invoice.payment_succeeded",+ data: {+ object: {+ customer: billing?.customerId,+ subscription: billing?.subscriptionId,+ },+ },+ };+ },+ },+ } as unknown as Stripe)+ );++ return request(app.getHttpServer())+ .post("/v2/billing/webhook")+ .expect(200)+ .then(async (res) => {+ const billing = await platformBillingRepositoryFixture.get(organization.id);+ expect(billing?.overdue).toEqual(false);+ });+ });++ it("/billing/webhook (POST) should delete subscription", () => {+ jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(+ () =>+ ({+ webhooks: {+ constructEventAsync: async () => {+ return {+ type: "customer.subscription.deleted",+ data: {+ object: {+ metadata: {+ teamId: organization.id,+ plan: "FREE",+ },+ id: billing?.subscriptionId,+ },+ },+ };+ },+ },+ } as unknown as Stripe)+ );++ return request(app.getHttpServer())+ .post("/v2/billing/webhook")+ .expect(200)+ .then(async (res) => {+ const billing = await platformBillingRepositoryFixture.get(organization.id);+ expect(billing).toBeNull();+ });+ });+});diff --git a/apps/api/v2/src/modules/billing/controllers/billing.controller.ts b/apps/api/v2/src/modules/billing/controllers/billing.controller.tsindex 40d3e287b32..f348c18ec5c 100644--- a/apps/api/v2/src/modules/billing/controllers/billing.controller.ts+++ b/apps/api/v2/src/modules/billing/controllers/billing.controller.ts@@ -102,13 +102,26 @@ export class BillingController {@Req() request: Request,@Headers("stripe-signature") stripeSignature: string): Promise<ApiResponse> {- const event = await this.billingService.stripeService.stripe.webhooks.constructEventAsync(- request.body,- stripeSignature,- this.stripeWhSecret- );+ const event = await this.billingService.stripeService+ .getStripe()+ .webhooks.constructEventAsync(request.body, stripeSignature, this.stripeWhSecret);- await this.billingService.createOrUpdateStripeSubscription(event);+ switch (event.type) {+ case "checkout.session.completed":+ await this.billingService.handleStripeCheckoutEvents(event);+ break;+ case "customer.subscription.deleted":+ await this.billingService.handleStripeSubscriptionDeleted(event);+ break;+ case "invoice.payment_failed":+ await this.billingService.handleStripePaymentFailed(event);+ break;+ case "invoice.payment_succeeded":+ await this.billingService.handleStripePaymentSuccess(event);+ break;+ default:+ break;+ }return {status: "success",diff --git a/apps/api/v2/src/modules/billing/services/billing.service.ts b/apps/api/v2/src/modules/billing/services/billing.service.tsindex bf25bc0c9e4..95088ccad53 100644--- a/apps/api/v2/src/modules/billing/services/billing.service.ts+++ b/apps/api/v2/src/modules/billing/services/billing.service.ts@@ -64,7 +64,7 @@ export class BillingService implements OnModuleDestroy {}async redirectToSubscribeCheckout(teamId: number, plan: PlatformPlan, customerId?: string) {- const { url } = await this.stripeService.stripe.checkout.sessions.create({+ const { url } = await this.stripeService.getStripe().checkout.sessions.create({customer: customerId,line_items: [{@@ -101,7 +101,7 @@ export class BillingService implements OnModuleDestroy {const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);const customerId = teamWithBilling?.platformBilling?.customerId;- const { url } = await this.stripeService.stripe.checkout.sessions.create({+ const { url } = await this.stripeService.getStripe().checkout.sessions.create({customer: customerId,success_url: `${this.webAppUrl}/settings/platform/`,cancel_url: `${this.webAppUrl}/settings/platform/plans`,@@ -131,41 +131,92 @@ export class BillingService implements OnModuleDestroy {);}- async createOrUpdateStripeSubscription(event: Stripe.Event) {- if (event.type === "checkout.session.completed") {- const subscription = event.data.object as Stripe.Checkout.Session;-- if (!subscription.metadata?.teamId) {- return {- status: "success",- };+ async handleStripeSubscriptionDeleted(event: Stripe.Event) {+ const subscription = event.data.object as Stripe.Subscription;+ const teamId = subscription?.metadata?.teamId;+ const plan = PlatformPlan[subscription?.metadata?.plan?.toUpperCase() as keyof typeof PlatformPlan];+ if (teamId && plan) {+ const currentBilling = await this.billingRepository.getBillingForTeam(Number.parseInt(teamId));+ if (currentBilling?.subscriptionId === subscription.id) {+ await this.billingRepository.deleteBilling(currentBilling.id);+ this.logger.log(`Stripe Subscription deleted`, {+ customerId: currentBilling.customerId,+ subscriptionId: currentBilling.subscriptionId,+ teamId,+ });+ return;}+ this.logger.log("No platform billing found.");+ return;+ }+ this.logger.log("Webhook received but not pertaining to Platform, discarding.");+ return;+ }- const teamId = Number.parseInt(subscription.metadata.teamId);- const plan = subscription.metadata.plan;- if (!plan || !teamId) {- this.logger.log("Webhook received but not pertaining to Platform, discarding.");- return {- status: "success",- };- }+ getSubscriptionIdFromInvoice(invoice: Stripe.Invoice): string | null {+ if (typeof invoice.subscription === "string") {+ return invoice.subscription;+ } else if (invoice.subscription && typeof invoice.subscription === "object") {+ return invoice.subscription.id;+ } else {+ return null;+ }+ }+ getCustomerIdFromInvoice(invoice: Stripe.Invoice): string | null {+ if (typeof invoice.customer === "string") {+ return invoice.customer;+ } else if (invoice.customer && typeof invoice.customer === "object") {+ return invoice.customer.id;+ } else {+ return null;+ }+ }- if (subscription.mode === "subscription") {- await this.setSubscriptionForTeam(- teamId,- subscription.subscription as string,- PlatformPlan[plan.toUpperCase() as keyof typeof PlatformPlan]- );- }+ async handleStripePaymentSuccess(event: Stripe.Event) {+ const invoice = event.data.object as Stripe.Invoice;+ const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);+ const customerId = this.getCustomerIdFromInvoice(invoice);+ if (subscriptionId && customerId) {+ await this.billingRepository.updateBillingOverdue(subscriptionId, customerId, false);+ }+ }- if (subscription.mode === "setup") {- await this.updateStripeSubscriptionForTeam(teamId, plan as PlatformPlan);- }+ async handleStripePaymentFailed(event: Stripe.Event) {+ const invoice = event.data.object as Stripe.Invoice;+ const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);+ const customerId = this.getCustomerIdFromInvoice(invoice);+ if (subscriptionId && customerId) {+ await this.billingRepository.updateBillingOverdue(subscriptionId, customerId, true);+ }+ }- return {- status: "success",- };+ async handleStripeCheckoutEvents(event: Stripe.Event) {+ const checkoutSession = event.data.object as Stripe.Checkout.Session;++ if (!checkoutSession.metadata?.teamId) {+ return;+ }++ const teamId = Number.parseInt(checkoutSession.metadata.teamId);+ const plan = checkoutSession.metadata.plan;+ if (!plan || !teamId) {+ this.logger.log("Webhook received but not pertaining to Platform, discarding.");+ return;+ }++ if (checkoutSession.mode === "subscription") {+ await this.setSubscriptionForTeam(+ teamId,+ checkoutSession.subscription as string,+ PlatformPlan[plan.toUpperCase() as keyof typeof PlatformPlan]+ );}++ if (checkoutSession.mode === "setup") {+ await this.updateStripeSubscriptionForTeam(teamId, plan as PlatformPlan);+ }++ return;}async updateStripeSubscriptionForTeam(teamId: number, plan: PlatformPlan) {@@ -175,9 +226,9 @@ export class BillingService implements OnModuleDestroy {throw new NotFoundException("Team plan not found");}- const existingUserSubscription = await this.stripeService.stripe.subscriptions.retrieve(- teamWithBilling?.platformBilling?.subscriptionId- );+ const existingUserSubscription = await this.stripeService+ .getStripe()+ .subscriptions.retrieve(teamWithBilling?.platformBilling?.subscriptionId);const currentLicensedItem = existingUserSubscription.items.data.find((item) => item.price?.recurring?.usage_type === "licensed");@@ -193,21 +244,23 @@ export class BillingService implements OnModuleDestroy {throw new NotFoundException("There is no overage item present in the subscription");}- await this.stripeService.stripe.subscriptions.update(teamWithBilling?.platformBilling?.subscriptionId, {- items: [- {- id: currentLicensedItem.id,- price: this.billingConfigService.get(plan)?.base,- },- {- id: currentOverageItem.id,- price: this.billingConfigService.get(plan)?.overage,- clear_usage: false,- },- ],- billing_cycle_anchor: "now",- proration_behavior: "create_prorations",- });+ await this.stripeService+ .getStripe()+ .subscriptions.update(teamWithBilling?.platformBilling?.subscriptionId, {+ items: [+ {+ id: currentLicensedItem.id,+ price: this.billingConfigService.get(plan)?.base,+ },+ {+ id: currentOverageItem.id,+ price: this.billingConfigService.get(plan)?.overage,+ clear_usage: false,+ },+ ],+ billing_cycle_anchor: "now",+ proration_behavior: "create_prorations",+ });await this.setSubscriptionForTeam(teamId,diff --git a/apps/api/v2/src/modules/billing/types.ts b/apps/api/v2/src/modules/billing/types.tsindex ea19f6cddea..d46928613be 100644--- a/apps/api/v2/src/modules/billing/types.ts+++ b/apps/api/v2/src/modules/billing/types.ts@@ -1,8 +1,9 @@export enum PlatformPlan {+ FREE = "FREE",STARTER = "STARTER",ESSENTIALS = "ESSENTIALS",SCALE = "SCALE",ENTERPRISE = "ENTERPRISE",}-export type PlatformPlanType = "STARTER" | "ESSENTIALS" | "SCALE" | "ENTERPRISE";+export type PlatformPlanType = "FREE" | "STARTER" | "ESSENTIALS" | "SCALE" | "ENTERPRISE";diff --git a/apps/api/v2/src/modules/organizations/organizations.repository.ts b/apps/api/v2/src/modules/organizations/organizations.repository.tsindex ecfa298ab3f..1af8e365b88 100644--- a/apps/api/v2/src/modules/organizations/organizations.repository.ts+++ b/apps/api/v2/src/modules/organizations/organizations.repository.ts@@ -33,7 +33,7 @@ export class OrganizationsRepository {}async createNewBillingRelation(orgId: number, plan?: PlatformPlan) {- const { id } = await this.stripeService.stripe.customers.create({+ const { id } = await this.stripeService.getStripe().customers.create({metadata: {createdBy: "oauth_client_no_csid", // mark in case this is needed in the future.},diff --git a/apps/api/v2/src/modules/stripe/stripe.service.ts b/apps/api/v2/src/modules/stripe/stripe.service.tsindex dd4f89800b7..ab8274a3453 100644--- a/apps/api/v2/src/modules/stripe/stripe.service.ts+++ b/apps/api/v2/src/modules/stripe/stripe.service.ts@@ -28,7 +28,7 @@ type IntegrationOAuthCallbackState = {@Injectable()export class StripeService {- public stripe: Stripe;+ private stripe: Stripe;private redirectUri = `${this.config.get("api.url")}/stripe/save`;constructor(@@ -44,6 +44,10 @@ export class StripeService {});}+ getStripe() {+ return this.stripe;+ }+async getStripeRedirectUrl(state: string, userEmail?: string, userName?: string | null) {const { client_id } = await this.getStripeAppKeys();diff --git a/apps/api/v2/swagger/documentation.json b/apps/api/v2/swagger/documentation.jsonindex 908bcd52fdb..17fb8141ea6 100644--- a/apps/api/v2/swagger/documentation.json+++ b/apps/api/v2/swagger/documentation.json@@ -5033,6 +5033,37 @@]}},+ "/v2/stripe/check/{teamId}": {+ "get": {+ "operationId": "StripeController_checkTeamStripeConnection",+ "summary": "Check team stripe connection",+ "parameters": [+ {+ "name": "teamId",+ "required": true,+ "in": "path",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StripCredentialsCheckOutputResponseDto"+ }+ }+ }+ }+ },+ "tags": [+ "Stripe"+ ]+ }+ },"/v2/timezones": {"get": {"operationId": "TimezonesController_getTimeZones",diff --git a/apps/api/v2/test/fixtures/repository/billing.repository.fixture.ts b/apps/api/v2/test/fixtures/repository/billing.repository.fixture.tsindex a999ec670c8..40565399218 100644--- a/apps/api/v2/test/fixtures/repository/billing.repository.fixture.ts+++ b/apps/api/v2/test/fixtures/repository/billing.repository.fixture.ts@@ -23,6 +23,14 @@ export class PlatformBillingRepositoryFixture {});}+ async get(orgId: number) {+ return this.prismaWriteClient.platformBilling.findFirst({+ where: {+ id: orgId,+ },+ });+ }+async deleteSubscriptionForTeam(teamId: number) {// silently try to delete the subscriptiontry {diff --git a/apps/web/components/settings/platform/platformUtils.ts b/apps/web/components/settings/platform/platformUtils.tsindex db0a5747132..2b39b96c9df 100644--- a/apps/web/components/settings/platform/platformUtils.ts+++ b/apps/web/components/settings/platform/platformUtils.ts@@ -8,12 +8,12 @@ type IndividualPlatformPlan = {// if pricing or plans change in future modify thisexport const platformPlans: IndividualPlatformPlan[] = [{- plan: "Starter",+ plan: "Free",description:- "Perfect for just getting started with community support and access to hosted platform APIs, Cal.com Atoms (React components) and more.",- pricing: 99,+ "The best plan to dip your toes into scheduling infrastructure. Start immediately with 25 free meetings per month",+ pricing: 0,includes: [- "Up to 100 bookings a month",+ "Up to 25 bookings a month","$0.99 overage beyond","Community Support","Cal Atoms (React Library)",diff --git a/apps/web/components/settings/platform/pricing/billing-card/index.tsx b/apps/web/components/settings/platform/pricing/billing-card/index.tsxindex 5552af4ac9b..b3dff623c87 100644--- a/apps/web/components/settings/platform/pricing/billing-card/index.tsx+++ b/apps/web/components/settings/platform/pricing/billing-card/index.tsx@@ -37,7 +37,7 @@ export const PlatformBillingCard = ({</h1><p className="pb-5 pt-3 text-base">{description}</p><h1 className="text-3xl font-semibold">- {pricing && (+ {pricing !== undefined && (<>US${pricing} <span className="text-sm">per month</span></>@@ -50,7 +50,7 @@ export const PlatformBillingCard = ({loading={isLoading}onClick={handleSubscribe}className="flex w-[100%] items-center justify-center">- {pricing ? "Subscribe" : "Schedule a time"}+ {pricing !== undefined ? "Subscribe" : "Schedule a time"}</Button></div>)}diff --git a/apps/web/lib/settings/platform/utils.ts b/apps/web/lib/settings/platform/utils.tsindex 3f67d22520b..f3093835e2c 100644--- a/apps/web/lib/settings/platform/utils.ts+++ b/apps/web/lib/settings/platform/utils.ts@@ -21,12 +21,13 @@ type HelpCardInfo = {// if pricing or plans change in future modify thisexport const platformPlans: IndividualPlatformPlan[] = [{- plan: "Starter",+ plan: "Free",description:- "Perfect for just getting started with community support and access to hosted platform APIs, Cal.com Atoms (React components) and more.",- pricing: 99,+ "The best plan to dip your toes into scheduling infrastructure. Start immediately with 25 free meetings per month",+ pricing: 0,includes: [- "Up to 100 bookings a month",+ "Up to 25 bookings a month",+ "$0.99 overage beyond","Community Support","Cal Atoms (React Library)","Platform APIs",