Skip to content

Commit

Permalink
fix: cancel sub when movingTeamToOrg (calcom#15594)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
2 people authored and p6l-richard committed Jul 22, 2024
1 parent 356f5d8 commit c254d63
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -184,6 +185,7 @@ async function moveTeam({
},
select: {
slug: true,
metadata: true,
members: {
select: {
role: true,
Expand Down Expand Up @@ -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({
Expand Down

0 comments on commit c254d63

Please sign in to comment.