refactor: Move Users Admin TRPC router from features package to trpc layer (#25816)

* move users admin router to trpc package

* users admin router

* update import path

* fix
This commit is contained in:
Benny Joo authored and GitHub committed 2025-12-14 08:45:20 -03:00
1 parent 43b6c63294
commit a8f43da472
5 files changed
+47 -32

No files matched your search

@@ -1,4 +1,3 @@
// eslint-disable-next-line no-restricted-imports
import { noop } from "lodash";
import { Controller, useForm } from "react-hook-form";
@@ -13,9 +12,24 @@ import { Button } from "@calcom/ui/components/button";
import { Form, EmailField, Select, Label, TextField } from "@calcom/ui/components/form";
import { ImageUploader } from "@calcom/ui/components/image-uploader";
import type { UserAdminRouterOutputs } from "../server/trpc-router";
type User = UserAdminRouterOutputs["get"]["user"];
interface User {
id: number;
name: string | null;
email: string;
username: string | null;
bio: string | null;
timeZone: string;
weekStart: string;
theme: string | null;
defaultScheduleId: number | null;
locale: string;
timeFormat: number;
allowDynamicBooking: boolean;
identityProvider: string;
role: string;
avatarUrl: string | null;
createdDate?: string | Date;
}
type Option<T extends string | number = string> = {
value: T;
@@ -33,7 +47,15 @@ type OptionValues = {
type FormValues = Pick<
User,
"avatarUrl" | "name" | "username" | "email" | "bio" | "createdDate" | "theme" | "defaultScheduleId" | "allowDynamicBooking"
| "avatarUrl"
| "name"
| "username"
| "email"
| "bio"
| "createdDate"
| "theme"
| "defaultScheduleId"
| "allowDynamicBooking"
> &
OptionValues;
@@ -1,39 +1,32 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { z } from "zod";
import NoSSR from "@calcom/lib/components/NoSSR";
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import { getParserWithGeneric } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
import LicenseRequired from "../../common/components/LicenseRequired";
import { UserForm } from "../components/UserForm";
import { userBodySchema } from "../schemas/userBodySchema";
import type { UserAdminRouterOutputs } from "../server/trpc-router";
type User = UserAdminRouterOutputs["get"]["user"];
const userIdSchema = z.object({ id: z.coerce.number() });
const UsersEditPage = () => {
const params = useParamsWithFallback();
const input = userIdSchema.safeParse(params);
if (!input.success) return <div>Invalid input</div>;
const [data] = trpc.viewer.users.get.useSuspenseQuery({ userId: input.data.id });
const { user } = data;
return (
<LicenseRequired>
<NoSSR>
<UsersEditView user={user} />
</NoSSR>
</LicenseRequired>
);
};
interface User {
id: number;
name: string | null;
email: string;
username: string | null;
bio: string | null;
timeZone: string;
weekStart: string;
theme: string | null;
defaultScheduleId: number | null;
locale: string;
timeFormat: number;
allowDynamicBooking: boolean;
identityProvider: string;
role: string;
avatarUrl: string | null;
createdDate?: string | Date;
}
export const UsersEditView = ({ user }: { user: User }) => {
const pathname = usePathname();
@@ -1,149 +0,0 @@
import { z } from "zod";
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
import { RedirectType, CreationSource } from "@calcom/prisma/enums";
import { UserSchema } from "@calcom/prisma/zod/modelSchema/UserSchema";
import { authedAdminProcedure } from "@calcom/trpc/server/procedures/authedProcedure";
import { router } from "@calcom/trpc/server/trpc";
import { TRPCError } from "@trpc/server";
import type { inferRouterOutputs } from "@trpc/server";
export type UserAdminRouter = typeof userAdminRouter;
export type UserAdminRouterOutputs = inferRouterOutputs<UserAdminRouter>;
const userIdSchema = z.object({ userId: z.coerce.number() });
const userBodySchema = UserSchema.pick({
name: true,
email: true,
username: true,
bio: true,
timeZone: true,
weekStart: true,
theme: true,
defaultScheduleId: true,
locale: true,
timeFormat: true,
// brandColor: true,
// darkBrandColor: true,
allowDynamicBooking: true,
identityProvider: true,
role: true,
avatarUrl: true,
});
/** Reusable logic that checks for admin permissions and if the requested user exists */
//const authedAdminWithUserMiddleware = middleware();
const authedAdminProcedureWithRequestedUser = authedAdminProcedure.use(async ({ ctx, next, getRawInput }) => {
const { prisma } = ctx;
const parsed = userIdSchema.safeParse(await getRawInput());
if (!parsed.success) throw new TRPCError({ code: "BAD_REQUEST", message: "User id is required" });
const { userId: id } = parsed.data;
const user = await prisma.user.findUnique({ where: { id } });
if (!user) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
return next({
ctx: {
user: ctx.user,
requestedUser: user,
},
});
});
export const userAdminRouter = router({
get: authedAdminProcedureWithRequestedUser.input(userIdSchema).query(async ({ ctx }) => {
const { requestedUser } = ctx;
return { user: requestedUser };
}),
list: authedAdminProcedure.query(async ({ ctx }) => {
const { prisma } = ctx;
// TODO: Add search, pagination, etc.
const users = await prisma.user.findMany();
return users;
}),
add: authedAdminProcedure.input(userBodySchema).mutation(async ({ ctx, input }) => {
const { prisma } = ctx;
const user = await prisma.user.create({ data: { ...input, creationSource: CreationSource.WEBAPP } });
return { user, message: `User with id: ${user.id} added successfully` };
}),
update: authedAdminProcedureWithRequestedUser
.input(userBodySchema.partial())
.mutation(async ({ ctx, input }) => {
const { prisma, requestedUser } = ctx;
const user = await prisma.$transaction(async (tx) => {
const userInternal = await tx.user.update({ where: { id: requestedUser.id }, data: input });
// If the profile has been moved to an Org -> we can easily access the profile we need to update
if (requestedUser.movedToProfileId && input.username) {
const profile = await tx.profile.update({
where: {
id: requestedUser.movedToProfileId,
},
data: {
username: input.username,
},
});
// Update all of this users tempOrgRedirectUrls
if (requestedUser.username && profile.organizationId) {
const data = await prisma.team.findUnique({
where: {
id: profile.organizationId,
},
select: {
slug: true,
},
});
// We should never hit this
if (!data?.slug) {
throw new Error("Team has no attached slug.");
}
const orgUrlPrefix = getOrgFullOrigin(data.slug);
const toUrl = `${orgUrlPrefix}/${input.username}`;
await prisma.tempOrgRedirect.updateMany({
where: {
type: RedirectType.User,
from: requestedUser.username, // Old username
},
data: {
toUrl,
},
});
}
return userInternal;
}
/**
* TODO (Sean/Hariom): Change this to profile specific when we have a way for a user to have > 1 orgs
* If the user wasnt a CAL account before being moved to an org they dont have the movedToProfileId value
* So we update all of their profiles to this new username - this tx will rollback if there is a username
* conflict here somehow (Note for now users only have ONE profile.)
**/
if (input.username) {
await tx.profile.updateMany({
where: {
userId: requestedUser.id,
},
data: {
username: input.username,
},
});
}
return userInternal;
});
return { user, message: `User with id: ${user.id} updated successfully` };
}),
delete: authedAdminProcedureWithRequestedUser.input(userIdSchema).mutation(async ({ ctx }) => {
const { prisma, requestedUser } = ctx;
await prisma.user.delete({ where: { id: requestedUser.id } });
return { message: `User with id: ${requestedUser.id} deleted successfully` };
}),
});