fix: cancel sub when movingTeamToOrg (#15594)
* fix: cancel sub when movingTeamToOrg * Cleanup code a little * Update packages/trpc/server/routers/viewer/organizations/createTeams.handler.ts Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> * Update packages/trpc/server/routers/viewer/organizations/createTeams.handler.ts Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> --------- Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
This commit is contained in:
co-authored by
Hariom Balhara
parent
48842e72a6
commit
835443a0d1
@@ -1,6 +1,7 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
@@ -184,6 +185,7 @@ async function moveTeam({
|
||||
},
|
||||
select: {
|
||||
slug: true,
|
||||
metadata: true,
|
||||
members: {
|
||||
select: {
|
||||
role: true,
|
||||
@@ -238,6 +240,34 @@ async function moveTeam({
|
||||
teamSlug: newSlug,
|
||||
orgSlug: org.slug || (orgMetadata?.requestedSlug ?? null),
|
||||
});
|
||||
|
||||
// Cancel existing stripe subscriptions once the team is migrated
|
||||
const subscriptionId = getSubscriptionId(team.metadata);
|
||||
if (subscriptionId) {
|
||||
await tryToCancelSubscription(subscriptionId);
|
||||
}
|
||||
}
|
||||
|
||||
async function tryToCancelSubscription(subscriptionId: string) {
|
||||
try {
|
||||
log.debug("Canceling stripe subscription", safeStringify({ subscriptionId }));
|
||||
return await stripe.subscriptions.cancel(subscriptionId);
|
||||
} catch (error) {
|
||||
log.error("Error while cancelling stripe subscription", error);
|
||||
}
|
||||
}
|
||||
|
||||
function getSubscriptionId(metadata: Prisma.JsonValue) {
|
||||
const parsedMetadata = teamMetadataSchema.safeParse(metadata);
|
||||
if (parsedMetadata.success) {
|
||||
const subscriptionId = parsedMetadata.data?.subscriptionId;
|
||||
if (!subscriptionId) {
|
||||
log.warn("No subscriptionId found in team metadata", safeStringify({ metadata, parsedMetadata }));
|
||||
}
|
||||
return subscriptionId;
|
||||
} else {
|
||||
log.warn(`There has been an error`, parsedMetadata.error);
|
||||
}
|
||||
}
|
||||
|
||||
async function addTeamRedirect({
|
||||
|
||||
Reference in New Issue
Block a user