feat: add Move Team to Organization admin migration page (#25067)

* feat: restore moveTeamToOrg admin endpoint for organization migration

- Add moveTeamToOrg and removeTeamFromOrg functions to orgMigration.ts
- Restore API endpoint at /api/orgMigration/moveTeamToOrg
- Restore admin UI page at /settings/admin/orgMigrations/moveTeamToOrg
- Add helper functions for team redirect management
- Support moving team members along with the team

This endpoint allows admins to migrate teams to organizations after org creation,
which is needed as a temporary solution until proper org admin permissions are implemented.

Co-Authored-By: [email protected] <[email protected]>

* fix: move moveTeamToOrg to lib/orgMigration and fix redirect URL

- Move moveTeamToOrg and removeTeamFromOrg functions from playwright/lib to lib/orgMigration.ts
- Update API endpoint to import from lib/orgMigration instead of playwright/lib
- Fix redirect URL format: use / instead of /team/
- Fix import path: use ../playwright/lib/orgMigration instead of ./playwright/lib/orgMigration
- Rename unused _dbRemoveTeamFromOrg in playwright file to satisfy linter
- Remove duplicate functions from playwright/lib/orgMigration.ts

This fixes the Vercel deployment failure caused by importing from test-only directories
in production API routes, and corrects the redirect URL format to match the original implementation.

Co-Authored-By: [email protected] <[email protected]>

* refactor: reuse existing createTeamsHandler for moveTeamToOrg endpoint

- Remove custom orgMigration.ts implementation
- Update API endpoint to call existing createTeamsHandler with org owner impersonation
- Remove moveMembers option from UI (always moves members by design)
- Fix Vercel deployment by removing playwright import from production code
- Use OrganizationRepository.adminFindById to fetch org owner

Co-Authored-By: [email protected] <[email protected]>

* refactor: migrate moveTeamToOrg admin page and API to App Router

- Move admin page from pages/settings/admin/orgMigrations to app/(use-page-wrapper)/settings/(admin-layout)/admin/orgMigrations
- Convert API route from pages/api/orgMigration/moveTeamToOrg.ts to app/api/orgMigration/moveTeamToOrg/route.ts
- Create client view component in modules/settings/admin/org-migrations/
- Remove old pages directory files and getServerSideProps

Co-Authored-By: [email protected] <[email protected]>

* fix: correct import paths for App Router compatibility

- Fix @calcom/lib/server to @calcom/lib/server/i18n for getTranslation
- Fix @calcom/ui barrel import to specific component paths

Co-Authored-By: [email protected] <[email protected]>

* fix: use TFunction type for getFormSchema parameter

Co-Authored-By: [email protected] <[email protected]>

* fix: use buildLegacyRequest for App Router session compatibility

Co-Authored-By: [email protected] <[email protected]>

* Remove unused fn

* cleanup

* cleanup

* fix: ui

* fix: handle slug conflict error when moving team to organization

- Intercept Prisma P2002 unique constraint error when moving a team
- Convert to user-friendly CONFLICT error with clear message
- Add test case for slug conflict scenario

Co-Authored-By: [email protected] <[email protected]>

* fix: use isPending instead of isLoading for tRPC mutation

Co-Authored-By: [email protected] <[email protected]>

* fixes

* fix: remove PII (emails) from admin log statement

Co-Authored-By: [email protected] <[email protected]>

* refactor: use instanceof pattern for Prisma error detection

Co-Authored-By: [email protected] <[email protected]>

* fixes

* fix: use i18n key for slug conflict error message instead of hardcoded English string

Co-Authored-By: bot_apk <[email protected]>

* fix: narrow P2002 catch scope to only prisma.team.update call

Separates the try-catch for prisma.team.update (slug conflict) from
creditService.moveCreditsFromTeamToOrg to avoid misattributing credit
service P2002 errors as slug conflicts.

Co-Authored-By: bot_apk <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: bot_apk <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-03-19 09:55:02 +05:30
1 parent 4b247640a8
commit dc43eba23b
10 files changed
+450 -130

No files matched your search

@@ -7,6 +7,7 @@ import { ZCreateSelfHostedLicenseSchema } from "./createSelfHostedLicenseKey.sch
import { ZAdminGetTeamsForFeatureSchema } from "./getTeamsForFeature.schema";
import { ZListMembersSchema } from "./listPaginated.schema";
import { ZAdminLockUserAccountSchema } from "./lockUserAccount.schema";
import { ZMoveTeamToOrgSchema } from "./moveTeamToOrg.schema";
import { ZAdminRemoveTwoFactor } from "./removeTwoFactor.schema";
import { ZResendPurchaseCompleteEmailSchema } from "./resendPurchaseCompleteEmail.schema";
import { ZAdminPasswordResetSchema } from "./sendPasswordReset.schema";
@@ -14,14 +15,14 @@ import { ZSetSMSLockState } from "./setSMSLockState.schema";
import { toggleFeatureFlag } from "./toggleFeatureFlag.procedure";
import { ZAdminUnassignFeatureFromTeamSchema } from "./unassignFeatureFromTeam.schema";
import { ZAdminVerifyWorkflowsSchema } from "./verifyWorkflows.schema";
import { watchlistRouter } from "./watchlist/_router";
import { ZWhitelistUserWorkflows } from "./whitelistUserWorkflows.schema";
import {
workspacePlatformCreateSchema,
workspacePlatformToggleEnabledSchema,
workspacePlatformUpdateSchema,
workspacePlatformUpdateServiceAccountSchema,
workspacePlatformToggleEnabledSchema,
} from "./workspacePlatform/schema";
import { watchlistRouter } from "./watchlist/_router";
const NAMESPACE = "admin";
@@ -95,6 +96,10 @@ export const adminRouter = router({
const { default: handler } = await import("./unassignFeatureFromTeam.handler");
return handler(opts);
}),
moveTeamToOrg: authedAdminProcedure.input(ZMoveTeamToOrgSchema).mutation(async (opts) => {
const { default: handler } = await import("./moveTeamToOrg.handler");
return handler(opts);
}),
workspacePlatform: router({
list: authedAdminProcedure.query(async () => {
const { default: handler } = await import("./workspacePlatform/list.handler");
@@ -0,0 +1,113 @@
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import slugify from "@calcom/lib/slugify";
import { CreationSource } from "@calcom/prisma/enums";
import { createTeamsHandler } from "@calcom/trpc/server/routers/viewer/organizations/createTeams.handler";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TMoveTeamToOrg } from "./moveTeamToOrg.schema";
const log = logger.getSubLogger({ prefix: ["moveTeamToOrg"] });
type MoveTeamToOrgOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
prisma: typeof import("@calcom/prisma").prisma;
};
input: TMoveTeamToOrg;
};
export const moveTeamToOrgHandler = async ({ ctx, input }: MoveTeamToOrgOptions) => {
const { teamId, targetOrgId, teamSlugInOrganization } = input;
log.debug(
"Moving team to org:",
safeStringify({
teamId,
targetOrgId,
teamSlugInOrganization,
})
);
const organizationRepository = getOrganizationRepository();
let org;
try {
org = await organizationRepository.adminFindById({ id: targetOrgId });
} catch (error) {
throw new TRPCError({ code: "NOT_FOUND", message: "organization_not_found" });
}
if (!org.members || org.members.length === 0) {
throw new TRPCError({ code: "BAD_REQUEST", message: "organization_owner_not_found" });
}
const teamRepository = new TeamRepository(ctx.prisma);
const team = await teamRepository.findById({ id: teamId });
if (!team) {
throw new TRPCError({ code: "NOT_FOUND", message: "team_not_found" });
}
if (team.parentId) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "cannot_move_subteam_already_in_org",
});
}
if (team.isOrganization) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "cannot_move_organization_to_organization",
});
}
const orgOwner = org.members[0].user;
log.info(
"Admin moving team to organization",
safeStringify({
adminUserId: ctx.user.id,
orgOwnerId: orgOwner.id,
teamId,
targetOrgId,
})
);
const oldTeamSlug = team.slug;
const newTeamSlug = slugify(teamSlugInOrganization);
await createTeamsHandler({
ctx: {
user: {
id: orgOwner.id,
organizationId: targetOrgId,
},
},
input: {
teamNames: [],
orgId: targetOrgId,
moveTeams: [
{
id: teamId,
newSlug: newTeamSlug,
shouldMove: true,
},
],
creationSource: CreationSource.WEBAPP,
},
});
return {
message: "team_moved_to_org_success",
teamId,
oldTeamSlug,
newTeamSlug,
organizationId: targetOrgId,
organizationSlug: org.slug,
};
};
export default moveTeamToOrgHandler;
@@ -0,0 +1,9 @@
import { z } from "zod";
export const ZMoveTeamToOrgSchema = z.object({
teamId: z.number(),
targetOrgId: z.number(),
teamSlugInOrganization: z.string().min(1),
});
export type TMoveTeamToOrg = z.infer<typeof ZMoveTeamToOrgSchema>;
@@ -1,5 +1,6 @@
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import slugify from "@calcom/lib/slugify";
import { Prisma } from "@calcom/prisma/client";
import { CreationSource, MembershipRole, RedirectType, UserPermissionRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -1248,5 +1249,63 @@ describe("createTeams handler - Comprehensive Tests", () => {
]);
inviteSpy.mockRestore();
});
it("should throw CONFLICT error when moving team with slug that already exists in the organization", async () => {
const { owner, organization } = await createScenario();
const teamToMove = await createTestTeam({
name: "Team To Move",
slug: "original-slug",
parentId: null,
});
await createTestMembership({
userId: owner.id,
teamId: teamToMove.id,
role: MembershipRole.OWNER,
});
// Mock the Prisma update to throw a unique constraint error (P2002)
// This simulates what happens when the database rejects a duplicate slug
const originalUpdate = prismock.team.update;
prismock.team.update = vi.fn().mockRejectedValueOnce(
new Prisma.PrismaClientKnownRequestError(
"Unique constraint failed on the fields: (`slug`,`parentId`)",
{
code: "P2002",
clientVersion: "5.0.0",
}
)
);
await expect(
createTeamsHandler({
ctx: {
user: {
id: owner.id,
organizationId: organization.id,
},
},
input: {
teamNames: [],
orgId: organization.id,
moveTeams: [
{
id: teamToMove.id,
shouldMove: true,
newSlug: "conflicting-slug",
},
],
creationSource: CreationSource.WEBAPP,
},
})
).rejects.toMatchObject({
code: "CONFLICT",
message: "slug_already_in_use_in_org",
});
// Restore the original update function
prismock.team.update = originalUpdate;
});
});
});
@@ -7,13 +7,11 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import slugify from "@calcom/lib/slugify";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { Prisma } from "@calcom/prisma/client";
import type { CreationSource } from "@calcom/prisma/enums";
import { MembershipRole, RedirectType } from "@calcom/prisma/enums";
import { teamMetadataSchema, teamMetadataStrictSchema } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
import { inviteMembersWithNoInviterPermissionCheck } from "../teams/inviteMember/inviteMember.handler";
import type { TCreateTeamsSchema } from "./createTeams.schema";
@@ -231,10 +229,13 @@ async function moveTeam({
parentId: org.id,
},
});
const creditService = new CreditService();
await creditService.moveCreditsFromTeamToOrg({ teamId, orgId: org.id });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
throw new TRPCError({
code: "CONFLICT",
message: "slug_already_in_use_in_org",
});
}
log.error(
"Error while moving team to organization",
safeStringify(error),
@@ -247,6 +248,21 @@ async function moveTeam({
throw error;
}
try {
const creditService = new CreditService();
await creditService.moveCreditsFromTeamToOrg({ teamId, orgId: org.id });
} catch (error) {
log.error(
"Error while moving credits from team to organization",
safeStringify(error),
safeStringify({
teamId,
orgId: org.id,
})
);
throw error;
}
// Owner is already a member of the team. Inviting an existing member can throw error
const invitableMembers = team.members.filter(isMembershipNotWithOwner).map((membership) => ({
usernameOrEmail: membership.user.email,