feat: trpc v10 migration (#5332)
* migrate router * createTRPCReact * frontend 1 * random format change * frontend 2 * withQuery * form router * TS-ERROR: proxy on utils-client * inferance * ssg * reuse * trpc rc4 * Apply suggestions from code review * skip test * move skip one level up * whops * rc 6 with new setData func Co-authored-by: zomars <[email protected]>
This commit is contained in:
1 parent
6d67808627
commit
db7c3fb52f
157 files changed
+3062
-3144
No files matched your search
@@ -7,10 +7,10 @@
|
||||
"main": "index.ts",
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^4.3.9",
|
||||
"@trpc/client": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/next": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/react": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/server": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/client": "^10.0.0-rc.6",
|
||||
"@trpc/next": "^10.0.0-rc.6",
|
||||
"@trpc/react-query": "^10.0.0-rc.6",
|
||||
"@trpc/server": "^10.0.0-rc.6",
|
||||
"superjson": "1.9.1",
|
||||
"zod": "^3.19.1"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { trpc } from "../trpc";
|
||||
|
||||
export function useMeQuery() {
|
||||
const meQuery = trpc.useQuery(["viewer.me"], {
|
||||
const meQuery = trpc.viewer.me.useQuery(undefined, {
|
||||
retry(failureCount) {
|
||||
return failureCount > 3;
|
||||
},
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export * from "@trpc/react";
|
||||
export * from "@trpc/react-query";
|
||||
export * from "./trpc";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/react-query/shared";
|
||||
@@ -1 +1 @@
|
||||
export * from "@trpc/react/ssg";
|
||||
export * from "@trpc/react-query/ssg";
|
||||
@@ -1,36 +1,19 @@
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createReactQueryHooks } from "@trpc/react";
|
||||
import { createTRPCReact } from "@trpc/react-query";
|
||||
|
||||
// ℹ️ Type-only import:
|
||||
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export
|
||||
import type { inferProcedureInput, inferProcedureOutput } from "../server";
|
||||
import type { inferRouterInputs, inferRouterOutputs } from "../server";
|
||||
import type { AppRouter } from "../server/routers/_app";
|
||||
|
||||
/**
|
||||
* A set of strongly-typed React hooks from your `AppRouter` type signature with `createReactQueryHooks`.
|
||||
* @link https://trpc.io/docs/react#3-create-trpc-hooks
|
||||
* A set of strongly-typed React hooks from your `AppRouter` type signature with `createTRPCReact`.
|
||||
* @link https://trpc.io/docs/v10/react#2-create-trpc-hooks
|
||||
*/
|
||||
export const trpc = createReactQueryHooks<AppRouter>();
|
||||
|
||||
export const proxy = trpc.proxy;
|
||||
export const trpc = createTRPCReact<AppRouter>();
|
||||
|
||||
export const transformer = superjson;
|
||||
/**
|
||||
* This is a helper method to infer the output of a query resolver
|
||||
* @example type HelloOutput = inferQueryOutput<'hello'>
|
||||
*/
|
||||
export type inferQueryOutput<TRouteKey extends keyof AppRouter["_def"]["queries"]> = inferProcedureOutput<
|
||||
AppRouter["_def"]["queries"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferQueryInput<TRouteKey extends keyof AppRouter["_def"]["queries"]> = inferProcedureInput<
|
||||
AppRouter["_def"]["queries"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferMutationInput<TRouteKey extends keyof AppRouter["_def"]["mutations"]> = inferProcedureInput<
|
||||
AppRouter["_def"]["mutations"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferMutationOutput<TRouteKey extends keyof AppRouter["_def"]["mutations"]> =
|
||||
inferProcedureOutput<AppRouter["_def"]["mutations"][TRouteKey]>;
|
||||
export type RouterInputs = inferRouterInputs<AppRouter>;
|
||||
export type RouterOutputs = inferRouterOutputs<AppRouter>;
|
||||
@@ -1,38 +0,0 @@
|
||||
import { performance } from "@calcom/lib/server/perfObserver";
|
||||
|
||||
import * as trpc from "@trpc/server";
|
||||
|
||||
import { Context } from "./createContext";
|
||||
|
||||
/**
|
||||
* Helper function to create a router with context
|
||||
* @deprecated
|
||||
*/
|
||||
export function createRouter() {
|
||||
return trpc.router<Context>().middleware(async ({ path, type, next }) => {
|
||||
performance.mark("Start");
|
||||
const result = await next();
|
||||
performance.mark("End");
|
||||
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
export function createProtectedRouter() {
|
||||
return createRouter().middleware(({ ctx, next }) => {
|
||||
if (!ctx.user || !ctx.session) {
|
||||
throw new trpc.TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
...ctx,
|
||||
// infers that `user` and `session` are non-nullable to downstream procedures
|
||||
session: ctx.session,
|
||||
user: ctx.user,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
/**
|
||||
* This file contains the root router of your tRPC-backend
|
||||
*/
|
||||
import { createRouter } from "../createRouter";
|
||||
import { publicProcedure, t } from "../trpc";
|
||||
import { publicRouter } from "./public";
|
||||
import { router } from "../trpc";
|
||||
import { viewerRouter } from "./viewer";
|
||||
|
||||
/**
|
||||
@@ -11,22 +9,9 @@ import { viewerRouter } from "./viewer";
|
||||
* If you want to use SSG, you need export this
|
||||
* @link https://trpc.io/docs/ssg
|
||||
* @link https://trpc.io/docs/router
|
||||
* @deprecated
|
||||
*/
|
||||
export const legacyRouter = createRouter()
|
||||
/**
|
||||
* Optionally do custom error (type safe!) formatting
|
||||
* @link https://trpc.io/docs/error-formatting
|
||||
*/
|
||||
// .formatError(({ shape, error }) => { })
|
||||
.merge("viewer.", viewerRouter)
|
||||
.interop();
|
||||
|
||||
const v10Router = t.router({
|
||||
hello: publicProcedure.query(() => "hello"),
|
||||
public: publicRouter,
|
||||
export const appRouter = router({
|
||||
viewer: viewerRouter,
|
||||
});
|
||||
|
||||
export const appRouter = t.mergeRouters(legacyRouter, v10Router);
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
@@ -1,5 +0,0 @@
|
||||
import { t, publicProcedure } from "../trpc";
|
||||
|
||||
export const publicRouter = t.router({
|
||||
session: publicProcedure.query(({ ctx }) => ctx.session),
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,34 +3,34 @@ import { z } from "zod";
|
||||
|
||||
import { generateUniqueAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const apiKeysRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
OR: [
|
||||
{
|
||||
NOT: {
|
||||
appId: "zapier",
|
||||
},
|
||||
export const apiKeysRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
OR: [
|
||||
{
|
||||
NOT: {
|
||||
appId: "zapier",
|
||||
},
|
||||
{
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("findKeyOfType", {
|
||||
input: z.object({
|
||||
appId: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
},
|
||||
{
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
findKeyOfType: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
appId: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return await ctx.prisma.apiKey.findFirst({
|
||||
where: {
|
||||
AND: [
|
||||
@@ -43,16 +43,17 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional().nullable(),
|
||||
neverExpires: z.boolean().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional().nullable(),
|
||||
neverExpires: z.boolean().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [hashedApiKey, apiKey] = generateUniqueAPIKey();
|
||||
// Here we snap never expires before deleting it so it's not passed to prisma create call.
|
||||
const neverExpires = input.neverExpires;
|
||||
@@ -69,15 +70,16 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
});
|
||||
const prefixedApiKey = `${process.env.API_KEY_PREFIX ?? "cal_"}${apiKey}`;
|
||||
return prefixedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("edit", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
edit: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...data } = input;
|
||||
const {
|
||||
apiKeys: [updatedApiKey],
|
||||
@@ -104,14 +106,15 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
},
|
||||
});
|
||||
return updatedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
|
||||
const apiKeyToDelete = await ctx.prisma.apiKey.findFirst({
|
||||
@@ -145,5 +148,5 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -6,15 +6,17 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const authRouter = createProtectedRouter()
|
||||
.mutation("changePassword", {
|
||||
input: z.object({
|
||||
oldPassword: z.string(),
|
||||
newPassword: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
export const authRouter = router({
|
||||
changePassword: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
oldPassword: z.string(),
|
||||
newPassword: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { oldPassword, newPassword } = input;
|
||||
|
||||
const { user } = ctx;
|
||||
@@ -60,13 +62,14 @@ export const authRouter = createProtectedRouter()
|
||||
password: hashedPassword,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("verifyPassword", {
|
||||
input: z.object({
|
||||
passwordInput: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
verifyPassword: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
passwordInput: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
@@ -84,5 +87,5 @@ export const authRouter = createProtectedRouter()
|
||||
}
|
||||
|
||||
return;
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -9,284 +9,290 @@ import { Schedule } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const availabilityRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const { prisma, user } = ctx;
|
||||
export const availabilityRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
const { prisma, user } = ctx;
|
||||
|
||||
const schedules = await prisma.schedule.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
const schedules = await prisma.schedule.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
|
||||
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
|
||||
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
|
||||
|
||||
return {
|
||||
schedules: schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
isDefault: schedule.id === defaultScheduleId,
|
||||
})),
|
||||
};
|
||||
},
|
||||
})
|
||||
.query("schedule", {
|
||||
input: z.object({
|
||||
scheduleId: z.optional(z.number()),
|
||||
return {
|
||||
schedules: schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
isDefault: schedule.id === defaultScheduleId,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
user: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
username: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
eventTypeId: stringOrNumber.optional(),
|
||||
withSource: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.query(({ input }) => {
|
||||
return getUserAvailability(input);
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId || (await getDefaultScheduleId(user.id, prisma)),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
schedule: router({
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
scheduleId: z.optional(z.number()),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId || (await getDefaultScheduleId(user.id, prisma)),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = convertScheduleToAvailability(schedule);
|
||||
return {
|
||||
schedule,
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.query("user", {
|
||||
input: z.object({
|
||||
username: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
eventTypeId: stringOrNumber.optional(),
|
||||
withSource: z.boolean().optional(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
return getUserAvailability(input);
|
||||
},
|
||||
})
|
||||
.mutation("schedule.create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
copyScheduleId: z.number().optional(),
|
||||
schedule: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
)
|
||||
.optional(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const data: Prisma.ScheduleCreateInput = {
|
||||
name: input.name,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = convertScheduleToAvailability(schedule);
|
||||
return {
|
||||
schedule,
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
}),
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
copyScheduleId: z.number().optional(),
|
||||
schedule: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
)
|
||||
.optional(),
|
||||
eventTypeId: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
const data: Prisma.ScheduleCreateInput = {
|
||||
name: input.name,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
// If an eventTypeId is provided then connect the new schedule to that event type
|
||||
...(input.eventTypeId && { eventType: { connect: { id: input.eventTypeId } } }),
|
||||
};
|
||||
// If an eventTypeId is provided then connect the new schedule to that event type
|
||||
...(input.eventTypeId && { eventType: { connect: { id: input.eventTypeId } } }),
|
||||
};
|
||||
|
||||
const availability = getAvailabilityFromSchedule(input.schedule || DEFAULT_SCHEDULE);
|
||||
data.availability = {
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
const availability = getAvailabilityFromSchedule(input.schedule || DEFAULT_SCHEDULE);
|
||||
data.availability = {
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
const schedule = await prisma.schedule.create({
|
||||
data,
|
||||
});
|
||||
const hasDefaultScheduleId = await hasDefaultSchedule(user, prisma);
|
||||
if (!hasDefaultScheduleId) {
|
||||
await setupDefaultSchedule(user.id, schedule.id, prisma);
|
||||
}
|
||||
const schedule = await prisma.schedule.create({
|
||||
data,
|
||||
});
|
||||
const hasDefaultScheduleId = await hasDefaultSchedule(user, prisma);
|
||||
if (!hasDefaultScheduleId) {
|
||||
await setupDefaultSchedule(user.id, schedule.id, prisma);
|
||||
}
|
||||
|
||||
return { schedule };
|
||||
},
|
||||
})
|
||||
.mutation("schedule.delete", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
return { schedule };
|
||||
}),
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
scheduleId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
|
||||
const scheduleToDelete = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (scheduleToDelete?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (user.defaultScheduleId === input.scheduleId) {
|
||||
// set a new default or unset default if no other schedule
|
||||
const scheduleToSetAsDefault = await prisma.schedule.findFirst({
|
||||
const scheduleToDelete = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
NOT: {
|
||||
id: input.scheduleId,
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (scheduleToDelete?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (user.defaultScheduleId === input.scheduleId) {
|
||||
// set a new default or unset default if no other schedule
|
||||
const scheduleToSetAsDefault = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
NOT: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: scheduleToSetAsDefault?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.schedule.delete({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
});
|
||||
}),
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
scheduleId: z.number(),
|
||||
timeZone: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
schedule: z.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
|
||||
let updatedUser;
|
||||
if (input.isDefault) {
|
||||
const setupDefault = await setupDefaultSchedule(user.id, input.scheduleId, prisma);
|
||||
updatedUser = setupDefault;
|
||||
}
|
||||
|
||||
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
|
||||
// Bug: https://github.com/prisma/prisma/issues/7290
|
||||
const userSchedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (userSchedule?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (!userSchedule || userSchedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
|
||||
const schedule = await prisma.schedule.update({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
data: {
|
||||
timeZone: input.timeZone,
|
||||
name: input.name,
|
||||
availability: {
|
||||
deleteMany: {
|
||||
scheduleId: {
|
||||
equals: input.scheduleId,
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: scheduleToSetAsDefault?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.schedule.delete({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("schedule.update", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
timeZone: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
schedule: z.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
|
||||
let updatedUser;
|
||||
if (input.isDefault) {
|
||||
const setupDefault = await setupDefaultSchedule(user.id, input.scheduleId, prisma);
|
||||
updatedUser = setupDefault;
|
||||
}
|
||||
|
||||
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
|
||||
// Bug: https://github.com/prisma/prisma/issues/7290
|
||||
const userSchedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (userSchedule?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (!userSchedule || userSchedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
|
||||
const schedule = await prisma.schedule.update({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
data: {
|
||||
timeZone: input.timeZone,
|
||||
name: input.name,
|
||||
availability: {
|
||||
deleteMany: {
|
||||
scheduleId: {
|
||||
equals: input.scheduleId,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const userAvailability = convertScheduleToAvailability(schedule);
|
||||
const userAvailability = convertScheduleToAvailability(schedule);
|
||||
|
||||
return {
|
||||
schedule,
|
||||
availability: userAvailability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: updatedUser
|
||||
? updatedUser.defaultScheduleId === schedule.id
|
||||
: user.defaultScheduleId === schedule.id,
|
||||
prevDefaultId: user.defaultScheduleId,
|
||||
currentDefaultId: updatedUser ? updatedUser.defaultScheduleId : user.defaultScheduleId,
|
||||
};
|
||||
},
|
||||
});
|
||||
return {
|
||||
schedule,
|
||||
availability: userAvailability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: updatedUser
|
||||
? updatedUser.defaultScheduleId === schedule.id
|
||||
: user.defaultScheduleId === schedule.id,
|
||||
prevDefaultId: user.defaultScheduleId,
|
||||
currentDefaultId: updatedUser ? updatedUser.defaultScheduleId : user.defaultScheduleId,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
export const convertScheduleToAvailability = (
|
||||
schedule: Partial<ScheduleModel> & { availability: AvailabilityModel[] }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,18 +1,22 @@
|
||||
import { EventTypeCustomInput, MembershipRole, PeriodType, Prisma } from "@prisma/client";
|
||||
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
|
||||
// REVIEW: From lint error
|
||||
import _ from "lodash";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { DailyLocationType } from "@calcom/app-store/locations";
|
||||
import { stripeDataSchema } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { validateBookingLimitOrder } from "@calcom/lib";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { baseEventTypeSelect, baseUserSelect } from "@calcom/prisma";
|
||||
import { _DestinationCalendarModel, _EventTypeCustomInputModel, _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import { EventTypeMetaDataSchema, stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { createEventTypeInput } from "@calcom/prisma/zod/custom/eventtype";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { authedProcedure, router } from "../../trpc";
|
||||
import { viewerRouter } from "../viewer";
|
||||
|
||||
function isPeriodType(keyInput: string): keyInput is PeriodType {
|
||||
@@ -88,143 +92,318 @@ const EventTypeUpdateInput = _EventTypeModel
|
||||
})
|
||||
);
|
||||
|
||||
export const eventTypesRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
team: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
description: true,
|
||||
length: true,
|
||||
schedulingType: true,
|
||||
slug: true,
|
||||
hidden: true,
|
||||
metadata: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: createEventTypeInput,
|
||||
async resolve({ ctx, input }) {
|
||||
const { schedulingType, teamId, ...rest } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const data: Prisma.EventTypeCreateInput = {
|
||||
...rest,
|
||||
owner: teamId ? undefined : { connect: { id: userId } },
|
||||
users: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const appKeys = await getAppKeysFromSlug("daily-video");
|
||||
if (typeof appKeys.api_key === "string") {
|
||||
data.locations = [{ type: DailyLocationType }];
|
||||
}
|
||||
|
||||
if (teamId && schedulingType) {
|
||||
const hasMembership = await ctx.prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasMembership?.role || !["ADMIN", "OWNER"].includes(hasMembership.role)) {
|
||||
console.warn(`User ${userId} does not have permission to create this new event type`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
data.team = {
|
||||
connect: {
|
||||
id: teamId,
|
||||
},
|
||||
};
|
||||
data.schedulingType = schedulingType;
|
||||
}
|
||||
|
||||
try {
|
||||
const eventType = await ctx.prisma.eventType.create({ data });
|
||||
return { eventType };
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002" && Array.isArray(e.meta?.target) && e.meta?.target.includes("slug")) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "URL Slug already exists for given user." });
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
const eventOwnerProcedure = authedProcedure.use(async ({ ctx, rawInput, next }) => {
|
||||
// Prevent non-owners to update/delete a team event
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
const event = await ctx.prisma.eventType.findUnique({
|
||||
where: { id: (rawInput as Record<"id", number>)?.id },
|
||||
include: {
|
||||
users: true,
|
||||
team: {
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
const event = await ctx.prisma.eventType.findUnique({
|
||||
where: { id: (rawInput as Record<"id", number>)?.id },
|
||||
include: {
|
||||
users: true,
|
||||
team: {
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const isAuthorized = (function () {
|
||||
if (event.team) {
|
||||
return event.team.members
|
||||
.filter((member) => member.role === MembershipRole.OWNER || member.role === MembershipRole.ADMIN)
|
||||
.map((member) => member.userId)
|
||||
.includes(ctx.user.id);
|
||||
}
|
||||
return event.userId === ctx.user.id || event.users.find((user) => user.id === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAuthorized) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an access an event ${event.id} they do not own.`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
const inputUsers = (rawInput as any).users || [];
|
||||
|
||||
const isAllowed = (function () {
|
||||
if (event.team) {
|
||||
const allTeamMembers = event.team.members.map((member) => member.userId);
|
||||
return inputUsers.every((userId: string) => allTeamMembers.includes(Number.parseInt(userId)));
|
||||
}
|
||||
return inputUsers.every((userId: string) => Number.parseInt(userId) === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAllowed) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an create an event for users ${inputUsers.join(", ")}.`);
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
|
||||
export const eventTypesRouter = router({
|
||||
// REVIEW: What should we name this procedure?
|
||||
getByViewer: authedProcedure.query(async ({ ctx }) => {
|
||||
const { prisma } = ctx;
|
||||
const eventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
// Position is required by lodash to sort on it. Don't remove it, TS won't complain but it would silently break reordering
|
||||
position: true,
|
||||
hashedLink: true,
|
||||
destinationCalendar: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
// logo: true, // Skipping to avoid 4mb limit
|
||||
bio: true,
|
||||
hideBranding: true,
|
||||
},
|
||||
},
|
||||
metadata: true,
|
||||
users: {
|
||||
select: baseUserSelect,
|
||||
},
|
||||
...baseEventTypeSelect,
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
bufferTime: true,
|
||||
plan: true,
|
||||
teams: {
|
||||
where: {
|
||||
accepted: true,
|
||||
},
|
||||
select: {
|
||||
role: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
eventTypes: {
|
||||
select: eventTypeSelect,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
eventTypes: {
|
||||
where: {
|
||||
team: null,
|
||||
},
|
||||
select: eventTypeSelect,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
|
||||
const isAuthorized = (function () {
|
||||
if (event.team) {
|
||||
return event.team.members
|
||||
.filter((member) => member.role === MembershipRole.OWNER || member.role === MembershipRole.ADMIN)
|
||||
.map((member) => member.userId)
|
||||
.includes(ctx.user.id);
|
||||
const mapEventType = (eventType: typeof user.eventTypes[number]) => ({
|
||||
...eventType,
|
||||
// @FIXME: cc @hariombalhara This is failing with production data
|
||||
// metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
||||
});
|
||||
|
||||
const userEventTypes = user.eventTypes.map(mapEventType);
|
||||
// backwards compatibility, TMP:
|
||||
const typesRaw = (
|
||||
await prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
select: eventTypeSelect,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
})
|
||||
).map(mapEventType);
|
||||
|
||||
type EventTypeGroup = {
|
||||
teamId?: number | null;
|
||||
profile: {
|
||||
slug: typeof user["username"];
|
||||
name: typeof user["name"];
|
||||
};
|
||||
metadata: {
|
||||
membershipCount: number;
|
||||
readOnly: boolean;
|
||||
};
|
||||
eventTypes: typeof userEventTypes;
|
||||
};
|
||||
|
||||
let eventTypeGroups: EventTypeGroup[] = [];
|
||||
const eventTypesHashMap = userEventTypes.concat(typesRaw).reduce((hashMap, newItem) => {
|
||||
const oldItem = hashMap[newItem.id];
|
||||
hashMap[newItem.id] = { ...oldItem, ...newItem };
|
||||
return hashMap;
|
||||
}, {} as Record<number, EventTypeGroup["eventTypes"][number]>);
|
||||
const mergedEventTypes = Object.values(eventTypesHashMap).map((eventType) => eventType);
|
||||
eventTypeGroups.push({
|
||||
teamId: null,
|
||||
profile: {
|
||||
slug: user.username,
|
||||
name: user.name,
|
||||
},
|
||||
eventTypes: _.orderBy(mergedEventTypes, ["position", "id"], ["desc", "asc"]),
|
||||
metadata: {
|
||||
membershipCount: 1,
|
||||
readOnly: false,
|
||||
},
|
||||
});
|
||||
|
||||
eventTypeGroups = ([] as EventTypeGroup[]).concat(
|
||||
eventTypeGroups,
|
||||
user.teams.map((membership) => ({
|
||||
teamId: membership.team.id,
|
||||
profile: {
|
||||
name: membership.team.name,
|
||||
image: `${CAL_URL}/team/${membership.team.slug}/avatar.png`,
|
||||
slug: "team/" + membership.team.slug,
|
||||
},
|
||||
metadata: {
|
||||
membershipCount: membership.team.members.length,
|
||||
readOnly: membership.role === MembershipRole.MEMBER,
|
||||
},
|
||||
eventTypes: membership.team.eventTypes.map(mapEventType),
|
||||
}))
|
||||
);
|
||||
return {
|
||||
viewer: {
|
||||
plan: user.plan,
|
||||
},
|
||||
// don't display event teams without event types,
|
||||
eventTypeGroups: eventTypeGroups.filter((groupBy) => !!groupBy.eventTypes?.length),
|
||||
// so we can show a dropdown when the user has teams
|
||||
profiles: eventTypeGroups.map((group) => ({
|
||||
teamId: group.teamId,
|
||||
...group.profile,
|
||||
...group.metadata,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
team: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
description: true,
|
||||
length: true,
|
||||
schedulingType: true,
|
||||
slug: true,
|
||||
hidden: true,
|
||||
metadata: true,
|
||||
},
|
||||
});
|
||||
}),
|
||||
create: authedProcedure.input(createEventTypeInput).mutation(async ({ ctx, input }) => {
|
||||
const { schedulingType, teamId, ...rest } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const data: Prisma.EventTypeCreateInput = {
|
||||
...rest,
|
||||
owner: teamId ? undefined : { connect: { id: userId } },
|
||||
users: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const appKeys = await getAppKeysFromSlug("daily-video");
|
||||
if (typeof appKeys.api_key === "string") {
|
||||
data.locations = [{ type: DailyLocationType }];
|
||||
}
|
||||
|
||||
if (teamId && schedulingType) {
|
||||
const hasMembership = await ctx.prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasMembership?.role || !["ADMIN", "OWNER"].includes(hasMembership.role)) {
|
||||
console.warn(`User ${userId} does not have permission to create this new event type`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return event.userId === ctx.user.id || event.users.find((user) => user.id === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAuthorized) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an access an event ${event.id} they do not own.`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
data.team = {
|
||||
connect: {
|
||||
id: teamId,
|
||||
},
|
||||
};
|
||||
data.schedulingType = schedulingType;
|
||||
}
|
||||
|
||||
const inputUsers = (rawInput as any).users || [];
|
||||
|
||||
const isAllowed = (function () {
|
||||
if (event.team) {
|
||||
const allTeamMembers = event.team.members.map((member) => member.userId);
|
||||
return inputUsers.every((userId: string) => allTeamMembers.includes(Number.parseInt(userId)));
|
||||
try {
|
||||
const eventType = await ctx.prisma.eventType.create({ data });
|
||||
return { eventType };
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002" && Array.isArray(e.meta?.target) && e.meta?.target.includes("slug")) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "URL Slug already exists for given user." });
|
||||
}
|
||||
}
|
||||
return inputUsers.every((userId: string) => Number.parseInt(userId) === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAllowed) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an create an event for users ${inputUsers.join(", ")}.`);
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
throw e;
|
||||
}
|
||||
|
||||
return next();
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
}),
|
||||
get: eventOwnerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const user = await ctx.prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
@@ -252,152 +431,150 @@ export const eventTypesRouter = createProtectedRouter()
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: EventTypeUpdateInput.strict(),
|
||||
async resolve({ ctx, input }) {
|
||||
const {
|
||||
schedule,
|
||||
periodType,
|
||||
locations,
|
||||
bookingLimits,
|
||||
destinationCalendar,
|
||||
customInputs,
|
||||
recurringEvent,
|
||||
users,
|
||||
id,
|
||||
hashedLink,
|
||||
...rest
|
||||
} = input;
|
||||
const data: Prisma.EventTypeUpdateInput = {
|
||||
...rest,
|
||||
metadata: rest.metadata === null ? Prisma.DbNull : rest.metadata,
|
||||
}),
|
||||
update: eventOwnerProcedure.input(EventTypeUpdateInput.strict()).mutation(async ({ ctx, input }) => {
|
||||
const {
|
||||
schedule,
|
||||
periodType,
|
||||
locations,
|
||||
bookingLimits,
|
||||
destinationCalendar,
|
||||
customInputs,
|
||||
recurringEvent,
|
||||
users,
|
||||
id,
|
||||
hashedLink,
|
||||
...rest
|
||||
} = input;
|
||||
const data: Prisma.EventTypeUpdateInput = {
|
||||
...rest,
|
||||
metadata: rest.metadata === null ? Prisma.DbNull : rest.metadata,
|
||||
};
|
||||
data.locations = locations ?? undefined;
|
||||
if (periodType) {
|
||||
data.periodType = handlePeriodType(periodType);
|
||||
}
|
||||
|
||||
if (recurringEvent) {
|
||||
data.recurringEvent = {
|
||||
dstart: recurringEvent.dtstart as unknown as Prisma.InputJsonObject,
|
||||
interval: recurringEvent.interval,
|
||||
count: recurringEvent.count,
|
||||
freq: recurringEvent.freq,
|
||||
until: recurringEvent.until as unknown as Prisma.InputJsonObject,
|
||||
tzid: recurringEvent.tzid,
|
||||
};
|
||||
data.locations = locations ?? undefined;
|
||||
if (periodType) {
|
||||
data.periodType = handlePeriodType(periodType);
|
||||
}
|
||||
} else if (recurringEvent === null) {
|
||||
data.recurringEvent = Prisma.DbNull;
|
||||
}
|
||||
|
||||
if (recurringEvent) {
|
||||
data.recurringEvent = {
|
||||
dstart: recurringEvent.dtstart as unknown as Prisma.InputJsonObject,
|
||||
interval: recurringEvent.interval,
|
||||
count: recurringEvent.count,
|
||||
freq: recurringEvent.freq,
|
||||
until: recurringEvent.until as unknown as Prisma.InputJsonObject,
|
||||
tzid: recurringEvent.tzid,
|
||||
};
|
||||
} else if (recurringEvent === null) {
|
||||
data.recurringEvent = Prisma.DbNull;
|
||||
}
|
||||
if (destinationCalendar) {
|
||||
/** We connect or create a destination calendar to the event type instead of the user */
|
||||
await viewerRouter.createCaller(ctx).setDestinationCalendar({
|
||||
...destinationCalendar,
|
||||
eventTypeId: id,
|
||||
});
|
||||
}
|
||||
|
||||
if (destinationCalendar) {
|
||||
/** We connect or create a destination calendar to the event type instead of the user */
|
||||
await viewerRouter.createCaller(ctx).mutation("setDestinationCalendar", {
|
||||
...destinationCalendar,
|
||||
eventTypeId: id,
|
||||
});
|
||||
}
|
||||
if (customInputs) {
|
||||
data.customInputs = handleCustomInputs(customInputs, id);
|
||||
}
|
||||
|
||||
if (customInputs) {
|
||||
data.customInputs = handleCustomInputs(customInputs, id);
|
||||
}
|
||||
if (bookingLimits) {
|
||||
const isValid = validateBookingLimitOrder(bookingLimits);
|
||||
if (!isValid)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Booking limits must be in ascending order." });
|
||||
data.bookingLimits = bookingLimits;
|
||||
}
|
||||
|
||||
if (bookingLimits) {
|
||||
const isValid = validateBookingLimitOrder(bookingLimits);
|
||||
if (!isValid)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Booking limits must be in ascending order." });
|
||||
data.bookingLimits = bookingLimits;
|
||||
}
|
||||
if (schedule) {
|
||||
data.schedule = {
|
||||
connect: {
|
||||
id: schedule,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (schedule) {
|
||||
data.schedule = {
|
||||
connect: {
|
||||
id: schedule,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (users) {
|
||||
data.users = {
|
||||
set: [],
|
||||
connect: users.map((userId: number) => ({ id: userId })),
|
||||
};
|
||||
}
|
||||
|
||||
if (users) {
|
||||
data.users = {
|
||||
set: [],
|
||||
connect: users.map((userId: number) => ({ id: userId })),
|
||||
};
|
||||
}
|
||||
|
||||
if (input?.price) {
|
||||
const paymentCredential = await ctx.prisma.credential.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
type: {
|
||||
contains: "_payment",
|
||||
},
|
||||
},
|
||||
select: {
|
||||
type: true,
|
||||
key: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (paymentCredential?.type === "stripe_payment") {
|
||||
const { default_currency } = stripeDataSchema.parse(paymentCredential.key);
|
||||
data.currency = default_currency;
|
||||
}
|
||||
}
|
||||
|
||||
const connectedLink = await ctx.prisma.hashedLink.findFirst({
|
||||
if (input?.price) {
|
||||
const paymentCredential = await ctx.prisma.credential.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
userId: ctx.user.id,
|
||||
type: {
|
||||
contains: "_payment",
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (hashedLink) {
|
||||
// check if hashed connection existed. If it did, do nothing. If it didn't, add a new connection
|
||||
if (!connectedLink) {
|
||||
// create a hashed link
|
||||
await ctx.prisma.hashedLink.upsert({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
update: {
|
||||
link: hashedLink,
|
||||
},
|
||||
create: {
|
||||
link: hashedLink,
|
||||
eventType: {
|
||||
connect: { id: input.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// check if hashed connection exists. If it does, disconnect
|
||||
if (connectedLink) {
|
||||
await ctx.prisma.hashedLink.delete({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (paymentCredential?.type === "stripe_payment") {
|
||||
const { default_currency } = stripeDataSchema.parse(paymentCredential.key);
|
||||
data.currency = default_currency;
|
||||
}
|
||||
}
|
||||
|
||||
const eventType = await ctx.prisma.eventType.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
const connectedLink = await ctx.prisma.hashedLink.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { eventType };
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (hashedLink) {
|
||||
// check if hashed connection existed. If it did, do nothing. If it didn't, add a new connection
|
||||
if (!connectedLink) {
|
||||
// create a hashed link
|
||||
await ctx.prisma.hashedLink.upsert({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
update: {
|
||||
link: hashedLink,
|
||||
},
|
||||
create: {
|
||||
link: hashedLink,
|
||||
eventType: {
|
||||
connect: { id: input.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// check if hashed connection exists. If it does, disconnect
|
||||
if (connectedLink) {
|
||||
await ctx.prisma.hashedLink.delete({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const eventType = await ctx.prisma.eventType.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
|
||||
return { eventType };
|
||||
}),
|
||||
delete: eventOwnerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
|
||||
await ctx.prisma.eventTypeCustomInput.deleteMany({
|
||||
@@ -415,5 +592,5 @@ export const eventTypesRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -5,15 +5,17 @@ import { samlProductID, samlTenantID, tenantPrefix, canAccess } from "@calcom/fe
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const samlRouter = createProtectedRouter()
|
||||
export const samlRouter = router({
|
||||
// Retrieve SAML Connection
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { connectionController, samlSPConfig } = await jackson();
|
||||
|
||||
const { teamId } = input;
|
||||
@@ -51,16 +53,16 @@ export const samlRouter = createProtectedRouter()
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
})
|
||||
|
||||
// Update the SAML Connection
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
encodedRawMetadata: z.string(),
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Update the SAML Connection
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
encodedRawMetadata: z.string(),
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { connectionController } = await jackson();
|
||||
|
||||
const { encodedRawMetadata, teamId } = input;
|
||||
@@ -86,15 +88,15 @@ export const samlRouter = createProtectedRouter()
|
||||
console.error("Error updating SAML connection", err);
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Updating SAML Connection failed." });
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// Delete the SAML Connection
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Delete the SAML Connection
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { connectionController } = await jackson();
|
||||
|
||||
const { teamId } = input;
|
||||
@@ -117,5 +119,5 @@ export const samlRouter = createProtectedRouter()
|
||||
console.error("Error deleting SAML connection", err);
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Deleting SAML Connection failed." });
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -17,7 +17,7 @@ import { TimeRange } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createRouter } from "../../createRouter";
|
||||
import { router, publicProcedure } from "../../trpc";
|
||||
|
||||
const getScheduleSchema = z
|
||||
.object({
|
||||
@@ -97,11 +97,10 @@ const checkIfIsAvailable = ({
|
||||
};
|
||||
|
||||
/** This should be called getAvailableSlots */
|
||||
export const slotsRouter = createRouter().query("getSchedule", {
|
||||
input: getScheduleSchema,
|
||||
async resolve({ input, ctx }) {
|
||||
export const slotsRouter = router({
|
||||
getSchedule: publicProcedure.input(getScheduleSchema).query(async ({ input, ctx }) => {
|
||||
return await getSchedule(input, ctx);
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
async function getEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeof getScheduleSchema>) {
|
||||
|
||||
@@ -24,15 +24,17 @@ import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { authedProcedure, router } from "../../trpc";
|
||||
|
||||
export const viewerTeamsRouter = createProtectedRouter()
|
||||
export const viewerTeamsRouter = router({
|
||||
// Retrieves team by id
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const team = await getTeamWithMembers(input.teamId, undefined, ctx.user.id);
|
||||
if (!team) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found." });
|
||||
@@ -48,39 +50,38 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
},
|
||||
requiresUpgrade: HOSTED_CAL_FEATURES ? !!team.members.find((m) => m.plan !== UserPlan.PRO) : false,
|
||||
};
|
||||
},
|
||||
})
|
||||
// Returns teams I a member of
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
|
||||
return memberships.map(({ team, ...membership }) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...team,
|
||||
}));
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
slug: z.string().transform((val) => slugify(val.trim())),
|
||||
logo: z
|
||||
.string()
|
||||
.optional()
|
||||
.nullable()
|
||||
.transform((v) => v || null),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Returns teams I a member of
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
|
||||
return memberships.map(({ team, ...membership }) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...team,
|
||||
}));
|
||||
}),
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
slug: z.string().transform((val) => slugify(val.trim())),
|
||||
logo: z
|
||||
.string()
|
||||
.optional()
|
||||
.nullable()
|
||||
.transform((v) => v || null),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { slug, name, logo } = input;
|
||||
|
||||
const nameCollisions = await ctx.prisma.team.findFirst({
|
||||
@@ -110,19 +111,20 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
closeComUpsertTeamUser(createTeam, ctx.user, MembershipRole.OWNER);
|
||||
|
||||
return createTeam;
|
||||
},
|
||||
})
|
||||
// Allows team owner to update team metadata
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
bio: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
logo: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
hideBranding: z.boolean().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Allows team owner to update team metadata
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
bio: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
logo: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
hideBranding: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.id))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (input.slug) {
|
||||
@@ -169,13 +171,14 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
|
||||
// Sync Services: Close.com
|
||||
if (prevTeam) closeComUpdateTeam(prevTeam, updatedTeam);
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamOwner(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (IS_TEAM_BILLING_ENABLED) await cancelTeamSubscriptionFromStripe(input.teamId);
|
||||
@@ -195,15 +198,15 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
|
||||
// Sync Services: Close.cm
|
||||
closeComDeleteTeam(deletedTeam);
|
||||
},
|
||||
})
|
||||
// Allows owner to remove member from team
|
||||
.mutation("removeMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
removeMember: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const isAdmin = await isTeamAdmin(ctx.user?.id, input.teamId);
|
||||
if (!isAdmin && ctx.user?.id !== input.memberId) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only a team owner can remove another team owner.
|
||||
@@ -231,17 +234,18 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
closeComDeleteTeamMembership(membership.user);
|
||||
|
||||
if (HOSTED_CAL_FEATURES) await removeSeat(ctx.user.id, input.teamId, input.memberId);
|
||||
},
|
||||
})
|
||||
.mutation("inviteMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
usernameOrEmail: z.string(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
language: z.string(),
|
||||
sendEmailInvitation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
inviteMember: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
usernameOrEmail: z.string(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
language: z.string(),
|
||||
sendEmailInvitation: z.boolean(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
if (input.role === MembershipRole.OWNER && !(await isTeamOwner(ctx.user?.id, input.teamId)))
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
@@ -345,14 +349,15 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("acceptOrLeave", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
accept: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
acceptOrLeave: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
accept: z.boolean(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.accept) {
|
||||
const membership = await ctx.prisma.membership.update({
|
||||
where: {
|
||||
@@ -390,15 +395,16 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("changeMemberRole", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
changeMemberRole: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only owners can award owner role.
|
||||
if (input.role === MembershipRole.OWNER && !(await isTeamOwner(ctx.user?.id, input.teamId)))
|
||||
@@ -449,17 +455,18 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
|
||||
// Sync Services: Close.com
|
||||
closeComUpsertTeamUser(membership.team, membership.user, membership.role);
|
||||
},
|
||||
})
|
||||
.query("getMemberAvailability", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
timezone: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
getMemberAvailability: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
timezone: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const team = await isTeamMember(ctx.user?.id, input.teamId);
|
||||
if (!team) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
@@ -488,14 +495,15 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
},
|
||||
{ user: member.user }
|
||||
);
|
||||
},
|
||||
})
|
||||
.query("getMembershipbyUser", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
getMembershipbyUser: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
@@ -511,15 +519,16 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("updateMembership", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
disableImpersonation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
updateMembership: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
disableImpersonation: z.boolean(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
@@ -538,13 +547,14 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
disableImpersonation: input.disableImpersonation,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("validateTeamSlug", {
|
||||
input: z.object({
|
||||
slug: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
validateTeamSlug: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
slug: z.string(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
slug: input.slug,
|
||||
@@ -552,13 +562,14 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
});
|
||||
|
||||
return !team;
|
||||
},
|
||||
})
|
||||
.mutation("publish", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
publish: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
const { teamId: id } = input;
|
||||
|
||||
@@ -606,5 +617,5 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
closeComUpdateTeam(prevTeam, updatedTeam);
|
||||
|
||||
return { url: `${WEBAPP_URL}/settings/teams/${updatedTeam.id}/profile` };
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
// Common data for all endpoints under webhook
|
||||
const webhookIdAndEventTypeIdSchema = z.object({
|
||||
@@ -19,62 +19,65 @@ const webhookIdAndEventTypeIdSchema = z.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
});
|
||||
|
||||
export const webhookRouter = createProtectedRouter()
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
|
||||
if (!rawInput) {
|
||||
return next();
|
||||
}
|
||||
const webhookIdAndEventTypeId = webhookIdAndEventTypeIdSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
}
|
||||
const { eventTypeId, id } = webhookIdAndEventTypeId.data;
|
||||
const webhookProcedure = authedProcedure.use(async ({ ctx, rawInput, next }) => {
|
||||
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
|
||||
if (!rawInput) {
|
||||
return next();
|
||||
}
|
||||
const webhookIdAndEventTypeId = webhookIdAndEventTypeIdSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
}
|
||||
const { eventTypeId, id } = webhookIdAndEventTypeId.data;
|
||||
|
||||
// A webhook is either linked to Event Type or to a user.
|
||||
if (eventTypeId) {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
eventTypes: {
|
||||
some: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
// A webhook is either linked to Event Type or to a user.
|
||||
if (eventTypeId) {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
eventTypes: {
|
||||
some: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Team should be available and the user should be a member of the team
|
||||
if (!team?.members.some((membership) => membership.userId === ctx.user.id)) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
} else if (id) {
|
||||
const authorizedHook = await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
id: id,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
// Team should be available and the user should be a member of the team
|
||||
if (!team?.members.some((membership) => membership.userId === ctx.user.id)) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
if (!authorizedHook) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
}
|
||||
return next();
|
||||
})
|
||||
.query("list", {
|
||||
input: z
|
||||
.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
async resolve({ ctx, input }) {
|
||||
} else if (id) {
|
||||
const authorizedHook = await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
id: id,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
if (!authorizedHook) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
export const webhookRouter = router({
|
||||
list: webhookProcedure
|
||||
.input(
|
||||
z
|
||||
.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional(),
|
||||
})
|
||||
.optional()
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const where: Prisma.WebhookWhereInput = {
|
||||
/* Don't mixup zapier webhooks with normal ones */
|
||||
AND: [{ appId: !input?.appId ? null : input.appId }],
|
||||
@@ -90,13 +93,14 @@ export const webhookRouter = createProtectedRouter()
|
||||
return await ctx.prisma.webhook.findMany({
|
||||
where,
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
webhookId: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
get: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
webhookId: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return await ctx.prisma.webhook.findUniqueOrThrow({
|
||||
where: {
|
||||
id: input.webhookId,
|
||||
@@ -110,19 +114,20 @@ export const webhookRouter = createProtectedRouter()
|
||||
secret: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
subscriberUrl: z.string().url(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
|
||||
active: z.boolean(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
create: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
subscriberUrl: z.string().url(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
|
||||
active: z.boolean(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.eventTypeId) {
|
||||
return await ctx.prisma.webhook.create({
|
||||
data: {
|
||||
@@ -139,20 +144,21 @@ export const webhookRouter = createProtectedRouter()
|
||||
...input,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("edit", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
subscriberUrl: z.string().url().optional(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
|
||||
active: z.boolean().optional(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
edit: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
subscriberUrl: z.string().url().optional(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
|
||||
active: z.boolean().optional(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...data } = input;
|
||||
const webhook = input.eventTypeId
|
||||
? await ctx.prisma.webhook.findFirst({
|
||||
@@ -178,14 +184,15 @@ export const webhookRouter = createProtectedRouter()
|
||||
},
|
||||
data,
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
delete: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
input.eventTypeId
|
||||
? await ctx.prisma.eventType.update({
|
||||
@@ -215,15 +222,16 @@ export const webhookRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("testTrigger", {
|
||||
input: z.object({
|
||||
url: z.string().url(),
|
||||
type: z.string(),
|
||||
payloadTemplate: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
testTrigger: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
url: z.string().url(),
|
||||
type: z.string(),
|
||||
payloadTemplate: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { url, type, payloadTemplate = null } = input;
|
||||
const translation = await getTranslation("en", "common");
|
||||
const language = {
|
||||
@@ -264,5 +272,5 @@ export const webhookRouter = createProtectedRouter()
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -30,7 +30,7 @@ import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
function isSMSAction(action: WorkflowActions) {
|
||||
if (action === WorkflowActions.SMS_ATTENDEE || action === WorkflowActions.SMS_NUMBER) {
|
||||
@@ -38,39 +38,39 @@ function isSMSAction(action: WorkflowActions) {
|
||||
}
|
||||
}
|
||||
|
||||
export const workflowsRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const workflows = await ctx.prisma.workflow.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
export const workflowsRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
const workflows = await ctx.prisma.workflow.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
steps: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
|
||||
return { workflows };
|
||||
},
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
return { workflows };
|
||||
}),
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const workflow = await ctx.prisma.workflow.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
@@ -100,18 +100,19 @@ export const workflowsRouter = createProtectedRouter()
|
||||
});
|
||||
}
|
||||
return workflow;
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
timeUnit: z.enum(TIME_UNIT).optional(),
|
||||
time: z.number().optional(),
|
||||
sendTo: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
timeUnit: z.enum(TIME_UNIT).optional(),
|
||||
time: z.number().optional(),
|
||||
sendTo: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { name, trigger, action, timeUnit, time, sendTo } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
@@ -138,42 +139,41 @@ export const workflowsRouter = createProtectedRouter()
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("createV2", {
|
||||
async resolve({ ctx }) {
|
||||
const userId = ctx.user.id;
|
||||
|
||||
try {
|
||||
const workflow = await ctx.prisma.workflow.create({
|
||||
data: {
|
||||
name: "",
|
||||
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
time: 24,
|
||||
timeUnit: TimeUnit.HOUR,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.workflowStep.create({
|
||||
data: {
|
||||
stepNumber: 1,
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
template: WorkflowTemplates.REMINDER,
|
||||
workflowId: workflow.id,
|
||||
},
|
||||
});
|
||||
return { workflow };
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
createV2: authedProcedure.mutation(async ({ ctx }) => {
|
||||
const userId = ctx.user.id;
|
||||
|
||||
try {
|
||||
const workflow = await ctx.prisma.workflow.create({
|
||||
data: {
|
||||
name: "",
|
||||
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
time: 24,
|
||||
timeUnit: TimeUnit.HOUR,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.workflowStep.create({
|
||||
data: {
|
||||
stepNumber: 1,
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
template: WorkflowTemplates.REMINDER,
|
||||
workflowId: workflow.id,
|
||||
},
|
||||
});
|
||||
return { workflow };
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
}),
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
|
||||
const workflowToDelete = await ctx.prisma.workflow.findFirst({
|
||||
@@ -217,31 +217,32 @@ export const workflowsRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
activeOn: z.number().array(),
|
||||
steps: z
|
||||
.object({
|
||||
id: z.number(),
|
||||
stepNumber: z.number(),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
workflowId: z.number(),
|
||||
sendTo: z.string().optional().nullable(),
|
||||
reminderBody: z.string().optional().nullable(),
|
||||
emailSubject: z.string().optional().nullable(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
numberRequired: z.boolean().nullable(),
|
||||
})
|
||||
.array(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
time: z.number().nullable(),
|
||||
timeUnit: z.enum(TIME_UNIT).nullable(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
activeOn: z.number().array(),
|
||||
steps: z
|
||||
.object({
|
||||
id: z.number(),
|
||||
stepNumber: z.number(),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
workflowId: z.number(),
|
||||
sendTo: z.string().optional().nullable(),
|
||||
reminderBody: z.string().optional().nullable(),
|
||||
emailSubject: z.string().optional().nullable(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
numberRequired: z.boolean().nullable(),
|
||||
})
|
||||
.array(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
time: z.number().nullable(),
|
||||
timeUnit: z.enum(TIME_UNIT).nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { user } = ctx;
|
||||
const { id, name, activeOn, steps, trigger, time, timeUnit } = input;
|
||||
|
||||
@@ -802,17 +803,18 @@ export const workflowsRouter = createProtectedRouter()
|
||||
return {
|
||||
workflow,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("testAction", {
|
||||
input: z.object({
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
emailSubject: z.string(),
|
||||
reminderBody: z.string(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
sendTo: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
testAction: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
emailSubject: z.string(),
|
||||
reminderBody: z.string(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
sendTo: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { action, emailSubject, reminderBody, template, sendTo } = input;
|
||||
try {
|
||||
const booking = await ctx.prisma.booking.findFirst({
|
||||
@@ -914,21 +916,23 @@ export const workflowsRouter = createProtectedRouter()
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("activateEventType", {
|
||||
input: z.object({
|
||||
eventTypeId: z.number(),
|
||||
workflowId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
activateEventType: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
eventTypeId: z.number(),
|
||||
workflowId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { eventTypeId, workflowId } = input;
|
||||
|
||||
const eventType = await ctx.prisma.eventType.findFirst({
|
||||
where: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
});
|
||||
// NOTE: This was unused
|
||||
// const eventType = await ctx.prisma.eventType.findFirst({
|
||||
// where: {
|
||||
// id: eventTypeId,
|
||||
// },
|
||||
// });
|
||||
|
||||
//check if event type is already active
|
||||
|
||||
@@ -954,5 +958,5 @@ export const workflowsRouter = createProtectedRouter()
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { initTRPC, TRPCError } from "@trpc/server";
|
||||
|
||||
import { Context } from "./createContext";
|
||||
|
||||
export const t = initTRPC.context<Context>().create({
|
||||
const t = initTRPC.context<Context>().create({
|
||||
transformer: superjson,
|
||||
});
|
||||
|
||||
@@ -29,5 +29,8 @@ const isAuthedMiddleware = t.middleware(({ ctx, next }) => {
|
||||
});
|
||||
});
|
||||
|
||||
export const router = t.router;
|
||||
export const mergeRouters = t.mergeRouters;
|
||||
export const middleware = t.middleware;
|
||||
export const publicProcedure = t.procedure.use(perfMiddleware);
|
||||
export const authedProcedure = t.procedure.use(perfMiddleware).use(isAuthedMiddleware);
|
||||
Reference in new issue
Block a user