* feat: add BillingCacheService with 1-hour TTL for team subscription data - Create BillingCacheService following CalendarsCacheService pattern - Use teamId-based cache keys with 1-hour TTL (3,600,000 ms) - Integrate caching into getBillingData method in BillingService - Add cache invalidation to all webhook handlers: - handleStripeSubscriptionDeleted - handleStripePaymentSuccess - handleStripePaymentFailed - handleStripePaymentPastDue - handleStripeCheckoutEvents - Add cache invalidation to cancelTeamSubscription method - Add RedisModule import to billing module - Add BillingCacheService to billing module providers - Add findTeamByPlatformBillingId method to OrganizationsRepository for cache invalidation Co-Authored-By: [email protected] <[email protected]> * refactor: implement BillingServiceCachingProxy pattern - Extract IBillingService interface with all public methods - Create BillingServiceCachingProxy that implements caching logic - Remove all caching logic from original BillingService - Simplify cache invalidation using billing.id = team.id - Update module to use proxy with proper dependency injection - Update controller to inject proxy interface - Remove unused BillingService import from controller This follows the proxy pattern requested in PR feedback, separating caching concerns from core billing logic for better maintainability. Co-Authored-By: [email protected] <[email protected]> * chore: add e2e for billing check * chore: eslint rule for blocking importing features from appstore, lib, prisma (#23832) * eslint rule * improve * fix * improve msg * chore: fix any types set by devin * fix: add mising expect in test * refactor: move cache methods into BillingServiceCachingProxy - Remove BillingCacheService abstraction as suggested by @keithwillcode - Move cache methods directly into proxy as private methods - Update proxy to inject RedisService directly - Move BillingData type to interface for better type safety - Remove BillingCacheService from module providers - Delete unused billing-cache.service.ts file This simplifies the architecture by removing unnecessary abstraction and follows standard caching proxy patterns. Co-Authored-By: [email protected] <[email protected]> * fix: test and legacy starter --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: [email protected] <[email protected]> Co-authored-by: Benny Joo <[email protected]> Co-authored-by: Morgan <[email protected]>
178 lines
5.5 KiB
TypeScript
178 lines
5.5 KiB
TypeScript
import { AppConfig } from "@/config/type";
|
|
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
|
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
|
|
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
|
|
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
|
|
import { SubscribeToPlanInput } from "@/modules/billing/controllers/inputs/subscribe-to-plan.input";
|
|
import { CheckPlatformBillingResponseDto } from "@/modules/billing/controllers/outputs/CheckPlatformBillingResponse.dto";
|
|
import { SubscribeTeamToBillingResponseDto } from "@/modules/billing/controllers/outputs/SubscribeTeamToBillingResponse.dto";
|
|
import { IBillingService } from "@/modules/billing/interfaces/billing-service.interface";
|
|
import { StripeService } from "@/modules/stripe/stripe.service";
|
|
import {
|
|
Body,
|
|
Controller,
|
|
Get,
|
|
Param,
|
|
Post,
|
|
Req,
|
|
UseGuards,
|
|
Headers,
|
|
HttpCode,
|
|
HttpStatus,
|
|
Inject,
|
|
Logger,
|
|
Delete,
|
|
ParseIntPipe,
|
|
} from "@nestjs/common";
|
|
import { ConfigService } from "@nestjs/config";
|
|
import { ApiExcludeController } from "@nestjs/swagger";
|
|
import { Request } from "express";
|
|
import Stripe from "stripe";
|
|
|
|
import { ApiResponse } from "@calcom/platform-types";
|
|
|
|
@Controller({
|
|
path: "/v2/billing",
|
|
version: API_VERSIONS_VALUES,
|
|
})
|
|
@ApiExcludeController(true)
|
|
export class BillingController {
|
|
private readonly stripeWhSecret: string;
|
|
private logger = new Logger("Billing Controller");
|
|
|
|
constructor(
|
|
@Inject("IBillingService") private readonly billingService: IBillingService,
|
|
public readonly stripeService: StripeService,
|
|
private readonly configService: ConfigService<AppConfig>
|
|
) {
|
|
this.stripeWhSecret = configService.get("stripe.webhookSecret", { infer: true }) ?? "";
|
|
}
|
|
|
|
@Get("/:teamId/check")
|
|
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
|
|
@MembershipRoles(["OWNER", "ADMIN", "MEMBER"])
|
|
async checkTeamBilling(
|
|
@Param("teamId", ParseIntPipe) teamId: number
|
|
): Promise<ApiResponse<CheckPlatformBillingResponseDto>> {
|
|
const { status, plan } = await this.billingService.getBillingData(teamId);
|
|
|
|
return {
|
|
status: "success",
|
|
data: {
|
|
valid: status === "valid",
|
|
plan,
|
|
},
|
|
};
|
|
}
|
|
|
|
@Post("/:teamId/subscribe")
|
|
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
|
|
@MembershipRoles(["OWNER", "ADMIN"])
|
|
async subscribeTeamToStripe(
|
|
@Param("teamId") teamId: number,
|
|
@Body() input: SubscribeToPlanInput
|
|
): Promise<ApiResponse<SubscribeTeamToBillingResponseDto | undefined>> {
|
|
const customerId = await this.billingService.createTeamBilling(teamId);
|
|
const url = await this.billingService.redirectToSubscribeCheckout(teamId, input.plan, customerId);
|
|
|
|
return {
|
|
status: "success",
|
|
data: {
|
|
url,
|
|
},
|
|
};
|
|
}
|
|
|
|
@Post("/:teamId/upgrade")
|
|
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
|
|
@MembershipRoles(["OWNER", "ADMIN"])
|
|
async upgradeTeamBillingInStripe(
|
|
@Param("teamId") teamId: number,
|
|
@Body() input: SubscribeToPlanInput
|
|
): Promise<ApiResponse<SubscribeTeamToBillingResponseDto | undefined>> {
|
|
const url = await this.billingService.updateSubscriptionForTeam(teamId, input.plan);
|
|
|
|
return {
|
|
status: "success",
|
|
data: {
|
|
url,
|
|
},
|
|
};
|
|
}
|
|
|
|
@Delete("/:organizationId/unsubscribe")
|
|
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
|
|
@MembershipRoles(["OWNER", "ADMIN"])
|
|
async cancelTeamSubscriptionInStripe(
|
|
@Param("organizationId") organizationId: number
|
|
): Promise<ApiResponse> {
|
|
await this.billingService.cancelTeamSubscription(organizationId);
|
|
|
|
return {
|
|
status: "success",
|
|
};
|
|
}
|
|
|
|
@Post("/webhook")
|
|
@HttpCode(HttpStatus.OK)
|
|
async stripeWebhook(
|
|
@Req() request: Request,
|
|
@Headers("stripe-signature") stripeSignature: string
|
|
): Promise<ApiResponse> {
|
|
try {
|
|
if (!stripeSignature) {
|
|
this.logger.warn("Missing stripe-signature header in webhook request");
|
|
return {
|
|
status: "success",
|
|
};
|
|
}
|
|
|
|
if (!this.stripeWhSecret) {
|
|
this.logger.error("Missing STRIPE_WEBHOOK_SECRET configuration");
|
|
return {
|
|
status: "success",
|
|
};
|
|
}
|
|
|
|
const event = await this.billingService.stripeService
|
|
.getStripe()
|
|
.webhooks.constructEventAsync(request.body, stripeSignature, this.stripeWhSecret);
|
|
|
|
switch (event.type) {
|
|
case "checkout.session.completed":
|
|
await this.billingService.handleStripeCheckoutEvents(event);
|
|
break;
|
|
case "customer.subscription.updated":
|
|
await this.billingService.handleStripePaymentPastDue(event);
|
|
break;
|
|
case "customer.subscription.deleted":
|
|
await this.billingService.handleStripeSubscriptionDeleted(event);
|
|
break;
|
|
case "invoice.created":
|
|
await this.billingService.handleStripeSubscriptionForActiveManagedUsers(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",
|
|
};
|
|
} catch (error) {
|
|
if (error instanceof Stripe.errors.StripeSignatureVerificationError) {
|
|
this.logger.error("Webhook signature validation failed", error);
|
|
return {
|
|
status: "success",
|
|
};
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
}
|