chore: Remove pages/settings (#18064)
* Remove unused org mkigration pages and delete pages/settings * Remove more unused code causing ts errors * Remove SettingsLayout
This commit is contained in:
1 parent
15e93af2ac
commit
ae1b844bea
14 files changed
+2
-3545
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1,76 +0,0 @@
|
||||
import { getFormSchema } from "@pages/settings/admin/orgMigrations/moveTeamToOrg";
|
||||
import type { NextApiRequest, NextApiResponse } from "next/types";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { moveTeamToOrg } from "../../../lib/orgMigration";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["moveTeamToOrg"] });
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const rawBody = req.body;
|
||||
|
||||
log.debug(
|
||||
"Moving team to org:",
|
||||
safeStringify({
|
||||
body: rawBody,
|
||||
})
|
||||
);
|
||||
|
||||
const translate = await getTranslation("en", "common");
|
||||
const moveTeamToOrgSchema = getFormSchema(translate);
|
||||
|
||||
const parsedBody = moveTeamToOrgSchema.safeParse(rawBody);
|
||||
|
||||
const session = await getServerSession({ req, res });
|
||||
|
||||
if (!session) {
|
||||
return res.status(403).json({ message: "No session found" });
|
||||
}
|
||||
|
||||
const isAdmin = session.user.role === UserPermissionRole.ADMIN;
|
||||
|
||||
if (!parsedBody.success) {
|
||||
log.error("moveTeamToOrg failed:", safeStringify(parsedBody.error));
|
||||
return res.status(400).json({ message: JSON.stringify(parsedBody.error) });
|
||||
}
|
||||
|
||||
const { teamId, targetOrgId, moveMembers, teamSlugInOrganization } = parsedBody.data;
|
||||
const isAllowed = isAdmin;
|
||||
if (!isAllowed) {
|
||||
return res.status(403).json({ message: "Not Authorized" });
|
||||
}
|
||||
|
||||
try {
|
||||
await moveTeamToOrg({
|
||||
targetOrg: {
|
||||
id: targetOrgId,
|
||||
teamSlug: teamSlugInOrganization,
|
||||
},
|
||||
teamId,
|
||||
moveMembers,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
if (error.statusCode > 300) {
|
||||
log.error("moveTeamToOrg failed:", safeStringify(error.message));
|
||||
}
|
||||
return res.status(error.statusCode).json({ message: error.message });
|
||||
}
|
||||
log.error("moveTeamToOrg failed:", safeStringify(error));
|
||||
const errorMessage = error instanceof Error ? error.message : "Something went wrong";
|
||||
|
||||
return res.status(500).json({ message: errorMessage });
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
message: `Added team ${teamId} to Org: ${targetOrgId} ${
|
||||
moveMembers ? " along with the members" : " without the members"
|
||||
}`,
|
||||
});
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import { getFormSchema } from "@pages/settings/admin/orgMigrations/moveUserToOrg";
|
||||
import type { NextApiRequest, NextApiResponse } from "next/types";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { moveUserToOrg } from "../../../lib/orgMigration";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["moveUserToOrg"] });
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const rawBody = req.body;
|
||||
const translate = await getTranslation("en", "common");
|
||||
const migrateBodySchema = getFormSchema(translate);
|
||||
log.debug(
|
||||
"Starting migration:",
|
||||
safeStringify({
|
||||
body: rawBody,
|
||||
})
|
||||
);
|
||||
const parsedBody = migrateBodySchema.safeParse(rawBody);
|
||||
|
||||
const session = await getServerSession({ req });
|
||||
|
||||
if (!session) {
|
||||
res.status(403).json({ message: "No session found" });
|
||||
return;
|
||||
}
|
||||
|
||||
const isAdmin = session.user.role === UserPermissionRole.ADMIN;
|
||||
|
||||
if (parsedBody.success) {
|
||||
const { userId, userName, shouldMoveTeams, targetOrgId, targetOrgUsername, targetOrgRole } =
|
||||
parsedBody.data;
|
||||
const isAllowed = isAdmin;
|
||||
if (isAllowed) {
|
||||
try {
|
||||
await moveUserToOrg({
|
||||
targetOrg: {
|
||||
id: targetOrgId,
|
||||
username: targetOrgUsername,
|
||||
membership: {
|
||||
role: targetOrgRole,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
id: userId,
|
||||
userName,
|
||||
},
|
||||
shouldMoveTeams,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
if (error.statusCode > 300) {
|
||||
log.error("Migration failed:", safeStringify(error));
|
||||
}
|
||||
return res.status(error.statusCode).json({ message: error.message });
|
||||
}
|
||||
log.error("Migration failed:", safeStringify(error));
|
||||
const errorMessage = error instanceof Error ? error.message : "Something went wrong";
|
||||
|
||||
return res.status(400).json({ message: errorMessage });
|
||||
}
|
||||
} else {
|
||||
return res.status(403).json({ message: "Not Authorized" });
|
||||
}
|
||||
return res.status(200).json({ message: "Migrated" });
|
||||
}
|
||||
log.error("Migration failed:", safeStringify(parsedBody.error));
|
||||
return res.status(400).json({ message: JSON.stringify(parsedBody.error) });
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { getFormSchema } from "@pages/settings/admin/orgMigrations/removeTeamFromOrg";
|
||||
import type { NextApiRequest, NextApiResponse } from "next/types";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { removeTeamFromOrg } from "../../../lib/orgMigration";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["removeTeamFromOrg"] });
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const rawBody = req.body;
|
||||
const translate = await getTranslation("en", "common");
|
||||
const removeTeamFromOrgSchema = getFormSchema(translate);
|
||||
log.debug(
|
||||
"Removing team from org:",
|
||||
safeStringify({
|
||||
body: rawBody,
|
||||
})
|
||||
);
|
||||
const parsedBody = removeTeamFromOrgSchema.safeParse(rawBody);
|
||||
|
||||
const session = await getServerSession({ req });
|
||||
|
||||
if (!session) {
|
||||
return res.status(403).json({ message: "No session found" });
|
||||
}
|
||||
|
||||
const isAdmin = session.user.role === UserPermissionRole.ADMIN;
|
||||
|
||||
if (!parsedBody.success) {
|
||||
log.error("RemoveTeamFromOrg failed:", safeStringify(parsedBody.error));
|
||||
return res.status(400).json({ message: JSON.stringify(parsedBody.error) });
|
||||
}
|
||||
const { teamId, targetOrgId } = parsedBody.data;
|
||||
const isAllowed = isAdmin;
|
||||
if (!isAllowed) {
|
||||
return res.status(403).json({ message: "Not Authorized" });
|
||||
}
|
||||
|
||||
try {
|
||||
await removeTeamFromOrg({
|
||||
targetOrgId,
|
||||
teamId,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
if (error.statusCode > 300) {
|
||||
log.error("RemoveTeamFromOrg failed:", safeStringify(error));
|
||||
}
|
||||
return res.status(error.statusCode).json({ message: error.message });
|
||||
}
|
||||
log.error("RemoveTeamFromOrg failed:", safeStringify(error));
|
||||
const errorMessage = error instanceof Error ? error.message : "Something went wrong";
|
||||
return res.status(500).json({ message: errorMessage });
|
||||
}
|
||||
|
||||
return res.status(200).json({ message: `Removed team ${teamId} from ${targetOrgId}` });
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { getFormSchema } from "@pages/settings/admin/orgMigrations/removeUserFromOrg";
|
||||
import type { NextApiRequest, NextApiResponse } from "next/types";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { removeUserFromOrg } from "../../../lib/orgMigration";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["removeUserFromOrg"] });
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const body = req.body;
|
||||
|
||||
log.debug(
|
||||
"Starting reverse migration:",
|
||||
safeStringify({
|
||||
body,
|
||||
})
|
||||
);
|
||||
|
||||
const translate = await getTranslation("en", "common");
|
||||
const migrateRevertBodySchema = getFormSchema(translate);
|
||||
const parsedBody = migrateRevertBodySchema.safeParse(body);
|
||||
const session = await getServerSession({ req });
|
||||
|
||||
if (!session) {
|
||||
return res.status(403).json({ message: "No session found" });
|
||||
}
|
||||
|
||||
const isAdmin = session.user.role === UserPermissionRole.ADMIN;
|
||||
if (!isAdmin) {
|
||||
return res.status(403).json({ message: "Only admin can take this action" });
|
||||
}
|
||||
|
||||
if (parsedBody.success) {
|
||||
const { userId, targetOrgId } = parsedBody.data;
|
||||
try {
|
||||
await removeUserFromOrg({ targetOrgId, userId });
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
if (error.statusCode > 300) {
|
||||
log.error("Reverse migration failed:", safeStringify(error));
|
||||
}
|
||||
return res.status(error.statusCode).json({ message: error.message });
|
||||
}
|
||||
log.error("Reverse migration failed:", safeStringify(error));
|
||||
const errorMessage = error instanceof Error ? error.message : "Something went wrong";
|
||||
|
||||
return res.status(500).json({ message: errorMessage });
|
||||
}
|
||||
return res.status(200).json({ message: "Reverted" });
|
||||
}
|
||||
log.error("Reverse Migration failed:", safeStringify(parsedBody.error));
|
||||
return res.status(400).json({ message: JSON.stringify(parsedBody.error) });
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import { getLayout as getSettingsLayout } from "@calcom/features/settings/layouts/SettingsLayout";
|
||||
import { HorizontalTabs } from "@calcom/ui";
|
||||
|
||||
export default function OrgMigrationLayout({ children }: { children: React.ReactElement }) {
|
||||
return getSettingsLayout(
|
||||
<div>
|
||||
<HorizontalTabs
|
||||
tabs={[
|
||||
{
|
||||
name: "Move Team to Org",
|
||||
href: "/settings/admin/orgMigrations/moveTeamToOrg",
|
||||
},
|
||||
{
|
||||
name: "Move User to Org",
|
||||
href: "/settings/admin/orgMigrations/moveUserToOrg",
|
||||
},
|
||||
{
|
||||
name: "Revert: Move Team to Org",
|
||||
href: "/settings/admin/orgMigrations/removeTeamFromOrg",
|
||||
},
|
||||
{
|
||||
name: "Revert: Move User to Org",
|
||||
href: "/settings/admin/orgMigrations/removeUserFromOrg",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export const getLayout = (page: React.ReactElement) => {
|
||||
return <OrgMigrationLayout>{page}</OrgMigrationLayout>;
|
||||
};
|
||||
@@ -1,153 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { TFunction } from "next-i18next";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { getStringAsNumberRequiredSchema } from "@calcom/prisma/zod-utils";
|
||||
import { Button, Form, Meta, SelectField, TextField, showToast } from "@calcom/ui";
|
||||
|
||||
import { getServerSideProps } from "@lib/settings/admin/orgMigrations/moveTeamToOrg/getServerSideProps";
|
||||
|
||||
import PageWrapper from "@components/PageWrapper";
|
||||
|
||||
import { getLayout } from "./_OrgMigrationLayout";
|
||||
|
||||
export { getServerSideProps };
|
||||
|
||||
export const getFormSchema = (t: TFunction) => {
|
||||
return z.object({
|
||||
teamId: z.number().or(getStringAsNumberRequiredSchema(t)),
|
||||
targetOrgId: z.number().or(getStringAsNumberRequiredSchema(t)),
|
||||
moveMembers: z.boolean(),
|
||||
teamSlugInOrganization: z.string(),
|
||||
});
|
||||
};
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Meta title="Organization Migration: Move a team" description="Migrates a team to an organization" />
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const enum State {
|
||||
IDLE,
|
||||
LOADING,
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
}
|
||||
|
||||
export default function MoveTeamToOrg() {
|
||||
const [state, setState] = useState(State.IDLE);
|
||||
const moveUsersOptions = [
|
||||
{
|
||||
label: "No",
|
||||
value: "false",
|
||||
},
|
||||
{
|
||||
label: "Yes",
|
||||
value: "true",
|
||||
},
|
||||
];
|
||||
const { t } = useLocale();
|
||||
const formSchema = getFormSchema(t);
|
||||
const formMethods = useForm({
|
||||
mode: "onSubmit",
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
|
||||
const { register, watch } = formMethods;
|
||||
const moveMembers = watch("moveMembers");
|
||||
return (
|
||||
<Wrapper>
|
||||
<Form
|
||||
className="space-y-6"
|
||||
noValidate={true}
|
||||
form={formMethods}
|
||||
handleSubmit={async (values) => {
|
||||
setState(State.LOADING);
|
||||
const res = await fetch(`/api/orgMigration/moveTeamToOrg`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
let response = null;
|
||||
try {
|
||||
response = await res.json();
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
showToast(e.message, "error", 10000);
|
||||
} else {
|
||||
showToast(t("something_went_wrong"), "error", 10000);
|
||||
}
|
||||
setState(State.ERROR);
|
||||
return;
|
||||
}
|
||||
if (res.status === 200) {
|
||||
setState(State.SUCCESS);
|
||||
showToast(response.message, "success", 10000);
|
||||
} else {
|
||||
setState(State.ERROR);
|
||||
showToast(response.message, "error", 10000);
|
||||
}
|
||||
}}>
|
||||
<div className="space-y-6">
|
||||
<TextField
|
||||
{...register("teamId")}
|
||||
label="Team ID"
|
||||
required
|
||||
placeholder="Enter teamId to move to org"
|
||||
/>
|
||||
<TextField
|
||||
{...register("teamSlugInOrganization")}
|
||||
label="New Slug"
|
||||
required
|
||||
placeholder="Team slug in the Organization"
|
||||
/>
|
||||
<TextField
|
||||
{...register("targetOrgId")}
|
||||
label="Target Organization ID"
|
||||
required
|
||||
placeholder="Enter Target organization ID"
|
||||
/>
|
||||
<div>
|
||||
<Controller
|
||||
name="moveMembers"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<SelectField
|
||||
containerClassName="mb-0"
|
||||
label="Move users"
|
||||
onChange={(option) => {
|
||||
onChange(option?.value === "true");
|
||||
}}
|
||||
value={moveUsersOptions.find((opt) => opt.value === value)}
|
||||
options={moveUsersOptions}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{moveMembers === true ? (
|
||||
<div className="mt-2">Members of the team will also be moved to the organization</div>
|
||||
) : moveMembers === false ? (
|
||||
<div className="mt-2">Members of the team will not be moved to the organization</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" loading={state === State.LOADING}>
|
||||
Move Team to Org
|
||||
</Button>
|
||||
</Form>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
MoveTeamToOrg.PageWrapper = PageWrapper;
|
||||
MoveTeamToOrg.getLayout = getLayout;
|
||||
@@ -1,188 +0,0 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* It could be an admin feature to move a user to an organization but because it's a temporary thing before mono-user orgs are implemented, it's not right to spend time on it.
|
||||
* Plus, we need to do it only for cal.com and not provide as a feature to our self hosters.
|
||||
*/
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { TFunction } from "next-i18next";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import z from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/client";
|
||||
import { getStringAsNumberRequiredSchema } from "@calcom/prisma/zod-utils";
|
||||
import { Button, Form, Meta, SelectField, TextField, showToast } from "@calcom/ui";
|
||||
|
||||
import { getServerSideProps } from "@lib/settings/admin/orgMigrations/moveUserToOrg/getServerSideProps";
|
||||
|
||||
import PageWrapper from "@components/PageWrapper";
|
||||
|
||||
import { getLayout } from "./_OrgMigrationLayout";
|
||||
|
||||
export { getServerSideProps };
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Meta
|
||||
title="Organization Migration: Move a user"
|
||||
description="Migrates a user to an organization along with the user's teams. But the teams' users are not migrated"
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const getFormSchema = (t: TFunction) =>
|
||||
z.object({
|
||||
userId: z.union([z.string().pipe(z.coerce.number()), z.number()]).optional(),
|
||||
userName: z.string().optional(),
|
||||
targetOrgId: z.union([getStringAsNumberRequiredSchema(t), z.number()]),
|
||||
targetOrgUsername: z.string().min(1, t("error_required_field")),
|
||||
shouldMoveTeams: z.boolean(),
|
||||
targetOrgRole: z.union([
|
||||
z.literal(MembershipRole.ADMIN),
|
||||
z.literal(MembershipRole.MEMBER),
|
||||
z.literal(MembershipRole.OWNER),
|
||||
]),
|
||||
});
|
||||
|
||||
const enum State {
|
||||
IDLE,
|
||||
LOADING,
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
}
|
||||
export default function MoveUserToOrg() {
|
||||
const [state, setState] = useState(State.IDLE);
|
||||
|
||||
const roles = Object.values(MembershipRole).map((role) => ({
|
||||
label: role,
|
||||
value: role,
|
||||
}));
|
||||
|
||||
const moveTeamsOptions = [
|
||||
{
|
||||
label: "Yes",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "No",
|
||||
value: "false",
|
||||
},
|
||||
];
|
||||
const { t } = useLocale();
|
||||
const formSchema = getFormSchema(t);
|
||||
const form = useForm({
|
||||
mode: "onSubmit",
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
|
||||
const shouldMoveTeams = form.watch("shouldMoveTeams");
|
||||
const register = form.register;
|
||||
return (
|
||||
<Wrapper>
|
||||
{/* Due to some reason auth from website doesn't work if /api endpoint is used. Spent a lot of time and in the end went with submitting data to the same page, because you can't do POST request to a page in Next.js, doing a GET request */}
|
||||
<Form
|
||||
form={form}
|
||||
className="space-y-6"
|
||||
handleSubmit={async (values) => {
|
||||
setState(State.LOADING);
|
||||
const res = await fetch(`/api/orgMigration/moveUserToOrg`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
let response = null;
|
||||
try {
|
||||
response = await res.json();
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
showToast(e.message, "error", 10000);
|
||||
} else {
|
||||
showToast(t("something_went_wrong"), "error", 10000);
|
||||
}
|
||||
setState(State.ERROR);
|
||||
return;
|
||||
}
|
||||
if (res.status === 200) {
|
||||
setState(State.SUCCESS);
|
||||
showToast(response.message, "success", 10000);
|
||||
} else {
|
||||
setState(State.ERROR);
|
||||
showToast(response.message, "error", 10000);
|
||||
}
|
||||
}}>
|
||||
<div className="space-y-6">
|
||||
<TextField
|
||||
type="text"
|
||||
{...register("userName")}
|
||||
label="User Name"
|
||||
required
|
||||
defaultValue=""
|
||||
placeholder="Enter username to move to Org"
|
||||
/>
|
||||
<Controller
|
||||
name="targetOrgRole"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<SelectField
|
||||
label="Role"
|
||||
options={roles}
|
||||
onChange={(option) => {
|
||||
if (!option) return;
|
||||
onChange(option.value);
|
||||
}}
|
||||
value={roles.find((role) => role.value === value)}
|
||||
required
|
||||
placeholder="Enter userId"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<TextField
|
||||
label="Username in Target Org"
|
||||
type="text"
|
||||
required
|
||||
{...register("targetOrgUsername")}
|
||||
placeholder="Enter New username for the Org"
|
||||
/>
|
||||
<TextField
|
||||
label="Target Organization ID"
|
||||
type="number"
|
||||
required
|
||||
{...register("targetOrgId")}
|
||||
placeholder="Enter Target organization ID"
|
||||
/>
|
||||
<Controller
|
||||
name="shouldMoveTeams"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<SelectField
|
||||
label="Move Teams"
|
||||
className="mb-0"
|
||||
onChange={(option) => {
|
||||
if (!option) return;
|
||||
onChange(option.value === "true");
|
||||
}}
|
||||
value={moveTeamsOptions.find((opt) => opt.value === value)}
|
||||
required
|
||||
options={moveTeamsOptions}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" loading={state === State.LOADING}>
|
||||
{shouldMoveTeams
|
||||
? "Move User to Org along with its teams(except the teams' users)"
|
||||
: "Move User to Org"}
|
||||
</Button>
|
||||
</Form>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
MoveUserToOrg.PageWrapper = PageWrapper;
|
||||
MoveUserToOrg.getLayout = getLayout;
|
||||
@@ -1,117 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { TFunction } from "next-i18next";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import z from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { getStringAsNumberRequiredSchema } from "@calcom/prisma/zod-utils";
|
||||
import { Button, Form, Meta, TextField, showToast } from "@calcom/ui";
|
||||
|
||||
import { getServerSideProps } from "@lib/settings/admin/orgMigrations/removeTeamFromOrg/getServerSideProps";
|
||||
|
||||
import PageWrapper from "@components/PageWrapper";
|
||||
|
||||
import { getLayout } from "./_OrgMigrationLayout";
|
||||
|
||||
export { getServerSideProps };
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Meta
|
||||
title="Organization Migration: Revert a team"
|
||||
description="Reverts a migration of a team to an organization"
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const enum State {
|
||||
IDLE,
|
||||
LOADING,
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
}
|
||||
|
||||
export const getFormSchema = (t: TFunction) =>
|
||||
z.object({
|
||||
targetOrgId: z.union([getStringAsNumberRequiredSchema(t), z.number()]),
|
||||
teamId: z.union([getStringAsNumberRequiredSchema(t), z.number()]),
|
||||
});
|
||||
|
||||
export default function RemoveTeamFromOrg() {
|
||||
const [state, setState] = useState(State.IDLE);
|
||||
const { t } = useLocale();
|
||||
const formSchema = getFormSchema(t);
|
||||
const form = useForm({
|
||||
mode: "onSubmit",
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
|
||||
const register = form.register;
|
||||
|
||||
return (
|
||||
<Wrapper>
|
||||
{/* Due to some reason auth from website doesn't work if /api endpoint is used. Spent a lot of time and in the end went with submitting data to the same page, because you can't do POST request to a page in Next.js, doing a GET request */}
|
||||
<Form
|
||||
form={form}
|
||||
className="space-y-6"
|
||||
handleSubmit={async (values) => {
|
||||
setState(State.LOADING);
|
||||
const res = await fetch(`/api/orgMigration/removeTeamFromOrg`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
let response = null;
|
||||
try {
|
||||
response = await res.json();
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
showToast(e.message, "error", 10000);
|
||||
} else {
|
||||
showToast(t("something_went_wrong"), "error", 10000);
|
||||
}
|
||||
setState(State.ERROR);
|
||||
return;
|
||||
}
|
||||
if (res.status === 200) {
|
||||
setState(State.SUCCESS);
|
||||
showToast(response.message, "success", 10000);
|
||||
} else {
|
||||
setState(State.ERROR);
|
||||
showToast(response.message, "error", 10000);
|
||||
}
|
||||
}}>
|
||||
<div className="space-y-6">
|
||||
<TextField
|
||||
label="Team ID"
|
||||
{...register("teamId")}
|
||||
required
|
||||
placeholder="Enter teamId to remove from org"
|
||||
/>
|
||||
<TextField
|
||||
className="mb-0"
|
||||
{...register("targetOrgId")}
|
||||
label="Target Organization ID"
|
||||
type="number"
|
||||
required
|
||||
placeholder="Enter Target organization ID"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" loading={state === State.LOADING}>
|
||||
Remove Team from Org
|
||||
</Button>
|
||||
</Form>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
RemoveTeamFromOrg.PageWrapper = PageWrapper;
|
||||
RemoveTeamFromOrg.getLayout = getLayout;
|
||||
@@ -1,115 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { TFunction } from "next-i18next";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import z from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { getStringAsNumberRequiredSchema } from "@calcom/prisma/zod-utils";
|
||||
import { Button, TextField, Meta, showToast, Form } from "@calcom/ui";
|
||||
|
||||
import { getServerSideProps } from "@lib/settings/admin/orgMigrations/removeUserFromOrg/getServerSideProps";
|
||||
|
||||
import PageWrapper from "@components/PageWrapper";
|
||||
|
||||
import { getLayout } from "./_OrgMigrationLayout";
|
||||
|
||||
export { getServerSideProps };
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Meta
|
||||
title="Organization Migration: Revert a user"
|
||||
description="Reverts a migration of a user to an organization"
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const enum State {
|
||||
IDLE,
|
||||
LOADING,
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
}
|
||||
|
||||
export const getFormSchema = (t: TFunction) =>
|
||||
z.object({
|
||||
userId: z.union([getStringAsNumberRequiredSchema(t), z.number()]),
|
||||
targetOrgId: z.union([getStringAsNumberRequiredSchema(t), z.number()]),
|
||||
});
|
||||
|
||||
export default function RemoveUserFromOrg() {
|
||||
const [state, setState] = useState(State.IDLE);
|
||||
const { t } = useLocale();
|
||||
const formSchema = getFormSchema(t);
|
||||
const form = useForm({
|
||||
mode: "onSubmit",
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
const register = form.register;
|
||||
return (
|
||||
<Wrapper>
|
||||
{/* Due to some reason auth from website doesn't work if /api endpoint is used. Spent a lot of time and in the end went with submitting data to the same page, because you can't do POST request to a page in Next.js, doing a GET request */}
|
||||
<Form
|
||||
form={form}
|
||||
className="space-y-6"
|
||||
handleSubmit={async (values) => {
|
||||
setState(State.LOADING);
|
||||
const res = await fetch(`/api/orgMigration/removeUserFromOrg`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
let response = null;
|
||||
try {
|
||||
response = await res.json();
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
showToast(e.message, "error", 10000);
|
||||
} else {
|
||||
showToast(t("something_went_wrong"), "error", 10000);
|
||||
}
|
||||
setState(State.ERROR);
|
||||
return;
|
||||
}
|
||||
if (res.status === 200) {
|
||||
setState(State.SUCCESS);
|
||||
showToast(response.message, "success", 10000);
|
||||
} else {
|
||||
setState(State.ERROR);
|
||||
showToast(response.message, "error", 10000);
|
||||
}
|
||||
}}>
|
||||
<div className="space-y-6">
|
||||
<TextField
|
||||
label="User ID"
|
||||
{...register("userId")}
|
||||
required
|
||||
placeholder="Enter userId to remove from org"
|
||||
/>
|
||||
<TextField
|
||||
className="mb-0"
|
||||
label="Target Organization ID"
|
||||
type="number"
|
||||
required
|
||||
{...register("targetOrgId")}
|
||||
placeholder="Enter Target organization ID"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" loading={state === State.LOADING}>
|
||||
Remove User from Org along with its teams
|
||||
</Button>
|
||||
</Form>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
RemoveUserFromOrg.PageWrapper = PageWrapper;
|
||||
RemoveUserFromOrg.getLayout = getLayout;
|
||||
@@ -4,9 +4,8 @@ import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { moveUserToOrg } from "@lib/orgMigration";
|
||||
|
||||
import { test } from "./lib/fixtures";
|
||||
import { moveUserToOrg } from "./lib/orgMigration";
|
||||
import { IS_STRIPE_ENABLED, submitAndWaitForResponse } from "./lib/testUtils";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
@@ -179,122 +179,6 @@ export async function removeUserFromOrg({ targetOrgId, userId }: { targetOrgId:
|
||||
log.debug(`orgId:${targetOrgId} attached to userId:${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure that the migration is idempotent
|
||||
*/
|
||||
export async function moveTeamToOrg({
|
||||
targetOrg,
|
||||
teamId,
|
||||
moveMembers,
|
||||
}: {
|
||||
targetOrg: { id: number; teamSlug: string };
|
||||
teamId: number;
|
||||
moveMembers?: boolean;
|
||||
}) {
|
||||
const possibleOrg = await getTeamOrThrowError(targetOrg.id);
|
||||
const { oldTeamSlug, updatedTeam } = await dbMoveTeamToOrg({ teamId, targetOrg });
|
||||
|
||||
const teamMetadata = teamMetadataSchema.parse(possibleOrg?.metadata);
|
||||
|
||||
if (!possibleOrg.isOrganization) {
|
||||
throw new Error(`${targetOrg.id} is not an Org`);
|
||||
}
|
||||
|
||||
const targetOrganization = possibleOrg;
|
||||
const orgMetadata = teamMetadata;
|
||||
await addTeamRedirect({
|
||||
oldTeamSlug,
|
||||
teamSlug: updatedTeam.slug,
|
||||
orgSlug: targetOrganization.slug || orgMetadata?.requestedSlug || null,
|
||||
});
|
||||
await setOrgSlugIfNotSet({ slug: targetOrganization.slug }, orgMetadata, targetOrg.id);
|
||||
if (moveMembers) {
|
||||
for (const membership of updatedTeam.members) {
|
||||
await moveUserToOrg({
|
||||
user: {
|
||||
id: membership.userId,
|
||||
},
|
||||
targetOrg: {
|
||||
id: targetOrg.id,
|
||||
membership: {
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
},
|
||||
},
|
||||
shouldMoveTeams: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
log.debug(`Successfully moved team ${teamId} to org ${targetOrg.id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure that the migration is idempotent
|
||||
*/
|
||||
export async function removeTeamFromOrg({ targetOrgId, teamId }: { targetOrgId: number; teamId: number }) {
|
||||
const removedTeam = await dbRemoveTeamFromOrg({ teamId });
|
||||
await removeTeamRedirect(removedTeam.slug);
|
||||
for (const membership of removedTeam.members) {
|
||||
await removeUserFromOrg({
|
||||
userId: membership.userId,
|
||||
targetOrgId,
|
||||
});
|
||||
}
|
||||
log.debug(`Successfully removed team ${teamId} from org ${targetOrgId}`);
|
||||
}
|
||||
|
||||
async function dbMoveTeamToOrg({
|
||||
teamId,
|
||||
targetOrg,
|
||||
}: {
|
||||
teamId: number;
|
||||
targetOrg: {
|
||||
id: number;
|
||||
teamSlug: string;
|
||||
};
|
||||
}) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!team) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: `Team with id: ${teamId} not found`,
|
||||
});
|
||||
}
|
||||
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
const oldTeamSlug = teamMetadata?.migratedToOrgFrom?.teamSlug || team.slug;
|
||||
|
||||
const updatedTeam = await prisma.team.update({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
data: {
|
||||
slug: targetOrg.teamSlug,
|
||||
parentId: targetOrg.id,
|
||||
metadata: {
|
||||
...teamMetadata,
|
||||
migratedToOrgFrom: {
|
||||
teamSlug: team.slug,
|
||||
lastMigrationTime: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { oldTeamSlug, updatedTeam };
|
||||
}
|
||||
|
||||
async function getUniqueUserThatDoesntBelongToOrg(
|
||||
userName: string | undefined,
|
||||
userId: number | undefined,
|
||||
@@ -491,53 +375,6 @@ async function addRedirect({
|
||||
}
|
||||
}
|
||||
|
||||
async function addTeamRedirect({
|
||||
oldTeamSlug,
|
||||
teamSlug,
|
||||
orgSlug,
|
||||
}: {
|
||||
oldTeamSlug: string | null;
|
||||
teamSlug: string | null;
|
||||
orgSlug: string | null;
|
||||
}) {
|
||||
if (!oldTeamSlug) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: "No oldSlug for team. Not adding the redirect",
|
||||
});
|
||||
}
|
||||
if (!teamSlug) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: "No slug for team. Not adding the redirect",
|
||||
});
|
||||
}
|
||||
if (!orgSlug) {
|
||||
log.warn(`No slug for org. Not adding the redirect`);
|
||||
return;
|
||||
}
|
||||
const orgUrlPrefix = getOrgFullOrigin(orgSlug);
|
||||
|
||||
await prisma.tempOrgRedirect.upsert({
|
||||
where: {
|
||||
from_type_fromOrgId: {
|
||||
type: RedirectType.Team,
|
||||
from: oldTeamSlug,
|
||||
fromOrgId: 0,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
type: RedirectType.Team,
|
||||
from: oldTeamSlug,
|
||||
fromOrgId: 0,
|
||||
toUrl: `${orgUrlPrefix}/${teamSlug}`,
|
||||
},
|
||||
update: {
|
||||
toUrl: `${orgUrlPrefix}/${teamSlug}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function updateMembership({
|
||||
targetOrgId,
|
||||
userToMoveToOrg,
|
||||
@@ -700,24 +537,6 @@ async function setOrgSlug({ targetOrgId, targetSlug }: { targetOrgId: number; ta
|
||||
});
|
||||
}
|
||||
|
||||
async function removeTeamRedirect(teamSlug: string | null) {
|
||||
if (!teamSlug) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: "No slug for team. Not removing the redirect",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.tempOrgRedirect.deleteMany({
|
||||
where: {
|
||||
type: RedirectType.Team,
|
||||
from: teamSlug,
|
||||
fromOrgId: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function removeUserAlongWithItsTeamsRedirects({
|
||||
nonOrgUserName,
|
||||
teamsToBeRemovedFromOrg,
|
||||
@@ -5,9 +5,8 @@ import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
import { moveUserToOrg } from "@lib/orgMigration";
|
||||
|
||||
import { test } from "../lib/fixtures";
|
||||
import { moveUserToOrg } from "../lib/orgMigration";
|
||||
import { bookTeamEvent, doOnOrgDomain, expectPageToBeNotFound, getInviteLink } from "../lib/testUtils";
|
||||
import { expectInvitationEmailToBeReceived } from "./expects";
|
||||
|
||||
|
||||
Reference in new issue
Block a user