feat: add PlatformOrganizationBillingTasker with sync and trigger.dev versions (#26803)
* feat: add PlatformOrganizationBillingTasker with sync and trigger.dev versions - Create PlatformOrganizationBillingTasker extending Tasker base class - Add sync tasker (PlatformOrganizationBillingSyncTasker) for synchronous execution - Add trigger.dev tasker (PlatformOrganizationBillingTriggerTasker) for async execution - Create trigger.dev task for incrementing subscription usage - Add PlatformOrganizationBillingTaskService with business logic - Add PlatformOrganizationBillingRepository for data access - Add createSubscriptionUsageRecord method to StripeBillingService - Follow BookingEmailAndSmsTasker pattern for consistency Co-Authored-By: [email protected] <[email protected]> * refactor: move repository methods per PR feedback - Move findPlatformOrgByUserId to OrganizationRepository - Create new PlatformBillingRepository for billing queries - Remove PlatformOrganizationBillingRepository (consolidated) - Update task service and trigger.dev task to use new repositories Co-Authored-By: [email protected] <[email protected]> * feat: add DI using @evyweb/ioctopus for platform billing tasker - Create di/tasker/ directory following BookingEmailAndSmsTasker pattern - Add tokens.ts with DI tokens for all billing tasker classes - Add module files for PlatformBillingRepository, TaskService, SyncTasker, TriggerTasker, Tasker - Add container files with getter functions - Update trigger.dev task to use DI container instead of manual instantiation Co-Authored-By: [email protected] <[email protected]> * refactor: add select statement to PlatformBillingRepository.findByTeamId Only select subscriptionId field since that's the only field used by the task service Co-Authored-By: [email protected] <[email protected]> * feat: add NestJS DI modules for platform billing tasker in API v2 - Add platform billing tasker exports to platform-libraries/organizations.ts - Export IBillingProviderService type from platform-libraries - Create StripeBillingProviderService wrapper implementing IBillingProviderService - Create PrismaPlatformBillingRepository extending PlatformBillingRepository - Create NestJS service wrappers for all platform billing tasker classes - Create PlatformBillingTaskerModule with all providers and exports - Update PlatformOrganizationBillingTaskService to use Pick<IBillingProviderService> Co-Authored-By: [email protected] <[email protected]> * feat: handle cancel and reschedule usage * fix: restore IsUserInBillingOrg to billing module providers Co-Authored-By: [email protected] <[email protected]> * chore: add idempotency key * fix: just log error] * fix: logger and typo * fix: address Cubic AI review feedback (high confidence issues) - Fix grammar error: 'Delayed task are' -> 'Delayed tasks are' in PlatformOrganizationBillingSyncTasker.ts (3 occurrences) - Re-throw error after logging in increment-usage.ts to enable trigger.dev retry mechanism Co-Authored-By: unknown <> * fix: remove duplicate code and use DI instead * fix: remove orThrow on find first in findPlatformOrgByUserId * refactor: prevent usage increment task from re-throwing errors --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
38 files changed
+931
-100
No files matched your search
@@ -47,6 +47,8 @@ const loadConfig = (): AppConfig => {
|
||||
e2e: getEnv("IS_E2E", "false") === "true",
|
||||
enableSlotsWorkers: getEnv("ENABLE_SLOTS_WORKERS", "true") === "true",
|
||||
slotsWorkerPoolSize: Number(getEnv("SLOTS_WORKER_POOL_SIZE", "4")),
|
||||
vercel: getEnv("VERCEL", "false") === "true",
|
||||
enableAsyncTasker: getEnv("ENABLE_ASYNC_TASKER", "false") === "true",
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -35,4 +35,6 @@ export type AppConfig = {
|
||||
e2e: boolean;
|
||||
enableSlotsWorkers: boolean;
|
||||
slotsWorkerPoolSize: number;
|
||||
vercel: boolean;
|
||||
enableAsyncTasker: boolean;
|
||||
};
|
||||
@@ -41,6 +41,8 @@ export type Environment = {
|
||||
ENABLE_SLOTS_WORKERS: string;
|
||||
SLOTS_WORKER_POOL_SIZE: string;
|
||||
USE_POOL: string;
|
||||
VERCEL: string;
|
||||
ENABLE_ASYNC_TASKER: string;
|
||||
};
|
||||
|
||||
export const getEnv = <K extends keyof Environment>(key: K, fallback?: Environment[K]): Environment[K] => {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PrismaPlatformBillingRepository } from "@/lib/repositories/prisma-platform-billing.repository";
|
||||
import { StripeBillingProviderService } from "@/lib/services/stripe-billing-provider.service";
|
||||
import { PlatformBillingSyncTaskerService } from "@/lib/services/tasker/platform-billing-sync-tasker.service";
|
||||
import { PlatformBillingTaskService } from "@/lib/services/tasker/platform-billing-task.service";
|
||||
import { PlatformBillingTasker } from "@/lib/services/tasker/platform-billing-tasker.service";
|
||||
import { PlatformBillingTriggerTaskerService } from "@/lib/services/tasker/platform-billing-trigger-tasker.service";
|
||||
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { StripeModule } from "@/modules/stripe/stripe.module";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, StripeModule, OrganizationsModule],
|
||||
providers: [
|
||||
PrismaPlatformBillingRepository,
|
||||
StripeBillingProviderService,
|
||||
{
|
||||
provide: Logger,
|
||||
useFactory: () => {
|
||||
return new Logger();
|
||||
},
|
||||
scope: Scope.TRANSIENT,
|
||||
},
|
||||
PlatformBillingTaskService,
|
||||
PlatformBillingSyncTaskerService,
|
||||
PlatformBillingTriggerTaskerService,
|
||||
PlatformBillingTasker,
|
||||
],
|
||||
exports: [PlatformBillingTasker],
|
||||
})
|
||||
export class PlatformBillingTaskerModule {}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformBillingRepository } from "@calcom/platform-libraries/organizations";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaPlatformBillingRepository extends PlatformBillingRepository {
|
||||
constructor(dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { StripeBillingService } from "@calcom/platform-libraries";
|
||||
import type { IBillingProviderService } from "@calcom/platform-libraries/organizations";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
|
||||
@Injectable()
|
||||
export class StripeBillingProviderService
|
||||
extends StripeBillingService
|
||||
implements Pick<IBillingProviderService, "createSubscriptionUsageRecord">
|
||||
{
|
||||
constructor(readonly stripeService: StripeService) {
|
||||
super(stripeService.getStripe());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PlatformBillingTaskService } from "@/lib/services/tasker/platform-billing-task.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformOrganizationBillingSyncTasker as BasePlatformOrganizationBillingSyncTasker } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingSyncTaskerService extends BasePlatformOrganizationBillingSyncTasker {
|
||||
constructor(billingTaskService: PlatformBillingTaskService, logger: Logger) {
|
||||
super({
|
||||
logger,
|
||||
billingTaskService,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PrismaPlatformBillingRepository } from "@/lib/repositories/prisma-platform-billing.repository";
|
||||
import { StripeBillingProviderService } from "@/lib/services/stripe-billing-provider.service";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformOrganizationBillingTaskService as BasePlatformOrganizationBillingTaskService } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingTaskService extends BasePlatformOrganizationBillingTaskService {
|
||||
constructor(
|
||||
organizationRepository: OrganizationsRepository,
|
||||
platformBillingRepository: PrismaPlatformBillingRepository,
|
||||
billingProviderService: StripeBillingProviderService,
|
||||
logger: Logger
|
||||
) {
|
||||
super({
|
||||
logger,
|
||||
organizationRepository,
|
||||
platformBillingRepository,
|
||||
billingProviderService,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { PlatformOrganizationBillingTasker as BasePlatformOrganizationBillingTasker } from "@calcom/platform-libraries/organizations";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PlatformBillingSyncTaskerService } from "@/lib/services/tasker/platform-billing-sync-tasker.service";
|
||||
import { PlatformBillingTriggerTaskerService } from "@/lib/services/tasker/platform-billing-trigger-tasker.service";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingTasker extends BasePlatformOrganizationBillingTasker {
|
||||
constructor(
|
||||
syncTasker: PlatformBillingSyncTaskerService,
|
||||
asyncTasker: PlatformBillingTriggerTaskerService,
|
||||
logger: Logger
|
||||
) {
|
||||
super({
|
||||
logger,
|
||||
asyncTasker: asyncTasker,
|
||||
syncTasker: syncTasker,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformOrganizationBillingTriggerTasker as BasePlatformOrganizationBillingTriggerTasker } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingTriggerTaskerService extends BasePlatformOrganizationBillingTriggerTasker {
|
||||
constructor(logger: Logger) {
|
||||
super({
|
||||
logger,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { BullModule } from "@nestjs/bull";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
|
||||
import { PlatformBillingTaskerModule } from "@/lib/modules/platform-billing-tasker.module";
|
||||
import { BillingProcessor } from "@/modules/billing/billing.processor";
|
||||
import { BillingRepository } from "@/modules/billing/billing.repository";
|
||||
import { BillingController } from "@/modules/billing/controllers/billing.controller";
|
||||
import { IsUserInBillingOrg } from "@/modules/billing/guards/is-user-in-billing-org";
|
||||
import { BillingServiceCachingProxy } from "@/modules/billing/services/billing-service-caching-proxy";
|
||||
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { BillingServiceCachingProxy } from "@/modules/billing/services/billing-service-caching-proxy";
|
||||
import { ManagedOrganizationsBillingService } from "@/modules/billing/services/managed-organizations.billing.service";
|
||||
import { MembershipsModule } from "@/modules/memberships/memberships.module";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
@@ -14,8 +17,6 @@ import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { RedisModule } from "@/modules/redis/redis.module";
|
||||
import { StripeModule } from "@/modules/stripe/stripe.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
import { BullModule } from "@nestjs/bull";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -32,6 +33,7 @@ import { Module } from "@nestjs/common";
|
||||
},
|
||||
}),
|
||||
UsersModule,
|
||||
PlatformBillingTaskerModule,
|
||||
],
|
||||
providers: [
|
||||
BillingConfigService,
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PlatformBilling, Team } from "@calcom/prisma/client";
|
||||
export type BillingData = {
|
||||
team: (Team & { platformBilling: PlatformBilling | null }) | null;
|
||||
status: "valid" | "no_subscription" | "no_billing";
|
||||
plan: string;
|
||||
plan: PlatformPlan | "none";
|
||||
};
|
||||
|
||||
export interface IBillingService {
|
||||
|
||||
@@ -1,14 +1,3 @@
|
||||
import { AppConfig } from "@/config/type";
|
||||
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
|
||||
import { BILLING_QUEUE, INCREMENT_JOB, IncrementJobDataType } from "@/modules/billing/billing.processor";
|
||||
import { BillingRepository } from "@/modules/billing/billing.repository";
|
||||
import { IBillingService } from "@/modules/billing/interfaces/billing-service.interface";
|
||||
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { InjectQueue } from "@nestjs/bull";
|
||||
import {
|
||||
BadRequestException,
|
||||
@@ -22,6 +11,16 @@ import { ConfigService } from "@nestjs/config";
|
||||
import { Queue } from "bull";
|
||||
import { DateTime } from "luxon";
|
||||
import Stripe from "stripe";
|
||||
import { AppConfig } from "@/config/type";
|
||||
import { PlatformBillingTasker } from "@/lib/services/tasker/platform-billing-tasker.service";
|
||||
import { BILLING_QUEUE, INCREMENT_JOB, IncrementJobDataType } from "@/modules/billing/billing.processor";
|
||||
import { BillingRepository } from "@/modules/billing/billing.repository";
|
||||
import { BillingData, IBillingService } from "@/modules/billing/interfaces/billing-service.interface";
|
||||
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
|
||||
@Injectable()
|
||||
export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
@@ -35,14 +34,13 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
private readonly configService: ConfigService<AppConfig>,
|
||||
private readonly billingConfigService: BillingConfigService,
|
||||
private readonly usersRepository: UsersRepository,
|
||||
private readonly oAuthClientRepository: OAuthClientRepository,
|
||||
private readonly bookingsRepository: BookingsRepository_2024_08_13,
|
||||
private readonly platformBillingTasker: PlatformBillingTasker,
|
||||
@InjectQueue(BILLING_QUEUE) private readonly billingQueue: Queue
|
||||
) {
|
||||
this.webAppUrl = this.configService.get("app.baseUrl", { infer: true }) ?? "https://app.cal.com";
|
||||
}
|
||||
|
||||
async getBillingData(teamId: number) {
|
||||
async getBillingData(teamId: number): Promise<BillingData> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
|
||||
if (teamWithBilling?.platformBilling) {
|
||||
@@ -52,7 +50,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
return {
|
||||
team: teamWithBilling,
|
||||
status: "valid" as const,
|
||||
plan: teamWithBilling.platformBilling.plan,
|
||||
plan: teamWithBilling.platformBilling.plan as PlatformPlan,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
@@ -62,7 +60,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
|
||||
async createTeamBilling(teamId: number): Promise<string> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
let customerId = teamWithBilling?.platformBilling?.customerId;
|
||||
let customerId = teamWithBilling?.platformBilling?.customerId ?? "";
|
||||
|
||||
if (!teamWithBilling?.platformBilling) {
|
||||
customerId = await this.teamsRepository.createNewBillingRelation(teamId);
|
||||
@@ -73,10 +71,14 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
return customerId!;
|
||||
return customerId;
|
||||
}
|
||||
|
||||
async redirectToSubscribeCheckout(teamId: number, plan: PlatformPlan, customerId?: string) {
|
||||
async redirectToSubscribeCheckout(
|
||||
teamId: number,
|
||||
plan: PlatformPlan,
|
||||
customerId?: string
|
||||
): Promise<string> {
|
||||
const { url } = await this.stripeService.getStripe().checkout.sessions.create({
|
||||
customer: customerId,
|
||||
line_items: [
|
||||
@@ -109,7 +111,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
return url;
|
||||
}
|
||||
|
||||
async updateSubscriptionForTeam(teamId: number, plan: PlatformPlan) {
|
||||
async updateSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<string> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
const customerId = teamWithBilling?.platformBilling?.customerId;
|
||||
|
||||
@@ -134,7 +136,11 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
return url;
|
||||
}
|
||||
|
||||
async setPerBookingSubscriptionForTeam(teamId: number, subscriptionId: string, plan: PlatformPlan) {
|
||||
async setPerBookingSubscriptionForTeam(
|
||||
teamId: number,
|
||||
subscriptionId: string,
|
||||
plan: PlatformPlan
|
||||
): Promise<ReturnType<typeof BillingRepository.prototype.updateTeamBilling>> {
|
||||
const billingCycleStart = DateTime.now().get("day");
|
||||
const billingCycleEnd = DateTime.now().plus({ month: 1 }).get("day");
|
||||
|
||||
@@ -152,7 +158,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
subscriptionId: string,
|
||||
plan: PlatformPlan,
|
||||
priceId: string
|
||||
) {
|
||||
): Promise<ReturnType<typeof BillingRepository.prototype.updateTeamBilling>> {
|
||||
const billingCycleStart = DateTime.now().get("day");
|
||||
const billingCycleEnd = DateTime.now().plus({ month: 1 }).get("day");
|
||||
|
||||
@@ -166,12 +172,12 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
);
|
||||
}
|
||||
|
||||
async handleStripeSubscriptionDeleted(event: Stripe.Event) {
|
||||
async handleStripeSubscriptionDeleted(event: Stripe.Event): Promise<void> {
|
||||
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));
|
||||
const currentBilling = await this.billingRepository.getBillingForTeam(Number.parseInt(teamId, 10));
|
||||
if (currentBilling?.subscriptionId === subscription.id) {
|
||||
await this.billingRepository.deleteBilling(currentBilling.id);
|
||||
this.logger.log(`Stripe Subscription deleted`, {
|
||||
@@ -207,7 +213,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentSuccess(event: Stripe.Event) {
|
||||
async handleStripePaymentSuccess(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
const customerId = this.getCustomerIdFromInvoice(invoice);
|
||||
@@ -216,7 +222,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentFailed(event: Stripe.Event) {
|
||||
async handleStripePaymentFailed(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
const customerId = this.getCustomerIdFromInvoice(invoice);
|
||||
@@ -225,7 +231,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentPastDue(event: Stripe.Event) {
|
||||
async handleStripePaymentPastDue(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
const customerId = this.getCustomerIdFromInvoice(invoice);
|
||||
@@ -249,14 +255,14 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripeCheckoutEvents(event: Stripe.Event) {
|
||||
async handleStripeCheckoutEvents(event: Stripe.Event): Promise<void> {
|
||||
const checkoutSession = event.data.object as Stripe.Checkout.Session;
|
||||
|
||||
if (!checkoutSession.metadata?.teamId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const teamId = Number.parseInt(checkoutSession.metadata.teamId);
|
||||
const teamId = Number.parseInt(checkoutSession.metadata.teamId, 10);
|
||||
const plan = checkoutSession.metadata.plan;
|
||||
if (!plan || !teamId) {
|
||||
this.logger.log("Webhook received but not pertaining to Platform, discarding.");
|
||||
@@ -288,7 +294,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
async handleStripeSubscriptionForActiveManagedUsers(event: Stripe.Event) {
|
||||
async handleStripeSubscriptionForActiveManagedUsers(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
|
||||
@@ -299,12 +305,16 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
const teamWithBilling = await this.billingRepository.getBillingForTeamBySubscriptionId(subscriptionId);
|
||||
|
||||
if (teamWithBilling?.plan === "PER_ACTIVE_USER") {
|
||||
const activeManagedUsersCount = await this.getActiveManagedUsersCount(
|
||||
let activeManagedUsersCount = await this.getActiveManagedUsersCount(
|
||||
subscriptionId,
|
||||
new Date(invoice.period_start * 1000),
|
||||
new Date(invoice.period_end * 1000)
|
||||
);
|
||||
|
||||
if (activeManagedUsersCount < 0) {
|
||||
activeManagedUsersCount = 1;
|
||||
}
|
||||
|
||||
const existingSubscription = await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.retrieve(subscriptionId);
|
||||
@@ -321,17 +331,18 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
|
||||
await this.stripeService.getStripe().subscriptions.update(subscriptionId, {
|
||||
items: [
|
||||
{ id: subscriptionItem.id, quantity: activeManagedUsersCount > 0 ? activeManagedUsersCount : 1 },
|
||||
],
|
||||
items: [{ id: subscriptionItem.id, quantity: activeManagedUsersCount }],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getActiveManagedUsersCount(subscriptionId: string, invoiceStart: Date, invoiceEnd: Date) {
|
||||
const managedUsersEmails = await this.usersRepository.getOrgsManagedUserEmailsBySubscriptionId(
|
||||
subscriptionId
|
||||
);
|
||||
async getActiveManagedUsersCount(
|
||||
subscriptionId: string,
|
||||
invoiceStart: Date,
|
||||
invoiceEnd: Date
|
||||
): Promise<number> {
|
||||
const managedUsersEmails =
|
||||
await this.usersRepository.getOrgsManagedUserEmailsBySubscriptionId(subscriptionId);
|
||||
|
||||
if (!managedUsersEmails) return 0;
|
||||
|
||||
@@ -362,7 +373,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
return activeManagedUserEmailsAsAttendee.length + activeManagedUserEmailsAsHost.length;
|
||||
}
|
||||
|
||||
async updateStripeSubscriptionForTeam(teamId: number, plan: PlatformPlan) {
|
||||
async updateStripeSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<void> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
|
||||
if (!teamWithBilling?.platformBilling || !teamWithBilling?.platformBilling.subscriptionId) {
|
||||
@@ -424,13 +435,37 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
startTime: Date;
|
||||
fromReschedule?: string | null;
|
||||
}
|
||||
) {
|
||||
): Promise<boolean | undefined> {
|
||||
if (this.configService.get("e2e")) {
|
||||
return true;
|
||||
}
|
||||
const { uid, startTime, fromReschedule } = booking;
|
||||
|
||||
const delay = startTime.getTime() - Date.now();
|
||||
if (this.configService.get("enableAsyncTasker")) {
|
||||
if (fromReschedule) {
|
||||
this.platformBillingTasker.rescheduleUsageIncrement({
|
||||
payload: { bookingUid: uid },
|
||||
options: { delay: startTime },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
this.platformBillingTasker.incrementUsage({
|
||||
payload: { userId },
|
||||
options: {
|
||||
delay: startTime,
|
||||
tags: [`platform.billing.usage.${uid}`],
|
||||
idempotencyKey: `platform.billing.usage.${uid}-${userId}`,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
let delay = startTime.getTime() - Date.now();
|
||||
|
||||
if (delay < 0) {
|
||||
delay = 0;
|
||||
}
|
||||
|
||||
if (fromReschedule) {
|
||||
// cancel the usage increment job for the booking that is being rescheduled
|
||||
await this.cancelUsageByBookingUid(fromReschedule);
|
||||
@@ -441,7 +476,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
{
|
||||
userId,
|
||||
} satisfies IncrementJobDataType,
|
||||
{ delay: delay > 0 ? delay : 0, jobId: `increment-${uid}`, removeOnComplete: true }
|
||||
{ delay: delay, jobId: `increment-${uid}`, removeOnComplete: true }
|
||||
);
|
||||
this.logger.log(`Added stripe usage increment job for booking ${uid} and user ${userId}`);
|
||||
}
|
||||
@@ -451,10 +486,16 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
* Cancels the usage increment job for a booking when it is cancelled.
|
||||
* Removing an attendee from a booking does not cancel the usage increment job.
|
||||
*/
|
||||
async cancelUsageByBookingUid(bookingUid: string) {
|
||||
async cancelUsageByBookingUid(bookingUid: string): Promise<boolean | undefined> {
|
||||
if (this.configService.get("e2e")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.configService.get("enableAsyncTasker")) {
|
||||
await this.platformBillingTasker.cancelUsageIncrement({ payload: { bookingUid } });
|
||||
return true;
|
||||
}
|
||||
|
||||
const job = await this.billingQueue.getJob(`increment-${bookingUid}`);
|
||||
if (job) {
|
||||
await job.remove();
|
||||
@@ -462,7 +503,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async cancelTeamSubscription(teamId: number) {
|
||||
async cancelTeamSubscription(teamId: number): Promise<void> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
const customerId = teamWithBilling?.platformBilling?.customerId;
|
||||
|
||||
@@ -484,7 +525,7 @@ export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
try {
|
||||
await this.billingQueue.close();
|
||||
} catch (err) {
|
||||
|
||||
Reference in new issue
Block a user