Files
calendar/packages/features/ee/billing/api/webhook/_customer.subscription.deleted.ts
T
d4bff9d6b1 feat: Cal.ai Self Serve #2 (#22995)
* feat: Cal.ai Self Serve #2

* chore: fix import and remove logs

* fix: update checkout session

* fix: type errors and test

* fix: imports

* fix: type err

* fix: type error

* fix: tests

* chore: save progress

* fix: workflow flow

* fix: workflow update bug

* tests: add unit tests for retell ai webhoo

* fix: status code

* fix: test and delete bug

* fix: add dynamic variables

* fix: type err

* chore: update unit test

* fix: type error

* chore: update default prompt

* fix: type errors

* fix: workflow permissions

* fix: workflow page

* fix: translations

* feat: add call duration

* chore: add booking uid

* fix: button positioning

* chore: update tests

* chore: improvements

* chore: some more improvements

* refactor: improvements

* refactor: code feedback

* refactor: improvements

* feat: enable credits for orgs (#23077)

* Show credits UI for orgs

* fix stripe callback url when buying credits

* give orgs 20% credits

* add test for calulating credits

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>

* fix: types

* fix: types

* chore: error

* fix: type error

* fix: type error

* chore: mock env

* feat: add idempotency key to prevent double charging

* chore: add userId and teamId

* fix: skip inbound calls

* chore: update tests

* feat: add feature flag for voice agent

* feat: finish test call and other improvements

* chore: add alert

* chore: update .env.example

* chore: improvements

* fix: update tests

* refactor: remove un necessary

* feat: add setup badge

* chore: improvements

* fix: use referene id

* chore: improvements

* fix: type error

* fix: type

* refactor: change pricing logic

* refactor: update tests

* fix: conflicts

* fix: billing link for orgs

* fix: types

* refactor: move feature flag up

* fix: alert and test call credit check

* fix: update unit tests

* fix: feedback

* refactor: improvements

* refactor: move handlers to separate files

* fix: types

* fix: missing import

* fix: type

* refactor: change general tools functions handling

* refactor: use repository

* refactor: improvements

* fix: types

* fix: type errorr

* fix: auth check

* feat: add creditFor

* fix: update defualt prompt

* fix: throw error on frontend

* fix: update unit tests

* fix: use deleteAllWorkflowReminders

* refactor: add connect phone number

* refactor: improvements

* chore: translation

* chore: update message

* chore: translation

* design improvements buy number dialog

* add translation for error message

* use translation key in error message

* refactor: improve connect phone number tab

* feat: support un saved workflow to tests

* chore: remove un used

* fix: remove un used

* fix: remove un used

* refactor: similify billing

---------

Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2025-08-29 05:04:05 +01:00

93 lines
3.2 KiB
TypeScript

import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import type { LazyModule, SWHMap } from "./__handler";
import { HttpCode } from "./__handler";
type Data = SWHMap["customer.subscription.deleted"]["data"];
type Handlers = Record<`prod_${string}`, () => LazyModule<Data>>;
const STRIPE_TEAM_PRODUCT_ID = process.env.STRIPE_TEAM_PRODUCT_ID || "";
const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) => {
const subscription = data.object;
const phoneNumber = await PrismaPhoneNumberRepository.findByStripeSubscriptionId({
stripeSubscriptionId: subscription.id,
});
if (phoneNumber) {
return await handleCalAIPhoneNumberSubscriptionDeleted(subscription, phoneNumber);
}
// Fall back to product-based handling for other subscriptions
let productId: string | null = null;
// @ts-expect-error - support legacy just in case.
if (subscription.plan) {
// @ts-expect-error - we know subscription.plan.product is defined when unsubscribing
productId = subscription.plan.product; // prod_xxxxx
} else {
const subscriptionItem = subscription.items?.data?.[0];
if (!subscriptionItem) {
throw new Error("Subscription item and plan missing");
}
const product = subscription.items.data[0]?.plan.product;
if (product) {
productId = typeof product === "string" ? product : product.id;
}
}
if (typeof productId !== "string") {
throw new Error(`Unable to determine Product ID from subscription: ${subscription.id}`);
}
const handlerGetter = handlers[productId as any];
if (!handlerGetter) {
console.log("No product handler found for product", productId);
return {
success: false,
message: `No product handler found for product: ${productId}`,
};
}
const handler = (await handlerGetter())?.default;
// auto catch unsupported Stripe products.
if (!handler) {
console.log("No product handler found for product", productId);
return {
success: false,
message: `No product handler found for product: ${productId}`,
};
}
return await handler(data);
};
async function handleCalAIPhoneNumberSubscriptionDeleted(
subscription: Data["object"],
phoneNumber: NonNullable<Awaited<ReturnType<typeof PrismaPhoneNumberRepository.findByStripeSubscriptionId>>>
) {
if (!subscription.id) {
throw new HttpCode(400, "Subscription ID not found");
}
if (!phoneNumber.userId) {
throw new HttpCode(400, "Phone number does not belong to a user");
}
try {
const aiService = createDefaultAIPhoneServiceProvider();
await aiService.cancelPhoneNumberSubscription({
phoneNumberId: phoneNumber.id,
userId: phoneNumber.userId,
teamId: phoneNumber.teamId ?? undefined,
});
return { success: true, subscriptionId: subscription.id };
} catch (error) {
console.error("Failed to update phone number subscription:", error);
throw new HttpCode(500, "Failed to update phone number subscription");
}
}
export default stripeWebhookProductHandler({
[STRIPE_TEAM_PRODUCT_ID]: () => import("./_customer.subscription.deleted.team-plan"),
});