Migrates all tRPC code to a monorepo package (#3484)
* WIP * WIP * Type and migration fixes * Adds missing default import * Fixes import * Fixes tRPC imports in App Store * Migrate stripe helpers * WIP * Type fixes * Type fix? * Test fixes * Adds missing stripe packages * Moved queries to lib instead Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
e82bcb6dba
commit
9447f16b82
152 files changed
+1066
-724
No files matched your search
@@ -1,119 +0,0 @@
|
||||
import { GetServerSidePropsContext } from "next";
|
||||
import { Session } from "next-auth";
|
||||
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { getLocaleFromHeaders } from "@lib/core/i18n/i18n.utils";
|
||||
import prisma from "@lib/prisma";
|
||||
import { defaultAvatarSrc } from "@lib/profile";
|
||||
|
||||
import * as trpc from "@trpc/server";
|
||||
import { Maybe } from "@trpc/server";
|
||||
import * as trpcNext from "@trpc/server/adapters/next";
|
||||
|
||||
type CreateContextOptions = trpcNext.CreateNextContextOptions | GetServerSidePropsContext;
|
||||
|
||||
async function getUserFromSession({
|
||||
session,
|
||||
req,
|
||||
}: {
|
||||
session: Maybe<Session>;
|
||||
req: CreateContextOptions["req"];
|
||||
}) {
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
bio: true,
|
||||
timeZone: true,
|
||||
weekStart: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
defaultScheduleId: true,
|
||||
bufferTime: true,
|
||||
theme: true,
|
||||
createdDate: true,
|
||||
hideBranding: true,
|
||||
avatar: true,
|
||||
twoFactorEnabled: true,
|
||||
disableImpersonation: true,
|
||||
identityProvider: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
plan: true,
|
||||
away: true,
|
||||
credentials: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
userId: true,
|
||||
appId: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
},
|
||||
selectedCalendars: {
|
||||
select: {
|
||||
externalId: true,
|
||||
integration: true,
|
||||
},
|
||||
},
|
||||
completedOnboarding: true,
|
||||
destinationCalendar: true,
|
||||
locale: true,
|
||||
timeFormat: true,
|
||||
trialEndsAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
// some hacks to make sure `username` and `email` are never inferred as `null`
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
const { email, username } = user;
|
||||
if (!email) {
|
||||
return null;
|
||||
}
|
||||
const avatar = user.avatar || defaultAvatarSrc({ email });
|
||||
|
||||
const locale = user.locale || getLocaleFromHeaders(req);
|
||||
return {
|
||||
...user,
|
||||
avatar,
|
||||
email,
|
||||
username,
|
||||
locale,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates context for an incoming request
|
||||
* @link https://trpc.io/docs/context
|
||||
*/
|
||||
export const createContext = async ({ req }: CreateContextOptions) => {
|
||||
// for API-response caching see https://trpc.io/docs/caching
|
||||
const session = await getSession({ req });
|
||||
|
||||
const user = await getUserFromSession({ session, req });
|
||||
const locale = user?.locale ?? getLocaleFromHeaders(req);
|
||||
const i18n = await serverSideTranslations(locale, ["common", "vital"]);
|
||||
return {
|
||||
i18n,
|
||||
prisma,
|
||||
session,
|
||||
user,
|
||||
locale,
|
||||
};
|
||||
};
|
||||
|
||||
export type Context = trpc.inferAsyncReturnType<typeof createContext>;
|
||||
@@ -1,34 +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
|
||||
*/
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
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,18 +1 @@
|
||||
import i18next from "i18next";
|
||||
import { i18n as nexti18next } from "next-i18next";
|
||||
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
|
||||
export const getTranslation = async (locale: string, ns: string) => {
|
||||
const create = async () => {
|
||||
const { _nextI18Next } = await serverSideTranslations(locale, [ns]);
|
||||
const _i18n = i18next.createInstance();
|
||||
_i18n.init({
|
||||
lng: locale,
|
||||
resources: _nextI18Next.initialI18nStore,
|
||||
fallbackLng: _nextI18Next.userConfig?.i18n.defaultLocale,
|
||||
});
|
||||
return _i18n;
|
||||
};
|
||||
const _i18n = nexti18next != null ? nexti18next : await create();
|
||||
return _i18n.getFixedT(locale, ns);
|
||||
};
|
||||
export * from "@calcom/lib/server/i18n";
|
||||
@@ -3,10 +3,9 @@ import { i18n } from "next-i18next.config";
|
||||
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
import superjson from "superjson";
|
||||
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { appRouter } from "@server/routers/_app";
|
||||
import { createSSGHelpers } from "@trpc/react/ssg";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { createSSGHelpers } from "@calcom/trpc/react/ssg";
|
||||
import { appRouter } from "@calcom/trpc/server/routers/_app";
|
||||
|
||||
/**
|
||||
* Initialize static site rendering tRPC helpers.
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { GetServerSidePropsContext } from "next";
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createContext } from "@server/createContext";
|
||||
import { createSSGHelpers } from "@trpc/react/ssg";
|
||||
|
||||
import { appRouter } from "../routers/_app";
|
||||
import { createSSGHelpers } from "@calcom/trpc/react/ssg";
|
||||
import { createContext } from "@calcom/trpc/server/createContext";
|
||||
import { appRouter } from "@calcom/trpc/server/routers/_app";
|
||||
|
||||
/**
|
||||
* Initialize server-side rendering tRPC helpers.
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
/**
|
||||
* This file contains the root router of your tRPC-backend
|
||||
*/
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createRouter } from "../createRouter";
|
||||
import { viewerRouter } from "./viewer";
|
||||
|
||||
/**
|
||||
* Create your application's root router
|
||||
* If you want to use SSG, you need export this
|
||||
* @link https://trpc.io/docs/ssg
|
||||
* @link https://trpc.io/docs/router
|
||||
*/
|
||||
export const appRouter = createRouter()
|
||||
/**
|
||||
* Add data transformers
|
||||
* @link https://trpc.io/docs/data-transformers
|
||||
*/
|
||||
.transformer(superjson)
|
||||
/**
|
||||
* Optionally do custom error (type safe!) formatting
|
||||
* @link https://trpc.io/docs/error-formatting
|
||||
*/
|
||||
// .formatError(({ shape, error }) => { })
|
||||
.merge("viewer.", viewerRouter);
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,132 +0,0 @@
|
||||
import { v4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import { generateUniqueAPIKey } from "@calcom/ee/lib/api/apiKeys";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
|
||||
export const apiKeysRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ 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 }) {
|
||||
return await ctx.prisma.apiKey.findFirst({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
{
|
||||
appId: input.appId,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.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 }) {
|
||||
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;
|
||||
delete input.neverExpires;
|
||||
await ctx.prisma.apiKey.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
userId: ctx.user.id,
|
||||
...input,
|
||||
// And here we pass a null to expiresAt if never expires is true. otherwise just pass expiresAt from input
|
||||
expiresAt: neverExpires ? null : input.expiresAt,
|
||||
hashedKey: hashedApiKey,
|
||||
},
|
||||
});
|
||||
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 }) {
|
||||
const { id, ...data } = input;
|
||||
const {
|
||||
apiKeys: [updatedApiKey],
|
||||
} = await ctx.prisma.user.update({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
data: {
|
||||
apiKeys: {
|
||||
update: {
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
apiKeys: {
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return updatedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
await ctx.prisma.user.update({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
data: {
|
||||
apiKeys: {
|
||||
delete: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -1,252 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getAvailabilityFromSchedule } from "@lib/availability";
|
||||
import { Schedule } from "@lib/types/schedule";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
export const availabilityRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ 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",
|
||||
},
|
||||
});
|
||||
return {
|
||||
schedules: schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
isDefault: user.defaultScheduleId === schedule.id || schedules.length === 1,
|
||||
})),
|
||||
};
|
||||
},
|
||||
})
|
||||
.query("schedule", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
});
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = schedule.availability.reduce(
|
||||
(schedule: Schedule, availability) => {
|
||||
availability.days.forEach((day) => {
|
||||
schedule[day].push({
|
||||
start: new Date(
|
||||
Date.UTC(
|
||||
new Date().getUTCFullYear(),
|
||||
new Date().getUTCMonth(),
|
||||
new Date().getUTCDate(),
|
||||
availability.startTime.getUTCHours(),
|
||||
availability.startTime.getUTCMinutes()
|
||||
)
|
||||
),
|
||||
end: new Date(
|
||||
Date.UTC(
|
||||
new Date().getUTCFullYear(),
|
||||
new Date().getUTCMonth(),
|
||||
new Date().getUTCDate(),
|
||||
availability.endTime.getUTCHours(),
|
||||
availability.endTime.getUTCMinutes()
|
||||
)
|
||||
),
|
||||
});
|
||||
});
|
||||
return schedule;
|
||||
},
|
||||
Array.from([...Array(7)]).map(() => [])
|
||||
);
|
||||
return {
|
||||
schedule,
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !user.defaultScheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.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(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const data: Prisma.ScheduleCreateInput = {
|
||||
name: input.name,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (input.schedule) {
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
data.availability = {
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
const schedule = await prisma.schedule.create({
|
||||
data,
|
||||
});
|
||||
return { schedule };
|
||||
},
|
||||
})
|
||||
.mutation("schedule.delete", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
}),
|
||||
async resolve({ 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) {
|
||||
// unset default
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
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);
|
||||
|
||||
if (input.isDefault) {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: input.scheduleId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 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,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
schedule,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -1,156 +0,0 @@
|
||||
import { SchedulingType } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sendLocationChangeEmails } from "@calcom/emails";
|
||||
import { parseRecurringEvent } from "@calcom/lib";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
// Common data for all endpoints under webhook
|
||||
const commonBookingSchema = z.object({
|
||||
bookingId: z.number(),
|
||||
});
|
||||
|
||||
export const bookingsRouter = 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({ ctx: { ...ctx, booking: null } });
|
||||
|
||||
const webhookIdAndEventTypeId = commonBookingSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
|
||||
const { bookingId } = webhookIdAndEventTypeId.data;
|
||||
const booking = await ctx.prisma.booking.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
/* If user is organizer */
|
||||
{ userId: ctx.user.id, id: bookingId },
|
||||
/* Or part of a collective booking */
|
||||
{
|
||||
eventType: {
|
||||
schedulingType: SchedulingType.COLLECTIVE,
|
||||
users: {
|
||||
some: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: {
|
||||
include: { destinationCalendar: true },
|
||||
},
|
||||
destinationCalendar: true,
|
||||
},
|
||||
});
|
||||
return next({ ctx: { ...ctx, booking } });
|
||||
})
|
||||
.middleware(async ({ ctx, next }) => {
|
||||
// So TS doesn't compain in the previous middleware.
|
||||
// This means the user doesn't have access to this booking
|
||||
if (!ctx.booking) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Booking here is non-nullable anymore
|
||||
return next({ ctx: { ...ctx, booking: ctx.booking } });
|
||||
})
|
||||
.mutation("editLocation", {
|
||||
input: commonBookingSchema.extend({
|
||||
newLocation: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { bookingId, newLocation: location } = input;
|
||||
const { booking } = ctx;
|
||||
|
||||
try {
|
||||
await ctx.prisma.booking.update({
|
||||
where: { id: bookingId },
|
||||
data: { location },
|
||||
});
|
||||
|
||||
const organizer = await ctx.prisma.user.findFirst({
|
||||
where: {
|
||||
id: booking.userId || 0,
|
||||
},
|
||||
select: {
|
||||
name: true,
|
||||
email: true,
|
||||
timeZone: true,
|
||||
locale: true,
|
||||
},
|
||||
rejectOnNotFound: true,
|
||||
});
|
||||
|
||||
const tOrganizer = await getTranslation(organizer.locale ?? "en", "common");
|
||||
|
||||
const attendeesListPromises = booking.attendees.map(async (attendee) => {
|
||||
return {
|
||||
name: attendee.name,
|
||||
email: attendee.email,
|
||||
timeZone: attendee.timeZone,
|
||||
language: {
|
||||
translate: await getTranslation(attendee.locale ?? "en", "common"),
|
||||
locale: attendee.locale ?? "en",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const attendeesList = await Promise.all(attendeesListPromises);
|
||||
|
||||
const evt: CalendarEvent = {
|
||||
title: booking.title || "",
|
||||
type: (booking.eventType?.title as string) || booking?.title || "",
|
||||
description: booking.description || "",
|
||||
startTime: booking.startTime ? dayjs(booking.startTime).format() : "",
|
||||
endTime: booking.endTime ? dayjs(booking.endTime).format() : "",
|
||||
organizer: {
|
||||
email: organizer.email,
|
||||
name: organizer.name ?? "Nameless",
|
||||
timeZone: organizer.timeZone,
|
||||
language: { translate: tOrganizer, locale: organizer.locale ?? "en" },
|
||||
},
|
||||
attendees: attendeesList,
|
||||
uid: booking.uid,
|
||||
recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),
|
||||
location,
|
||||
destinationCalendar: booking?.destinationCalendar || booking?.user?.destinationCalendar,
|
||||
};
|
||||
|
||||
const eventManager = new EventManager(ctx.user);
|
||||
// TODO: This is causing duplicate calendar events when updating location
|
||||
const scheduleResult = await eventManager.create(evt);
|
||||
|
||||
const results = scheduleResult.results;
|
||||
if (results.length > 0 && results.every((res) => !res.success)) {
|
||||
const error = {
|
||||
errorCode: "BookingUpdateLocationFailed",
|
||||
message: "Updating location failed",
|
||||
};
|
||||
logger.error(`Booking ${ctx.user.username} failed`, error, results);
|
||||
} else {
|
||||
const metadata: AdditionalInformation = {};
|
||||
if (results.length) {
|
||||
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
|
||||
metadata.conferenceData = results[0].createdEvent?.conferenceData;
|
||||
metadata.entryPoints = results[0].createdEvent?.entryPoints;
|
||||
}
|
||||
try {
|
||||
await sendLocationChangeEmails({ ...evt, additionalInformation: metadata });
|
||||
} catch (error) {
|
||||
console.log("Error sending LocationChangeEmails");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
return { message: "Location updated" };
|
||||
},
|
||||
});
|
||||
@@ -1,408 +0,0 @@
|
||||
import { EventTypeCustomInput, MembershipRole, PeriodType, Prisma } from "@prisma/client";
|
||||
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { _DestinationCalendarModel, _EventTypeCustomInputModel, _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import { stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { createEventTypeInput } from "@calcom/prisma/zod/custom/eventtype";
|
||||
import { stripeDataSchema } from "@calcom/stripe/server";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
import { viewerRouter } from "@server/routers/viewer";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
function isPeriodType(keyInput: string): keyInput is PeriodType {
|
||||
return Object.keys(PeriodType).includes(keyInput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that it is a valid HTTP URL
|
||||
* It automatically avoids
|
||||
* - XSS attempts through javascript:alert('hi')
|
||||
* - mailto: links
|
||||
*/
|
||||
function assertValidUrl(url: string | null | undefined) {
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!url.startsWith("http://") && !url.startsWith("https://")) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR", message: "Invalid URL" });
|
||||
}
|
||||
}
|
||||
|
||||
function handlePeriodType(periodType: string | undefined): PeriodType | undefined {
|
||||
if (typeof periodType !== "string") return undefined;
|
||||
const passedPeriodType = periodType.toUpperCase();
|
||||
if (!isPeriodType(passedPeriodType)) return undefined;
|
||||
return PeriodType[passedPeriodType];
|
||||
}
|
||||
|
||||
function handleCustomInputs(customInputs: EventTypeCustomInput[], eventTypeId: number) {
|
||||
const cInputsIdsToDelete = customInputs.filter((input) => input.id > 0).map((e) => e.id);
|
||||
const cInputsToCreate = customInputs
|
||||
.filter((input) => input.id < 0)
|
||||
.map((input) => ({
|
||||
type: input.type,
|
||||
label: input.label,
|
||||
required: input.required,
|
||||
placeholder: input.placeholder,
|
||||
}));
|
||||
const cInputsToUpdate = customInputs
|
||||
.filter((input) => input.id > 0)
|
||||
.map((input) => ({
|
||||
data: {
|
||||
type: input.type,
|
||||
label: input.label,
|
||||
required: input.required,
|
||||
placeholder: input.placeholder,
|
||||
},
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
deleteMany: {
|
||||
eventTypeId,
|
||||
NOT: {
|
||||
id: { in: cInputsIdsToDelete },
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: cInputsToCreate,
|
||||
},
|
||||
update: cInputsToUpdate,
|
||||
};
|
||||
}
|
||||
|
||||
const EventTypeUpdateInput = _EventTypeModel
|
||||
/** Optional fields */
|
||||
.extend({
|
||||
customInputs: z.array(_EventTypeCustomInputModel),
|
||||
destinationCalendar: _DestinationCalendarModel.pick({
|
||||
integration: true,
|
||||
externalId: true,
|
||||
}),
|
||||
users: z.array(stringOrNumber).optional(),
|
||||
schedule: z.number().optional(),
|
||||
hashedLink: z.string(),
|
||||
})
|
||||
.partial()
|
||||
.merge(
|
||||
_EventTypeModel
|
||||
/** Required fields */
|
||||
.pick({
|
||||
id: true,
|
||||
})
|
||||
);
|
||||
|
||||
export const eventTypesRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.webhook.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.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: "integrations:daily" }];
|
||||
}
|
||||
|
||||
if (teamId && schedulingType) {
|
||||
const hasMembership = await ctx.prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasMembership) {
|
||||
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;
|
||||
}
|
||||
},
|
||||
})
|
||||
// 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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
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();
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const user = await ctx.prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
bufferTime: true,
|
||||
avatar: true,
|
||||
plan: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
return await ctx.prisma.eventType.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: EventTypeUpdateInput.strict(),
|
||||
async resolve({ ctx, input }) {
|
||||
const {
|
||||
schedule,
|
||||
periodType,
|
||||
locations,
|
||||
destinationCalendar,
|
||||
customInputs,
|
||||
recurringEvent,
|
||||
users,
|
||||
id,
|
||||
hashedLink,
|
||||
...rest
|
||||
} = input;
|
||||
assertValidUrl(input.successRedirectUrl);
|
||||
const data: Prisma.EventTypeUpdateInput = rest;
|
||||
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,
|
||||
};
|
||||
} else {
|
||||
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).mutation("setDestinationCalendar", {
|
||||
...destinationCalendar,
|
||||
eventTypeId: id,
|
||||
});
|
||||
}
|
||||
|
||||
if (customInputs) {
|
||||
data.customInputs = handleCustomInputs(customInputs, id);
|
||||
}
|
||||
|
||||
if (schedule) {
|
||||
data.schedule = {
|
||||
connect: {
|
||||
id: schedule,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
select: {
|
||||
id: 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,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const eventType = await ctx.prisma.eventType.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
|
||||
return { eventType };
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
|
||||
await ctx.prisma.eventTypeCustomInput.deleteMany({
|
||||
where: {
|
||||
eventTypeId: id,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.eventType.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -1,286 +0,0 @@
|
||||
import { SchedulingType } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { CurrentSeats } from "@calcom/core/getUserAvailability";
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import dayjs, { Dayjs } from "@calcom/dayjs";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import { TimeRange } from "@calcom/types/schedule";
|
||||
|
||||
import isOutOfBounds from "@lib/isOutOfBounds";
|
||||
import getSlots from "@lib/slots";
|
||||
|
||||
import { createRouter } from "@server/createRouter";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const getScheduleSchema = z
|
||||
.object({
|
||||
// startTime ISOString
|
||||
startTime: z.string(),
|
||||
// endTime ISOString
|
||||
endTime: z.string(),
|
||||
// Event type ID
|
||||
eventTypeId: z.number().optional(),
|
||||
// invitee timezone
|
||||
timeZone: z.string().optional(),
|
||||
// or list of users (for dynamic events)
|
||||
usernameList: z.array(z.string()).optional(),
|
||||
debug: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => !!data.eventTypeId || !!data.usernameList,
|
||||
"Either usernameList or eventTypeId should be filled in."
|
||||
);
|
||||
|
||||
export type Slot = {
|
||||
time: string;
|
||||
attendees?: number;
|
||||
bookingUid?: string;
|
||||
users?: string[];
|
||||
};
|
||||
|
||||
const checkForAvailability = ({
|
||||
time,
|
||||
busy,
|
||||
eventLength,
|
||||
beforeBufferTime,
|
||||
currentSeats,
|
||||
}: {
|
||||
time: Dayjs;
|
||||
busy: (TimeRange | { start: string; end: string })[];
|
||||
eventLength: number;
|
||||
beforeBufferTime: number;
|
||||
currentSeats?: CurrentSeats;
|
||||
}) => {
|
||||
if (currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const slotEndTime = time.add(eventLength, "minutes").utc();
|
||||
const slotStartTime = time.subtract(beforeBufferTime, "minutes").utc();
|
||||
|
||||
return busy.every((busyTime) => {
|
||||
const startTime = dayjs.utc(busyTime.start);
|
||||
const endTime = dayjs.utc(busyTime.end);
|
||||
|
||||
if (endTime.isBefore(slotStartTime) || startTime.isAfter(slotEndTime)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (slotStartTime.isBetween(startTime, endTime, null, "[)")) {
|
||||
return false;
|
||||
} else if (slotEndTime.isBetween(startTime, endTime, null, "(]")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if start times are the same
|
||||
if (time.utc().isBetween(startTime, endTime, null, "[)")) {
|
||||
return false;
|
||||
}
|
||||
// Check if slot end time is between start and end time
|
||||
else if (slotEndTime.isBetween(startTime, endTime)) {
|
||||
return false;
|
||||
}
|
||||
// Check if startTime is between slot
|
||||
else if (startTime.isBetween(time, slotEndTime)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
export const slotsRouter = createRouter().query("getSchedule", {
|
||||
input: getScheduleSchema,
|
||||
async resolve({ input, ctx }) {
|
||||
return await getSchedule(input, ctx);
|
||||
},
|
||||
});
|
||||
|
||||
export async function getSchedule(
|
||||
input: {
|
||||
timeZone?: string | undefined;
|
||||
eventTypeId?: number | undefined;
|
||||
usernameList?: string[] | undefined;
|
||||
debug?: boolean | undefined;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
},
|
||||
ctx: { prisma: typeof prisma }
|
||||
) {
|
||||
if (input.debug === true) {
|
||||
logger.setSettings({ minLevel: "debug" });
|
||||
}
|
||||
if (process.env.INTEGRATION_TEST_MODE === "true") {
|
||||
logger.setSettings({ minLevel: "silly" });
|
||||
}
|
||||
const startPrismaEventTypeGet = performance.now();
|
||||
const eventType = await ctx.prisma.eventType.findUnique({
|
||||
where: {
|
||||
id: input.eventTypeId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
minimumBookingNotice: true,
|
||||
length: true,
|
||||
seatsPerTimeSlot: true,
|
||||
timeZone: true,
|
||||
slotInterval: true,
|
||||
beforeEventBuffer: true,
|
||||
afterEventBuffer: true,
|
||||
schedulingType: true,
|
||||
periodType: true,
|
||||
periodStartDate: true,
|
||||
periodEndDate: true,
|
||||
periodCountCalendarDays: true,
|
||||
periodDays: true,
|
||||
schedule: {
|
||||
select: {
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
availability: {
|
||||
select: {
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
days: true,
|
||||
},
|
||||
},
|
||||
users: {
|
||||
select: {
|
||||
username: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const endPrismaEventTypeGet = performance.now();
|
||||
logger.debug(
|
||||
`Prisma eventType get took ${endPrismaEventTypeGet - startPrismaEventTypeGet}ms for event:${
|
||||
input.eventTypeId
|
||||
}`
|
||||
);
|
||||
if (!eventType) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const startTime =
|
||||
input.timeZone === "Etc/GMT"
|
||||
? dayjs.utc(input.startTime)
|
||||
: dayjs(input.startTime).utc().tz(input.timeZone);
|
||||
const endTime =
|
||||
input.timeZone === "Etc/GMT" ? dayjs.utc(input.endTime) : dayjs(input.endTime).utc().tz(input.timeZone);
|
||||
|
||||
if (!startTime.isValid() || !endTime.isValid()) {
|
||||
throw new TRPCError({ message: "Invalid time range given.", code: "BAD_REQUEST" });
|
||||
}
|
||||
let currentSeats: CurrentSeats | undefined = undefined;
|
||||
|
||||
const userSchedules = await Promise.all(
|
||||
eventType.users.map(async (currentUser) => {
|
||||
const {
|
||||
busy,
|
||||
workingHours,
|
||||
currentSeats: _currentSeats,
|
||||
} = await getUserAvailability(
|
||||
{
|
||||
userId: currentUser.id,
|
||||
dateFrom: startTime.format(),
|
||||
dateTo: endTime.format(),
|
||||
eventTypeId: input.eventTypeId,
|
||||
afterEventBuffer: eventType.afterEventBuffer,
|
||||
},
|
||||
{ user: currentUser, eventType, currentSeats }
|
||||
);
|
||||
if (!currentSeats && _currentSeats) currentSeats = _currentSeats;
|
||||
|
||||
return {
|
||||
workingHours,
|
||||
busy,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const workingHours = userSchedules.flatMap((s) => s.workingHours);
|
||||
|
||||
const slots: Record<string, Slot[]> = {};
|
||||
const availabilityCheckProps = {
|
||||
eventLength: eventType.length,
|
||||
beforeBufferTime: eventType.beforeEventBuffer,
|
||||
currentSeats,
|
||||
};
|
||||
const isWithinBounds = (_time: Parameters<typeof isOutOfBounds>[0]) =>
|
||||
!isOutOfBounds(_time, {
|
||||
periodType: eventType.periodType,
|
||||
periodStartDate: eventType.periodStartDate,
|
||||
periodEndDate: eventType.periodEndDate,
|
||||
periodCountCalendarDays: eventType.periodCountCalendarDays,
|
||||
periodDays: eventType.periodDays,
|
||||
});
|
||||
|
||||
let time = startTime;
|
||||
let getSlotsTime = 0;
|
||||
let checkForAvailabilityTime = 0;
|
||||
let getSlotsCount = 0;
|
||||
let checkForAvailabilityCount = 0;
|
||||
do {
|
||||
const startGetSlots = performance.now();
|
||||
// get slots retrieves the available times for a given day
|
||||
const times = getSlots({
|
||||
inviteeDate: time,
|
||||
eventLength: eventType.length,
|
||||
workingHours,
|
||||
minimumBookingNotice: eventType.minimumBookingNotice,
|
||||
frequency: eventType.slotInterval || eventType.length,
|
||||
});
|
||||
const endGetSlots = performance.now();
|
||||
getSlotsTime += endGetSlots - startGetSlots;
|
||||
getSlotsCount++;
|
||||
// if ROUND_ROBIN - slots stay available on some() - if normal / COLLECTIVE - slots only stay available on every()
|
||||
const filterStrategy =
|
||||
!eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE
|
||||
? ("every" as const)
|
||||
: ("some" as const);
|
||||
|
||||
const filteredTimes = times.filter(isWithinBounds).filter((time) =>
|
||||
userSchedules[filterStrategy]((schedule) => {
|
||||
const startCheckForAvailability = performance.now();
|
||||
const result = checkForAvailability({ time, ...schedule, ...availabilityCheckProps });
|
||||
const endCheckForAvailability = performance.now();
|
||||
checkForAvailabilityCount++;
|
||||
checkForAvailabilityTime += endCheckForAvailability - startCheckForAvailability;
|
||||
return result;
|
||||
})
|
||||
);
|
||||
|
||||
slots[time.format("YYYY-MM-DD")] = filteredTimes.map((time) => ({
|
||||
time: time.toISOString(),
|
||||
users: eventType.users.map((user) => user.username || ""),
|
||||
// Conditionally add the attendees and booking id to slots object if there is already a booking during that time
|
||||
...(currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString()) && {
|
||||
attendees:
|
||||
currentSeats[
|
||||
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
|
||||
]._count.attendees,
|
||||
bookingUid:
|
||||
currentSeats[
|
||||
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
|
||||
].uid,
|
||||
}),
|
||||
}));
|
||||
time = time.add(1, "day");
|
||||
} while (time.isBefore(endTime));
|
||||
|
||||
logger.debug(`getSlots took ${getSlotsTime}ms and executed ${getSlotsCount} times`);
|
||||
|
||||
logger.debug(
|
||||
`checkForAvailability took ${checkForAvailabilityTime}ms and executed ${checkForAvailabilityCount} times`
|
||||
);
|
||||
logger.silly(`Available slots: ${JSON.stringify(slots)}`);
|
||||
return {
|
||||
slots,
|
||||
};
|
||||
}
|
||||
@@ -1,514 +0,0 @@
|
||||
import { MembershipRole, Prisma, UserPlan } from "@prisma/client";
|
||||
import { randomBytes } from "crypto";
|
||||
import { resolve } from "path";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import { sendTeamInviteEmail } from "@calcom/emails";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import {
|
||||
addSeat,
|
||||
downgradeTeamMembers,
|
||||
ensureSubscriptionQuantityCorrectness,
|
||||
getTeamSeatStats,
|
||||
removeSeat,
|
||||
upgradeTeam,
|
||||
} from "@calcom/stripe/team-billing";
|
||||
|
||||
import { BASE_URL, HOSTED_CAL_FEATURES } from "@lib/config/constants";
|
||||
import { getTeamWithMembers, isTeamAdmin, isTeamOwner } from "@lib/queries/teams";
|
||||
import slugify from "@lib/slugify";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
import { getTranslation } from "@server/lib/i18n";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
export const viewerTeamsRouter = createProtectedRouter()
|
||||
// Retrieves team by id
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const team = await getTeamWithMembers(input.teamId);
|
||||
if (!team?.members.find((m) => m.id === ctx.user.id)) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not a member of this team." });
|
||||
}
|
||||
const membership = team?.members.find((membership) => membership.id === ctx.user.id);
|
||||
return {
|
||||
...team,
|
||||
membership: {
|
||||
role: membership?.role as MembershipRole,
|
||||
isMissingSeat: membership?.plan === UserPlan.FREE,
|
||||
},
|
||||
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,
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
const teams = await ctx.prisma.team.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: memberships.map((membership) => membership.teamId),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return memberships.map((membership) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...teams.find((team) => team.id === membership.teamId),
|
||||
}));
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (ctx.user.plan === "FREE") {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not a pro user." });
|
||||
}
|
||||
|
||||
const slug = slugify(input.name);
|
||||
|
||||
const nameCollisions = await ctx.prisma.team.count({
|
||||
where: {
|
||||
OR: [{ name: input.name }, { slug: slug }],
|
||||
},
|
||||
});
|
||||
|
||||
if (nameCollisions > 0)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Team name already taken." });
|
||||
|
||||
const createTeam = await ctx.prisma.team.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
slug: slug,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.membership.create({
|
||||
data: {
|
||||
teamId: createTeam.id,
|
||||
userId: ctx.user.id,
|
||||
role: "OWNER",
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
// 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 }) {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.id))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (input.slug) {
|
||||
const userConflict = await ctx.prisma.team.findMany({
|
||||
where: {
|
||||
slug: input.slug,
|
||||
},
|
||||
});
|
||||
if (userConflict.some((t) => t.id !== input.id)) return;
|
||||
}
|
||||
await ctx.prisma.team.update({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
data: {
|
||||
name: input.name,
|
||||
slug: input.slug,
|
||||
logo: input.logo,
|
||||
bio: input.bio,
|
||||
hideBranding: input.hideBranding,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamOwner(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (process.env.STRIPE_PRIVATE_KEY) {
|
||||
await downgradeTeamMembers(input.teamId);
|
||||
}
|
||||
|
||||
// delete all memberships
|
||||
await ctx.prisma.membership.deleteMany({
|
||||
where: {
|
||||
teamId: input.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.team.delete({
|
||||
where: {
|
||||
id: input.teamId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
// Allows owner to remove member from team
|
||||
.mutation("removeMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only a team owner can remove another team owner.
|
||||
if (
|
||||
(await isTeamOwner(input.memberId, input.teamId)) &&
|
||||
!(await isTeamOwner(ctx.user?.id, input.teamId))
|
||||
)
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
if (ctx.user?.id === input.memberId)
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not remove yourself from a team you own.",
|
||||
});
|
||||
await ctx.prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId: input.memberId, teamId: input.teamId },
|
||||
},
|
||||
});
|
||||
|
||||
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 }) {
|
||||
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" });
|
||||
|
||||
const translation = await getTranslation(input.language ?? "en", "common");
|
||||
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
id: input.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!team) throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
|
||||
|
||||
const invitee = await ctx.prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ username: input.usernameOrEmail }, { email: input.usernameOrEmail }],
|
||||
},
|
||||
});
|
||||
|
||||
let inviteeUserId: number | undefined = invitee?.id;
|
||||
|
||||
if (!invitee) {
|
||||
// liberal email match
|
||||
const isEmail = (str: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
|
||||
|
||||
if (!isEmail(input.usernameOrEmail))
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: `Invite failed because there is no corresponding user for ${input.usernameOrEmail}`,
|
||||
});
|
||||
|
||||
// valid email given, create User and add to team
|
||||
const user = await ctx.prisma.user.create({
|
||||
data: {
|
||||
email: input.usernameOrEmail,
|
||||
invitedTo: input.teamId,
|
||||
teams: {
|
||||
create: {
|
||||
teamId: input.teamId,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
inviteeUserId = user.id;
|
||||
|
||||
const token: string = randomBytes(32).toString("hex");
|
||||
|
||||
await ctx.prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: input.usernameOrEmail,
|
||||
token,
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
},
|
||||
});
|
||||
|
||||
if (ctx?.user?.name && team?.name) {
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: input.usernameOrEmail,
|
||||
teamName: team.name,
|
||||
joinLink: `${BASE_URL}/auth/signup?token=${token}&callbackUrl=${BASE_URL + "/settings/teams"}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// create provisional membership
|
||||
try {
|
||||
await ctx.prisma.membership.create({
|
||||
data: {
|
||||
teamId: input.teamId,
|
||||
userId: invitee.id,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This user is a member of this team / has a pending invitation.",
|
||||
});
|
||||
}
|
||||
} else throw e;
|
||||
}
|
||||
|
||||
// inform user of membership by email
|
||||
if (input.sendEmailInvitation && ctx?.user?.name && team?.name) {
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: input.usernameOrEmail,
|
||||
teamName: team.name,
|
||||
joinLink: BASE_URL + "/settings/teams",
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (HOSTED_CAL_FEATURES) await addSeat(ctx.user.id, team.id, inviteeUserId);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("acceptOrLeave", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
accept: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (input.accept) {
|
||||
await ctx.prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: { userId: ctx.user.id, teamId: input.teamId },
|
||||
},
|
||||
data: {
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
//get team owner so we can alter their subscription seat count
|
||||
const teamOwner = await ctx.prisma.membership.findFirst({
|
||||
where: { teamId: input.teamId, role: MembershipRole.OWNER },
|
||||
});
|
||||
|
||||
// TODO: disable if not hosted by Cal
|
||||
if (teamOwner) await removeSeat(teamOwner.userId, input.teamId, ctx.user.id);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
await ctx.prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId: ctx.user.id, teamId: input.teamId },
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("changeMemberRole", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
}),
|
||||
async resolve({ 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)))
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: input.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
const targetMembership = memberships.find((m) => m.userId === input.memberId);
|
||||
const myMembership = memberships.find((m) => m.userId === ctx.user.id);
|
||||
const teamHasMoreThanOneOwner = memberships.some((m) => m.role === MembershipRole.OWNER);
|
||||
|
||||
if (myMembership?.role === MembershipRole.ADMIN && targetMembership?.role === MembershipRole.OWNER) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not change the role of an owner if you are an admin.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!teamHasMoreThanOneOwner) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not change the role of the only owner of a team.",
|
||||
});
|
||||
}
|
||||
|
||||
if (myMembership?.role === MembershipRole.ADMIN && input.memberId === ctx.user.id) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not change yourself to a higher role.",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: { userId: input.memberId, teamId: input.teamId },
|
||||
},
|
||||
data: {
|
||||
role: input.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 }) {
|
||||
const team = await isTeamAdmin(ctx.user?.id, input.teamId);
|
||||
if (!team) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
// verify member is in team
|
||||
const members = await ctx.prisma.membership.findMany({
|
||||
where: { teamId: input.teamId },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
username: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const member = members?.find((m) => m.userId === input.memberId);
|
||||
if (!member) throw new TRPCError({ code: "NOT_FOUND", message: "Member not found" });
|
||||
if (!member.user.username)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Member doesn't have a username" });
|
||||
|
||||
// get availability for this member
|
||||
return await getUserAvailability(
|
||||
{
|
||||
username: member.user.username,
|
||||
timezone: input.timezone,
|
||||
dateFrom: input.dateFrom,
|
||||
dateTo: input.dateTo,
|
||||
},
|
||||
{ user: member.user }
|
||||
);
|
||||
},
|
||||
})
|
||||
.mutation("upgradeTeam", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!HOSTED_CAL_FEATURES)
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Team billing is not enabled" });
|
||||
return await upgradeTeam(ctx.user.id, input.teamId);
|
||||
},
|
||||
})
|
||||
.query("getTeamSeats", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
return await getTeamSeatStats(input.teamId);
|
||||
},
|
||||
})
|
||||
.mutation("ensureSubscriptionQuantityCorrectness", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
return await ensureSubscriptionQuantityCorrectness(ctx.user.id, input.teamId);
|
||||
},
|
||||
})
|
||||
.query("getMembershipbyUser", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You cannot view memberships that are not your own.",
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: input.memberId,
|
||||
teamId: input.teamId,
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("updateMembership", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
disableImpersonation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You cannot edit memberships that are not your own.",
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: input.memberId,
|
||||
teamId: input.teamId,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
disableImpersonation: input.disableImpersonation,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,248 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { v4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
|
||||
import { WEBHOOK_TRIGGER_EVENTS } from "@lib/webhooks/constants";
|
||||
import sendPayload from "@lib/webhooks/sendPayload";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
import { getTranslation } from "@server/lib/i18n";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
// Common data for all endpoints under webhook
|
||||
const webhookIdAndEventTypeIdSchema = z.object({
|
||||
// Webhook ID
|
||||
id: z.string().optional(),
|
||||
// Event type ID
|
||||
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;
|
||||
|
||||
// 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,
|
||||
},
|
||||
});
|
||||
|
||||
// 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,
|
||||
},
|
||||
});
|
||||
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 }) {
|
||||
const where: Prisma.WebhookWhereInput = {
|
||||
/* Don't mixup zapier webhooks with normal ones */
|
||||
AND: [{ appId: !input?.appId ? null : input.appId }],
|
||||
};
|
||||
if (Array.isArray(where.AND)) {
|
||||
if (input?.eventTypeId) {
|
||||
where.AND?.push({ eventTypeId: input.eventTypeId });
|
||||
} else {
|
||||
where.AND?.push({ userId: ctx.user.id });
|
||||
}
|
||||
}
|
||||
|
||||
return await ctx.prisma.webhook.findMany({
|
||||
where,
|
||||
});
|
||||
},
|
||||
})
|
||||
.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 }) {
|
||||
if (input.eventTypeId) {
|
||||
return await ctx.prisma.webhook.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
...input,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.webhook.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
userId: ctx.user.id,
|
||||
...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 }) {
|
||||
const { id, ...data } = input;
|
||||
const webhook = input.eventTypeId
|
||||
? await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.eventTypeId,
|
||||
id,
|
||||
},
|
||||
})
|
||||
: await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
id,
|
||||
},
|
||||
});
|
||||
if (!webhook) {
|
||||
// user does not own this webhook
|
||||
// team event doesn't own this webhook
|
||||
return null;
|
||||
}
|
||||
return await ctx.prisma.webhook.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
input.eventTypeId
|
||||
? await ctx.prisma.eventType.update({
|
||||
where: {
|
||||
id: input.eventTypeId,
|
||||
},
|
||||
data: {
|
||||
webhooks: {
|
||||
delete: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: await ctx.prisma.user.update({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
data: {
|
||||
webhooks: {
|
||||
delete: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("testTrigger", {
|
||||
input: z.object({
|
||||
url: z.string().url(),
|
||||
type: z.string(),
|
||||
payloadTemplate: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
const { url, type, payloadTemplate = null } = input;
|
||||
const translation = await getTranslation("en", "common");
|
||||
const language = {
|
||||
locale: "en",
|
||||
translate: translation,
|
||||
};
|
||||
|
||||
const data = {
|
||||
type: "Test",
|
||||
title: "Test trigger event",
|
||||
description: "",
|
||||
startTime: new Date().toISOString(),
|
||||
endTime: new Date().toISOString(),
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "John Doe",
|
||||
timeZone: "Europe/London",
|
||||
language,
|
||||
},
|
||||
],
|
||||
organizer: {
|
||||
name: "Cal",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
language,
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const webhook = { subscriberUrl: url, payloadTemplate, appId: null, secret: null };
|
||||
return await sendPayload(null, type, new Date().toISOString(), webhook, data);
|
||||
} catch (_err) {
|
||||
const error = getErrorFromUnknown(_err);
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,678 +0,0 @@
|
||||
import {
|
||||
Prisma,
|
||||
PrismaPromise,
|
||||
WorkflowTemplates,
|
||||
WorkflowActions,
|
||||
WorkflowTriggerEvents,
|
||||
BookingStatus,
|
||||
WorkflowMethods,
|
||||
} from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
WORKFLOW_TEMPLATES,
|
||||
WORKFLOW_TRIGGER_EVENTS,
|
||||
WORKFLOW_ACTIONS,
|
||||
TIME_UNIT,
|
||||
} from "@ee/lib/workflows/constants";
|
||||
import {
|
||||
deleteScheduledEmailReminder,
|
||||
scheduleEmailReminder,
|
||||
} from "@ee/lib/workflows/reminders/emailReminderManager";
|
||||
import {
|
||||
deleteScheduledSMSReminder,
|
||||
scheduleSMSReminder,
|
||||
} from "@ee/lib/workflows/reminders/smsReminderManager";
|
||||
|
||||
import { createProtectedRouter } from "@server/createRouter";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
export const workflowsRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const workflows = await ctx.prisma.workflow.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
include: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
return { workflows };
|
||||
},
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const workflow = await ctx.prisma.workflow.findFirst({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
{
|
||||
id: input.id,
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
time: true,
|
||||
timeUnit: true,
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
trigger: true,
|
||||
steps: {
|
||||
orderBy: {
|
||||
stepNumber: "asc",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!workflow) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
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 }) {
|
||||
const { name, trigger, action, timeUnit, time, sendTo } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
try {
|
||||
const workflow = await ctx.prisma.workflow.create({
|
||||
data: {
|
||||
name,
|
||||
trigger,
|
||||
userId,
|
||||
timeUnit: time ? timeUnit : undefined,
|
||||
time,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.workflowStep.create({
|
||||
data: {
|
||||
stepNumber: 1,
|
||||
action,
|
||||
workflowId: workflow.id,
|
||||
sendTo,
|
||||
},
|
||||
});
|
||||
return { workflow };
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
|
||||
//delete all scheduled reminders of this workflow
|
||||
const scheduledReminders = await ctx.prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
workflowStep: {
|
||||
workflowId: id,
|
||||
},
|
||||
scheduled: true,
|
||||
NOT: {
|
||||
referenceId: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
scheduledReminders.forEach((reminder) => {
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await ctx.prisma.workflow.deleteMany({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
{
|
||||
id,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
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),
|
||||
})
|
||||
.array(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
time: z.number().nullable(),
|
||||
timeUnit: z.enum(TIME_UNIT).nullable(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user } = ctx;
|
||||
const { id, name, activeOn, steps, trigger, time, timeUnit } = input;
|
||||
|
||||
const userWorkflow = await ctx.prisma.workflow.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
steps: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userWorkflow || userWorkflow.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
//remove all scheduled Email and SMS reminders for eventTypes that are not active any more
|
||||
const oldActiveOnEventTypes = await ctx.prisma.workflowsOnEventTypes.findMany({
|
||||
where: {
|
||||
workflowId: id,
|
||||
},
|
||||
select: {
|
||||
eventTypeId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const removedEventTypes = oldActiveOnEventTypes
|
||||
.map((eventType) => {
|
||||
return eventType.eventTypeId;
|
||||
})
|
||||
.filter((eventType) => {
|
||||
if (!activeOn.includes(eventType)) {
|
||||
return eventType;
|
||||
}
|
||||
});
|
||||
|
||||
const remindersToDeletePromise: PrismaPromise<
|
||||
{
|
||||
id: number;
|
||||
referenceId: string | null;
|
||||
method: string;
|
||||
scheduled: boolean;
|
||||
}[]
|
||||
>[] = [];
|
||||
removedEventTypes.forEach((eventTypeId) => {
|
||||
const reminderToDelete = ctx.prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
booking: {
|
||||
eventTypeId: eventTypeId,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
workflowStepId: {
|
||||
in: userWorkflow.steps.map((step) => {
|
||||
return step.id;
|
||||
}),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
referenceId: true,
|
||||
method: true,
|
||||
scheduled: true,
|
||||
},
|
||||
});
|
||||
remindersToDeletePromise.push(reminderToDelete);
|
||||
});
|
||||
|
||||
const remindersToDelete = await Promise.all(remindersToDeletePromise);
|
||||
|
||||
const deleteReminderPromise: PrismaPromise<Prisma.BatchPayload>[] = [];
|
||||
remindersToDelete.flat().forEach((reminder) => {
|
||||
//already scheduled reminders
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
const deleteReminder = ctx.prisma.workflowReminder.deleteMany({
|
||||
where: {
|
||||
id: reminder.id,
|
||||
booking: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
deleteReminderPromise.push(deleteReminder);
|
||||
});
|
||||
|
||||
await Promise.all(deleteReminderPromise);
|
||||
|
||||
//update active on & reminders for new eventTypes
|
||||
await ctx.prisma.workflowsOnEventTypes.deleteMany({
|
||||
where: {
|
||||
workflowId: id,
|
||||
},
|
||||
});
|
||||
|
||||
let newEventTypes: number[] = [];
|
||||
if (activeOn.length) {
|
||||
if (trigger === WorkflowTriggerEvents.BEFORE_EVENT) {
|
||||
newEventTypes = activeOn.filter((eventType) => {
|
||||
if (
|
||||
!oldActiveOnEventTypes ||
|
||||
!oldActiveOnEventTypes
|
||||
.map((oldEventType) => {
|
||||
return oldEventType.eventTypeId;
|
||||
})
|
||||
.includes(eventType)
|
||||
) {
|
||||
return eventType;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (newEventTypes.length > 0) {
|
||||
//create reminders for all bookings with newEventTypes
|
||||
const bookingsForReminders = await ctx.prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: { in: newEventTypes },
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
steps.forEach(async (step) => {
|
||||
if (step.action !== WorkflowActions.SMS_ATTENDEE) {
|
||||
//as we do not have attendees phone number (user is notified about that when setting this action)
|
||||
bookingsForReminders.forEach(async (booking) => {
|
||||
const bookingInfo = {
|
||||
uid: booking.uid,
|
||||
attendees: booking.attendees.map((attendee) => {
|
||||
return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
|
||||
}),
|
||||
organizer: booking.user
|
||||
? {
|
||||
name: booking.user.name || "",
|
||||
email: booking.user.email,
|
||||
timeZone: booking.user.timeZone,
|
||||
}
|
||||
: { name: "", email: "", timeZone: "" },
|
||||
startTime: booking.startTime.toISOString(),
|
||||
title: booking.title,
|
||||
};
|
||||
if (
|
||||
step.action === WorkflowActions.EMAIL_HOST ||
|
||||
step.action === WorkflowActions.EMAIL_ATTENDEE
|
||||
) {
|
||||
const sendTo =
|
||||
step.action === WorkflowActions.EMAIL_HOST
|
||||
? bookingInfo.organizer?.email
|
||||
: bookingInfo.attendees[0].email;
|
||||
await scheduleEmailReminder(
|
||||
bookingInfo,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
step.emailSubject || "",
|
||||
step.reminderBody || "",
|
||||
step.id,
|
||||
step.template
|
||||
);
|
||||
} else if (step.action === WorkflowActions.SMS_NUMBER) {
|
||||
await scheduleSMSReminder(
|
||||
bookingInfo,
|
||||
step.sendTo || "",
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
step.reminderBody || "",
|
||||
step.id,
|
||||
step.template
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
//create all workflow - eventtypes relationships
|
||||
activeOn.forEach(async (eventTypeId) => {
|
||||
await ctx.prisma.workflowsOnEventTypes.createMany({
|
||||
data: {
|
||||
workflowId: id,
|
||||
eventTypeId,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
userWorkflow.steps.map(async (oldStep) => {
|
||||
const newStep = steps.filter((s) => s.id === oldStep.id)[0];
|
||||
const remindersFromStep = await ctx.prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
workflowStepId: oldStep.id,
|
||||
},
|
||||
include: {
|
||||
booking: true,
|
||||
},
|
||||
});
|
||||
//step was deleted
|
||||
if (!newStep) {
|
||||
//delete already scheduled reminders
|
||||
if (remindersFromStep.length > 0) {
|
||||
remindersFromStep.forEach((reminder) => {
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
await ctx.prisma.workflowStep.delete({
|
||||
where: {
|
||||
id: oldStep.id,
|
||||
},
|
||||
});
|
||||
//step was edited
|
||||
} else if (JSON.stringify(oldStep) !== JSON.stringify(newStep)) {
|
||||
await ctx.prisma.workflowStep.update({
|
||||
where: {
|
||||
id: oldStep.id,
|
||||
},
|
||||
data: {
|
||||
action: newStep.action,
|
||||
sendTo: newStep.action === WorkflowActions.SMS_NUMBER ? newStep.sendTo : null,
|
||||
stepNumber: newStep.stepNumber,
|
||||
workflowId: newStep.workflowId,
|
||||
reminderBody: newStep.template === WorkflowTemplates.CUSTOM ? newStep.reminderBody : null,
|
||||
emailSubject: newStep.template === WorkflowTemplates.CUSTOM ? newStep.emailSubject : null,
|
||||
template: newStep.template,
|
||||
},
|
||||
});
|
||||
//cancel all reminders of step and create new ones (not for newEventTypes)
|
||||
const remindersToUpdate = remindersFromStep.filter((reminder) => {
|
||||
if (reminder.booking?.eventTypeId && !newEventTypes.includes(reminder.booking?.eventTypeId)) {
|
||||
return reminder;
|
||||
}
|
||||
});
|
||||
remindersToUpdate.forEach(async (reminder) => {
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
await ctx.prisma.workflowReminder.deleteMany({
|
||||
where: {
|
||||
id: reminder.id,
|
||||
},
|
||||
});
|
||||
});
|
||||
const eventTypesToUpdateReminders = activeOn.filter((eventTypeId) => {
|
||||
if (!newEventTypes.includes(eventTypeId)) {
|
||||
return eventTypeId;
|
||||
}
|
||||
});
|
||||
if (eventTypesToUpdateReminders && trigger === WorkflowTriggerEvents.BEFORE_EVENT) {
|
||||
const bookingsOfEventTypes = await ctx.prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: {
|
||||
in: eventTypesToUpdateReminders,
|
||||
},
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
bookingsOfEventTypes.forEach(async (booking) => {
|
||||
const bookingInfo = {
|
||||
uid: booking.uid,
|
||||
attendees: booking.attendees.map((attendee) => {
|
||||
return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
|
||||
}),
|
||||
organizer: booking.user
|
||||
? {
|
||||
name: booking.user.name || "",
|
||||
email: booking.user.email,
|
||||
timeZone: booking.user.timeZone,
|
||||
}
|
||||
: { name: "", email: "", timeZone: "" },
|
||||
startTime: booking.startTime.toISOString(),
|
||||
title: booking.title,
|
||||
};
|
||||
if (
|
||||
newStep.action === WorkflowActions.EMAIL_HOST ||
|
||||
newStep.action === WorkflowActions.EMAIL_ATTENDEE
|
||||
) {
|
||||
const sendTo =
|
||||
newStep.action === WorkflowActions.EMAIL_HOST
|
||||
? bookingInfo.organizer?.email
|
||||
: bookingInfo.attendees[0].email;
|
||||
await scheduleEmailReminder(
|
||||
bookingInfo,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
newStep.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
newStep.emailSubject || "",
|
||||
newStep.reminderBody || "",
|
||||
newStep.id,
|
||||
newStep.template
|
||||
);
|
||||
} else if (newStep.action === WorkflowActions.SMS_NUMBER) {
|
||||
await scheduleSMSReminder(
|
||||
bookingInfo,
|
||||
newStep.sendTo || "",
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
newStep.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
newStep.reminderBody || "",
|
||||
newStep.id || 0,
|
||||
newStep.template
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
//added steps
|
||||
const addedSteps = steps.map((s) => {
|
||||
if (s.id <= 0) {
|
||||
const { id, ...stepToAdd } = s;
|
||||
if (stepToAdd) {
|
||||
return stepToAdd;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (addedSteps) {
|
||||
const eventTypesToCreateReminders = activeOn.map((activeEventType) => {
|
||||
if (activeEventType && !newEventTypes.includes(activeEventType)) {
|
||||
return activeEventType;
|
||||
}
|
||||
});
|
||||
addedSteps.forEach(async (step) => {
|
||||
if (step) {
|
||||
const createdStep = await ctx.prisma.workflowStep.create({
|
||||
data: step,
|
||||
});
|
||||
if (
|
||||
trigger === WorkflowTriggerEvents.BEFORE_EVENT &&
|
||||
eventTypesToCreateReminders &&
|
||||
step.action !== WorkflowActions.SMS_ATTENDEE
|
||||
) {
|
||||
const bookingsForReminders = await ctx.prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: { in: eventTypesToCreateReminders as number[] },
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
bookingsForReminders.forEach(async (booking) => {
|
||||
const bookingInfo = {
|
||||
uid: booking.uid,
|
||||
attendees: booking.attendees.map((attendee) => {
|
||||
return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
|
||||
}),
|
||||
organizer: booking.user
|
||||
? {
|
||||
name: booking.user.name || "",
|
||||
email: booking.user.email,
|
||||
timeZone: booking.user.timeZone,
|
||||
}
|
||||
: { name: "", email: "", timeZone: "" },
|
||||
startTime: booking.startTime.toISOString(),
|
||||
title: booking.title,
|
||||
};
|
||||
|
||||
if (
|
||||
step.action === WorkflowActions.EMAIL_ATTENDEE ||
|
||||
step.action === WorkflowActions.EMAIL_HOST
|
||||
) {
|
||||
const sendTo =
|
||||
step.action === WorkflowActions.EMAIL_HOST
|
||||
? bookingInfo.organizer?.email
|
||||
: bookingInfo.attendees[0].email;
|
||||
await scheduleEmailReminder(
|
||||
bookingInfo,
|
||||
trigger,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
step.emailSubject || "",
|
||||
step.reminderBody || "",
|
||||
createdStep.id,
|
||||
step.template
|
||||
);
|
||||
} else if (step.action === WorkflowActions.SMS_NUMBER && step.sendTo) {
|
||||
await scheduleSMSReminder(
|
||||
bookingInfo,
|
||||
step.sendTo,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
step.reminderBody || "",
|
||||
createdStep.id,
|
||||
step.template
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//update trigger, name, time, timeUnit
|
||||
await ctx.prisma.workflow.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data: {
|
||||
name,
|
||||
trigger,
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
});
|
||||
|
||||
const workflow = await ctx.prisma.workflow.findFirst({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
workflow,
|
||||
};
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user