feat: v2 event-types POST, PATCH, DELETE endpoints (#14237)

* create event type: use createEventType from trpc handler

* create event type: simplify handler input and create e2e test

* update event type + test

* delete end point

* check if owner owns event type

* fix: starting v2

* fixes

* remove unused enum

* fix TS issue for update input

* docs refresh

* docs

* docs

* simplify event types docs

* docs refactor

* fix: check if user already has event type with existing slug

* refactor update into a service

* fix tests

* remove unused import

* update create event link

* refactor: create event handler process passed locations

* move input out of folder

* reuse eventtype location for inputs

* docs: example POST event-type return

---------

Co-authored-by: Rajiv Sahal <[email protected]>
Co-authored-by: Morgan <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-04-02 15:50:12 +02:00
1 parent 2cbf9e1ac8
commit 3b263e9282
27 files changed
+1329 -80

No files matched your search

+4 -1
View File
@@ -2,7 +2,10 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
export async function getUsersCredentials(user: NonNullable<TrpcSessionUser>) {
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"] };
export async function getUsersCredentials(user: User) {
const credentials = await prisma.credential.findMany({
where: {
userId: user.id,
+5
View File
@@ -19,10 +19,15 @@ export type UpdateScheduleOutputType = Awaited<
export { getEventTypeById } from "@calcom/lib/event-types/getEventTypeById";
export { getEventTypesByViewer } from "@calcom/lib/event-types/getEventTypesByViewer";
export { getEventTypesPublic } from "@calcom/lib/event-types/getEventTypesPublic";
export { createHandler as createEventType } from "@calcom/trpc/server/routers/viewer/eventTypes/create.handler";
export { updateHandler as updateEventType } from "@calcom/trpc/server/routers/viewer/eventTypes/update.handler";
export { SchedulingType, PeriodType } from "@calcom/prisma/enums";
export type { EventType } from "@calcom/lib/event-types/getEventTypeById";
export type { EventTypesByViewer } from "@calcom/lib/event-types/getEventTypesByViewer";
export type { EventTypesPublic } from "@calcom/lib/event-types/getEventTypesPublic";
export type { UpdateEventTypeReturn } from "@calcom/trpc/server/routers/viewer/eventTypes/update.handler";
export type PublicEventType = Awaited<ReturnType<typeof getPublicEvent>>;
export { getPublicEvent };
+8 -6
View File
@@ -318,6 +318,11 @@ export const createdEventSchema = z
})
.passthrough();
const schemaDefaultConferencingApp = z.object({
appSlug: z.string().default("daily-video").optional(),
appLink: z.string().optional(),
});
export const userMetadata = z
.object({
proPaidForByTeamId: z.number().optional(),
@@ -325,12 +330,7 @@ export const userMetadata = z
vitalSettings: vitalSettingsUpdateSchema.optional(),
isPremium: z.boolean().optional(),
sessionTimeout: z.number().optional(), // Minutes
defaultConferencingApp: z
.object({
appSlug: z.string().default("daily-video").optional(),
appLink: z.string().optional(),
})
.optional(),
defaultConferencingApp: schemaDefaultConferencingApp.optional(),
defaultBookerLayouts: bookerLayouts.optional(),
emailChangeWaitingForVerification: z
.string()
@@ -347,6 +347,8 @@ export const userMetadata = z
})
.nullable();
export type DefaultConferencingApp = z.infer<typeof schemaDefaultConferencingApp>;
export const orgSettingsSchema = z
.object({
isOrganizationVerified: z.boolean().optional(),
+2
View File
@@ -28,3 +28,5 @@ export const createEventTypeInput = z.object({
description: z.string(),
length: z.number(),
}).strict();
export type EventTypeLocation = (z.infer<typeof imports.eventTypeLocations>)[number];
@@ -7,9 +7,15 @@ import { TRPCError } from "@trpc/server";
import type { TSetDestinationCalendarInputSchema } from "./setDestinationCalendar.schema";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
selectedCalendars: SessionUser["selectedCalendars"];
};
type SetDestinationCalendarOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
user: User;
};
input: TSetDestinationCalendarInputSchema;
};
@@ -9,49 +9,43 @@ import { EventTypeRepository } from "@calcom/lib/server/repository/eventType";
import type { PrismaClient } from "@calcom/prisma";
import { SchedulingType } from "@calcom/prisma/enums";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeLocation } from "@calcom/prisma/zod/custom/eventtype";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../trpc";
import type { TCreateInputSchema } from "./create.schema";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
organizationId: SessionUser["organizationId"];
organization: {
isOrgAdmin: SessionUser["organization"]["isOrgAdmin"];
};
profile: {
id: SessionUser["id"] | null;
};
metadata: SessionUser["metadata"];
};
type CreateOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
user: User;
prisma: PrismaClient;
};
input: TCreateInputSchema;
};
export const createHandler = async ({ ctx, input }: CreateOptions) => {
const { schedulingType, teamId, metadata, ...rest } = input;
const { schedulingType, teamId, metadata, locations: inputLocations, ...rest } = input;
const userId = ctx.user.id;
const isManagedEventType = schedulingType === SchedulingType.MANAGED;
const isOrgAdmin = !!ctx.user?.organization?.isOrgAdmin;
// Get Users default conferencing app
const defaultConferencingData = userMetadataSchema.parse(ctx.user.metadata)?.defaultConferencingApp;
const appKeys = await getAppKeysFromSlug("daily-video");
let locations: { type: string; link?: string }[] = [];
// If no locations are passed in and the user has a daily api key then default to daily
if (
(typeof rest?.locations === "undefined" || rest.locations?.length === 0) &&
typeof appKeys.api_key === "string"
) {
locations = [{ type: DailyLocationType }];
}
if (defaultConferencingData && defaultConferencingData.appSlug !== "daily-video") {
const credentials = await getUsersCredentials(ctx.user);
const foundApp = getApps(credentials, true).filter(
(app) => app.slug === defaultConferencingData.appSlug
)[0]; // There is only one possible install here so index [0] is the one we are looking for ;
const locationType = foundApp?.locationOption?.value ?? DailyLocationType; // Default to Daily if no location type is found
locations = [{ type: locationType, link: defaultConferencingData.appLink }];
}
const locations: EventTypeLocation[] =
inputLocations && inputLocations.length !== 0 ? inputLocations : await getDefaultLocations(ctx.user);
const data: Prisma.EventTypeCreateInput = {
...rest,
@@ -122,3 +116,23 @@ export const createHandler = async ({ ctx, input }: CreateOptions) => {
throw new TRPCError({ code: "BAD_REQUEST" });
}
};
async function getDefaultLocations(user: User): Promise<EventTypeLocation[]> {
const defaultConferencingData = userMetadataSchema.parse(user.metadata)?.defaultConferencingApp;
const appKeys = await getAppKeysFromSlug("daily-video");
if (typeof appKeys.api_key === "string") {
return [{ type: DailyLocationType }];
}
if (defaultConferencingData && defaultConferencingData.appSlug !== "daily-video") {
const credentials = await getUsersCredentials(user);
const foundApp = getApps(credentials, true).filter(
(app) => app.slug === defaultConferencingData.appSlug
)[0]; // There is only one possible install here so index [0] is the one we are looking for ;
const locationType = foundApp?.locationOption?.value ?? DailyLocationType; // Default to Daily if no location type is found
return [{ type: locationType, link: defaultConferencingData.appLink }];
}
return [];
}
@@ -18,15 +18,27 @@ import { setDestinationCalendarHandler } from "../../loggedInViewer/setDestinati
import type { TUpdateInputSchema } from "./update.schema";
import { ensureUniqueBookingFields, handleCustomInputs, handlePeriodType } from "./util";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
username: SessionUser["username"];
profile: {
id: SessionUser["profile"]["id"] | null;
};
selectedCalendars: SessionUser["selectedCalendars"];
};
type UpdateOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
user: User;
res?: NextApiResponse | GetServerSidePropsContext["res"];
prisma: PrismaClient;
};
input: TUpdateInputSchema;
};
export type UpdateEventTypeReturn = Awaited<ReturnType<typeof updateHandler>>;
export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
const {
schedule,