feat: High Water Mark (HWM) billing for monthly subscriptions (#27559)

* wip

* fix: claue reveiew commentsd

* add seed test

* fix: seed test plus subscriptin undefined in webhook

* chore: udpate triggr

* Integration test + HWM seed script

* add feature flag for hmw

* Remove redudant docs

* feat: add hwm-seating feature flag for high water mark billing

- Add new hwm-seating feature flag to control HWM billing logic
- Update HighWaterMarkService to use hwm-seating flag
- Update SeatChangeTrackingService to use hwm-seating flag
- Update BillingPeriodService to use hwm-seating flag
- Add flag to migration SQL
- Enable flag in seed script and integration test

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix: add hwm-seating to useFlags and fix test mocks

- Add hwm-seating to useFlags.ts initial data
- Add shouldApplyHighWaterMark mock to TeamBillingService tests

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix test

* feat: move to invoice paid subscription

* fix: transactions for transiants updates + reusable util

* fix: address Cubic AI review feedback for HWM billing

- Fix dotenv import hoisting in seed-hwm-test.ts by using side-effect import
- Remove logging of sensitive information (password/emails) in seed script
- Fix incorrect newHighWaterMark return value when update is not performed

Co-Authored-By: unknown <>

* add additional unit tests

* improve DI

* fix migration + restore package.json trigger update

* feat:move to featurerepo+update tests

* fix mocks

* fix DI calls

* revert faeturerepo to featuresrepository

* fix: pass featureRepository to BillingPeriodService and HighWaterMarkService

- Fix TeamBillingService.ts: pass featureRepository to BillingPeriodService constructor
- Fix _invoice.upcoming.ts: pass featureRepository to HighWaterMarkService constructor
- Fix hwm-webhook-utils.ts: pass featureRepository to HighWaterMarkService constructor

These services require featureRepository for feature flag checks but production
call sites were missing this required dependency, causing runtime errors.

Addresses Cubic AI review feedback on PR #27559

Co-Authored-By: unknown <>

* fix import

* update feature repo usage to features

* remove test thats mocking the wrong stuff

* revert RegularBookingService changes

* remove hide branding

* remove change in redudant file

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-02-05 09:56:31 +00:00
1 parent 249065851b
commit 1ad4ad6e4e
28 files changed
+3641 -41

No files matched your search

@@ -1,11 +1,10 @@
import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing";
import { PrismaPhoneNumberRepository } from "@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository";
import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils";
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"] });
@@ -32,10 +31,7 @@ const handler = async (data: Data) => {
? await handleCalAIPhoneNumberSubscriptionUpdate(subscription, phoneNumber)
: null;
const teamBillingResult = await handleTeamBillingRenewal(
subscription,
previousAttributes
);
const teamBillingResult = await handleTeamBillingRenewal(subscription, previousAttributes);
return {
phoneNumber: phoneNumberResult,
@@ -61,8 +57,7 @@ async function handleCalAIPhoneNumberSubscriptionUpdate(
paused: PhoneNumberSubscriptionStatus.CANCELLED,
};
const subscriptionStatus =
statusMap[subscription.status] || PhoneNumberSubscriptionStatus.UNPAID;
const subscriptionStatus = statusMap[subscription.status] || PhoneNumberSubscriptionStatus.UNPAID;
await prisma.calAiPhoneNumber.update({
where: {
@@ -92,8 +87,7 @@ async function handleTeamBillingRenewal(
const { subscriptionStart, subscriptionEnd, subscriptionTrialEnd } =
billingProviderService.extractSubscriptionDates(subscription);
const { billingPeriod, pricePerSeat, paidSeats } =
extractBillingDataFromStripeSubscription(subscription);
const { billingPeriod, pricePerSeat, paidSeats } = extractBillingDataFromStripeSubscription(subscription);
const teamBillingRepo = new PrismaTeamBillingRepository(prisma);
const orgBillingRepo = new PrismaOrganizationBillingRepository(prisma);
@@ -107,12 +101,11 @@ async function handleTeamBillingRenewal(
pricePerSeat: pricePerSeat ?? null,
};
const teamBilling = await teamBillingRepo.findBySubscriptionId(
subscription.id
);
const teamBilling = await teamBillingRepo.findBySubscriptionId(subscription.id);
if (teamBilling) {
await teamBillingRepo.updateById(teamBilling.id, billingUpdateData);
// HWM reset is handled by invoice.paid webhook after payment completes
return { success: true, type: "team", teamId: teamBilling.teamId };
}
@@ -120,15 +113,13 @@ async function handleTeamBillingRenewal(
if (orgBilling) {
await orgBillingRepo.updateById(orgBilling.id, billingUpdateData);
// HWM reset is handled by invoice.paid webhook after payment completes
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,
customerId: typeof subscription.customer === "string" ? subscription.customer : subscription.customer?.id,
});
return { skipped: true, reason: "no billing record found" };
@@ -1,5 +1,3 @@
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";
@@ -10,18 +8,26 @@ import { UserRepository } from "@calcom/features/users/repositories/UserReposito
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { prisma } from "@calcom/prisma";
import { z } from "zod";
import { getTeamBillingServiceFactory } from "../../di/containers/Billing";
import type { SWHMap } from "./__handler";
import { handleHwmResetAfterRenewal, validateInvoiceLinesForHwm } from "./hwm-webhook-utils";
const invoicePaidSchema = z.object({
object: z.object({
customer: z.string(),
subscription: z.string(),
billing_reason: z.string().nullable(),
lines: z.object({
data: z.array(
z.object({
subscription_item: z.string(),
period: z
.object({
start: z.number(),
end: z.number(),
})
.optional(),
})
),
}),
@@ -57,9 +63,18 @@ const handler = async (data: SWHMap["invoice.paid"]["data"]) => {
if (!organizationOnboarding) {
// Invoice Paid is received for all organizations, even those that were created before Organization Onboarding was introduced.
logger.info(
`No onboarding record found for stripe customer id: ${invoice.customer}, Organization created before Organization Onboarding was introduced, so ignoring the webhook`
);
// For renewals, we still need to reset the HWM
if (invoice.billing_reason === "subscription_cycle") {
logger.info(`Processing renewal invoice for subscription ${subscriptionId}`);
const validation = validateInvoiceLinesForHwm(invoice.lines.data, subscriptionId, logger);
if (validation.isValid) {
await handleHwmResetAfterRenewal(subscriptionId, validation.periodStart, logger);
}
} else {
logger.info(
`No onboarding record found for stripe customer id: ${invoice.customer}, Organization created before Organization Onboarding was introduced, so ignoring the webhook`
);
}
return {
success: true,
@@ -87,11 +102,17 @@ const handler = async (data: SWHMap["invoice.paid"]["data"]) => {
);
if (organizationOnboarding.isComplete) {
// If the organization is already complete, there is nothing to do
// Repeat requests can come for recurring payments
// If the organization is already complete, handle renewal HWM reset
if (invoice.billing_reason === "subscription_cycle") {
logger.info(`Processing renewal invoice for completed org, subscription ${subscriptionId}`);
const validation = validateInvoiceLinesForHwm(invoice.lines.data, subscriptionId, logger);
if (validation.isValid) {
await handleHwmResetAfterRenewal(subscriptionId, validation.periodStart, logger);
}
}
return {
success: true,
message: "Onboarding already completed, skipping",
message: "Onboarding already completed",
};
}
@@ -0,0 +1,50 @@
import logger from "@calcom/lib/logger";
import { z } from "zod";
import type { SWHMap } from "./__handler";
import { handleHwmResetAfterRenewal, validateInvoiceLinesForHwm } from "./hwm-webhook-utils";
const log = logger.getSubLogger({ prefix: ["invoice-paid-team"] });
const invoicePaidSchema = z.object({
object: z.object({
customer: z.string(),
subscription: z.string(),
billing_reason: z.string().nullable(),
lines: z.object({
data: z.array(
z.object({
subscription_item: z.string(),
period: z
.object({
start: z.number(),
end: z.number(),
})
.optional(),
})
),
}),
}),
});
const handler = async (data: SWHMap["invoice.paid"]["data"]) => {
const { object: invoice } = invoicePaidSchema.parse(data);
const subscriptionId = invoice.subscription;
log.debug(`Processing invoice paid webhook for team subscription ${subscriptionId}`, {
billingReason: invoice.billing_reason,
customerId: invoice.customer,
});
// Only handle renewal invoices for HWM reset
if (invoice.billing_reason === "subscription_cycle") {
log.info(`Processing renewal invoice for team subscription ${subscriptionId}`);
const validation = validateInvoiceLinesForHwm(invoice.lines.data, subscriptionId, log);
if (validation.isValid) {
await handleHwmResetAfterRenewal(subscriptionId, validation.periodStart, log);
}
}
return { success: true };
};
export default handler;
@@ -1,13 +1,14 @@
import process from "node:process";
import logger from "@calcom/lib/logger";
import type { LazyModule, SWHMap } from "./__handler";
type Data = SWHMap["invoice.paid"]["data"];
type Handlers = Record<`prod_${string}`, () => LazyModule<Data>>;
// We can't crash here if STRIPE_ORG_PRODUCT_ID is not set, because not all self-hosters use Organizations and it might break the build on import of this module.
// We can't crash here if these are not set, because not all self-hosters use Organizations/Teams and it might break the build on import of this module.
const STRIPE_ORG_PRODUCT_ID = process.env.STRIPE_ORG_PRODUCT_ID || "";
const STRIPE_TEAM_PRODUCT_ID = process.env.STRIPE_TEAM_PRODUCT_ID || "";
const log = logger.getSubLogger({ prefix: ["stripe-webhook-invoice-paid"] });
@@ -48,4 +49,5 @@ const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) =
export default stripeWebhookProductHandler({
[STRIPE_ORG_PRODUCT_ID]: () => import("./_invoice.paid.org"),
[STRIPE_TEAM_PRODUCT_ID]: () => import("./_invoice.paid.team"),
});
@@ -0,0 +1,57 @@
import { getBillingProviderService } from "@calcom/features/ee/billing/di/containers/Billing";
import { HighWaterMarkService } from "@calcom/features/ee/billing/service/highWaterMark/HighWaterMarkService";
import logger from "@calcom/lib/logger";
import type { SWHMap } from "./__handler";
type Data = SWHMap["invoice.upcoming"]["data"];
const log = logger.getSubLogger({ prefix: ["stripe-webhook-invoice-upcoming"] });
const handler = async (data: Data) => {
const invoice = data.object;
// Only handle subscription invoices
if (!invoice.subscription) {
log.debug("Not a subscription invoice, skipping");
return { success: false, message: "Not a subscription invoice" };
}
const subscriptionId =
typeof invoice.subscription === "string" ? invoice.subscription : invoice.subscription.id;
log.info("Processing invoice.upcoming webhook", {
invoiceId: invoice.id,
subscriptionId,
customerId: typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id,
});
const billingService = getBillingProviderService();
const highWaterMarkService = new HighWaterMarkService({
logger: log,
billingService,
});
try {
const applied = await highWaterMarkService.applyHighWaterMarkToSubscription(subscriptionId);
if (applied) {
log.info("Successfully applied high water mark before renewal", {
subscriptionId,
});
return { success: true, highWaterMarkApplied: true };
}
log.debug("No high water mark update needed", { subscriptionId });
return { success: true, highWaterMarkApplied: false };
} catch (error) {
log.error("Failed to apply high water mark", {
subscriptionId,
error,
});
// Return success: false but don't throw - we don't want to fail the webhook
return { success: false, error: String(error) };
}
};
export default handler;
@@ -0,0 +1,204 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
extractPeriodStartFromInvoice,
validateInvoiceLinesForHwm,
handleHwmResetAfterRenewal,
} from "./hwm-webhook-utils";
// Mock dependencies
vi.mock("@calcom/ee/billing/di/containers/Billing", () => ({
getBillingProviderService: vi.fn(() => ({
handleSubscriptionUpdate: vi.fn(),
getSubscription: vi.fn(),
})),
}));
const mockResetSubscriptionAfterRenewal = vi.fn();
vi.mock("@calcom/features/ee/billing/service/highWaterMark/HighWaterMarkService", () => {
return {
HighWaterMarkService: class MockHighWaterMarkService {
resetSubscriptionAfterRenewal = mockResetSubscriptionAfterRenewal;
},
};
});
// Create a mock logger
const createMockLogger = () => ({
warn: vi.fn(),
info: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
});
describe("hwm-webhook-utils", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("extractPeriodStartFromInvoice", () => {
it("returns undefined for empty array", () => {
const result = extractPeriodStartFromInvoice([]);
expect(result).toBeUndefined();
});
it("returns undefined for null/undefined input", () => {
// @ts-expect-error - testing edge case
expect(extractPeriodStartFromInvoice(null)).toBeUndefined();
// @ts-expect-error - testing edge case
expect(extractPeriodStartFromInvoice(undefined)).toBeUndefined();
});
it("returns undefined when first item has no period", () => {
const result = extractPeriodStartFromInvoice([{}]);
expect(result).toBeUndefined();
});
it("returns undefined when period has no start", () => {
// @ts-expect-error - testing edge case
const result = extractPeriodStartFromInvoice([{ period: { end: 1234567890 } }]);
expect(result).toBeUndefined();
});
it("returns period start when valid", () => {
const timestamp = 1704067200; // 2024-01-01 00:00:00 UTC
const result = extractPeriodStartFromInvoice([
{ period: { start: timestamp, end: timestamp + 86400 } },
]);
expect(result).toBe(timestamp);
});
it("returns first item period start when multiple items exist", () => {
const firstTimestamp = 1704067200;
const secondTimestamp = 1704153600;
const result = extractPeriodStartFromInvoice([
{ period: { start: firstTimestamp, end: firstTimestamp + 86400 } },
{ period: { start: secondTimestamp, end: secondTimestamp + 86400 } },
]);
expect(result).toBe(firstTimestamp);
});
});
describe("validateInvoiceLinesForHwm", () => {
it("returns invalid for empty array and logs warning", () => {
const mockLog = createMockLogger();
// @ts-expect-error - mock logger
const result = validateInvoiceLinesForHwm([], "sub_123", mockLog);
expect(result.isValid).toBe(false);
expect(result.periodStart).toBeUndefined();
expect(mockLog.warn).toHaveBeenCalledWith(
"Invoice has no line items for subscription sub_123, cannot process HWM"
);
});
it("returns invalid for null input and logs warning", () => {
const mockLog = createMockLogger();
// @ts-expect-error - testing edge case
const result = validateInvoiceLinesForHwm(null, "sub_456", mockLog);
expect(result.isValid).toBe(false);
expect(mockLog.warn).toHaveBeenCalled();
});
it("returns invalid when period.start is missing and logs warning", () => {
const mockLog = createMockLogger();
// @ts-expect-error - mock logger
const result = validateInvoiceLinesForHwm([{ period: undefined }], "sub_789", mockLog);
expect(result.isValid).toBe(false);
expect(result.periodStart).toBeUndefined();
expect(mockLog.warn).toHaveBeenCalledWith(
"Invoice line item missing period.start for subscription sub_789, cannot process HWM"
);
});
it("returns valid with periodStart when data is correct", () => {
const mockLog = createMockLogger();
const timestamp = 1704067200;
const result = validateInvoiceLinesForHwm(
[{ period: { start: timestamp, end: timestamp + 86400 } }],
"sub_valid",
// @ts-expect-error - mock logger
mockLog
);
expect(result.isValid).toBe(true);
expect(result.periodStart).toBe(timestamp);
expect(mockLog.warn).not.toHaveBeenCalled();
});
});
describe("handleHwmResetAfterRenewal", () => {
it("returns failure when periodStartTimestamp is undefined", async () => {
const mockLog = createMockLogger();
// @ts-expect-error - mock logger
const result = await handleHwmResetAfterRenewal("sub_123", undefined, mockLog);
expect(result.success).toBe(false);
expect(result.error).toBe("No period start timestamp");
expect(mockLog.warn).toHaveBeenCalledWith(
"No period start timestamp for subscription sub_123, skipping HWM reset"
);
expect(mockResetSubscriptionAfterRenewal).not.toHaveBeenCalled();
});
it("returns success when reset succeeds", async () => {
const mockLog = createMockLogger();
mockResetSubscriptionAfterRenewal.mockResolvedValue(true);
const timestamp = 1704067200;
// @ts-expect-error - mock logger
const result = await handleHwmResetAfterRenewal("sub_456", timestamp, mockLog);
expect(result.success).toBe(true);
expect(result.updated).toBe(true);
expect(mockResetSubscriptionAfterRenewal).toHaveBeenCalledWith({
subscriptionId: "sub_456",
newPeriodStart: new Date(timestamp * 1000),
});
expect(mockLog.info).toHaveBeenCalled();
});
it("returns success with updated=false when no update needed", async () => {
const mockLog = createMockLogger();
mockResetSubscriptionAfterRenewal.mockResolvedValue(false);
const timestamp = 1704067200;
// @ts-expect-error - mock logger
const result = await handleHwmResetAfterRenewal("sub_789", timestamp, mockLog);
expect(result.success).toBe(true);
expect(result.updated).toBe(false);
});
it("returns failure when reset throws an error", async () => {
const mockLog = createMockLogger();
mockResetSubscriptionAfterRenewal.mockRejectedValue(new Error("Stripe API error"));
const timestamp = 1704067200;
// @ts-expect-error - mock logger
const result = await handleHwmResetAfterRenewal("sub_error", timestamp, mockLog);
expect(result.success).toBe(false);
expect(result.error).toBe("Stripe API error");
expect(mockLog.error).toHaveBeenCalledWith("Failed to reset HWM after invoice paid", {
subscriptionId: "sub_error",
error: "Stripe API error",
});
});
it("handles non-Error thrown values", async () => {
const mockLog = createMockLogger();
mockResetSubscriptionAfterRenewal.mockRejectedValue("string error");
const timestamp = 1704067200;
// @ts-expect-error - mock logger
const result = await handleHwmResetAfterRenewal("sub_string", timestamp, mockLog);
expect(result.success).toBe(false);
expect(result.error).toBe("string error");
});
});
});
@@ -0,0 +1,86 @@
import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing";
import { HighWaterMarkService } from "@calcom/features/ee/billing/service/highWaterMark/HighWaterMarkService";
import logger from "@calcom/lib/logger";
import type { Logger } from "tslog";
const defaultLogger = logger.getSubLogger({ prefix: ["hwm-webhook-utils"] });
export function extractPeriodStartFromInvoice(
linesData: Array<{ period?: { start: number; end: number } }>
): number | undefined {
if (!linesData || linesData.length === 0) {
return undefined;
}
return linesData[0]?.period?.start;
}
export function validateInvoiceLinesForHwm(
linesData: Array<{ period?: { start: number; end: number } }>,
subscriptionId: string,
log: Logger<unknown> = defaultLogger
): { isValid: boolean; periodStart?: number } {
if (!linesData || linesData.length === 0) {
log.warn(
`Invoice has no line items for subscription ${subscriptionId}, cannot process HWM`
);
return { isValid: false };
}
const periodStart = linesData[0]?.period?.start;
if (!periodStart) {
log.warn(
`Invoice line item missing period.start for subscription ${subscriptionId}, cannot process HWM`
);
return { isValid: false };
}
return { isValid: true, periodStart };
}
export interface HwmResetResult {
success: boolean;
updated?: boolean;
error?: string;
}
export async function handleHwmResetAfterRenewal(
subscriptionId: string,
periodStartTimestamp: number | undefined,
log: Logger<unknown> = defaultLogger
): Promise<HwmResetResult> {
if (!periodStartTimestamp) {
log.warn(
`No period start timestamp for subscription ${subscriptionId}, skipping HWM reset`
);
return { success: false, error: "No period start timestamp" };
}
const newPeriodStart = new Date(periodStartTimestamp * 1000);
const billingProviderService = getBillingProviderService();
const highWaterMarkService = new HighWaterMarkService({
logger: log,
billingService: billingProviderService,
});
try {
const updated = await highWaterMarkService.resetSubscriptionAfterRenewal({
subscriptionId,
newPeriodStart,
});
log.info("HWM reset after invoice paid", {
subscriptionId,
newPeriodStart,
updated,
});
return { success: true, updated };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log.error("Failed to reset HWM after invoice paid", {
subscriptionId,
error: errorMessage,
});
return { success: false, error: errorMessage };
}
}
@@ -11,6 +11,7 @@ const handlers = {
"invoice.paid": () => import("./_invoice.paid"),
"invoice.payment_failed": () => import("./_invoice.payment_failed"),
"invoice.payment_succeeded": () => import("./_invoice.payment_succeeded"),
"invoice.upcoming": () => import("./_invoice.upcoming"),
"checkout.session.completed": () => import("./_checkout.session.completed"),
};