From 3af533e2c8220c1ab910fc1c9205c6ac3d7c3b19 Mon Sep 17 00:00:00 2001 From: sean-brydon <55134778+sean-brydon@users.noreply.github.com> Date: Thu, 22 Jan 2026 11:23:38 +0000 Subject: [PATCH] feat: add monthly proration processing (#27002) * feat: add seat tracking infrastructure for monthly proration Add seat change logging infrastructure with operationId for idempotency. This PR adds the foundation for monthly proration billing by tracking seat additions and removals, gated behind the monthly-proration feature flag. - Add operationId field to SeatChangeLog for idempotency - Update SeatChangeLogRepository to support upsert with operationId - Add feature flag guard in SeatChangeTrackingService - Integrate seat tracking in team member invites - Integrate seat tracking in bulk user deletions - Integrate seat tracking in team service operations - Integrate seat tracking in DSYNC user creation When monthly-proration feature flag is disabled, seat logging is skipped and behavior remains unchanged. Co-Authored-By: Claude Sonnet 4.5 * feat: add monthly proration processing Add monthly proration billing processing that works on top of the seat tracking infrastructure. This PR implements the core proration logic, webhook handlers, and integration with Stripe billing. - Enhance MonthlyProrationService to process seat change logs - Add payment webhook handlers (invoice.payment_succeeded, invoice.payment_failed) - Update subscription webhook to sync billing period on renewals - Update TeamBillingService to skip real-time updates when proration enabled - Enhance StripeBillingService with proration capabilities - Add Tasker enhancements for processing queues - Update team creation/upgrade routes Depends on: feat/monthly-proration-seat-tracking Co-Authored-By: Claude Sonnet 4.5 * fix: remove unused logger from SeatChangeTrackingService * fix: description for calculation * fix null check on trial * chore: no more prisma calls * add feature flag check * fix stub --------- Co-authored-by: Claude Sonnet 4.5 Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../web/app/api/teams/[team]/upgrade/route.ts | 33 ++ apps/web/app/api/teams/api/create/route.ts | 14 +- apps/web/app/api/teams/create/route.ts | 14 +- .../_customer.subscription.updated.test.ts | 97 ++++++ .../webhook/_customer.subscription.updated.ts | 69 +++- .../billing/api/webhook/_invoice.paid.org.ts | 14 +- .../webhook/_invoice.payment_failed.test.ts | 51 +++ .../api/webhook/_invoice.payment_failed.ts | 48 +++ .../_invoice.payment_succeeded.test.ts | 59 ++++ .../api/webhook/_invoice.payment_succeeded.ts | 35 +++ .../features/ee/billing/api/webhook/index.ts | 2 + .../di/modules/MonthlyProrationService.ts | 2 + .../ee/billing/lib/proration-utils.ts | 30 ++ .../billing/lib/stripe-subscription-utils.ts | 49 ++- .../ee/billing/lib/subscription-updates.ts | 30 ++ .../repository/billing/IBillingRepository.ts | 11 + .../PrismaOrganizationBillingRepository.ts | 18 +- .../billing/PrismaTeamBillingRepository.ts | 18 +- .../billing/StubBillingRepository.ts | 16 +- .../MonthlyProrationTeamRepository.ts | 21 +- .../IBillingProviderService.ts | 17 +- .../StripeBillingService.test.ts | 11 +- .../billingProvider/StripeBillingService.ts | 95 +++++- .../proration/MonthlyProrationService.ts | 295 +++++++++++++----- ...onthlyProrationService.integration-test.ts | 97 +++++- .../__tests__/MonthlyProrationService.test.ts | 142 ++++++++- .../seatTracking/SeatChangeTrackingService.ts | 8 +- .../service/teams/TeamBillingFactory.test.ts | 14 +- .../service/teams/TeamBillingService.test.ts | 78 ++++- .../service/teams/TeamBillingService.ts | 25 +- .../teams/internal-team-billing.test.ts | 76 ++++- packages/lib/tasker/Tasker.ts | 44 ++- 32 files changed, 1355 insertions(+), 178 deletions(-) create mode 100644 packages/features/ee/billing/api/webhook/_customer.subscription.updated.test.ts create mode 100644 packages/features/ee/billing/api/webhook/_invoice.payment_failed.test.ts create mode 100644 packages/features/ee/billing/api/webhook/_invoice.payment_failed.ts create mode 100644 packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.test.ts create mode 100644 packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.ts create mode 100644 packages/features/ee/billing/lib/proration-utils.ts create mode 100644 packages/features/ee/billing/lib/subscription-updates.ts diff --git a/apps/web/app/api/teams/[team]/upgrade/route.ts b/apps/web/app/api/teams/[team]/upgrade/route.ts index 57bd326498..b5182c51f6 100644 --- a/apps/web/app/api/teams/[team]/upgrade/route.ts +++ b/apps/web/app/api/teams/[team]/upgrade/route.ts @@ -7,6 +7,10 @@ import type Stripe from "stripe"; import { z } from "zod"; import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing"; +import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing"; +import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing"; +import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils"; +import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/billing/IBillingRepository"; import { getServerSession } from "@calcom/features/auth/lib/getServerSession"; import stripe from "@calcom/features/ee/payments/server/stripe"; import { WEBAPP_URL } from "@calcom/lib/constants"; @@ -86,6 +90,35 @@ async function getHandler(req: NextRequest, { params }: { params: Promise { + const findByStripeSubscriptionIdFn = vi.fn().mockResolvedValue(null); + const prismaMockObj = { + teamBilling: { + findUnique: vi.fn(), + update: vi.fn(), + }, + organizationBilling: { + findUnique: vi.fn(), + update: vi.fn(), + }, + calAiPhoneNumber: { + update: vi.fn(), + }, + }; + return { + findByStripeSubscriptionId: findByStripeSubscriptionIdFn, + prismaMock: prismaMockObj, + }; +}); + +vi.mock("@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository", () => { + return { + PrismaPhoneNumberRepository: class { + findByStripeSubscriptionId = findByStripeSubscriptionId; + }, + }; +}); + +vi.mock("@calcom/ee/billing/di/containers/Billing", () => ({ + getBillingProviderService: () => ({ + extractSubscriptionDates: () => ({ + subscriptionStart: new Date("2024-01-01T00:00:00.000Z"), + subscriptionEnd: new Date("2024-12-31T00:00:00.000Z"), + subscriptionTrialEnd: null, + }), + }), +})); + +vi.mock("@calcom/prisma", () => ({ + default: prismaMock, +})); + +describe("customer.subscription.updated webhook", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("updates team billing on renewal", async () => { + prismaMock.teamBilling.findUnique.mockResolvedValue({ id: "tb_1", teamId: 123 }); + prismaMock.organizationBilling.findUnique.mockResolvedValue(null); + + const data = { + object: { + id: "sub_123", + status: "active", + items: { + data: [ + { + quantity: 5, + price: { + unit_amount: 12000, + recurring: { interval: "year" }, + }, + }, + ], + }, + }, + previous_attributes: { + current_period_start: 1690000000, + }, + } as unknown as SWHMap["customer.subscription.updated"]["data"]; + + const result = await handler(data); + + expect(prismaMock.teamBilling.update).toHaveBeenCalledWith({ + where: { id: "tb_1" }, + data: expect.objectContaining({ + billingPeriod: "ANNUALLY", + pricePerSeat: 12000, + paidSeats: 5, + subscriptionStart: new Date("2024-01-01T00:00:00.000Z"), + subscriptionEnd: new Date("2024-12-31T00:00:00.000Z"), + subscriptionTrialEnd: null, + }), + }); + expect(result).toEqual({ + phoneNumber: null, + teamBilling: { success: true, type: "team", teamId: 123 }, + }); + }); +}); diff --git a/packages/features/ee/billing/api/webhook/_customer.subscription.updated.ts b/packages/features/ee/billing/api/webhook/_customer.subscription.updated.ts index 0621025b0b..e167880e7f 100644 --- a/packages/features/ee/billing/api/webhook/_customer.subscription.updated.ts +++ b/packages/features/ee/billing/api/webhook/_customer.subscription.updated.ts @@ -1,7 +1,14 @@ +import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing"; import { PrismaPhoneNumberRepository } from "@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository"; +import { PrismaOrganizationBillingRepository } from "@calcom/features/ee/billing/repository/billing/PrismaOrganizationBillingRepository"; +import { PrismaTeamBillingRepository } from "@calcom/features/ee/billing/repository/billing/PrismaTeamBillingRepository"; +import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils"; +import logger from "@calcom/lib/logger"; import prisma from "@calcom/prisma"; import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums"; +const log = logger.getSubLogger({ prefix: ["subscription-updated-webhook"] }); + import type { SWHMap } from "./__handler"; import { HttpCode } from "./__handler"; @@ -9,6 +16,7 @@ type Data = SWHMap["customer.subscription.updated"]["data"]; const handler = async (data: Data) => { const subscription = data.object; + const previousAttributes = data.previous_attributes; if (!subscription.id) { throw new HttpCode(400, "Subscription ID not found"); @@ -19,11 +27,16 @@ const handler = async (data: Data) => { stripeSubscriptionId: subscription.id, }); - if (!phoneNumber) { - throw new HttpCode(202, "Phone number not found"); - } + const phoneNumberResult = phoneNumber + ? await handleCalAIPhoneNumberSubscriptionUpdate(subscription, phoneNumber) + : null; - return await handleCalAIPhoneNumberSubscriptionUpdate(subscription, phoneNumber); + const teamBillingResult = await handleTeamBillingRenewal(subscription, previousAttributes); + + return { + phoneNumber: phoneNumberResult, + teamBilling: teamBillingResult, + }; }; type Subscription = Data["object"]; @@ -58,4 +71,52 @@ async function handleCalAIPhoneNumberSubscriptionUpdate( return { success: true, subscriptionId: subscription.id, status: subscriptionStatus }; } +async function handleTeamBillingRenewal( + subscription: Subscription, + previousAttributes: Data["previous_attributes"] +) { + if (!previousAttributes?.current_period_start) { + return { skipped: true, reason: "not a renewal" }; + } + + const billingProviderService = getBillingProviderService(); + const { subscriptionStart, subscriptionEnd, subscriptionTrialEnd } = + billingProviderService.extractSubscriptionDates(subscription); + + const { billingPeriod, pricePerSeat, paidSeats } = extractBillingDataFromStripeSubscription(subscription); + + const teamBillingRepo = new PrismaTeamBillingRepository(prisma); + const orgBillingRepo = new PrismaOrganizationBillingRepository(prisma); + + const billingUpdateData = { + paidSeats: paidSeats ?? null, + subscriptionStart, + subscriptionEnd, + subscriptionTrialEnd, + billingPeriod, + pricePerSeat: pricePerSeat ?? null, + }; + + const teamBilling = await teamBillingRepo.findBySubscriptionId(subscription.id); + + if (teamBilling) { + await teamBillingRepo.updateById(teamBilling.id, billingUpdateData); + return { success: true, type: "team", teamId: teamBilling.teamId }; + } + + const orgBilling = await orgBillingRepo.findBySubscriptionId(subscription.id); + + if (orgBilling) { + await orgBillingRepo.updateById(orgBilling.id, billingUpdateData); + return { success: true, type: "organization", teamId: orgBilling.teamId }; + } + + log.warn("Subscription renewal received but no billing record found", { + subscriptionId: subscription.id, + customerId: typeof subscription.customer === "string" ? subscription.customer : subscription.customer?.id, + }); + + return { skipped: true, reason: "no billing record found" }; +} + export default handler; diff --git a/packages/features/ee/billing/api/webhook/_invoice.paid.org.ts b/packages/features/ee/billing/api/webhook/_invoice.paid.org.ts index 2558804303..4a45382336 100644 --- a/packages/features/ee/billing/api/webhook/_invoice.paid.org.ts +++ b/packages/features/ee/billing/api/webhook/_invoice.paid.org.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing"; +import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils"; import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/billing/IBillingRepository"; import { BillingEnabledOrgOnboardingService } from "@calcom/features/ee/organizations/lib/service/onboarding/BillingEnabledOrgOnboardingService"; import stripe from "@calcom/features/ee/payments/server/stripe"; @@ -124,7 +125,11 @@ const handler = async (data: SWHMap["invoice.paid"]["data"]) => { // Get the Stripe subscription object const stripeSubscription = await stripe.subscriptions.retrieve(paymentSubscriptionId); const billingService = getBillingProviderService(); - const { subscriptionStart } = billingService.extractSubscriptionDates(stripeSubscription); + const { subscriptionStart, subscriptionEnd, subscriptionTrialEnd } = + billingService.extractSubscriptionDates(stripeSubscription); + + const { billingPeriod, pricePerSeat, paidSeats } = + extractBillingDataFromStripeSubscription(stripeSubscription); const teamBillingServiceFactory = getTeamBillingServiceFactory(); const teamBillingService = teamBillingServiceFactory.init(organization); @@ -136,7 +141,12 @@ const handler = async (data: SWHMap["invoice.paid"]["data"]) => { // TODO: Write actual status when webhook events are added status: SubscriptionStatus.ACTIVE, planName: Plan.ORGANIZATION, - subscriptionStart, + subscriptionStart: subscriptionStart ?? undefined, + subscriptionEnd: subscriptionEnd ?? undefined, + subscriptionTrialEnd: subscriptionTrialEnd ?? undefined, + billingPeriod, + pricePerSeat, + paidSeats, }); logger.debug(`Marking onboarding as complete for organization ${organization.id}`); diff --git a/packages/features/ee/billing/api/webhook/_invoice.payment_failed.test.ts b/packages/features/ee/billing/api/webhook/_invoice.payment_failed.test.ts new file mode 100644 index 0000000000..33ef977e38 --- /dev/null +++ b/packages/features/ee/billing/api/webhook/_invoice.payment_failed.test.ts @@ -0,0 +1,51 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { buildMonthlyProrationMetadata } from "../../lib/proration-utils"; +import type { SWHMap } from "./__handler"; +import handler from "./_invoice.payment_failed"; + +const handleProrationPaymentFailure = vi.fn(); +const getPaymentIntentFailureReason = vi.fn().mockResolvedValue("card_declined"); + +vi.mock("@calcom/ee/billing/di/containers/Billing", () => ({ + getBillingProviderService: () => ({ + getPaymentIntentFailureReason, + }), +})); + +vi.mock("../../service/proration/MonthlyProrationService", () => ({ + MonthlyProrationService: class { + handleProrationPaymentFailure = handleProrationPaymentFailure; + }, +})); + +describe("invoice.payment_failed webhook", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("records proration failure with payment intent reason", async () => { + const data = { + object: { + payment_intent: "pi_123", + status: "open", + lines: { + data: [ + { + metadata: buildMonthlyProrationMetadata({ prorationId: "pr_123" }), + }, + ], + }, + }, + } as unknown as SWHMap["invoice.payment_failed"]["data"]; + + const result = await handler(data); + + expect(getPaymentIntentFailureReason).toHaveBeenCalledWith("pi_123"); + expect(handleProrationPaymentFailure).toHaveBeenCalledWith({ + prorationId: "pr_123", + reason: "card_declined", + }); + expect(result).toEqual({ success: true }); + }); +}); diff --git a/packages/features/ee/billing/api/webhook/_invoice.payment_failed.ts b/packages/features/ee/billing/api/webhook/_invoice.payment_failed.ts new file mode 100644 index 0000000000..f28eaad672 --- /dev/null +++ b/packages/features/ee/billing/api/webhook/_invoice.payment_failed.ts @@ -0,0 +1,48 @@ +import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing"; +import logger from "@calcom/lib/logger"; + +import { findMonthlyProrationLineItem } from "../../lib/proration-utils"; +import { MonthlyProrationService } from "../../service/proration/MonthlyProrationService"; +import type { SWHMap } from "./__handler"; + +const log = logger.getSubLogger({ prefix: ["invoice-payment-failed"] }); + +type Data = SWHMap["invoice.payment_failed"]["data"]; + +const handler = async (data: Data) => { + const invoice = data.object; + + const prorationLineItem = findMonthlyProrationLineItem(invoice.lines.data); + + if (!prorationLineItem) { + return { success: true, message: "no proration line items in invoice" }; + } + + const prorationId = prorationLineItem.metadata?.prorationId; + if (!prorationId) { + log.warn("proration line item missing prorationId metadata"); + return { success: false, message: "missing prorationId in metadata" }; + } + + const prorationService = new MonthlyProrationService(); + let failureReason = invoice.status ?? "payment_failed"; + const paymentIntentId = + typeof invoice.payment_intent === "string" ? invoice.payment_intent : invoice.payment_intent?.id; + + if (paymentIntentId) { + const billingProviderService = getBillingProviderService(); + const paymentFailureReason = await billingProviderService.getPaymentIntentFailureReason(paymentIntentId); + failureReason = paymentFailureReason ?? failureReason; + } + + await prorationService.handleProrationPaymentFailure({ + prorationId, + reason: failureReason, + }); + + log.info(`proration ${prorationId} marked as failed`); + + return { success: true }; +}; + +export default handler; diff --git a/packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.test.ts b/packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.test.ts new file mode 100644 index 0000000000..2ebc00da4e --- /dev/null +++ b/packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.test.ts @@ -0,0 +1,59 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { buildMonthlyProrationMetadata } from "../../lib/proration-utils"; +import type { SWHMap } from "./__handler"; +import handler from "./_invoice.payment_succeeded"; + +const handleProrationPaymentSuccess = vi.fn(); + +vi.mock("../../service/proration/MonthlyProrationService", () => ({ + MonthlyProrationService: class { + handleProrationPaymentSuccess = handleProrationPaymentSuccess; + }, +})); + +describe("invoice.payment_succeeded webhook", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("marks proration as charged when line item is present", async () => { + const data = { + object: { + lines: { + data: [ + { + metadata: buildMonthlyProrationMetadata({ prorationId: "pr_123" }), + }, + ], + }, + }, + } as unknown as SWHMap["invoice.payment_succeeded"]["data"]; + + const result = await handler(data); + + expect(handleProrationPaymentSuccess).toHaveBeenCalledWith("pr_123"); + expect(result).toEqual({ success: true }); + }); + + it("skips when no proration line item exists", async () => { + const data = { + object: { + lines: { + data: [ + { + metadata: { + type: "other", + }, + }, + ], + }, + }, + } as unknown as SWHMap["invoice.payment_succeeded"]["data"]; + + const result = await handler(data); + + expect(handleProrationPaymentSuccess).not.toHaveBeenCalled(); + expect(result).toEqual({ success: true, message: "no proration line items in invoice" }); + }); +}); diff --git a/packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.ts b/packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.ts new file mode 100644 index 0000000000..d7a4b448ad --- /dev/null +++ b/packages/features/ee/billing/api/webhook/_invoice.payment_succeeded.ts @@ -0,0 +1,35 @@ +import logger from "@calcom/lib/logger"; + +import { findMonthlyProrationLineItem } from "../../lib/proration-utils"; +import { MonthlyProrationService } from "../../service/proration/MonthlyProrationService"; +import type { SWHMap } from "./__handler"; + +const log = logger.getSubLogger({ prefix: ["invoice-payment-succeeded"] }); + +type Data = SWHMap["invoice.payment_succeeded"]["data"]; + +const handler = async (data: Data) => { + const invoice = data.object; + + const prorationLineItem = findMonthlyProrationLineItem(invoice.lines.data); + + if (!prorationLineItem) { + return { success: true, message: "no proration line items in invoice" }; + } + + const prorationId = prorationLineItem.metadata?.prorationId; + if (!prorationId) { + log.warn("proration line item missing prorationId metadata"); + return { success: false, message: "missing prorationId in metadata" }; + } + + const prorationService = new MonthlyProrationService(); + + await prorationService.handleProrationPaymentSuccess(prorationId); + + log.info(`proration ${prorationId} marked as charged`); + + return { success: true }; +}; + +export default handler; diff --git a/packages/features/ee/billing/api/webhook/index.ts b/packages/features/ee/billing/api/webhook/index.ts index 4472997461..74346405e5 100644 --- a/packages/features/ee/billing/api/webhook/index.ts +++ b/packages/features/ee/billing/api/webhook/index.ts @@ -9,6 +9,8 @@ const handlers = { "customer.subscription.deleted": () => import("./_customer.subscription.deleted"), "customer.subscription.updated": () => import("./_customer.subscription.updated"), "invoice.paid": () => import("./_invoice.paid"), + "invoice.payment_failed": () => import("./_invoice.payment_failed"), + "invoice.payment_succeeded": () => import("./_invoice.payment_succeeded"), "checkout.session.completed": () => import("./_checkout.session.completed"), }; diff --git a/packages/features/ee/billing/di/modules/MonthlyProrationService.ts b/packages/features/ee/billing/di/modules/MonthlyProrationService.ts index 471eae19da..c8e3457425 100644 --- a/packages/features/ee/billing/di/modules/MonthlyProrationService.ts +++ b/packages/features/ee/billing/di/modules/MonthlyProrationService.ts @@ -1,4 +1,5 @@ import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di"; +import { moduleLoader as featuresRepositoryModuleLoader } from "@calcom/features/di/modules/FeaturesRepository"; import { moduleLoader as triggerDevLoggerServiceModule } from "@calcom/features/di/shared/services/triggerDevLogger.service"; import { MonthlyProrationService } from "@calcom/features/ee/billing/service/proration/MonthlyProrationService"; @@ -15,6 +16,7 @@ const loadModule = bindModuleToClassOnToken({ classs: MonthlyProrationService, depsMap: { logger: triggerDevLoggerServiceModule, + featuresRepository: featuresRepositoryModuleLoader, }, }); diff --git a/packages/features/ee/billing/lib/proration-utils.ts b/packages/features/ee/billing/lib/proration-utils.ts new file mode 100644 index 0000000000..a981de1d13 --- /dev/null +++ b/packages/features/ee/billing/lib/proration-utils.ts @@ -0,0 +1,30 @@ +export const MONTHLY_PRORATION_METADATA_TYPE = "monthly_proration"; + +type MetadataContainer = { + metadata?: Record | null; +}; + +export function buildMonthlyProrationMetadata(params: { + prorationId: string; + teamId?: number; + monthKey?: string; +}): Record { + const metadata: Record = { + type: MONTHLY_PRORATION_METADATA_TYPE, + prorationId: params.prorationId, + }; + + if (typeof params.teamId === "number") { + metadata.teamId = params.teamId.toString(); + } + + if (params.monthKey) { + metadata.monthKey = params.monthKey; + } + + return metadata; +} + +export function findMonthlyProrationLineItem(lineItems: T[]): T | undefined { + return lineItems.find((line) => line.metadata?.type === MONTHLY_PRORATION_METADATA_TYPE); +} diff --git a/packages/features/ee/billing/lib/stripe-subscription-utils.ts b/packages/features/ee/billing/lib/stripe-subscription-utils.ts index 36fe396a41..d072597945 100644 --- a/packages/features/ee/billing/lib/stripe-subscription-utils.ts +++ b/packages/features/ee/billing/lib/stripe-subscription-utils.ts @@ -1,23 +1,62 @@ -import type Stripe from "stripe"; import type { BillingPeriod } from "@calcom/prisma/enums"; +type SubscriptionItemLike = { + id: string; + quantity?: number | null; + price: { + unit_amount: number | null; + recurring: { interval: string } | null; + }; +}; + +type SubscriptionItems = SubscriptionItemLike[] | { data: SubscriptionItemLike[] }; + +export interface StripeSubscriptionLike { + items: SubscriptionItems; + current_period_start: number; + current_period_end: number; + trial_end: number | null; +} + export interface BillingData { billingPeriod: BillingPeriod; pricePerSeat: number | undefined; paidSeats: number | undefined; + subscriptionStart: Date | undefined; + subscriptionEnd: Date | undefined; + subscriptionTrialEnd: Date | undefined; } -export function extractBillingDataFromStripeSubscription(subscription: Stripe.Subscription): BillingData { +const getSubscriptionItems = (subscription: StripeSubscriptionLike) => + Array.isArray(subscription.items) ? subscription.items : subscription.items.data; + +export function extractBillingDataFromStripeSubscription(subscription: StripeSubscriptionLike): BillingData { + const subscriptionItems = getSubscriptionItems(subscription); + const primaryItem = subscriptionItems[0]; + const billingPeriod: BillingPeriod = - subscription.items.data[0]?.price.recurring?.interval === "year" ? "ANNUALLY" : "MONTHLY"; + primaryItem?.price.recurring?.interval === "year" ? "ANNUALLY" : "MONTHLY"; - const pricePerSeat = subscription.items.data[0]?.price.unit_amount; + const pricePerSeat = primaryItem?.price.unit_amount ?? undefined; - const paidSeats = subscription.items.data[0]?.quantity; + const paidSeats = primaryItem?.quantity ?? undefined; + + const subscriptionStart = subscription.current_period_start + ? new Date(subscription.current_period_start * 1000) + : undefined; + + const subscriptionEnd = subscription.current_period_end + ? new Date(subscription.current_period_end * 1000) + : undefined; + + const subscriptionTrialEnd = subscription.trial_end ? new Date(subscription.trial_end * 1000) : undefined; return { billingPeriod, pricePerSeat, paidSeats, + subscriptionStart, + subscriptionEnd, + subscriptionTrialEnd, }; } diff --git a/packages/features/ee/billing/lib/subscription-updates.ts b/packages/features/ee/billing/lib/subscription-updates.ts new file mode 100644 index 0000000000..a9980da013 --- /dev/null +++ b/packages/features/ee/billing/lib/subscription-updates.ts @@ -0,0 +1,30 @@ +import type { ISimpleLogger } from "@calcom/features/di/shared/services/logger.service"; + +import type { IBillingProviderService } from "../service/billingProvider/IBillingProviderService"; + +type ProrationBehavior = "none" | "create_prorations" | "always_invoice"; + +export async function updateSubscriptionQuantity(params: { + billingService: IBillingProviderService; + subscriptionId: string; + subscriptionItemId: string; + quantity: number; + prorationBehavior?: ProrationBehavior; + logger?: ISimpleLogger; +}): Promise { + const { billingService, subscriptionId, subscriptionItemId, quantity, prorationBehavior, logger } = params; + + try { + await billingService.handleSubscriptionUpdate({ + subscriptionId, + subscriptionItemId, + membershipCount: quantity, + ...(prorationBehavior ? { prorationBehavior } : {}), + }); + } catch (error) { + if (logger) { + logger.error(`Failed to update subscription ${subscriptionId} quantity to ${quantity}:`, error); + } + throw error; + } +} diff --git a/packages/features/ee/billing/repository/billing/IBillingRepository.ts b/packages/features/ee/billing/repository/billing/IBillingRepository.ts index a483d2d94b..3ad98a935c 100644 --- a/packages/features/ee/billing/repository/billing/IBillingRepository.ts +++ b/packages/features/ee/billing/repository/billing/IBillingRepository.ts @@ -25,8 +25,19 @@ export interface BillingRecord { status: SubscriptionStatus; } +export interface IBillingRepositoryUpdateArgs { + paidSeats?: number | null; + subscriptionStart?: Date | null; + subscriptionEnd?: Date | null; + subscriptionTrialEnd?: Date | null; + billingPeriod?: "MONTHLY" | "ANNUALLY" | null; + pricePerSeat?: number | null; +} + export interface IBillingRepository { create(args: IBillingRepositoryCreateArgs): Promise; + findBySubscriptionId(subscriptionId: string): Promise<{ id: string; teamId: number } | null>; + updateById(id: string, data: IBillingRepositoryUpdateArgs): Promise; } export interface IBillingRepositoryConstructorArgs { diff --git a/packages/features/ee/billing/repository/billing/PrismaOrganizationBillingRepository.ts b/packages/features/ee/billing/repository/billing/PrismaOrganizationBillingRepository.ts index 6783a47a02..5a4fdd8dad 100644 --- a/packages/features/ee/billing/repository/billing/PrismaOrganizationBillingRepository.ts +++ b/packages/features/ee/billing/repository/billing/PrismaOrganizationBillingRepository.ts @@ -1,8 +1,9 @@ import type { PrismaClient } from "@calcom/prisma"; -import { +import type { IBillingRepository, IBillingRepositoryCreateArgs, + IBillingRepositoryUpdateArgs, BillingRecord, Plan, SubscriptionStatus, @@ -23,4 +24,19 @@ export class PrismaOrganizationBillingRepository implements IBillingRepository { status: billingRecord.status as SubscriptionStatus, }; } + + async findBySubscriptionId(subscriptionId: string): Promise<{ id: string; teamId: number } | null> { + const record = await this.prismaClient.organizationBilling.findUnique({ + where: { subscriptionId }, + select: { id: true, teamId: true }, + }); + return record; + } + + async updateById(id: string, data: IBillingRepositoryUpdateArgs): Promise { + await this.prismaClient.organizationBilling.update({ + where: { id }, + data, + }); + } } diff --git a/packages/features/ee/billing/repository/billing/PrismaTeamBillingRepository.ts b/packages/features/ee/billing/repository/billing/PrismaTeamBillingRepository.ts index 685b39bdb6..cf6f3abf60 100644 --- a/packages/features/ee/billing/repository/billing/PrismaTeamBillingRepository.ts +++ b/packages/features/ee/billing/repository/billing/PrismaTeamBillingRepository.ts @@ -1,8 +1,9 @@ import type { PrismaClient } from "@calcom/prisma"; -import { +import type { IBillingRepository, IBillingRepositoryCreateArgs, + IBillingRepositoryUpdateArgs, BillingRecord, Plan, SubscriptionStatus, @@ -23,4 +24,19 @@ export class PrismaTeamBillingRepository implements IBillingRepository { status: billingRecord.status as SubscriptionStatus, }; } + + async findBySubscriptionId(subscriptionId: string): Promise<{ id: string; teamId: number } | null> { + const record = await this.prismaClient.teamBilling.findUnique({ + where: { subscriptionId }, + select: { id: true, teamId: true }, + }); + return record; + } + + async updateById(id: string, data: IBillingRepositoryUpdateArgs): Promise { + await this.prismaClient.teamBilling.update({ + where: { id }, + data, + }); + } } diff --git a/packages/features/ee/billing/repository/billing/StubBillingRepository.ts b/packages/features/ee/billing/repository/billing/StubBillingRepository.ts index c77d4a280e..abaed3e406 100644 --- a/packages/features/ee/billing/repository/billing/StubBillingRepository.ts +++ b/packages/features/ee/billing/repository/billing/StubBillingRepository.ts @@ -1,4 +1,9 @@ -import type { BillingRecord, IBillingRepository, IBillingRepositoryCreateArgs } from "./IBillingRepository"; +import type { + BillingRecord, + IBillingRepository, + IBillingRepositoryCreateArgs, + IBillingRepositoryUpdateArgs, +} from "./IBillingRepository"; export class StubBillingRepository implements IBillingRepository { async create(args: IBillingRepositoryCreateArgs): Promise { @@ -13,4 +18,13 @@ export class StubBillingRepository implements IBillingRepository { status: args.status, }; } + + async findBySubscriptionId(_subscriptionId: string): Promise<{ id: string; teamId: number } | null> { + // Stub implementation - returns null indicating no record found + return null; + } + + async updateById(_id: string, _data: IBillingRepositoryUpdateArgs): Promise { + // Stub implementation - no-op + } } diff --git a/packages/features/ee/billing/repository/proration/MonthlyProrationTeamRepository.ts b/packages/features/ee/billing/repository/proration/MonthlyProrationTeamRepository.ts index cb49d0cc71..45c23aed90 100644 --- a/packages/features/ee/billing/repository/proration/MonthlyProrationTeamRepository.ts +++ b/packages/features/ee/billing/repository/proration/MonthlyProrationTeamRepository.ts @@ -70,7 +70,9 @@ export class MonthlyProrationTeamRepository { if (!team) return null; - let billing: BillingInfo | null = team.isOrganization ? team.organizationBilling : team.teamBilling; + let billing: BillingInfo | null = team.isOrganization + ? team.organizationBilling + : team.teamBilling; if (!billing) { billing = this.extractBillingFromMetadata(team.metadata); @@ -92,13 +94,13 @@ export class MonthlyProrationTeamRepository { { teamBilling: { billingPeriod: "ANNUALLY", - subscriptionTrialEnd: { lt: new Date() }, + OR: [{ subscriptionTrialEnd: { lt: new Date() } }, { subscriptionTrialEnd: null }], }, }, { organizationBilling: { billingPeriod: "ANNUALLY", - subscriptionTrialEnd: { lt: new Date() }, + OR: [{ subscriptionTrialEnd: { lt: new Date() } }, { subscriptionTrialEnd: null }], }, }, ], @@ -162,6 +164,19 @@ export class MonthlyProrationTeamRepository { } } + async getTeamMemberCount(teamId: number): Promise { + const team = await this.prisma.team.findUnique({ + where: { id: teamId }, + select: { + _count: { + select: { members: true }, + }, + }, + }); + + return team?._count.members ?? null; + } + async createOrganizationBilling(data: { teamId: number; subscriptionId: string; diff --git a/packages/features/ee/billing/service/billingProvider/IBillingProviderService.ts b/packages/features/ee/billing/service/billingProvider/IBillingProviderService.ts index 71a3114046..8d9c1dca17 100644 --- a/packages/features/ee/billing/service/billingProvider/IBillingProviderService.ts +++ b/packages/features/ee/billing/service/billingProvider/IBillingProviderService.ts @@ -1,6 +1,6 @@ import type Stripe from "stripe"; -import { SubscriptionStatus } from "../../repository/billing/IBillingRepository"; +import type { SubscriptionStatus } from "../../repository/billing/IBillingRepository"; export interface IBillingProviderService { checkoutSessionIsPaid(paymentId: string): Promise; @@ -10,6 +10,7 @@ export interface IBillingProviderService { subscriptionId: string; subscriptionItemId: string; membershipCount: number; + prorationBehavior?: "none" | "create_prorations" | "always_invoice"; }): Promise; handleEndTrial(subscriptionId: string): Promise; @@ -72,17 +73,31 @@ export interface IBillingProviderService { amount: number; currency: string; description: string; + subscriptionId?: string; + invoiceId?: string; metadata?: Record; }): Promise<{ invoiceItemId: string }>; + deleteInvoiceItem(invoiceItemId: string): Promise; + createInvoice(args: { customerId: string; autoAdvance: boolean; + collectionMethod?: "charge_automatically" | "send_invoice"; + daysUntilDue?: number; + pendingInvoiceItemsBehavior?: "exclude" | "include"; + subscriptionId?: string; metadata?: Record; }): Promise<{ invoiceId: string }>; finalizeInvoice(invoiceId: string): Promise; + voidInvoice(invoiceId: string): Promise; + + getPaymentIntentFailureReason(paymentIntentId: string): Promise; + + hasDefaultPaymentMethod(args: { customerId: string; subscriptionId?: string }): Promise; + // Usage-based billing createSubscriptionUsageRecord(args: { subscriptionId: string; diff --git a/packages/features/ee/billing/service/billingProvider/StripeBillingService.test.ts b/packages/features/ee/billing/service/billingProvider/StripeBillingService.test.ts index 60acf3689c..1d2475e747 100644 --- a/packages/features/ee/billing/service/billingProvider/StripeBillingService.test.ts +++ b/packages/features/ee/billing/service/billingProvider/StripeBillingService.test.ts @@ -1,5 +1,5 @@ import type Stripe from "stripe"; -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { StripeBillingService } from "./StripeBillingService"; @@ -45,6 +45,15 @@ describe("StripeBillingService", () => { expect(stripeMock.subscriptions.update).toHaveBeenCalledWith(args.subscriptionId, { items: [{ quantity: args.membershipCount, id: args.subscriptionItemId }], }); + + await stripeBillingService.handleSubscriptionUpdate({ + ...args, + prorationBehavior: "none", + }); + expect(stripeMock.subscriptions.update).toHaveBeenCalledWith(args.subscriptionId, { + items: [{ quantity: args.membershipCount, id: args.subscriptionItemId }], + proration_behavior: "none", + }); }); it("should throw an error if subscription item is not found", async () => { diff --git a/packages/features/ee/billing/service/billingProvider/StripeBillingService.ts b/packages/features/ee/billing/service/billingProvider/StripeBillingService.ts index acc151cd72..f36597ab98 100644 --- a/packages/features/ee/billing/service/billingProvider/StripeBillingService.ts +++ b/packages/features/ee/billing/service/billingProvider/StripeBillingService.ts @@ -1,10 +1,11 @@ -import type Stripe from "stripe"; - import logger from "@calcom/lib/logger"; +import type Stripe from "stripe"; import { SubscriptionStatus } from "../../repository/billing/IBillingRepository"; import type { IBillingProviderService } from "./IBillingProviderService"; +const log = logger.getSubLogger({ prefix: ["StripeBillingService"] }); + export class StripeBillingService implements IBillingProviderService { constructor(private stripe: Stripe) {} @@ -138,7 +139,7 @@ export class StripeBillingService implements IBillingProviderService { } async handleSubscriptionUpdate(args: Parameters[0]) { - const { subscriptionId, subscriptionItemId, membershipCount } = args; + const { subscriptionId, subscriptionItemId, membershipCount, prorationBehavior } = args; const subscription = await this.stripe.subscriptions.retrieve(subscriptionId); const subscriptionQuantity = subscription.items.data.find( (sub) => sub.id === subscriptionItemId @@ -146,6 +147,7 @@ export class StripeBillingService implements IBillingProviderService { if (!subscriptionQuantity) throw new Error("Subscription not found"); await this.stripe.subscriptions.update(subscriptionId, { items: [{ quantity: membershipCount, id: subscriptionItemId }], + ...(prorationBehavior ? { proration_behavior: prorationBehavior } : {}), }); } @@ -245,23 +247,44 @@ export class StripeBillingService implements IBillingProviderService { } async createInvoiceItem(args: Parameters[0]) { - const { customerId, amount, currency, description, metadata } = args; + const { customerId, amount, currency, description, subscriptionId, invoiceId, metadata } = args; const invoiceItem = await this.stripe.invoiceItems.create({ customer: customerId, amount, currency, description, + invoice: invoiceId, + subscription: subscriptionId, metadata, }); return { invoiceItemId: invoiceItem.id }; } + async deleteInvoiceItem(invoiceItemId: string) { + await this.stripe.invoiceItems.del(invoiceItemId); + } + async createInvoice(args: Parameters[0]) { - const { customerId, autoAdvance, metadata } = args; + const { + customerId, + autoAdvance, + collectionMethod, + daysUntilDue, + pendingInvoiceItemsBehavior, + subscriptionId, + metadata, + } = args; const invoice = await this.stripe.invoices.create({ customer: customerId, auto_advance: autoAdvance, + collection_method: collectionMethod, + ...(pendingInvoiceItemsBehavior && !subscriptionId + ? { pending_invoice_items_behavior: pendingInvoiceItemsBehavior } + : {}), + subscription: subscriptionId, + // days_until_due is required for send_invoice collection method + ...(collectionMethod === "send_invoice" && { days_until_due: daysUntilDue ?? 30 }), metadata, }); @@ -272,15 +295,69 @@ export class StripeBillingService implements IBillingProviderService { await this.stripe.invoices.finalizeInvoice(invoiceId); } + async voidInvoice(invoiceId: string) { + try { + const invoice = await this.stripe.invoices.retrieve(invoiceId); + // Can only void invoices that are open or uncollectible + if (invoice.status === "open" || invoice.status === "uncollectible") { + await this.stripe.invoices.voidInvoice(invoiceId); + } else if (invoice.status === "draft") { + // Delete draft invoices instead of voiding + await this.stripe.invoices.del(invoiceId); + } + // If paid or void, no action needed + } catch (error) { + log.warn("Failed to void invoice", { invoiceId, error }); + throw error; + } + } + + async getPaymentIntentFailureReason(paymentIntentId: string) { + try { + const paymentIntent = await this.stripe.paymentIntents.retrieve(paymentIntentId); + return paymentIntent.last_payment_error?.message ?? null; + } catch (error) { + log.warn("Failed to retrieve payment intent failure reason", { paymentIntentId, error }); + return null; + } + } + + async hasDefaultPaymentMethod(args: Parameters[0]) { + const { customerId, subscriptionId } = args; + const subscription = subscriptionId ? await this.stripe.subscriptions.retrieve(subscriptionId) : null; + + const subscriptionDefault = subscription + ? typeof subscription.default_payment_method === "string" + ? subscription.default_payment_method + : subscription.default_payment_method?.id + : null; + + if (subscriptionDefault) { + return true; + } + + const customer = await this.stripe.customers.retrieve(customerId); + if (customer.deleted) { + return false; + } + + const customerDefault = + typeof customer.invoice_settings?.default_payment_method === "string" + ? customer.invoice_settings.default_payment_method + : customer.invoice_settings?.default_payment_method?.id; + + return Boolean(customerDefault); + } + async createSubscriptionUsageRecord( args: Parameters[0] ) { const { subscriptionId, action, quantity } = args; - const log = logger.getSubLogger({ prefix: ["createSubscriptionUsageRecord"] }); + const usageLog = logger.getSubLogger({ prefix: ["createSubscriptionUsageRecord"] }); const subscription = await this.stripe.subscriptions.retrieve(subscriptionId); if (!subscription?.id) { - log.error(`Failed to retrieve stripe subscription (${subscriptionId})`); + usageLog.error(`Failed to retrieve stripe subscription (${subscriptionId})`); throw new Error(`Failed to retrieve stripe subscription (${subscriptionId})`); } @@ -288,7 +365,7 @@ export class StripeBillingService implements IBillingProviderService { (item) => item.price?.recurring?.usage_type === "metered" ); if (!meteredItem) { - log.error(`Stripe subscription (${subscriptionId}) is not usage based`); + usageLog.error(`Stripe subscription (${subscriptionId}) is not usage based`); throw new Error(`Stripe subscription (${subscriptionId}) is not usage based`); } @@ -298,7 +375,7 @@ export class StripeBillingService implements IBillingProviderService { timestamp: "now", }); - log.info(`Created usage record for subscription ${subscriptionId}`, { + usageLog.info(`Created usage record for subscription ${subscriptionId}`, { subscriptionId, itemId: meteredItem.id, action, diff --git a/packages/features/ee/billing/service/proration/MonthlyProrationService.ts b/packages/features/ee/billing/service/proration/MonthlyProrationService.ts index a987e7c973..4ab88b2b47 100644 --- a/packages/features/ee/billing/service/proration/MonthlyProrationService.ts +++ b/packages/features/ee/billing/service/proration/MonthlyProrationService.ts @@ -1,7 +1,12 @@ -import stripe from "@calcom/features/ee/payments/server/stripe"; +import { getFeaturesRepository } from "@calcom/features/di/containers/FeaturesRepository"; import type { ISimpleLogger } from "@calcom/features/di/shared/services/logger.service"; +import stripe from "@calcom/features/ee/payments/server/stripe"; +import type { IFeaturesRepository } from "@calcom/features/flags/features.repository.interface"; import logger from "@calcom/lib/logger"; import type { Logger } from "tslog"; +import { buildMonthlyProrationMetadata } from "../../lib/proration-utils"; +import { extractBillingDataFromStripeSubscription } from "../../lib/stripe-subscription-utils"; +import { updateSubscriptionQuantity } from "../../lib/subscription-updates"; import { MonthlyProrationRepository } from "../../repository/proration/MonthlyProrationRepository"; import type { BillingInfo } from "../../repository/proration/MonthlyProrationTeamRepository"; import { MonthlyProrationTeamRepository } from "../../repository/proration/MonthlyProrationTeamRepository"; @@ -28,6 +33,8 @@ interface ProcessMonthlyProrationsParams { export interface MonthlyProrationServiceDeps { logger: ISimpleLogger; + featuresRepository: IFeaturesRepository; + billingService?: IBillingProviderService; } export class MonthlyProrationService { @@ -35,6 +42,7 @@ export class MonthlyProrationService { private teamRepository: MonthlyProrationTeamRepository; private prorationRepository: MonthlyProrationRepository; private billingService: IBillingProviderService; + private featuresRepository: IFeaturesRepository; constructor(deps: MonthlyProrationServiceDeps); constructor(customLogger?: Logger, billingService?: IBillingProviderService); @@ -44,18 +52,36 @@ export class MonthlyProrationService { ) { if (depsOrLogger && typeof depsOrLogger === "object" && "logger" in depsOrLogger) { this.logger = depsOrLogger.logger; + this.featuresRepository = depsOrLogger.featuresRepository; + this.billingService = depsOrLogger.billingService || new StripeBillingService(stripe); } else { this.logger = (depsOrLogger as Logger) || log; + this.featuresRepository = getFeaturesRepository(); + this.billingService = billingService || new StripeBillingService(stripe); } this.teamRepository = new MonthlyProrationTeamRepository(); this.prorationRepository = new MonthlyProrationRepository(); - this.billingService = billingService || new StripeBillingService(stripe); } async processMonthlyProrations(params: ProcessMonthlyProrationsParams) { const { monthKey, teamIds } = params; + const isFeatureEnabled = await this.featuresRepository.checkIfFeatureIsEnabledGlobally("monthly-proration"); + if (!isFeatureEnabled) { + this.logger.info("Monthly proration feature is not enabled, skipping batch processing", { monthKey }); + return []; + } + const teamIdsList = teamIds || (await this.teamRepository.getAnnualTeamsWithSeatChanges(monthKey)); + const teamIdsPreview = teamIds && teamIds.length <= 25 ? teamIds : undefined; + const teamIdsTruncated = teamIds ? teamIds.length > 25 : false; + + this.logger.info("Monthly proration batch started", { + monthKey, + teamCount: teamIdsList.length, + teamIds: teamIdsPreview, + teamIdsTruncated, + }); const teamsToProcess = teamIdsList.map((id: number) => ({ id })); @@ -68,18 +94,34 @@ export class MonthlyProrationService { if (result) results.push(result); } + this.logger.info("Monthly proration batch finished", { + monthKey, + teamCount: teamIdsList.length, + processedCount: results.length, + skippedCount: teamIdsList.length - results.length, + }); + return results; } async createProrationForTeam(params: CreateProrationParams) { const { teamId, monthKey } = params; + this.logger.info(`[${teamId}] starting monthly proration`, { monthKey }); + const seatTracker = new SeatChangeTrackingService(); const changes = await seatTracker.getMonthlyChanges({ teamId, monthKey }); + this.logger.info(`[${teamId}] seat changes`, { + additions: changes.additions, + removals: changes.removals, + netChange: changes.netChange, + }); + // If there are no changes at all (no additions or removals), skip processing if (changes.additions === 0 && changes.removals === 0) { + this.logger.info(`[${teamId}] no seat changes, skipping proration`); return null; } @@ -110,6 +152,12 @@ export class MonthlyProrationService { const paidSeats = billing.paidSeats ?? (await this.getSubscriptionQuantity(billing.subscriptionId)); + this.logger.info(`[${teamId}] billing summary`, { + billingPeriod: billing.billingPeriod, + pricePerSeat: billing.pricePerSeat, + paidSeats, + }); + const [year, month] = monthKey.split("-").map(Number); const periodEnd = new Date(Date.UTC(year, month, 0, 23, 59, 59, 999)); @@ -121,6 +169,13 @@ export class MonthlyProrationService { monthEnd: periodEnd, }); + this.logger.info(`[${teamId}] proration calculation`, { + netSeatIncrease: changes.netChange, + pricePerSeat: billing.pricePerSeat, + remainingDays: calculation.remainingDays, + proratedAmount: calculation.proratedAmount, + }); + const proration = await this.prorationRepository.createProration({ teamId, monthKey, @@ -143,6 +198,14 @@ export class MonthlyProrationService { organizationBillingId: teamWithBilling.isOrganization ? billing.id : null, }); + this.logger.info(`[${teamId}] proration record created`, { + prorationId: proration.id, + seatsAdded: proration.seatsAdded, + seatsRemoved: proration.seatsRemoved, + netSeatIncrease: proration.netSeatIncrease, + status: proration.status, + }); + await seatTracker.markAsProcessed({ teamId, monthKey, @@ -150,15 +213,32 @@ export class MonthlyProrationService { }); if (calculation.proratedAmount > 0) { + this.logger.info(`[${teamId}] creating invoice item`, { + prorationId: proration.id, + proratedAmount: proration.proratedAmount, + }); const updatedProration = await this.createStripeInvoiceItem(proration); + this.logger.info(`[${teamId}] invoice processed`, { + prorationId: updatedProration.id, + status: updatedProration.status, + invoiceId: updatedProration.invoiceId, + }); return updatedProration; } - await this.updateSubscriptionQuantity( - proration.subscriptionId, - proration.subscriptionItemId, - proration.seatsAtEnd - ); + this.logger.info(`[${teamId}] no charge required, updating subscription quantity`, { + prorationId: proration.id, + seatsAtEnd: proration.seatsAtEnd, + }); + + await updateSubscriptionQuantity({ + billingService: this.billingService, + subscriptionId: proration.subscriptionId, + subscriptionItemId: proration.subscriptionItemId, + quantity: proration.seatsAtEnd, + prorationBehavior: "none", + logger: this.logger, + }); await this.teamRepository.updatePaidSeats( teamId, @@ -167,9 +247,17 @@ export class MonthlyProrationService { proration.seatsAtEnd ); - return await this.prorationRepository.updateProrationStatus(proration.id, "CHARGED", { + const updatedProration = await this.prorationRepository.updateProrationStatus(proration.id, "CHARGED", { chargedAt: new Date(), }); + + this.logger.info(`[${teamId}] subscription updated without charge`, { + prorationId: updatedProration.id, + status: updatedProration.status, + seatsAtEnd: updatedProration.seatsAtEnd, + }); + + return updatedProration; } private calculateProration(params: { @@ -207,45 +295,110 @@ export class MonthlyProrationService { netSeatIncrease: number; monthKey: string; teamId: number; + subscriptionId: string; + remainingDays: number; + invoiceId?: string | null; }) { const amountInCents = Math.round(proration.proratedAmount); + const hasDefaultPaymentMethod = await this.billingService.hasDefaultPaymentMethod({ + customerId: proration.customerId, + subscriptionId: proration.subscriptionId, + }); + const { invoiceItemId } = await this.billingService.createInvoiceItem({ customerId: proration.customerId, amount: amountInCents, currency: "usd", description: `Additional ${proration.netSeatIncrease} seat${ proration.netSeatIncrease > 1 ? "s" : "" - } for ${proration.monthKey}`, - metadata: { - type: "monthly_proration", + } for ${proration.monthKey} (${proration.remainingDays} days remaining)`, + subscriptionId: proration.subscriptionId, + metadata: buildMonthlyProrationMetadata({ prorationId: proration.id, - teamId: proration.teamId.toString(), + teamId: proration.teamId, monthKey: proration.monthKey, - }, + }), }); - const { invoiceId } = await this.billingService.createInvoice({ - customerId: proration.customerId, - autoAdvance: true, - metadata: { - type: "monthly_proration", + let invoiceId: string | null = null; + let invoiceFinalized = false; + + try { + const invoice = await this.billingService.createInvoice({ + customerId: proration.customerId, + autoAdvance: true, + collectionMethod: hasDefaultPaymentMethod ? "charge_automatically" : "send_invoice", + subscriptionId: proration.subscriptionId, + metadata: buildMonthlyProrationMetadata({ prorationId: proration.id }), + }); + + invoiceId = invoice.invoiceId; + + await this.billingService.finalizeInvoice(invoiceId); + invoiceFinalized = true; + + return await this.prorationRepository.updateProrationStatus( + proration.id, + hasDefaultPaymentMethod ? "INVOICE_CREATED" : "PENDING", + { + invoiceItemId, + invoiceId, + } + ); + } catch (error) { + await this.handleInvoiceCreationFailure({ + error, prorationId: proration.id, - }, - }); - - await this.billingService.finalizeInvoice(invoiceId); - - const updatedProration = await this.prorationRepository.updateProrationStatus( - proration.id, - "INVOICE_CREATED", - { - invoiceItemId, invoiceId, - } - ); + invoiceItemId, + invoiceFinalized, + }); + throw error; + } + } - return updatedProration; + private async handleInvoiceCreationFailure(params: { + error: unknown; + prorationId: string; + invoiceId: string | null; + invoiceItemId: string; + invoiceFinalized: boolean; + }) { + const { error, prorationId, invoiceId, invoiceItemId, invoiceFinalized } = params; + + if (invoiceFinalized) { + // Invoice is live and potentially being charged - don't clean up + // The webhook will handle payment success/failure + this.logger.error("Proration status update failed after invoice finalized - webhook will handle", { + prorationId, + invoiceId, + error, + }); + return; + } + + // Invoice not yet live - mark as FAILED to enable retry via retryFailedProration() + const failureReason = error instanceof Error ? error.message : "Invoice creation failed"; + try { + await this.prorationRepository.updateProrationStatus(prorationId, "FAILED", { + failedAt: new Date(), + failureReason, + }); + } catch (statusError) { + this.logger.error("Failed to update proration status to FAILED", { prorationId, error: statusError }); + } + + // Clean up Stripe artifacts + try { + if (invoiceId) { + await this.billingService.voidInvoice(invoiceId); + } else { + await this.billingService.deleteInvoiceItem(invoiceItemId); + } + } catch (cleanupError) { + this.logger.error("Failed to clean up Stripe artifacts", { prorationId, invoiceId, invoiceItemId, error: cleanupError }); + } } async handleProrationPaymentSuccess(prorationId: string) { @@ -258,38 +411,23 @@ export class MonthlyProrationService { chargedAt: new Date(), }); - await this.updateSubscriptionQuantity( - proration.subscriptionId, - proration.subscriptionItemId, - proration.seatsAtEnd - ); + // Use the seat count that was captured when the proration was created. + // Any member changes after proration creation will be captured in the next month's cycle. + const seatsToApply = proration.seatsAtEnd; + + await updateSubscriptionQuantity({ + billingService: this.billingService, + subscriptionId: proration.subscriptionId, + subscriptionItemId: proration.subscriptionItemId, + quantity: seatsToApply, + prorationBehavior: "none", + logger: this.logger, + }); const billingId = proration.teamBillingId || proration.organizationBillingId; if (billingId) { const isOrganization = !!proration.organizationBillingId; - await this.teamRepository.updatePaidSeats( - proration.teamId, - isOrganization, - billingId, - proration.seatsAtEnd - ); - } - } - - private async updateSubscriptionQuantity( - subscriptionId: string, - subscriptionItemId: string, - quantity: number - ): Promise { - try { - await this.billingService.handleSubscriptionUpdate({ - subscriptionId, - subscriptionItemId, - membershipCount: quantity, - }); - } catch (error) { - this.logger.error(`Failed to update subscription ${subscriptionId} quantity to ${quantity}:`, error); - throw error; + await this.teamRepository.updatePaidSeats(proration.teamId, isOrganization, billingId, seatsToApply); } } @@ -312,6 +450,11 @@ export class MonthlyProrationService { if (!proration) throw new Error(`Proration ${prorationId} not found`); if (proration.status !== "FAILED") throw new Error(`Proration ${prorationId} is not in FAILED status`); + // Void the old invoice to prevent double charging + if (proration.invoiceId) { + await this.billingService.voidInvoice(proration.invoiceId); + } + await this.createStripeInvoiceItem(proration); } @@ -337,25 +480,21 @@ export class MonthlyProrationService { throw new Error(`Subscription ${billing.subscriptionId} not found`); } - const billingPeriod: "ANNUALLY" | "MONTHLY" = - subscription.items[0]?.price.recurring?.interval === "year" ? "ANNUALLY" : "MONTHLY"; - - const pricePerSeat = subscription.items[0]?.price.unit_amount ?? 0; - - const subscriptionStart = subscription.current_period_start - ? new Date(subscription.current_period_start * 1000) - : null; - - const subscriptionEnd = subscription.current_period_end - ? new Date(subscription.current_period_end * 1000) - : null; + const { + billingPeriod, + pricePerSeat: rawPricePerSeat, + paidSeats: rawPaidSeats, + subscriptionStart, + subscriptionEnd, + subscriptionTrialEnd, + } = extractBillingDataFromStripeSubscription(subscription); + const pricePerSeat = rawPricePerSeat ?? 0; + const paidSeats = rawPaidSeats ?? 0; const subscriptionItemId = subscription.items[0]?.id || billing.subscriptionItemId || ""; const customerId = subscription.customer; - const subscriptionTrialEnd = subscription.trial_end ? new Date(subscription.trial_end * 1000) : null; if (needsCreation) { - const paidSeats = subscription.items[0]?.quantity || 0; const billingData = { teamId, subscriptionId: billing.subscriptionId, @@ -366,9 +505,9 @@ export class MonthlyProrationService { billingPeriod, pricePerSeat, paidSeats, - subscriptionStart, - subscriptionEnd, - subscriptionTrialEnd, + subscriptionStart: subscriptionStart ?? null, + subscriptionEnd: subscriptionEnd ?? null, + subscriptionTrialEnd: subscriptionTrialEnd ?? null, }; const createdBilling = isOrganization @@ -394,8 +533,8 @@ export class MonthlyProrationService { billing.billingPeriod = billingPeriod; billing.pricePerSeat = pricePerSeat; - billing.subscriptionStart = subscriptionStart; - billing.subscriptionEnd = subscriptionEnd; + billing.subscriptionStart = subscriptionStart ?? null; + billing.subscriptionEnd = subscriptionEnd ?? null; billing.subscriptionItemId = subscriptionItemId; if (needsCreation) { billing.customerId = customerId; diff --git a/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.integration-test.ts b/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.integration-test.ts index fdd5670e3d..ac36ce508d 100644 --- a/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.integration-test.ts +++ b/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.integration-test.ts @@ -1,13 +1,18 @@ +import { TeamService } from "@calcom/features/ee/teams/services/teamService"; +import type { IFeaturesRepository } from "@calcom/features/flags/features.repository.interface"; import prisma from "@calcom/prisma"; import type { Team, User } from "@calcom/prisma/client"; import { MembershipRole } from "@calcom/prisma/enums"; +import { createMemberships } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { buildMonthlyProrationMetadata } from "../../../lib/proration-utils"; import type { IBillingProviderService } from "../../billingProvider/IBillingProviderService"; import { SeatChangeTrackingService } from "../../seatTracking/SeatChangeTrackingService"; import { MonthlyProrationService } from "../MonthlyProrationService"; const mockBillingService: IBillingProviderService = { createInvoiceItem: vi.fn().mockResolvedValue({ invoiceItemId: "ii_test_123" }), + deleteInvoiceItem: vi.fn().mockResolvedValue(undefined), createInvoice: vi.fn().mockResolvedValue({ invoiceId: "in_test_123" }), finalizeInvoice: vi.fn().mockResolvedValue(undefined), getSubscription: vi.fn().mockResolvedValue({ @@ -38,11 +43,38 @@ const mockBillingService: IBillingProviderService = { getCustomer: vi.fn().mockResolvedValue(null), getSubscriptions: vi.fn().mockResolvedValue(null), updateCustomer: vi.fn().mockResolvedValue(undefined), + getPaymentIntentFailureReason: vi.fn().mockResolvedValue(null), + hasDefaultPaymentMethod: vi.fn().mockResolvedValue(true), } as IBillingProviderService; +const mockFeaturesRepository: IFeaturesRepository = { + checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(true), + checkIfUserHasFeature: vi.fn().mockResolvedValue(false), + getUserFeaturesStatus: vi.fn().mockResolvedValue({}), + checkIfUserHasFeatureNonHierarchical: vi.fn().mockResolvedValue(false), + checkIfTeamHasFeature: vi.fn().mockResolvedValue(false), + getTeamsWithFeatureEnabled: vi.fn().mockResolvedValue([]), + setUserFeatureState: vi.fn().mockResolvedValue(undefined), + setTeamFeatureState: vi.fn().mockResolvedValue(undefined), + getUserFeatureStates: vi.fn().mockResolvedValue({}), + getTeamsFeatureStates: vi.fn().mockResolvedValue({}), + getUserAutoOptIn: vi.fn().mockResolvedValue(false), + getTeamsAutoOptIn: vi.fn().mockResolvedValue({}), + setUserAutoOptIn: vi.fn().mockResolvedValue(undefined), + setTeamAutoOptIn: vi.fn().mockResolvedValue(undefined), +}; + +const mockLogger = { + info: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + debug: vi.fn(), +}; + describe("MonthlyProrationService Integration Tests", () => { let testUser: User; let testTeam: Team; + let billingCustomerId: string; const monthKey = "2026-01"; beforeEach(async () => { @@ -78,12 +110,14 @@ describe("MonthlyProrationService Integration Tests", () => { const subscriptionEnd = new Date("2026-06-01T00:00:00Z"); const subscriptionTrialEnd = new Date("2025-06-08T00:00:00Z"); + billingCustomerId = `cus_test_${timestamp}`; + await prisma.teamBilling.create({ data: { teamId: testTeam.id, subscriptionId: `sub_test_${timestamp}`, subscriptionItemId: `si_test_${timestamp}`, - customerId: `cus_test_${timestamp}`, + customerId: billingCustomerId, billingPeriod: "ANNUALLY", pricePerSeat: 12000, paidSeats: 0, @@ -97,21 +131,50 @@ describe("MonthlyProrationService Integration Tests", () => { }); it("should process end-to-end proration for annual team with seat additions", async () => { - const seatTracker = new SeatChangeTrackingService(); const prorationService = new MonthlyProrationService(undefined, mockBillingService); + const timestamp = Date.now(); + const randomSuffix = Math.random().toString(36).substring(7); - await seatTracker.logSeatAddition({ + vi.mocked(mockBillingService.createInvoice).mockClear(); + vi.mocked(mockBillingService.createInvoiceItem).mockClear(); + + const newMembers = await Promise.all( + [0, 1, 2].map((index) => + prisma.user.create({ + data: { + email: `test-proration-member-${timestamp}-${randomSuffix}-${index}@example.com`, + username: `testprorationmember-${timestamp}-${randomSuffix}-${index}`, + name: `Test Proration Member ${index}`, + }, + select: { + id: true, + email: true, + username: true, + identityProvider: true, + completedOnboarding: true, + }, + }) + ) + ); + + await createMemberships({ teamId: testTeam.id, - userId: testUser.id, - triggeredBy: testUser.id, - seatCount: 3, + language: "en", + invitees: newMembers.map((member) => ({ + ...member, + profiles: [], + teams: [], + password: null, + newRole: MembershipRole.MEMBER, + needToCreateOrgMembership: false, + })), + parentId: null, + accepted: true, }); - await seatTracker.logSeatRemoval({ + await TeamService.leaveTeamMembership({ teamId: testTeam.id, - userId: testUser.id, - triggeredBy: testUser.id, - seatCount: 1, + userId: newMembers[0].id, }); const proration = await prorationService.createProrationForTeam({ @@ -125,6 +188,13 @@ describe("MonthlyProrationService Integration Tests", () => { expect(proration?.seatsRemoved).toBe(1); expect(proration?.status).toBe("INVOICE_CREATED"); expect(proration?.invoiceItemId).toBe("ii_test_123"); + expect(mockBillingService.createInvoice).toHaveBeenCalledWith({ + customerId: billingCustomerId, + autoAdvance: true, + collectionMethod: "charge_automatically", + subscriptionId: proration!.subscriptionId, + metadata: buildMonthlyProrationMetadata({ prorationId: proration!.id }), + }); const seatChanges = await prisma.seatChangeLog.findMany({ where: { teamId: testTeam.id, monthKey }, @@ -226,7 +296,11 @@ describe("MonthlyProrationService Integration Tests", () => { seatCount: 3, }); - const prorationService = new MonthlyProrationService(undefined, mockBillingService); + const prorationService = new MonthlyProrationService({ + logger: mockLogger, + featuresRepository: mockFeaturesRepository, + billingService: mockBillingService, + }); const results = await prorationService.processMonthlyProrations({ monthKey }); const filteredResults = results.filter((r) => [testTeam.id, testTeam2.id].includes(r.teamId)); @@ -321,6 +395,7 @@ describe("MonthlyProrationService Integration Tests", () => { subscriptionId: proration!.subscriptionId, subscriptionItemId: proration!.subscriptionItemId, membershipCount: proration!.seatsAtEnd, + prorationBehavior: "none", }); }); diff --git a/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.test.ts b/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.test.ts index a037fdec30..1662e98251 100644 --- a/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.test.ts +++ b/packages/features/ee/billing/service/proration/__tests__/MonthlyProrationService.test.ts @@ -1,7 +1,7 @@ import { prisma } from "@calcom/prisma"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { buildMonthlyProrationMetadata } from "../../../lib/proration-utils"; import type { IBillingProviderService } from "../../billingProvider/IBillingProviderService"; - import { MonthlyProrationService } from "../MonthlyProrationService"; vi.mock("@calcom/prisma", () => ({ @@ -59,6 +59,7 @@ const mockTeamRepository = { getTeamWithBilling: vi.fn(), getAnnualTeamsWithSeatChanges: vi.fn(), updatePaidSeats: vi.fn(), + getTeamMemberCount: vi.fn(), }; const mockProrationRepository = { @@ -69,6 +70,7 @@ const mockProrationRepository = { const mockBillingService: IBillingProviderService = { createInvoiceItem: vi.fn().mockResolvedValue({ invoiceItemId: "ii_test_123" }), + deleteInvoiceItem: vi.fn().mockResolvedValue(undefined), createInvoice: vi.fn().mockResolvedValue({ invoiceId: "in_test_123" }), finalizeInvoice: vi.fn().mockResolvedValue(undefined), getSubscription: vi.fn().mockResolvedValue({ @@ -98,6 +100,9 @@ const mockBillingService: IBillingProviderService = { getCustomer: vi.fn().mockResolvedValue(null), getSubscriptions: vi.fn().mockResolvedValue(null), updateCustomer: vi.fn().mockResolvedValue(undefined), + getPaymentIntentFailureReason: vi.fn().mockResolvedValue(null), + hasDefaultPaymentMethod: vi.fn().mockResolvedValue(true), + voidInvoice: vi.fn().mockResolvedValue(undefined), } as IBillingProviderService; vi.mock("../../../repository/proration/MonthlyProrationTeamRepository", () => ({ @@ -105,6 +110,7 @@ vi.mock("../../../repository/proration/MonthlyProrationTeamRepository", () => ({ getTeamWithBilling = mockTeamRepository.getTeamWithBilling; getAnnualTeamsWithSeatChanges = mockTeamRepository.getAnnualTeamsWithSeatChanges; updatePaidSeats = mockTeamRepository.updatePaidSeats; + getTeamMemberCount = mockTeamRepository.getTeamMemberCount; }, })); @@ -182,6 +188,7 @@ describe("MonthlyProrationService", () => { subscriptionId: "sub_123", subscriptionItemId: "si_123", membershipCount: 10, + prorationBehavior: "none", }); }); @@ -238,6 +245,134 @@ describe("MonthlyProrationService", () => { expect(mockBillingService.finalizeInvoice).toHaveBeenCalled(); }); + it("should charge only for net additions when removals exist", async () => { + const subscriptionStart = new Date("2026-01-01"); + const subscriptionEnd = new Date("2027-01-01"); + + const { SeatChangeTrackingService } = await import("../../seatTracking/SeatChangeTrackingService"); + vi.spyOn(SeatChangeTrackingService.prototype, "getMonthlyChanges").mockResolvedValueOnce({ + additions: 20, + removals: 10, + netChange: 10, + }); + vi.spyOn(SeatChangeTrackingService.prototype, "markAsProcessed").mockResolvedValueOnce(10); + + mockTeamRepository.getTeamWithBilling.mockResolvedValueOnce({ + id: 1, + isOrganization: false, + memberCount: 120, + billing: { + id: "team-billing-999", + subscriptionId: "sub_999", + subscriptionItemId: "si_999", + customerId: "cus_999", + billingPeriod: "ANNUALLY", + pricePerSeat: 10000, + subscriptionStart, + subscriptionEnd, + paidSeats: 110, + }, + }); + + mockProrationRepository.createProration.mockResolvedValueOnce({ + id: "proration-999", + customerId: "cus_999", + proratedAmount: 25000, + netSeatIncrease: 10, + monthKey: "2026-01", + teamId: 1, + subscriptionId: "sub_999", + subscriptionItemId: "si_999", + seatsAtEnd: 120, + } as any); + + mockProrationRepository.updateProrationStatus.mockResolvedValueOnce({ + id: "proration-999", + status: "INVOICE_CREATED", + } as any); + + await service.createProrationForTeam({ + teamId: 1, + monthKey: "2026-01", + }); + + expect(mockProrationRepository.createProration).toHaveBeenCalledWith( + expect.objectContaining({ + seatsAdded: 20, + seatsRemoved: 10, + netSeatIncrease: 10, + seatsAtStart: 110, + seatsAtEnd: 120, + }) + ); + expect(mockBillingService.createInvoiceItem).toHaveBeenCalledWith( + expect.objectContaining({ + subscriptionId: "sub_999", + }) + ); + expect(mockBillingService.createInvoice).toHaveBeenCalled(); + }); + + it("should send invoice when no default payment method exists", async () => { + const subscriptionStart = new Date("2026-01-01"); + const subscriptionEnd = new Date("2027-01-01"); + + const { SeatChangeTrackingService } = await import("../../seatTracking/SeatChangeTrackingService"); + vi.spyOn(SeatChangeTrackingService.prototype, "markAsProcessed").mockResolvedValueOnce(2); + vi.mocked(mockBillingService.hasDefaultPaymentMethod).mockResolvedValueOnce(false); + + mockTeamRepository.getTeamWithBilling.mockResolvedValueOnce({ + id: 1, + isOrganization: false, + memberCount: 12, + billing: { + id: "team-billing-789", + subscriptionId: "sub_789", + subscriptionItemId: "si_789", + customerId: "cus_789", + billingPeriod: "ANNUALLY", + pricePerSeat: 10000, + subscriptionStart, + subscriptionEnd, + paidSeats: 10, + }, + }); + + mockProrationRepository.createProration.mockResolvedValueOnce({ + id: "proration-789", + customerId: "cus_789", + proratedAmount: 5000, + netSeatIncrease: 2, + monthKey: "2026-01", + teamId: 1, + subscriptionId: "sub_789", + subscriptionItemId: "si_789", + seatsAtEnd: 12, + } as any); + + mockProrationRepository.updateProrationStatus.mockResolvedValueOnce({ + id: "proration-789", + status: "PENDING", + } as any); + + await service.createProrationForTeam({ + teamId: 1, + monthKey: "2026-01", + }); + + expect(mockBillingService.createInvoice).toHaveBeenCalledWith({ + customerId: "cus_789", + autoAdvance: true, + collectionMethod: "send_invoice", + subscriptionId: "sub_789", + metadata: buildMonthlyProrationMetadata({ prorationId: "proration-789" }), + }); + expect(mockProrationRepository.updateProrationStatus).toHaveBeenCalledWith("proration-789", "PENDING", { + invoiceItemId: "ii_test_123", + invoiceId: "in_test_123", + }); + }); + it("should use organization billing for organizations", async () => { const { SeatChangeTrackingService } = await import("../../seatTracking/SeatChangeTrackingService"); vi.spyOn(SeatChangeTrackingService.prototype, "markAsProcessed").mockResolvedValueOnce(3); @@ -309,7 +444,7 @@ describe("MonthlyProrationService", () => { }); describe("handleProrationPaymentSuccess", () => { - it("should update proration status to CHARGED", async () => { + it("should update proration status to CHARGED using seatsAtEnd from proration record", async () => { mockProrationRepository.findById.mockResolvedValueOnce({ id: "proration-123", status: "INVOICE_CREATED", @@ -328,11 +463,14 @@ describe("MonthlyProrationService", () => { expect(mockProrationRepository.updateProrationStatus).toHaveBeenCalledWith("proration-123", "CHARGED", { chargedAt: expect.any(Date), }); + // Should use seatsAtEnd from proration record, not current member count expect(mockBillingService.handleSubscriptionUpdate).toHaveBeenCalledWith({ subscriptionId: "sub_123", subscriptionItemId: "si_123", membershipCount: 13, + prorationBehavior: "none", }); + expect(mockTeamRepository.updatePaidSeats).toHaveBeenCalledWith(1, false, "billing-123", 13); }); }); diff --git a/packages/features/ee/billing/service/seatTracking/SeatChangeTrackingService.ts b/packages/features/ee/billing/service/seatTracking/SeatChangeTrackingService.ts index c6e405d309..76accd74ec 100644 --- a/packages/features/ee/billing/service/seatTracking/SeatChangeTrackingService.ts +++ b/packages/features/ee/billing/service/seatTracking/SeatChangeTrackingService.ts @@ -1,11 +1,7 @@ import { formatMonthKey } from "@calcom/features/ee/billing/lib/month-key"; import { SeatChangeLogRepository } from "@calcom/features/ee/billing/repository/seatChangeLogs/SeatChangeLogRepository"; -import logger from "@calcom/lib/logger"; import type { Prisma } from "@calcom/prisma/client"; import type { SeatChangeType } from "@calcom/prisma/enums"; -import type { Logger } from "tslog"; - -const log = logger.getSubLogger({ prefix: ["SeatChangeTrackingService"] }); export interface SeatChangeLogParams { teamId: number; @@ -26,11 +22,9 @@ export interface MonthlyChanges { } export class SeatChangeTrackingService { - private logger: Logger; private repository: SeatChangeLogRepository; - constructor(customLogger?: Logger, repository?: SeatChangeLogRepository) { - this.logger = customLogger || log; + constructor(repository?: SeatChangeLogRepository) { this.repository = repository || new SeatChangeLogRepository(); } diff --git a/packages/features/ee/billing/service/teams/TeamBillingFactory.test.ts b/packages/features/ee/billing/service/teams/TeamBillingFactory.test.ts index 8a7b7c596b..aac1582bbb 100644 --- a/packages/features/ee/billing/service/teams/TeamBillingFactory.test.ts +++ b/packages/features/ee/billing/service/teams/TeamBillingFactory.test.ts @@ -19,19 +19,31 @@ describe("TeamBilling", () => { const createMockBillingProviderService = (): IBillingProviderService => ({ handleSubscriptionCancel: vi.fn(), handleSubscriptionUpdate: vi.fn(), + handleSubscriptionCreation: vi.fn(), checkoutSessionIsPaid: vi.fn(), getSubscriptionStatus: vi.fn(), handleEndTrial: vi.fn(), createCustomer: vi.fn(), + createPaymentIntent: vi.fn(), + createSubscriptionCheckout: vi.fn(), createPrice: vi.fn(), getPrice: vi.fn(), getCheckoutSession: vi.fn(), - createCheckoutSession: vi.fn(), + getCustomer: vi.fn(), + getSubscriptions: vi.fn(), + updateCustomer: vi.fn(), + createInvoiceItem: vi.fn(), + deleteInvoiceItem: vi.fn(), + createInvoice: vi.fn(), + finalizeInvoice: vi.fn(), + getSubscription: vi.fn(), + getPaymentIntentFailureReason: vi.fn(), }); const createMockTeamBillingDataRepository = (): ITeamBillingDataRepository => ({ find: vi.fn(), findMany: vi.fn(), + findBySubscriptionId: vi.fn(), }); const createMockBillingRepository = (): IBillingRepository => ({ diff --git a/packages/features/ee/billing/service/teams/TeamBillingService.test.ts b/packages/features/ee/billing/service/teams/TeamBillingService.test.ts index 6e6605697e..09aec002c8 100644 --- a/packages/features/ee/billing/service/teams/TeamBillingService.test.ts +++ b/packages/features/ee/billing/service/teams/TeamBillingService.test.ts @@ -1,11 +1,9 @@ -import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock"; - -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - import { purchaseTeamOrOrgSubscription } from "@calcom/features/ee/teams/lib/payments"; import { WEBAPP_URL } from "@calcom/lib/constants"; - +import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { IBillingRepository } from "../../repository/billing/IBillingRepository"; +import { Plan, SubscriptionStatus } from "../../repository/billing/IBillingRepository"; import type { ITeamBillingDataRepository } from "../../repository/teamBillingData/ITeamBillingDataRepository"; import type { IBillingProviderService } from "../billingProvider/IBillingProviderService"; import { TeamBillingPublishResponseStatus } from "./ITeamBillingService"; @@ -23,6 +21,14 @@ vi.mock("@calcom/features/ee/teams/lib/payments", () => ({ purchaseTeamOrOrgSubscription: vi.fn(), })); +const shouldApplyMonthlyProration = vi.fn().mockResolvedValue(false); + +vi.mock("../billingPeriod/BillingPeriodService", () => ({ + BillingPeriodService: class { + shouldApplyMonthlyProration = shouldApplyMonthlyProration; + }, +})); + const mockTeam = { id: 1, metadata: { @@ -37,18 +43,32 @@ const mockTeam = { const createMockBillingProviderService = (): IBillingProviderService => ({ handleSubscriptionCancel: vi.fn(), handleSubscriptionUpdate: vi.fn(), + handleSubscriptionCreation: vi.fn(), checkoutSessionIsPaid: vi.fn(), getSubscriptionStatus: vi.fn(), handleEndTrial: vi.fn(), createCustomer: vi.fn(), + createPaymentIntent: vi.fn(), + createSubscriptionCheckout: vi.fn(), createPrice: vi.fn(), getPrice: vi.fn(), getCheckoutSession: vi.fn(), - createCheckoutSession: vi.fn(), + getCustomer: vi.fn(), + getSubscriptions: vi.fn(), + updateCustomer: vi.fn(), + createInvoiceItem: vi.fn(), + deleteInvoiceItem: vi.fn(), + createInvoice: vi.fn(), + finalizeInvoice: vi.fn(), + getSubscription: vi.fn(), + getPaymentIntentFailureReason: vi.fn(), + hasDefaultPaymentMethod: vi.fn(), }); const createMockTeamBillingDataRepository = (): ITeamBillingDataRepository => ({ find: vi.fn(), + findMany: vi.fn(), + findBySubscriptionId: vi.fn(), }); const createMockBillingRepository = (): IBillingRepository => ({ @@ -164,6 +184,7 @@ describe("TeamBillingService", () => { paymentId: "cs_789", paymentRequired: false, }); + shouldApplyMonthlyProration.mockResolvedValue(false); await teamBillingService.updateQuantity(); @@ -173,6 +194,31 @@ describe("TeamBillingService", () => { membershipCount: 10, }); }); + + it("should skip subscription updates when monthly proration applies", async () => { + const mockTeamNotOrg = { + ...mockTeam, + isOrganization: false, + }; + const teamBillingService = new TeamBillingService({ + team: mockTeamNotOrg, + billingProviderService: mockBillingProviderService, + teamBillingDataRepository: mockTeamBillingDataRepository, + billingRepository: mockBillingRepository, + }); + + prismaMock.membership.count.mockResolvedValue(10); + vi.spyOn(teamBillingService, "checkIfTeamPaymentRequired").mockResolvedValue({ + url: "http://checkout.url", + paymentId: "cs_789", + paymentRequired: false, + }); + shouldApplyMonthlyProration.mockResolvedValue(true); + + await teamBillingService.updateQuantity(); + + expect(mockBillingProviderService.handleSubscriptionUpdate).not.toHaveBeenCalled(); + }); }); describe("checkIfTeamPaymentRequired", () => { @@ -244,8 +290,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_org_123", subscriptionItemId: "si_org_123", customerId: "cus_org_123", - planName: "ORGANIZATION" as const, - status: "ACTIVE" as const, + planName: Plan.ORGANIZATION, + status: SubscriptionStatus.ACTIVE, }; const mockCreatedRecord = { @@ -282,8 +328,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_team_456", subscriptionItemId: "si_team_456", customerId: "cus_team_456", - planName: "TEAM" as const, - status: "ACTIVE" as const, + planName: Plan.TEAM, + status: SubscriptionStatus.ACTIVE, }; const mockCreatedRecord = { @@ -320,8 +366,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_detailed_789", subscriptionItemId: "si_detailed_789", customerId: "cus_detailed_789", - planName: "ENTERPRISE" as const, - status: "TRIALING" as const, + planName: Plan.ENTERPRISE, + status: SubscriptionStatus.TRIALING, }; const mockCreatedRecord = { @@ -348,8 +394,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_detailed_789", subscriptionItemId: "si_detailed_789", customerId: "cus_detailed_789", - planName: "ENTERPRISE", - status: "TRIALING", + planName: Plan.ENTERPRISE, + status: SubscriptionStatus.TRIALING, }) ); }); @@ -367,8 +413,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_error_999", subscriptionItemId: "si_error_999", customerId: "cus_error_999", - planName: "TEAM" as const, - status: "ACTIVE" as const, + planName: Plan.TEAM, + status: SubscriptionStatus.ACTIVE, }; const repositoryError = new Error("Database constraint violation"); diff --git a/packages/features/ee/billing/service/teams/TeamBillingService.ts b/packages/features/ee/billing/service/teams/TeamBillingService.ts index 143a9f5827..a17d262163 100644 --- a/packages/features/ee/billing/service/teams/TeamBillingService.ts +++ b/packages/features/ee/billing/service/teams/TeamBillingService.ts @@ -1,5 +1,3 @@ -import type { z } from "zod"; - import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing"; import { purchaseTeamOrOrgSubscription } from "@calcom/features/ee/teams/lib/payments"; import { WEBAPP_URL } from "@calcom/lib/constants"; @@ -10,18 +8,20 @@ import { safeStringify } from "@calcom/lib/safeStringify"; import { prisma } from "@calcom/prisma"; import type { Prisma } from "@calcom/prisma/client"; import { teamMetadataStrictSchema } from "@calcom/prisma/zod-utils"; - +import type { z } from "zod"; +import { updateSubscriptionQuantity } from "../../lib/subscription-updates"; // import billing from "../.."; import type { IBillingRepository, IBillingRepositoryCreateArgs, } from "../../repository/billing/IBillingRepository"; -import { ITeamBillingDataRepository } from "../../repository/teamBillingData/ITeamBillingDataRepository"; +import type { ITeamBillingDataRepository } from "../../repository/teamBillingData/ITeamBillingDataRepository"; +import { BillingPeriodService } from "../billingPeriod/BillingPeriodService"; import type { IBillingProviderService } from "../billingProvider/IBillingProviderService"; import { - TeamBillingPublishResponseStatus, type ITeamBillingService, type TeamBillingInput, + TeamBillingPublishResponseStatus, } from "./ITeamBillingService"; const log = logger.getSubLogger({ prefix: ["TeamBilling"] }); @@ -165,10 +165,19 @@ export class TeamBillingService implements ITeamBillingService { const membershipCount = await prisma.membership.count({ where: { teamId } }); if (!subscriptionId) throw Error("missing subscriptionId"); if (!subscriptionItemId) throw Error("missing subscriptionItemId"); - await this.billingProviderService.handleSubscriptionUpdate({ + + const billingPeriodService = new BillingPeriodService(); + const shouldApplyMonthlyProration = await billingPeriodService.shouldApplyMonthlyProration(teamId); + if (shouldApplyMonthlyProration) { + log.info(`Skipping subscription update for team ${teamId} because monthly proration is enabled.`); + return; + } + + await updateSubscriptionQuantity({ + billingService: this.billingProviderService, subscriptionId, subscriptionItemId, - membershipCount, + quantity: membershipCount, }); log.info(`Updated subscription ${subscriptionId} for team ${teamId} to ${membershipCount} seats.`); } catch (error) { @@ -221,6 +230,6 @@ export class TeamBillingService implements ITeamBillingService { } } async saveTeamBilling(args: IBillingRepositoryCreateArgs) { -await this.billingRepository.create(args); + await this.billingRepository.create(args); } } diff --git a/packages/features/ee/billing/teams/internal-team-billing.test.ts b/packages/features/ee/billing/teams/internal-team-billing.test.ts index dac7e034bd..1109fff3ee 100644 --- a/packages/features/ee/billing/teams/internal-team-billing.test.ts +++ b/packages/features/ee/billing/teams/internal-team-billing.test.ts @@ -1,11 +1,9 @@ -import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock"; - -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - import { purchaseTeamOrOrgSubscription } from "@calcom/features/ee/teams/lib/payments"; import { WEBAPP_URL } from "@calcom/lib/constants"; - +import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { IBillingRepository } from "../repository/billing/IBillingRepository"; +import { Plan, SubscriptionStatus } from "../repository/billing/IBillingRepository"; import type { ITeamBillingDataRepository } from "../repository/teamBillingData/ITeamBillingDataRepository"; import type { IBillingProviderService } from "../service/billingProvider/IBillingProviderService"; import { TeamBillingPublishResponseStatus } from "../service/teams/ITeamBillingService"; @@ -22,6 +20,14 @@ vi.mock("@calcom/lib/constants", async () => { vi.mock("@calcom/features/ee/teams/lib/payments", () => ({ purchaseTeamOrOrgSubscription: vi.fn(), })); + +const shouldApplyMonthlyProration = vi.fn().mockResolvedValue(false); + +vi.mock("../service/billingPeriod/BillingPeriodService", () => ({ + BillingPeriodService: class { + shouldApplyMonthlyProration = shouldApplyMonthlyProration; + }, +})); const mockTeam = { id: 1, metadata: { @@ -45,13 +51,32 @@ describe("TeamBillingService", () => { mockBillingProviderService = { handleSubscriptionCancel: vi.fn(), handleSubscriptionUpdate: vi.fn(), + handleSubscriptionCreation: vi.fn(), checkoutSessionIsPaid: vi.fn(), getSubscriptionStatus: vi.fn(), handleEndTrial: vi.fn(), + createCustomer: vi.fn(), + createPaymentIntent: vi.fn(), + createSubscriptionCheckout: vi.fn(), + createPrice: vi.fn(), + getPrice: vi.fn(), + getCheckoutSession: vi.fn(), + getCustomer: vi.fn(), + getSubscriptions: vi.fn(), + updateCustomer: vi.fn(), + createInvoiceItem: vi.fn(), + deleteInvoiceItem: vi.fn(), + createInvoice: vi.fn(), + finalizeInvoice: vi.fn(), + getSubscription: vi.fn(), + getPaymentIntentFailureReason: vi.fn(), + hasDefaultPaymentMethod: vi.fn(), } as IBillingProviderService; mockTeamBillingDataRepository = { find: vi.fn(), + findMany: vi.fn(), + findBySubscriptionId: vi.fn(), } as unknown as ITeamBillingDataRepository; mockBillingRepository = { @@ -141,6 +166,7 @@ describe("TeamBillingService", () => { paymentId: "cs_789", paymentRequired: false, }); + shouldApplyMonthlyProration.mockResolvedValue(false); await teamBillingServiceNotOrg.updateQuantity(); @@ -150,6 +176,30 @@ describe("TeamBillingService", () => { membershipCount: 10, }); }); + + it("should skip subscription updates when monthly proration applies", async () => { + const mockTeamNotOrg = { + ...mockTeam, + isOrganization: false, + }; + const teamBillingServiceNotOrg = new TeamBillingService({ + team: mockTeamNotOrg, + billingProviderService: mockBillingProviderService, + teamBillingDataRepository: mockTeamBillingDataRepository, + billingRepository: mockBillingRepository, + }); + prismaMock.membership.count.mockResolvedValue(10); + vi.spyOn(teamBillingServiceNotOrg, "checkIfTeamPaymentRequired").mockResolvedValue({ + url: "http://checkout.url", + paymentId: "cs_789", + paymentRequired: false, + }); + shouldApplyMonthlyProration.mockResolvedValue(true); + + await teamBillingServiceNotOrg.updateQuantity(); + + expect(mockBillingProviderService.handleSubscriptionUpdate).not.toHaveBeenCalled(); + }); }); describe("checkIfTeamPaymentRequired", () => { @@ -213,8 +263,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_org_123", subscriptionItemId: "si_org_123", customerId: "cus_org_123", - planName: "ORGANIZATION" as const, - status: "ACTIVE" as const, + planName: Plan.ORGANIZATION, + status: SubscriptionStatus.ACTIVE, }; await teamBillingService.saveTeamBilling(mockBillingArgs); @@ -228,8 +278,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_detailed_789", subscriptionItemId: "si_detailed_789", customerId: "cus_detailed_789", - planName: "ENTERPRISE" as const, - status: "TRIALING" as const, + planName: Plan.ENTERPRISE, + status: SubscriptionStatus.TRIALING, }; await teamBillingService.saveTeamBilling(mockBillingArgs); @@ -240,8 +290,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_detailed_789", subscriptionItemId: "si_detailed_789", customerId: "cus_detailed_789", - planName: "ENTERPRISE", - status: "TRIALING", + planName: Plan.ENTERPRISE, + status: SubscriptionStatus.TRIALING, }) ); }); @@ -252,8 +302,8 @@ describe("TeamBillingService", () => { subscriptionId: "sub_error_999", subscriptionItemId: "si_error_999", customerId: "cus_error_999", - planName: "TEAM" as const, - status: "ACTIVE" as const, + planName: Plan.TEAM, + status: SubscriptionStatus.ACTIVE, }; const repositoryError = new Error("Database constraint violation"); diff --git a/packages/lib/tasker/Tasker.ts b/packages/lib/tasker/Tasker.ts index 1deb789b5a..b8cf6e082c 100644 --- a/packages/lib/tasker/Tasker.ts +++ b/packages/lib/tasker/Tasker.ts @@ -7,18 +7,27 @@ import { redactError } from "../redactError"; import type { ILogger } from "./types"; const isAsyncTaskerEnabled = - ENABLE_ASYNC_TASKER && process.env.TRIGGER_SECRET_KEY && process.env.TRIGGER_API_URL; + ENABLE_ASYNC_TASKER && + process.env.TRIGGER_SECRET_KEY && + process.env.TRIGGER_API_URL; export abstract class Tasker { protected readonly asyncTasker: T; protected readonly syncTasker: T; protected readonly logger: ILogger; - constructor(dependencies: { asyncTasker: T; syncTasker: T; logger: ILogger }) { + constructor(dependencies: { + asyncTasker: T; + syncTasker: T; + logger: ILogger; + }) { this.logger = dependencies.logger; if (!isAsyncTaskerEnabled) { - if (ENABLE_ASYNC_TASKER && (!process.env.TRIGGER_SECRET_KEY || !process.env.TRIGGER_API_URL)) { + if ( + ENABLE_ASYNC_TASKER && + (!process.env.TRIGGER_SECRET_KEY || !process.env.TRIGGER_API_URL) + ) { this.logger.info( "Missing env variables TRIGGER_SECRET_KEY or TRIGGER_API_URL, falling back to Sync tasker." ); @@ -32,14 +41,18 @@ export abstract class Tasker { }); } - this.asyncTasker = isAsyncTaskerEnabled ? dependencies.asyncTasker : dependencies.syncTasker; + this.asyncTasker = isAsyncTaskerEnabled + ? dependencies.asyncTasker + : dependencies.syncTasker; this.syncTasker = dependencies.syncTasker; } public async dispatch( taskName: K, ...args: T[K] extends (...args: any[]) => any ? Parameters : never - ): Promise any ? Awaited> : never> { + ): Promise< + T[K] extends (...args: any[]) => any ? Awaited> : never + > { this.logger.info(`Safely Dispatching task '${String(taskName)}'`, { args }); return this._safeDispatch(taskName, ...args); } @@ -47,10 +60,14 @@ export abstract class Tasker { private async _safeDispatch( taskName: K, ...args: T[K] extends (...args: any[]) => any ? Parameters : never - ): Promise any ? Awaited> : never> { + ): Promise< + T[K] extends (...args: any[]) => any ? Awaited> : never + > { try { this.logger.info( - `${isAsyncTaskerEnabled ? "AsyncTasker" : "SyncTasker"} '${String(taskName)}' dispatched.` + `${isAsyncTaskerEnabled ? "AsyncTasker" : "SyncTasker"} '${String( + taskName + )}' dispatched.` ); const method = this.asyncTasker[taskName] as (...args: any[]) => any; return await method.apply(this.asyncTasker, args); @@ -68,13 +85,20 @@ export abstract class Tasker { throw err; } - this.logger.warn(`Trying again with SyncTasker for '${String(taskName)}'.`); + this.logger.warn( + `Trying again with SyncTasker for '${String(taskName)}'.` + ); try { - const fallbackMethod = this.syncTasker[taskName] as (...args: any[]) => any; + const fallbackMethod = this.syncTasker[taskName] as ( + ...args: any[] + ) => any; return await fallbackMethod.apply(this.syncTasker, args); } catch (err) { - this.logger.error(`SyncTasker failed for '${String(taskName)}'.`, this.getErrorDetails(err)); + this.logger.error( + `SyncTasker failed for '${String(taskName)}'.`, + this.getErrorDetails(err) + ); throw err; } }